Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/environments.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
97 changes: 97 additions & 0 deletions docs/managed_lifecycle_performance.md
Original file line number Diff line number Diff line change
@@ -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.
25 changes: 25 additions & 0 deletions docs/managed_operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
75 changes: 73 additions & 2 deletions src/dryml/core/_content_facts.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down
11 changes: 11 additions & 0 deletions src/dryml/core/node_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@


EXACT_KEY_VERSION = "dryml-node-exact/v1"
_FLAT_EVIDENCE = object()


def _bytes(value):
Expand Down Expand Up @@ -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
Expand All @@ -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 = []
Expand All @@ -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):
Expand Down
29 changes: 24 additions & 5 deletions src/dryml/core/store/dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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.
"""

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
Loading
Loading