model-debugger 0.4.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.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
mdb/core/bounded.py ADDED
@@ -0,0 +1,101 @@
1
+ """Bound a list that grows with the model to a cap, and store the full list by pointer.
2
+
3
+ One mechanism for every record or result list that grows with the layers or heads (the forecast
4
+ identity chain, the explain terms, the what-if operands): the record keeps ``cap`` items chosen
5
+ by a stated rule plus a summary (``count``, ``listed``, a ``rest`` summary, a ``pointer``), and
6
+ the full list is a sha256-checked JSON blob, put in a project ``LocalStore`` (a tensor pointer
7
+ to uint8 bytes) or, with no store, held in memory per ``run`` (``load_json`` resolves both).
8
+ Torch-free: numpy is imported only when a blob is stored or read from a store.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import weakref
16
+ from collections.abc import Callable, Mapping, Sequence
17
+ from typing import Any
18
+
19
+ MAX_ITEMS = 64 # the record's sequence bound (``core.pointers.MAX_INLINE_ITEMS``)
20
+ _HELD: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
21
+
22
+
23
+ def json_bytes(obj: Any) -> bytes:
24
+ """The canonical JSON bytes of ``obj`` (what the blob's sha256 is taken over)."""
25
+ return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
26
+
27
+
28
+ def put_json(obj: Any, *, store: Any = None, run: Any = None,
29
+ absent_reason: str | None = None) -> dict[str, Any]:
30
+ """Store ``obj`` and return its pointer. With ``store``: ``{state: "stored", ref, bytes,
31
+ sha256, tensor}`` (``tensor`` is the record-level tensor pointer). Without: ``{state:
32
+ "absent", sha256, reason}``, and ``obj`` is held in memory on ``run`` when one is given."""
33
+ raw = json_bytes(obj)
34
+ digest = hashlib.sha256(raw).hexdigest()
35
+ if store is not None:
36
+ import numpy as np
37
+
38
+ from mdb.core.pointers import tensor_pointer
39
+
40
+ stored = store.put_tensor(np.frombuffer(raw, dtype=np.uint8).copy())
41
+ return {"state": "stored", "ref": stored["ref"], "bytes": len(raw), "sha256": digest,
42
+ "tensor": tensor_pointer(stored["ref"], sha256=stored["sha256"],
43
+ shape=stored["shape"], dtype=stored["dtype"])}
44
+ if run is not None:
45
+ _HELD.setdefault(run, {})[digest] = raw # the bytes, so a held copy cannot change
46
+ from mdb.core import custody # an open record sink seals the bytes too
47
+
48
+ custody.emit_payload(digest, raw)
49
+ return {"state": "absent", "sha256": digest,
50
+ "reason": absent_reason or "no project store: the full list is held in memory on "
51
+ "the run (bounded.load_json), not stored"}
52
+
53
+
54
+ def load_json(pointer: Mapping[str, Any], *, store: Any = None, run: Any = None,
55
+ tensor: Mapping[str, Any] | None = None) -> Any:
56
+ """The full object ``pointer`` (from ``put_json``) points at: from ``store`` (checked
57
+ against ``pointer["sha256"]``; ``tensor`` overrides ``pointer["tensor"]``) or from the run's
58
+ in-memory copy. ``ValueError`` if absent or changed."""
59
+ if pointer["state"] == "stored":
60
+ from mdb.core.pointers import resolve_tensor
61
+
62
+ raw = resolve_tensor(tensor if tensor is not None else pointer["tensor"], store=store,
63
+ framework="numpy").tobytes()
64
+ if hashlib.sha256(raw).hexdigest() != pointer["sha256"]:
65
+ raise ValueError("the stored list differs from the pointer's sha256")
66
+ return json.loads(raw)
67
+ held = _HELD.get(run, {}).get(pointer["sha256"]) if run is not None else None
68
+ if held is None:
69
+ raise ValueError("the full list is not held: " + pointer.get("reason", "absent"))
70
+ if hashlib.sha256(held).hexdigest() != pointer["sha256"]:
71
+ raise ValueError("the held list differs from the pointer's sha256")
72
+ return json.loads(held)
73
+
74
+
75
+ def keep_indices(items: Sequence[Any], cap: int,
76
+ rank: Callable[[Any], Any] | None = None) -> list[int]:
77
+ """Indices (original order) of the ``cap`` items to keep: the ``cap`` smallest by ``rank``
78
+ (ties by position), or the first ``cap`` with no ``rank``."""
79
+ if rank is None:
80
+ return list(range(min(cap, len(items))))
81
+ order = sorted(range(len(items)), key=lambda i: (rank(items[i]), i))
82
+ return sorted(order[:cap])
83
+
84
+
85
+ def bound_list(items: Sequence[Any], cap: int = MAX_ITEMS, *, rank: Callable[[Any], Any] | None = None,
86
+ rest: Callable[[list[Any]], dict[str, Any]] | None = None, store: Any = None,
87
+ run: Any = None, keep: str = "") -> tuple[list[Any], dict[str, Any] | None]:
88
+ """``(kept, summary)``. Within ``cap`` the list is returned whole and ``summary`` is
89
+ ``None`` (nothing changes, nothing is stored). Over it ``kept`` is the ``keep_indices``
90
+ selection and ``summary`` is ``{count, listed, keep, rest: {count, **rest(rest_items)},
91
+ pointer}``; ``keep`` states the rule in words."""
92
+ if len(items) <= cap:
93
+ return list(items), None
94
+ chosen = keep_indices(items, cap, rank)
95
+ taken = set(chosen)
96
+ left = [x for i, x in enumerate(items) if i not in taken]
97
+ summary = {"count": len(items), "listed": len(chosen),
98
+ "keep": keep or ("the first " if rank is None else "the best ranked ") + str(cap),
99
+ "rest": {"count": len(left), **(rest(left) if rest else {})},
100
+ "pointer": put_json(list(items), store=store, run=run)}
101
+ return [items[i] for i in chosen], summary
@@ -0,0 +1,202 @@
1
+ """JSON Schemas (draft 2020-12) of a checkpoint (``mdb.engine.checkpoint``), built in code as
2
+ ``analysis.symbols.frame.json_schema`` builds the symbol-table ones. Standard library only, so a
3
+ reader validates a checkpoint record or document without torch.
4
+
5
+ ``json_schema(name)`` for ``name`` in ``SCHEMAS``:
6
+
7
+ * ``mdb-checkpoint-v2``: the state document (``checkpoint.build``), the JSON a checkpoint file
8
+ holds as its ``document`` member or a project stores as a JSON blob.
9
+ * ``checkpoint-state``: the body of the sealed ``checkpoint-state`` record (``checkpoint._body``;
10
+ its ``schema`` field is also ``mdb-checkpoint-v2``). The record envelope is ``mdb-record-v3``
11
+ (``core.records``) and is not repeated here.
12
+
13
+ Both are closed at the top level and where the engine writes a literal of fixed keys; mappings
14
+ whose keys belong to another layer (model identity, execution contract, lineage, custody, the
15
+ procedure, edit manifests and receipts, saturn's execution point and surface) are open
16
+ objects. ``docs/CHECKPOINT-SCHEMA.md`` describes every field and the hydrate path.
17
+
18
+ The self-contained file (``mdb-checkpoint-file-v2``) is a ``torch.save`` of
19
+ ``{schema, record, document, tensors}`` (``FILE_KEYS``), not JSON: ``record`` and ``document``
20
+ are JSON text, ``tensors`` maps ``part_key`` (``<sha256>.<dtype>.<d0>x<d1>...``, ``scalar`` for
21
+ a 0-d part) to the part tensor.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from typing import Any
26
+
27
+ DOCUMENT = "mdb-checkpoint-v2" # the state document; also the record body's ``schema``
28
+ FILE = "mdb-checkpoint-file-v2" # a self-contained checkpoint file (torch.save)
29
+ KIND = "checkpoint-state" # the record kind (``core.kinds.CHECKPOINT_STATE``)
30
+ FILE_KEYS = ("schema", "record", "document", "tensors")
31
+ SCHEMAS = (DOCUMENT, KIND)
32
+
33
+ _HEX = "^[0-9a-f]{64}$"
34
+ _SHA = {"type": "string", "pattern": _HEX}
35
+ _INT = {"type": "integer", "minimum": 0}
36
+ _INTS = {"type": "array", "items": _INT}
37
+ _OBJ = {"type": "object"}
38
+ _OBJS = {"type": "array", "items": _OBJ}
39
+
40
+
41
+ def _closed(required: dict[str, Any], optional: dict[str, Any] | None = None,
42
+ description: str | None = None) -> dict[str, Any]:
43
+ out = {"type": "object", "required": list(required),
44
+ "properties": {**required, **(optional or {})}, "additionalProperties": False}
45
+ if description:
46
+ out["description"] = description
47
+ return out
48
+
49
+
50
+ def _null(schema: dict[str, Any]) -> dict[str, Any]:
51
+ return {"anyOf": [schema, {"type": "null"}]}
52
+
53
+
54
+ # a value of a cut's state, encoded (``_Writer.encode``): tensors by descriptor index
55
+ _VALUE = {"oneOf": [
56
+ _closed({"kind": {"const": "tensor"}, "t": _INT}),
57
+ _closed({"kind": {"const": "mapping"},
58
+ "items": {"type": "object", "additionalProperties": {"$ref": "#/$defs/value"}}}),
59
+ _closed({"kind": {"enum": ["list", "tuple"]},
60
+ "items": {"type": "array", "items": {"$ref": "#/$defs/value"}}}),
61
+ _closed({"kind": {"const": "scalar"},
62
+ "value": {"type": ["null", "boolean", "integer", "number", "string"]}}),
63
+ ]}
64
+
65
+ _CUT = _closed({
66
+ "boundary": {"type": "string"},
67
+ "parent": _null(_SHA),
68
+ "execution_point": _null(_OBJ),
69
+ "surface": _null(_OBJ),
70
+ "payload": {"$ref": "#/$defs/value"},
71
+ }, description="a kept native StateCut: fingerprint inputs and the encoded state")
72
+
73
+ _MARK = _closed({
74
+ "fingerprint": _SHA, "transitions": _INT, "row": _INT, "label": {"type": "string"},
75
+ "phase": {"type": "string"}, "layer": {"type": "integer"},
76
+ "supplied": _null({"type": "integer"}),
77
+ "cut": _null({"$ref": "#/$defs/cut"}),
78
+ "edits": _OBJS, "cells": _OBJS, "fired": _OBJS, "cell_fired": _OBJS,
79
+ }, description="a trail mark; edits/cells/fired/cell_fired are the committed transition after "
80
+ "it (empty for the cursor's own mark)")
81
+
82
+ _PART = _closed({"sha256": _SHA, "shape": _INTS, "dtype": {"type": "string"}},
83
+ {"ref": _SHA},
84
+ description="one content-addressed tensor part; ref: the project store blob")
85
+
86
+ _TENSOR = _closed({
87
+ "dtype": {"type": "string"}, "shape": _INTS, "stride": _INTS,
88
+ "axis": _null(_INT), "parts": _INTS,
89
+ }, description="a held tensor as parts concatenated along axis (None: one part)")
90
+
91
+ _HOLD = {"type": "object",
92
+ "required": ["name", "address", "port", "layers", "rows", "source", "kind", "writes",
93
+ "cells", "dropped"],
94
+ "properties": {
95
+ "name": {"type": "string"}, "address": {"type": "string"},
96
+ "port": {"type": "string"}, "layers": _INTS, "rows": _null(_INTS),
97
+ "source": {"type": "string"}, "kind": {"enum": ["value", "norm-scale"]},
98
+ "writes": {"type": "array", "items": {"type": "string"}}, "cells": _OBJS,
99
+ "dropped": {"type": "boolean"},
100
+ "snapshot": _closed({
101
+ "source": {"type": "string"}, "where": {"type": "string"}, "cut": _SHA,
102
+ "tokens": _INTS,
103
+ "values": {"type": "object", "additionalProperties": _INT}})},
104
+ "additionalProperties": False}
105
+
106
+ _TEXT = {"type": "string"}
107
+ _RECIPE = _closed({
108
+ "schema": {"const": "mdb-engine-checkpoint-v1"}, "name": _null(_TEXT),
109
+ "model_identity": {}, "prompt_sha256": _SHA, "prefill": _INT, "where": _TEXT, "cut": _SHA,
110
+ "transitions": _INT, "port": _null(_TEXT), "lookahead": {"enum": ["none", "layer", "auto"]},
111
+ "numeric_scope": _OBJ, "edits": _OBJS, "path_edits": _OBJS,
112
+ }, {"supplied": {"type": "array"}}, description="Run.checkpoint() at the cut: restore input")
113
+
114
+ _LINEAGE = {"type": "object", "required": ["root"],
115
+ "properties": {"root": {"enum": ["prompt", "checkpoint"]},
116
+ "checkpoints": {"type": "array", "items": _SHA}}}
117
+
118
+ _DOCUMENT_PROPERTIES: dict[str, Any] = {
119
+ "schema": {"const": DOCUMENT},
120
+ "name": _null({"type": "string"}),
121
+ "model_identity": {"description": "adapter.model_identity (text or mapping)"},
122
+ "execution": {**_OBJ, "description": "adapter.execution: the execution contract"},
123
+ "shape": {"$ref": "#/$defs/shape"},
124
+ "prompt": _INTS,
125
+ "prefill": _INT,
126
+ "lookahead": {"enum": ["none", "layer", "auto"]},
127
+ "history": {"enum": ["cursor", "row", "root"]},
128
+ "where": {"type": "string"},
129
+ "cursor": _closed({"port": _null({"type": "string"}), "edits": _OBJS, "cells": _OBJS}),
130
+ "ancestry": {"type": "array", "items": {"$ref": "#/$defs/mark"}},
131
+ "marks": {"type": "array", "items": {"$ref": "#/$defs/mark"}, "minItems": 1},
132
+ "edit_tensors": {"type": "object", "propertyNames": {"pattern": _HEX},
133
+ "additionalProperties": _INT},
134
+ "captured": {"type": "object", "additionalProperties": _INT},
135
+ "holds": {"type": "array", "items": _HOLD},
136
+ "recipe": _RECIPE,
137
+ "lineage": _LINEAGE,
138
+ "parts": {"type": "array", "items": {"$ref": "#/$defs/part"}},
139
+ "tensors": {"type": "array", "items": {"$ref": "#/$defs/tensor"}},
140
+ }
141
+
142
+ _SHAPE = _closed({"family": {"type": "string"}, "layers": _INT, "kv_heads": _INT,
143
+ "head_dim": _INT, "vocab": _INT})
144
+ _PLACE = _closed({"fingerprint": _SHA, "transitions": _INT, "row": _INT,
145
+ "label": {"type": "string"}})
146
+ _DOCUMENT_POINTER = {"oneOf": [
147
+ _closed({"state": {"const": "file"}, "bytes": _INT, "sha256": _SHA}),
148
+ _closed({"state": {"const": "stored"}, "ref": _SHA, "bytes": _INT, "sha256": _SHA,
149
+ "tensor": _closed({"kind": {"const": "tensor"}, "ref": _SHA, "sha256": _SHA,
150
+ "shape": _INTS, "dtype": {"type": "string"}})}),
151
+ ]}
152
+
153
+ _BODY_PROPERTIES: dict[str, Any] = {
154
+ "schema": {"const": DOCUMENT},
155
+ "name": _null({"type": "string"}),
156
+ "where": {"type": "string"},
157
+ "port": _null({"type": "string"}),
158
+ "cut": _PLACE,
159
+ "root": _PLACE,
160
+ "history": {"enum": ["cursor", "row", "root"]},
161
+ "marks": _INT,
162
+ "stored_cuts": _INT,
163
+ "prompt": _closed({"tokens": {**_INTS, "maxItems": 64}, "length": _INT, "sha256": _SHA}),
164
+ "procedure": {"type": "object", "required": ["prefill", "first_row", "prompt_rows"]},
165
+ "shape": _SHAPE,
166
+ "source": _closed({"dtype": {"type": "string"}, "device": {"type": "string"}}),
167
+ "lineage": _LINEAGE,
168
+ "recipe": _closed({"sha256": _SHA, "path_edits": _INT, "staged": _INT}),
169
+ "edited": {"type": "boolean"},
170
+ "holds": {"type": "array", "maxItems": 64, "items": _closed({
171
+ "name": {"type": "string"}, "address": {"type": "string"},
172
+ "dropped": {"type": "boolean"}})},
173
+ "captured": {"type": "array", "maxItems": 64, "items": {"type": "string"}},
174
+ "document": _DOCUMENT_POINTER,
175
+ "tensors": _closed({
176
+ "count": _INT,
177
+ "sha256": _null({"type": "array", "maxItems": 60,
178
+ "items": {"type": "string", "pattern": "^([0-9a-f]{64}){1,60}$"}}),
179
+ "parts_sha256": _SHA}),
180
+ "bytes": _closed({"value": {"type": "number", "minimum": 0},
181
+ "authority": {"const": "measured"}}),
182
+ "custody": {"type": "object", "required": ["schema"]},
183
+ }
184
+ _BODY_OPTIONAL = {"store": _closed({"uri": {"type": "string"}})}
185
+
186
+
187
+ def json_schema(name: str = DOCUMENT) -> dict[str, Any]:
188
+ """The JSON Schema (draft 2020-12) of ``name``: ``mdb-checkpoint-v2`` (the state document)
189
+ or ``checkpoint-state`` (the sealed record's body)."""
190
+ if name not in SCHEMAS:
191
+ raise ValueError(f"schema is one of {SCHEMAS}")
192
+ base: dict[str, Any] = {"$schema": "https://json-schema.org/draft/2020-12/schema",
193
+ "$id": f"https://mdb.local/schemas/{name}.json", "title": name}
194
+ if name == DOCUMENT:
195
+ return {**base, **_closed(_DOCUMENT_PROPERTIES), "$defs": {
196
+ "value": _VALUE, "cut": _CUT, "mark": _MARK, "part": _PART, "tensor": _TENSOR,
197
+ "shape": _SHAPE}}
198
+ return {**base, **_closed(_BODY_PROPERTIES, _BODY_OPTIONAL),
199
+ "x-record-kind": {"kind": KIND, "schema": "mdb-record-v3"}}
200
+
201
+
202
+ __all__ = ["DOCUMENT", "FILE", "FILE_KEYS", "KIND", "SCHEMAS", "json_schema"]