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/route.py ADDED
@@ -0,0 +1,774 @@
1
+ """Metadata-plus-delta route: choose a measured intervention before paying for its bytes.
2
+
3
+ Saturn already applies a measured intervention to a session and rolls it back
4
+ exactly (:meth:`Session.apply` / :meth:`Session.restore`) and binds an ordered,
5
+ recipient-locked schedule of measured Acts to one parent
6
+ (:mod:`saturn.program`). What it did not have is a *payload-free catalog* of
7
+ candidate deltas you can query and choose among before hydrating any heavy
8
+ tensor, plus the custody accounting that proves the compact route lost nothing
9
+ and that the applied delta rolled back bit-exactly.
10
+
11
+ This module is that thin layer. A :class:`DeltaCard` is a content-addressed,
12
+ tensor-free description of one measured delta: the recipient identity it was
13
+ measured against, free-form selection ``tags``, the registered operation that
14
+ applies it, a content address (sha256 + shape + dtype + where to fetch the
15
+ bytes) for the heavy delta tensor, and the measured effect. A
16
+ :class:`MetadataDeltaRoute` indexes many cards and answers :meth:`select`
17
+ (``**tags``) purely from metadata; only :meth:`MetadataDeltaRoute.hydrate`
18
+ touches bytes, through a caller-owned resolver, deduplicated and byte-accounted.
19
+ :func:`apply_delta` then composes the existing ``Session`` lifecycle -- fork a
20
+ candidate and a native branch from one parent, apply, continue, compare, and
21
+ restore -- into one route-execution receipt whose ``rollback.verified_exact``
22
+ and per-element ``restored_elements`` are the public analog of the privately
23
+ demonstrated exact rollback.
24
+
25
+ Adapter-neutral: the same card drives a decoder (add to ``hidden``) and a FLUX
26
+ block suffix (add to ``image`` / ``text``). Nothing here is diffusion-specific
27
+ and no private vocabulary is carried over.
28
+
29
+ Relationship to :mod:`saturn.program`: a ``Program`` binds *one* measured
30
+ arm's ordered Acts to *one* parent and replays it. This module does not repeat
31
+ that -- it reuses ``Session``/``Act``/``Receipt`` and adds only what Program
32
+ lacks: a payload-free catalog of *many* candidate deltas, selection before
33
+ hydration, a deduplicated resolver seam with byte accounting, and a
34
+ native-comparison-plus-exact-rollback receipt. Hydrated card Acts can be fed to
35
+ ``Program`` or to :func:`apply_delta` interchangeably.
36
+
37
+ Claim boundary: this is controlled mechanics. A route selects and applies a
38
+ measured delta and proves exact custody and exact rollback; it does not assert
39
+ that the delta is semantically meaningful or that two model families are
40
+ equivalent.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import argparse
46
+ import json
47
+ import math
48
+ import re
49
+ from collections.abc import Callable, Mapping, Sequence
50
+ from dataclasses import dataclass, field
51
+ from pathlib import Path
52
+ from typing import Any
53
+
54
+ from .core import Act, Session, StateCut
55
+ from .values import describe, digest
56
+
57
+ DELTA_CARD_SCHEMA = "saturn-pub-delta-card-v1"
58
+ METADATA_DELTA_ROUTE_SCHEMA = "saturn-pub-metadata-delta-route-v1"
59
+ ROUTE_EXECUTION_SCHEMA = "saturn-pub-route-execution-v1"
60
+
61
+ DEFAULT_CLAIM_BOUNDARY = (
62
+ "controlled mechanics: a selected, content-verified delta applied and rolled "
63
+ "back exactly; not a claim of semantic meaning or cross-family equivalence"
64
+ )
65
+ _BUILTIN_OPERATIONS = {
66
+ "add": "saturn.builtin.add",
67
+ "replace": "saturn.builtin.replace",
68
+ "zero": "saturn.builtin.zero",
69
+ }
70
+ _VALUE_OPERATIONS = ("add", "replace")
71
+ _SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
72
+
73
+ # Selection coordinate keys promoted to keyword arguments on ``select``. Any other
74
+ # string-keyed tag is still selectable through ``select(tags={...})``; these are
75
+ # only the conventional, adapter-neutral names.
76
+ SELECTION_KEYS = ("role", "family", "site", "stream", "step", "consumer")
77
+
78
+
79
+ class RouteError(ValueError):
80
+ """Raised when a metadata-plus-delta route cannot be safely built or used."""
81
+
82
+
83
+ # --- payload-free value discipline (no tensor bytes ever enter the metadata plane) ------
84
+
85
+
86
+ def _payload_free(value: Any, label: str = "value") -> Any:
87
+ """Return a JSON-safe copy, refusing tensor-like payloads and non-finite floats."""
88
+ if value is None or isinstance(value, (str, bool, int)):
89
+ return value
90
+ if isinstance(value, float):
91
+ if not math.isfinite(value):
92
+ raise RouteError(f"{label} cannot contain non-finite floats")
93
+ return value
94
+ if isinstance(value, Mapping):
95
+ return {str(key): _payload_free(item, f"{label}.{key}") for key, item in value.items()}
96
+ if isinstance(value, (list, tuple)):
97
+ return [_payload_free(item, label) for item in value]
98
+ if isinstance(value, (set, frozenset)):
99
+ return sorted((_payload_free(item, label) for item in value), key=repr)
100
+ if any(hasattr(value, marker) for marker in ("detach", "numpy", "ndim", "shape")):
101
+ raise RouteError(f"raw tensor-like {type(value).__name__} is not allowed in {label}")
102
+ raise RouteError(f"{label} is not JSON-safe: {type(value).__name__}")
103
+
104
+
105
+ def _fingerprint(value: Any) -> str:
106
+ return digest(_payload_free(value))
107
+
108
+
109
+ def _text(value: Any, label: str) -> str:
110
+ result = str(value or "").strip()
111
+ if not result:
112
+ raise RouteError(f"{label} must be non-empty")
113
+ return result
114
+
115
+
116
+ def _item_size(dtype: Any) -> int:
117
+ name = str(dtype or "").lower()
118
+ if any(token in name for token in ("float64", "double", "int64", "complex64")):
119
+ return 8
120
+ if any(token in name for token in ("float16", "bfloat16", "half", "int16")):
121
+ return 2
122
+ if any(token in name for token in ("uint8", "int8", "bool")):
123
+ return 1
124
+ return 4
125
+
126
+
127
+ def _numel(shape: Any) -> int | None:
128
+ if not isinstance(shape, Sequence) or isinstance(shape, (str, bytes, bytearray)):
129
+ return None
130
+ total = 1
131
+ try:
132
+ for dimension in shape:
133
+ dimension = int(dimension)
134
+ if dimension < 0:
135
+ return None
136
+ total *= dimension
137
+ except (TypeError, ValueError, OverflowError):
138
+ return None
139
+ return total
140
+
141
+
142
+ def _declared_bytes(ref: Mapping[str, Any]) -> int | None:
143
+ if ref.get("bytes") is not None:
144
+ try:
145
+ value = int(ref["bytes"])
146
+ except (TypeError, ValueError):
147
+ return None
148
+ return value if value >= 0 else None
149
+ count = _numel(ref.get("shape"))
150
+ if count is None:
151
+ return None
152
+ return count * _item_size(ref.get("dtype"))
153
+
154
+
155
+ def _reference(ref: Any, *, label: str) -> dict[str, Any]:
156
+ if not isinstance(ref, Mapping):
157
+ raise RouteError(f"{label} must be an object")
158
+ value = _payload_free(ref, label)
159
+ role = _text(value.get("role"), f"{label}.role")
160
+ source_handle = _text(value.get("source_handle"), f"{label}.source_handle")
161
+ sha256 = str(value.get("sha256") or "").removeprefix("sha256:")
162
+ if _SHA256_RE.fullmatch(sha256) is None:
163
+ raise RouteError(f"{label}.sha256 must be a lowercase SHA-256 digest")
164
+ shape = value.get("shape")
165
+ if shape is not None and _numel(shape) is None:
166
+ raise RouteError(f"{label}.shape must contain non-negative dimensions")
167
+ return {**value, "role": role, "source_handle": source_handle, "sha256": sha256}
168
+
169
+
170
+ def _artifact_key(ref: Mapping[str, Any]) -> str:
171
+ return "|".join(
172
+ (str(ref.get("source_handle") or ""), str(ref.get("role") or ""), str(ref["sha256"]))
173
+ )
174
+
175
+
176
+ def _operation_spec(operation: Any) -> dict[str, Any]:
177
+ if not isinstance(operation, Mapping):
178
+ raise RouteError("operation must be an object")
179
+ value = _payload_free(operation, "operation")
180
+ kind = _text(value.get("kind"), "operation.kind")
181
+ if kind not in _BUILTIN_OPERATIONS and "operation_id" not in value:
182
+ raise RouteError(
183
+ "operation.kind must be add, replace, or zero, or declare operation_id/version "
184
+ "and be hydrated with an explicit builder"
185
+ )
186
+ address = _text(value.get("address"), "operation.address")
187
+ spec: dict[str, Any] = {"kind": kind, "address": address}
188
+ if kind in _VALUE_OPERATIONS:
189
+ dose = value.get("dose", 1)
190
+ if isinstance(dose, bool) or not isinstance(dose, (int, float)):
191
+ raise RouteError("operation.dose must be numeric")
192
+ if not math.isfinite(float(dose)):
193
+ raise RouteError("operation.dose must be finite")
194
+ spec["dose"] = dose
195
+ for carry in ("operation_id", "operation_version"):
196
+ if value.get(carry) is not None:
197
+ spec[carry] = str(value[carry])
198
+ return spec
199
+
200
+
201
+ # --- the content-addressed metadata record for one measured delta -----------------------
202
+
203
+
204
+ @dataclass(frozen=True)
205
+ class DeltaCard:
206
+ """A tensor-free, content-addressed description of one measured intervention delta."""
207
+
208
+ card_id: str
209
+ recipient: Mapping[str, Any]
210
+ tags: Mapping[str, Any]
211
+ operation: Mapping[str, Any]
212
+ artifact_refs: tuple[Mapping[str, Any], ...] = ()
213
+ act_manifest: Mapping[str, Any] | None = None
214
+ effect: Mapping[str, Any] = field(default_factory=dict)
215
+ claim_boundary: str = DEFAULT_CLAIM_BOUNDARY
216
+ limitations: tuple[str, ...] = ()
217
+ schema: str = DELTA_CARD_SCHEMA
218
+
219
+ def __post_init__(self) -> None:
220
+ if self.schema != DELTA_CARD_SCHEMA:
221
+ raise RouteError(f"unsupported delta-card schema {self.schema!r}")
222
+ object.__setattr__(self, "card_id", _text(self.card_id, "card_id"))
223
+ recipient = _payload_free(self.recipient, "recipient")
224
+ for required in ("model_identity", "execution", "boundary", "parent_fingerprint"):
225
+ if required not in recipient:
226
+ raise RouteError(f"recipient must declare {required}")
227
+ object.__setattr__(self, "recipient", recipient)
228
+ tags = _payload_free(self.tags, "tags")
229
+ if not isinstance(tags, Mapping) or not tags:
230
+ raise RouteError("tags must be a non-empty object of selectable scalars")
231
+ for key, item in tags.items():
232
+ if isinstance(item, bool) or not isinstance(item, (str, int)):
233
+ raise RouteError(f"tag {key!r} must be a string or integer")
234
+ object.__setattr__(self, "tags", tags)
235
+ object.__setattr__(self, "operation", _operation_spec(self.operation))
236
+ refs = tuple(
237
+ _reference(ref, label=f"artifact_refs[{i}]") for i, ref in enumerate(self.artifact_refs)
238
+ )
239
+ roles = [ref["role"] for ref in refs]
240
+ if len(set(roles)) != len(roles):
241
+ raise RouteError("artifact_refs roles must be unique")
242
+ kind = self.operation["kind"]
243
+ if kind in _VALUE_OPERATIONS and "value" not in roles:
244
+ raise RouteError(f"{kind} operation requires an artifact_ref with role 'value'")
245
+ if kind == "zero" and refs:
246
+ raise RouteError("zero operation does not reference any artifact")
247
+ object.__setattr__(self, "artifact_refs", refs)
248
+ if self.act_manifest is not None:
249
+ object.__setattr__(
250
+ self, "act_manifest", _payload_free(self.act_manifest, "act_manifest")
251
+ )
252
+ object.__setattr__(self, "effect", _payload_free(self.effect or {}, "effect"))
253
+ object.__setattr__(self, "claim_boundary", _text(self.claim_boundary, "claim_boundary"))
254
+ limitations = tuple(_text(item, "limitations") for item in self.limitations)
255
+ object.__setattr__(self, "limitations", limitations)
256
+
257
+ @property
258
+ def fingerprint(self) -> str:
259
+ return _fingerprint(self.to_dict(include_fingerprint=False))
260
+
261
+ def ref(self, role: str = "value") -> Mapping[str, Any]:
262
+ for candidate in self.artifact_refs:
263
+ if candidate["role"] == role:
264
+ return candidate
265
+ raise RouteError(f"delta card has no artifact ref for role {role!r}")
266
+
267
+ def to_dict(self, *, include_fingerprint: bool = True) -> dict[str, Any]:
268
+ payload = {
269
+ "schema": self.schema,
270
+ "card_id": self.card_id,
271
+ "recipient": dict(self.recipient),
272
+ "tags": dict(self.tags),
273
+ "operation": dict(self.operation),
274
+ "artifact_refs": [dict(ref) for ref in self.artifact_refs],
275
+ "act_manifest": None if self.act_manifest is None else dict(self.act_manifest),
276
+ "effect": dict(self.effect),
277
+ "claim_boundary": self.claim_boundary,
278
+ "limitations": list(self.limitations),
279
+ }
280
+ if include_fingerprint:
281
+ payload["fingerprint"] = self.fingerprint
282
+ return payload
283
+
284
+ @classmethod
285
+ def from_dict(cls, payload: Mapping[str, Any]) -> DeltaCard:
286
+ if not isinstance(payload, Mapping):
287
+ raise RouteError("delta card payload must be an object")
288
+ card = cls(
289
+ card_id=str(payload.get("card_id") or ""),
290
+ recipient=payload.get("recipient") or {},
291
+ tags=payload.get("tags") or {},
292
+ operation=payload.get("operation") or {},
293
+ artifact_refs=tuple(payload.get("artifact_refs") or ()),
294
+ act_manifest=payload.get("act_manifest"),
295
+ effect=payload.get("effect") or {},
296
+ claim_boundary=str(payload.get("claim_boundary") or DEFAULT_CLAIM_BOUNDARY),
297
+ limitations=tuple(payload.get("limitations") or ()),
298
+ schema=str(payload.get("schema") or DELTA_CARD_SCHEMA),
299
+ )
300
+ supplied = payload.get("fingerprint")
301
+ if supplied and str(supplied) != card.fingerprint:
302
+ raise RouteError("delta card fingerprint does not match its content")
303
+ return card
304
+
305
+ @classmethod
306
+ def from_act(
307
+ cls,
308
+ *,
309
+ card_id: str,
310
+ parent: StateCut,
311
+ act: Act,
312
+ tags: Mapping[str, Any],
313
+ source_handle: str,
314
+ effect: Mapping[str, Any] | None = None,
315
+ limitations: Sequence[str] = (),
316
+ ) -> DeltaCard:
317
+ """Save a measured builtin-operation ``Act`` (bound to ``parent``) as a card.
318
+
319
+ The heavy delta tensor is never embedded: its content address (sha256,
320
+ shape, dtype) is read from the Act's own sealed parameters and recorded
321
+ as an artifact reference that a resolver fetches at hydration time.
322
+ """
323
+ operation_id = act.operation_id
324
+ kind = next(
325
+ (name for name, oid in _BUILTIN_OPERATIONS.items() if oid == operation_id), None
326
+ )
327
+ if kind is None:
328
+ raise RouteError(
329
+ "from_act supports the builtin add/replace/zero operations; for a custom "
330
+ "operation, build DeltaCard directly with an explicit operation spec"
331
+ )
332
+ if len(act.writes) != 1:
333
+ raise RouteError("delta operation must write exactly one address")
334
+ address = act.writes[0]
335
+ manifest = act.manifest()
336
+ operation: dict[str, Any] = {"kind": kind, "address": address}
337
+ refs: list[dict[str, Any]] = []
338
+ if kind in _VALUE_OPERATIONS:
339
+ described = describe(act.parameters["value"])
340
+ if not isinstance(described, Mapping) or described.get("kind") != "tensor":
341
+ raise RouteError(f"{kind} delta requires a tensor value")
342
+ operation["dose"] = act.parameters.get("dose", 1)
343
+ refs.append(
344
+ {
345
+ "role": "value",
346
+ "sha256": described["sha256"],
347
+ "shape": list(described["shape"]),
348
+ "dtype": str(described["dtype"]),
349
+ "source_handle": source_handle,
350
+ "bytes": _declared_bytes(
351
+ {"shape": described["shape"], "dtype": described["dtype"]}
352
+ ),
353
+ }
354
+ )
355
+ return cls(
356
+ card_id=card_id,
357
+ recipient={
358
+ "model_identity": parent.model_identity,
359
+ "execution": dict(parent.execution),
360
+ "boundary": parent.boundary,
361
+ "parent_fingerprint": parent.fingerprint,
362
+ },
363
+ tags=tags,
364
+ operation=operation,
365
+ artifact_refs=tuple(refs),
366
+ act_manifest=manifest,
367
+ effect=effect or {},
368
+ limitations=tuple(limitations),
369
+ )
370
+
371
+
372
+ # --- the payload-free catalog with lazy, deduplicated, byte-accounted hydration ---------
373
+
374
+ Resolver = Callable[[Mapping[str, Any]], Any]
375
+ Builder = Callable[["DeltaCard", Mapping[str, Any]], Act]
376
+
377
+
378
+ class MetadataDeltaRoute:
379
+ """A metadata index over many :class:`DeltaCard`s with lazy, accounted hydration."""
380
+
381
+ def __init__(
382
+ self,
383
+ cards: Sequence[DeltaCard | Mapping[str, Any]],
384
+ *,
385
+ transport: Mapping[str, Any] | None = None,
386
+ ) -> None:
387
+ parsed: list[DeltaCard] = []
388
+ seen: set[str] = set()
389
+ for card in cards:
390
+ card = card if isinstance(card, DeltaCard) else DeltaCard.from_dict(card)
391
+ if card.card_id in seen:
392
+ raise RouteError(f"duplicate card_id {card.card_id!r}")
393
+ seen.add(card.card_id)
394
+ parsed.append(card)
395
+ self.cards: tuple[DeltaCard, ...] = tuple(parsed)
396
+ self._by_id = {card.card_id: card for card in self.cards}
397
+ self._index: dict[str, dict[str, set[str]]] = {}
398
+ for card in self.cards:
399
+ for key, value in card.tags.items():
400
+ self._index.setdefault(key, {}).setdefault(str(value), set()).add(card.card_id)
401
+ self.transport = _payload_free(transport or {}, "transport")
402
+ self._cache: dict[str, Any] = {}
403
+ self._metrics = {
404
+ "metadata_queries": 0,
405
+ "metadata_rows_returned": 0,
406
+ "artifact_requests": 0,
407
+ "artifact_hydrations": 0,
408
+ "artifact_cache_hits": 0,
409
+ "declared_bytes_requested": 0,
410
+ "hydrated_bytes": 0,
411
+ }
412
+
413
+ @property
414
+ def fingerprint(self) -> str:
415
+ return _fingerprint(
416
+ {
417
+ "schema": METADATA_DELTA_ROUTE_SCHEMA,
418
+ "cards": [card.fingerprint for card in self.cards],
419
+ "transport": self.transport,
420
+ }
421
+ )
422
+
423
+ @property
424
+ def declared_total_bytes(self) -> int:
425
+ total = 0
426
+ for card in self.cards:
427
+ for ref in card.artifact_refs:
428
+ declared = _declared_bytes(ref)
429
+ if declared is not None:
430
+ total += declared
431
+ return total
432
+
433
+ def to_dict(self) -> dict[str, Any]:
434
+ return {
435
+ "schema": METADATA_DELTA_ROUTE_SCHEMA,
436
+ "fingerprint": self.fingerprint,
437
+ "transport": dict(self.transport),
438
+ "cards": [card.to_dict() for card in self.cards],
439
+ }
440
+
441
+ @classmethod
442
+ def from_dict(cls, payload: Mapping[str, Any]) -> MetadataDeltaRoute:
443
+ if not isinstance(payload, Mapping) or payload.get("schema") != METADATA_DELTA_ROUTE_SCHEMA:
444
+ raise RouteError("unsupported metadata-delta-route payload")
445
+ route = cls(payload.get("cards") or (), transport=payload.get("transport") or {})
446
+ supplied = payload.get("fingerprint")
447
+ if supplied and str(supplied) != route.fingerprint:
448
+ raise RouteError("metadata-delta-route fingerprint does not match its content")
449
+ return route
450
+
451
+ def select(
452
+ self,
453
+ *,
454
+ card_id: str | None = None,
455
+ tags: Mapping[str, Any] | None = None,
456
+ **keyword_tags: Any,
457
+ ) -> tuple[DeltaCard, ...]:
458
+ """Return matching cards from metadata only -- no artifact bytes are touched."""
459
+ query: dict[str, Any] = {}
460
+ for source in (tags or {}, keyword_tags):
461
+ for key, value in source.items():
462
+ if value is None:
463
+ continue
464
+ if key in query and query[key] != value:
465
+ raise RouteError(f"conflicting selection for tag {key!r}")
466
+ query[key] = value
467
+ candidate_ids: set[str] | None = None
468
+ if card_id is not None:
469
+ candidate_ids = {card_id} & set(self._by_id)
470
+ for key, value in query.items():
471
+ matches = set(self._index.get(key, {}).get(str(value), ()))
472
+ candidate_ids = matches if candidate_ids is None else candidate_ids & matches
473
+ ids = set(self._by_id) if candidate_ids is None else candidate_ids
474
+ rows = sorted((self._by_id[i] for i in ids), key=lambda card: card.card_id)
475
+ self._metrics["metadata_queries"] += 1
476
+ self._metrics["metadata_rows_returned"] += len(rows)
477
+ return tuple(rows)
478
+
479
+ def project(
480
+ self, cards: Sequence[DeltaCard] | None = None, *, fields: Sequence[str] = ()
481
+ ) -> list[dict[str, Any]]:
482
+ """A deterministic, payload-free projection of cards for parity checks."""
483
+ rows = self.cards if cards is None else tuple(cards)
484
+ fields = tuple(fields) or ("card_id", "tags", "operation")
485
+ projected = []
486
+ for card in sorted(rows, key=lambda card: card.card_id):
487
+ payload = card.to_dict()
488
+ projected.append({field: payload.get(field) for field in fields})
489
+ return projected
490
+
491
+ def hydrate(
492
+ self,
493
+ card: DeltaCard | str,
494
+ resolver: Resolver,
495
+ *,
496
+ builder: Builder | None = None,
497
+ ) -> Act:
498
+ """Resolve a card's referenced bytes (lazily, deduplicated) and rebuild its Act.
499
+
500
+ ``resolver`` is caller-owned so the catalog works against an in-memory
501
+ store, a local content-addressed directory, or a remote object store
502
+ without duplicating custody. Each resolved value is content-verified
503
+ against its reference (sha256, shape, dtype) before it is admitted.
504
+ """
505
+ card = card if isinstance(card, DeltaCard) else self._by_id[card]
506
+ values: dict[str, Any] = {}
507
+ for ref in card.artifact_refs:
508
+ key = _artifact_key(ref)
509
+ self._metrics["artifact_requests"] += 1
510
+ declared = _declared_bytes(ref)
511
+ if declared is not None:
512
+ self._metrics["declared_bytes_requested"] += declared
513
+ if key in self._cache:
514
+ value = self._cache[key]
515
+ self._metrics["artifact_cache_hits"] += 1
516
+ else:
517
+ value = resolver(ref)
518
+ self._verify(ref, value)
519
+ self._cache[key] = value
520
+ self._metrics["artifact_hydrations"] += 1
521
+ if declared is not None:
522
+ self._metrics["hydrated_bytes"] += declared
523
+ values[ref["role"]] = value
524
+ act = self._build(card, values) if builder is None else builder(card, values)
525
+ if not isinstance(act, Act):
526
+ raise RouteError("builder did not produce an Act")
527
+ act.verify_implementation()
528
+ if card.act_manifest is not None and act.manifest() != dict(card.act_manifest):
529
+ raise RouteError("hydrated Act does not match the card's measured operation")
530
+ return act
531
+
532
+ @staticmethod
533
+ def _verify(ref: Mapping[str, Any], value: Any) -> None:
534
+ summary = describe(value)
535
+ if not isinstance(summary, Mapping) or summary.get("kind") != "tensor":
536
+ raise RouteError(f"resolved artifact {ref['role']!r} is not a tensor")
537
+ if summary["sha256"] != ref["sha256"]:
538
+ raise RouteError(
539
+ f"resolved artifact {ref['role']!r} content does not match its address"
540
+ )
541
+ if ref.get("shape") is not None and list(summary["shape"]) != list(ref["shape"]):
542
+ raise RouteError(
543
+ f"resolved artifact {ref['role']!r} shape does not match its reference"
544
+ )
545
+ if ref.get("dtype") and str(summary["dtype"]) != str(ref["dtype"]):
546
+ raise RouteError(
547
+ f"resolved artifact {ref['role']!r} dtype does not match its reference"
548
+ )
549
+
550
+ @staticmethod
551
+ def _build(card: DeltaCard, values: Mapping[str, Any]) -> Act:
552
+ operation = card.operation
553
+ kind = operation["kind"]
554
+ address = operation["address"]
555
+ if kind == "zero":
556
+ return Act.zero(address)
557
+ value = values["value"]
558
+ if kind == "add":
559
+ return Act.add(address, value, dose=operation.get("dose", 1))
560
+ if kind == "replace":
561
+ return Act.replace(address, value)
562
+ raise RouteError(
563
+ f"operation kind {kind!r} needs an explicit builder; no builtin constructor"
564
+ )
565
+
566
+ def receipt(self) -> dict[str, Any]:
567
+ """Compact custody accounting -- never exposes a cached payload."""
568
+ declared_total = self.declared_total_bytes
569
+ hydrated = self._metrics["hydrated_bytes"]
570
+ selected = self.transport.get("selected_bytes_estimate", hydrated)
571
+ dense = self.transport.get("dense_bytes_estimate", declared_total)
572
+ reduction = (1.0 - selected / dense) if dense and selected is not None else None
573
+ return {
574
+ "schema": ROUTE_EXECUTION_SCHEMA,
575
+ "route_fingerprint": self.fingerprint,
576
+ "raw_payloads_embedded": False,
577
+ "card_count": len(self.cards),
578
+ "declared_total_bytes": declared_total,
579
+ "transport": {
580
+ "policy": "metadata_plus_selected_delta",
581
+ "dense_bytes_estimate": dense,
582
+ "selected_bytes_estimate": selected,
583
+ "estimated_reduction": reduction,
584
+ },
585
+ "cache": dict(self._metrics),
586
+ }
587
+
588
+
589
+ # --- the thin lifecycle bridge: apply a selected delta, compare to native, roll back -----
590
+
591
+
592
+ def apply_delta(
593
+ session: Session,
594
+ acts: Act | Sequence[Act],
595
+ *,
596
+ continuation_steps: int = 0,
597
+ evaluator: Callable[[Session], Mapping[str, Any]] | None = None,
598
+ parent: StateCut | None = None,
599
+ ) -> dict[str, Any]:
600
+ """Fork a candidate and a native branch from one parent, apply the delta, compare, roll back.
601
+
602
+ Returns the two branches plus a sealed route-execution receipt. The receipt's
603
+ ``rollback.verified_exact`` is True and ``rollback.restored_elements`` counts
604
+ every restored tensor element -- the public analog of an exact rollback. This
605
+ reuses ``Session.apply`` / ``continue_`` / ``compare`` / ``restore``; it does
606
+ not reimplement them.
607
+ """
608
+ acts = (acts,) if isinstance(acts, Act) else tuple(acts)
609
+ if not acts:
610
+ raise RouteError("apply_delta requires at least one Act")
611
+ parent = parent or session.capture()
612
+ if continuation_steps < 0:
613
+ raise RouteError("continuation_steps must be non-negative")
614
+
615
+ native = session.fork(parent)
616
+ candidate = session.fork(parent)
617
+ apply_receipts = [candidate.apply(act).to_dict() for act in acts]
618
+ if continuation_steps:
619
+ native.continue_(continuation_steps)
620
+ candidate.continue_(continuation_steps)
621
+ comparison = candidate.compare(native, evaluator)
622
+ rollback = candidate.restore(parent)
623
+ rollback_row = rollback.to_dict()
624
+
625
+ restored_slots, restored_elements = _count_elements(parent)
626
+ verified = bool(rollback_row.get("verified_exact")) and (
627
+ rollback_row.get("result") == parent.fingerprint
628
+ )
629
+ receipt = {
630
+ "schema": ROUTE_EXECUTION_SCHEMA,
631
+ "model_identity": session.adapter.model_identity,
632
+ "parent": parent.fingerprint,
633
+ "entry_boundary": parent.boundary,
634
+ "continuation_steps": continuation_steps,
635
+ "apply": apply_receipts,
636
+ "effect": {
637
+ "equal_payload": comparison["equal_payload"],
638
+ "changed_vs_native": not comparison["equal_payload"],
639
+ **({"metrics": comparison["metrics"]} if "metrics" in comparison else {}),
640
+ },
641
+ "rollback": {
642
+ "verified_exact": verified,
643
+ "restored": rollback_row.get("result"),
644
+ "matches_parent": rollback_row.get("result") == parent.fingerprint,
645
+ "restored_slots": restored_slots,
646
+ "restored_elements": restored_elements,
647
+ "receipt": rollback_row,
648
+ },
649
+ "raw_payloads_embedded": False,
650
+ }
651
+ receipt["fingerprint"] = _fingerprint(receipt)
652
+ return {
653
+ "native": native,
654
+ "candidate": candidate,
655
+ "parent": parent,
656
+ "comparison": comparison,
657
+ "rollback": rollback,
658
+ "receipt": receipt,
659
+ }
660
+
661
+
662
+ def _count_elements(cut: StateCut) -> tuple[int, int]:
663
+ """Count durable tensor slots and total tensor elements in a cut's payload."""
664
+
665
+ def walk(value: Any) -> tuple[int, int]:
666
+ summary = describe(value)
667
+ return _walk_described(summary)
668
+
669
+ def _walk_described(summary: Any) -> tuple[int, int]:
670
+ if isinstance(summary, Mapping) and summary.get("kind") == "tensor":
671
+ count = _numel(summary.get("shape")) or 0
672
+ return (1, count)
673
+ slots = elements = 0
674
+ if isinstance(summary, Mapping) and summary.get("kind") == "mapping":
675
+ for item in summary.get("items", ()):
676
+ s, e = _walk_described(item.get("value"))
677
+ slots += s
678
+ elements += e
679
+ elif isinstance(summary, Mapping) and summary.get("kind") in ("list", "tuple"):
680
+ for item in summary.get("items", ()):
681
+ s, e = _walk_described(item)
682
+ slots += s
683
+ elements += e
684
+ return (slots, elements)
685
+
686
+ total_slots = total_elements = 0
687
+ for value in cut.payload.values():
688
+ slots, elements = walk(value)
689
+ total_slots += slots
690
+ total_elements += elements
691
+ return total_slots, total_elements
692
+
693
+
694
+ # --- stdlib-only CLI (torch-free): inspect a saved route without touching any bytes ------
695
+
696
+
697
+ def _load_route(path: str) -> MetadataDeltaRoute:
698
+ try:
699
+ payload = json.loads(Path(path).expanduser().read_text(encoding="utf-8"))
700
+ except (OSError, json.JSONDecodeError) as exc:
701
+ raise RouteError(f"cannot read route JSON {path}") from exc
702
+ return MetadataDeltaRoute.from_dict(payload)
703
+
704
+
705
+ def _parse_tags(pairs: Sequence[str]) -> dict[str, Any]:
706
+ tags: dict[str, Any] = {}
707
+ for pair in pairs:
708
+ if "=" not in pair:
709
+ raise RouteError(f"--tag expects key=value, got {pair!r}")
710
+ key, _, raw = pair.partition("=")
711
+ key = key.strip()
712
+ raw = raw.strip()
713
+ tags[key] = int(raw) if re.fullmatch(r"-?\d+", raw) else raw
714
+ return tags
715
+
716
+
717
+ def main(argv: Sequence[str] | None = None) -> int:
718
+ parser = argparse.ArgumentParser(
719
+ description="Inspect a saved metadata-plus-delta route without hydrating any bytes"
720
+ )
721
+ sub = parser.add_subparsers(dest="command", required=True)
722
+ validate = sub.add_parser("validate", help="load a route JSON and print its custody receipt")
723
+ validate.add_argument("route")
724
+ select = sub.add_parser("select", help="select cards by tag from metadata only")
725
+ select.add_argument("route")
726
+ select.add_argument("--tag", action="append", default=[], help="key=value (repeatable)")
727
+ select.add_argument("--card-id")
728
+ show = sub.add_parser("show", help="print one card by id")
729
+ show.add_argument("route")
730
+ show.add_argument("card_id")
731
+ args = parser.parse_args(argv)
732
+ route = _load_route(args.route)
733
+ if args.command == "validate":
734
+ print(json.dumps(route.receipt(), indent=2, sort_keys=True))
735
+ return 0
736
+ if args.command == "select":
737
+ cards = route.select(card_id=args.card_id, tags=_parse_tags(args.tag))
738
+ print(
739
+ json.dumps(
740
+ {
741
+ "schema": ROUTE_EXECUTION_SCHEMA,
742
+ "route_fingerprint": route.fingerprint,
743
+ "selected": [card.card_id for card in cards],
744
+ "projection": route.project(cards),
745
+ "cache": route.receipt()["cache"],
746
+ },
747
+ indent=2,
748
+ sort_keys=True,
749
+ )
750
+ )
751
+ return 0
752
+ matches = [item for item in route.cards if item.card_id == args.card_id]
753
+ if not matches:
754
+ raise RouteError(f"unknown card_id {args.card_id!r}")
755
+ print(json.dumps(matches[0].to_dict(), indent=2, sort_keys=True))
756
+ return 0
757
+
758
+
759
+ __all__ = [
760
+ "DELTA_CARD_SCHEMA",
761
+ "DEFAULT_CLAIM_BOUNDARY",
762
+ "METADATA_DELTA_ROUTE_SCHEMA",
763
+ "ROUTE_EXECUTION_SCHEMA",
764
+ "SELECTION_KEYS",
765
+ "DeltaCard",
766
+ "MetadataDeltaRoute",
767
+ "RouteError",
768
+ "apply_delta",
769
+ "main",
770
+ ]
771
+
772
+
773
+ if __name__ == "__main__": # pragma: no cover - exercised through the console script
774
+ raise SystemExit(main())