model-runtime 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
saturn/paths.py ADDED
@@ -0,0 +1,324 @@
1
+ """Bounded temporal assays and point-aligned, same-parent trajectory comparisons.
2
+
3
+ This is an execution/observation helper, not measured Program certification.
4
+ Every mutation and transition still uses Session. Full cuts are deliberately
5
+ opt-in through this tracing workflow rather than retained by ordinary execution.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable, Mapping
11
+ from dataclasses import dataclass, field
12
+ from types import MappingProxyType
13
+ from typing import Any
14
+
15
+ from .core import Act, Receipt, Session, StateCut
16
+ from .values import clone, describe, digest
17
+
18
+
19
+ class PathExecutionError(RuntimeError):
20
+ """A failed arm retains completed cuts/receipts and the last valid state."""
21
+
22
+ def __init__(self, error: Exception, *, points, events, cut, attempts):
23
+ super().__init__(f"{type(error).__name__}: {error}")
24
+ self.points = tuple(points)
25
+ self.events = tuple(events)
26
+ self.cut = cut
27
+ self.attempts = tuple(attempts)
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class TimedAct:
32
+ after_steps: int
33
+ act: Act
34
+
35
+ def __post_init__(self):
36
+ if type(self.after_steps) is not int or self.after_steps < 0:
37
+ raise ValueError("schedule offset must be a nonnegative integer")
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class PathSchedule:
42
+ instructions: tuple[TimedAct, ...] = ()
43
+
44
+ def __post_init__(self):
45
+ object.__setattr__(self, "instructions", tuple(self.instructions))
46
+ offsets = [item.after_steps for item in self.instructions]
47
+ if offsets != sorted(offsets):
48
+ raise ValueError("schedule must be ordered; same-offset Acts keep declared order")
49
+
50
+ def to_dict(self) -> dict[str, Any]:
51
+ return {
52
+ "instructions": [
53
+ {"after_steps": item.after_steps, "act": item.act.manifest()}
54
+ for item in self.instructions
55
+ ],
56
+ "authority": "exploratory-execution-not-measured-program",
57
+ }
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class TracePoint:
62
+ offset: int
63
+ cut: StateCut
64
+ values: Mapping[str, Any]
65
+ metrics: Mapping[str, Any]
66
+ receipts: tuple[Receipt, ...]
67
+ fingerprint: str = field(init=False)
68
+
69
+ def __post_init__(self):
70
+ object.__setattr__(self, "values", MappingProxyType(clone(dict(self.values))))
71
+ object.__setattr__(self, "metrics", MappingProxyType(clone(dict(self.metrics))))
72
+ object.__setattr__(self, "fingerprint", digest(self._body()))
73
+
74
+ def _body(self) -> dict[str, Any]:
75
+ return {
76
+ "offset": self.offset,
77
+ "cut": self.cut.fingerprint,
78
+ "execution_point": dict(self.cut.execution_point or {}),
79
+ "values": describe(dict(self.values)),
80
+ "metrics": clone(dict(self.metrics)),
81
+ "receipts": [row.to_dict() for row in self.receipts],
82
+ }
83
+
84
+ def verify(self) -> None:
85
+ self.cut.verify()
86
+ if digest(self._body()) != self.fingerprint:
87
+ raise ValueError("trace observations changed")
88
+ if any(
89
+ describe(value) != describe(self.cut.payload[port])
90
+ for port, value in self.values.items()
91
+ ):
92
+ raise ValueError("trace observations are not cut-backed slots")
93
+
94
+ def to_dict(self) -> dict[str, Any]:
95
+ self.verify()
96
+ return {**self._body(), "fingerprint": self.fingerprint}
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class Trajectory:
101
+ name: str
102
+ parent: StateCut
103
+ schedule: PathSchedule
104
+ points: tuple[TracePoint, ...]
105
+ events: tuple[tuple[Receipt, StateCut], ...]
106
+ entry: StateCut
107
+
108
+ @classmethod
109
+ def run(
110
+ cls,
111
+ session: Session,
112
+ *,
113
+ name: str,
114
+ parent: StateCut,
115
+ steps: int,
116
+ ports: tuple[str, ...],
117
+ schedule: PathSchedule = PathSchedule(),
118
+ evaluator: Callable[[Session], Mapping[str, Any]] | None = None,
119
+ ) -> Trajectory:
120
+ if not name or type(steps) is not int or steps < 1 or not ports:
121
+ raise ValueError("trace requires name, positive budget and observed ports")
122
+ if len(set(ports)) != len(ports):
123
+ raise ValueError("trace ports must be unique")
124
+ if any(item.after_steps > steps for item in schedule.instructions):
125
+ raise ValueError("schedule extends past the declared horizon")
126
+ parent.verify()
127
+ branch = session.fork(parent)
128
+ entry = branch.capture(retain=False)
129
+ points = []
130
+ events = []
131
+ for offset in range(steps + 1):
132
+ receipts = []
133
+ try:
134
+ if offset:
135
+ receipt = branch.step()
136
+ receipts.append(receipt)
137
+ events.append((receipt, branch.capture(retain=False)))
138
+ for item in schedule.instructions:
139
+ if item.after_steps == offset:
140
+ receipt = branch.apply(item.act)
141
+ receipts.append(receipt)
142
+ events.append((receipt, branch.capture(retain=False)))
143
+ cut = branch.capture(retain=False)
144
+ values = {port: branch.read(port) for port in ports}
145
+ metrics = {} if evaluator is None else dict(evaluator(branch.fork(cut)))
146
+ # Refuse non-JSON/unstable metric artifacts before returning a trace.
147
+ digest(metrics)
148
+ except Exception as exc:
149
+ raise PathExecutionError(
150
+ exc,
151
+ points=points,
152
+ events=events,
153
+ cut=branch.capture(retain=False),
154
+ attempts=branch.attempts,
155
+ ) from exc
156
+ points.append(TracePoint(offset, cut, clone(values), clone(metrics), tuple(receipts)))
157
+ return cls(name, parent, schedule, tuple(points), tuple(events), entry)
158
+
159
+ def verify(self) -> None:
160
+ self.parent.verify()
161
+ self.entry.verify()
162
+ if len(self.points) < 2 or [p.offset for p in self.points] != list(range(len(self.points))):
163
+ raise ValueError(
164
+ "trace offsets must be consecutive from zero; not aligned to transitions"
165
+ )
166
+ if (
167
+ self.entry.parent != self.parent.fingerprint
168
+ or describe(self.entry.payload) != describe(self.parent.payload)
169
+ or self.entry.model_identity != self.parent.model_identity
170
+ or dict(self.entry.execution) != dict(self.parent.execution)
171
+ ):
172
+ raise ValueError("trace entry is not a fork of its declared parent")
173
+ current = self.entry
174
+ for receipt, cut in self.events:
175
+ cut.verify()
176
+ body = receipt.to_dict()
177
+ if (
178
+ body.get("parent") != current.fingerprint
179
+ or body.get("result") != cut.fingerprint
180
+ or cut.parent != current.fingerprint
181
+ or cut.model_identity != self.parent.model_identity
182
+ or dict(cut.execution) != dict(self.parent.execution)
183
+ or body.get("model_identity") != cut.model_identity
184
+ or body.get("execution") != dict(cut.execution)
185
+ or body.get("execution_point") != dict(cut.execution_point or {})
186
+ ):
187
+ raise ValueError("trace event ancestry or execution mismatch")
188
+ current = cut
189
+ if [r.fingerprint for p in self.points for r in p.receipts] != [
190
+ r.fingerprint for r, _ in self.events
191
+ ]:
192
+ raise ValueError("trace point receipts do not match retained events")
193
+ event_cuts = {receipt.fingerprint: cut.fingerprint for receipt, cut in self.events}
194
+ for point in self.points:
195
+ point.verify()
196
+ native_rows = [
197
+ row.to_dict() for row in point.receipts if row.to_dict()["operation"] != "apply"
198
+ ]
199
+ if (
200
+ len(native_rows) != (1 if point.offset else 0)
201
+ or any(
202
+ row["operation"] != "continue" or row.get("steps") != 1 for row in native_rows
203
+ )
204
+ or (native_rows and point.receipts[0].to_dict()["operation"] != "continue")
205
+ ):
206
+ raise ValueError(
207
+ "trace offset does not count one native transition before its Acts"
208
+ )
209
+ expected = (
210
+ event_cuts[point.receipts[-1].fingerprint]
211
+ if point.receipts
212
+ else self.entry.fingerprint
213
+ )
214
+ if point.cut.fingerprint != expected:
215
+ raise ValueError("trace point cut is not its producing event")
216
+ measured = [
217
+ (point.offset, row.to_dict()["act"])
218
+ for point in self.points
219
+ for row in point.receipts
220
+ if row.to_dict()["operation"] == "apply"
221
+ ]
222
+ declared = [(item.after_steps, item.act.manifest()) for item in self.schedule.instructions]
223
+ if measured != declared:
224
+ raise ValueError("trace schedule does not match recorded Acts")
225
+
226
+ def to_dict(self) -> dict[str, Any]:
227
+ self.verify()
228
+ return {
229
+ "schema": "saturn-pub-trajectory-v1",
230
+ "name": self.name,
231
+ "parent": self.parent.fingerprint,
232
+ "entry": self.entry.fingerprint,
233
+ "schedule": self.schedule.to_dict(),
234
+ "points": [point.to_dict() for point in self.points],
235
+ "events": [
236
+ {"receipt": receipt.to_dict(), "cut": cut.fingerprint}
237
+ for receipt, cut in self.events
238
+ ],
239
+ "authority": "observations-only",
240
+ }
241
+
242
+
243
+ def compare_trajectories(native: Trajectory, candidate: Trajectory) -> dict[str, Any]:
244
+ """Exact selected-port differences and recovery windows at recorded points.
245
+
246
+ A recovery means equality of that selected observable, not semantic repair.
247
+ Evaluator measurements remain separate. Clock misalignment is an error;
248
+ restoring/changing clocks cannot masquerade as an aligned comparison.
249
+ """
250
+ if native.parent.fingerprint != candidate.parent.fingerprint:
251
+ raise ValueError("trajectory comparison requires one exact common parent")
252
+ native.verify()
253
+ candidate.verify()
254
+ if len(native.points) != len(candidate.points):
255
+ raise ValueError("trajectory horizons differ")
256
+ rows = []
257
+ windows: dict[str, list[dict[str, Any]]] = {}
258
+ active: dict[str, int] = {}
259
+ first = None
260
+ for left, right in zip(native.points, candidate.points):
261
+ left.cut.verify()
262
+ right.cut.verify()
263
+ for point in (left, right):
264
+ if point.cut.model_identity != native.parent.model_identity or dict(
265
+ point.cut.execution
266
+ ) != dict(native.parent.execution):
267
+ raise ValueError("trace cut model or execution differs from parent")
268
+ if left.offset != right.offset or dict(left.cut.execution_point or {}) != dict(
269
+ right.cut.execution_point or {}
270
+ ):
271
+ raise ValueError("trajectory execution points are not aligned")
272
+ if set(left.values) != set(right.values):
273
+ raise ValueError("trajectory observed ports differ")
274
+ # Retained observations must still describe the sealed cut's port values.
275
+ for point in (left, right):
276
+ payload = point.cut.payload
277
+ if any(
278
+ describe(value) != describe(payload[port]) for port, value in point.values.items()
279
+ ):
280
+ raise ValueError("trace observations changed or are not cut-backed slots")
281
+ different = []
282
+ recovered = []
283
+ for port in left.values:
284
+ equal = describe(left.values[port]) == describe(right.values[port])
285
+ if not equal:
286
+ different.append(port)
287
+ active.setdefault(port, left.offset)
288
+ elif port in active:
289
+ recovered.append(port)
290
+ windows.setdefault(port, []).append(
291
+ {"diverged_at": active.pop(port), "recovered_at": left.offset}
292
+ )
293
+ if different and first is None:
294
+ first = {
295
+ "offset": left.offset,
296
+ "ports": different,
297
+ "execution_point": dict(right.cut.execution_point or {}),
298
+ }
299
+ rows.append(
300
+ {
301
+ "offset": left.offset,
302
+ "native_cut": left.cut.fingerprint,
303
+ "candidate_cut": right.cut.fingerprint,
304
+ "different_ports": different,
305
+ "recovered_ports": recovered,
306
+ "native_metrics": clone(dict(left.metrics)),
307
+ "candidate_metrics": clone(dict(right.metrics)),
308
+ "receipts": [receipt.fingerprint for receipt in right.receipts],
309
+ }
310
+ )
311
+ for port, offset in active.items():
312
+ windows.setdefault(port, []).append({"diverged_at": offset, "recovered_at": None})
313
+ return {
314
+ "schema": "saturn-pub-trajectory-diff-v1",
315
+ "parent": native.parent.fingerprint,
316
+ "native": native.name,
317
+ "candidate": candidate.name,
318
+ "first_recorded_divergence": first,
319
+ "observable_windows": windows,
320
+ "rows": rows,
321
+ "comparator": "exact-typed-selected-port-content",
322
+ "interpretation": "observable recovery is not automatic semantic repair",
323
+ "terminal_status": "not-assessed",
324
+ }
saturn/program.py ADDED
@@ -0,0 +1,364 @@
1
+ """Recipient-bound schedules compiled from measured panel rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import importlib
7
+ import inspect
8
+ import json
9
+ import platform
10
+ from collections.abc import Callable, Mapping
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from .core import Act, Adapter, Receipt, Session
16
+ from .store import LocalStore
17
+ from .values import canonical, clone, digest
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Instruction:
22
+ after_steps: int
23
+ act: Act
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Program:
28
+ model_identity: str
29
+ execution: dict[str, Any]
30
+ entry_boundary: str
31
+ instructions: tuple[Instruction, ...]
32
+ evidence_parent: str
33
+ evidence_plan: str
34
+ evidence_arm: str
35
+ context: str
36
+ continuation_steps: int
37
+
38
+ def manifest(self) -> dict[str, Any]:
39
+ return {
40
+ "schema": "saturn-pub-program-v2",
41
+ "model_identity": self.model_identity,
42
+ "execution": self.execution,
43
+ "entry_boundary": self.entry_boundary,
44
+ "instructions": [
45
+ {"after_steps": item.after_steps, "act": item.act.manifest()}
46
+ for item in self.instructions
47
+ ],
48
+ "evidence_parent": self.evidence_parent,
49
+ "evidence_plan": self.evidence_plan,
50
+ "evidence_arm": self.evidence_arm,
51
+ "context": self.context,
52
+ "continuation_steps": self.continuation_steps,
53
+ }
54
+
55
+ @classmethod
56
+ def compile(
57
+ cls,
58
+ session: Session,
59
+ panel: dict[str, Any],
60
+ arm: str,
61
+ instructions: tuple[Instruction, ...],
62
+ *,
63
+ context: str,
64
+ ) -> Program:
65
+ cut = session.capture()
66
+ rows = [row for row in panel["rows"] if row["name"] == arm]
67
+ if len(rows) != 1 or rows[0]["status"] != "completed" or not instructions or not context:
68
+ raise ValueError("compilation requires one completed measured arm and explicit context")
69
+ if panel["parent"] != cut.fingerprint:
70
+ raise ValueError("panel parent does not match the recipient state")
71
+ if any(item.after_steps < 0 for item in instructions):
72
+ raise ValueError("instruction delay must be non-negative")
73
+ for item in instructions:
74
+ item.act.require_reproducible()
75
+ measured = [
76
+ receipt["act"] for receipt in rows[0]["receipts"] if receipt["operation"] == "apply"
77
+ ]
78
+ if measured != [item.act.manifest() for item in instructions]:
79
+ raise ValueError("program operations do not match the measured arm")
80
+ # v1 certifies only the panel's pre-continuation schedule.
81
+ if any(item.after_steps for item in instructions):
82
+ raise ValueError("nonzero delays require a separately measured temporal panel")
83
+ return cls(
84
+ session.adapter.model_identity,
85
+ dict(session.adapter.execution),
86
+ cut.boundary,
87
+ instructions,
88
+ cut.fingerprint,
89
+ panel["plan"],
90
+ arm,
91
+ context,
92
+ panel["continuation_steps"],
93
+ )
94
+
95
+ def run(
96
+ self, session: Session, *, context: str, continuation_steps: int | None = None
97
+ ) -> Session:
98
+ cut = session.capture()
99
+ continuation_steps = (
100
+ self.continuation_steps if continuation_steps is None else continuation_steps
101
+ )
102
+ if continuation_steps != self.continuation_steps:
103
+ raise ValueError("continuation budget is outside the measured program support")
104
+ if (
105
+ cut.model_identity != self.model_identity
106
+ or dict(cut.execution) != self.execution
107
+ or cut.boundary != self.entry_boundary
108
+ or cut.fingerprint != self.evidence_parent
109
+ or context != self.context
110
+ ):
111
+ raise ValueError("program recipient/context is outside its measured support")
112
+ branch = session.fork(cut)
113
+ for instruction in self.instructions:
114
+ instruction.act.require_reproducible()
115
+ if instruction.after_steps:
116
+ branch.continue_(instruction.after_steps)
117
+ branch.apply(instruction.act)
118
+ branch.continue_(continuation_steps)
119
+ return branch
120
+
121
+
122
+ class GenericJSONAdapter(Adapter):
123
+ """A declarative adapter factory for small JSON-only replay organisms."""
124
+
125
+ def __init__(self, specification: Mapping[str, Any]):
126
+ specification = clone(dict(specification))
127
+ canonical(specification)
128
+ if specification.get("kind") != "generic-json":
129
+ raise ValueError("generic adapter specification requires kind='generic-json'")
130
+ self.specification = specification
131
+ self.model_identity = str(specification["model_identity"])
132
+ self.execution = dict(specification["execution"])
133
+ self._boundary = str(specification.get("boundary", "json-step"))
134
+ self._slots = tuple(specification.get("slots", ()))
135
+ if not self._slots or any(not isinstance(slot, str) or not slot for slot in self._slots):
136
+ raise ValueError("generic JSON adapter requires named slots")
137
+
138
+ def boundary(self, state: Mapping[str, Any]) -> str:
139
+ cursor = self.specification.get("boundary_slot")
140
+ return self._boundary if cursor is None else f"{self._boundary}:{state[cursor]}"
141
+
142
+ def validate(self, state: Mapping[str, Any]) -> None:
143
+ if set(state) != set(self._slots):
144
+ raise ValueError("generic JSON state does not match its declared slots")
145
+ canonical(dict(state))
146
+
147
+ def addresses(self, state: Mapping[str, Any]) -> tuple[str, ...]:
148
+ self.validate(state)
149
+ return self._slots
150
+
151
+ def advance(self, state: Mapping[str, Any]) -> Mapping[str, Any]:
152
+ self.validate(state)
153
+ result = clone(dict(state))
154
+ transition = self.specification.get("advance", {"kind": "identity"})
155
+ kind = transition.get("kind")
156
+ if kind == "identity":
157
+ return result
158
+ if kind == "increment":
159
+ slot = transition["slot"]
160
+ if slot not in result or type(result[slot]) not in (int, float):
161
+ raise ValueError("generic increment requires a numeric declared slot")
162
+ result[slot] += transition.get("amount", 1)
163
+ self.validate(result)
164
+ return result
165
+ raise ValueError("unknown generic JSON transition")
166
+
167
+
168
+ def _python_factory_digest(module: str, qualname: str) -> str:
169
+ target: Any = importlib.import_module(module)
170
+ for component in qualname.split("."):
171
+ target = getattr(target, component)
172
+ try:
173
+ source = inspect.getsource(target).encode()
174
+ except (OSError, TypeError):
175
+ source = repr(target).encode()
176
+ return hashlib.sha256(source).hexdigest()
177
+
178
+
179
+ @dataclass(frozen=True)
180
+ class ReplayBundle:
181
+ """A sealed replay description plus local cut ancestry and optional data bytes."""
182
+
183
+ _body: bytes
184
+
185
+ @classmethod
186
+ def create(
187
+ cls,
188
+ program: Program,
189
+ store: LocalStore,
190
+ *,
191
+ branch_heads: Mapping[str, str],
192
+ receipts: tuple[Receipt | Mapping[str, Any], ...] = (),
193
+ environment: Mapping[str, Any] | None = None,
194
+ adapter_factory: Mapping[str, Any],
195
+ include_data: bool = False,
196
+ ) -> ReplayBundle:
197
+ if not branch_heads:
198
+ raise ValueError("ReplayBundle requires at least one named branch head")
199
+ factory = clone(dict(adapter_factory))
200
+ factory.setdefault("model_identity", program.model_identity)
201
+ factory.setdefault("execution", clone(program.execution))
202
+ if (
203
+ factory["model_identity"] != program.model_identity
204
+ or factory["execution"] != program.execution
205
+ ):
206
+ raise ValueError("adapter factory identity differs from the measured program")
207
+ kind = factory.get("kind")
208
+ if kind == "python":
209
+ observed = _python_factory_digest(factory["module"], factory["qualname"])
210
+ supplied = factory.setdefault("implementation_digest", observed)
211
+ if supplied != observed:
212
+ raise ValueError("adapter factory implementation digest mismatch")
213
+ elif kind == "generic-json":
214
+ unsigned = {
215
+ key: value for key, value in factory.items() if key != "implementation_digest"
216
+ }
217
+ observed = digest(unsigned)
218
+ supplied = factory.setdefault("implementation_digest", observed)
219
+ if supplied != observed:
220
+ raise ValueError("generic adapter factory provenance digest mismatch")
221
+ else:
222
+ raise ValueError("adapter factory must be 'python' or 'generic-json'")
223
+ graph = store.export_graph(branch_heads, include_data=include_data)
224
+ for identifier, record in graph["cuts"].items():
225
+ manifest = record["manifest"]
226
+ if (
227
+ manifest["model_identity"] != program.model_identity
228
+ or manifest["execution"] != program.execution
229
+ ):
230
+ raise ValueError(f"cut identity differs from the program: {identifier}")
231
+ receipt_rows = []
232
+ for receipt in receipts:
233
+ row = receipt.to_dict() if isinstance(receipt, Receipt) else clone(dict(receipt))
234
+ if "fingerprint" not in row:
235
+ row["fingerprint"] = hashlib.sha256(canonical(row)).hexdigest()
236
+ receipt_rows.append(row)
237
+ env = {
238
+ "python": platform.python_version(),
239
+ "implementation": platform.python_implementation(),
240
+ "platform": platform.platform(),
241
+ **({} if environment is None else clone(dict(environment))),
242
+ }
243
+ return cls(
244
+ canonical(
245
+ {
246
+ "schema": "saturn-pub-replay-bundle-v1",
247
+ "program": program.manifest(),
248
+ "branch_heads": dict(branch_heads),
249
+ "receipts": receipt_rows,
250
+ "environment": env,
251
+ "adapter_factory": factory,
252
+ "local_graph": graph,
253
+ }
254
+ )
255
+ )
256
+
257
+ @property
258
+ def fingerprint(self) -> str:
259
+ return hashlib.sha256(self._body).hexdigest()
260
+
261
+ def to_dict(self) -> dict[str, Any]:
262
+ return {**json.loads(self._body), "fingerprint": self.fingerprint}
263
+
264
+ def verify(self) -> None:
265
+ body = json.loads(self._body)
266
+ if body.get("schema") != "saturn-pub-replay-bundle-v1":
267
+ raise ValueError("unknown ReplayBundle schema")
268
+ program = body.get("program", {})
269
+ factory = body.get("adapter_factory", {})
270
+ if factory.get("model_identity") != program.get("model_identity") or factory.get(
271
+ "execution"
272
+ ) != program.get("execution"):
273
+ raise ValueError("ReplayBundle adapter/program identity mismatch")
274
+ if factory.get("kind") == "generic-json":
275
+ unsigned = {
276
+ key: value for key, value in factory.items() if key != "implementation_digest"
277
+ }
278
+ if digest(unsigned) != factory.get("implementation_digest"):
279
+ raise ValueError("ReplayBundle generic adapter provenance changed")
280
+ graph = body.get("local_graph", {})
281
+ if graph.get("heads") != body.get("branch_heads"):
282
+ raise ValueError("ReplayBundle branch heads differ from its local graph")
283
+ for name, identifier in body.get("branch_heads", {}).items():
284
+ if not isinstance(name, str) or identifier not in graph.get("cuts", {}):
285
+ raise ValueError("ReplayBundle branch head is not in local custody")
286
+ for identifier, record in graph.get("cuts", {}).items():
287
+ if digest(record.get("manifest")) != identifier:
288
+ raise ValueError("ReplayBundle contains a cut with a broken identity")
289
+ manifest = record["manifest"]
290
+ if manifest.get("model_identity") != program.get("model_identity") or manifest.get(
291
+ "execution"
292
+ ) != program.get("execution"):
293
+ raise ValueError("ReplayBundle cut/program identity mismatch")
294
+ for receipt in body.get("receipts", ()):
295
+ if not isinstance(receipt, dict) or "fingerprint" not in receipt:
296
+ raise ValueError("ReplayBundle receipt is not sealed")
297
+ sealed = dict(receipt)
298
+ fingerprint = sealed.pop("fingerprint")
299
+ if hashlib.sha256(canonical(sealed)).hexdigest() != fingerprint:
300
+ raise ValueError("ReplayBundle receipt fingerprint mismatch")
301
+
302
+ def save(self, path: str | Path) -> str:
303
+ self.verify()
304
+ destination = Path(path)
305
+ destination.parent.mkdir(parents=True, exist_ok=True)
306
+ body = canonical(self.to_dict())
307
+ destination.write_bytes(body)
308
+ return self.fingerprint
309
+
310
+ export = save
311
+
312
+ @classmethod
313
+ def load(cls, path: str | Path) -> ReplayBundle:
314
+ data = json.loads(Path(path).read_bytes())
315
+ fingerprint = data.pop("fingerprint", None)
316
+ bundle = cls(canonical(data))
317
+ if fingerprint != bundle.fingerprint:
318
+ raise ValueError("ReplayBundle fingerprint mismatch")
319
+ bundle.verify()
320
+ return bundle
321
+
322
+ def _adapter(self, adapter_factory: Callable[[], Adapter] | None = None) -> Adapter:
323
+ body = json.loads(self._body)
324
+ provenance = body["adapter_factory"]
325
+ if adapter_factory is not None:
326
+ adapter = adapter_factory()
327
+ elif provenance["kind"] == "generic-json":
328
+ adapter = GenericJSONAdapter(provenance)
329
+ else:
330
+ if (
331
+ _python_factory_digest(provenance["module"], provenance["qualname"])
332
+ != provenance["implementation_digest"]
333
+ ):
334
+ raise ValueError("adapter factory implementation changed")
335
+ target: Any = importlib.import_module(provenance["module"])
336
+ for component in provenance["qualname"].split("."):
337
+ target = getattr(target, component)
338
+ adapter = target(**provenance.get("kwargs", {}))
339
+ if not isinstance(adapter, Adapter):
340
+ raise ValueError("adapter factory did not produce an Adapter")
341
+ if (
342
+ adapter.model_identity != provenance["model_identity"]
343
+ or dict(adapter.execution) != provenance["execution"]
344
+ ):
345
+ raise ValueError("hydrated adapter identity differs from its provenance")
346
+ return adapter
347
+
348
+ def restore(
349
+ self,
350
+ store: LocalStore,
351
+ *,
352
+ allow_data: bool = False,
353
+ adapter_factory: Callable[[], Adapter] | None = None,
354
+ ) -> Adapter:
355
+ self.verify()
356
+ body = json.loads(self._body)
357
+ # Construct and check the native identity before importing any state bytes.
358
+ adapter = self._adapter(adapter_factory)
359
+ graph = body["local_graph"]
360
+ if graph.get("data_included"):
361
+ store.import_graph(graph, allow_data=allow_data)
362
+ elif allow_data:
363
+ raise ValueError("ReplayBundle was exported without state data")
364
+ return adapter