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/custody.py ADDED
@@ -0,0 +1,629 @@
1
+ """Record custody and record sinks.
2
+
3
+ Sealing order could be proved only from git commit times, a prereg's "written" time is
4
+ unreliable, ``REVISION`` pinned the library but not the driver, and drivers that kept only record
5
+ ids never stored the sealed bodies. Two debugger switches fix that for every sealed record
6
+ (forecast, trace, watch-hits, circuit-map, supplied-forecast, branch, pool, ...), because they
7
+ act inside ``records.seal_record``:
8
+
9
+ * ``declare(script=, prereg=, kernel_path=)``: custody for this process. While declared, every
10
+ record sealed gets ``body.custody`` = ``{schema, script, script_sha256, prereg,
11
+ prereg_sha256, libraries, kernel_path, declared_at}`` (files hashed when declared: the
12
+ bytes that ran, not the bytes at audit time; ``libraries`` = versions of mdb, saturn,
13
+ torch, transformers and every interop library already imported). A record that already carries
14
+ ``custody`` (``Branches``, ``Pool``: they always do) keeps its own. Undeclared, records are
15
+ sealed exactly as before (the REPL goldens and every stored id are unchanged).
16
+ * ``records_to(path)``: a sink. Every record sealed after it (in any module) is appended to
17
+ ``path`` as one canonical JSON line (``records.stored_form``, the digest's form), so a record
18
+ persists with no project attached; ``Sink.records()`` reads them back verified. Several sinks
19
+ may be open; ``Sink.close()`` stops one. A v3 record's stored form keeps its execution profile
20
+ by sha256, so before the first record of each profile the sink writes the profile once as an
21
+ ``{"mdb_execution": "mdb-execution-v1", "sha256", "execution"}`` line; ``Sink.records()``
22
+ reads v3 and v2 lines (one file may hold both).
23
+
24
+ Sink names: shard jobs that all opened
25
+ ``records-<tag>.jsonl`` were collected into one directory and only the last shard's records
26
+ survived. So ``path`` may be omitted (``records-<run>.jsonl`` in the working directory), a
27
+ directory (``<dir>/records-<run>.jsonl``) or contain ``{run}``; ``<run>`` is ``run_tag()``
28
+ (``MRUN_JOB_ID`` when set, a timestamp and the pid: unique per process and job). An explicit
29
+ file that already holds data and was not opened by this process is refused
30
+ (``FileExistsError``) unless ``append=True``.
31
+
32
+ Payloads: a record too large for one line keeps a sha256 pointer to the full payload
33
+ (``bounded.put_json``; ``state: "absent"`` with no project store, e.g. a compact
34
+ ``Branches.seal``'s ``arms_payload``). While a sink is open the payload bytes are also written
35
+ to it as one ``{"mdb_payload": ...}`` line, so the full payload (per-arm probe values) is sealed
36
+ in the file; ``Sink.load_json(pointer)`` reads it back sha256-checked. Records are unchanged:
37
+ a sink never alters a record's id.
38
+ * plug-in sinks: installed ``mdb.sinks`` entry points (``core.plugins``) named by
39
+ ``records.plugins`` (``MDB_RECORDS_PLUGINS``: names or ``all``; default none) receive every
40
+ sealed record after the file sinks, in ``emit``, each as its own deep copy. A plug-in that
41
+ fails to load or raises is warned about once and skipped; sealing goes on.
42
+
43
+ The environment can declare custody for a job payload with no code change: ``MDB_SCRIPT`` and
44
+ ``MDB_PREREG`` (paths) and the kernel path (``custody.kernel_path`` of ``mdb.core.settings``:
45
+ ``MDB_CUSTODY_KERNEL_PATH``, the older ``MDB_KERNEL_PATH``, or a config file; any one of them
46
+ declares) are read on first use (an unreadable file raises on every seal, never once). The
47
+ record sink is ``records.sink`` (``MDB_RECORDS_SINK``, the older ``MDB_RECORDS``, or a config
48
+ file; same naming rules) with ``records.append`` and ``records.payloads``. The sink is opened on
49
+ first use even when custody was declared in code first.
50
+
51
+ Config files: when a loaded file sets a key that reaches a record
52
+ (``settings.current().provenance()``), every record carries custody, and the block has
53
+ ``config`` = ``{schema, sources: [{path, sha256, layer, settings}], resolved, origins}``. With
54
+ no such file (none, or locations only), nothing changes (record ids are as before).
55
+ ``declare(kernel_path=None)`` and ``records_to(path=None, append=None, payloads=None)`` take the
56
+ configured values for arguments left as None.
57
+ """
58
+
59
+ from __future__ import annotations
60
+
61
+ import contextlib
62
+ import contextvars
63
+ import copy
64
+ import hashlib
65
+ import json
66
+ import os
67
+ import sys
68
+ import threading
69
+ import time
70
+ from pathlib import Path
71
+ from typing import Any
72
+
73
+ SCHEMA = "mdb-custody-v1"
74
+ CORE_LIBRARIES = ("mdb", "saturn", "torch", "transformers")
75
+ INTEROP_LIBRARIES = ("nnsight", "sae_lens", "transformer_lens", "pyvene", "circuit_tracer",
76
+ "safetensors", "numpy")
77
+ _LOCK = threading.Lock()
78
+ # env_read: custody from the environment/settings done (also set by declare/clear);
79
+ # sinks_read: the configured sink opened (independent: declaring custody in code first must not
80
+ # skip the sink).
81
+ # sink_error: the configured sink was refused; kept apart from env_error so that declare()/clear()
82
+ # (which reset custody) never hide it: every later seal raises until the sink is read again.
83
+ # inits: init files the REPL ran ({path, sha256}); they change what later records measure.
84
+ _STATE: dict[str, Any] = {"declared": None, "env_read": False, "sinks_read": False,
85
+ "env_error": None, "sink_error": None, "inits": []}
86
+ _SINKS: list[Sink] = []
87
+ _OWNED: set[str] = set() # sink files this process opened (it may reopen and append)
88
+ PAYLOAD_SCHEMA = "mdb-payload-v1"
89
+ _RUN_TAG: list[str] = []
90
+
91
+
92
+ def file_sha256(path: str | Path) -> str:
93
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
94
+
95
+
96
+ def _version(name: str) -> str | None:
97
+ module = sys.modules.get(name)
98
+ if module is None:
99
+ return None
100
+ version = getattr(module, "__version__", None)
101
+ if version is None:
102
+ try:
103
+ from importlib.metadata import version as dist_version
104
+
105
+ version = dist_version(name.replace("_", "-"))
106
+ except Exception:
107
+ version = "unknown"
108
+ return str(version)
109
+
110
+
111
+ def libraries() -> dict[str, str]:
112
+ """Versions of the core and interop libraries this process has imported (nothing is
113
+ imported here: a record about a run was made with what is loaded)."""
114
+ out = {}
115
+ for name in (*CORE_LIBRARIES, *INTEROP_LIBRARIES):
116
+ found = _version(name)
117
+ if found is not None:
118
+ out[name] = found
119
+ return out
120
+
121
+
122
+ def _main_script() -> str | None:
123
+ main = sys.modules.get("__main__")
124
+ path = getattr(main, "__file__", None)
125
+ return path if path and Path(path).is_file() else None
126
+
127
+
128
+ def declare(*, script: str | Path | None = None, prereg: str | Path | None = None,
129
+ kernel_path: str | None = None, note: str | None = None) -> dict[str, Any]:
130
+ """Declare custody for every record sealed from now on (returns the custody block).
131
+ ``script`` defaults to the ``__main__`` file when there is one; ``kernel_path`` to the
132
+ configured ``[custody] kernel_path`` (``mdb.core.settings``), else ``undeclared``."""
133
+ script = script if script is not None else _main_script()
134
+ if kernel_path is None:
135
+ kernel_path = _settings().current().get("custody.kernel_path")
136
+ block: dict[str, Any] = {"schema": SCHEMA, "script": None, "script_sha256": None,
137
+ "prereg": None, "prereg_sha256": None,
138
+ "kernel_path": kernel_path or "undeclared",
139
+ "declared_at": time.strftime("%Y-%m-%dT%H:%M:%S%z")}
140
+ if script is not None:
141
+ block["script"], block["script_sha256"] = str(script), file_sha256(script)
142
+ if prereg is not None:
143
+ block["prereg"], block["prereg_sha256"] = str(prereg), file_sha256(prereg)
144
+ if note:
145
+ block["note"] = str(note)
146
+ with _LOCK:
147
+ _STATE["declared"] = block
148
+ _STATE["env_read"] = True
149
+ _STATE["env_error"] = None
150
+ return block_with_libraries(block)
151
+
152
+
153
+ def clear() -> None:
154
+ """Forget declared custody and noted init files (records seal as before). A refused sink
155
+ stays an error until the environment is read again."""
156
+ with _LOCK:
157
+ _STATE["declared"] = None
158
+ _STATE["inits"] = []
159
+ _STATE["env_read"] = True
160
+ _STATE["env_error"] = None
161
+
162
+
163
+ def _settings() -> Any:
164
+ from . import settings
165
+
166
+ return settings
167
+
168
+
169
+ def _from_env() -> None:
170
+ """Declare custody and open the sink from the environment and settings once. A failure (a
171
+ missing ``MDB_SCRIPT`` file, a bad config file) is kept and raised on EVERY later call:
172
+ custody never drops silently after the first error. Setting ``_STATE["env_read"] = False``
173
+ re-reads both (the environment changed)."""
174
+ if _STATE["env_read"] and _STATE["sinks_read"]:
175
+ if _STATE["env_error"] is not None:
176
+ raise _STATE["env_error"]
177
+ if _STATE["sink_error"] is not None:
178
+ raise _STATE["sink_error"]
179
+ return
180
+ again = not _STATE["env_read"]
181
+ stage = "custody"
182
+ try:
183
+ # the settings the process loaded with (a file edited later must not change the block)
184
+ resolved = _settings().current()
185
+ if again:
186
+ script, prereg = os.environ.get("MDB_SCRIPT"), os.environ.get("MDB_PREREG")
187
+ kernel = resolved.get("custody.kernel_path")
188
+ if script or prereg or kernel:
189
+ declare(script=script, prereg=prereg, kernel_path=kernel)
190
+ stage = "sink"
191
+ if again or not _STATE["sinks_read"]:
192
+ _STATE["sink_error"] = None
193
+ sink = resolved.get("records.sink")
194
+ if sink:
195
+ target = sink_path(sink)
196
+ if not any(s.path == target.absolute() or s.path == target for s in _SINKS):
197
+ records_to(target, append=resolved.get("records.append"),
198
+ payloads=resolved.get("records.payloads"))
199
+ except BaseException as error:
200
+ _STATE["env_read"], _STATE["sinks_read"] = True, True
201
+ _STATE["sink_error" if stage == "sink" else "env_error"] = error
202
+ raise
203
+ _STATE["env_read"], _STATE["sinks_read"], _STATE["env_error"] = True, True, None
204
+
205
+
206
+ def reread() -> None:
207
+ """Read the environment and config files again at the next seal, as a new process would
208
+ (the settings are otherwise fixed when first loaded). Declared custody is kept."""
209
+ _settings().reset()
210
+ with _LOCK:
211
+ _STATE["env_read"], _STATE["sinks_read"] = False, False
212
+ _STATE["env_error"], _STATE["sink_error"] = None, None
213
+
214
+
215
+ def ran_init(path: str | Path) -> dict[str, Any]:
216
+ """Note that the REPL ran the init file ``path`` (hashed now): every record sealed from now
217
+ on carries custody with ``init: [{path, sha256}]``. Returns the entry."""
218
+ entry = {"path": str(Path(path).expanduser().absolute()), "sha256": file_sha256(path)}
219
+ with _LOCK:
220
+ if entry not in _STATE["inits"]:
221
+ _STATE["inits"].append(entry)
222
+ return entry
223
+
224
+
225
+ def config_block() -> dict[str, Any] | None:
226
+ """The loaded config files and resolved recorded settings, or None with no config file."""
227
+ _from_env()
228
+ return _settings().current().provenance()
229
+
230
+
231
+ def block_with_libraries(block: dict[str, Any]) -> dict[str, Any]:
232
+ return {**block, "libraries": libraries()}
233
+
234
+
235
+ def _undeclared() -> dict[str, Any]:
236
+ script = _main_script()
237
+ return {"schema": SCHEMA, "script": script,
238
+ "script_sha256": file_sha256(script) if script else None,
239
+ "prereg": None, "prereg_sha256": None, "kernel_path": "undeclared",
240
+ "declared_at": None}
241
+
242
+
243
+ def current() -> dict[str, Any] | None:
244
+ """The declared custody block with library versions now, or None when undeclared and no
245
+ config file was loaded. With a config file, a block is always returned (the ``__main__``
246
+ script when undeclared) and carries ``config``."""
247
+ _from_env()
248
+ block = _STATE["declared"]
249
+ config = config_block()
250
+ if config is not None:
251
+ block = {**(block if block is not None else _undeclared()), "config": config}
252
+ if _STATE["inits"]:
253
+ block = {**(block if block is not None else _undeclared()),
254
+ "init": [dict(entry) for entry in _STATE["inits"]]}
255
+ return None if block is None else block_with_libraries(block)
256
+
257
+
258
+ def custody(kernel_path: str | None = None) -> dict[str, Any]:
259
+ """A custody block for a record that always carries one (branches, pools): the declared
260
+ custody if any, else the ``__main__`` script (when a file) and the library versions;
261
+ ``kernel_path`` overrides the declared one."""
262
+ block = current()
263
+ if block is None:
264
+ block = block_with_libraries(_undeclared())
265
+ if kernel_path is not None:
266
+ block["kernel_path"] = kernel_path
267
+ return block
268
+
269
+
270
+ class Sink:
271
+ """An append-only JSONL file of sealed records (one canonical record per line)."""
272
+
273
+ def __init__(self, path: str | Path, *, payloads: bool = True):
274
+ self.path = Path(path)
275
+ self.path.parent.mkdir(parents=True, exist_ok=True)
276
+ self.count = 0
277
+ self.payload_count = 0
278
+ self.payloads_on = bool(payloads)
279
+ self._executions: set[str] = set() # execution profiles this sink has written
280
+
281
+ def _append(self, line: str) -> None:
282
+ with _LOCK, self.path.open("a", encoding="utf-8") as handle:
283
+ handle.write(line + "\n")
284
+
285
+ def write(self, record: dict[str, Any]) -> None:
286
+ """Append one record's stored form. A v3 record keeps its execution profile by sha256,
287
+ so the profile is written first, once per sink, as an ``mdb_execution`` line."""
288
+ from .records import EXECUTION_SCHEMA, SCHEMA, stored_record
289
+ from .records import _canonical as canonical
290
+
291
+ stored = stored_record(record)
292
+ if record.get("schema") == SCHEMA and "execution" in record:
293
+ digest = stored["execution_sha256"]
294
+ if digest not in self._executions:
295
+ self._append(canonical({"mdb_execution": EXECUTION_SCHEMA, "sha256": digest,
296
+ "execution": record["execution"]}))
297
+ self._executions.add(digest)
298
+ self._append(canonical(stored))
299
+ self.count += 1
300
+
301
+ def write_payload(self, digest: str, raw: bytes) -> None:
302
+ """One payload line: the exact JSON bytes a record's pointer names by ``sha256``."""
303
+ if not self.payloads_on:
304
+ return
305
+ line = json.dumps({"mdb_payload": PAYLOAD_SCHEMA, "sha256": digest, "bytes": len(raw),
306
+ "raw": raw.decode("utf-8")}, sort_keys=True, separators=(",", ":"))
307
+ self._append(line)
308
+ self.payload_count += 1
309
+
310
+ def _lines(self) -> list[dict[str, Any]]:
311
+ if not self.path.exists():
312
+ return []
313
+ from .pointers import RecordError
314
+ from .records import parse_line
315
+
316
+ out = []
317
+ for number, line in enumerate(self.path.read_text(encoding="utf-8").splitlines(), 1):
318
+ if not line.strip():
319
+ continue
320
+ # a payload line may exceed the record bound (it carries a bounded object's bytes)
321
+ big = line.startswith('{"bytes":') and '"mdb_payload"' in line[:200]
322
+ value = parse_line(line, f"{self.path}:{number}", limit=None if big else _LIMIT())
323
+ if not isinstance(value, dict):
324
+ raise RecordError(f"{self.path}:{number}: not a record, payload or execution line")
325
+ out.append(value)
326
+ return out
327
+
328
+ def records(self, *, verify: bool = True) -> list[dict[str, Any]]:
329
+ """The records written to this file (by any process), as logical records (v3 and v2),
330
+ verified unless ``verify=False``. Payload and execution lines are not records and are
331
+ skipped (``payloads()``, ``executions()``)."""
332
+ from .records import load_record
333
+
334
+ lines = self._lines()
335
+ executions = _executions(lines)
336
+ return [load_record(r, executions=executions, verify=verify) for r in lines
337
+ if "mdb_payload" not in r and "mdb_execution" not in r]
338
+
339
+ def executions(self) -> dict[str, Any]:
340
+ """sha256 -> execution profile for every ``mdb_execution`` line, each checked."""
341
+ return _executions(self._lines())
342
+
343
+ def payloads(self) -> dict[str, bytes]:
344
+ """sha256 -> payload bytes for every payload line, each checked against its sha256."""
345
+ out = {}
346
+ for line in self._lines():
347
+ if "mdb_payload" not in line:
348
+ continue
349
+ raw = line["raw"].encode("utf-8")
350
+ if hashlib.sha256(raw).hexdigest() != line["sha256"]:
351
+ raise ValueError(f"payload {line['sha256'][:12]} differs from its sha256")
352
+ out[line["sha256"]] = raw
353
+ return out
354
+
355
+ def load_json(self, pointer: dict[str, Any]) -> Any:
356
+ """The full object a ``bounded.put_json`` pointer names, from this file's payloads."""
357
+ raw = self.payloads().get(pointer["sha256"])
358
+ if raw is None:
359
+ raise ValueError(f"no payload {pointer['sha256'][:12]} in {self.path}")
360
+ return json.loads(raw)
361
+
362
+ def close(self) -> None:
363
+ with _LOCK:
364
+ if self in _SINKS:
365
+ _SINKS.remove(self)
366
+
367
+ def __enter__(self) -> Sink:
368
+ return self
369
+
370
+ def __exit__(self, *exc: Any) -> None:
371
+ self.close()
372
+
373
+
374
+ def _LIMIT() -> int:
375
+ from .records import MAX_LINE_BYTES
376
+
377
+ return MAX_LINE_BYTES
378
+
379
+
380
+ def _executions(lines: list[dict[str, Any]]) -> dict[str, Any]:
381
+ """sha256 -> profile of every ``mdb_execution`` line; a malformed or edited one is a
382
+ ``RecordError``."""
383
+ from .pointers import RecordError
384
+ from .records import seal_digest
385
+
386
+ out = {}
387
+ for line in lines:
388
+ if "mdb_execution" not in line:
389
+ continue
390
+ try:
391
+ sha, profile = line["sha256"], line["execution"]
392
+ same = seal_digest(profile) == sha
393
+ except (KeyError, TypeError, ValueError) as error:
394
+ raise RecordError(f"execution line is malformed: {type(error).__name__}: "
395
+ f"{error}") from error
396
+ if not same:
397
+ raise RecordError(f"execution profile {sha[:12]} differs from its sha256")
398
+ out[sha] = profile
399
+ return out
400
+
401
+
402
+ def run_tag() -> str:
403
+ """This process's sink tag: ``<MRUN_JOB_ID>-`` (when set) + start time + ``pid<pid>``."""
404
+ if not _RUN_TAG:
405
+ job = os.environ.get("MRUN_JOB_ID", "").strip()
406
+ parts = [job] if job else []
407
+ parts += [time.strftime("%Y%m%dT%H%M%S"), f"pid{os.getpid()}"]
408
+ _RUN_TAG.append("".join(c if c.isalnum() or c in "-_." else "_"
409
+ for c in "-".join(parts)))
410
+ return _RUN_TAG[0]
411
+
412
+
413
+ def sink_path(path: str | Path | None = None) -> Path:
414
+ """Where a sink named ``path`` writes: ``None`` -> ``./records-<run>.jsonl``; a directory
415
+ (existing, ending in a separator, or a name with no suffix that does not exist yet, so
416
+ ``Path("out/sinks")`` is a directory and ``Path("out/records.jsonl")`` a file) ->
417
+ ``<dir>/records-<run>.jsonl``; ``{run}`` in the name
418
+ -> replaced by ``run_tag()``; any other path as given."""
419
+ name = f"records-{run_tag()}.jsonl"
420
+ if path is None:
421
+ return Path.cwd() / name
422
+ text = str(path)
423
+ if "{run}" in text:
424
+ return Path(text.replace("{run}", run_tag()))
425
+ as_path = Path(text)
426
+ if (text.endswith(("/", os.sep)) or as_path.is_dir()
427
+ or (not as_path.suffix and not as_path.exists())):
428
+ return as_path / name
429
+ return as_path
430
+
431
+
432
+ def records_to(path: str | Path | None = None, *, append: bool | None = None,
433
+ payloads: bool | None = None) -> Sink:
434
+ """Open a sink: every record sealed from now on is appended to ``sink_path(path)``.
435
+
436
+ A file that already holds data and that this process did not open is refused unless
437
+ ``append=True`` (two shards writing one name lose records when collected); use a directory,
438
+ ``{run}`` or no path for a unique per-process name. ``payloads=False`` keeps the file to
439
+ records only (no ``mdb_payload`` lines). Calling it again for a path that already has an open
440
+ sink returns that sink (so re-running a notebook cell does not write every record twice).
441
+
442
+ Arguments left as None take the configured ``[records]`` ``sink``, ``append`` and
443
+ ``payloads`` (``mdb.core.settings``; with no sink configured, ``./records-<run>.jsonl``)."""
444
+ resolved = _settings().current()
445
+ path = path if path is not None else resolved.get("records.sink")
446
+ append = bool(append if append is not None else resolved.get("records.append"))
447
+ payloads = bool(payloads if payloads is not None else resolved.get("records.payloads"))
448
+ target = sink_path(path).absolute()
449
+ key = str(target)
450
+ if (not append and key not in _OWNED and target.is_file()
451
+ and target.stat().st_size > 0):
452
+ raise FileExistsError(
453
+ f"record sink {target} already holds records this process did not write; pass "
454
+ "append=True to add to it, or give a directory / a name with {run} / no path for a "
455
+ f"unique per-run file (records-{run_tag()}.jsonl)")
456
+ with _LOCK:
457
+ for open_sink in _SINKS:
458
+ if str(open_sink.path.absolute()) == key:
459
+ open_sink.payloads_on = bool(payloads)
460
+ return open_sink
461
+ sink = Sink(target, payloads=payloads)
462
+ with _LOCK:
463
+ _OWNED.add(key)
464
+ _SINKS.append(sink)
465
+ return sink
466
+
467
+
468
+ def emit_payload(digest: str, raw: bytes) -> None:
469
+ """Hand a payload's bytes to every open sink (``bounded.put_json`` calls this when it has no
470
+ store, so a pointer with ``state: "absent"`` is still sealed in the sink file)."""
471
+ _from_env()
472
+ for sink in list(_SINKS):
473
+ sink.write_payload(digest, raw)
474
+
475
+
476
+ def sinks() -> list[Sink]:
477
+ return list(_SINKS)
478
+
479
+
480
+ # The checkpoint the run a record is sealed about is rooted at (``Run.from_checkpoint``), for a
481
+ # sealer that does not name its run (``seal_record(run=...)`` does): set by
482
+ # ``from_checkpoint(run)``.
483
+ _FROM_CHECKPOINT: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar(
484
+ "mdb_from_checkpoint", default=None)
485
+
486
+
487
+ @contextlib.contextmanager
488
+ def from_checkpoint(run: Any):
489
+ """While open, every record sealed carries ``custody.from_checkpoint`` of ``run`` (when it
490
+ is rooted at a checkpoint whose path is not recomputed: ``{checkpoint, path}``)."""
491
+ origin = getattr(run, "from_checkpoint", None)
492
+ token = _FROM_CHECKPOINT.set(None if origin is None else dict(origin))
493
+ try:
494
+ yield
495
+ finally:
496
+ _FROM_CHECKPOINT.reset(token)
497
+
498
+
499
+ def checkpoint_origin(runs: Any) -> dict[str, Any] | None:
500
+ """``custody.from_checkpoint`` of a record about ``runs`` (a run, or several): the
501
+ ``Run.from_checkpoint`` of the one run rooted at a checkpoint; for several distinct ones,
502
+ ``{"checkpoint": None, "path": "unverified" | "verified", "checkpoints": [...]}`` (path
503
+ verified only when every one is); None when none is."""
504
+ if runs is None:
505
+ return None
506
+ items = runs if isinstance(runs, (list, tuple)) else [runs]
507
+ found: list[dict[str, Any]] = []
508
+ for run in items:
509
+ origin = run if isinstance(run, dict) else getattr(run, "from_checkpoint", None)
510
+ if origin is not None and dict(origin) not in found:
511
+ found.append(dict(origin))
512
+ if not found:
513
+ return None
514
+ if len(found) == 1:
515
+ return found[0]
516
+ path = "verified" if all(o["path"] == "verified" for o in found) else "unverified"
517
+ return {"checkpoint": None, "path": path, "checkpoints": found[:64]}
518
+
519
+
520
+ def attach_custody(kind: str, body: dict[str, Any], run: Any = None) -> dict[str, Any]:
521
+ """``body`` with the declared custody added (unchanged when undeclared or already there),
522
+ and ``custody.from_checkpoint`` when the record is about a run rooted at a checkpoint:
523
+ ``run`` (the sealer names it, ``checkpoint_origin``), else an open ``from_checkpoint``
524
+ context."""
525
+ origin = checkpoint_origin(run) if run is not None else None
526
+ if origin is None:
527
+ origin = _FROM_CHECKPOINT.get()
528
+ if "custody" in body:
529
+ if origin is None or not isinstance(body["custody"], dict) or \
530
+ "from_checkpoint" in body["custody"]:
531
+ return body
532
+ return {**body, "custody": {**body["custody"], "from_checkpoint": origin}}
533
+ block = current()
534
+ if origin is not None:
535
+ block = {**(block or {}), "from_checkpoint": origin}
536
+ return body if block is None else {**body, "custody": block}
537
+
538
+
539
+ _PLUGINS: dict[str, Any] = {} # mdb.sinks name -> its sink object (None: it failed to load)
540
+ _PLUGIN_WARNED: set[str] = set()
541
+
542
+
543
+ def _plugin_warn(name: str, what: str, error: BaseException | None = None) -> None:
544
+ if name in _PLUGIN_WARNED:
545
+ return
546
+ _PLUGIN_WARNED.add(name)
547
+ import warnings
548
+
549
+ tail = "" if error is None else f": {type(error).__name__}: {error}"
550
+ warnings.warn(f"mdb record sink {name!r} {what}{tail}; records still seal", RuntimeWarning,
551
+ stacklevel=3)
552
+
553
+
554
+ def _close_plugins() -> None:
555
+ for name, sink in list(_PLUGINS.items()):
556
+ close = getattr(sink, "close", None)
557
+ if close is None:
558
+ continue
559
+ try:
560
+ close()
561
+ except Exception as error:
562
+ _plugin_warn(name, "failed to close", error)
563
+
564
+
565
+ def plugin_sinks() -> list[tuple[str, Any]]:
566
+ """``[(name, sink)]`` of the ``mdb.sinks`` entry points ``records.plugins`` names (``all``:
567
+ every installed one), each made once per process. Nothing is imported while the setting is
568
+ empty (the default). A name that is not installed or whose factory raises is warned about
569
+ once and skipped."""
570
+ wanted = _settings().current().get("records.plugins")
571
+ if not wanted:
572
+ return []
573
+ from . import plugins
574
+
575
+ found = plugins.entries(plugins.SINK_GROUP)
576
+ if not _PLUGINS:
577
+ import atexit
578
+
579
+ atexit.register(_close_plugins)
580
+ out = []
581
+ for name in (sorted(found) if "all" in wanted else wanted):
582
+ if name not in _PLUGINS:
583
+ _PLUGINS[name] = None
584
+ if name not in found:
585
+ _plugin_warn(name, f"is not installed (mdb.sinks: {', '.join(found) or 'none'})")
586
+ continue
587
+ try:
588
+ _PLUGINS[name] = found[name].load()()
589
+ except Exception as error:
590
+ _plugin_warn(name, "failed to load", error)
591
+ continue
592
+ if _PLUGINS[name] is not None:
593
+ out.append((name, _PLUGINS[name]))
594
+ return out
595
+
596
+
597
+ def emit(record: dict[str, Any]) -> None:
598
+ """Hand a sealed record to every open sink (``records.seal_record`` calls this), then to
599
+ every enabled ``mdb.sinks`` plug-in. A plug-in gets its own deep copy (it cannot change the
600
+ record the caller holds; measured cheaper than the canonical JSON sealing already did); one
601
+ that raises is warned about once and the record is sealed all the same."""
602
+ _from_env()
603
+ for sink in list(_SINKS):
604
+ sink.write(record)
605
+ for name, sink in plugin_sinks():
606
+ try:
607
+ sink.write(copy.deepcopy(record))
608
+ except Exception as error:
609
+ _plugin_warn(name, "failed to write a record", error)
610
+
611
+
612
+ def emit_file(record: dict[str, Any], path: Any) -> None:
613
+ """Tell every enabled ``mdb.sinks`` plug-in that has a ``file(record, path)`` method that
614
+ the file of a sealed record now exists (``engine.checkpoint.save`` to a path: the record is
615
+ sealed before the file is written). Same failure rule as ``emit``."""
616
+ for name, sink in plugin_sinks():
617
+ tell = getattr(sink, "file", None)
618
+ if tell is None:
619
+ continue
620
+ try:
621
+ tell(copy.deepcopy(record), str(path))
622
+ except Exception as error:
623
+ _plugin_warn(name, "failed to take a record's file", error)
624
+
625
+
626
+ __all__ = ["CORE_LIBRARIES", "INTEROP_LIBRARIES", "PAYLOAD_SCHEMA", "SCHEMA", "Sink",
627
+ "attach_custody", "checkpoint_origin", "clear", "config_block", "from_checkpoint", "current", "custody", "declare", "emit",
628
+ "emit_file", "emit_payload", "file_sha256", "libraries", "plugin_sinks", "ran_init", "records_to",
629
+ "reread", "run_tag", "sink_path", "sinks"]
mdb/core/errors.py ADDED
@@ -0,0 +1,51 @@
1
+ """Typed operation errors (stdlib only). ``mdb.ops.errors`` re-exports them.
2
+
3
+ Every error renders the same way on every front end: ``to_json()`` is
4
+ ``{"type", "message", "state", "reason"}``. ``state`` is ``refused`` when the request is valid
5
+ or malformed but cannot run (nothing changed), and ``unresolved`` for an internal failure
6
+ (the requested part could not be computed).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+
12
+ class OpError(ValueError):
13
+ """Base of operation errors. ``kind`` names the class on the wire."""
14
+
15
+ kind = "error"
16
+ state = "refused"
17
+
18
+ def __init__(self, message: str, kind: str | None = None, state: str | None = None):
19
+ self.message = message
20
+ if kind is not None:
21
+ self.kind = kind
22
+ if state is not None:
23
+ self.state = state
24
+ super().__init__(message)
25
+
26
+ def to_json(self) -> dict[str, str]:
27
+ return {"type": self.kind, "message": self.message, "state": self.state,
28
+ "reason": self.message}
29
+
30
+
31
+ class UnknownOp(OpError):
32
+ kind = "unknown-op"
33
+
34
+
35
+ class BadArgs(OpError):
36
+ kind = "bad-args"
37
+
38
+
39
+ class Refused(OpError):
40
+ """The operation is valid but cannot run in this state (or is not built yet)."""
41
+
42
+ kind = "refused"
43
+
44
+ def __init__(self, reason: str):
45
+ self.reason = reason
46
+ super().__init__(reason)
47
+
48
+
49
+ def internal(error: BaseException) -> OpError:
50
+ """An unexpected exception as a typed error: ``internal``, state ``unresolved``."""
51
+ return OpError(f"{type(error).__name__}: {error}", kind="internal", state="unresolved")