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/symbols.py ADDED
@@ -0,0 +1,398 @@
1
+ """Optional, context-qualified debug information over existing typed ports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .contracts import StateAddress
12
+ from .core import Session, StateCut
13
+ from .values import describe, digest
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class SymbolBinding:
18
+ """A read-only local binding. Evidence labels confer no mutation authority.
19
+
20
+ Context slots must cover the input dependencies relevant to the claim. The
21
+ library checks their identity; it cannot infer whether the claim is complete.
22
+ Each location is bound to an exact execution point and state schema.
23
+ """
24
+
25
+ symbol: str
26
+ model_identity: str
27
+ execution: str
28
+ context: str
29
+ context_slots: tuple[tuple[str, str], ...]
30
+ locations: tuple[StateAddress, ...]
31
+ evidence: tuple[str, ...]
32
+ claim: str
33
+ status: str = "supplied"
34
+ abstain_reason: str | None = None
35
+ confidence: float | None = None
36
+
37
+ def __post_init__(self):
38
+ object.__setattr__(self, "locations", tuple(self.locations))
39
+ object.__setattr__(self, "context_slots", tuple(tuple(row) for row in self.context_slots))
40
+ object.__setattr__(self, "evidence", tuple(self.evidence))
41
+ if self.confidence is not None and (
42
+ isinstance(self.confidence, bool)
43
+ or not math.isfinite(self.confidence)
44
+ or not 0 <= self.confidence <= 1
45
+ ):
46
+ raise ValueError("symbol confidence must be a finite value in [0, 1]")
47
+ if not all((self.symbol, self.model_identity, self.execution, self.context, self.claim)):
48
+ raise ValueError("symbol requires identity, context and a bounded claim")
49
+ if self.status not in {"supplied", "observed", "validated", "abstained"}:
50
+ raise ValueError("unknown symbol status")
51
+ if not self.evidence:
52
+ raise ValueError("symbol requires evidence references")
53
+ if self.status == "abstained":
54
+ if not self.abstain_reason or self.locations:
55
+ raise ValueError("abstention requires a reason and no executable locations")
56
+ elif not self.locations or self.abstain_reason:
57
+ raise ValueError("binding requires locations or explicit abstention")
58
+ if any(not loc.execution_point or not loc.state_schema for loc in self.locations):
59
+ raise ValueError("symbol locations require exact point and schema")
60
+ if len({name for name, _ in self.context_slots}) != len(self.context_slots):
61
+ raise ValueError("duplicate context slot")
62
+
63
+ @classmethod
64
+ def bind(
65
+ cls,
66
+ session: Session,
67
+ symbol: str,
68
+ locations: tuple[StateAddress, ...],
69
+ *,
70
+ context: str,
71
+ context_slots: tuple[str, ...],
72
+ evidence: tuple[str, ...],
73
+ claim: str,
74
+ status: str = "supplied",
75
+ ) -> SymbolBinding:
76
+ frame = session.inspect()
77
+ point = digest(dict(frame.execution_point))
78
+ schema = frame.surface["state_schema"]
79
+ for location in locations:
80
+ # Bare locations are qualified here; supplied qualifiers must not be erased.
81
+ session.read_port(location)
82
+ bound = tuple(
83
+ StateAddress(loc.slot, loc.selector, loc.role, point, schema) for loc in locations
84
+ )
85
+ for location in bound:
86
+ session.read_port(location)
87
+ return cls(
88
+ symbol,
89
+ session.adapter.model_identity,
90
+ digest(dict(session.adapter.execution)),
91
+ context,
92
+ tuple((name, digest(describe(session.read(name)))) for name in context_slots),
93
+ bound,
94
+ evidence,
95
+ claim,
96
+ status,
97
+ )
98
+
99
+ def to_dict(self) -> dict[str, Any]:
100
+ body = {
101
+ "schema": "saturn-pub-debug-symbol-v1",
102
+ "symbol": self.symbol,
103
+ "model_identity": self.model_identity,
104
+ "execution": self.execution,
105
+ "context": self.context,
106
+ "context_slots": dict(self.context_slots),
107
+ "locations": [loc.to_dict() for loc in self.locations],
108
+ "evidence": list(self.evidence),
109
+ "claim": self.claim,
110
+ "status": self.status,
111
+ "abstain_reason": self.abstain_reason,
112
+ "confidence": self.confidence,
113
+ "authority": "read-only-debug-info",
114
+ }
115
+ return {**body, "fingerprint": digest(body)}
116
+
117
+ @classmethod
118
+ def from_dict(cls, value: dict[str, Any]) -> SymbolBinding:
119
+ body = {k: v for k, v in value.items() if k != "fingerprint"}
120
+ if digest(body) != value.get("fingerprint"):
121
+ raise ValueError("symbol seal mismatch")
122
+ result = cls(
123
+ value["symbol"],
124
+ value["model_identity"],
125
+ value["execution"],
126
+ value["context"],
127
+ tuple(value["context_slots"].items()),
128
+ tuple(
129
+ StateAddress(
130
+ loc["slot"],
131
+ tuple(loc["selector"]),
132
+ loc["role"],
133
+ loc["execution_point"],
134
+ loc["state_schema"],
135
+ )
136
+ for loc in value["locations"]
137
+ ),
138
+ tuple(value["evidence"]),
139
+ value["claim"],
140
+ value["status"],
141
+ value["abstain_reason"],
142
+ value["confidence"],
143
+ )
144
+ if result.to_dict() != value:
145
+ raise ValueError("unsupported symbol schema or fields")
146
+ return result
147
+
148
+ def _support(self, model_identity, execution, context, slot_digest):
149
+ if context != self.context or model_identity != self.model_identity:
150
+ raise ValueError("symbol context or model mismatch")
151
+ if digest(dict(execution)) != self.execution:
152
+ raise ValueError("symbol execution mismatch")
153
+ for name, expected in self.context_slots:
154
+ if slot_digest(name) != expected:
155
+ raise ValueError(f"symbol input context changed: {name}")
156
+ if self.status == "abstained":
157
+ raise ValueError(f"symbol abstained: {self.abstain_reason}")
158
+
159
+ def resolve(self, session: Session, *, context: str) -> tuple[StateAddress, ...]:
160
+ self._support(
161
+ session.adapter.model_identity,
162
+ session.adapter.execution,
163
+ context,
164
+ lambda name: digest(describe(session.read(name))),
165
+ )
166
+ for location in self.locations:
167
+ session.read_port(location)
168
+ return self.locations
169
+
170
+ def resolve_metadata(
171
+ self, *, model_identity, execution, execution_point, surface, slots, context: str
172
+ ) -> tuple[StateAddress, ...]:
173
+ """Check support against caller-verified typed descriptors, without a model.
174
+
175
+ This checks descriptive support, not live adapter availability, tensor
176
+ page integrity, semantic truth, or mutation authority. Native reads
177
+ must still pass ``resolve`` against an executable Session.
178
+ """
179
+
180
+ def slot_digest(name):
181
+ if name not in slots:
182
+ raise ValueError(f"symbol context slot unavailable: {name}")
183
+ return digest(slots[name])
184
+
185
+ self._support(model_identity, execution, context, slot_digest)
186
+ declared = {slot["name"]: slot for slot in surface.get("slots", [])}
187
+ for location in self.locations:
188
+ slot = declared.get(location.slot)
189
+ if slot is None or location.slot not in slots:
190
+ raise ValueError(f"symbol state port unavailable: {location.slot}")
191
+ if location.role and slot["role"] != location.role:
192
+ raise ValueError("state port role mismatch")
193
+ if location.execution_point != digest(dict(execution_point)):
194
+ raise ValueError("state port clock mismatch")
195
+ if location.state_schema != surface.get("state_schema"):
196
+ raise ValueError("state port schema mismatch")
197
+ _descriptor_selector(slots[location.slot], location.selector)
198
+ return self.locations
199
+
200
+
201
+ def _descriptor_selector(value, selector):
202
+ """Bounds-check the integer selectors supported by Session.read_port."""
203
+ remaining = tuple(selector)
204
+ while remaining:
205
+ if value.get("kind") == "tensor":
206
+ shape = value["shape"]
207
+ if len(remaining) > len(shape) or any(
208
+ not -size <= index < size for index, size in zip(remaining, shape)
209
+ ):
210
+ raise ValueError("state port selector is outside support")
211
+ return
212
+ index, *tail = remaining
213
+ if value.get("kind") in {"list", "tuple"}:
214
+ items = value["items"]
215
+ if not -len(items) <= index < len(items):
216
+ raise ValueError("state port selector is outside support")
217
+ value = items[index]
218
+ elif value.get("kind") == "mapping":
219
+ matches = [
220
+ row["value"]
221
+ for row in value["items"]
222
+ if row["key"] == {"kind": "scalar", "type": "int", "value": index}
223
+ ]
224
+ if len(matches) != 1:
225
+ raise ValueError("state port selector is outside support")
226
+ value = matches[0]
227
+ else:
228
+ raise ValueError("state port selector is outside support")
229
+ remaining = tuple(tail)
230
+
231
+
232
+ class SymbolTable:
233
+ """Several local bindings may describe one symbol at different safe points."""
234
+
235
+ def __init__(self, bindings: tuple[SymbolBinding, ...] = ()):
236
+ self.bindings = list(bindings)
237
+
238
+ def save(self, path: str | Path, cut: StateCut) -> None:
239
+ """Write sealed debug info beside a cut; never add execution authority."""
240
+ cut.verify()
241
+ for row in self.bindings:
242
+ if row.model_identity != cut.model_identity or row.execution != digest(
243
+ dict(cut.execution)
244
+ ):
245
+ raise ValueError("debug info belongs to another execution")
246
+ body = {
247
+ "schema": "saturn-pub-debug-info-v1",
248
+ "cut": cut.fingerprint,
249
+ "bindings": [row.to_dict() for row in self.bindings],
250
+ }
251
+ Path(path).write_text(json.dumps({**body, "fingerprint": digest(body)}, indent=2) + "\n")
252
+
253
+ @classmethod
254
+ def load(cls, path: str | Path, cut: StateCut) -> SymbolTable:
255
+ cut.verify()
256
+ value = json.loads(Path(path).read_text())
257
+ body = {k: v for k, v in value.items() if k != "fingerprint"}
258
+ if (
259
+ digest(body) != value.get("fingerprint")
260
+ or body.get("cut") != cut.fingerprint
261
+ or body.get("schema") != "saturn-pub-debug-info-v1"
262
+ or set(body) != {"schema", "cut", "bindings"}
263
+ ):
264
+ raise ValueError("debug info seal or cut reference mismatch")
265
+ rows = tuple(SymbolBinding.from_dict(row) for row in body["bindings"])
266
+ if any(
267
+ row.model_identity != cut.model_identity or row.execution != digest(dict(cut.execution))
268
+ for row in rows
269
+ ):
270
+ raise ValueError("debug info execution mismatch")
271
+ return cls(rows)
272
+
273
+ def resolve(self, session: Session, symbol: str, *, context: str) -> SymbolBinding:
274
+ candidates = [row for row in self.bindings if row.symbol == symbol]
275
+ matches = []
276
+ reasons = []
277
+ for row in candidates:
278
+ try:
279
+ row.resolve(session, context=context)
280
+ matches.append(row)
281
+ except ValueError as exc:
282
+ reasons.append(str(exc))
283
+ if len(matches) != 1:
284
+ raise ValueError(
285
+ f"symbol {symbol!r} requires one qualified binding; "
286
+ f"found {len(matches)}; {'; '.join(reasons) or 'no binding'}"
287
+ )
288
+ return matches[0]
289
+
290
+
291
+ def structural_symbols(session: Session) -> list[dict[str, Any]]:
292
+ """Adapter declarations, not inferred semantic roles or measured writers."""
293
+ frame = session.inspect()
294
+ return [
295
+ {
296
+ **slot,
297
+ "symbol": slot["name"],
298
+ "status": "adapter-declared",
299
+ "readable": slot["name"] in frame.slots,
300
+ "authority": "structural-description",
301
+ }
302
+ for slot in frame.surface["slots"]
303
+ ]
304
+
305
+
306
+ def backtrace(session: Session, slot: str) -> dict[str, Any]:
307
+ """Walk recorded read/write footprints backwards from the current value.
308
+
309
+ Unspecified native footprints stop the walk. Declared dependency edges are
310
+ execution provenance, not proof of semantic causality. Fork-prefix receipts
311
+ are not implicitly reconstructed from cut bytes.
312
+ """
313
+ surface = session.inspect().surface
314
+ if slot not in {row["name"] for row in surface["slots"]}:
315
+ raise ValueError(f"undeclared state slot: {slot}")
316
+ needed = {slot}
317
+ rows = []
318
+
319
+ def expand(body, enclosing=None):
320
+ if body["operation"] == "step" and body.get("micro_receipts"):
321
+ for micro in reversed(body["micro_receipts"]):
322
+ yield from expand(micro, body["fingerprint"])
323
+ else:
324
+ yield body, enclosing
325
+
326
+ bodies = [item for receipt in reversed(session.receipts) for item in expand(receipt.to_dict())]
327
+ for body, enclosing in bodies:
328
+ if not needed:
329
+ break
330
+ receipt_id = body["fingerprint"]
331
+ if body["operation"] == "restore":
332
+ rows.append(
333
+ {
334
+ "receipt": receipt_id,
335
+ "operation": "restore",
336
+ "status": "ancestry-boundary",
337
+ "cut": body["result"],
338
+ }
339
+ )
340
+ break
341
+ if body["operation"] == "apply":
342
+ steps = [
343
+ {
344
+ "native_operation": {
345
+ **body["act"],
346
+ "operation": body["act"]["name"],
347
+ "footprint": "declared",
348
+ },
349
+ "after": body.get("execution_point", {}),
350
+ }
351
+ ]
352
+ elif body["operation"] == "continue":
353
+ steps = body.get("transitions", [])
354
+ else:
355
+ rows.append(
356
+ {
357
+ "receipt": receipt_id,
358
+ "operation": body["operation"],
359
+ "status": "unexpanded-history",
360
+ }
361
+ )
362
+ break
363
+ stop = False
364
+ for index in range(len(steps) - 1, -1, -1):
365
+ step = steps[index]
366
+ spec = step.get("native_operation", {})
367
+ if spec.get("footprint") != "declared":
368
+ rows.append({"receipt": receipt_id, "status": "unknown-footprint"})
369
+ stop = True
370
+ break
371
+ writes = set(spec.get("writes", [])) | set(spec.get("invalidates", []))
372
+ used = needed & writes
373
+ if used:
374
+ rows.append(
375
+ {
376
+ "receipt": receipt_id,
377
+ "enclosing_receipt": enclosing,
378
+ "cut": body["result"] if index == len(steps) - 1 else None,
379
+ "cut_scope": "receipt-reference"
380
+ if index == len(steps) - 1
381
+ else "point-only",
382
+ "receipt_result": body["result"],
383
+ "operation": spec["operation"],
384
+ "writes_needed": sorted(used),
385
+ "reads": spec.get("reads", []),
386
+ "point": step["after"],
387
+ "status": "declared-dependency",
388
+ }
389
+ )
390
+ needed = (needed - writes) | set(spec.get("reads", []))
391
+ if stop:
392
+ break
393
+ return {
394
+ "slot": slot,
395
+ "writers": rows,
396
+ "unresolved": sorted(needed),
397
+ "authority": "declared-provenance-not-semantic-proof",
398
+ }
@@ -0,0 +1,61 @@
1
+ """Reversible PyTorch update intervals, adapted from Saturn's verified controller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from typing import Any
7
+
8
+ from ..values import clone
9
+ from ._checkpoint import (
10
+ DeterministicCheckpointController,
11
+ EvaluationMutationError,
12
+ EvaluationScores,
13
+ ImmutableDirectoryReceiptStore,
14
+ PromotionObjective,
15
+ PromotionPolicy,
16
+ TrainingIntervalError,
17
+ TrainingStateBoundary,
18
+ )
19
+
20
+
21
+ class TrainingTransaction(DeterministicCheckpointController):
22
+ """Register caller-owned caches/hooks alongside the sampler/training cursor.
23
+
24
+ Callbacks must expose restorable data, not arbitrary executable objects.
25
+ Baseline establishment and interval execution use the original controller API.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ *,
31
+ mutable: Mapping[str, tuple[Callable, Callable]] | None = None,
32
+ cursor_capture: Callable,
33
+ cursor_restore: Callable,
34
+ **kwargs: Any,
35
+ ):
36
+ registered = dict(mutable or {})
37
+
38
+ def capture() -> dict[str, Any]:
39
+ return {
40
+ "cursor": clone(cursor_capture()),
41
+ "mutable": {name: clone(callbacks[0]()) for name, callbacks in registered.items()},
42
+ }
43
+
44
+ def restore(state: dict[str, Any]) -> None:
45
+ cursor_restore(clone(state["cursor"]))
46
+ for name, callbacks in registered.items():
47
+ callbacks[1](clone(state["mutable"][name]))
48
+
49
+ super().__init__(cursor_capture=capture, cursor_restore=restore, **kwargs)
50
+
51
+
52
+ __all__ = [
53
+ "TrainingTransaction",
54
+ "EvaluationScores",
55
+ "PromotionObjective",
56
+ "PromotionPolicy",
57
+ "ImmutableDirectoryReceiptStore",
58
+ "TrainingStateBoundary",
59
+ "TrainingIntervalError",
60
+ "EvaluationMutationError",
61
+ ]