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/records.py ADDED
@@ -0,0 +1,1027 @@
1
+ """One sealed record envelope, generalised from ``circuit_investigation.save/record``.
2
+
3
+ A record, as every caller sees it (the *logical* record; the same fields in v2 and v3)::
4
+
5
+ {schema: "mdb-record-v3", id, session_id, kind, model_identity, execution, authority,
6
+ pointers: [...], body, digest}
7
+
8
+ Schema v3 (written by ``seal_record`` from mdb 0.2.2). Its *stored form* (``stored_form``: the
9
+ canonical UTF-8 JSON that the digest covers, that ``put_record`` writes and a sink appends) is
10
+ the logical record with two changes:
11
+
12
+ * ``execution`` is replaced by ``execution_sha256`` (``seal_digest(execution)``). The execution
13
+ profile is the session's, so it is kept once: in the project's session row, or as one
14
+ ``{"mdb_execution": ...}`` line per sink file. A reader passes it back (``load_record``).
15
+ * the ``values`` of a column claim (``nums``) are the base64 of their little-endian bytes.
16
+
17
+ ``digest`` = ``id`` = ``seal_digest`` of the stored form without ``id`` and ``digest``, so the
18
+ id still binds every field, the execution profile included (through its sha256). The stored
19
+ form is at most ``MAX_RECORD_BYTES_V3`` (1 MiB); the structure outside column values is bounded
20
+ as in v2 (no arrays or tensors, at most 64 inline items per sequence, at most
21
+ ``MAX_RECORD_ITEMS_V3`` values). A column claim holds up to ``MAX_NUMS_INLINE`` values inline;
22
+ more go to a tensor blob by pointer (``nums(..., store=)``).
23
+
24
+ Schema v2 (``mdb-record-v2``, mdb <= 0.2.1) is read and verified unchanged: its stored form is
25
+ the canonical JSON of the logical record, at most 64 KiB (``MAX_RECORD_BYTES``), and it has no
26
+ column claims. ``migrate_record`` writes the v3 twin of a v2 record (same content, new id);
27
+ ``mdb.core.migrate`` does it for files.
28
+
29
+ Authority rule, enforced by ``seal_record`` and ``verify_record`` for every kind: inside
30
+ ``body`` every numeric leaf (int or float, never bool) must be the ``value`` of a labelled
31
+ number ``num(value, authority, ...)`` (exact key set, real finite value, one of the five
32
+ authorities), unless it sits at a path the kind declares structural (``plain_numeric``: shapes, indices,
33
+ counts, ids, byte sizes). A declared path exempts only a *leaf* that is a non-negative ``int``
34
+ (never a bool, at most 15 decimal digits, so it is exact in JSON/JS) or a list of such ints; it
35
+ covers a whole subtree only when it ends in an explicit ``**`` marker, and even then only
36
+ non-negative ints are exempt. Lists, tuples and mappings are walked fully. The
37
+ kind's ``numeric`` paths must exist and hold labelled numbers; a labelled-number mapping with
38
+ extra keys is an error; NaN and +-Inf are refused everywhere. Sealing or verifying a record of
39
+ an undeclared kind is refused. Pointers must be of a known kind (file, parameter, run,
40
+ occurrence, tensor) and their free fields are typed: ``selector`` is a list whose entries are ``None``
41
+ (the whole axis), a non-negative int or a list of non-negative ints; ``array`` is an array name
42
+ (text) or ``{shape: [int, ...], dtype: str}``; ``role`` and ``json_pointer`` are text; a run
43
+ pointer's ``plan`` is a file pointer; a parameter pointer's ``model`` is a canonical model
44
+ identity. ``execution`` and ``model_identity`` are scanned too: ints (>= 0) anywhere, floats
45
+ only at the adapters' configuration constants (``EXECUTION_FLOATS``), nothing else numeric.
46
+ Integers in records are capped at 15 decimal digits; a larger one (or a ``ValueError`` from a
47
+ huge int) is a ``RecordError``. A path component ``*`` matches every key of a mapping or index
48
+ of a list. Out of scope by design: a string that looks like a number is text, and a boolean is
49
+ not a numeric claim; neither is refused.
50
+
51
+ ``mdb-circuit-investigation-v1`` records keep their own format and readers
52
+ (``circuit_investigation``); ``verify_legacy`` checks one the way ``circuit_investigation.record``
53
+ does, without the session binding.
54
+ """
55
+ from __future__ import annotations
56
+
57
+ import array
58
+ import base64
59
+ import binascii
60
+ import json
61
+ import math
62
+ import numbers
63
+ import sys
64
+ from collections.abc import Mapping
65
+ from dataclasses import dataclass
66
+
67
+ from .pointers import (
68
+ AUTHORITIES,
69
+ MAX_RECORD_BYTES,
70
+ RecordError,
71
+ _canonical,
72
+ _identity_record,
73
+ _sha,
74
+ check_bounded,
75
+ seal_digest,
76
+ validate_pointer,
77
+ )
78
+
79
+ SCHEMA = "mdb-record-v3"
80
+ SCHEMA_V2 = "mdb-record-v2"
81
+ SCHEMAS = (SCHEMA, SCHEMA_V2) # every schema ``verify_record`` and the index accept
82
+ LEGACY_SCHEMAS = ("mdb-circuit-investigation-v1",)
83
+ FIELDS = ("schema", "id", "session_id", "kind", "model_identity", "execution", "authority",
84
+ "pointers", "body", "digest")
85
+ STORED_FIELDS = ("schema", "id", "session_id", "kind", "model_identity", "execution_sha256",
86
+ "authority", "pointers", "body", "digest")
87
+ EXECUTION_SCHEMA = "mdb-execution-v1" # a sink's ``{"mdb_execution": ...}`` line
88
+ MAX_RECORD_BYTES_V3 = 1024 * 1024 # stored form of a v3 record (v2: ``MAX_RECORD_BYTES``)
89
+ MAX_RECORD_ITEMS_V3 = 65536 # JSON values outside column values (v2: 4096)
90
+ MAX_NUMS_INLINE = 65536 # values one column claim holds inline
91
+ NUMS_KIND = "nums"
92
+ NUMS_DTYPES = {"float64": "d", "float32": "f", "int64": "q"} # dtype -> ``array`` typecode
93
+ NUMS_KEYS = ("kind", "authority", "proof", "unit", "pointer", "shape", "dtype", "values")
94
+ _NUMS_REQUIRED = {"kind", "authority", "shape", "dtype", "values"}
95
+ NUM_KEYS = ("value", "authority", "proof", "unit", "pointer")
96
+ POINTER_KINDS = ("file", "parameter", "run", "occurrence", "tensor")
97
+ _POINTER_FIELDS = {
98
+ "file": {"kind", "locator", "digest", "array", "selector", "json_pointer", "role"},
99
+ "parameter": {"kind", "parameter", "model", "selector"},
100
+ "run": {"kind", "run_id", "plan_sha256", "plan"},
101
+ "tensor": {"kind", "ref", "sha256", "shape", "dtype"},
102
+ }
103
+ _SHORT = 64
104
+
105
+
106
+ def stored_record(record):
107
+ """The stored form of a record as a mapping: v3 -> ``execution_sha256`` and encoded column
108
+ values; v2 (and an already stored v3 mapping) -> unchanged."""
109
+ if (isinstance(record, Mapping) and record.get("schema") == SCHEMA
110
+ and "execution" in record):
111
+ return _encode(record)
112
+ return record
113
+
114
+
115
+ def stored_form(record):
116
+ """The text a record is stored and transmitted as: canonical JSON of ``stored_record`` (the
117
+ digest's form)."""
118
+ return _canonical(stored_record(record))
119
+
120
+
121
+ def stored_bytes(record):
122
+ """UTF-8 bytes of ``stored_form``; text that is not encodable is a ``RecordError``."""
123
+ try:
124
+ return stored_form(record).encode("utf-8")
125
+ except UnicodeEncodeError as error:
126
+ raise RecordError("record holds text that cannot be encoded as UTF-8") from error
127
+
128
+
129
+ def _huge_int_guard(function):
130
+ """A ``ValueError``/``OverflowError`` from a huge int (``10**5000``) is a ``RecordError``."""
131
+ import functools
132
+
133
+ @functools.wraps(function)
134
+ def guarded(*args, **kwargs):
135
+ try:
136
+ return function(*args, **kwargs)
137
+ except RecordError:
138
+ raise
139
+ except (ValueError, OverflowError) as error:
140
+ raise RecordError(f"record holds a number that cannot be sealed: {error}") from error
141
+ return guarded
142
+
143
+
144
+ def _bounded_record(value, label):
145
+ """v2: ``check_bounded`` with the size measured on ``stored_bytes`` (one definition)."""
146
+ try:
147
+ out = check_bounded(value, label, max_bytes=None)
148
+ except UnicodeEncodeError as error:
149
+ raise RecordError(f"{label} holds text that cannot be encoded as UTF-8") from error
150
+ size = len(stored_bytes(out))
151
+ if size > MAX_RECORD_BYTES:
152
+ raise RecordError(f"{label} is {size} bytes (> {MAX_RECORD_BYTES}); store it by pointer")
153
+ return out
154
+
155
+
156
+ def _is_nums(value):
157
+ return (isinstance(value, Mapping) and value.get("kind") == NUMS_KIND and "values" in value
158
+ and "value" not in value)
159
+
160
+
161
+ _LEAVES = frozenset((str, int, float, bool, type(None)))
162
+
163
+
164
+ def _column_paths(value, path=(), depth=0, out=None):
165
+ """Paths (key / index tuples) of the column claims inside ``value`` (leaves are skipped
166
+ without a call: this walk runs on every seal, verify and read)."""
167
+ out = [] if out is None else out
168
+ if depth > 32:
169
+ raise RecordError("record nests too deeply")
170
+ kind = type(value)
171
+ if kind is dict or (kind is not list and kind is not tuple and isinstance(value, Mapping)):
172
+ if value.get("kind") == NUMS_KIND and "values" in value and "value" not in value:
173
+ out.append(path)
174
+ return out
175
+ items = value.items()
176
+ elif kind is list or kind is tuple:
177
+ items = enumerate(value)
178
+ else:
179
+ return out
180
+ for key, item in items:
181
+ if type(item) not in _LEAVES:
182
+ _column_paths(item, (*path, key), depth + 1, out)
183
+ return out
184
+
185
+
186
+ def _at(value, path):
187
+ for part in path:
188
+ value = value[part]
189
+ return value
190
+
191
+
192
+ def _bounded_v3(value, label):
193
+ """v3 bounds on a logical envelope: column values are checked by ``check_nums`` (at most
194
+ ``MAX_NUMS_INLINE`` each) and set aside; everything else by ``check_bounded`` with
195
+ ``MAX_RECORD_ITEMS_V3``. Returns the envelope in canonical form and the column paths."""
196
+ if not isinstance(value, Mapping):
197
+ raise RecordError(f"{label} must be a mapping")
198
+ body = value.get("body")
199
+ paths = _column_paths(body) if isinstance(body, Mapping) else []
200
+ columns = [check_nums(_at(body, p), "body" + "".join(f".{k}" for k in p)) for p in paths]
201
+ for path in paths:
202
+ body = _replace_at(body, (*path, "values"), [])
203
+ if paths:
204
+ value = {**value, "body": body}
205
+ try:
206
+ out = check_bounded(value, label, max_bytes=None, max_items=MAX_RECORD_ITEMS_V3)
207
+ except UnicodeEncodeError as error:
208
+ raise RecordError(f"{label} holds text that cannot be encoded as UTF-8") from error
209
+ for path, column in zip(paths, columns):
210
+ _at(out["body"], path)["values"] = column["values"]
211
+ return out, paths
212
+
213
+
214
+ def _replace_at(value, path, new):
215
+ """A copy of ``value`` with ``new`` at ``path``; only the containers on the path are copied
216
+ (a tuple on the path becomes a list, as ``check_bounded`` would make it)."""
217
+ if not path:
218
+ return new
219
+ head = path[0]
220
+ copy = dict(value) if isinstance(value, Mapping) else list(value)
221
+ copy[head] = _replace_at(value[head], path[1:], new)
222
+ return copy
223
+
224
+
225
+ INT_DIGITS = 15
226
+ _INT_CAP = 10 ** INT_DIGITS
227
+
228
+
229
+ def _count(value):
230
+ """A non-negative int below 10**15 (bool is not an int here)."""
231
+ return isinstance(value, int) and not isinstance(value, bool) and 0 <= value < _INT_CAP
232
+
233
+
234
+ def _selector(value, label):
235
+ """``None`` (whole axis), a non-negative int or a list of them, per entry, in a list."""
236
+ if not isinstance(value, list):
237
+ raise RecordError(f"{label} selector must be a list")
238
+ for item in value:
239
+ if not (item is None or _count(item)
240
+ or (isinstance(item, list) and all(_count(i) for i in item))):
241
+ raise RecordError(f"{label} selector entries are None, a non-negative integer or a "
242
+ "list of non-negative integers")
243
+ return value
244
+
245
+
246
+ def _array_field(value):
247
+ if isinstance(value, str):
248
+ return
249
+ if (not isinstance(value, Mapping) or set(value) != {"shape", "dtype"}
250
+ or not isinstance(value["shape"], list) or not all(_count(n) for n in value["shape"])
251
+ or not isinstance(value["dtype"], str)):
252
+ raise RecordError("file pointer array is its name (text) or {shape: [int, ...], dtype: text}")
253
+
254
+
255
+ def _typed_pointer(pointer):
256
+ """Free fields of the three stored pointer kinds are text, structure or counts, never claims."""
257
+ kind = pointer["kind"]
258
+ if kind == "file":
259
+ locator, digest = pointer["locator"], pointer["digest"]
260
+ if not isinstance(locator["root"], str) or not isinstance(locator["path"], str):
261
+ raise RecordError("file pointer locator root and path are text")
262
+ if not _count(digest["size"]) or not isinstance(digest["sha256"], str):
263
+ raise RecordError("file pointer digest is {sha256: text, size: non-negative integer}")
264
+ if "array" in pointer:
265
+ _array_field(pointer["array"])
266
+ if "selector" in pointer:
267
+ _selector(pointer["selector"], "file pointer")
268
+ for field in ("json_pointer", "role"):
269
+ if field in pointer and not isinstance(pointer[field], str):
270
+ raise RecordError(f"file pointer {field} is text")
271
+ elif kind == "parameter":
272
+ if "selector" in pointer:
273
+ _selector(pointer["selector"], "parameter pointer")
274
+ if "model" in pointer and _canonical(_identity_record(pointer["model"])) != _canonical(
275
+ pointer["model"]):
276
+ raise RecordError("parameter pointer model is not a canonical model identity")
277
+ elif kind == "run":
278
+ if "plan_sha256" in pointer and (not isinstance(pointer["plan_sha256"], str)
279
+ or _sha(pointer["plan_sha256"], "plan sha256")
280
+ != pointer["plan_sha256"]):
281
+ raise RecordError("run pointer plan_sha256 is a sha256 hex digest")
282
+ if "plan" in pointer:
283
+ plan = pointer["plan"]
284
+ if not isinstance(plan, Mapping) or plan.get("kind") != "file":
285
+ raise RecordError("run pointer plan is a file pointer")
286
+ if _canonical(_record_pointer(plan)) != _canonical(plan):
287
+ raise RecordError("run pointer plan is not in canonical form")
288
+
289
+
290
+ def _typed_occurrence(pointer):
291
+ """An occurrence pointer's integers obey the 15-digit cap too (value shape, event)."""
292
+ shape = pointer["value"]["shape"]
293
+ if not isinstance(shape, list) or not all(_count(n) for n in shape):
294
+ raise RecordError("occurrence value shape holds integers in [0, 10**15)")
295
+ event = pointer["event"]
296
+ if event is not None and not _count(event):
297
+ raise RecordError("occurrence event is an integer in [0, 10**15)")
298
+
299
+
300
+ def _record_pointer(pointer):
301
+ try:
302
+ pointer = validate_pointer(pointer)
303
+ kind = pointer["kind"]
304
+ if kind not in POINTER_KINDS:
305
+ raise RecordError(f"pointer kind {kind!r} is not one of " + ", ".join(POINTER_KINDS))
306
+ extra = set(pointer) - _POINTER_FIELDS.get(kind, set(pointer))
307
+ if extra:
308
+ raise RecordError(f"{kind} pointer has unknown fields {sorted(extra)}")
309
+ if kind == "occurrence":
310
+ _typed_occurrence(pointer)
311
+ elif kind != "tensor": # validate_tensor_pointer already typed every field
312
+ _typed_pointer(pointer)
313
+ except (TypeError, KeyError, AttributeError) as error:
314
+ raise RecordError(f"malformed pointer: {error}") from error
315
+ except RecordError:
316
+ raise
317
+ except (ValueError, OverflowError) as error:
318
+ raise RecordError(f"malformed pointer: {error}") from error
319
+ return pointer
320
+
321
+
322
+ def _short_text(value, label):
323
+ if not isinstance(value, str) or not value or len(value) > _SHORT or value != value.strip():
324
+ raise RecordError(f"{label} must be short text (<= {_SHORT} chars, no surrounding space)")
325
+ return value
326
+
327
+
328
+ def _authority(value, label="authority"):
329
+ if value not in AUTHORITIES:
330
+ raise RecordError(f"{label} must be one of " + ", ".join(AUTHORITIES))
331
+ return value
332
+
333
+
334
+ @_huge_int_guard
335
+ def num(value, authority, *, proof=None, unit=None, pointer=None):
336
+ """A numeric claim: ``{value, authority, proof?, unit?, pointer?}``.
337
+
338
+ ``proof`` names the identity or theorem (``P14``), ``pointer`` the evidence the number was
339
+ read from or derived on. Booleans and non-finite numbers are refused.
340
+ """
341
+ np = __import__("sys").modules.get("numpy")
342
+ if np is not None and isinstance(value, np.generic):
343
+ value = value.item()
344
+ if (isinstance(value, bool) or not isinstance(value, numbers.Real)
345
+ or (not isinstance(value, numbers.Integral) and not math.isfinite(value))):
346
+ raise RecordError("a numeric claim needs a finite number")
347
+ if isinstance(value, numbers.Integral) and not -_INT_CAP < int(value) < _INT_CAP:
348
+ raise RecordError(f"a numeric claim holds at most {INT_DIGITS} decimal digits "
349
+ "(exact in JSON and JS); store larger integers as text")
350
+ out = {"value": int(value) if isinstance(value, numbers.Integral) else float(value),
351
+ "authority": _authority(authority)}
352
+ if proof is not None:
353
+ out["proof"] = _short_text(proof, "proof")
354
+ if unit is not None:
355
+ out["unit"] = _short_text(unit, "unit")
356
+ if pointer is not None:
357
+ out["pointer"] = _record_pointer(pointer)
358
+ return out
359
+
360
+
361
+ def is_num(value):
362
+ """A num-shaped mapping: only num keys, a ``value``, and an authority or a numeric value."""
363
+ if not isinstance(value, Mapping) or "value" not in value or not set(value) <= set(NUM_KEYS):
364
+ return False
365
+ number = value["value"]
366
+ return "authority" in value or (isinstance(number, numbers.Real)
367
+ and not isinstance(number, bool))
368
+
369
+
370
+ @_huge_int_guard
371
+ def check_num(value, label="claim"):
372
+ """Validate a stored numeric claim; returns it in canonical form."""
373
+ if not isinstance(value, Mapping) or "value" not in value or not set(value) <= set(NUM_KEYS):
374
+ raise RecordError(f"{label} must be a num(value, authority) claim, not "
375
+ f"{type(value).__name__}")
376
+ if "authority" not in value:
377
+ raise RecordError(f"{label} has no authority")
378
+ rebuilt = num(value["value"], value["authority"], proof=value.get("proof"),
379
+ unit=value.get("unit"), pointer=value.get("pointer"))
380
+ if _canonical(rebuilt) != _canonical(dict(value)):
381
+ raise RecordError(f"{label} is not a canonical numeric claim")
382
+ return rebuilt
383
+
384
+
385
+ # --------------------------------------------------------------------------- column claims (v3)
386
+
387
+ def _flat(values):
388
+ """(flat row-major list, shape, dtype kind or None) of a nested list, numpy array or torch
389
+ tensor (``"f4"`` for float32 and narrower floats, ``"f8"``, ``"i"``)."""
390
+ if hasattr(values, "detach"):
391
+ values = values.detach().cpu()
392
+ if values.is_floating_point() and values.element_size() < 4:
393
+ values = values.float() # bfloat16 / float16 are exact in float32
394
+ values = values.numpy()
395
+ if hasattr(values, "tolist") and hasattr(values, "shape") and hasattr(values, "dtype"):
396
+ kind = values.dtype.kind
397
+ tag = "i" if kind in "iu" else ("f4" if kind == "f" and values.dtype.itemsize <= 4
398
+ else "f8" if kind == "f" else None)
399
+ return values.reshape(-1).tolist(), [int(n) for n in values.shape], tag
400
+ shape, level = [], values
401
+ while isinstance(level, (list, tuple)):
402
+ shape.append(len(level))
403
+ level = level[0] if level else None
404
+ flat = list(values)
405
+ for _ in range(len(shape) - 1):
406
+ flat = [x for row in flat for x in row]
407
+ return flat, shape, None
408
+
409
+
410
+ def _column_value(value, dtype, label):
411
+ np = sys.modules.get("numpy")
412
+ if np is not None and isinstance(value, np.generic):
413
+ value = value.item()
414
+ if isinstance(value, bool) or not isinstance(value, numbers.Real):
415
+ raise RecordError(f"{label} values are numbers (no booleans, text or None)")
416
+ if dtype == "int64":
417
+ if not isinstance(value, numbers.Integral) or not -_INT_CAP < int(value) < _INT_CAP:
418
+ raise RecordError(f"{label}: an int64 column holds integers of at most {INT_DIGITS} "
419
+ "decimal digits")
420
+ return int(value)
421
+ value = float(value)
422
+ if not math.isfinite(value):
423
+ raise RecordError(f"{label} values must be finite")
424
+ if dtype == "float32" and array.array("f", [value])[0] != value:
425
+ raise RecordError(f"{label}: {value!r} is not exactly a float32 value")
426
+ return value
427
+
428
+
429
+ @_huge_int_guard
430
+ def nums(values, authority, *, proof=None, unit=None, pointer=None, shape=None, dtype=None,
431
+ store=None, inline=None):
432
+ """A column claim: many numbers with one authority, proof and unit (schema v3).
433
+
434
+ ``{kind: "nums", authority, proof?, unit?, pointer?, shape, dtype, values}``. ``values`` is
435
+ a nested list, a numpy array or a tensor (flattened row-major; ``shape`` defaults to its
436
+ shape). ``dtype`` is ``float64`` (default), ``float32`` (every value must be exactly a
437
+ float32) or ``int64`` (default for integer arrays). Values are finite.
438
+
439
+ Up to ``MAX_NUMS_INLINE`` values are held inline (the stored form keeps their bytes as
440
+ base64). More, or ``inline=False``, need ``store`` (a project or its ``LocalStore``): the
441
+ values go to a tensor blob and ``values`` is a tensor pointer, checked by sha256 on read
442
+ (``nums_values``). In the record a column costs about 8 bytes per float64 value (base64:
443
+ 10.7 characters) against about 70 for one ``num`` per value.
444
+ """
445
+ flat, found, tag = _flat(values)
446
+ shape = found if shape is None else [int(n) for n in shape]
447
+ if dtype is None:
448
+ if tag is None:
449
+ tag = "i" if flat and all(isinstance(v, numbers.Integral)
450
+ and not isinstance(v, bool) for v in flat) else "f8"
451
+ dtype = {"i": "int64", "f4": "float32"}.get(tag, "float64")
452
+ if dtype not in NUMS_DTYPES:
453
+ raise RecordError("a column dtype is one of " + ", ".join(NUMS_DTYPES))
454
+ flat = [_column_value(v, dtype, "column") for v in flat]
455
+ if math.prod(shape) != len(flat):
456
+ raise RecordError(f"column shape {shape} does not hold {len(flat)} values")
457
+ out = {"kind": NUMS_KIND, "authority": _authority(authority), "shape": shape,
458
+ "dtype": dtype}
459
+ if proof is not None:
460
+ out["proof"] = _short_text(proof, "proof")
461
+ if unit is not None:
462
+ out["unit"] = _short_text(unit, "unit")
463
+ if pointer is not None:
464
+ out["pointer"] = _record_pointer(pointer)
465
+ if inline is None:
466
+ inline = len(flat) <= MAX_NUMS_INLINE
467
+ if inline:
468
+ out["values"] = flat
469
+ else:
470
+ if store is None:
471
+ raise RecordError(f"a column of {len(flat)} values (> {MAX_NUMS_INLINE} inline) is "
472
+ "kept by pointer: pass store= (a project or its LocalStore)")
473
+ import numpy as np
474
+
475
+ from .pointers import tensor_pointer
476
+
477
+ store = getattr(store, "store", store)
478
+ data = np.asarray(flat, dtype=dtype).reshape(shape)
479
+ try:
480
+ stored = store.put_tensor(data)
481
+ except (ValueError, OverflowError) as error:
482
+ raise RecordError(f"the column store refused the values: {error}") from error
483
+ out["values"] = tensor_pointer(stored["ref"], sha256=stored["sha256"],
484
+ shape=stored["shape"], dtype=stored["dtype"])
485
+ return check_nums(out)
486
+
487
+
488
+ @_huge_int_guard
489
+ def check_nums(value, label="column"):
490
+ """Validate a column claim; returns it in canonical form (``values`` a list of Python
491
+ numbers, or a tensor pointer whose shape and dtype match)."""
492
+ if not isinstance(value, Mapping) or value.get("kind") != NUMS_KIND:
493
+ raise RecordError(f"{label} must be a nums column claim")
494
+ keys = set(value)
495
+ if not _NUMS_REQUIRED <= keys or not keys <= set(NUMS_KEYS):
496
+ raise RecordError(f"{label} column fields are {', '.join(sorted(_NUMS_REQUIRED))} and "
497
+ "optionally proof, unit, pointer")
498
+ dtype, shape = value["dtype"], value["shape"]
499
+ if dtype not in NUMS_DTYPES:
500
+ raise RecordError(f"{label} dtype must be one of " + ", ".join(NUMS_DTYPES))
501
+ if (not isinstance(shape, (list, tuple)) or not shape
502
+ or not all(_count(n) for n in shape)):
503
+ raise RecordError(f"{label} shape is a non-empty list of non-negative integers")
504
+ out = {"kind": NUMS_KIND, "authority": _authority(value["authority"], f"{label} authority"),
505
+ "shape": list(shape), "dtype": dtype}
506
+ for field in ("proof", "unit"):
507
+ if field in value:
508
+ out[field] = _short_text(value[field], f"{label} {field}")
509
+ if "pointer" in value:
510
+ out["pointer"] = _record_pointer(value["pointer"])
511
+ values = value["values"]
512
+ if isinstance(values, Mapping):
513
+ out["values"] = _record_pointer(values)
514
+ if (out["values"]["kind"] != "tensor" or out["values"]["shape"] != out["shape"]
515
+ or out["values"]["dtype"] != dtype):
516
+ raise RecordError(f"{label} values pointer is a tensor pointer of the column's "
517
+ "shape and dtype")
518
+ return out
519
+ if not isinstance(values, (list, tuple)):
520
+ raise RecordError(f"{label} values are a list or a tensor pointer")
521
+ if len(values) > MAX_NUMS_INLINE:
522
+ raise RecordError(f"{label} holds {len(values)} values inline (> {MAX_NUMS_INLINE}); "
523
+ "keep it by pointer (nums(..., store=))")
524
+ if math.prod(out["shape"]) != len(values):
525
+ raise RecordError(f"{label} shape {out['shape']} does not hold {len(values)} values")
526
+ if dtype != "int64" and any(isinstance(v, numbers.Integral) and not isinstance(v, bool)
527
+ for v in values):
528
+ # one logical form per content: a float column holds floats (1.0, never 1)
529
+ raise RecordError(f"{label} is a float column holding integers; give floats")
530
+ out["values"] = [_column_value(v, dtype, label) for v in values]
531
+ return out
532
+
533
+
534
+ def nums_values(claim, *, store=None):
535
+ """The values of a column claim as a numpy array of its shape and dtype (inline, or read
536
+ from ``store`` and checked against the pointer's sha256)."""
537
+ import numpy as np
538
+
539
+ claim = check_nums(claim)
540
+ values = claim["values"]
541
+ if isinstance(values, Mapping):
542
+ from .pointers import resolve_tensor
543
+
544
+ return resolve_tensor(values, store=getattr(store, "store", store), framework="numpy")
545
+ return np.asarray(values, dtype=claim["dtype"]).reshape(claim["shape"])
546
+
547
+
548
+ def _pack(values, dtype):
549
+ data = array.array(NUMS_DTYPES[dtype], values)
550
+ if sys.byteorder != "little":
551
+ data.byteswap()
552
+ return base64.b64encode(data.tobytes()).decode("ascii")
553
+
554
+
555
+ def _unpack(text, dtype, count, label):
556
+ if not isinstance(text, str):
557
+ raise RecordError(f"{label} stored values are base64 text")
558
+ try:
559
+ raw = base64.b64decode(text.encode("ascii"), validate=True)
560
+ except (binascii.Error, UnicodeEncodeError, ValueError) as error:
561
+ raise RecordError(f"{label} stored values are not base64: {error}") from error
562
+ data = array.array(NUMS_DTYPES[dtype])
563
+ if len(raw) != count * data.itemsize:
564
+ raise RecordError(f"{label} stored values are {len(raw)} bytes, not {count} x "
565
+ f"{data.itemsize} (truncated or corrupt)")
566
+ data.frombytes(raw)
567
+ if sys.byteorder != "little":
568
+ data.byteswap()
569
+ out = data.tolist()
570
+ if dtype != "int64" and not all(math.isfinite(v) for v in out):
571
+ raise RecordError(f"{label} stored values are not finite")
572
+ if base64.b64encode(raw).decode("ascii") != text:
573
+ raise RecordError(f"{label} stored values are not canonical base64")
574
+ return out
575
+
576
+
577
+ # --------------------------------------------------------------------------- kinds
578
+
579
+ @dataclass(frozen=True)
580
+ class KindSpec:
581
+ """What a record kind must hold.
582
+
583
+ ``numeric``: dotted body paths whose values are ``num`` claims; ``*`` stands for every
584
+ item of a list or every value of a mapping. Every declared path must exist and hold labelled
585
+ numbers. ``required``: dotted body paths that must be present. ``pointers``: pointer kinds
586
+ the record must carry at least one of each. ``plain_numeric``: dotted body paths (``*``
587
+ allowed) of structural leaves (shapes, indices, counts, ids, byte sizes): a path exempts a
588
+ leaf holding a non-negative int, or a list of such ints. It covers a whole subtree only
589
+ with a trailing ``**`` marker (``sizes.**``), and even then only non-negative ints are
590
+ exempt; a float, a negative number or an int past 15 digits is refused everywhere.
591
+ """
592
+ name: str
593
+ numeric: tuple = ()
594
+ required: tuple = ()
595
+ pointers: tuple = ()
596
+ plain_numeric: tuple = ()
597
+
598
+ def __post_init__(self):
599
+ for attr in ("numeric", "required", "pointers", "plain_numeric"):
600
+ object.__setattr__(self, attr, tuple(getattr(self, attr)))
601
+ _short_text(self.name, "record kind")
602
+ for path in self.plain_numeric:
603
+ parts = path.split(".")
604
+ if "**" in parts[:-1] or any(not p for p in parts):
605
+ raise RecordError(f"plain_numeric path {path!r}: '**' only as the last component")
606
+
607
+
608
+ _KINDS = {}
609
+
610
+
611
+ def declare_kind(name, *, numeric=(), required=(), pointers=(), plain_numeric=()):
612
+ """Declare a record kind. Re-declaring the same spec is a no-op; a different one fails."""
613
+ spec = KindSpec(name, numeric, required, pointers, plain_numeric)
614
+ if name in _KINDS and _KINDS[name] != spec:
615
+ raise RecordError(f"record kind {name!r} is already declared differently")
616
+ _KINDS[name] = spec
617
+ return spec
618
+
619
+
620
+ def kind_spec(name):
621
+ return _KINDS.get(name)
622
+
623
+
624
+ def _claims(value, parts, label, path):
625
+ """Yield (label, value) for every value at the dotted claim path; absent branches raise."""
626
+ if not parts:
627
+ yield label, value
628
+ return
629
+ head, rest = parts[0], parts[1:]
630
+ if head == "*":
631
+ if isinstance(value, Mapping):
632
+ for key, item in value.items():
633
+ yield from _claims(item, rest, f"{label}.{key}", path)
634
+ elif isinstance(value, (list, tuple)):
635
+ for i, item in enumerate(value):
636
+ yield from _claims(item, rest, f"{label}[{i}]", path)
637
+ else:
638
+ raise RecordError(f"{label} must be a mapping or list holding the claims at "
639
+ f"body.{path}, not {type(value).__name__}")
640
+ return
641
+ if not isinstance(value, Mapping) or head not in value:
642
+ raise RecordError(f"{label}.{head} is missing (the kind declares a claim at body.{path})")
643
+ yield from _claims(value[head], rest, f"{label}.{head}", path)
644
+
645
+
646
+ def _present(value, parts):
647
+ if not parts:
648
+ return True
649
+ if isinstance(value, Mapping) and parts[0] in value:
650
+ return _present(value[parts[0]], parts[1:])
651
+ return False
652
+
653
+
654
+ def _is_number(value):
655
+ return isinstance(value, numbers.Real) and not isinstance(value, bool)
656
+
657
+
658
+ class _Rule:
659
+ """Which numeric leaves a scan exempts: ``patterns`` (body) or the execution profile."""
660
+
661
+ def __init__(self, patterns=(), *, any_count=False, floats=(), columns=False):
662
+ self.patterns, self.any_count, self.floats = patterns, any_count, tuple(floats)
663
+ self.columns = columns # v3: a column claim (``nums``) is a labelled leaf
664
+
665
+ def covers(self, parts):
666
+ """The path lies under a ``**`` subtree (or anywhere, for a profile)."""
667
+ if self.any_count:
668
+ return True
669
+ return any(p[-1] == "**" and len(parts) >= len(p) - 1
670
+ and all(a == "*" or a == b for a, b in zip(p[:-1], parts)) for p in self.patterns)
671
+
672
+ def leaf(self, parts):
673
+ """The path is a declared structural leaf."""
674
+ return self.covers(parts) or any(
675
+ p[-1] != "**" and len(p) == len(parts) and all(a == "*" or a == b
676
+ for a, b in zip(p, parts))
677
+ for p in self.patterns)
678
+
679
+ def exempt(self, parts, number):
680
+ if isinstance(number, float):
681
+ return tuple(parts) in self.floats
682
+ return _count(number) and self.leaf(parts)
683
+
684
+
685
+ def _scan_claims(value, label, parts=(), rule=None, depth=0):
686
+ """Every numeric leaf is a labelled number's value or an exempt structural leaf."""
687
+ rule = rule or _Rule()
688
+ if depth > 32:
689
+ raise RecordError(f"{label} nests too deeply")
690
+ if isinstance(value, Mapping):
691
+ if "value" in value and "authority" in value:
692
+ check_num(value, label) # exact key set, real value, known authority
693
+ return
694
+ if rule.columns and _is_nums(value):
695
+ return # checked whole by ``check_nums`` in ``_bounded_v3``
696
+ if ("value" in value and set(value) <= set(NUM_KEYS)
697
+ and (_is_number(value["value"]) or isinstance(value["value"], str))
698
+ and not rule.covers(parts)):
699
+ raise RecordError(f"{label} has no authority") # a claim that dropped its label
700
+ for key, item in value.items():
701
+ _scan_claims(item, f"{label}.{key}", (*parts, key), rule, depth + 1)
702
+ elif isinstance(value, (list, tuple)):
703
+ if (value and all(_count(i) for i in value) and rule.leaf(parts)):
704
+ return # a declared list of counts
705
+ for i, item in enumerate(value):
706
+ _scan_claims(item, f"{label}[{i}]", (*parts, str(i)), rule, depth + 1)
707
+ elif _is_number(value):
708
+ if isinstance(value, float) and not math.isfinite(value):
709
+ raise RecordError(f"{label} is not finite")
710
+ if isinstance(value, int) and not -_INT_CAP < value < _INT_CAP:
711
+ raise RecordError(f"{label} holds more than {INT_DIGITS} decimal digits")
712
+ if not rule.exempt(parts, value):
713
+ raise RecordError(f"{label} is a bare number; a claim is num(value, authority) "
714
+ "and only declared structural leaves hold plain non-negative "
715
+ "integers")
716
+
717
+
718
+ # Floats an adapter's execution profile may carry: configuration constants, not measurements.
719
+ EXECUTION_FLOATS = (("batch", "guidance"), ("guidance",), ("eta",),
720
+ ("logit_softcap", "final"), ("logit_softcap", "attention"))
721
+ _PROFILE = _Rule(any_count=True, floats=EXECUTION_FLOATS)
722
+ _IDENTITY = _Rule(any_count=True)
723
+
724
+
725
+ @_huge_int_guard
726
+ def validate_body(kind, body, pointers=(), *, columns=False):
727
+ """Check ``body`` against the declared kind and the authority rule; raises ``RecordError``.
728
+ ``columns`` (schema v3): column claims (``nums``) are labelled numbers too."""
729
+ spec = _KINDS.get(kind)
730
+ if spec is None:
731
+ raise RecordError(f"record kind {kind!r} is not declared (declare_kind)")
732
+ if not isinstance(body, Mapping):
733
+ raise RecordError("record body must be a mapping")
734
+ for path in spec.required:
735
+ if not _present(body, path.split(".")):
736
+ raise RecordError(f"record kind {kind!r} requires body.{path}")
737
+ for path in spec.numeric:
738
+ for label, value in _claims(body, path.split("."), "body", path):
739
+ if columns and _is_nums(value):
740
+ check_nums(value, label)
741
+ else:
742
+ check_num(value, label)
743
+ patterns = tuple(tuple(p.split(".")) for p in spec.plain_numeric)
744
+ _scan_claims(body, "body", (), _Rule(patterns, columns=columns))
745
+ have = {p.get("kind") for p in pointers}
746
+ missing = [k for k in spec.pointers if k not in have]
747
+ if missing:
748
+ raise RecordError(f"record kind {kind!r} needs pointers of kind {missing}")
749
+
750
+
751
+ # --------------------------------------------------------------------------- seal / verify
752
+
753
+ def _check_envelope(record):
754
+ """``model_identity`` and ``execution`` carry no measurements (see the module docstring)."""
755
+ _scan_claims(record["model_identity"], "record.model_identity", (), _IDENTITY)
756
+ _scan_claims(record["execution"], "record.execution", (), _PROFILE)
757
+
758
+
759
+ CONTENT_FIELDS = ("session_id", "kind", "model_identity", "execution", "authority", "pointers",
760
+ "body")
761
+
762
+
763
+ def _encode(record, paths=None):
764
+ """The stored mapping of a logical v3 record (with or without ``id``/``digest``);
765
+ ``paths``: the body's column paths when already known."""
766
+ try:
767
+ out = {k: v for k, v in record.items() if k != "execution"}
768
+ out["execution_sha256"] = seal_digest(record["execution"])
769
+ body = record["body"]
770
+ if paths is None:
771
+ paths = _column_paths(body) if isinstance(body, Mapping) else ()
772
+ for path in paths:
773
+ column = _at(body, path)
774
+ if not isinstance(column["values"], Mapping):
775
+ body = _replace_at(body, (*path, "values"),
776
+ _pack(column["values"], column["dtype"]))
777
+ except (TypeError, KeyError, OverflowError, ValueError) as error:
778
+ raise RecordError(f"record cannot be encoded: {error}") from error
779
+ out["body"] = body
780
+ return out
781
+
782
+
783
+ def _decode(stored, execution):
784
+ """The logical record of a stored v3 mapping, given its execution profile (unverified)."""
785
+ if not isinstance(stored, Mapping) or set(stored) != set(STORED_FIELDS):
786
+ raise RecordError("stored v3 record fields are " + ", ".join(STORED_FIELDS))
787
+ if not isinstance(execution, Mapping):
788
+ raise RecordError("a v3 record is read with its execution profile (a mapping)")
789
+ if seal_digest(execution) != stored["execution_sha256"]:
790
+ raise RecordError("the execution profile given differs from the record's "
791
+ "execution_sha256")
792
+ body = stored["body"]
793
+ for path in _column_paths(body) if isinstance(body, Mapping) else ():
794
+ column = _at(body, path)
795
+ label = "body" + "".join(f".{k}" for k in path)
796
+ values = column["values"]
797
+ if isinstance(values, Mapping):
798
+ continue
799
+ shape, dtype = column.get("shape"), column.get("dtype")
800
+ if (dtype not in NUMS_DTYPES or not isinstance(shape, list) or not shape
801
+ or not all(_count(n) for n in shape)):
802
+ raise RecordError(f"{label} column has no valid shape and dtype")
803
+ if math.prod(shape) > MAX_NUMS_INLINE:
804
+ raise RecordError(f"{label} holds more than {MAX_NUMS_INLINE} values inline")
805
+ body = _replace_at(body, (*path, "values"),
806
+ _unpack(values, dtype, math.prod(shape), label))
807
+ out = {k: v for k, v in stored.items() if k != "execution_sha256"}
808
+ out["execution"], out["body"] = dict(execution), body
809
+ return out
810
+
811
+
812
+ def _size_v3(stored, label="record"):
813
+ size = len(_canonical(stored).encode("utf-8"))
814
+ if size > MAX_RECORD_BYTES_V3:
815
+ raise RecordError(f"{label} is {size} bytes (> {MAX_RECORD_BYTES_V3}); store it by "
816
+ "pointer")
817
+ return size
818
+
819
+
820
+ def _seal(*, session_id, kind, model_identity, execution, authority, body, pointers):
821
+ """A v3 record of exactly this content (no custody added, no sink written)."""
822
+ if not isinstance(session_id, str) or not session_id.strip():
823
+ raise RecordError("a record needs a session id")
824
+ pointers = [_record_pointer(p) for p in pointers]
825
+ envelope, paths = _bounded_v3({
826
+ "schema": SCHEMA, "session_id": session_id, "kind": _short_text(kind, "record kind"),
827
+ "model_identity": model_identity, "execution": execution,
828
+ "authority": _authority(authority), "pointers": pointers, "body": body,
829
+ }, "record")
830
+ _check_envelope(envelope)
831
+ validate_body(kind, envelope["body"], envelope["pointers"], columns=True)
832
+ stored = _encode(envelope, paths)
833
+ digest = seal_digest(stored)
834
+ try:
835
+ _size_v3({**stored, "id": digest, "digest": digest})
836
+ except UnicodeEncodeError as error:
837
+ raise RecordError("record holds text that cannot be encoded as UTF-8") from error
838
+ return {**envelope, "id": digest, "digest": digest}
839
+
840
+
841
+ @_huge_int_guard
842
+ def seal_record(*, session_id, kind, model_identity, execution, authority, body, pointers=(),
843
+ run=None):
844
+ """Build and seal one record (schema v3). ``model_identity``/``execution`` are the
845
+ session's values.
846
+
847
+ Custody (``core.custody``): while custody is declared the body gains ``custody`` (script
848
+ and prereg sha256, library versions, kernel path) unless it carries its own; every open
849
+ record sink receives the sealed record. ``run``: the run (or runs) the record is about; when
850
+ one is rooted at a checkpoint whose path is not recomputed, custody gains
851
+ ``from_checkpoint`` (``custody.checkpoint_origin``)."""
852
+ from . import custody
853
+
854
+ if not isinstance(body, Mapping):
855
+ raise RecordError("record body must be a mapping")
856
+ record = _seal(session_id=session_id, kind=kind, model_identity=model_identity,
857
+ execution=execution, authority=authority, pointers=pointers,
858
+ body=custody.attach_custody(kind, dict(body), run=run))
859
+ custody.emit(record)
860
+ return record
861
+
862
+
863
+ def _verify_v2(record):
864
+ record = _bounded_record(dict(record), "record")
865
+ envelope = {k: v for k, v in record.items() if k not in ("id", "digest")}
866
+ digest = seal_digest(envelope)
867
+ if record["digest"] != digest or record["id"] != digest:
868
+ raise RecordError("record seal differs from its content")
869
+ return record, False
870
+
871
+
872
+ def _verify_v3(record):
873
+ envelope, paths = _bounded_v3({k: v for k, v in record.items()
874
+ if k not in ("id", "digest")}, "record")
875
+ stored = _encode(envelope, paths)
876
+ digest = seal_digest(stored)
877
+ if record["digest"] != digest or record["id"] != digest:
878
+ raise RecordError("record seal differs from its content")
879
+ _size_v3({**stored, "id": digest, "digest": digest})
880
+ return {**envelope, "id": digest, "digest": digest}, True
881
+
882
+
883
+ @_huge_int_guard
884
+ def verify_record(record, *, require_kind=True):
885
+ """Check a logical record (v3 or v2): fields, seal, bounds, authority, pointers, kind and
886
+ body. A stored v3 mapping (``execution_sha256``) is read with ``load_record``.
887
+
888
+ The kind must be declared in this process (``require_kind`` is kept for callers and is
889
+ always in force): a record of an undeclared kind is refused, sealed or not.
890
+ """
891
+ if isinstance(record, Mapping) and set(record) == set(STORED_FIELDS):
892
+ raise RecordError("this is a stored v3 record (execution_sha256): read it with "
893
+ "load_record(stored, execution=...)")
894
+ if not isinstance(record, Mapping) or set(record) != set(FIELDS):
895
+ raise RecordError("record fields are " + ", ".join(FIELDS))
896
+ if record["schema"] == SCHEMA:
897
+ record, columns = _verify_v3(record)
898
+ elif record["schema"] == SCHEMA_V2:
899
+ record, columns = _verify_v2(record)
900
+ else:
901
+ raise RecordError(f"record schema must be one of {', '.join(map(repr, SCHEMAS))}")
902
+ _authority(record["authority"])
903
+ if not isinstance(record["pointers"], list):
904
+ raise RecordError("record pointers are a list")
905
+ pointers = [_record_pointer(p) for p in record["pointers"]]
906
+ if _canonical(pointers) != _canonical(record["pointers"]):
907
+ raise RecordError("record pointers are not in canonical form")
908
+ _check_envelope(record)
909
+ validate_body(record["kind"], record["body"], pointers, columns=columns)
910
+ return record
911
+
912
+
913
+ MAX_LINE_BYTES = MAX_RECORD_BYTES_V3 + 4096 # a stored record line (v3 bound + framing slack)
914
+
915
+
916
+ def _no_duplicates(pairs):
917
+ out = {}
918
+ for key, value in pairs:
919
+ if key in out:
920
+ raise RecordError(f"duplicate key {key!r} in a stored record")
921
+ out[key] = value
922
+ return out
923
+
924
+
925
+ def parse_line(text, label="stored record", *, limit=MAX_LINE_BYTES):
926
+ """Parse one stored JSON line: refused before parsing when longer than ``limit`` and on a
927
+ duplicate key (the id covers the parsed value, so a first-wins reader must not see another
928
+ one). Every error is a ``RecordError``."""
929
+ if limit is not None and len(text) > limit:
930
+ raise RecordError(f"{label} is {len(text)} bytes (> {limit}); refused before parsing")
931
+ try:
932
+ return json.loads(text, object_pairs_hook=_no_duplicates)
933
+ except (ValueError, RecursionError) as error:
934
+ raise RecordError(f"{label} is not readable JSON (truncated or corrupt): "
935
+ f"{error}") from error
936
+
937
+
938
+ def _parse(stored):
939
+ if isinstance(stored, (bytes, bytearray)):
940
+ if len(stored) > MAX_LINE_BYTES:
941
+ raise RecordError(f"stored record is {len(stored)} bytes (> {MAX_LINE_BYTES}); "
942
+ "refused before parsing")
943
+ try:
944
+ stored = bytes(stored).decode("utf-8")
945
+ except UnicodeDecodeError as error:
946
+ raise RecordError(f"stored record is not UTF-8: {error}") from error
947
+ if isinstance(stored, str):
948
+ stored = parse_line(stored)
949
+ if not isinstance(stored, Mapping):
950
+ raise RecordError("a stored record is a JSON object")
951
+ return stored
952
+
953
+
954
+ def load_record(stored, *, execution=None, executions=None, verify=True):
955
+ """The logical record of a stored one (a JSON line, bytes or a parsed mapping), verified.
956
+
957
+ v3 needs its execution profile: ``execution`` (checked against ``execution_sha256``) or
958
+ ``executions`` (``{sha256: profile}``, e.g. a sink's ``mdb_execution`` lines). v2 records
959
+ (and logical v3 records) are verified as they are. ``verify=False`` decodes only."""
960
+ stored = _parse(stored)
961
+ if set(stored) == set(STORED_FIELDS) and stored.get("schema") == SCHEMA:
962
+ if execution is None:
963
+ execution = (executions or {}).get(stored.get("execution_sha256"))
964
+ if execution is None:
965
+ raise RecordError(f"no execution profile {str(stored.get('execution_sha256'))[:12]}"
966
+ " was given for this v3 record (execution= or executions=)")
967
+ stored = _decode(stored, execution)
968
+ return verify_record(stored) if verify else dict(stored)
969
+
970
+
971
+ def migrate_record(record):
972
+ """The v3 record of a v2 record: the same content (every field but ``schema``, ``id`` and
973
+ ``digest`` canonically equal, so every number bit-identical) under a new id. The v2 record
974
+ is verified first; a v3 record is returned verified and unchanged. No custody is added and
975
+ no sink receives it."""
976
+ old = verify_record(record)
977
+ if old["schema"] == SCHEMA:
978
+ return old
979
+ new = _seal(**{k: old[k] for k in CONTENT_FIELDS})
980
+ same_content(old, new)
981
+ return new
982
+
983
+
984
+ def same_content(a, b):
985
+ """Raise ``RecordError`` unless two logical records hold the same content (canonical JSON
986
+ of every field but ``schema``, ``id`` and ``digest``); returns the differing-field list
987
+ (empty)."""
988
+ differ = [k for k in CONTENT_FIELDS if _canonical(a[k]) != _canonical(b[k])]
989
+ if differ:
990
+ raise RecordError("records differ in " + ", ".join(differ))
991
+ return differ
992
+
993
+
994
+ def verify_legacy(body, identifier):
995
+ """Check an ``mdb-circuit-investigation-v1`` body against its id (saturn digest)."""
996
+ from saturn.values import digest
997
+
998
+ if not isinstance(body, Mapping) or body.get("schema") not in LEGACY_SCHEMAS:
999
+ raise RecordError("not a legacy circuit-investigation record")
1000
+ if digest(body) != identifier:
1001
+ raise RecordError("legacy record seal differs from its id")
1002
+ return {"record_id": identifier, **body}
1003
+
1004
+
1005
+ # --------------------------------------------------------------------------- built-in kinds
1006
+
1007
+ # An occurrence record (chapter 10 of the model-math series). Checkpoint -> model_identity;
1008
+ # numerical profile -> execution; clock, port, addresses, parent cut and ordered edits ->
1009
+ # the occurrence pointer's address and cut; hydration recipe -> the pointer's recipe/event.
1010
+ # The body holds the rest: input/history, transform window and convention, retained terms
1011
+ # with an explicit unlisted-term sum, the consumer address and the source evidence.
1012
+ OCCURRENCE = declare_kind(
1013
+ "occurrence",
1014
+ numeric=("retained.*.value", "unlisted"),
1015
+ required=("history", "transform", "retained", "unlisted", "consumer", "evidence"),
1016
+ pointers=("occurrence",),
1017
+ # Structure, not claims, declared leaf by leaf: the token ids and the parent row of the
1018
+ # history, the window and head of the transform, source rows and ids of retained terms,
1019
+ # byte sizes and event indices of evidence. Anything else numeric there is a labelled number.
1020
+ plain_numeric=("history.token_ids", "history.parent_row", "transform.window",
1021
+ "transform.head", "retained.*.src", "retained.*.row", "retained.*.token",
1022
+ "retained.*.layer", "retained.*.head", "evidence.*.size",
1023
+ "evidence.*.event", "evidence.*.index"),
1024
+ )
1025
+
1026
+ # the analysis layer's kinds (torch-free), so any reader can verify them
1027
+ from . import kinds as _kinds # noqa: E402, F401