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
@@ -0,0 +1,224 @@
1
+ """Graph view: a sealed slice graph (or the session graph) laid out on clock coordinates.
2
+
3
+ Nodes keep the ids of the recorded ``StateGraph``. Nodes beyond ``k`` (nearest to the center
4
+ first) are folded into one aggregate node per (kind, role) group, reported in ``pruned``.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import sqlite3
9
+ from collections import deque
10
+
11
+ from ..schema import CircuitOverlay, GraphEdge, GraphNode, GraphView, PrunedGroup, SliceRef
12
+ from ..stored import as_str
13
+ from .common import ViewError, address_cell, cell_address, parse, record_id, short
14
+ from .records import _interaction
15
+
16
+ MAX_K = 64
17
+
18
+
19
+ def _slice_ref(sliced):
20
+ return SliceRef(id=sliced["slice_id"], component=sliced["component"], cut=sliced["cut_id"],
21
+ complete=bool(sliced["complete"]))
22
+
23
+
24
+ def _role(kind, labels, meta, source_ref):
25
+ if source_ref.startswith("symbol://") or "binding" in meta:
26
+ return "symbol"
27
+ if source_ref.startswith("slice-gap://"):
28
+ return "gap"
29
+ if source_ref.startswith(("circuit://", "slice://", "state-annotation://", "watch://")):
30
+ return "record"
31
+ if kind == "action":
32
+ return "operation"
33
+ if kind == "state":
34
+ return "state"
35
+ slot = meta.get("slot") or (labels[0] if labels else "")
36
+ return {"keys": "cache", "values": "cache", "tokens": "cursor", "logits": "readout",
37
+ "hidden": "carrier"}.get(slot, "value")
38
+
39
+
40
+ def _node(model, raw):
41
+ content = raw.get("content") or {}
42
+ meta = content.get("metadata") or {}
43
+ labels = raw.get("labels") or []
44
+ kind = raw["kind"]
45
+ source_ref = str(content.get("source_ref") or content.get("act_ref") or "")
46
+ cell = None
47
+ native = meta.get("native_receipt") if isinstance(meta.get("native_receipt"), dict) else {}
48
+ if native.get("operation"):
49
+ meta = {**meta, "operation": native["operation"], "receipt": native.get("fingerprint")}
50
+ if kind == "action":
51
+ point = meta.get("point")
52
+ cell = model.place(point) if point else None
53
+ if cell is None and native.get("parent") in model.cell_of_cut:
54
+ cell = model.cell_of_cut[native["parent"]]
55
+ elif kind == "state":
56
+ cell = model.cell_of_cut.get(content.get("state_fingerprint") or "")
57
+ else:
58
+ cut = meta.get("native_cut") or (meta.get("boundary") or {}).get("cut")
59
+ cell = model.cell_of_cut.get(cut) if cut else None
60
+ label = labels[0] if labels else (meta.get("operation") or kind)
61
+ if kind == "state":
62
+ label = "cut " + short(content.get("state_fingerprint", ""), 8)
63
+ small = {k: meta[k] for k in ("slot", "operation", "receipt", "native_cut", "kind",
64
+ "record_id", "terminal_status", "support") if k in meta
65
+ and isinstance(meta[k], (str, bool))}
66
+ return GraphNode(id=raw["node_id"], kind=kind, label=str(label)[:48],
67
+ role=_role(kind, labels, meta, source_ref),
68
+ x=cell[0] if cell else None, y=cell[1] if cell else None,
69
+ addr=cell_address(model, *cell) if cell else None,
70
+ ev="measured" if raw.get("evidence") and any(
71
+ e.get("class") == "observed" for e in raw["evidence"]) else None,
72
+ meta=small)
73
+
74
+
75
+ def _edge_type(edge, nodes):
76
+ evidence = [e.get("class") for e in edge.get("evidence") or []]
77
+ if edge["graph"] == "knowledge":
78
+ return "attribution" if nodes.get(edge["source"], {}).get("role") == "symbol" \
79
+ else "unknown"
80
+ relation = edge["relation"]
81
+ target = nodes.get(edge["target"], {})
82
+ source = nodes.get(edge["source"], {})
83
+ if relation == "writes" and target.get("role") == "cache":
84
+ return "kv_write"
85
+ if (source.get("meta") or {}).get("operation") == "apply":
86
+ return "intervention"
87
+ return "dataflow" if "observed" in evidence else "declared"
88
+
89
+
90
+ def _choose_slice(model, slices, addr, slice_id):
91
+ if slice_id:
92
+ match = [s for s in slices if s["slice_id"].startswith(slice_id)]
93
+ if len(match) != 1:
94
+ raise ViewError("unknown_slice", f"slice {slice_id!r} matches {len(match)} slices", 404)
95
+ return match[0]
96
+ if addr:
97
+ cell = address_cell(model, parse(addr))
98
+ at = [s for s in slices if model.cell_of_cut.get(s["cut_id"]) == cell]
99
+ if at:
100
+ return at[-1]
101
+ return slices[-1] if slices else None
102
+
103
+
104
+ def _prune(nodes, edges, center, depth, k):
105
+ adjacent = {}
106
+ for e in edges:
107
+ adjacent.setdefault(e.source, []).append(e.target)
108
+ adjacent.setdefault(e.target, []).append(e.source)
109
+ order, dist = [], {}
110
+ starts = [center] if center in nodes else list(nodes)[:1]
111
+ queue = deque((s, 0) for s in starts)
112
+ while queue:
113
+ node, d = queue.popleft()
114
+ if node in dist:
115
+ continue
116
+ dist[node] = d
117
+ order.append(node)
118
+ for nxt in sorted(adjacent.get(node, [])):
119
+ if nxt not in dist and d + 1 <= depth:
120
+ queue.append((nxt, d + 1))
121
+ order += sorted(n for n in nodes if n not in dist)
122
+ kept = set(order[:k])
123
+ groups = {}
124
+ for node in order[k:]:
125
+ n = nodes[node]
126
+ groups.setdefault((n.kind, n.role), []).append(node)
127
+ out_nodes = [nodes[n] for n in order[:k]]
128
+ folded, pruned = {}, []
129
+ for (kind, role), members in sorted(groups.items()):
130
+ gid = f"more:{kind}:{role}"
131
+ folded.update({m: gid for m in members})
132
+ out_nodes.append(GraphNode(id=gid, kind="aggregate", label=f"+{len(members)} more {role}",
133
+ role=role, count=len(members)))
134
+ pruned.append(PrunedGroup(group=f"{kind}/{role}", count=len(members), node=gid))
135
+ out_edges, seen = [], set()
136
+ for e in edges:
137
+ s, t = folded.get(e.source, e.source), folded.get(e.target, e.target)
138
+ if s == t or (s not in kept and not s.startswith("more:")) or (
139
+ t not in kept and not t.startswith("more:")):
140
+ continue
141
+ key = (s, t, e.type)
142
+ if key in seen:
143
+ continue
144
+ seen.add(key)
145
+ out_edges.append(e.model_copy(update={"source": s, "target": t,
146
+ "id": e.id if (s, t) == (e.source, e.target)
147
+ else f"{e.id[:16]}~{s[-8:]}~{t[-8:]}"}))
148
+ return out_nodes, out_edges, pruned
149
+
150
+
151
+ def _overlays(model, sliced, node_ids):
152
+ out = []
153
+ if sliced is None:
154
+ return out
155
+ records = [r for r in model.records() if isinstance(r, dict)]
156
+ focus = [r for r in records if r.get("kind") == "focus"
157
+ and r.get("slice_id") == sliced["slice_id"]]
158
+ for f in focus:
159
+ members = [n for n in [f.get("node_id")] if isinstance(n, str) and n in node_ids]
160
+ if not members:
161
+ continue
162
+ fid = record_id(f)
163
+ out.append(CircuitOverlay(id="focus:" + fid, kind="focus",
164
+ label=f"focus {as_str(f.get('component'))[:48]}",
165
+ nodes=members,
166
+ verdict=as_str(f.get("terminal_status")) or "unknown",
167
+ record=fid))
168
+ for r in records:
169
+ if r.get("focus_id") == fid and r.get("kind") in ("comparison", "interface-test"):
170
+ rid = record_id(r)
171
+ # the number is a labelled field, never text in the label
172
+ interaction = _interaction(r) if r["kind"] == "comparison" else None
173
+ out.append(CircuitOverlay(id=f"{r['kind']}:{rid}", kind=r["kind"],
174
+ label=r["kind"], interaction=interaction,
175
+ nodes=members,
176
+ verdict=as_str(r.get("terminal_status")) or "unknown",
177
+ record=rid))
178
+ return out[:16]
179
+
180
+
181
+ def graph(model, *, addr=None, zoom="slice", depth=3, k=48, slice_id=None):
182
+ if zoom not in ("slice", "session"):
183
+ raise ViewError("bad_zoom", "zoom is 'slice' or 'session'")
184
+ if not 1 <= k <= MAX_K or not 0 <= depth <= 16:
185
+ raise ViewError("bad_bounds", f"k is 1..{MAX_K} and depth 0..16")
186
+ slices = model.slices()
187
+ sliced = _choose_slice(model, slices, addr, slice_id) if zoom == "slice" else None
188
+ if zoom == "slice" and sliced is None:
189
+ zoom = "session"
190
+ if zoom == "slice":
191
+ raw_nodes, raw_edges = sliced["graph"]["nodes"], sliced["graph"]["edges"]
192
+ center = (sliced.get("targets") or [None])[0]
193
+ authority = sliced.get("authority", "declared-dependency")
194
+ else:
195
+ try:
196
+ snap = model.session_graph()
197
+ except (ValueError, KeyError, TypeError, AttributeError, LookupError, OSError,
198
+ sqlite3.Error) as error:
199
+ raise ViewError("graph_unreadable", "the session graph could not be read "
200
+ f"({type(error).__name__})", 409) from error
201
+ raw_nodes, raw_edges = snap["nodes"], snap["edges"]
202
+ center = None
203
+ authority = "recorded history (execution + knowledge graphs)"
204
+ nodes = {n["node_id"]: _node(model, n) for n in raw_nodes}
205
+ plain = {i: n.model_dump() for i, n in nodes.items()}
206
+ edges = [GraphEdge(id=e["edge_id"], source=e["source"], target=e["target"],
207
+ type=_edge_type(e, plain), relation=e["relation"],
208
+ evidence=",".join(sorted({x.get("class", "?") for x in e.get("evidence")
209
+ or []})) or "none")
210
+ for e in raw_edges if e["source"] in nodes and e["target"] in nodes]
211
+ if addr and zoom == "session":
212
+ cell = address_cell(model, parse(addr))
213
+ at = [n.id for n in nodes.values() if (n.x, n.y) == cell and n.kind == "state"]
214
+ center = at[-1] if at else None
215
+ out_nodes, out_edges, pruned = _prune(nodes, edges, center, depth, k)
216
+ lanes = {}
217
+ for n in out_nodes:
218
+ if n.x is None:
219
+ lanes.setdefault(n.role, len(lanes))
220
+ n.lane = lanes[n.role]
221
+ return GraphView(zoom=zoom, center=center, slice=_slice_ref(sliced) if sliced else None,
222
+ nodes=out_nodes, edges=out_edges, pruned=pruned,
223
+ overlays=_overlays(model, sliced, {n.id for n in out_nodes}),
224
+ slices=[_slice_ref(s) for s in slices][:32], authority=authority)
@@ -0,0 +1,402 @@
1
+ """Live views: the cursor frame, its lists page by page, the clock, and the run's ledger
2
+ (circuits, forecasts, declared symbols) of a live session.
3
+
4
+ All run on the live session's worker thread (``LiveSession.call``). Tables, ports and edits come
5
+ from read ops through ``mdb.ops.dispatch`` (``where``, ``list``, ``info``, ``checkpoints``),
6
+ edit provenance from ``Run.read_info`` and durable checkpoints from ``Debugger.checkpoints``;
7
+ nothing here re-derives what an op or the engine reports.
8
+
9
+ The frame always fits the response cap. Each list in it (breakpoints, displays, checkpoints,
10
+ staged and committed edits, and each port's upstream edits) shows its first items within a byte
11
+ budget and names what it left out in ``more`` (``Omitted``: the list, how many, and the
12
+ ``GET .../live/items`` request that pages through the rest). An item larger than ``ITEM_BYTES``
13
+ is shown clipped (long strings shortened, ``clipped: <bytes>``) and served whole by the items
14
+ route when it fits a page. If the frame is still over budget (very long conditions, many
15
+ ports), every list budget is halved until it fits; the ports themselves are never dropped.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from typing import Any, get_args
21
+
22
+ from ..schema import (
23
+ CAP_BYTES,
24
+ Ev,
25
+ LiveCheckpoint,
26
+ LiveCircuit,
27
+ LiveEdit,
28
+ LiveForecast,
29
+ LiveFrame,
30
+ LiveItems,
31
+ LiveLedger,
32
+ LivePort,
33
+ LiveRow,
34
+ LiveState,
35
+ LiveStop,
36
+ LiveSymbol,
37
+ LiveTimeline,
38
+ LiveUpstream,
39
+ Omitted,
40
+ )
41
+
42
+ PAGE = 64 # the most one op page holds
43
+ MAX_ROWS = 256 # rows a live timeline lists (the latest)
44
+ LABELS = get_args(Ev)
45
+ LISTS = ("breakpoints", "displays", "checkpoints", "staged", "committed", "upstream")
46
+ FRAME_BYTES = CAP_BYTES - 8192 # the frame's data; the rest is envelope and headroom
47
+ PAGE_BYTES = CAP_BYTES - 8192 # one items page
48
+ ITEM_BYTES = 2048 # an item larger than this is clipped in the frame
49
+ UPSTREAM_SHOWN = 4 # upstream edits listed per port (all are counted)
50
+ BUDGETS = {"breakpoints": 6144, "displays": 3072, "checkpoints": 4096, "staged": 6144,
51
+ "committed": 10240}
52
+ LEDGER_LIMIT = 64 # entries per ledger list (the latest)
53
+ LEDGER_BYTES = CAP_BYTES - 8192 # the ledger's data
54
+
55
+
56
+ def _read(ctx, name, **args):
57
+ from mdb.ops import dispatch
58
+
59
+ return dispatch(ctx, name, args)
60
+
61
+
62
+ def _size(value: Any) -> int:
63
+ return len(json.dumps(value, separators=(",", ":"), ensure_ascii=False, default=str))
64
+
65
+
66
+ def _shorten(value: Any) -> Any:
67
+ if isinstance(value, str) and len(value) > 200:
68
+ return value[:200] + "…"
69
+ if isinstance(value, dict):
70
+ return {k: _shorten(v) for k, v in value.items()}
71
+ if isinstance(value, list):
72
+ return [_shorten(v) for v in value[:8]]
73
+ return value
74
+
75
+
76
+ def clip(item: Any, limit: int = ITEM_BYTES) -> Any:
77
+ """``item`` unchanged when it fits ``limit`` bytes, else shortened (strings to 200
78
+ characters, lists to 8 items) with ``clipped`` set to its full size in bytes."""
79
+ size = _size(item)
80
+ if size <= limit or not isinstance(item, dict):
81
+ return item
82
+ short = _shorten(item)
83
+ short["clipped"] = size
84
+ return short
85
+
86
+
87
+ def fit(items: list, budget: int, *, clip_items: bool = True) -> list:
88
+ """The longest prefix of ``items`` whose JSON fits ``budget`` bytes (items clipped first)."""
89
+ out, used = [], 0
90
+ for item in items:
91
+ item = clip(item) if clip_items else item
92
+ size = _size(item) + 1
93
+ if used + size > budget:
94
+ break
95
+ out.append(item)
96
+ used += size
97
+ return out
98
+
99
+
100
+ def _paged(ctx, subject: str, key: str) -> list:
101
+ out, offset = [], 0
102
+ while True:
103
+ page = _read(ctx, "info", subject=subject, offset=offset, limit=PAGE)
104
+ out += page[key]
105
+ offset += PAGE
106
+ if offset >= page["total"]:
107
+ return out
108
+
109
+
110
+ def _edits(ctx) -> tuple[list, list]:
111
+ """Every staged edit and every committed edit (flat, in commit order: each carries its
112
+ ``row``, ``layer`` and ``transition``), from the ``info edits`` op."""
113
+ staged, committed, offset = [], [], 0
114
+ while True:
115
+ page = _read(ctx, "info", subject="edits", offset=offset, limit=PAGE)
116
+ staged += page["staged"]
117
+ for group in page["committed"]:
118
+ committed += [{**edit, "row": group["row"], "layer": group["layer"],
119
+ "transition": group["transition"]} for edit in group["edits"]]
120
+ offset += PAGE
121
+ if offset >= page["total"]:
122
+ return staged, committed
123
+
124
+
125
+ def _limits(debugger) -> dict[str, int]:
126
+ """The model's geometry the views lay out against: layers, positions, query and KV heads."""
127
+ adapter = debugger.adapter
128
+ return {"layers": int(adapter.layers), "max_positions": int(adapter.max_positions),
129
+ "heads": int(adapter.num_heads), "kv_heads": int(adapter.num_kv_heads)}
130
+
131
+
132
+ def _selection(record) -> str | None:
133
+ """The selector text of an edit record: its ``selection``, else the bracket of a state
134
+ cell's address (``cache.L1.v[row=2]`` -> ``row=2``); None for a whole port."""
135
+ selection = record.get("selection")
136
+ if isinstance(selection, str) and selection:
137
+ return selection
138
+ cell = record.get("cell")
139
+ if isinstance(cell, str) and "[" in cell:
140
+ return cell.partition("[")[2].rstrip("]") or None
141
+ return None
142
+
143
+
144
+ def _upstream(info) -> list[dict]:
145
+ return [{**{k: item[k] for k in ("row", "layer", "port", "op", "staged")},
146
+ "selection": _selection(item)} for item in info["upstream_edits"]]
147
+
148
+
149
+ def _mark(layer, record) -> str:
150
+ """A row's edit mark: ``L<layer>.<port>`` with the edit's selector (``L22.A[h6]``)."""
151
+ selection = _selection(record)
152
+ return f"L{layer}.{record['port']}" + (f"[{selection}]" if selection else "")
153
+
154
+
155
+ def edit_of(run, addr: str, shown: int = UPSTREAM_SHOWN) -> LiveEdit:
156
+ """``Run.read_info(addr)`` as a ``LiveEdit`` (the first ``shown`` upstream edits, all
157
+ counted). An authority outside the record vocabulary is not relabelled: the edit is refused
158
+ and says what the engine reported."""
159
+ info = run.read_info(addr)
160
+ authority, state, reason = info["authority"], info["state"], info["reason"]
161
+ if authority is not None and authority not in LABELS:
162
+ authority, state = None, "refused"
163
+ reason = f"the engine reported authority {info['authority']!r}, not a record label"
164
+ by = info["by"]
165
+ upstream = _upstream(info)
166
+ return LiveEdit(state=state, authority=authority, edited=bool(info["edited"]),
167
+ kind=str(info["kind"]), by=None if by is None else str(by),
168
+ reason=reason if state != "resolved" else None,
169
+ upstream=[LiveUpstream(**u) for u in upstream[:shown]],
170
+ upstream_total=len(upstream))
171
+
172
+
173
+ def checkpoints(session) -> list[LiveCheckpoint]:
174
+ """One row per checkpoint name: a name is the key and its latest checkpoint wins. With a
175
+ project the latest durable record of each name (``restart NAME`` replays exactly that one
176
+ after a server restart; the in-memory copy, written after it, is the same position), else the
177
+ in-memory checkpoint (``checkpoints`` op). Order: first use of each name."""
178
+ memory = {}
179
+ offset = 0
180
+ while True:
181
+ page = _read(session.ctx, "checkpoints", offset=offset, limit=PAGE)
182
+ memory.update({c["name"]: c["where"] for c in page["checkpoints"]})
183
+ offset += PAGE
184
+ if offset >= page["total"]:
185
+ break
186
+ rows: dict[str, LiveCheckpoint] = {}
187
+ if session.debugger.project is not None:
188
+ for item in session.debugger.checkpoints(): # oldest first: the latest of a name wins
189
+ rows[item["name"]] = LiveCheckpoint(name=item["name"], where=item["where"],
190
+ store="durable")
191
+ for name, where in memory.items():
192
+ if name not in rows:
193
+ rows[name] = LiveCheckpoint(name=name, where=where, store="memory")
194
+ return list(rows.values())
195
+
196
+
197
+ def _items_route(session, name: str, offset: int, addr: str | None = None) -> str:
198
+ tail = f"&addr={addr}" if addr else ""
199
+ return f"GET /api/v1/s/{session.sid}/live/items?list={name}&offset={offset}{tail}"
200
+
201
+
202
+ def full_list(session, name: str, addr: str | None = None) -> list:
203
+ """Every item of one frame list (see ``LISTS``); ``upstream`` needs ``addr``."""
204
+ ctx = session.ctx
205
+ if name == "breakpoints":
206
+ return _paged(ctx, "breakpoints", "items")
207
+ if name == "displays":
208
+ return _paged(ctx, "display", "displays")
209
+ if name == "checkpoints":
210
+ return [c.model_dump(mode="json") for c in checkpoints(session)]
211
+ if ctx.run is None:
212
+ return []
213
+ if name in ("staged", "committed"):
214
+ staged, committed = _edits(ctx)
215
+ return staged if name == "staged" else committed
216
+ if name == "upstream":
217
+ if not addr:
218
+ raise ValueError("the upstream list names a computed address (addr=)")
219
+ return _upstream(ctx.run.read_info(addr))
220
+ raise ValueError(f"no live list {name!r}; lists: {', '.join(LISTS)}")
221
+
222
+
223
+ def items(session, name: str, offset: int = 0, addr: str | None = None) -> LiveItems:
224
+ """One page of a frame list from ``offset``: as many whole items as fit ``PAGE_BYTES`` (at
225
+ least one, clipped if even it alone is over the page)."""
226
+ every = full_list(session, name, addr)
227
+ rest = every[offset:]
228
+ shown = fit(rest, PAGE_BYTES, clip_items=False)
229
+ if not shown and rest:
230
+ shown = [clip(rest[0], PAGE_BYTES)]
231
+ end = offset + len(shown)
232
+ return LiveItems(list=name, addr=addr, offset=offset, total=len(every), items=shown,
233
+ next=end if end < len(every) else None)
234
+
235
+
236
+ def frame(session) -> tuple[LiveFrame, list[Omitted]]:
237
+ """The live frame (see ``LiveFrame``) and what it left out."""
238
+ ctx, debugger = session.ctx, session.debugger
239
+ lists = {"breakpoints": full_list(session, "breakpoints"),
240
+ "displays": full_list(session, "displays"),
241
+ "checkpoints": full_list(session, "checkpoints")}
242
+ base = dict(session=session.sid, family=debugger.family, seq=session.seq,
243
+ live=LiveState(state="paused"), limits=_limits(debugger))
244
+ ports, upstream_totals, where, listing, edits_meta = [], {}, None, None, {}
245
+ if ctx.run is not None:
246
+ where = _read(ctx, "where")
247
+ listing = _read(ctx, "list")
248
+ lists["staged"], lists["committed"] = _edits(ctx)
249
+ edits_meta = {"where": ctx.run.where}
250
+ row, layer = listing["row"], listing["layer"]
251
+ for item in listing["ports"]:
252
+ addr = f"t{row}.L{layer}.{item['port']}"
253
+ edit = edit_of(ctx.run, addr) if item["computed"] else None
254
+ if edit is not None:
255
+ upstream_totals[addr] = edit.upstream_total
256
+ ports.append(LivePort(
257
+ port=item["port"], addr=addr, sublayer=item["sublayer"],
258
+ operator=item["operator"], proofs=list(item["proofs"]),
259
+ editable=bool(item["editable"]), cursor=bool(item["cursor"]),
260
+ focus=bool(item["focus"]), computed=bool(item["computed"]), edit=edit))
261
+ scale = 1.0
262
+ while True:
263
+ # a checkpoint row is never clipped: its name is what `restart` is sent
264
+ shown = {name: fit(values, int(BUDGETS[name] * scale),
265
+ clip_items=name != "checkpoints") for name, values in lists.items()}
266
+ more = [Omitted(field=name, count=len(values) - len(shown[name]),
267
+ reason=_items_route(session, name, len(shown[name])))
268
+ for name, values in lists.items() if len(shown[name]) < len(values)]
269
+ keep = UPSTREAM_SHOWN if scale >= 0.5 else 0
270
+ for port in ports:
271
+ if port.edit is not None:
272
+ port.edit.upstream = port.edit.upstream[:keep]
273
+ if port.edit.upstream_total > keep:
274
+ more.append(Omitted(
275
+ field=f"upstream:{port.addr}", count=port.edit.upstream_total - keep,
276
+ reason=_items_route(session, "upstream", keep, port.addr)))
277
+ if ctx.run is None:
278
+ built = LiveFrame(**base, where=None, stop=None, row=None, layer=None, ports=[],
279
+ tokens=[], edits=None, breakpoints=shown["breakpoints"],
280
+ displays=shown["displays"], checkpoints=shown["checkpoints"],
281
+ more=more)
282
+ else:
283
+ edits = {**edits_meta, "staged": shown["staged"], "committed": shown["committed"],
284
+ "staged_total": len(lists["staged"]),
285
+ "committed_total": len(lists["committed"])}
286
+ built = LiveFrame(**base, where=where["where"], stop=where["stop"],
287
+ row=listing["row"], layer=listing["layer"], ports=ports,
288
+ checks=listing.get("checks"), tokens=where["tokens"], edits=edits,
289
+ breakpoints=shown["breakpoints"], displays=shown["displays"],
290
+ checkpoints=[LiveCheckpoint(**c) for c in shown["checkpoints"]],
291
+ more=more)
292
+ if _size(built.model_dump(mode="json")) <= FRAME_BYTES or scale < 1 / 64:
293
+ return built, more
294
+ scale /= 2
295
+
296
+
297
+ def _test_summary(test: dict | None) -> str | None:
298
+ """The last ``circuit test`` in one line: its two measured ratios against the reference, or
299
+ why they were refused (there is no pass/fail verdict)."""
300
+ if test is None:
301
+ return None
302
+ ref, ratios = test.get("reference", {}), test.get("ratios", {})
303
+ if ratios.get("state"):
304
+ return f"ref {ref.get('name')}: ratios {ratios['state']}"
305
+ return (f"ref {ref.get('name')}: faithfulness {ratios['faithfulness']['value']:.4g}, "
306
+ f"knock-out share {ratios['knockout_share']['value']:.4g} [measured]")
307
+
308
+
309
+ def _circuit_row(circuit, carried=None) -> LiveCircuit:
310
+ """A ledger row; ``carried`` is the debugger's ``carried_circuits`` (id -> circuit built by
311
+ an earlier run), the test ``circuit show`` uses for ``from_previous_run``."""
312
+ body = circuit.record["body"]
313
+ last = circuit.tests[-1] if circuit.tests else None
314
+ previous = (carried or {}).get(circuit.id) is circuit
315
+ return LiveCircuit(id=int(circuit.id), consumer=str(body["consumer"]), k=int(body["k"]),
316
+ depth=int(body["depth"]), count=int(body["count"]),
317
+ where=str(body["where"]), record=str(circuit.record["id"]),
318
+ tests=len(circuit.tests),
319
+ verdict=_test_summary(last),
320
+ from_previous_run=previous)
321
+
322
+
323
+ def _forecast_row(entry) -> LiveForecast:
324
+ from mdb.analysis.predict import forecast
325
+
326
+ view = forecast.view(entry)
327
+ bound = {k: v for k, v in view["bound"].items() if k != "premises"}
328
+ return LiveForecast(id=int(view["id"]), target=str(view["target"]),
329
+ status=str(view["status"]), sealed_at=str(view["sealed_at"]),
330
+ record=str(view["record"]), steps=int(view["method_summary"]["count"]),
331
+ predicted=view["predicted"], bound=bound,
332
+ verdict=view.get("verdict"))
333
+
334
+
335
+ def ledger(session, limit: int = LEDGER_LIMIT) -> tuple[LiveLedger, list[Omitted]]:
336
+ """The run's circuit ledger, its sealed forecasts and its declared symbols: the latest
337
+ ``limit`` of each, within ``LEDGER_BYTES`` (what is left out is named in ``more``). Read
338
+ from the ledgers the ``circuit``, ``forecast`` and ``symbol`` ops keep on the run; nothing is
339
+ recomputed. Without a run every list is empty."""
340
+ from mdb.analysis.circuits import build as circuits
341
+ from mdb.analysis.predict import forecast
342
+ from mdb.analysis.symbols import table as symbols
343
+
344
+ run = session.ctx.run
345
+ rows: dict[str, list] = {"circuits": [], "forecasts": [], "symbols": []}
346
+ if run is not None:
347
+ carried = getattr(session.debugger, "carried_circuits", None)
348
+ rows["circuits"] = [_circuit_row(c, carried)
349
+ for _, c in sorted(circuits.ledger(run).items())]
350
+ rows["forecasts"] = [_forecast_row(e) for _, e in sorted(forecast.ledger(run).items())]
351
+ rows["symbols"] = [LiveSymbol(name=name, definitions=list(b.addresses),
352
+ rows=sorted({int(c.row) for c in b.cells}))
353
+ for name, b in sorted(symbols.declared(run).items())]
354
+ budget = LEDGER_BYTES // 3
355
+ shown, more = {}, []
356
+ for name, items in rows.items():
357
+ latest = items[-limit:]
358
+ dumped = fit([i.model_dump(mode="json") for i in reversed(latest)], budget,
359
+ clip_items=False)
360
+ shown[name] = items[len(items) - len(dumped):]
361
+ if len(shown[name]) < len(items):
362
+ more.append(Omitted(field=name, count=len(items) - len(shown[name]),
363
+ reason="the earliest entries (lower ids)"))
364
+ names = [name for name, other in (getattr(session.debugger, "runs", None) or {}).items()
365
+ if other is not run]
366
+ return LiveLedger(session=session.sid, seq=session.seq,
367
+ where=None if run is None else run.where, more=more,
368
+ runs=names[:LEDGER_LIMIT], **shown), more
369
+
370
+
371
+ def timeline(session) -> tuple[LiveTimeline, int]:
372
+ """The live clock and how many earlier rows it left out (``MAX_ROWS`` latest are listed)."""
373
+ ctx, debugger = session.ctx, session.debugger
374
+ run = ctx.run
375
+ if run is None:
376
+ return LiveTimeline(session=session.sid, where=None, stops=[], cursor=None, root=None,
377
+ rows=[], limits=_limits(debugger)), 0
378
+ stops = list(run.stops())
379
+ here_row, here_index = run.parse(run.where)
380
+ # the run's root: the first stepped row's start (prefill=K), or a stored cut's stop
381
+ root_row, root_index = run.parse(run.root)
382
+ context = [int(t) for t in run.session.read("tokens")[0].tolist()]
383
+ marks: dict[int, list[str]] = {}
384
+ for record in run.committed_edits():
385
+ marks.setdefault(int(record["row"]), []).append(_mark(record["layer"], record))
386
+ pending = run.pending_layer
387
+ for record in run.staged_info():
388
+ marks.setdefault(here_row, []).append(f"{_mark(pending, record)} (staged)")
389
+ rows = []
390
+ for row in range(here_row + 1):
391
+ first = root_index if row == root_row else 0 # stops of this row the run has
392
+ count = (None if row < root_row else len(stops) - first if row < here_row
393
+ else here_index + 1 - first)
394
+ rows.append(LiveRow(row=row, token=context[row] if row < len(context) else None,
395
+ count=count, edits=marks.get(row, [])))
396
+ left_out = max(0, len(rows) - MAX_ROWS)
397
+ return LiveTimeline(
398
+ session=session.sid, where=run.where, stops=stops,
399
+ cursor=LiveStop(row=here_row, index=here_index, label=stops[here_index]),
400
+ root=LiveStop(row=root_row, index=root_index, label=stops[root_index]),
401
+ rows=rows[left_out:],
402
+ limits=_limits(debugger)), left_out