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/serve/recorded.py ADDED
@@ -0,0 +1,515 @@
1
+ """Read-only model of one recorded project session: clocks, cuts, branches and index rows.
2
+
3
+ Everything here is derived from verified ``mdb.core.project_read`` reads and from sealed
4
+ cut metadata; nothing is executed. ``Recorded`` caches one ``SessionModel`` per session and
5
+ rebuilds it when the session's index rows change.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sqlite3
11
+ import threading
12
+ from pathlib import Path
13
+
14
+ from saturn.values import digest
15
+
16
+ from ..core import address as addresses
17
+ from . import _legacy, blobs
18
+ from .schema import AxisTick, ClockAxis
19
+ from .states import StateCuts
20
+ from .stored import as_dict, as_int, as_list, as_str
21
+
22
+ # What a read of stored rows may raise when a row is corrupt (bad JSON, broken seal, wrong shape).
23
+ READ_ERRORS = (ValueError, KeyError, TypeError, AttributeError, LookupError, OSError,
24
+ sqlite3.Error, RecursionError, ArithmeticError)
25
+
26
+
27
+ class SessionUnreadable(Exception):
28
+ """A session whose stored rows cannot be turned into a model: refused as a whole (the other
29
+ sessions of the project are unaffected)."""
30
+
31
+ def __init__(self, reason):
32
+ super().__init__(reason)
33
+ self.reason = reason
34
+
35
+ LAYER_UNKNOWN = "layer count unknown"
36
+ NOT_RECORDED = "not recorded; model layer count unknown"
37
+
38
+
39
+ def layer_fallback(n):
40
+ return (f"at least {n} recorded layers (inferred from the highest recorded layer index; the "
41
+ "model's layer count is not recorded)")
42
+
43
+
44
+ class DepthTicks:
45
+ """The second clock axis of an autoregressive decoder: boundaries inside one token step.
46
+
47
+ Ticks follow ``mdb.core.address`` state-slot semantics: ``Lk`` is the hidden state entering
48
+ layer k (``tN.Lk.h``; ``tN.emb`` is ``tN.L0.h``), ``out`` the state after the last layer
49
+ (``tN.L{n-1}.h_out``), ``logits``/``sample`` the readout. ``embed`` (only when recorded) is
50
+ the boundary before the embedding; no occurrence address names it. Under layer granularity
51
+ the embed boundary of step t+1 holds token t's logits, so it is drawn in column t at
52
+ ``logits``.
53
+ """
54
+
55
+ def __init__(self, n_layers, granularity, observed, status="known"):
56
+ """``status``: ``known`` (the surface's layer clock), ``inferred`` (highest recorded layer
57
+ index: a lower bound, not the model's count) or ``unknown`` (no layer ticks at all)."""
58
+ self.n, self.granularity, self.status = n_layers or 0, granularity, status
59
+ n_layers = self.n
60
+ keys = ([("embed",)] if ("embed",) in observed else [])
61
+ if status != "unknown":
62
+ keys += [("L", k) for k in range(n_layers)] + [("out",)]
63
+ keys += [k for k in (("fn",), ("logits",), ("sample",))
64
+ if k in observed or (k == ("logits",) and granularity == "layer")]
65
+ self.keys = keys
66
+ self.index = {key: i for i, key in enumerate(keys)}
67
+
68
+ def place(self, point):
69
+ """``(token column, tick key)`` of a native execution point, or None."""
70
+ if not isinstance(point, dict) or not isinstance(point.get("logical_step"), int):
71
+ return None
72
+ t, phase, idx = point["logical_step"], point.get("phase"), point.get("index")
73
+ if phase == "layer" and isinstance(idx, int):
74
+ if self.status == "unknown":
75
+ return None
76
+ return (t, ("L", idx)) if idx < self.n else (t, ("out",)) if idx == self.n else None
77
+ if phase == "embed":
78
+ if self.granularity == "layer":
79
+ return (t - 1, ("logits",)) if t >= 1 else (0, ("embed",))
80
+ return t, ("embed",)
81
+ mapped = {"normalization": ("out",), "readout": ("fn",), "sample": ("logits",),
82
+ "commit": ("sample",)}.get(phase)
83
+ return None if mapped is None else (t, mapped)
84
+
85
+ def tick_of_address(self, address):
86
+ if not isinstance(address, addresses.Occurrence):
87
+ return None
88
+ port, layer = address.port, address.layer
89
+ if port == "emb":
90
+ key = ("L", 0) # value_key: tN.emb is tN.L0.h (the embed boundary precedes it)
91
+ elif port == "h_out" and layer is not None:
92
+ if layer > self.n - 1:
93
+ return None
94
+ key = ("out",) if layer == self.n - 1 else ("L", layer + 1)
95
+ elif layer is not None:
96
+ key = ("L", layer)
97
+ elif port == "fn":
98
+ key = ("fn",) if ("fn",) in self.index else ("out",)
99
+ elif port in ("logits", "M"):
100
+ key = ("logits",)
101
+ elif port == "sample":
102
+ key = ("sample",) if ("sample",) in self.index else ("logits",)
103
+ else:
104
+ return None
105
+ return self.index.get(key)
106
+
107
+ def axis(self):
108
+ ticks = []
109
+ for i, key in enumerate(self.keys):
110
+ inferred = self.status == "inferred"
111
+ if key[0] == "L":
112
+ ticks.append(AxisTick(i=i, label=f"L{key[1]}", frag=f"L{key[1]}", port="h",
113
+ detail=f"hidden state entering layer {key[1]}",
114
+ inferred=inferred))
115
+ elif key == ("out",):
116
+ last = max(self.n - 1, 0)
117
+ detail = ("hidden state after the last layer" if self.status == "known" else
118
+ f"hidden state after layer {last}; whether it is the last layer is "
119
+ "not recorded")
120
+ ticks.append(AxisTick(i=i, label=f"L{last} out", frag=f"L{last}", port="h_out",
121
+ detail=detail, inferred=inferred))
122
+ elif key == ("embed",):
123
+ ticks.append(AxisTick(i=i, label="pre-embed", addressable=False,
124
+ detail="before the embedding: the cut holds tokens and "
125
+ "cache, no hidden state; no occurrence address names it "
126
+ "(tN.emb is tN.L0.h)"))
127
+ else:
128
+ port = {"fn": "fn", "logits": "logits", "sample": "sample"}
129
+ ticks.append(AxisTick(i=i, label=key[0], port=port[key[0]],
130
+ detail={"fn": "final-norm output",
131
+ "logits": "readout logits",
132
+ "sample": "sampled token"}[key[0]]))
133
+ if self.status == "known":
134
+ note = f"{self.n} decoder layers; {self.granularity} granularity"
135
+ elif self.status == "inferred":
136
+ note = layer_fallback(self.n) + f"; {self.granularity} granularity"
137
+ else:
138
+ note = f"layer count unknown (no layer ticks drawn); {self.granularity} granularity"
139
+ return ClockAxis(id="layer", label="depth", kind="ordinal", ticks=ticks, note=note)
140
+
141
+
142
+ class SessionModel:
143
+ def __init__(self, project, sid: str):
144
+ self.project, self.sid = project, sid
145
+ self.store_root = _legacy.store_root(project)
146
+ row = _legacy.session_row(project, sid)
147
+ self.row = row
148
+ self._cache, self._problems = {}, []
149
+ self.identity = json.loads(row["identity"])
150
+ self.execution = json.loads(row["execution"])
151
+ self.selected = as_str(row["selected"])
152
+ self.debug_info = json.loads(row["debug_info"])
153
+ for name in ("execution", "debug_info"):
154
+ if not isinstance(getattr(self, name), dict):
155
+ raise ValueError(f"session {name} is not an object")
156
+ if not isinstance(self.identity, (str, dict)):
157
+ raise ValueError("session identity is neither text nor an object")
158
+ self.granularity = as_str(self.execution.get("granularity")) or "layer"
159
+ self.cut_ids = _legacy.cut_ids(project, sid)
160
+ self.cuts = {c: _legacy.cut_descriptor(project, sid, c) for c in self.cut_ids}
161
+ for cut, desc in self.cuts.items():
162
+ parent = desc.get("parent") if isinstance(desc, dict) else 0
163
+ if not (isinstance(desc, dict) and isinstance(desc.get("execution_point"), dict)
164
+ and isinstance(desc.get("surface"), dict)
165
+ and (parent is None or isinstance(parent, str))):
166
+ raise ValueError(f"cut {cut[:12]} has a malformed descriptor")
167
+ # the cuts kept by checkpoint-state records (``Debugger.checkpoint`` stores no native
168
+ # cut beside them): same ids and descriptor fields; a native cut of the same id wins
169
+ self.states = StateCuts(project, sid)
170
+ for cut, entry in self.states.cuts.items():
171
+ if cut not in self.cuts:
172
+ self.cut_ids.append(cut)
173
+ self.cuts[cut] = entry["descriptor"]
174
+ if self.selected not in self.cuts and self.states.cursor is not None:
175
+ self.selected = self.states.cursor # the newest checkpoint's cursor
176
+ self.receipts = _legacy.receipts(project, sid)
177
+ self.slots = {}
178
+ for cut in self.cuts.values():
179
+ for slot in as_list(cut["surface"].get("slots")):
180
+ if isinstance(slot, dict) and isinstance(slot.get("name"), str):
181
+ self.slots.setdefault(slot["name"], slot)
182
+ points = [c["execution_point"] for c in self.cuts.values()]
183
+ steps = [as_int(p.get("logical_step")) for p in points]
184
+ steps = [t for t in steps if t is not None and t >= 0]
185
+ # the recording's first stepped row: the lowest logical step of any cut's execution point
186
+ self.first_step = min(steps) if steps else None
187
+ for receipt in self.receipts:
188
+ for step in receipt.get("transitions") or []:
189
+ points += [step.get("before"), step.get("after")]
190
+ self.n_layers, self.layer_note, self.layers_status = self._layers(points)
191
+ observed = set()
192
+ probe = DepthTicks(self.n_layers, self.granularity, set(), self.layers_status)
193
+ for point in points:
194
+ placed = probe.place(point)
195
+ if placed:
196
+ observed.add(placed[1])
197
+ self.depth = DepthTicks(self.n_layers, self.granularity, observed, self.layers_status)
198
+ self.cell_of_cut = {c: self.place(d["execution_point"]) for c, d in self.cuts.items()}
199
+ self.tokens, self.tokens_reason = self._tokens()
200
+ self.point_cells = [cell for cell in map(self.place, points) if cell]
201
+ columns = [x for x, _ in self.point_cells] + [len(self.tokens or []) - 1, 0]
202
+ self.n_tokens = max(columns) + 1
203
+ self._branches()
204
+
205
+ @property
206
+ def layers_known(self):
207
+ return self.layers_status == "known"
208
+
209
+ def _layers(self, points):
210
+ """``(count, note, status)``: ``known`` only from the cut surface's layer clock; the
211
+ highest recorded layer index is a lower bound (``inferred``), never the model's count."""
212
+ schema = (self.slots.get("layer") or {}).get("schema") or {}
213
+ if isinstance(schema.get("maximum"), int) and not isinstance(schema["maximum"], bool) \
214
+ and schema["maximum"] >= 1:
215
+ return schema["maximum"], "from the cut surface's layer clock", "known"
216
+ seen = [p.get("index") for p in points if isinstance(p, dict) and p.get("phase") == "layer"
217
+ and isinstance(p.get("index"), int) and p["index"] >= 1]
218
+ if not seen:
219
+ return None, LAYER_UNKNOWN, "unknown"
220
+ return max(seen), layer_fallback(max(seen)), "inferred"
221
+
222
+ def place(self, point):
223
+ placed = self.depth.place(point) if hasattr(self, "depth") else None
224
+ if placed is None or placed[1] not in self.depth.index or placed[0] < 0:
225
+ return None
226
+ return placed[0], self.depth.index[placed[1]]
227
+
228
+ def _tokens(self):
229
+ """Token ids from the ``tokens`` slot of the longest retained cut (numpy read)."""
230
+ candidates = [c for c in self.cut_ids if "tokens" in self._slot_names(c)]
231
+ if not candidates:
232
+ return None, "no cut retains a tokens slot"
233
+ best, best_len = None, -1
234
+ for cut in candidates:
235
+ try:
236
+ shape = self.slot_info(cut, "tokens")["shape"] or []
237
+ except (blobs.BlobError, OSError, ValueError):
238
+ continue
239
+ if shape and shape[-1] > best_len:
240
+ best, best_len = cut, shape[-1]
241
+ if best is None:
242
+ return None, "tokens slot has no tensor descriptor"
243
+ try:
244
+ array, _ = self.cut_slot(best, "tokens")
245
+ except blobs.BlobError as error:
246
+ return None, error.reason
247
+ return [int(v) for v in array.reshape(-1).tolist()], None
248
+
249
+ def cut_slot(self, cut, slot, item=None):
250
+ """``(array, info)`` of a slot tensor of a native cut or a checkpoint-state cut."""
251
+ if cut in self.states and not self._native(cut):
252
+ return self.states.cut_slot(cut, slot, item)
253
+ return blobs.cut_slot(self.store_root, cut, slot, item)
254
+
255
+ def slot_info(self, cut, slot, item=None):
256
+ if cut in self.states and not self._native(cut):
257
+ return self.states.slot_info(cut, slot, item)
258
+ return blobs.slot_info(self.store_root, cut, slot, item)
259
+
260
+ def _native(self, cut):
261
+ return (Path(self.store_root) / "cuts" / f"{cut}.json").is_file()
262
+
263
+ def _slot_names(self, cut):
264
+ if cut in self.states and not self._native(cut):
265
+ return self.states.slot_names(cut)
266
+ path = Path(self.store_root) / "cuts" / f"{cut}.json"
267
+ try:
268
+ return set(json.loads(path.read_bytes()).get("slots") or {})
269
+ except (OSError, ValueError):
270
+ return set()
271
+
272
+ def _branches(self):
273
+ """Name branches: the selected cut's lineage is ``main``; each other fork ``b<n>``."""
274
+ self.producer = {}
275
+ for receipt in self.receipts:
276
+ if receipt.get("result") in self.cuts and receipt.get("operation") not in (
277
+ "restore", "abort"):
278
+ self.producer.setdefault(receipt["result"], receipt)
279
+ main, cursor = [], self.selected
280
+ while cursor in self.cuts and cursor not in main:
281
+ main.append(cursor)
282
+ cursor = self.cuts[cursor]["parent"]
283
+ self.branch, taken, count = {c: "main" for c in main}, set(), 0
284
+ for cut in self.cut_ids:
285
+ if cut in self.branch:
286
+ continue
287
+ parent = self.cuts[cut]["parent"]
288
+ inherited = self.branch.get(parent)
289
+ if inherited and inherited != "main" and parent not in taken:
290
+ self.branch[cut] = inherited
291
+ taken.add(parent)
292
+ else:
293
+ count += 1
294
+ self.branch[cut] = f"b{count}"
295
+ self.main = list(reversed(main))
296
+
297
+ def lineage(self, cut):
298
+ out, cursor = [], cut
299
+ while cursor in self.cuts and cursor not in out:
300
+ out.append(cursor)
301
+ cursor = self.cuts[cursor]["parent"]
302
+ return list(reversed(out))
303
+
304
+ def branch_cuts(self, name):
305
+ heads = [c for c in self.cut_ids if self.branch.get(c) == name]
306
+ return self.lineage(heads[-1]) if heads else []
307
+
308
+ def axes(self):
309
+ ticks = []
310
+ for x in range(self.n_tokens):
311
+ token = self.tokens[x] if self.tokens and x < len(self.tokens) else None
312
+ ticks.append(AxisTick(i=x, label=f"t{x}" if token is None else f"t{x}:{token}",
313
+ frag=f"t{x}"))
314
+ token_axis = ClockAxis(id="token", label="token row", kind="ordinal", ticks=ticks,
315
+ note="token rows (logical_step)")
316
+ ports = [AxisTick(i=i, label=name, detail=(slot.get("role") or ""))
317
+ for i, (name, slot) in enumerate(sorted(self.slots.items()))]
318
+ port_axis = ClockAxis(id="port", label="recorded slot", kind="categorical", ticks=ports,
319
+ note="state slots retained in cuts; in-layer ports need the engine")
320
+ return [token_axis, self.depth.axis(), port_axis]
321
+
322
+ def records(self):
323
+ """Every indexed record (legacy ``circuit_records`` and v2 ``records``), read one row at
324
+ a time so one unverifiable row cannot hide the rest. A row whose kind this process has
325
+ not declared, or that fails verification, becomes a placeholder carrying ``unreadable``
326
+ (shown as unresolved). Absent tables read as empty. Sorted by (kind, id): the two tables
327
+ share no insertion order."""
328
+ from ..core import recipe as _recipe # noqa: F401 -- durable checkpoint records
329
+ from ..core import records as core_records # declares the core kinds ("occurrence")
330
+ from ..core.index import get_record
331
+
332
+ rows = []
333
+ try:
334
+ with _legacy.db(self.project) as db:
335
+ tables = {r[0] for r in db.execute(
336
+ "SELECT name FROM sqlite_master WHERE type='table'")}
337
+ if "circuit_records" in tables:
338
+ rows += [(r[0], r[1], "legacy", "legacy") for r in db.execute(
339
+ "SELECT id, kind FROM circuit_records WHERE session_id=?", (self.sid,))]
340
+ if "records" in tables:
341
+ rows += [(r[0], r[1], "v2", "v3" if r[2] == "mdb-record-v3" else "v2")
342
+ for r in db.execute(
343
+ "SELECT id, kind, schema FROM records WHERE session_id=?", (self.sid,))]
344
+ except sqlite3.Error:
345
+ return []
346
+ out = []
347
+ for rid, kind, schema, label in rows:
348
+ try:
349
+ record = get_record(self.project, self.sid, rid)
350
+ if isinstance(record, dict) and record.get("verified") is False:
351
+ # core returns a placeholder row for an undeclared kind or a bad seal
352
+ state = record.get("state") if record.get("state") in (
353
+ "unresolved", "refused") else "unresolved"
354
+ record = {"record_id": rid, "kind": kind, "schema": f"index-{label}",
355
+ "unreadable": (f"{state}: "
356
+ + str(record.get("reason") or "unverified"))[:300],
357
+ "unreadable_state": state}
358
+ out.append(record)
359
+ except Exception as error: # noqa: BLE001 - one corrupt row is one placeholder row
360
+ if schema == "v2" and core_records.kind_spec(kind) is None:
361
+ state, reason = "unresolved", f"unresolved: undeclared kind {kind}"
362
+ else:
363
+ state, reason = "refused", ("refused: record failed verification "
364
+ f"({str(error)[:160] or type(error).__name__})")
365
+ out.append({"record_id": rid, "kind": kind, "schema": f"index-{label}",
366
+ "unreadable": reason[:300], "unreadable_state": state})
367
+ out.sort(key=lambda r: (str(r.get("kind")), str(r.get("id") or r.get("record_id"))))
368
+ return out
369
+
370
+ def _problem(self, kind, ident, error, reason=None):
371
+ reason = reason or (f"refused: {kind} {as_str(ident)[:12] or '?'} could not be read "
372
+ f"({type(error).__name__})")
373
+ if any(p["kind"] == kind and p["record_id"] == (as_str(ident) or kind)
374
+ for p in self._problems):
375
+ return
376
+ self._problems.append({"record_id": as_str(ident) or f"{kind}", "kind": kind,
377
+ "schema": "index-unreadable", "unreadable": reason,
378
+ "unreadable_state": "refused"})
379
+
380
+ def unreadable(self):
381
+ """Placeholder rows for stored rows (slices, symbols, ...) that could not be read."""
382
+ from .views.symbols import build_rows # malformed bindings/lifecycles surface here
383
+
384
+ self.symbols(), self.slices(), self.lifecycles(), self.findings()
385
+ build_rows(self)
386
+ try:
387
+ self.session_graph() # rows left out of the session graph are listed too
388
+ except READ_ERRORS:
389
+ pass
390
+ return list(self._problems)
391
+
392
+ def _refuse(self, kind, ident, error):
393
+ """Per-row refusal from the project reader: the row is listed, the rest is served."""
394
+ self._problem(kind, ident, error)
395
+
396
+ def _graph_refuse(self, kind, ident, error):
397
+ """A row left out of the session graph. Rows already listed as refused are not listed
398
+ twice; a row that is readable on its own (e.g. a record whose reference does not
399
+ resolve) is listed under ``graph:<id>``."""
400
+ ident = as_str(ident) or kind
401
+ if any(p["record_id"] == ident for p in self._problems):
402
+ return
403
+ self._problem("session-graph", "graph:" + ident, error, reason=(
404
+ f"refused from the session graph: {kind} {ident[:12]} "
405
+ f"({type(error).__name__}: {str(error)[:120]})")[:300])
406
+
407
+ def session_graph(self):
408
+ """The sealed session graph (cached); raises when the session history itself does not
409
+ verify. Rows that cannot be placed are left out and listed by ``unreadable()``."""
410
+ if "session_graph" not in self._cache:
411
+ self.symbols(), self.slices(), self.lifecycles(), self.findings()
412
+ try:
413
+ self._cache["session_graph"] = (_legacy.session_graph(
414
+ self.project, self.sid, refuse=self._graph_refuse), None)
415
+ except READ_ERRORS as error:
416
+ self._cache["session_graph"] = (None, error)
417
+ graph, error = self._cache["session_graph"]
418
+ if error is not None:
419
+ raise error
420
+ return graph
421
+
422
+ def _cached(self, key, read):
423
+ if key not in self._cache:
424
+ try:
425
+ self._cache[key] = read()
426
+ except READ_ERRORS as error:
427
+ self._problem(key, key, error)
428
+ self._cache[key] = []
429
+ return self._cache[key]
430
+
431
+ def lifecycles(self):
432
+ return self._cached("lifecycles", lambda: [
433
+ r for r in _legacy.symbol_lifecycles(self.project, self.sid, refuse=self._refuse)
434
+ if isinstance(r, dict) and isinstance(r.get("lifecycle"), dict)
435
+ and isinstance(r.get("joins"), dict) and isinstance(r.get("lifecycle_id"), str)])
436
+
437
+ def findings(self):
438
+ return self._cached("findings", lambda: [
439
+ f for f in _legacy.findings(self.project, self.sid, refuse=self._refuse)
440
+ if isinstance(f, dict) and isinstance(f.get("annotation_id"), str)])
441
+
442
+ def symbols(self):
443
+ return self._cached("symbols", lambda: [
444
+ b for b in _legacy.symbols(self.project, self.sid, refuse=self._refuse)
445
+ if isinstance(b, dict) and isinstance(b.get("fingerprint"), str)])
446
+
447
+ def slices(self):
448
+ if "slices" in self._cache:
449
+ return self._cache["slices"]
450
+ out = []
451
+ try:
452
+ ids = list(_legacy.slice_ids(self.project, self.sid))
453
+ except READ_ERRORS as error:
454
+ self._problem("slice", "slices", error)
455
+ ids = []
456
+ for slice_id in ids:
457
+ try:
458
+ sliced = _legacy.slice_record(self.project, self.sid, slice_id)
459
+ graph = as_dict(as_dict(sliced).get("graph"))
460
+ if not (isinstance(sliced.get("slice_id"), str)
461
+ and isinstance(sliced.get("cut_id"), str)
462
+ and isinstance(sliced.get("component"), str)
463
+ and isinstance(graph.get("nodes"), list)
464
+ and isinstance(graph.get("edges"), list)):
465
+ raise ValueError("malformed slice")
466
+ out.append(sliced)
467
+ except READ_ERRORS as error:
468
+ self._problem("slice", slice_id, error)
469
+ self._cache["slices"] = out
470
+ return out
471
+
472
+ def cells_of_point_digest(self, point_digest):
473
+ return [self.cell_of_cut[c] for c, d in self.cuts.items()
474
+ if self.cell_of_cut[c] and digest(d["execution_point"]) == point_digest]
475
+
476
+
477
+ class Recorded:
478
+ """A project opened read-only, with cached per-session models."""
479
+
480
+ def __init__(self, root):
481
+ self.root = Path(root).expanduser().resolve()
482
+ self.project = _legacy.open_project(self.root)
483
+ self._models, self._lock = {}, threading.Lock()
484
+
485
+ def sessions(self):
486
+ return _legacy.sessions(self.project)
487
+
488
+ def _revision(self, sid):
489
+ with _legacy.db(self.project) as db:
490
+ tables = {r[0] for r in db.execute("SELECT name FROM sqlite_master")}
491
+ parts = [db.execute("SELECT revision FROM sessions WHERE id=?", (sid,)).fetchone()]
492
+ for table in ("cuts", "receipts", "symbols", "slices", "records",
493
+ "circuit_records", "symbol_lifecycles"):
494
+ if table in tables:
495
+ parts.append(db.execute(f"SELECT count(*) FROM {table} WHERE session_id=?",
496
+ (sid,)).fetchone()[0])
497
+ if parts[0] is None:
498
+ raise KeyError(sid)
499
+ return tuple([parts[0][0], *parts[1:]])
500
+
501
+ def model(self, sid) -> SessionModel:
502
+ revision = self._revision(sid)
503
+ with self._lock:
504
+ cached = self._models.get(sid)
505
+ if cached and cached[0] == revision:
506
+ return cached[1]
507
+ try:
508
+ built = SessionModel(self.project, sid)
509
+ except Exception as error: # noqa: BLE001 - a corrupt session is refused, not a crash
510
+ raise SessionUnreadable(
511
+ f"session {sid[:24]!r} is unreadable ({type(error).__name__}: "
512
+ f"{str(error)[:120]})") from error
513
+ with self._lock:
514
+ self._models[sid] = (revision, built)
515
+ return built