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/core.py ADDED
@@ -0,0 +1,1979 @@
1
+ """One transaction lifecycle for native model execution and counterfactual research."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import hashlib
7
+ import inspect
8
+ import marshal
9
+ from abc import ABC, abstractmethod
10
+ from collections.abc import Callable, Mapping
11
+ from dataclasses import InitVar, dataclass, field
12
+ from types import CodeType, MappingProxyType
13
+ from typing import Any, NamedTuple
14
+
15
+ from .contracts import (
16
+ ExecutionPoint,
17
+ NumericalContract,
18
+ SlotSpec,
19
+ StateAddress,
20
+ SurfaceManifest,
21
+ TransitionSpec,
22
+ )
23
+ from .values import clone, describe, describe_mapping, describe_remembered, digest, tensor
24
+
25
+ _OPERATION_REGISTRY: dict[tuple[str, str], tuple[str, Callable[..., Any], bool]] = {}
26
+
27
+
28
+ def _portable_code(code: CodeType) -> CodeType:
29
+ """Remove source-location metadata while preserving executable semantics."""
30
+ constants = tuple(
31
+ _portable_code(value) if isinstance(value, CodeType) else value for value in code.co_consts
32
+ )
33
+ return code.replace(
34
+ co_consts=constants,
35
+ co_filename="<saturn-operation>",
36
+ co_firstlineno=1,
37
+ co_linetable=b"",
38
+ )
39
+
40
+
41
+ def _implementation_value(value: Any, *, strict: bool) -> Any:
42
+ try:
43
+ return describe(value)
44
+ except (TypeError, ValueError):
45
+ if strict:
46
+ raise ValueError("registered operation closure/defaults must be content-sealable")
47
+ rendered = repr(value).encode()
48
+ return {
49
+ "kind": "opaque-exploratory",
50
+ "type": f"{type(value).__module__}.{type(value).__qualname__}",
51
+ "repr_sha256": hashlib.sha256(rendered).hexdigest(),
52
+ }
53
+
54
+
55
+ def _implementation_digest(implementation: Callable[..., Any], *, strict: bool = False) -> str:
56
+ target = implementation
57
+ closure = None
58
+ defaults = None
59
+ kwdefaults = None
60
+ if inspect.ismethod(target):
61
+ target = target.__func__
62
+ if inspect.isfunction(target):
63
+ code = target.__code__
64
+ closure = [cell.cell_contents for cell in (target.__closure__ or ())]
65
+ defaults = target.__defaults__
66
+ kwdefaults = target.__kwdefaults__
67
+ owner = {"module": target.__module__, "qualname": target.__qualname__}
68
+ else:
69
+ call = type(target).__call__
70
+ code = call.__code__
71
+ owner = {"module": type(target).__module__, "qualname": type(target).__qualname__}
72
+ body = {
73
+ **owner,
74
+ "code_sha256": hashlib.sha256(marshal.dumps(_portable_code(code))).hexdigest(),
75
+ "defaults": _implementation_value(defaults, strict=strict),
76
+ "kwdefaults": _implementation_value(kwdefaults, strict=strict),
77
+ "closure": _implementation_value(closure, strict=strict),
78
+ }
79
+ return digest(body)
80
+
81
+
82
+ def _implementation_state_digest(
83
+ implementation: Callable[..., Any], *, strict: bool = False
84
+ ) -> str:
85
+ if inspect.ismethod(implementation):
86
+ implementation = implementation.__func__
87
+ if inspect.isfunction(implementation):
88
+ state = {
89
+ "kind": "function-state",
90
+ "defaults": _implementation_value(implementation.__defaults__, strict=strict),
91
+ "kwdefaults": _implementation_value(implementation.__kwdefaults__, strict=strict),
92
+ "closure": _implementation_value(
93
+ [cell.cell_contents for cell in (implementation.__closure__ or ())],
94
+ strict=strict,
95
+ ),
96
+ }
97
+ else:
98
+ slots: dict[str, Any] = {}
99
+ for owner in type(implementation).__mro__:
100
+ declared = owner.__dict__.get("__slots__", ())
101
+ if isinstance(declared, str):
102
+ declared = (declared,)
103
+ for name in declared:
104
+ if name not in {"__dict__", "__weakref__"} and hasattr(implementation, name):
105
+ slots[f"{owner.__module__}.{owner.__qualname__}.{name}"] = getattr(
106
+ implementation, name
107
+ )
108
+ state = {
109
+ "kind": "callable-instance-state",
110
+ "type": f"{type(implementation).__module__}.{type(implementation).__qualname__}",
111
+ "dict": _implementation_value(
112
+ dict(getattr(implementation, "__dict__", {})), strict=strict
113
+ ),
114
+ "slots": _implementation_value(slots, strict=strict),
115
+ }
116
+ return digest(state)
117
+
118
+
119
+ def _register_operation(
120
+ operation_id: str,
121
+ version: str,
122
+ implementation: Callable[..., Any],
123
+ *,
124
+ pure: bool,
125
+ ) -> str:
126
+ if not operation_id or not version or not callable(implementation):
127
+ raise ValueError("operation registration requires id, version, and callable")
128
+ if not pure:
129
+ raise ValueError("replayable operation registration requires an explicit pure=True")
130
+ implementation_digest = _implementation_digest(implementation, strict=True)
131
+ key = (operation_id, version)
132
+ existing = _OPERATION_REGISTRY.get(key)
133
+ if existing is not None and existing[0] != implementation_digest:
134
+ raise ValueError("operation id/version is already bound to a different implementation")
135
+ _OPERATION_REGISTRY[key] = (implementation_digest, implementation, True)
136
+ return implementation_digest
137
+
138
+
139
+ class _ReplaceOperation:
140
+ def __init__(self, address: str, value: Any):
141
+ self.address = address
142
+ self.value = clone(value)
143
+
144
+ def __call__(self, _: Mapping[str, Any]) -> Mapping[str, Any]:
145
+ return {self.address: clone(self.value)}
146
+
147
+
148
+ class _AddOperation:
149
+ def __init__(self, address: str, value: Any, dose: float):
150
+ self.address = address
151
+ self.value = clone(value)
152
+ self.dose = dose
153
+
154
+ def __call__(self, inputs: Mapping[str, Any]) -> Mapping[str, Any]:
155
+ return {self.address: inputs[self.address] + self.dose * self.value}
156
+
157
+
158
+ class _ZeroOperation:
159
+ def __init__(self, address: str):
160
+ self.address = address
161
+
162
+ def __call__(self, inputs: Mapping[str, Any]) -> Mapping[str, Any]:
163
+ return {self.address: inputs[self.address] * 0}
164
+
165
+
166
+ def _all_bools(value: Any) -> bool:
167
+ return type(value) is bool or (
168
+ isinstance(value, list) and bool(value) and all(_all_bools(item) for item in value)
169
+ )
170
+
171
+
172
+ class _PatchOperation:
173
+ def __init__(self, address: str, value: Any, mask: Any, mode: str, dose: float):
174
+ self.address = address
175
+ self.value = clone(value)
176
+ self.mask = clone(mask)
177
+ self.mode = mode
178
+ self.dose = dose
179
+
180
+ def __call__(self, inputs: Mapping[str, Any]) -> Mapping[str, Any]:
181
+ current = inputs[self.address]
182
+ if not tensor(current):
183
+ raise ValueError("patch currently requires a tensor-valued address")
184
+ torch = __import__("torch")
185
+ if tensor(self.mask):
186
+ if self.mask.dtype != torch.bool:
187
+ raise ValueError("patch tensor mask must have bool dtype")
188
+ mask = self.mask.to(device=current.device)
189
+ else:
190
+ if not _all_bools(self.mask):
191
+ raise ValueError("patch JSON mask must contain only booleans")
192
+ mask = torch.tensor(self.mask, dtype=torch.bool, device=current.device)
193
+ if tuple(mask.shape) != tuple(current.shape):
194
+ raise ValueError("patch mask shape must exactly match the current tensor")
195
+ value = self.value
196
+ if tensor(value):
197
+ if tuple(value.shape) != tuple(current.shape) or value.dtype != current.dtype:
198
+ raise ValueError("patch value tensor shape/dtype must match the current tensor")
199
+ value = value.to(device=current.device)
200
+ selected = value[mask]
201
+ elif type(value) not in (int, float, bool):
202
+ raise ValueError("patch value must be a scalar or matching tensor")
203
+ else:
204
+ selected = value
205
+ result = current.detach().clone()
206
+ if self.mode == "replace":
207
+ result[mask] = selected
208
+ else:
209
+ result[mask] = result[mask] + self.dose * selected
210
+ return {self.address: result}
211
+
212
+
213
+ @dataclass(frozen=True)
214
+ class Frame:
215
+ """Immutable metadata descriptor; tensor readback is always a private copy."""
216
+
217
+ boundary: str
218
+ slots: Mapping[str, Any]
219
+ execution_point: Mapping[str, Any] = field(default_factory=dict)
220
+ surface: Mapping[str, Any] = field(default_factory=dict)
221
+
222
+ def __post_init__(self) -> None:
223
+ object.__setattr__(self, "slots", MappingProxyType(clone(dict(self.slots))))
224
+ object.__setattr__(
225
+ self, "execution_point", MappingProxyType(clone(dict(self.execution_point)))
226
+ )
227
+ object.__setattr__(self, "surface", MappingProxyType(clone(dict(self.surface))))
228
+
229
+
230
+ def _statecut_manifest(
231
+ model_identity: str,
232
+ execution: Mapping[str, Any],
233
+ boundary: str,
234
+ parent: str | None,
235
+ payload: Any,
236
+ execution_point: Mapping[str, Any] | None,
237
+ surface: Mapping[str, Any] | None,
238
+ ) -> dict[str, Any]:
239
+ """The sealed manifest of a StateCut, given the ``describe`` of its payload."""
240
+ return {
241
+ "schema": "saturn-pub-statecut-v2",
242
+ "model_identity": model_identity,
243
+ "execution": dict(execution),
244
+ "boundary": boundary,
245
+ "parent": parent,
246
+ "payload": payload,
247
+ "execution_point": None if execution_point is None else describe(dict(execution_point)),
248
+ "surface": None if surface is None else describe(dict(surface)),
249
+ }
250
+
251
+
252
+ def _slot_descriptors(described: Any) -> dict[str, Any] | None:
253
+ """``{slot: describe(value)}`` from the ``describe`` of a payload mapping (None when a key is
254
+ not a plain scalar, so the caller hashes instead)."""
255
+ out: dict[str, Any] = {}
256
+ for item in described["items"]:
257
+ key = item["key"]
258
+ if key.get("kind") != "scalar":
259
+ return None
260
+ out[key["value"]] = item["value"]
261
+ return out
262
+
263
+
264
+ class _Appended:
265
+ """A sealed tensor held as blocks: ``torch.cat(chunks, dim)`` is it bit for bit, with the
266
+ standard contiguous layout it was sealed with. A cut holds a grown cache tensor this way, so
267
+ consecutive cuts share every block and each adds only the rows its transition appended."""
268
+
269
+ __slots__ = ("chunks", "dim", "guard")
270
+
271
+ def __init__(
272
+ self,
273
+ chunks: tuple[Any, ...],
274
+ dim: int,
275
+ guard: tuple[tuple[int, Any, int], ...] | None = None,
276
+ ):
277
+ self.chunks, self.dim = chunks, dim
278
+ # ``(index, chunk, version)`` of every chunk that tracks in-place writes, recorded once
279
+ # when the chunk joins (a grown layer extends its prefix's guard by the new chunk), so
280
+ # a cut holding this block form is version-guarded without walking its chunks
281
+ self.guard = (
282
+ tuple(
283
+ (index, chunk, chunk._version)
284
+ for index, chunk in enumerate(chunks)
285
+ if _versioned(chunk)
286
+ )
287
+ if guard is None
288
+ else guard
289
+ )
290
+
291
+ def materialize(self, *, register: bool) -> Any:
292
+ """The tensor (a fresh one). ``register``: the caller (a Session hydrating its own state)
293
+ will treat it as immutable, so a later cut sharing it is sealed as these same blocks."""
294
+ import torch
295
+
296
+ with torch.inference_mode(False):
297
+ full = torch.cat(self.chunks, dim=self.dim)
298
+ if register:
299
+ _register_appended(full, self)
300
+ return full
301
+
302
+
303
+ _APPENDED: dict[int, tuple[Any, int, _Appended]] = {}
304
+
305
+
306
+ def _register_appended(full: Any, compact: _Appended) -> None:
307
+ import weakref
308
+
309
+ key = id(full)
310
+
311
+ def forget(_: Any, key: int = key) -> None:
312
+ entry = _APPENDED.get(key)
313
+ if entry is not None and entry[0]() is None:
314
+ _APPENDED.pop(key, None)
315
+
316
+ _APPENDED[key] = (weakref.ref(full, forget), full._version, compact)
317
+
318
+
319
+ def _appended_of(value: Any) -> _Appended | None:
320
+ """The block form registered for ``value`` (None when none is, or when ``value`` was
321
+ written in place since it was registered)."""
322
+ entry = _APPENDED.get(id(value))
323
+ if entry is None or entry[0]() is not value or value._version != entry[1]:
324
+ return None
325
+ return entry[2]
326
+
327
+
328
+ def _standard_strides(shape: tuple[int, ...]) -> tuple[int, ...]:
329
+ strides, step = [], 1
330
+ for size in reversed(shape):
331
+ strides.append(step)
332
+ step *= max(int(size), 1)
333
+ return tuple(reversed(strides))
334
+
335
+
336
+ def seal_append(full: Any, base: Any, dim: int) -> bool:
337
+ """Declare that ``full`` is ``base`` with rows appended along ``dim`` (bitwise: the caller
338
+ checked it), so a cut that holds ``full`` holds ``base``'s blocks plus the appended rows only.
339
+ ``full`` must have the standard contiguous layout (``torch.cat`` gives it) and keep a version
340
+ counter; otherwise nothing is declared. Returns whether it was."""
341
+ dim = dim % full.dim()
342
+ if (
343
+ not _versioned(full)
344
+ or full.requires_grad
345
+ or tuple(full.stride()) != _standard_strides(tuple(full.shape))
346
+ or base.dim() != full.dim()
347
+ or base.shape[dim] >= full.shape[dim]
348
+ ):
349
+ return False
350
+ count = base.shape[dim]
351
+ rest = full.narrow(dim, count, full.shape[dim] - count).clone(
352
+ memory_format=__import__("torch").contiguous_format
353
+ )
354
+ known = _appended_of(base) if _versioned(base) else None
355
+ if known is not None and known.dim == dim:
356
+ index = len(known.chunks)
357
+ guard = known.guard + (((index, rest, rest._version),) if _versioned(rest) else ())
358
+ compact = _Appended((*known.chunks, rest), dim, guard)
359
+ elif count == 0:
360
+ compact = _Appended((rest,), dim)
361
+ else:
362
+ compact = _Appended((_share(base), rest), dim)
363
+ _register_appended(full, compact)
364
+ return True
365
+
366
+
367
+ @dataclass(frozen=True, eq=False)
368
+ class Blocks:
369
+ """A sealed state tensor as the blocks a cut holds it in (``cut_blocks``), or as the blocks a
370
+ caller rebuilds it from (``StateCut.from_blocks``): ``torch.cat(chunks, dim)`` is the tensor
371
+ bit for bit, with the standard contiguous layout; ``dim`` None is one chunk, the tensor
372
+ itself, of layout ``stride``. Blocks of a grown cache layer are the prefix rows then the
373
+ rows each transition appended, so consecutive cuts share every block but the last."""
374
+
375
+ chunks: tuple[Any, ...]
376
+ dim: int | None
377
+ shape: tuple[int, ...]
378
+ stride: tuple[int, ...]
379
+ dtype: Any
380
+
381
+ def tensor(self) -> Any:
382
+ """The tensor (built once per ``Blocks`` object and kept, so cuts sharing this object
383
+ share it); a block form of more than one chunk is declared, so a cut holding the
384
+ tensor keeps the chunks."""
385
+ cached = self.__dict__.get("_full")
386
+ if cached is not None:
387
+ return cached
388
+ import torch
389
+
390
+ if self.dim is None or len(self.chunks) == 1:
391
+ full = self.chunks[0]
392
+ if tuple(full.shape) != tuple(self.shape):
393
+ raise ValueError("Blocks chunk differs from its shape")
394
+ if tuple(full.stride()) != tuple(self.stride):
395
+ strided = torch.empty_strided(tuple(self.shape), tuple(self.stride),
396
+ dtype=full.dtype, device=full.device)
397
+ strided.copy_(full)
398
+ full = strided
399
+ elif not self.chunks:
400
+ full = torch.empty(tuple(self.shape), dtype=self.dtype)
401
+ else:
402
+ with torch.inference_mode(False):
403
+ full = torch.cat(self.chunks, dim=self.dim)
404
+ if (tuple(full.shape) != tuple(self.shape)
405
+ or tuple(full.stride()) != _standard_strides(tuple(self.shape))
406
+ or tuple(self.stride) != _standard_strides(tuple(self.shape))):
407
+ raise ValueError("Blocks chunks differ from their shape or layout")
408
+ _register_appended(full, _Appended(tuple(self.chunks), self.dim))
409
+ if full.dtype != self.dtype:
410
+ raise ValueError("Blocks chunks differ from their dtype")
411
+ object.__setattr__(self, "_full", full)
412
+ return full
413
+
414
+
415
+ def cut_blocks(cut: StateCut) -> dict[str, Any]:
416
+ """The payload of ``cut`` with every tensor as ``Blocks`` (the blocks the cut holds: no
417
+ tensor is copied or concatenated). Refuses (``InPlaceWrite``) a cut a tensor of which was
418
+ written in place since it was sealed. The chunks are the cut's own immutable tensors: read
419
+ them, never write them."""
420
+ cut._check_sealed()
421
+
422
+ def walk(value: Any) -> Any:
423
+ if isinstance(value, _Appended):
424
+ chunks = tuple(value.chunks)
425
+ shape = list(chunks[0].shape)
426
+ shape[value.dim] = sum(int(c.shape[value.dim]) for c in chunks)
427
+ return Blocks(chunks, value.dim, tuple(shape), _standard_strides(tuple(shape)),
428
+ chunks[0].dtype)
429
+ if tensor(value):
430
+ known = _appended_of(value) if _versioned(value) else None
431
+ if known is not None:
432
+ return walk(known)
433
+ return Blocks((value,), None, tuple(value.shape), tuple(value.stride()),
434
+ value.dtype)
435
+ if isinstance(value, Mapping):
436
+ return {key: walk(item) for key, item in value.items()}
437
+ if isinstance(value, tuple):
438
+ return tuple(walk(item) for item in value)
439
+ if isinstance(value, list):
440
+ return [walk(item) for item in value]
441
+ return copy.deepcopy(value)
442
+
443
+ return walk(dict(cut._payload))
444
+
445
+
446
+ def _compact(value: Any) -> Any:
447
+ """``_share`` for sealing: a tensor declared with ``seal_append`` is held as its blocks."""
448
+ if tensor(value):
449
+ if _versioned(value):
450
+ known = _appended_of(value)
451
+ if known is not None:
452
+ return known
453
+ return _share(value)
454
+ if isinstance(value, Mapping):
455
+ return {key: _compact(item) for key, item in value.items()}
456
+ if isinstance(value, tuple):
457
+ return tuple(_compact(item) for item in value)
458
+ if isinstance(value, list):
459
+ return [_compact(item) for item in value]
460
+ return copy.deepcopy(value)
461
+
462
+
463
+ def _expand(value: Any, *, register: bool) -> Any:
464
+ """``value`` with every block form materialized (tensors and other leaves as they are;
465
+ containers copied)."""
466
+ if isinstance(value, _Appended):
467
+ return value.materialize(register=register)
468
+ if tensor(value):
469
+ return value
470
+ if isinstance(value, Mapping):
471
+ return {key: _expand(item, register=register) for key, item in value.items()}
472
+ if isinstance(value, tuple):
473
+ return tuple(_expand(item, register=register) for item in value)
474
+ if isinstance(value, list):
475
+ return [_expand(item, register=register) for item in value]
476
+ return copy.deepcopy(value)
477
+
478
+
479
+ def _tensor_leaves(value: Any, path: str = "") -> list[tuple[str, Any]]:
480
+ """``(path, tensor)`` for every tensor in a payload (mappings, lists and tuples walked, and
481
+ the blocks of a block form)."""
482
+ if tensor(value):
483
+ return [(path, value)]
484
+ out: list[tuple[str, Any]] = []
485
+ if isinstance(value, _Appended):
486
+ for index, item in enumerate(value.chunks):
487
+ out += _tensor_leaves(item, f"{path}<{index}>")
488
+ elif isinstance(value, Mapping):
489
+ for key, item in value.items():
490
+ out += _tensor_leaves(item, f"{path}.{key}" if path else str(key))
491
+ elif isinstance(value, (list, tuple)):
492
+ for index, item in enumerate(value):
493
+ out += _tensor_leaves(item, f"{path}[{index}]")
494
+ return out
495
+
496
+
497
+ def held_bytes(*objects: Any) -> int:
498
+ """Bytes of the distinct tensor storages that ``objects`` reference (StateCuts, Sessions,
499
+ states, mappings and sequences of them); a storage two of them share counts once.
500
+
501
+ Each tensor object and each block form is visited once however many cuts share it
502
+ (consecutive cuts share every K/V layer a transition did not replace)."""
503
+ storages: dict[Any, int] = {}
504
+ seen: set[int] = set()
505
+
506
+ def walk(value: Any) -> None:
507
+ if isinstance(value, StateCut):
508
+ walk(value._payload)
509
+ elif isinstance(value, Session):
510
+ walk(value._state)
511
+ elif tensor(value):
512
+ if id(value) in seen:
513
+ return
514
+ seen.add(id(value))
515
+ storage = value.untyped_storage()
516
+ storages[(str(value.device), storage.data_ptr())] = storage.nbytes()
517
+ elif isinstance(value, _Appended):
518
+ if id(value) in seen:
519
+ return
520
+ seen.add(id(value))
521
+ for chunk in value.chunks:
522
+ walk(chunk)
523
+ elif isinstance(value, Mapping):
524
+ for item in value.values():
525
+ walk(item)
526
+ elif isinstance(value, (list, tuple)):
527
+ for item in value:
528
+ walk(item)
529
+
530
+ for item in objects:
531
+ walk(item)
532
+ return sum(storages.values())
533
+
534
+
535
+ def _versioned(value: Any) -> bool:
536
+ """Whether a tensor tracks in-place writes (an inference tensor has no version counter)."""
537
+ is_inference = getattr(value, "is_inference", None)
538
+ return not (callable(is_inference) and is_inference())
539
+
540
+
541
+ def _share(value: Any) -> Any:
542
+ """``value`` with its containers copied and its tensors shared, for a sealed (immutable)
543
+ state: a tensor that tracks in-place writes is kept by reference, an inference tensor (no
544
+ version counter, so a write to it could not be detected) is copied into a normal one."""
545
+ if tensor(value):
546
+ if value.requires_grad:
547
+ return clone(value)
548
+ if _versioned(value):
549
+ return value
550
+ import torch
551
+
552
+ with torch.inference_mode(False):
553
+ return value.clone(memory_format=torch.preserve_format)
554
+ if isinstance(value, Mapping):
555
+ return {key: _share(item) for key, item in value.items()}
556
+ if isinstance(value, tuple):
557
+ return tuple(_share(item) for item in value)
558
+ if isinstance(value, list):
559
+ return [_share(item) for item in value]
560
+ return copy.deepcopy(value)
561
+
562
+
563
+ def own_hook(hook: Any) -> Any:
564
+ """Mark a forward hook as one of this library's own controllers (mdb's port and trace
565
+ hooks). They never write the native cache's K/V tensors, so they do not force
566
+ ``DecoderAdapter._cache`` onto its copying path; any unmarked hook does."""
567
+ hook._saturn_own_hook = True
568
+ return hook
569
+
570
+
571
+ class InPlaceWrite(ValueError):
572
+ """A tensor that a sealed cut or a transition's input state shares was written in place."""
573
+
574
+
575
+ def _versions(value: Any) -> tuple[tuple[str, Any, int | None], ...]:
576
+ """``(path, tensor, version)`` of every tensor of ``value`` that tracks in-place writes; a
577
+ block form is one ``(path, block form, None)`` entry, checked against the guard it recorded
578
+ for its chunks when they joined (``_Appended.guard``), so its chunks are not walked here."""
579
+ out: list[tuple[str, Any, int | None]] = []
580
+
581
+ def walk(item: Any, path: str) -> None:
582
+ if tensor(item):
583
+ if _versioned(item):
584
+ out.append((path, item, item._version))
585
+ elif isinstance(item, _Appended):
586
+ out.append((path, item, None))
587
+ elif isinstance(item, Mapping):
588
+ for key, child in item.items():
589
+ walk(child, f"{path}.{key}" if path else str(key))
590
+ elif isinstance(item, (list, tuple)):
591
+ for index, child in enumerate(item):
592
+ walk(child, f"{path}[{index}]")
593
+
594
+ walk(value, "")
595
+ return tuple(out)
596
+
597
+
598
+ def _check_versions(recorded: tuple[tuple[str, Any, int | None], ...], what: str) -> None:
599
+ written = []
600
+ for path, item, version in recorded:
601
+ if version is None:
602
+ written += [
603
+ f"{path}<{index}>"
604
+ for index, chunk, sealed in item.guard
605
+ if chunk._version != sealed
606
+ ]
607
+ elif item._version != version:
608
+ written.append(path)
609
+ if written:
610
+ raise InPlaceWrite(f"{what} was written in place: {', '.join(written)}")
611
+
612
+
613
+ @dataclass(frozen=True)
614
+ class StateCut:
615
+ """A sealed snapshot of an adapter's declared mutable execution closure.
616
+
617
+ The payload is copied once at construction, unless the caller passes ``_shared=True``
618
+ (Session only, for an adapter whose ``shares_state`` contract holds): then the cut keeps the
619
+ state's tensors by reference (its containers are copied), so consecutive cuts of one session
620
+ share every tensor a transition did not replace. A sealed tensor is immutable: the cut
621
+ records each tensor's version counter, and every read of the payload (``payload``,
622
+ ``slot``, ``verify``, a restore) refuses (``InPlaceWrite``, naming the slot) when one was
623
+ written in place since. ``_described`` (private, Session only) is the ``describe`` of that
624
+ payload when the caller already holds it for the very tensors it hands in, so the
625
+ fingerprint is sealed without hashing them again; with it, ``_sealed`` is the fingerprint
626
+ Session already digested from exactly these fields (``Session._seal``), so the manifest is
627
+ not described twice. ``verify`` always re-hashes.
628
+ """
629
+
630
+ model_identity: str
631
+ execution: Mapping[str, Any]
632
+ boundary: str
633
+ parent: str | None
634
+ _payload: Mapping[str, Any] = field(repr=False)
635
+ execution_point: Mapping[str, Any] | None = None
636
+ surface: Mapping[str, Any] | None = None
637
+ fingerprint: str = field(init=False)
638
+ _described: InitVar[Any] = None
639
+ _sealed: InitVar[str | None] = None
640
+ _shared: InitVar[bool] = False
641
+
642
+ def __post_init__(
643
+ self, _described: Any = None, _sealed: str | None = None, _shared: bool = False
644
+ ) -> None:
645
+ object.__setattr__(self, "execution", MappingProxyType(clone(dict(self.execution))))
646
+ payload = dict(self._payload)
647
+ object.__setattr__(self, "_payload", _compact(payload) if _shared else clone(payload))
648
+ object.__setattr__(self, "_guard", _versions(self._payload))
649
+ if self.execution_point is not None:
650
+ object.__setattr__(
651
+ self,
652
+ "execution_point",
653
+ MappingProxyType(clone(dict(self.execution_point))),
654
+ )
655
+ if self.surface is not None:
656
+ object.__setattr__(self, "surface", MappingProxyType(clone(dict(self.surface))))
657
+ if _described is not None and _sealed is not None:
658
+ object.__setattr__(self, "fingerprint", _sealed) # Session sealed these very fields
659
+ return
660
+ payload = describe(self._payload) if _described is None else _described
661
+ object.__setattr__(self, "fingerprint", digest(self._manifest(payload)))
662
+
663
+ @property
664
+ def payload(self) -> dict[str, Any]:
665
+ self._check_sealed()
666
+ return self._private(self._payload)
667
+
668
+ def slot(self, name: str) -> Any:
669
+ """One payload slot as a private copy (``payload[name]`` without copying the others)."""
670
+ self._check_sealed()
671
+ return self._private(self._payload[name])
672
+
673
+ @staticmethod
674
+ def _private(value: Any) -> Any:
675
+ """A private copy: block forms are concatenated (already a fresh tensor), the rest
676
+ cloned."""
677
+ if isinstance(value, _Appended):
678
+ return value.materialize(register=False)
679
+ if isinstance(value, Mapping):
680
+ return {key: StateCut._private(item) for key, item in value.items()}
681
+ if isinstance(value, tuple):
682
+ return tuple(StateCut._private(item) for item in value)
683
+ if isinstance(value, list):
684
+ return [StateCut._private(item) for item in value]
685
+ return clone(value)
686
+
687
+ def _check_sealed(self) -> None:
688
+ """Refuse when a payload tensor was written in place since the cut was sealed."""
689
+ _check_versions(self._guard, "a sealed StateCut tensor")
690
+
691
+ def _shared_payload(self) -> dict[str, Any]:
692
+ """The payload with its containers copied and its (immutable) tensors shared, block
693
+ forms materialized (and registered, so cuts of the hydrated state share the blocks): the
694
+ state a Session hydrates from this cut when its adapter's ``shares_state`` holds."""
695
+ self._check_sealed()
696
+ return _share(_expand(self._payload, register=True))
697
+
698
+ def _hydrate(self, shared: bool) -> tuple[Any, dict[str, Any]]:
699
+ """``(describe of the payload, state)`` for a Session taking this cut: the payload is
700
+ verified against the fingerprint (as ``verify``) and handed over as ``_shared_payload``
701
+ (``shared``) or as a private copy, materializing block forms once."""
702
+ self._check_sealed()
703
+ if shared:
704
+ state = _share(_expand(self._payload, register=True))
705
+ else:
706
+ state = self._private(self._payload)
707
+ described = describe(state)
708
+ if digest(self._manifest(described)) != self.fingerprint:
709
+ raise ValueError("StateCut payload or metadata changed")
710
+ return described, state
711
+
712
+ def nbytes(self) -> int:
713
+ """Bytes of the distinct tensor storages this cut references (shared ones included)."""
714
+ return held_bytes(self)
715
+
716
+ def _manifest(self, payload: Any) -> dict[str, Any]:
717
+ return _statecut_manifest(
718
+ self.model_identity,
719
+ self.execution,
720
+ self.boundary,
721
+ self.parent,
722
+ payload,
723
+ self.execution_point,
724
+ self.surface,
725
+ )
726
+
727
+ def manifest(self) -> dict[str, Any]:
728
+ self._check_sealed()
729
+ return self._manifest(describe(_expand(self._payload, register=False)))
730
+
731
+ def _verified(self) -> Any:
732
+ """Hash the payload once, refuse a cut whose content or metadata no longer matches its
733
+ fingerprint, and return the payload's ``describe``."""
734
+ self._check_sealed()
735
+ described = describe(_expand(self._payload, register=False))
736
+ if digest(self._manifest(described)) != self.fingerprint:
737
+ raise ValueError("StateCut payload or metadata changed")
738
+ return described
739
+
740
+ def verify(self) -> None:
741
+ self._verified()
742
+
743
+ @classmethod
744
+ def from_blocks(
745
+ cls,
746
+ model_identity: str,
747
+ execution: Mapping[str, Any],
748
+ boundary: str,
749
+ parent: str | None,
750
+ payload: Mapping[str, Any],
751
+ execution_point: Mapping[str, Any] | None = None,
752
+ surface: Mapping[str, Any] | None = None,
753
+ ) -> StateCut:
754
+ """A cut of ``payload`` whose tensors may be ``Blocks`` (``cut_blocks``): it keeps their
755
+ chunks by reference (a tensor of several chunks as that block form) instead of copying,
756
+ so cuts rebuilt from shared blocks share memory as the cuts of one session do. The
757
+ fingerprint is computed from the content (every tensor hashed once per object), so a
758
+ cut rebuilt from the blocks of another is that cut exactly when its content, metadata
759
+ and parent are. The caller hands the chunks over: they must not be written afterwards
760
+ (a later read of the cut refuses one that was, ``InPlaceWrite``)."""
761
+
762
+ def full(value: Any) -> Any:
763
+ if isinstance(value, Blocks):
764
+ return value.tensor()
765
+ if isinstance(value, Mapping):
766
+ return {key: full(item) for key, item in value.items()}
767
+ if isinstance(value, tuple):
768
+ return tuple(full(item) for item in value)
769
+ if isinstance(value, list):
770
+ return [full(item) for item in value]
771
+ return value
772
+
773
+ state = full(dict(payload))
774
+ return cls(model_identity, execution, boundary, parent, state,
775
+ execution_point=execution_point, surface=surface,
776
+ _described=describe_remembered(state), _shared=True)
777
+
778
+
779
+ @dataclass(frozen=True)
780
+ class Act:
781
+ """A registered operation gets exactly its declared reads and writes."""
782
+
783
+ name: str
784
+ reads: tuple[str, ...]
785
+ writes: tuple[str, ...]
786
+ implementation: Callable[[Mapping[str, Any]], Mapping[str, Any]] = field(repr=False)
787
+ invalidates: tuple[str, ...] = ()
788
+ numerical_contract: str = "behavioral-intervention"
789
+ parameters: Mapping[str, Any] = field(default_factory=dict)
790
+ operation_id: str | None = None
791
+ operation_version: str | None = None
792
+ preconditions: Mapping[str, str] = field(default_factory=dict)
793
+ preserve: tuple[str, ...] = ()
794
+ implementation_digest: str = field(init=False)
795
+ implementation_state_digest: str = field(init=False)
796
+ operation_pure: bool = field(init=False)
797
+
798
+ def __post_init__(self) -> None:
799
+ if not self.name or not self.writes or not callable(self.implementation):
800
+ raise ValueError("Act requires a name, writes, and callable implementation")
801
+ for group in (self.reads, self.writes, self.invalidates):
802
+ if len(set(group)) != len(group) or any(not isinstance(x, str) or not x for x in group):
803
+ raise ValueError("Act addresses must be unique non-empty strings")
804
+ object.__setattr__(self, "parameters", MappingProxyType(clone(dict(self.parameters))))
805
+ if (self.operation_id is None) != (self.operation_version is None):
806
+ raise ValueError("operation id and version must be supplied together")
807
+ implementation_digest = _implementation_digest(
808
+ self.implementation, strict=self.operation_id is not None
809
+ )
810
+ implementation_state_digest = _implementation_state_digest(
811
+ self.implementation, strict=self.operation_id is not None
812
+ )
813
+ pure = False
814
+ if self.operation_id is not None and self.operation_version is not None:
815
+ registered = _OPERATION_REGISTRY.get((self.operation_id, self.operation_version))
816
+ if registered is None:
817
+ raise ValueError("operation id/version is not registered in this process")
818
+ if registered[0] != implementation_digest:
819
+ raise ValueError("registered operation implementation digest mismatch")
820
+ pure = registered[2]
821
+ for address, expected in self.preconditions.items():
822
+ if not isinstance(address, str) or not address or not isinstance(expected, str):
823
+ raise ValueError("Act preconditions require address-to-digest strings")
824
+ if len(set(self.preserve)) != len(self.preserve) or any(
825
+ not isinstance(address, str) or not address for address in self.preserve
826
+ ):
827
+ raise ValueError("Act preserve addresses must be unique non-empty strings")
828
+ object.__setattr__(self, "preconditions", MappingProxyType(clone(dict(self.preconditions))))
829
+ object.__setattr__(self, "implementation_digest", implementation_digest)
830
+ object.__setattr__(self, "implementation_state_digest", implementation_state_digest)
831
+ object.__setattr__(self, "operation_pure", pure)
832
+
833
+ def manifest(self) -> dict[str, Any]:
834
+ return {
835
+ "name": self.name,
836
+ "reads": list(self.reads),
837
+ "writes": list(self.writes),
838
+ "invalidates": list(self.invalidates),
839
+ "numerical_contract": self.numerical_contract,
840
+ "parameters": describe(dict(self.parameters)),
841
+ "operation": {
842
+ "id": self.operation_id,
843
+ "version": self.operation_version,
844
+ "implementation_digest": self.implementation_digest,
845
+ "implementation_state_digest": self.implementation_state_digest,
846
+ "pure": self.operation_pure,
847
+ "authority": "registered" if self.operation_id is not None else "exploratory",
848
+ },
849
+ "preconditions": dict(self.preconditions),
850
+ "preserve": list(self.preserve),
851
+ }
852
+
853
+ @classmethod
854
+ def register_operation(
855
+ cls,
856
+ operation_id: str,
857
+ version: str,
858
+ implementation: Callable[[Mapping[str, Any]], Mapping[str, Any]],
859
+ *,
860
+ pure: bool,
861
+ ) -> str:
862
+ return _register_operation(operation_id, version, implementation, pure=pure)
863
+
864
+ register = register_operation
865
+
866
+ @classmethod
867
+ def registered(
868
+ cls,
869
+ name: str,
870
+ reads: tuple[str, ...],
871
+ writes: tuple[str, ...],
872
+ *,
873
+ operation_id: str,
874
+ operation_version: str,
875
+ implementation: Callable[[Mapping[str, Any]], Mapping[str, Any]] | None = None,
876
+ invalidates: tuple[str, ...] = (),
877
+ numerical_contract: str = "behavioral-intervention",
878
+ parameters: Mapping[str, Any] | None = None,
879
+ preconditions: Mapping[str, str] | None = None,
880
+ preserve: tuple[str, ...] = (),
881
+ ) -> Act:
882
+ registered = _OPERATION_REGISTRY.get((operation_id, operation_version))
883
+ if registered is None:
884
+ raise ValueError("operation id/version is not registered in this process")
885
+ bound = registered[1] if implementation is None else implementation
886
+ return cls(
887
+ name,
888
+ reads,
889
+ writes,
890
+ bound,
891
+ invalidates,
892
+ numerical_contract,
893
+ {} if parameters is None else parameters,
894
+ operation_id,
895
+ operation_version,
896
+ {} if preconditions is None else preconditions,
897
+ preserve,
898
+ )
899
+
900
+ def require_reproducible(self) -> None:
901
+ self.verify_implementation()
902
+ if self.operation_id is None or self.operation_version is None or not self.operation_pure:
903
+ raise ValueError("measured programs require a registered pure operation")
904
+ registered = _OPERATION_REGISTRY.get((self.operation_id, self.operation_version))
905
+ if registered is None or registered[0] != self.implementation_digest:
906
+ raise ValueError("measured operation binding is unavailable or changed")
907
+
908
+ def verify_implementation(self) -> None:
909
+ observed_code = _implementation_digest(
910
+ self.implementation, strict=self.operation_id is not None
911
+ )
912
+ observed_state = _implementation_state_digest(
913
+ self.implementation, strict=self.operation_id is not None
914
+ )
915
+ if observed_code != self.implementation_digest:
916
+ raise ValueError("Act implementation code or closure changed")
917
+ if observed_state != self.implementation_state_digest:
918
+ raise ValueError("Act implementation state changed")
919
+
920
+ @classmethod
921
+ def replace(cls, address: str, value: Any, *, name: str = "replace") -> Act:
922
+ operation = _ReplaceOperation(address, value)
923
+ _register_operation("saturn.builtin.replace", "1", operation, pure=True)
924
+ return cls(
925
+ name,
926
+ (address,),
927
+ (address,),
928
+ operation,
929
+ parameters={"value": clone(value)},
930
+ operation_id="saturn.builtin.replace",
931
+ operation_version="1",
932
+ )
933
+
934
+ @classmethod
935
+ def add(cls, address: str, value: Any, *, dose: float = 1, name: str = "add") -> Act:
936
+ operation = _AddOperation(address, value, dose)
937
+ _register_operation("saturn.builtin.add", "1", operation, pure=True)
938
+ return cls(
939
+ name,
940
+ (address,),
941
+ (address,),
942
+ operation,
943
+ parameters={"value": clone(value), "dose": dose},
944
+ operation_id="saturn.builtin.add",
945
+ operation_version="1",
946
+ )
947
+
948
+ @classmethod
949
+ def zero(cls, address: str) -> Act:
950
+ operation = _ZeroOperation(address)
951
+ _register_operation("saturn.builtin.zero", "1", operation, pure=True)
952
+ return cls(
953
+ "zero",
954
+ (address,),
955
+ (address,),
956
+ operation,
957
+ operation_id="saturn.builtin.zero",
958
+ operation_version="1",
959
+ )
960
+
961
+ @classmethod
962
+ def patch(
963
+ cls,
964
+ address: str,
965
+ value: Any,
966
+ mask: Any,
967
+ *,
968
+ mode: str = "replace",
969
+ dose: float = 1,
970
+ expected_digest: str | None = None,
971
+ ) -> Act:
972
+ if mode not in ("replace", "add"):
973
+ raise ValueError("patch mode must be 'replace' or 'add'")
974
+ if isinstance(dose, bool) or not isinstance(dose, (int, float)):
975
+ raise ValueError("patch dose must be numeric")
976
+ operation = _PatchOperation(address, value, mask, mode, dose)
977
+ _register_operation("saturn.builtin.patch", "1", operation, pure=True)
978
+ return cls(
979
+ "patch",
980
+ (address,),
981
+ (address,),
982
+ operation,
983
+ parameters={
984
+ "address": address,
985
+ "value": clone(value),
986
+ "mask": clone(mask),
987
+ "mode": mode,
988
+ "dose": dose,
989
+ },
990
+ operation_id="saturn.builtin.patch",
991
+ operation_version="1",
992
+ preconditions={} if expected_digest is None else {address: expected_digest},
993
+ )
994
+
995
+
996
+ @dataclass(frozen=True)
997
+ class Receipt:
998
+ """Content-sealed metadata; outputs are summaries, never tensor payloads."""
999
+
1000
+ _body: bytes
1001
+
1002
+ @classmethod
1003
+ def make(cls, **body: Any) -> Receipt:
1004
+ from .values import canonical
1005
+
1006
+ return cls(canonical({"schema": "saturn-pub-receipt-v1", **body}))
1007
+
1008
+ @property
1009
+ def fingerprint(self) -> str:
1010
+ import hashlib
1011
+
1012
+ return hashlib.sha256(self._body).hexdigest()
1013
+
1014
+ def to_dict(self) -> dict[str, Any]:
1015
+ import json
1016
+
1017
+ return {**json.loads(self._body), "fingerprint": self.fingerprint}
1018
+
1019
+
1020
+ class PortStop(Exception):
1021
+ """Raised by a port controller to end a read-only probe at a declared port."""
1022
+
1023
+
1024
+ class Adapter(ABC):
1025
+ """Native executor contract. Execution state belongs to a Session, not the model.
1026
+
1027
+ Adapters that expose ports accept ``advance(state, *, ports=controller)`` and install the
1028
+ controller around their native call; ``ports(state)`` names the hook sites the next
1029
+ transition offers. A controller may define a per-transition lifecycle: ``begin()`` is
1030
+ called before each transition's ``advance`` (in ``probe`` and ``continue_``);
1031
+ ``probe_check()`` after a probe's ``advance``; ``manifest()`` once after the same
1032
+ ``advance`` in ``continue_``, never earlier. A non-empty ``manifest()`` is recorded as that
1033
+ transition's ``port_edits`` and so must list only edits applied during that call; it may
1034
+ raise to refuse committing a transition whose staged edits did not take effect.
1035
+
1036
+ A controller may also define ``check_ahead(ahead)``, called by ``continue_`` before anything
1037
+ runs with ``adapter.ports_ahead(state, steps)``; it raises to refuse a call in which none of
1038
+ the transitions would reach what the controller addresses. ``begin_call()`` / ``end_call()``
1039
+ bracket one ``continue_`` call (``end_call`` raises if a controller that carries edits was
1040
+ never installed by the call).
1041
+ """
1042
+
1043
+ model_identity: str
1044
+ execution: Mapping[str, Any]
1045
+ # The immutable-state contract. True: ``advance`` (hooks and port controllers included)
1046
+ # never writes a tensor of its input state in place and may return the input's unchanged
1047
+ # tensors in its result. A Session then hands ``advance`` its state without copying it and
1048
+ # seals cuts that share tensors by reference (consecutive cuts share what a transition did
1049
+ # not replace); every transition's input tensors are checked by version counter afterwards
1050
+ # and a write is refused (``InPlaceWrite``). False (the default): every state handed to
1051
+ # ``advance`` is a private copy and every cut owns a copy of its payload.
1052
+ shares_state: bool = False
1053
+
1054
+ @abstractmethod
1055
+ def boundary(self, state: Mapping[str, Any]) -> str: ...
1056
+
1057
+ @abstractmethod
1058
+ def validate(self, state: Mapping[str, Any]) -> None: ...
1059
+
1060
+ def validate_state(self, state: Mapping[str, Any]) -> None:
1061
+ """``validate`` for a caller that ran ``validate_execution`` earlier in the same call; an
1062
+ adapter whose ``validate`` repeats a check of ``validate_execution`` may skip it here."""
1063
+ self.validate(state)
1064
+
1065
+ @abstractmethod
1066
+ def advance(self, state: Mapping[str, Any]) -> Mapping[str, Any]: ...
1067
+
1068
+ @abstractmethod
1069
+ def addresses(self, state: Mapping[str, Any]) -> tuple[str, ...]: ...
1070
+
1071
+ def ports(self, state: Mapping[str, Any]) -> tuple[str, ...]:
1072
+ """Hook sites of the next transition; empty means it accepts no port controller."""
1073
+ return ()
1074
+
1075
+ def ports_ahead(self, state: Mapping[str, Any], steps: int) -> tuple[Any, ...] | None:
1076
+ """For each of the next ``steps`` transitions, the site index a port controller can
1077
+ address there (``None`` for a transition that offers no ports); ``None`` overall when
1078
+ the adapter cannot say without running."""
1079
+ return None
1080
+
1081
+ def point(self, state: Mapping[str, Any]) -> ExecutionPoint:
1082
+ return ExecutionPoint(
1083
+ str(self.execution.get("family", type(self).__name__)),
1084
+ 0,
1085
+ self.boundary(state),
1086
+ next_operation="advance",
1087
+ )
1088
+
1089
+ def surface(self, state: Mapping[str, Any]) -> SurfaceManifest:
1090
+ writable = set(self.addresses(state))
1091
+ family = str(self.execution.get("family", type(self).__name__))
1092
+ return SurfaceManifest(
1093
+ tuple(SlotSpec(name, writable=name in writable) for name in sorted(state)),
1094
+ f"{family}-declared-state-v1",
1095
+ "native-suffix",
1096
+ )
1097
+
1098
+ def validate_execution(self) -> None:
1099
+ """Adapters may reject drift of their frozen native executor."""
1100
+
1101
+ def capture_external(self) -> Any:
1102
+ """Optional registered side-effect closure; default adapters must be pure."""
1103
+ return None
1104
+
1105
+ def restore_external(self, snapshot: Any) -> None:
1106
+ if snapshot is not None:
1107
+ raise ValueError("adapter did not implement external closure restoration")
1108
+
1109
+ def numerical_contract(self) -> NumericalContract:
1110
+ return NumericalContract(program=str(self.execution.get("adapter", "custom-adapter")))
1111
+
1112
+ def transition(self, state: Mapping[str, Any]) -> TransitionSpec:
1113
+ """Describe the next safe transition; unspecified footprints stay unknown."""
1114
+ return TransitionSpec(self.point(state).next_operation or "advance")
1115
+
1116
+ def read(self, state: Mapping[str, Any], address: str) -> Any:
1117
+ if address not in self.addresses(state):
1118
+ raise ValueError(f"unsupported address at {self.boundary(state)}: {address}")
1119
+ return clone(state[address])
1120
+
1121
+ def read_part(self, state: Mapping[str, Any], address: str, index: Any) -> Any:
1122
+ """``read(state, address)[index]``; an adapter may override it to copy only that part."""
1123
+ return self.read(state, address)[index]
1124
+
1125
+ def write(
1126
+ self, state: Mapping[str, Any], writes: Mapping[str, Any], invalidates: tuple[str, ...]
1127
+ ) -> Mapping[str, Any]:
1128
+ result = clone(state)
1129
+ for address, value in writes.items():
1130
+ if address not in self.addresses(state):
1131
+ raise ValueError(f"unsupported write address: {address}")
1132
+ old = state[address]
1133
+ if hasattr(old, "shape") and (old.shape != value.shape or old.dtype != value.dtype):
1134
+ raise ValueError(f"write shape/dtype mismatch: {address}")
1135
+ result[address] = clone(value)
1136
+ for address in invalidates:
1137
+ if address in writes:
1138
+ raise ValueError("cannot invalidate a written address")
1139
+ result.pop(address, None)
1140
+ self.validate(result)
1141
+ return result
1142
+
1143
+
1144
+ def _flatten_execution(execution: Mapping[str, Any], prefix: str = "") -> dict[str, Any]:
1145
+ out: dict[str, Any] = {}
1146
+ for key, value in execution.items():
1147
+ name = f"{prefix}{key}"
1148
+ if isinstance(value, Mapping):
1149
+ out.update(_flatten_execution(value, prefix=f"{name}."))
1150
+ else:
1151
+ out[name] = value
1152
+ return out
1153
+
1154
+
1155
+ def _refuse_incompatible(cut: StateCut, adapter: Adapter) -> None:
1156
+ """Refuse a cut of another model identity or execution contract, naming every differing
1157
+ execution field (``numeric_scope.bf16_reduced_precision_reduction``, say)."""
1158
+ if cut.model_identity != adapter.model_identity:
1159
+ raise ValueError("incompatible model identity or execution contract (model_identity)")
1160
+ recorded, current = dict(cut.execution), dict(adapter.execution)
1161
+ if recorded == current:
1162
+ return
1163
+ left, right = _flatten_execution(recorded), _flatten_execution(current)
1164
+ differing = [
1165
+ f"{name}: cut {left.get(name, 'missing')!r}, adapter {right.get(name, 'missing')!r}"
1166
+ for name in sorted(set(left) | set(right))
1167
+ if left.get(name, "missing") != right.get(name, "missing")
1168
+ ]
1169
+ raise ValueError(
1170
+ "incompatible model identity or execution contract (" + "; ".join(differing) + ")"
1171
+ )
1172
+
1173
+
1174
+ def _validate_state(adapter: Any, state: Mapping[str, Any]) -> None:
1175
+ """``adapter.validate_state(state)``, or ``validate`` for an adapter without it."""
1176
+ getattr(adapter, "validate_state", adapter.validate)(state)
1177
+
1178
+
1179
+ def _adopt(value: Any) -> Any:
1180
+ """``clone(value)`` for a value its owner hands over and no longer references: the same
1181
+ content and layout, except that a contiguous tensor (of which ``clone`` would make an
1182
+ identical copy, strides included) is kept instead of copied."""
1183
+ if tensor(value):
1184
+ return value if value.is_contiguous() and not value.requires_grad else clone(value)
1185
+ if isinstance(value, Mapping):
1186
+ return {key: _adopt(item) for key, item in value.items()}
1187
+ if isinstance(value, tuple):
1188
+ return tuple(_adopt(item) for item in value)
1189
+ if isinstance(value, list):
1190
+ return [_adopt(item) for item in value]
1191
+ return copy.deepcopy(value)
1192
+
1193
+
1194
+ class _Seal(NamedTuple):
1195
+ """What a StateCut of a state records, computed without copying the state."""
1196
+
1197
+ payload: dict[str, Any] # the state's values plus the external closure, not copied
1198
+ slots: dict[str, Any] # {slot: describe(value)} of the state (external closure excluded)
1199
+ described: Any # describe of the payload
1200
+ boundary: str
1201
+ point: dict[str, Any]
1202
+ surface: dict[str, Any]
1203
+ fingerprint: str
1204
+
1205
+
1206
+ class Session:
1207
+ """Resident native executor with isolated branches and explicit commit."""
1208
+
1209
+ def __init__(self, adapter: Adapter, state: Mapping[str, Any], *, parent: str | None = None):
1210
+ adapter.validate_execution()
1211
+ _validate_state(adapter, state)
1212
+ adapter.surface(state).validate(state)
1213
+ self._open(adapter, clone(state), parent)
1214
+
1215
+ def _open(
1216
+ self,
1217
+ adapter: Adapter,
1218
+ state: dict[str, Any],
1219
+ parent: str | None,
1220
+ slots: dict[str, Any] | None = None,
1221
+ ) -> None:
1222
+ """Start on ``state``, validated by the caller and handed over (never copied here).
1223
+
1224
+ ``_slots`` is ``{slot: describe(value)}`` of ``_state`` or None until computed. It is set
1225
+ only together with a validated ``_state``, and ``_state`` is private (every read copies),
1226
+ so a cut of it is sealed from these descriptors without hashing or validating again.
1227
+ """
1228
+ self.adapter = adapter
1229
+ self._state = state
1230
+ self._slots = slots
1231
+ self._external_state = clone(adapter.capture_external())
1232
+ self._parent = parent
1233
+ self._fork_parent = parent
1234
+ self._aborted = False
1235
+ self._poisoned: str | None = None # an in-place write reached the state: see _advance_guarded
1236
+ self.receipts: list[Receipt] = []
1237
+ self.history: list[StateCut] = []
1238
+ self.attempts: list[Receipt] = []
1239
+
1240
+ def _check_poison(self) -> None:
1241
+ if self._poisoned is not None:
1242
+ raise InPlaceWrite(
1243
+ f"{self._poisoned}; this session's state is unusable until restore(cut) of a "
1244
+ "cut that does not share the written tensor"
1245
+ )
1246
+
1247
+ def inspect(self) -> Frame:
1248
+ self._check_poison()
1249
+ self._activate()
1250
+ self.adapter.validate_execution()
1251
+ return Frame(
1252
+ self.adapter.boundary(self._state),
1253
+ {
1254
+ a: describe(self.adapter.read(self._state, a))
1255
+ for a in self.adapter.addresses(self._state)
1256
+ },
1257
+ self.adapter.point(self._state).to_dict(),
1258
+ self.adapter.surface(self._state).to_dict(),
1259
+ )
1260
+
1261
+ def read(self, address: str, index: Any = None) -> Any:
1262
+ """A private copy of ``address``; with ``index``, of ``address[index]`` only (one layer
1263
+ of a per-layer cache slot, say), through the adapter's ``read_part``."""
1264
+ self._check_poison()
1265
+ self._activate()
1266
+ self.adapter.validate_execution()
1267
+ if address == "__saturn_external__" and self._external_state is not None:
1268
+ value = clone(self._external_state)
1269
+ return value if index is None else value[index]
1270
+ if index is None:
1271
+ return self.adapter.read(self._state, address)
1272
+ read_part = getattr(self.adapter, "read_part", None)
1273
+ if read_part is None:
1274
+ return self.adapter.read(self._state, address)[index]
1275
+ return read_part(self._state, address, index)
1276
+
1277
+ def _activate(self) -> None:
1278
+ if self._external_state is not None:
1279
+ self.adapter.restore_external(clone(self._external_state))
1280
+
1281
+ @staticmethod
1282
+ def _cut_state(cut: StateCut, shared: bool = False) -> tuple[Any, dict[str, Any], Any]:
1283
+ """``(describe of the payload, state, external)`` of a cut, verified against its
1284
+ fingerprint: a private copy of its payload, or (``shared``, the adapter's
1285
+ ``shares_state`` contract) its immutable tensors shared."""
1286
+ described, payload = cut._hydrate(shared)
1287
+ return described, payload, payload.pop("__saturn_external__", None)
1288
+
1289
+ def _shares(self) -> bool:
1290
+ return bool(getattr(self.adapter, "shares_state", False))
1291
+
1292
+ def _input(self) -> dict[str, Any]:
1293
+ """The state handed to ``advance``: shared (containers copied, tensors by reference)
1294
+ under the adapter's ``shares_state`` contract, else a private copy."""
1295
+ return _share(self._state) if self._shares() else clone(self._state)
1296
+
1297
+ def _advance_guarded(self, candidate: dict[str, Any], **options: Any) -> Any:
1298
+ """``adapter.advance(candidate, **options)``, refusing (``InPlaceWrite``, naming the
1299
+ slot) when the call wrote one of the input's tensors in place: under ``shares_state``
1300
+ those tensors are shared with sealed cuts and the session state. Checked on every exit,
1301
+ a port controller's ``PortStop`` included."""
1302
+ if not self._shares():
1303
+ return self.adapter.advance(candidate, **options)
1304
+ recorded = _versions(candidate)
1305
+ try:
1306
+ result = self.adapter.advance(candidate, **options)
1307
+ except BaseException:
1308
+ self._guard_input(recorded)
1309
+ raise
1310
+ self._guard_input(recorded)
1311
+ return result
1312
+
1313
+ def _guard_input(self, recorded: tuple[tuple[str, Any, int], ...]) -> None:
1314
+ """Refuse a transition that wrote its input in place, and poison the session: its state
1315
+ shares the written tensor, so it refuses every use until a restore replaces it."""
1316
+ try:
1317
+ _check_versions(recorded, "the transition's input state")
1318
+ except InPlaceWrite as error:
1319
+ self._poisoned = str(error)
1320
+ raise
1321
+
1322
+ def read_port(self, address: StateAddress) -> Any:
1323
+ surface = self.adapter.surface(self._state)
1324
+ slot = surface.slot(address.slot)
1325
+ point = self.adapter.point(self._state)
1326
+ if address.role and slot.role != address.role:
1327
+ raise ValueError("state port role mismatch")
1328
+ if address.execution_point and address.execution_point != point.fingerprint:
1329
+ raise ValueError("state port clock mismatch")
1330
+ if address.state_schema and address.state_schema != surface.state_schema:
1331
+ raise ValueError("state port schema mismatch")
1332
+ value = self.read(address.slot)
1333
+ if address.selector:
1334
+ try:
1335
+ if hasattr(value, "shape"):
1336
+ value = value[address.selector]
1337
+ else:
1338
+ for index in address.selector:
1339
+ value = value[index]
1340
+ except (IndexError, KeyError, TypeError) as exc:
1341
+ raise ValueError("state port selector is outside support") from exc
1342
+ return clone(value) # a compact copy of the selected part, not a view of the read
1343
+ return value # ``read`` already returned a private copy
1344
+
1345
+ def _seal(
1346
+ self,
1347
+ state: Mapping[str, Any],
1348
+ parent: str | None,
1349
+ slots: Mapping[str, Any] | None = None,
1350
+ *,
1351
+ execution_checked: bool = False,
1352
+ state_checked: bool = False,
1353
+ ) -> _Seal:
1354
+ """What ``_cut(state, parent)`` records, copying nothing: validates as a cut does unless
1355
+ the caller already did in this call (``execution_checked``: ``validate_execution``;
1356
+ ``state_checked``: the state's own checks) and hashes only the slots missing from
1357
+ ``slots`` (``{slot: describe(value)}`` known for these very values)."""
1358
+ if not execution_checked:
1359
+ self.adapter.validate_execution()
1360
+ reused = self._sealed_again(state, parent, slots, state_checked)
1361
+ if reused is not None:
1362
+ return reused
1363
+ if not state_checked:
1364
+ _validate_state(self.adapter, state)
1365
+ surface = self.adapter.surface(state)
1366
+ if not state_checked:
1367
+ surface.validate(state)
1368
+ external = clone(self.adapter.capture_external())
1369
+ if "__saturn_external__" in state:
1370
+ raise ValueError("reserved external closure slot used by adapter")
1371
+ own = {
1372
+ name: slots[name] if slots is not None and name in slots else describe_remembered(value)
1373
+ for name, value in state.items()
1374
+ }
1375
+ payload, described = dict(state), dict(own)
1376
+ if external is not None:
1377
+ payload["__saturn_external__"] = external
1378
+ described["__saturn_external__"] = describe(external)
1379
+ surface = SurfaceManifest(
1380
+ surface.slots + (SlotSpec("__saturn_external__", role="runtime"),),
1381
+ surface.state_schema,
1382
+ surface.consumer,
1383
+ surface.horizon,
1384
+ )
1385
+ sealed = describe_mapping(described)
1386
+ boundary = self.adapter.boundary(state)
1387
+ point = self.adapter.point(state).to_dict()
1388
+ manifest = surface.to_dict()
1389
+ fingerprint = digest(
1390
+ _statecut_manifest(
1391
+ self.adapter.model_identity,
1392
+ self.adapter.execution,
1393
+ boundary,
1394
+ parent,
1395
+ sealed,
1396
+ point,
1397
+ manifest,
1398
+ )
1399
+ )
1400
+ seal = _Seal(payload, own, sealed, boundary, point, manifest, fingerprint)
1401
+ if external is None:
1402
+ self._last_seal = (
1403
+ state,
1404
+ parent,
1405
+ own,
1406
+ self.adapter.model_identity,
1407
+ copy.deepcopy(dict(self.adapter.execution)),
1408
+ seal,
1409
+ )
1410
+ return seal
1411
+
1412
+ def _sealed_again(
1413
+ self,
1414
+ state: Mapping[str, Any],
1415
+ parent: str | None,
1416
+ slots: Mapping[str, Any] | None,
1417
+ state_checked: bool,
1418
+ ) -> _Seal | None:
1419
+ """The last seal of this session when it sealed this very state object (the session's
1420
+ state is replaced, never written, and a cut's tensors are immutable) with the same
1421
+ parent, from the slot descriptors that seal made, with the same model identity and
1422
+ execution contract and no external closure: a transition is sealed by ``_record``,
1423
+ then by ``capture`` and by the next call's ``_head``, all of one state. Checked
1424
+ states only: a caller asking for the state checks gets them by sealing afresh."""
1425
+ last = getattr(self, "_last_seal", None)
1426
+ if (
1427
+ last is None
1428
+ or not state_checked
1429
+ or last[0] is not state
1430
+ or last[1] != parent
1431
+ or last[2] is not slots
1432
+ or last[3] != self.adapter.model_identity
1433
+ or last[4] != self.adapter.execution
1434
+ or self.adapter.capture_external() is not None
1435
+ ):
1436
+ return None
1437
+ return last[5]._replace(payload=dict(last[5].payload))
1438
+
1439
+ def _cut(
1440
+ self,
1441
+ state: Mapping[str, Any],
1442
+ parent: str | None,
1443
+ slots: Mapping[str, Any] | None = None,
1444
+ *,
1445
+ state_checked: bool = False,
1446
+ ) -> StateCut:
1447
+ seal = self._seal(state, parent, slots, state_checked=state_checked)
1448
+ return StateCut(
1449
+ self.adapter.model_identity,
1450
+ self.adapter.execution,
1451
+ seal.boundary,
1452
+ parent,
1453
+ seal.payload,
1454
+ execution_point=seal.point,
1455
+ surface=seal.surface,
1456
+ _described=seal.described,
1457
+ _sealed=seal.fingerprint,
1458
+ )
1459
+
1460
+ def _head(self, *, execution_checked: bool = False, poisoned: bool = False) -> str:
1461
+ """The fingerprint ``capture()`` would give now, with its checks, copying nothing (and
1462
+ hashing nothing once the state's slot descriptors are known). ``poisoned``: allowed on a
1463
+ session whose state an in-place write reached (the restore that replaces it)."""
1464
+ if not poisoned:
1465
+ self._check_poison()
1466
+ self._activate()
1467
+ seal = self._seal(
1468
+ self._state,
1469
+ self._parent,
1470
+ self._slots,
1471
+ execution_checked=execution_checked,
1472
+ state_checked=self._slots is not None,
1473
+ )
1474
+ self._slots = seal.slots
1475
+ return seal.fingerprint
1476
+
1477
+ def capture(self, *, retain: bool = True) -> StateCut:
1478
+ self._check_poison()
1479
+ self._activate()
1480
+ seal = self._seal(
1481
+ self._state, self._parent, self._slots, state_checked=self._slots is not None
1482
+ )
1483
+ self._slots = seal.slots
1484
+ cut = StateCut(
1485
+ self.adapter.model_identity,
1486
+ self.adapter.execution,
1487
+ seal.boundary,
1488
+ self._parent,
1489
+ seal.payload,
1490
+ execution_point=seal.point,
1491
+ surface=seal.surface,
1492
+ _described=seal.described,
1493
+ _sealed=seal.fingerprint,
1494
+ _shared=self._shares(),
1495
+ )
1496
+ if retain:
1497
+ self.history.append(cut)
1498
+ return cut
1499
+
1500
+ @classmethod
1501
+ def from_cut(cls, adapter: Adapter, cut: StateCut) -> Session:
1502
+ """Hydrate a declared closure, including registered external state.
1503
+
1504
+ One hash (``verify``), one copy of the payload and one validation: the hydrated state is
1505
+ that copy, its slot descriptors are the verified ones, and the restore receipt the
1506
+ session starts with is the one ``restore(cut)`` writes there.
1507
+ """
1508
+ _refuse_incompatible(cut, adapter)
1509
+ described, state, external = cls._cut_state(
1510
+ cut, bool(getattr(adapter, "shares_state", False))
1511
+ )
1512
+ slots = cls._state_slots(described)
1513
+ current = clone(adapter.capture_external())
1514
+ try:
1515
+ if external is not None:
1516
+ adapter.restore_external(clone(external))
1517
+ adapter.validate_execution()
1518
+ _validate_state(adapter, state)
1519
+ adapter.surface(state).validate(state)
1520
+ session = cls.__new__(cls)
1521
+ session._open(adapter, state, cut.parent, slots)
1522
+ session._activate()
1523
+ session._matches(cut, state, external)
1524
+ session._settle(cut, state, external, slots, session._head(execution_checked=True))
1525
+ return session
1526
+ finally:
1527
+ adapter.restore_external(current)
1528
+
1529
+ @staticmethod
1530
+ def _state_slots(described: Any) -> dict[str, Any] | None:
1531
+ """Slot descriptors of the state a cut's payload hydrates to (its external closure is
1532
+ not part of the state)."""
1533
+ slots = _slot_descriptors(described)
1534
+ if slots is not None:
1535
+ slots.pop("__saturn_external__", None)
1536
+ return slots
1537
+
1538
+ def _matches(
1539
+ self, cut: StateCut, state: Mapping[str, Any], external: Any, *, validate: bool = False
1540
+ ) -> None:
1541
+ """Refuse a cut whose boundary, execution point or state closure differs from what the
1542
+ adapter derives from its payload ``state`` with the cut's external closure installed
1543
+ (``validate``: run the state checks first, as building that cut would)."""
1544
+ current = clone(self.adapter.capture_external())
1545
+ try:
1546
+ if external is not None:
1547
+ self.adapter.restore_external(clone(external))
1548
+ if validate:
1549
+ _validate_state(self.adapter, state)
1550
+ surface = self.adapter.surface(state)
1551
+ if validate:
1552
+ surface.validate(state)
1553
+ if clone(self.adapter.capture_external()) is not None:
1554
+ surface = SurfaceManifest(
1555
+ surface.slots + (SlotSpec("__saturn_external__", role="runtime"),),
1556
+ surface.state_schema,
1557
+ surface.consumer,
1558
+ surface.horizon,
1559
+ )
1560
+ if cut.boundary != self.adapter.boundary(state):
1561
+ raise ValueError("boundary does not match payload")
1562
+ if cut.execution_point is not None and dict(cut.execution_point) != (
1563
+ self.adapter.point(state).to_dict()
1564
+ ):
1565
+ raise ValueError("execution point does not match payload")
1566
+ if cut.surface is not None and dict(cut.surface) != surface.to_dict():
1567
+ raise ValueError("state closure does not match adapter")
1568
+ finally:
1569
+ self.adapter.restore_external(current)
1570
+
1571
+ def _compatible(self, cut: StateCut) -> tuple[dict[str, Any], Any, dict[str, Any] | None]:
1572
+ """Refuse a cut this session cannot take; returns ``(state, external, slots)``: a private
1573
+ copy of its payload, its external closure and the state's verified slot descriptors."""
1574
+ self._activate()
1575
+ self.adapter.validate_execution()
1576
+ _refuse_incompatible(cut, self.adapter)
1577
+ described, state, external = self._cut_state(cut, self._shares())
1578
+ self._matches(cut, state, external, validate=True)
1579
+ return state, external, self._state_slots(described)
1580
+
1581
+ def fork(self, cut: StateCut | None = None) -> Session:
1582
+ if cut is None:
1583
+ parent = self._head()
1584
+ state, external, slots = self._input(), self._external_state, self._slots
1585
+ else:
1586
+ state, external, slots = self._compatible(cut)
1587
+ parent = cut.fingerprint
1588
+ current = clone(self.adapter.capture_external())
1589
+ try:
1590
+ if external is not None:
1591
+ self.adapter.restore_external(clone(external))
1592
+ branch = Session.__new__(Session)
1593
+ branch._open(self.adapter, state, parent, slots)
1594
+ return branch
1595
+ finally:
1596
+ self.adapter.restore_external(current)
1597
+
1598
+ def _record(
1599
+ self,
1600
+ operation: str,
1601
+ before: str,
1602
+ *,
1603
+ state: Mapping[str, Any] | None = None,
1604
+ owned: bool = False,
1605
+ slots: Mapping[str, Any] | None = None,
1606
+ checked: bool = False,
1607
+ **details: Any,
1608
+ ) -> Receipt:
1609
+ """Make ``state`` (default: the current one) this session's state, with ``before`` (a
1610
+ fingerprint) as its parent, and write the receipt. ``owned``: the caller hands ``state``
1611
+ over and keeps no reference, so it is adopted rather than copied. ``slots``: descriptors
1612
+ known for some of its values. ``checked``: the caller validated it (and the executor)
1613
+ just now."""
1614
+ candidate = self._state if state is None else state
1615
+ adopted = _adopt(candidate) if owned else clone(candidate)
1616
+ seal = self._seal(adopted, before, slots, execution_checked=checked, state_checked=checked)
1617
+ receipt = Receipt.make(
1618
+ operation=operation,
1619
+ parent=before,
1620
+ model_identity=self.adapter.model_identity,
1621
+ execution=dict(self.adapter.execution),
1622
+ result=seal.fingerprint,
1623
+ boundary=seal.boundary,
1624
+ execution_point=dict(seal.point),
1625
+ numerical_contract=self.adapter.numerical_contract().to_dict(),
1626
+ **details,
1627
+ )
1628
+ self._state = adopted
1629
+ self._slots = seal.slots
1630
+ self._external_state = clone(self.adapter.capture_external())
1631
+ self._parent = before
1632
+ self.receipts.append(receipt)
1633
+ return receipt
1634
+
1635
+ def _failed(self, operation: str, before: str, error: Exception) -> None:
1636
+ self.attempts.append(
1637
+ Receipt.make(
1638
+ operation=operation,
1639
+ parent=before,
1640
+ result=before,
1641
+ status="refused",
1642
+ error=type(error).__name__,
1643
+ reason=str(error),
1644
+ physical_attempt=len(self.attempts) + 1,
1645
+ )
1646
+ )
1647
+
1648
+ def apply(self, act: Act) -> Receipt:
1649
+ before = self._head()
1650
+ external = clone(self.adapter.capture_external())
1651
+ try:
1652
+ act.verify_implementation()
1653
+ for address, expected in act.preconditions.items():
1654
+ if digest(describe(self.read(address))) != expected:
1655
+ raise ValueError(f"Act precondition changed: {address}")
1656
+ surface = self.adapter.surface(self._state)
1657
+ for address in act.writes:
1658
+ slot = surface.slot(address)
1659
+ if not slot.writable:
1660
+ raise ValueError(f"read-only state port: {address}")
1661
+ if set(slot.invalidates) - set(act.invalidates):
1662
+ raise ValueError(f"missing declared invalidations for {address}")
1663
+ preserved = {
1664
+ slot.name: describe(self._state[slot.name])
1665
+ for slot in surface.slots
1666
+ if slot.persistence == "authoritative"
1667
+ and slot.name not in set(act.writes) | set(act.invalidates)
1668
+ }
1669
+ preserved.update({a: describe(self.read(a)) for a in act.preserve})
1670
+ reads = MappingProxyType({a: self.read(a) for a in act.reads})
1671
+ writes = dict(act.implementation(reads))
1672
+ if act.operation_pure:
1673
+ act.verify_implementation()
1674
+ if set(writes) != set(act.writes):
1675
+ raise ValueError("implementation must return exactly the declared writes")
1676
+ state = self.adapter.write(clone(self._state), writes, act.invalidates)
1677
+ for address, value in preserved.items():
1678
+ if address not in state or describe(state[address]) != value:
1679
+ raise ValueError(f"Act changed preserved port: {address}")
1680
+ return self._record(
1681
+ "apply", before, state=state, act=act.manifest(), writes=describe(writes)
1682
+ )
1683
+ except Exception as exc:
1684
+ self.adapter.restore_external(external)
1685
+ self._failed("apply", before, exc)
1686
+ raise
1687
+
1688
+ def _accepts_ports(self) -> bool:
1689
+ return "ports" in inspect.signature(self.adapter.advance).parameters
1690
+
1691
+ def _advance_options(self) -> dict[str, Any]:
1692
+ """``{"validated": True}`` for an adapter whose ``advance`` takes it: the session hands
1693
+ ``advance`` only states it validated (with ``validate_execution``) in the same call."""
1694
+ if "validated" in inspect.signature(self.adapter.advance).parameters:
1695
+ return {"validated": True}
1696
+ return {}
1697
+
1698
+ def probe(self, controller: Any) -> dict[str, Any]:
1699
+ """Run the next transition on a throw-away candidate with ``controller`` installed.
1700
+
1701
+ Read-only: records no receipt, attempt or history entry and leaves the session state
1702
+ and external closure as they were. ``PortStop`` ends the probe normally; any other
1703
+ exception propagates unchanged.
1704
+ """
1705
+ self._check_poison()
1706
+ self._activate()
1707
+ self.adapter.validate_execution()
1708
+ if not self._accepts_ports() or not self.adapter.ports(self._state):
1709
+ raise ValueError(f"no ports at {self.adapter.boundary(self._state)}")
1710
+ external = clone(self.adapter.capture_external())
1711
+ candidate = self._input()
1712
+ stopped = False
1713
+ begin = getattr(controller, "begin", None)
1714
+ if begin is not None:
1715
+ begin()
1716
+ options = self._advance_options()
1717
+ if options: # the state is validated; re-check the executor after the controller's begin
1718
+ self.adapter.validate_execution()
1719
+ try:
1720
+ self._advance_guarded(candidate, ports=controller, **options)
1721
+ except PortStop:
1722
+ stopped = True
1723
+ finally:
1724
+ self.adapter.restore_external(external)
1725
+ check = getattr(controller, "probe_check", None)
1726
+ if check is not None:
1727
+ check()
1728
+ return {"boundary": self.adapter.boundary(self._state), "stopped": stopped}
1729
+
1730
+ def continue_(self, steps: int = 1, *, ports: Any = None) -> Receipt:
1731
+ if isinstance(steps, bool) or not isinstance(steps, int) or steps < 1:
1732
+ raise ValueError("steps must be a positive integer")
1733
+ if ports is not None and not self._accepts_ports():
1734
+ raise ValueError("adapter does not accept a port controller")
1735
+ if ports is not None:
1736
+ check_ahead = getattr(ports, "check_ahead", None)
1737
+ ahead = self.adapter.ports_ahead(self._state, steps) if check_ahead else None
1738
+ if ahead is not None:
1739
+ check_ahead(ahead) # refuses before anything runs: no receipt, no attempt
1740
+ before = self._head()
1741
+ external = clone(self.adapter.capture_external())
1742
+ try:
1743
+ candidate = self._input()
1744
+ known = dict(self._slots or {}) # descriptors of candidate's values (clone keeps them)
1745
+ options = self._advance_options()
1746
+ transitions = []
1747
+ begin_call = getattr(ports, "begin_call", None)
1748
+ if begin_call is not None:
1749
+ begin_call()
1750
+ for _ in range(steps):
1751
+ entry = self.adapter.point(candidate).to_dict()
1752
+ spec = self.adapter.transition(candidate)
1753
+ slots = {slot.name for slot in self.adapter.surface(candidate).slots}
1754
+ if set(spec.reads + spec.writes + spec.invalidates) - slots:
1755
+ raise ValueError("transition footprint contains undeclared slots")
1756
+ changed = set(spec.writes + spec.invalidates)
1757
+ preserved = (
1758
+ {
1759
+ name: known[name] if name in known else describe_remembered(value)
1760
+ for name, value in candidate.items()
1761
+ if name not in changed
1762
+ }
1763
+ if spec.footprint == "declared"
1764
+ else {}
1765
+ )
1766
+ begin = getattr(ports, "begin", None)
1767
+ if begin is not None:
1768
+ begin()
1769
+ candidate = dict(
1770
+ self._advance_guarded(candidate, **options)
1771
+ if ports is None
1772
+ else self._advance_guarded(candidate, ports=ports, **options)
1773
+ )
1774
+ known = {}
1775
+ for name, expected in preserved.items():
1776
+ observed = (
1777
+ describe_remembered(candidate[name]) if name in candidate else None
1778
+ )
1779
+ if observed != expected:
1780
+ raise ValueError(f"native transition changed undeclared slot: {name}")
1781
+ known[name] = observed
1782
+ self.adapter.validate_execution()
1783
+ _validate_state(self.adapter, candidate)
1784
+ self.adapter.surface(candidate).validate(candidate)
1785
+ transitions.append(
1786
+ {
1787
+ "before": entry,
1788
+ "after": self.adapter.point(candidate).to_dict(),
1789
+ "native_operation": spec.to_dict(),
1790
+ "structural_operation": spec.operation,
1791
+ "occurrence": digest(
1792
+ {
1793
+ "entry": entry,
1794
+ "operation": spec.operation,
1795
+ "transaction_parent": before,
1796
+ "transition_index": len(transitions),
1797
+ "execution": dict(self.adapter.execution),
1798
+ }
1799
+ ),
1800
+ }
1801
+ )
1802
+ manifest = getattr(ports, "manifest", None)
1803
+ edits = manifest() if manifest is not None else None
1804
+ if edits:
1805
+ transitions[-1]["port_edits"] = edits
1806
+ end_call = getattr(ports, "end_call", None)
1807
+ if end_call is not None:
1808
+ end_call()
1809
+ return self._record(
1810
+ "continue",
1811
+ before,
1812
+ state=candidate,
1813
+ owned=True,
1814
+ slots=known,
1815
+ checked=True,
1816
+ steps=steps,
1817
+ transitions=transitions,
1818
+ )
1819
+ except Exception as exc:
1820
+ self.adapter.restore_external(external)
1821
+ self._failed("continue", before, exc)
1822
+ raise
1823
+
1824
+ def step(self, *, granularity: str = "transition", max_steps: int = 10000) -> Receipt:
1825
+ if granularity == "transition":
1826
+ return self.continue_(1)
1827
+ if granularity not in {"token", "denoise"}:
1828
+ raise ValueError("step granularity must be transition, token or denoise")
1829
+ if type(max_steps) is not int or max_steps < 1:
1830
+ raise ValueError("max_steps must be positive")
1831
+ self._activate()
1832
+ point = self.adapter.point(self._state)
1833
+ family = self.adapter.execution.get("family", "")
1834
+ if (granularity == "token" and "qwen" not in family) or (
1835
+ granularity == "denoise"
1836
+ and family not in {"ddim", "diffusion", "diffusion-ddim", "flux2-klein"}
1837
+ ):
1838
+ raise ValueError("macro-step is not supported by this family")
1839
+ before = self.capture(retain=False)
1840
+ branch = self.fork(before)
1841
+ try:
1842
+ for count in range(1, max_steps + 1):
1843
+ branch.continue_()
1844
+ if self.adapter.point(branch._state).logical_step != point.logical_step:
1845
+ return self._record(
1846
+ "step",
1847
+ before.fingerprint,
1848
+ state=branch._state,
1849
+ slots=branch._slots,
1850
+ steps=count,
1851
+ granularity=granularity,
1852
+ micro_receipts=[r.to_dict() for r in branch.receipts],
1853
+ )
1854
+ raise ValueError("macro-step limit reached before a complete boundary")
1855
+ except Exception as exc:
1856
+ self.history.append(branch.capture())
1857
+ self._activate()
1858
+ self._failed("step", before.fingerprint, exc)
1859
+ raise
1860
+
1861
+ def replay(self, cut: StateCut, *, steps: int = 1) -> Session:
1862
+ branch = self.fork(cut)
1863
+ branch.continue_(steps)
1864
+ return branch
1865
+
1866
+ def restore(self, cut: StateCut) -> Receipt:
1867
+ state, external, slots = self._compatible(cut)
1868
+ return self._settle(
1869
+ cut, state, external, slots, self._head(execution_checked=True, poisoned=True)
1870
+ )
1871
+
1872
+ def _settle(
1873
+ self,
1874
+ cut: StateCut,
1875
+ state: dict[str, Any],
1876
+ external: Any,
1877
+ slots: dict[str, Any] | None,
1878
+ before: str,
1879
+ ) -> Receipt:
1880
+ """The rest of ``restore`` once ``cut`` is verified and compatible and ``state`` (a
1881
+ private copy of its payload, validated) is in hand: check that it seals to the cut's
1882
+ fingerprint, write the receipt (``before``: the fingerprint left) and take it over."""
1883
+ current = clone(self.adapter.capture_external())
1884
+ try:
1885
+ if external is not None:
1886
+ self.adapter.restore_external(clone(external))
1887
+ restored = self._seal(
1888
+ state, cut.parent, slots, execution_checked=True, state_checked=True
1889
+ )
1890
+ if restored.fingerprint != cut.fingerprint:
1891
+ raise ValueError("restore fingerprint mismatch")
1892
+ receipt = Receipt.make(
1893
+ operation="restore",
1894
+ parent=before,
1895
+ result=cut.fingerprint,
1896
+ verified_exact=True,
1897
+ model_identity=self.adapter.model_identity,
1898
+ execution=dict(self.adapter.execution),
1899
+ execution_point=dict(cut.execution_point or {}),
1900
+ numerical_contract=self.adapter.numerical_contract().to_dict(),
1901
+ )
1902
+ except Exception as exc:
1903
+ self.adapter.restore_external(current)
1904
+ self._failed("restore", before, exc)
1905
+ raise
1906
+ self._state = state
1907
+ self._poisoned = None
1908
+ self._slots = restored.slots
1909
+ self._external_state = external
1910
+ self._parent = cut.parent
1911
+ self.receipts.append(receipt)
1912
+ return receipt
1913
+
1914
+ def commit(self, branch: Session) -> Receipt:
1915
+ parent = self._head()
1916
+ if branch.adapter is not self.adapter or branch._origin != parent or branch._aborted:
1917
+ raise ValueError("branch was not forked from the current parent")
1918
+ candidate = branch.capture(retain=False)
1919
+ state, external, slots = self._compatible(candidate)
1920
+ current = clone(self._external_state)
1921
+ try:
1922
+ if external is not None:
1923
+ self.adapter.restore_external(clone(external))
1924
+ return self._record(
1925
+ "commit",
1926
+ parent,
1927
+ state=state,
1928
+ owned=True,
1929
+ slots=slots,
1930
+ candidate=candidate.fingerprint,
1931
+ )
1932
+ except Exception as exc:
1933
+ self.adapter.restore_external(current)
1934
+ self._failed("commit", parent, exc)
1935
+ raise
1936
+
1937
+ def abort(self, branch: Session, *, reason: str = "researcher discarded candidate") -> Receipt:
1938
+ """Keep candidate evidence inspectable, but remove its permission to commit."""
1939
+ if branch.adapter is not self.adapter:
1940
+ raise ValueError("candidate belongs to another resident adapter")
1941
+ parent = self._head()
1942
+ candidate = branch._head()
1943
+ branch._aborted = True
1944
+ receipt = Receipt.make(
1945
+ operation="abort",
1946
+ parent=parent,
1947
+ candidate=candidate,
1948
+ result=parent,
1949
+ reason=reason,
1950
+ parent_unchanged=True,
1951
+ model_identity=self.adapter.model_identity,
1952
+ execution=dict(self.adapter.execution),
1953
+ )
1954
+ self.receipts.append(receipt)
1955
+ return receipt
1956
+
1957
+ @property
1958
+ def _origin(self) -> str | None:
1959
+ return self._fork_parent
1960
+
1961
+ def compare(
1962
+ self, other: Session, evaluator: Callable[[Session], Mapping[str, Any]] | None = None
1963
+ ) -> dict[str, Any]:
1964
+ if other.adapter is not self.adapter:
1965
+ raise ValueError("comparison requires the same resident adapter")
1966
+ left, right = self.capture(retain=False), other.capture(retain=False)
1967
+ result = {
1968
+ "left": left.fingerprint,
1969
+ "right": right.fingerprint,
1970
+ "equal_payload": describe(left.payload) == describe(right.payload),
1971
+ "left_state": describe(left.payload),
1972
+ "right_state": describe(right.payload),
1973
+ }
1974
+ if evaluator:
1975
+ result["metrics"] = {
1976
+ "left": dict(evaluator(self.fork(left))),
1977
+ "right": dict(evaluator(other.fork(right))),
1978
+ }
1979
+ return result