From 9e0dd78118172911036f417fa37838c7392e2038 Mon Sep 17 00:00:00 2001 From: Matthew Krafczyk Date: Mon, 26 Oct 2026 07:53:39 -0500 Subject: [PATCH] perf(managed): restore lifecycle performance after Node cutover Reuse invocation-scoped environment evidence and bounded immutable metadata interpretations while retaining fresh authority, ownership, generation, payload, and publication checks. Preserve exact canonical comparison evidence and eliminate duplicate JSON traversal and unnecessary installed-file probes. Add work-count and failure-boundary coverage plus a repeatable fresh-cache benchmark. Controlled runs improve 4.7x and 6.1x over the regressed implementation; the user's notebook falls from 130.671s to 87.383s total. Verification: 702 affected-subsystem tests passed; good-enough passed 4,447 with 29 skipped in 23m47s; changed Python F/E9 lint and diff checks passed. Exhaustive, installed-package, and real Ray/GPU suites were not run. --- docs/environments.md | 8 ++ docs/formats.md | 8 ++ docs/managed_lifecycle_performance.md | 97 +++++++++++++++ docs/managed_operations.md | 25 ++++ src/dryml/core/_content_facts.py | 75 +++++++++++- src/dryml/core/node_prepare.py | 11 ++ src/dryml/core/store/dir.py | 29 ++++- src/dryml/environments/introspection.py | 25 +++- src/dryml/formats/canonical.py | 57 ++++++--- src/dryml/managed/context.py | 19 ++- src/dryml/managed/control.py | 53 +++++++- src/dryml/managed/runtime.py | 12 +- src/dryml/managed/storage.py | 6 +- tests/core/test_content_facts_scope.py | 52 ++++++++ tests/core/test_node_key_contract.py | 25 ++++ .../environments/test_environment_records.py | 27 ++++ tests/formats/test_canonical_v1_1.py | 20 +++ tests/managed/test_lifecycle_performance.py | 115 ++++++++++++++++++ tests/tools/benchmark_cached_dataset.py | 68 +++++++++++ 19 files changed, 697 insertions(+), 35 deletions(-) create mode 100644 docs/managed_lifecycle_performance.md create mode 100644 tests/core/test_content_facts_scope.py create mode 100644 tests/managed/test_lifecycle_performance.py create mode 100644 tests/tools/benchmark_cached_dataset.py diff --git a/docs/environments.md b/docs/environments.md index 65f664ae..9bcca922 100644 --- a/docs/environments.md +++ b/docs/environments.md @@ -20,6 +20,14 @@ Inspection uses `importlib.metadata` for installed distributions. It does not im Each inspection reads fresh metadata. File inventories used to infer distribution locations are read once per distribution during that inspection, not cached across calls; later inspections continue to observe installed-environment changes. +For standard `PathDistribution` records on Python 3.12+, location discovery reads +the machine-readable `RECORD` inventory directly, validates all row/hash/size +syntax, and checks filesystem presence only until finding its first existing +entry. This avoids the standard library's eager existence checks for every later +file while retaining the same inferred location. Other providers, older Python +versions, and missing/empty RECORD inventories retain the normal `files` fallback. +Managed lifecycle capture shares one observation only within an executing +invocation; this does not introduce a process-global environment cache. The distribution inventory follows the interpreter's installation directories, including enabled user and inherited system site directories in import-path diff --git a/docs/formats.md b/docs/formats.md index 7ca60dec..1a82dc7f 100644 --- a/docs/formats.md +++ b/docs/formats.md @@ -6,6 +6,14 @@ serialized Object payloads are trusted same-host inputs. Readers reject malforme incomplete, unsupported, or incompatible authority before hydration or activation; there is no migration, conversion format, or fallback reader. +The shared bounded JSON codec validates and detaches encoder-ready dict/list trees +in one traversal. Frozen decoding still produces immutable mappings/tuples, and +canonical byte ordering, duplicate rejection, cycle detection and all size/type +bounds are unchanged. Node preparations may retain full canonical comparison +evidence alongside keys in the same bounded LRU; repeated equality avoids +relabeling without treating a matching digest as proof. These are implementation +optimizations, with no persistent-format or identity-version change. + ## Object And Store Authority ### Shared Node Graph V1 / CDef Identity 3 diff --git a/docs/managed_lifecycle_performance.md b/docs/managed_lifecycle_performance.md new file mode 100644 index 00000000..804bfd80 --- /dev/null +++ b/docs/managed_lifecycle_performance.md @@ -0,0 +1,97 @@ +# Managed Lifecycle Performance + +## Fresh-cache benchmark + +Run the opt-in developer benchmark in `big_env`: + +```bash +source ~/conda.sh +conda activate big_env +TMPDIR=/tmp/dryml CUDA_VISIBLE_DEVICES="" JAX_PLATFORMS=cpu \ + python -m tests.tools.benchmark_cached_dataset --repeats 3 +TMPDIR=/tmp/dryml CUDA_VISIBLE_DEVICES="" JAX_PLATFORMS=cpu \ + python -m tests.tools.benchmark_cached_dataset --depth 5 --repeats 3 +``` + +Each sample computes one one-element NumPy array into a fresh Store with default +SQLite indexing and real environment observation. Depth 5 wraps the same source +in five `Take(..., 1)` operators: data work stays constant while recipe metadata +grows. Checkpointing, final state publication, and managed completion are timed; +build is separate. The saved result is freshly restored and its content verified +after timing. Temporary Stores are removed on exit. `--elements` supports a +larger finite input, without touching user datasets or Stores. + +The same script can run against an archived pre-Node source using its `src/` and +repository root on `PYTHONPATH`. Its old-build/return-value adapters exist only for +comparative benchmarking, not as product compatibility APIs. Use fresh Python +processes and the same environment for each implementation; compare multiple +samples and CPU time as well as wall time. These measurements are opt-in, not +flaky automated time cutoffs. + +## 2026-10-26 comparison on schumann + +Medians of three fresh-Store samples per row, using the same script and `big_env`: + +| Implementation | Depth 0 wall / CPU | Depth 5 wall / CPU | +| --- | --- | --- | +| Before the Node lifecycle refactor (`f996ea43`) | 6.58s / 6.32s | 7.97s / 7.59s | +| Before this performance pass (`11354d8a`) | 24.14s / 22.89s | 48.93s / 46.68s | +| Performance branch | 5.09s / 4.70s | 7.99s / 7.41s | + +This recovers approximately **4.7× / 6.1×** wall-time speedups over the regressed +implementation. The simple case is about **23% faster** than the pre-refactor +baseline; the deeper recipe reaches roughly wall-time parity, with slightly lower +CPU time. The deeper wall-time difference is below the variation among samples, +so it is not evidence of an additional speedup over the old implementation. +Earlier measurements under lower host load had smaller absolute times; the +comparison above reran all implementations together. It does not measure the +user's full dataset, GPU work, or Dispatch startup/transport. + +### Notebook follow-up + +The user also reported the following timings for the actual dispatched cache +workload, before and after this performance pass: + +| Stage | Before | After | +| --- | --- | --- | +| Concretize | 0.046s | 0.042s | +| Build | 0.023s | 0.047s | +| Compute | 124.857s | 83.695s | +| Outside worker | 5.745s | 3.600s | +| Total cell | 130.671s | 87.383s | + +This is approximately **33% less compute and total wall time** (about 1.5× +end-to-end speedup). These are user-reported single runs of the real workload, +not controlled benchmark medians; they confirm an application-level improvement +without attributing all remaining time or run-to-run variation to the framework. + +## Work removed and correctness boundaries + +- Observe the environment only once per executing invocation that actually + captures state. Replay and capture-free explicit-final selection do not scan it. +- Reuse bounded interpretations of identical immutable control/Node/metadata bytes + within the same process/thread/task admission. Every file read, pending check, + owner/generation fence, selected-state reader and publication acknowledgement + remains fresh. Scope exit, including cancellation, clears all entries. +- Retain complete canonical Node comparison evidence within the preparation's + existing LRU budget. Equality still compares exact evidence under hash ties. +- Validate and detach encoder-ready JSON in one traversal rather than freezing + and thawing the same tree. Byte output and closed grammar bounds are retained. +- Infer standard distribution locations without statting all subsequent installed + files. All RECORD row/hash/size syntax is still checked, and later observations + read the inventory afresh. + +Routine regression tests guard work counts and failure behavior, not elapsed +seconds: stable safe points still read authority without redecoding graphs; +changed bytes and wrong operation IDs fail; cancellation clears facts; copied +caller contexts cannot borrow them; eviction affects work only; replay skips +environment observation; and environment failures remain unavailable evidence. + +## Verification + +- Affected subsystem selection: **702 passed** under the representative policy. +- Final routine gate: **4,447 passed, 29 skipped**, **23m47s** complete local wall + time across both interpreter phases on the loaded host. Test selection was not + weakened or expanded to exhaustive coverage. +- Changed Python F/E9 lint and diff whitespace checks passed. +- Exhaustive, installed-package and real Ray/GPU integration suites were not run. diff --git a/docs/managed_operations.md b/docs/managed_operations.md index 073b6055..c1bd4568 100644 --- a/docs/managed_operations.md +++ b/docs/managed_operations.md @@ -31,6 +31,31 @@ proofs and optional-backend limits are recorded in Acquiring low-level admission or constructing metadata alone does not retain private state. U15's selected saved-start handshake does acquire physical grants. +### Invocation-local performance and evidence + +Snapshot environment evidence is observed lazily before the first capture's state +reservations, once per executing invocation. Later checkpoints and automatic final +capture reuse that observation, with independent capture timestamps and requirement +collection. An unavailable observation remains unavailable for that invocation; +resume/rerun starts a fresh observation. Replay and explicitly selected finals that +need no capture perform no environment inventory. + +Admission also owns a caller-local, bounded memo of immutable metadata +interpretations. Exact source bytes, reader implementations and interpretation +parameters distinguish entries; encoding facts are attached to immutable Node +handles. At most 64 entries and 4 MiB of encoded source/output bytes are retained, +with interpreted values additionally bounded by their closed codec grammars. The +outer admission clears every entry on normal return, failure or cancellation. +Inherited process/thread/task contexts cannot use another caller's memo. + +This memo shares decoding, canonical JSON validation, and pure Node interpretation +across control and Store readers. It does **not** cache file reads, pending flags, +authority cuts, ownership, generations, payload availability, grants or publication +acknowledgements. Every safe point rereads current bytes; every selected-state +reader and external override is still freshly consulted. Changed/malformed bytes +cannot match an old interpretation, and a hash alone is never a cache/equality +proof. See [performance measurements](managed_lifecycle_performance.md). + ### Execute transport boundaries [Generic Execute](execute.md) supplies detached invocation-graph transport; diff --git a/src/dryml/core/_content_facts.py b/src/dryml/core/_content_facts.py index 943cb72d..40815df1 100644 --- a/src/dryml/core/_content_facts.py +++ b/src/dryml/core/_content_facts.py @@ -1,15 +1,86 @@ -"""Internal primitive and owned-size rules for Repo and pure Node content facts. +"""Internal bounds and caller-scoped memoization for immutable content facts. -This dependency-light helper owns no cache, parser, domain values or resources. +This dependency-light helper owns no parser, domain policy or external resources. Sizes overcount repeated immutable leaves and prospective tuple/container slots; callers add source/context and facility bookkeeping before reserving storage. """ +import asyncio +from collections import OrderedDict +from contextlib import contextmanager +from contextvars import ContextVar +import os import sys +from threading import get_ident import weakref from types import MappingProxyType +_content_facts = ContextVar("dryml_immutable_content_facts", default=None) + + +def _caller(): + try: + task = asyncio.current_task() + except RuntimeError: + task = None + return os.getpid(), get_ident(), task + + +class _ContentFacts: + """Bound pure interpretations by complete input bytes within one caller scope. + + At most 64 entries and 4 MiB of encoded source/output bytes are retained; + each interpreted value remains bounded by its owning decoder's grammar. + Kind keys distinguish reader implementations and interpretation parameters. + No paths, authority cuts, pending flags, owners or availability are cached. + """ + + def __init__(self): + self.caller = _caller() + self.entries = OrderedDict() + self.bytes = 0 + self.active = True + + def decode(self, kind, payload, build): + key = kind, payload + if key in self.entries: + self.entries.move_to_end(key) + return self.entries[key][0] + result = build() + charge = len(payload) + (len(result) if type(result) is bytes else 0) + if charge <= 4 * 1024 * 1024: + while self.entries and (len(self.entries) >= 64 or self.bytes + charge > 4 * 1024 * 1024): + _, (_, old_charge) = self.entries.popitem(last=False) + self.bytes -= old_charge + self.entries[key] = result, charge + self.bytes += charge + return result + + +def _current_content_facts(): + facts = _content_facts.get() + return facts if facts is not None and facts.active and facts.caller == _caller() else None + + +@contextmanager +def _content_facts_scope(): + """Share immutable interpretations only; clear them on every outer scope exit.""" + if _current_content_facts() is not None: + yield + return + facts = _ContentFacts() + token = _content_facts.set(facts) + try: + yield + finally: + facts.active = False + facts.entries.clear() + facts.bytes = 0 + facts.caller = None + _content_facts.reset(token) + + def _primitive_size(value): """Bound prospective owned primitive containers, without allocating copies.""" if type(value) in (dict, MappingProxyType): diff --git a/src/dryml/core/node_prepare.py b/src/dryml/core/node_prepare.py index ee9808c3..3d10d801 100644 --- a/src/dryml/core/node_prepare.py +++ b/src/dryml/core/node_prepare.py @@ -20,6 +20,7 @@ EXACT_KEY_VERSION = "dryml-node-exact/v1" +_FLAT_EVIDENCE = object() def _bytes(value): @@ -612,6 +613,9 @@ def exact_equal(self, node, other, other_node): Returns bool; foreign handles raise ValueError. Does not use digest equality as authority or consult external state. Exact unordered symmetry search can be expensive; counts expose that cost rather than imposing a refusal limit. + Full canonical evidence is retained in the same bounded owner LRU as + semantic keys; resident repeat comparisons require no relabeling. Eviction + or clear only changes work, never collision-sensitive equality. """ if self.view.name != other.view.name: return False @@ -622,11 +626,17 @@ def exact_equal(self, node, other, other_node): return left == right def _flat(self, root, *, retain=False): + evidence_key = _FLAT_EVIDENCE, root + flat = self._facts.get(evidence_key) + if flat is not None: + self._facts.move_to_end(evidence_key) + return flat if retain else flat[0] cached = self._facts.get(root) if cached is not None and cached[3] is not None: order = cached[3][0] labels = {slot: index for index, slot in enumerate(order)} result = _bytes(_canonical_values([self._rows[slot] for slot in order], labels.__getitem__)) + self._cache_put(evidence_key, (result, cached[3]), 192 + _primitive_size((result, cached[3]))) return (result, cached[3]) if retain else result closure = self._closures[root] slots = [] @@ -636,6 +646,7 @@ def _flat(self, root, *, retain=False): slots.append(bit.bit_length() - 1) remaining ^= bit result, evidence = self._label_table(root, self._rows, self._children, slots) + self._cache_put(evidence_key, (result, evidence), 192 + _primitive_size((result, evidence))) return (result, evidence) if retain else result def _transport_order(self, root): diff --git a/src/dryml/core/store/dir.py b/src/dryml/core/store/dir.py index 7df647b7..3c46c004 100644 --- a/src/dryml/core/store/dir.py +++ b/src/dryml/core/store/dir.py @@ -24,7 +24,7 @@ from .records import ( StoreFormatRecord, StoreRecordError, StateKeyRecord, NodeBlockRecord, NodeRootRecord, StateVariantManifest, - StateAvailabilityRecord, NodeMembershipRecord, DeclarationAnchorRecord, + StateAvailabilityRecord, NodeMembershipRecord, DeclarationAnchorRecord, NodeMetadataRecord, DeclarationRequirementRecord, _json_bytes, _digest_value, _digest, _MAX_RECORD_BYTES, AuthorityRecord, MutationIntentRecord, NodeNameRecord, RetiredDeclarationAnchorRecord, ) @@ -75,8 +75,10 @@ class DirStore(Store): Side Effects: May initialize the root and persistent Store UUID. Public metadata reads - validate current authority; same-bucket inspection shares interpretation - only within its explicit fenced batch. Existing incompatible Stores are + validate current authority. A caller-owned bounded content scope may share + interpretation of identical immutable bytes across detached batches; every + batch still reads and revalidates its own current cut and byte witnesses. + Existing incompatible Stores are refused without conversion, deletion or replacement. """ @@ -890,11 +892,22 @@ def _read_node_block(self, digest): return record def _expand_node_root(self, record): + from .._content_facts import _current_content_facts + from ..node_codec import decode_node_graph + block = self._read_node_block(record.block_digest) + facts = _current_content_facts() + if facts is None: + return self._decode_node_root(record, block) + return facts.decode(("store-node-root", record.view_bytes, record.root_kind, + decode_node_graph, type(self)._validate_node_selections), + block.content, lambda: self._decode_node_root(record, block)) + + def _decode_node_root(self, record, block): + """Interpret freshly read immutable bytes; no Store validity is retained.""" from ..node_codec import decode_node_graph, NodeCodecError from ..node_prepare import NodePreparation from ..node_views import creation_cdef, object_projection from ..node import require_saved - block = self._read_node_block(record.block_digest) detached = authority.detached_owner(self) cache_key = block.content, record.view_bytes, record.root_kind if detached is not None and cache_key in detached.node_views: @@ -1934,7 +1947,13 @@ def _read_file(self, path: str, record_type): if record_type is DeclarationAnchorRecord and payload.startswith( b"DRYML-METADATA/dryml-declaration-retired-anchor/1\n"): record_type = RetiredDeclarationAnchorRecord - return record_type.from_bytes(payload) + from .._content_facts import _current_content_facts + facts = _current_content_facts() + reader = record_type.from_bytes + if facts is not None and record_type in (NodeBlockRecord, NodeRootRecord, NodeMetadataRecord): + return facts.decode((record_type, getattr(reader, "__func__", reader), record_type.max_bytes), + payload, lambda: reader(payload)) + return reader(payload) except StoreRecordError as error: raise StoreAuthorityError(f"Malformed Store record {path!r}: {error}") from error diff --git a/src/dryml/environments/introspection.py b/src/dryml/environments/introspection.py index 2da7f4ad..eb3adc11 100644 --- a/src/dryml/environments/introspection.py +++ b/src/dryml/environments/introspection.py @@ -3,6 +3,7 @@ from __future__ import annotations import importlib.metadata as metadata +import csv import os import platform import site @@ -31,13 +32,29 @@ def _distribution_location(dist: metadata.Distribution) -> str | None: """Find the first file's parent with one inventory read, or return unknown.""" try: + if type(dist) is metadata.PathDistribution and sys.version_info >= (3, 12): + record = dist.read_text("RECORD") + if record: + first = None + for row in csv.reader(record.splitlines()): + if not 1 <= len(row) <= 3: + raise ValueError("Malformed installed-file inventory.") + if len(row) > 1 and row[1]: + metadata.FileHash(row[1]) + if len(row) > 2 and row[2]: + int(row[2]) + if first is None: + located = dist.locate_file(metadata.PackagePath(row[0])) + if located.exists(): + first = str(Path(located).parent) + return first files = dist.files if files: first = next(iter(files), None) if first is not None: located = dist.locate_file(first) return str(Path(located).parent) - except (OSError, TypeError, ValueError): + except (OSError, TypeError, ValueError, csv.Error): return None return None @@ -84,8 +101,10 @@ def inspect_current() -> EnvironmentRecord: inventory. Heavy modules such as TensorFlow, Torch, JAX, Ray, or Slurm integrations are never imported by this function. - Each call reads fresh metadata; a distribution's file inventory is read only - once to infer its location and is not retained across calls. + Each call reads fresh metadata; file inventories are not retained across calls. + Standard RECORD inventories on Python 3.12+ are scanned directly to infer the + first existing file's parent without statting every later file. Inventory row + syntax is still validated; other distributions retain their files interface. The DRYML version uses that same installed inventory, or is unknown when DRYML has no installed record; source-tree metadata cannot override it. diff --git a/src/dryml/formats/canonical.py b/src/dryml/formats/canonical.py index 8ed80300..0fae46b3 100644 --- a/src/dryml/formats/canonical.py +++ b/src/dryml/formats/canonical.py @@ -33,8 +33,20 @@ def deep_freeze_json( Mapping keys must be strings; sequences preserve their order. Sets are intentionally rejected because they have no JSON meaning. Bounds apply to - the complete value, including scalar nodes. + the complete value, including scalar nodes. value may contain JSON scalar, + Mapping and Sequence values; max_* integer parameters bound its tree. Returns + detached MappingProxyType/tuple containers. Raises CanonicalJSONError for + unsupported, cyclic, nonfinite or oversized input. Performs no IO or mutation. """ + return _project_json(value, max_depth=max_depth, max_nodes=max_nodes, + max_entries=max_entries, max_string=max_string, max_int_bits=max_int_bits, + mutable=False) + + +def _project_json(value, *, max_depth=DEFAULT_MAX_DEPTH, max_nodes=DEFAULT_MAX_NODES, + max_entries=DEFAULT_MAX_ENTRIES, max_string=DEFAULT_MAX_STRING, + max_int_bits=DEFAULT_MAX_INT_BITS, mutable): + """Validate and detach once into either frozen or encoder-ready containers.""" nodes = [0] active: set[int] = set() @@ -45,7 +57,21 @@ def freeze(item: Any, depth: int) -> FrozenJson: raise CanonicalJSONError("canonical JSON exceeds node bound", context={"limit": max_nodes}) if depth > max_depth: raise CanonicalJSONError("canonical JSON exceeds depth bound", context={"limit": max_depth}) - if isinstance(item, Mapping): + kind = type(item) + if kind is str: + check_string(item, max_string) + return item + if kind is bool or item is None: + return item + if kind is int: + if item.bit_length() > max_int_bits: + raise CanonicalJSONError("canonical JSON integer exceeds bit bound", context={"limit": max_int_bits}) + return item + if kind is float: + if not math.isfinite(item): + raise CanonicalJSONError("canonical JSON floats must be finite") + return item + if type(item) is dict or isinstance(item, Mapping): identity = id(item) if identity in active: raise CanonicalJSONError("canonical JSON cannot contain cyclic containers") @@ -59,10 +85,11 @@ def freeze(item: Any, depth: int) -> FrozenJson: keys.append(key) active.add(identity) try: - return MappingProxyType({key: freeze(item[key], depth + 1) for key in sorted(keys)}) + projected = {key: freeze(item[key], depth + 1) for key in sorted(keys)} + return projected if mutable else MappingProxyType(projected) finally: active.remove(identity) - if isinstance(item, Sequence) and not isinstance(item, str | bytes | bytearray): + if type(item) in (list, tuple) or isinstance(item, Sequence) and not isinstance(item, str | bytes | bytearray): identity = id(item) if identity in active: raise CanonicalJSONError("canonical JSON cannot contain cyclic containers") @@ -70,7 +97,8 @@ def freeze(item: Any, depth: int) -> FrozenJson: raise CanonicalJSONError("canonical JSON sequence exceeds entry bound", context={"limit": max_entries}) active.add(identity) try: - return tuple(freeze(child, depth + 1) for child in item) + projected = (freeze(child, depth + 1) for child in item) + return list(projected) if mutable else tuple(projected) finally: active.remove(identity) if isinstance(item, str): @@ -92,18 +120,15 @@ def freeze(item: Any, depth: int) -> FrozenJson: def json_ready(value: Any, **bounds: Any) -> Any: - """Return a detached mutable JSON projection after bounded validation.""" + """Return detached dict/list JSON data with the same bounds as deep_freeze_json. - frozen = deep_freeze_json(value, **bounds) - - def thaw(item: FrozenJson) -> Any: - if isinstance(item, Mapping): - return {key: thaw(value) for key, value in item.items()} - if isinstance(item, tuple): - return [thaw(value) for value in item] - return item - - return thaw(frozen) + value accepts JSON scalars and supported Mapping/Sequence containers. Optional + max_* integer bounds apply to the complete tree. Validation and copying share + one traversal; source containers are never retained or mutated. Raises + CanonicalJSONError for cyclic, unsupported, nonfinite or oversized input and + TypeError for unknown bound arguments. Performs no IO. + """ + return _project_json(value, mutable=True, **bounds) def canonical_json_dumps(data: Any, **bounds: Any) -> str: diff --git a/src/dryml/managed/context.py b/src/dryml/managed/context.py index 2c5b3d56..4f13b40c 100644 --- a/src/dryml/managed/context.py +++ b/src/dryml/managed/context.py @@ -21,7 +21,9 @@ class ManagedContext: operation-wide and immutable; final selection protects its exact graph while completed-result authority remains owned by the result finalizer. retain/release manage independent explicit/durable roots without private-state serialization. - Foreign/retired/recursive use raises + Snapshot environment evidence is observed lazily once per invocation before + its first capture and shared by later captures. Replay and explicit final + selection without capture do not observe the environment. Foreign/retired/recursive use raises ManagedContextError; stale ownership raises ManagedConflictError. Accepted interruption always prevents completion, even when author code catches it. """ @@ -44,6 +46,7 @@ def __init__(self, token, *, admission, control, generation, obj=None, self._final_report = None self._failure_code = "method_error" self._checkpoint_error = None + self._snapshot_observer = None @property def active(self): @@ -132,7 +135,8 @@ def checkpoint(self, *, states=None, durable=False, initial=False): try: from .storage import _publish_checkpoint from .runtime import _associate_state - selected, report = _publish_checkpoint(self.state_repo, self._obj, states=states, store=self._store) + selected, report = _publish_checkpoint(self.state_repo, self._obj, states=states, store=self._store, + snapshot_observer=self._environment_observer()) _associate_state(self, selected, "latest", report=report, published=lambda: _checkpoint_boundary("state_published")) if initial: @@ -288,7 +292,8 @@ def _finalize_state(self): self.control_store.retention.adopt(str(UUID(intent.token)), _stores(self._control)) else: _checkpoint_boundary("final_capture_started") - selected, report = _publish_checkpoint(self.state_repo, self._obj, store=self._store) + selected, report = _publish_checkpoint(self.state_repo, self._obj, store=self._store, + snapshot_observer=self._environment_observer()) self._final_report = report _associate_state(self, selected, "final", report=report, published=lambda: _checkpoint_boundary("final_state_published")) @@ -296,6 +301,13 @@ def _finalize_state(self): self._safe_point() return selected + def _environment_observer(self): + """Retain one invocation's observation, never Store or payload authority.""" + if self._snapshot_observer is None: + from .runtime import _preobserve_snapshot_environment + self._snapshot_observer = _preobserve_snapshot_environment() + return self._snapshot_observer + def _safe_point(self, *, allow_completed=False): self._require_active(terminal_ok=True) current = self._control.inspect(self.operation_id) @@ -384,6 +396,7 @@ def _require_mutation(self): def _deactivate(self): self._active = False + self._snapshot_observer = None def _checkpoint_boundary(stage): diff --git a/src/dryml/managed/control.py b/src/dryml/managed/control.py index f3b6abed..0be05962 100644 --- a/src/dryml/managed/control.py +++ b/src/dryml/managed/control.py @@ -8,6 +8,7 @@ from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass, field, replace +from functools import wraps import hashlib import json import os @@ -17,6 +18,7 @@ from uuid import UUID, uuid4 from dryml.core.node import Node, require_saved +from dryml.core._content_facts import _current_content_facts from dryml.core.node_codec import decode_node_graph, encode_node_graph from dryml.core.node_prepare import NodePreparation from dryml.core.repo import Repo @@ -37,6 +39,19 @@ _STATES = frozenset({"running", "interrupted", "failed", "finalizing", "completed"}) +def _decoded_record(reader): + @wraps(reader) + def decode(cls, payload, *args, **kwargs): + facts = _current_content_facts() + build = lambda: reader(cls, payload, *args, **kwargs) + operation_id = kwargs.get("operation_id") + if (facts is None or type(payload) is not bytes or args or set(kwargs) - {"operation_id"} + or operation_id is not None and type(operation_id) is not str): + return build() + return facts.decode((cls, reader, tuple(kwargs.items())), payload, build) + return decode + + def _digest(value, label): if type(value) is not str or not _HEX.fullmatch(value): raise ManagedControlError("invalid_current", label + " must be a lowercase SHA-256 digest") @@ -71,8 +86,14 @@ def _data(payload): if type(payload) is not bytes or len(payload) > _MAX_BYTES: raise ManagedControlError("invalid_control", "control bytes exceed their support bound") try: - canonical_json_load_bytes(payload, max_depth=96, max_nodes=65536, - max_entries=16384, max_string=_MAX_BYTES, max_int_bits=64) + def validate(): + canonical_json_load_bytes(payload, max_depth=96, max_nodes=65536, + max_entries=16384, max_string=_MAX_BYTES, max_int_bits=64) + facts = _current_content_facts() + if facts is None: + validate() + else: + facts.decode(("control-json", canonical_json_load_bytes), payload, validate) return json.loads(payload) except (ValueError, TypeError) as error: raise ManagedControlError("invalid_control", "control metadata is malformed") from error @@ -87,6 +108,12 @@ def _closed(data, schema, version, fields): def _node_data(node): if node is None: return None + facts = _current_content_facts() + if facts is not None: + encoded = facts.decode(("control-node-encoding", node, encode_node_graph, NodePreparation), b"", + lambda: _bytes({"schema": "dryml-managed-node", "version": 1, + "graph": encode_node_graph(NodePreparation((node,)))})) + return json.loads(encoded) return {"schema": "dryml-managed-node", "version": 1, "graph": encode_node_graph(NodePreparation((node,)))} @@ -94,6 +121,13 @@ def _node_data(node): def _node(data, *, saved=False): if data is None: return None + facts = _current_content_facts() + if facts is not None: + return facts.decode(("node", saved), _bytes(data), lambda: _decode_node(data, saved=saved)) + return _decode_node(data, saved=saved) + + +def _decode_node(data, *, saved): _closed(data, "dryml-managed-node", 1, {"graph"}) try: node = decode_node_graph(data["graph"]) @@ -432,11 +466,16 @@ def to_bytes(self): return _bytes(self.to_data()) @classmethod + @_decoded_record def from_bytes(cls, payload, *, operation_id=None): """Decode bytes and optional path digest, rejecting every incompatible nested codec. Returns ControlSnapshot; malformed/old records raise ManagedControlError without modifying source bytes or inspecting any referenced private data. + payload is exact bytes; operation_id is an optional path-bound digest. + Within the caller's admission, identical bytes/path constraints may reuse a + bounded immutable decode. This is never a current-authority or payload + witness; no IO occurs and callers must freshly read their source bytes. """ data = _data(payload) fields = {"operation_id", "receiver", "member", "argument_digest", "run_id", "invocation_id", @@ -558,8 +597,16 @@ def to_bytes(self): return _bytes(self.to_data()) @classmethod + @_decoded_record def from_bytes(cls, payload, *, operation_id): - """Decode exact start evidence for operation_id or raise ManagedControlError.""" + """Decode exact bounded start evidence for a required path-bound operation. + + payload is bytes and operation_id a lowercase digest. Returns immutable + StartPreparation; malformed/version-incompatible or mismatched nested + evidence raises ManagedControlError without changing source bytes. A + caller-local bounded content scope may reuse identical-byte decodes, never + current authority. No Store IO, hooks, restoration or capture occurs. + """ data = _data(payload) _closed(data, "dryml-managed-start", 1, {"token", "previous", "proposed", "phase", "settled"}) result = cls(data["token"], None if data["previous"] is None else diff --git a/src/dryml/managed/runtime.py b/src/dryml/managed/runtime.py index f14ae3bf..a10e4736 100644 --- a/src/dryml/managed/runtime.py +++ b/src/dryml/managed/runtime.py @@ -7,6 +7,7 @@ from .config import ManagedConfig, _ResolvedManagedConfig from .control import (ControlHistory, ControlIntent, ControlSnapshot, ManagedControlStore, StartPreparation, _same_snapshot_bytes) +from dryml.core._content_facts import _content_facts_scope from .errors import (ManagedConfigError, ManagedConflictError, ManagedRecoveryError, ManagedRerunRequiredError) from .identity import AdmissionIdentity, _argument_digest_bound, operation_digest @@ -222,6 +223,7 @@ def _validate_start_control(config): raise ManagedConfigError("start_requires_rerun", "start_from requires explicit rerun on every invocation") +@_content_facts_scope() def admit_execution(identity, descriptor, config, control, *, realize, execute): """Select replay/recovery/execution from detached facts under the same owner. @@ -237,6 +239,9 @@ def admit_execution(identity, descriptor, config, control, *, realize, execute): this invocation. Caller adapters must not reconstruct receivers before this gate. Cleanup failures attach evidence without replacing the execution error, even on Python versions without exception-note support. + Bounded immutable control decodes are shared only within this caller's + admission; every authority read, owner/generation fence and acknowledgement + remains fresh. Decode facts are discarded on success, failure or cancellation. """ from .descriptor import ManagedOperation _validate_start_control(config) @@ -649,7 +654,12 @@ def request_interrupt(descriptor, instance, *, state_repo=None, control_store=No def _preobserve_snapshot_environment(): - """Preserve the existing deferred observation seam for later execution integration.""" + """Observe once before capture reservations and preserve unavailable evidence. + + The caller retains the returned no-argument observer only for this invocation. + Ordinary errors are deferred to Core's capture-evidence handling; cancellation + propagates immediately. No Store authority or payload proof is retained. + """ from dryml.environments.introspection import inspect_current try: environment = inspect_current() diff --git a/src/dryml/managed/storage.py b/src/dryml/managed/storage.py index f6d79716..0db48cff 100644 --- a/src/dryml/managed/storage.py +++ b/src/dryml/managed/storage.py @@ -20,12 +20,14 @@ from .errors import ManagedConflictError, ManagedStoreError -def _publish_checkpoint(repo, obj, *, states=None, store=None): +def _publish_checkpoint(repo, obj, *, states=None, store=None, snapshot_observer=None): """Publish through Core's save batch with provisional, non-user retention. The returned (SavedNode, StoreReport) names every provisional token, including partial failures carried by Core exceptions. Reservations cover only state IO; the caller must transfer protection before retiring these publication roots. + snapshot_observer optionally supplies invocation-scoped environment evidence; + its result is never ownership, payload-availability, or publication evidence. """ from dryml.core.state import reserve from dryml.core.repo_plan import build_routed_save_plan, execute_routed_save_plan @@ -34,7 +36,7 @@ def _publish_checkpoint(repo, obj, *, states=None, store=None): with reserve(obj._identity_node, nodes, object_ids), repo._retain_save_context() as context: routed = build_routed_save_plan(repo, plan, context, store=store) return execute_routed_save_plan(repo, routed, states=states, - provisional=True, report_stores=True) + provisional=True, report_stores=True, snapshot_observer=snapshot_observer) def _validate_selection(repo, obj, original, selected, *, source_store=None): diff --git a/tests/core/test_content_facts_scope.py b/tests/core/test_content_facts_scope.py new file mode 100644 index 00000000..338ec074 --- /dev/null +++ b/tests/core/test_content_facts_scope.py @@ -0,0 +1,52 @@ +"""Pure memoization stays bounded, caller-local and non-authoritative.""" + +import asyncio +from contextvars import copy_context +from threading import Thread + +import pytest + +from dryml.core._content_facts import _content_facts_scope, _current_content_facts + + +def test_content_scope_rejects_copied_callers_and_releases_on_cancellation(): + inherited = copy_context() + with pytest.raises(KeyboardInterrupt): + with _content_facts_scope(): + facts = _current_content_facts() + assert facts.decode("value", b"source", lambda: 1) == 1 + assert facts.decode("value", b"source", lambda: pytest.fail("duplicate interpretation")) == 1 + assert facts.decode("value", b"changed", lambda: 2) == 2 + inherited = copy_context() + seen = [] + worker = Thread(target=lambda: inherited.run(lambda: seen.append(_current_content_facts()))) + worker.start() + worker.join(5) + assert not worker.is_alive() and seen == [None] + + async def child(): + assert _current_content_facts() is None + with _content_facts_scope(): + assert _current_content_facts() is not facts + + asyncio.run(child()) + raise KeyboardInterrupt() + assert not facts.active and not facts.entries and facts.bytes == 0 + assert _current_content_facts() is None + assert inherited.run(_current_content_facts) is None + + +def test_content_scope_evicts_without_changing_results_or_caching_errors(): + with _content_facts_scope(): + facts = _current_content_facts() + for index in range(100): + assert facts.decode("value", str(index).encode(), lambda: index) == index + assert len(facts.entries) <= 64 + assert facts.decode("value", b"0", lambda: 0) == 0 + huge = b"x" * (4 * 1024 * 1024 + 1) + assert facts.decode("large", huge, lambda: 1) == 1 + assert facts.decode("large", huge, lambda: 2) == 2 + with pytest.raises(ValueError): + facts.decode("invalid", b"source", lambda: (_ for _ in ()).throw(ValueError())) + assert facts.decode("invalid", b"source", lambda: "recovered") == "recovered" + assert facts.bytes <= 4 * 1024 * 1024 diff --git a/tests/core/test_node_key_contract.py b/tests/core/test_node_key_contract.py index 7b71ef21..ddc74c20 100644 --- a/tests/core/test_node_key_contract.py +++ b/tests/core/test_node_key_contract.py @@ -30,6 +30,31 @@ def test_graph_digest_includes_node_local_facets(): assert root.exact_digest() != bound.exact_digest() +def test_repeated_exact_comparisons_reuse_full_evidence_and_clear_recomputes(monkeypatch): + from dryml.core.node_prepare import NodePreparation + + left = Definition(KeyNode, {Definition(KeyNode, 1), Definition(KeyNode, 2)}) + right = left.copy_graph() + different = Definition(KeyNode, {Definition(KeyNode, 1), Definition(KeyNode, 3)}) + a, b, c = (NodePreparation((node,)) for node in (left, right, different)) + assert a.exact_equal(left, b, right) + assert not a.exact_equal(left, c, different) + original = NodePreparation._label_table + calls = [] + + def label(*args, **kwargs): + calls.append(True) + return original(*args, **kwargs) + + monkeypatch.setattr(NodePreparation, "_label_table", label) + assert a.exact_equal(left, b, right) + assert not a.exact_equal(left, c, different) + assert not calls + a.clear() + assert a.exact_equal(left, b, right) + assert calls + + def test_one_contract_two_schedulers_and_warm_requests(): from dryml.core.node_prepare import NodePreparation diff --git a/tests/environments/test_environment_records.py b/tests/environments/test_environment_records.py index 6cb43668..38ed0c55 100644 --- a/tests/environments/test_environment_records.py +++ b/tests/environments/test_environment_records.py @@ -179,6 +179,33 @@ def locate_file(self, entry): assert introspection._distribution_location(FailingDist()) is None +@pytest.mark.skipif(sys.version_info < (3, 12), reason="stdlib RECORD filtering fast path") +@pytest.mark.parametrize("tail", ["later.py,,0\n", "invalid.py,,not-an-integer\n"]) +def test_record_location_checks_only_first_existing_file_and_validates_tail(tmp_path, monkeypatch, tail): + from pathlib import Path + + info = tmp_path / "sample-1.dist-info" + info.mkdir() + (tmp_path / "first.py").touch() + (info / "RECORD").write_text("missing.py,,0\nfirst.py,,0\n" + tail) + dist = metadata.PathDistribution(info) + try: + expected = str(Path(dist.locate_file(dist.files[0])).parent) + except ValueError: + expected = None + visited = [] + exists = Path.exists + + def counted(path): + visited.append(path.name) + return exists(path) + + monkeypatch.setattr(Path, "exists", counted) + assert introspection._distribution_location(dist) == expected + assert visited == ["missing.py", "first.py"] + assert expected == (None if "not-an-integer" in tail else str(tmp_path)) + + def test_installed_software_evidence_ignores_transient_vendor_paths( monkeypatch, tmp_path, ): diff --git a/tests/formats/test_canonical_v1_1.py b/tests/formats/test_canonical_v1_1.py index 3f2a9f85..dc6857c5 100644 --- a/tests/formats/test_canonical_v1_1.py +++ b/tests/formats/test_canonical_v1_1.py @@ -22,3 +22,23 @@ def test_canonical_decoding_returns_a_deeply_immutable_projection(): assert decoded["nested"]["items"] == (1, 2) with pytest.raises(TypeError): decoded["nested"]["new"] = True + + +def test_encoder_projection_detaches_once_with_identical_validation_bounds(): + from collections import UserDict + from types import MappingProxyType + from dryml.formats import CanonicalJSONError, deep_freeze_json, json_ready + + source = UserDict({"nested": MappingProxyType({"items": [1, True, None, -0.0]})}) + ready = json_ready(source) + assert ready == {"nested": {"items": [1, True, None, -0.0]}} + ready["nested"]["items"].append("changed") + assert len(source["nested"]["items"]) == 4 + for project in (deep_freeze_json, json_ready): + for bounds in ({"max_depth": 1}, {"max_nodes": 3}, {"max_entries": 2}, {"max_string": 2}): + with pytest.raises(CanonicalJSONError): + project(source, **bounds) + cycle = [] + cycle.append(cycle) + with pytest.raises(CanonicalJSONError, match="cyclic"): + project(cycle) diff --git a/tests/managed/test_lifecycle_performance.py b/tests/managed/test_lifecycle_performance.py new file mode 100644 index 00000000..ed6f7734 --- /dev/null +++ b/tests/managed/test_lifecycle_performance.py @@ -0,0 +1,115 @@ +"""Work-count guards for managed execution without cached authority checks.""" + +import pytest + +from dryml.managed import ManagedConfig +from tests.conftest import _synthetic_environment_record +from tests.managed.u16_fixtures import Value, setup + + +@pytest.mark.parametrize("unavailable", [False, True]) +def test_environment_observed_once_per_execution_and_never_on_replay(tmp_path, monkeypatch, unavailable): + from dryml.environments import introspection + + observations = [] + environment = _synthetic_environment_record() + + def observe(): + observations.append(True) + if unavailable: + raise OSError("inventory unavailable") + return environment + + monkeypatch.setattr(introspection, "inspect_current", observe) + control, live = setup(tmp_path) + + def body(obj, ctx): + obj.value += 1 + ctx.checkpoint() + obj.value += 1 + + monkeypatch.setattr(Value, "action", body) + config = ManagedConfig(state_repo=control.state_repo) + result = live.run(managed=config) + assert len(observations) == 1 and Value.captures == 2 + capture = control.state_repo.get_snapshot_metadata(result.final_state_ref) + assert capture.environment_status == ("unavailable" if unavailable else "known") + assert capture.environment == (None if unavailable else environment) + + replay = live.run(managed=config) + assert replay.execution.producer_invocation_id == result.execution.producer_invocation_id + assert len(observations) == 1 and Value.captures == 2 + + live.run(managed=ManagedConfig(state_repo=control.state_repo, rerun=True)) + assert len(observations) == 2 and Value.captures == 4 + + +def test_safe_points_reread_authority_without_redecoding_stable_graphs( + tmp_path, monkeypatch, fixed_managed_snapshot_environment): + from dryml.managed import control as module + + control, live = setup(tmp_path, index="sqlite") + decodes, reads = [], [] + decode, capture = module.decode_node_graph, module.ManagedControlStore._capture + + def counted_decode(*args, **kwargs): + decodes.append(True) + return decode(*args, **kwargs) + + def counted_capture(*args, **kwargs): + reads.append(True) + return capture(*args, **kwargs) + + monkeypatch.setattr(module, "decode_node_graph", counted_decode) + monkeypatch.setattr(module.ManagedControlStore, "_capture", counted_capture) + + def body(obj, ctx): + ctx.checkpoint() + ctx._safe_point() + previous_decodes, previous_reads = len(decodes), len(reads) + for _ in range(5): + ctx._safe_point() + assert len(decodes) == previous_decodes + assert len(reads) >= previous_reads + 5 + + monkeypatch.setattr(Value, "action", body) + result = live.run(managed=ManagedConfig(state_repo=control.state_repo)) + assert result.status.state == "completed" and decodes + + +def test_selected_final_without_capture_does_not_observe_environment( + tmp_path, monkeypatch, fixed_snapshot_environment): + from dryml.environments import introspection + + control, live = setup(tmp_path) + saved = control.state_repo.save(live) + monkeypatch.setattr(Value, "action", lambda obj, ctx: ctx.final_state(saved)) + monkeypatch.setattr(introspection, "inspect_current", lambda: pytest.fail("capture-free final observed environment")) + result = live.run(managed=ManagedConfig(state_repo=control.state_repo)) + assert result.final_state_ref.graph_equal(saved) + + +def test_control_decode_reuse_rejects_changed_bytes_and_wrong_operation( + tmp_path, monkeypatch, fixed_managed_snapshot_environment): + from dryml.core._content_facts import _content_facts_scope + from dryml.managed import ManagedControlError + from dryml.managed.control import ControlSnapshot + + control, live = setup(tmp_path) + monkeypatch.setattr(Value, "action", lambda obj, ctx: None) + result = live.run(managed=ManagedConfig(state_repo=control.state_repo)) + operation = result.execution.operation_id + payload = control.inspect(operation).to_bytes() + with _content_facts_scope(): + first = ControlSnapshot.from_bytes(payload, operation_id=operation) + assert ControlSnapshot.from_bytes(payload, operation_id=operation) is first + with pytest.raises(ManagedControlError): + ControlSnapshot.from_bytes(payload + b"!", operation_id=operation) + with pytest.raises(ManagedControlError): + ControlSnapshot.from_bytes(payload, operation_id="f" * 64) + + path = control._current_path(control._operation_path(operation)) + from pathlib import Path + Path(path).write_bytes(payload + b"!") + with pytest.raises(ManagedControlError): + control.inspect(operation) diff --git a/tests/tools/benchmark_cached_dataset.py b/tests/tools/benchmark_cached_dataset.py new file mode 100644 index 00000000..25d111ac --- /dev/null +++ b/tests/tools/benchmark_cached_dataset.py @@ -0,0 +1,68 @@ +"""Opt-in fresh-Store cache benchmark; emits JSON lines and restores every result. + +Run with ``python -m tests.tools.benchmark_cached_dataset --depth 5 --repeats 3`` +in the development environment. Each sample owns a disposable TemporaryDirectory +under TMPDIR, uses real environment observation and SQLite publication, and times +build and compute separately. Imports, restore verification and cleanup are outside +the compute measurement. This is not a timing assertion or an automated test. +""" + +import argparse +import json +from tempfile import TemporaryDirectory +from time import perf_counter, process_time + +import numpy as np + +from dryml.artifacts import CachedDataset +from dryml.core import Definition, Ref, Repo +from dryml.core.store.dir import DirStore +from dryml.data.structural import Take +from dryml.managed import ManagedConfig +from tests.artifacts.test_cached_dataset import CountingDataset + + +def main(): + """Benchmark CLI-selected recipe depth/repeats; reject invalid counts via argparse. + + Reads --depth (nonnegative int) and --repeats/--elements (positive ints) from + argv. Returns None after emitting one JSON object per sample. Framework/IO + failures propagate with cleanup; source traversal and restored content are + verified rather than reporting a failed/incomplete invocation as a timing. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--depth", type=int, default=0) + parser.add_argument("--repeats", type=int, default=3) + parser.add_argument("--elements", type=int, default=1) + args = parser.parse_args() + if args.depth < 0 or args.repeats < 1 or args.elements < 1: + parser.error("depth must be nonnegative; repeats and elements must be positive") + for sample in range(args.repeats): + source = Definition(CountingDataset, [np.asarray([1], dtype=np.int32)] * args.elements, args.elements) + for _ in range(args.depth): + source = Definition(Take, source, args.elements) + recipe = Definition(CachedDataset, Ref(source.concretize())) + with TemporaryDirectory(prefix="dryml-cache-benchmark-") as root: + repo = Repo(DirStore(root + "/store")) + try: + started = perf_counter() + concrete = recipe.concretize() + cache = (repo.build(concrete) if hasattr(repo, "build") else + repo._load_structural(concrete, require_store=False)) + built = perf_counter() + cpu_started = process_time() + result = cache.compute(codec="numpy", managed=ManagedConfig(state_repo=repo)) + cpu_seconds = process_time() - cpu_started + completed = perf_counter() + saved = getattr(result, "final_state_ref", result) + restored = repo.load_state_ref(saved, reuse_live="never") + assert restored.ready and len(restored) == args.elements and restored.peek().tolist() == [1] + print(json.dumps({"sample": sample, "depth": args.depth, "elements": args.elements, + "build_seconds": built - started, "compute_seconds": completed - built, + "compute_cpu_seconds": cpu_seconds}), flush=True) + finally: + repo.close(flush=False) + + +if __name__ == "__main__": + main()