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.
- mdb/__init__.py +43 -0
- mdb/__main__.py +5 -0
- mdb/analysis/__init__.py +34 -0
- mdb/analysis/circuits/__init__.py +6 -0
- mdb/analysis/circuits/build.py +690 -0
- mdb/analysis/circuits/test.py +600 -0
- mdb/analysis/features/__init__.py +5 -0
- mdb/analysis/features/basis.py +685 -0
- mdb/analysis/features/sae.py +374 -0
- mdb/analysis/features/watch.py +268 -0
- mdb/analysis/measure/__init__.py +7 -0
- mdb/analysis/measure/branches.py +806 -0
- mdb/analysis/measure/bridge.py +379 -0
- mdb/analysis/measure/changes.py +201 -0
- mdb/analysis/measure/compare.py +348 -0
- mdb/analysis/measure/donors.py +193 -0
- mdb/analysis/measure/novelty.py +227 -0
- mdb/analysis/measure/paths.py +146 -0
- mdb/analysis/measure/pools.py +454 -0
- mdb/analysis/measure/readout.py +387 -0
- mdb/analysis/measure/reads.py +455 -0
- mdb/analysis/measure/sweep.py +215 -0
- mdb/analysis/numerics/__init__.py +6 -0
- mdb/analysis/numerics/accumulation.py +180 -0
- mdb/analysis/numerics/finite.py +1712 -0
- mdb/analysis/numerics/labels.py +80 -0
- mdb/analysis/numerics/pooling.py +89 -0
- mdb/analysis/numerics/stability.py +183 -0
- mdb/analysis/numerics/summary.py +306 -0
- mdb/analysis/numerics/units.py +86 -0
- mdb/analysis/numerics/verdict.py +244 -0
- mdb/analysis/numerics/why_frames.py +162 -0
- mdb/analysis/predict/__init__.py +7 -0
- mdb/analysis/predict/capture.py +265 -0
- mdb/analysis/predict/consumers.py +52 -0
- mdb/analysis/predict/explain.py +776 -0
- mdb/analysis/predict/forecast.py +635 -0
- mdb/analysis/predict/plan.py +248 -0
- mdb/analysis/predict/propagate.py +596 -0
- mdb/analysis/predict/rounding.py +95 -0
- mdb/analysis/predict/rowmodel.py +817 -0
- mdb/analysis/predict/supplied.py +103 -0
- mdb/analysis/predict/verify.py +433 -0
- mdb/analysis/predict/whatif.py +840 -0
- mdb/analysis/symbols/__init__.py +7 -0
- mdb/analysis/symbols/binding.py +138 -0
- mdb/analysis/symbols/candidates.py +320 -0
- mdb/analysis/symbols/circuit_map.py +592 -0
- mdb/analysis/symbols/components.py +436 -0
- mdb/analysis/symbols/frame.py +451 -0
- mdb/analysis/symbols/hop.py +439 -0
- mdb/analysis/symbols/liveness.py +292 -0
- mdb/analysis/symbols/probe.py +393 -0
- mdb/analysis/symbols/rows.py +400 -0
- mdb/analysis/symbols/sealed.py +149 -0
- mdb/analysis/symbols/subspace.py +380 -0
- mdb/analysis/symbols/symbol_finite.py +417 -0
- mdb/analysis/symbols/symbol_runs.py +683 -0
- mdb/analysis/symbols/table.py +1110 -0
- mdb/cli.py +105 -0
- mdb/core/__init__.py +4 -0
- mdb/core/address.py +1353 -0
- mdb/core/bounded.py +101 -0
- mdb/core/checkpoint_schema.py +202 -0
- mdb/core/checkpoint_store.py +377 -0
- mdb/core/circuit_pages.py +117 -0
- mdb/core/custody.py +629 -0
- mdb/core/errors.py +51 -0
- mdb/core/foreign_names.py +152 -0
- mdb/core/graph_seal.py +426 -0
- mdb/core/index.py +403 -0
- mdb/core/kinds.py +255 -0
- mdb/core/locate.py +161 -0
- mdb/core/migrate.py +280 -0
- mdb/core/neuronpedia.py +116 -0
- mdb/core/plugins.py +78 -0
- mdb/core/pointers.py +621 -0
- mdb/core/project.py +248 -0
- mdb/core/project_read.py +1038 -0
- mdb/core/recipe.py +457 -0
- mdb/core/records.py +1027 -0
- mdb/core/resolve.py +296 -0
- mdb/core/settings.py +718 -0
- mdb/engine/__init__.py +21 -0
- mdb/engine/attention_observer.py +53 -0
- mdb/engine/attention_port.py +903 -0
- mdb/engine/breakpoints.py +1465 -0
- mdb/engine/bundle.py +137 -0
- mdb/engine/checkpoint.py +1265 -0
- mdb/engine/core_file.py +306 -0
- mdb/engine/edits.py +323 -0
- mdb/engine/holds.py +256 -0
- mdb/engine/models.py +172 -0
- mdb/engine/ports.py +1424 -0
- mdb/engine/refs.py +223 -0
- mdb/engine/run.py +2162 -0
- mdb/engine/selfcheck.py +347 -0
- mdb/engine/trace.py +536 -0
- mdb/interop/__init__.py +17 -0
- mdb/interop/circuit_tracer_graph.py +253 -0
- mdb/interop/circuit_tracer_names.py +44 -0
- mdb/interop/clone.py +22 -0
- mdb/interop/names.py +295 -0
- mdb/interop/nn.py +431 -0
- mdb/interop/pyvene_compat.py +40 -0
- mdb/interop/pyvene_names.py +82 -0
- mdb/interop/tl.py +149 -0
- mdb/interop/verify.py +85 -0
- mdb/machines/__init__.py +53 -0
- mdb/machines/x86/__init__.py +13 -0
- mdb/machines/x86/address.py +171 -0
- mdb/machines/x86/binary.py +285 -0
- mdb/machines/x86/grid.py +188 -0
- mdb/machines/x86/index.py +184 -0
- mdb/machines/x86/interchange.py +156 -0
- mdb/machines/x86/lanes.py +281 -0
- mdb/machines/x86/method.py +252 -0
- mdb/machines/x86/method_v2.py +105 -0
- mdb/machines/x86/mlp.py +430 -0
- mdb/machines/x86/records.py +138 -0
- mdb/machines/x86/session.py +631 -0
- mdb/machines/x86/trace.py +351 -0
- mdb/ops/__init__.py +31 -0
- mdb/ops/builtin.py +1977 -0
- mdb/ops/context.py +60 -0
- mdb/ops/debugger.py +926 -0
- mdb/ops/errors.py +8 -0
- mdb/ops/features.py +513 -0
- mdb/ops/graph.py +58 -0
- mdb/ops/inspect.py +906 -0
- mdb/ops/lines.py +496 -0
- mdb/ops/named.py +672 -0
- mdb/ops/predict.py +450 -0
- mdb/ops/registry.py +332 -0
- mdb/ops/sets.py +988 -0
- mdb/ops/sweep.py +574 -0
- mdb/repl/__init__.py +5 -0
- mdb/repl/__main__.py +244 -0
- mdb/repl/config.py +213 -0
- mdb/repl/remote.py +324 -0
- mdb/repl/render.py +1699 -0
- mdb/repl/shell.py +409 -0
- mdb/serve/__init__.py +17 -0
- mdb/serve/__main__.py +180 -0
- mdb/serve/_legacy.py +97 -0
- mdb/serve/app.py +526 -0
- mdb/serve/blobs.py +280 -0
- mdb/serve/caps.py +148 -0
- mdb/serve/export.py +9 -0
- mdb/serve/guard.py +216 -0
- mdb/serve/live.py +412 -0
- mdb/serve/live_reduce.py +90 -0
- mdb/serve/recorded.py +515 -0
- mdb/serve/reduce.py +449 -0
- mdb/serve/schema.py +969 -0
- mdb/serve/states.py +125 -0
- mdb/serve/static/assets/index-BJpByNCO.js +58 -0
- mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
- mdb/serve/static/index.html +14 -0
- mdb/serve/static/manifest.json +5 -0
- mdb/serve/stored.py +34 -0
- mdb/serve/typegen.py +131 -0
- mdb/serve/views/__init__.py +1 -0
- mdb/serve/views/common.py +201 -0
- mdb/serve/views/frame.py +235 -0
- mdb/serve/views/graph.py +224 -0
- mdb/serve/views/live.py +402 -0
- mdb/serve/views/records.py +557 -0
- mdb/serve/views/sessions.py +151 -0
- mdb/serve/views/symbols.py +185 -0
- mdb/serve/views/timeline.py +121 -0
- model_debugger-0.4.0.dist-info/METADATA +1516 -0
- model_debugger-0.4.0.dist-info/RECORD +177 -0
- model_debugger-0.4.0.dist-info/WHEEL +4 -0
- model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
- model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
- model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
"""Records drawer: sealed records, findings, slices and symbol lifecycles of one session."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
from collections import Counter
|
|
8
|
+
|
|
9
|
+
from ...core.address import format_address, from_json
|
|
10
|
+
from ...core.circuit_pages import PAGE_SCHEMA, PageError, locate
|
|
11
|
+
from ...core.records import SCHEMAS as RECORD_SCHEMAS
|
|
12
|
+
from .. import blobs
|
|
13
|
+
from ..caps import NONFINITE, bound_json, canonical, nonfinite
|
|
14
|
+
from ..schema import (
|
|
15
|
+
STRUCTURAL_KEYS,
|
|
16
|
+
ArmRow,
|
|
17
|
+
Link,
|
|
18
|
+
NamedNum,
|
|
19
|
+
Num,
|
|
20
|
+
Omitted,
|
|
21
|
+
PointerRef,
|
|
22
|
+
RecordDetail,
|
|
23
|
+
RecordPage,
|
|
24
|
+
RecordSummary,
|
|
25
|
+
StoredBody,
|
|
26
|
+
num,
|
|
27
|
+
)
|
|
28
|
+
from ..schema import unresolved as unresolved_num
|
|
29
|
+
from ..stored import as_dict, as_int, as_list, as_str, is_number
|
|
30
|
+
from .common import (
|
|
31
|
+
ViewError,
|
|
32
|
+
blob_ref,
|
|
33
|
+
cell_address,
|
|
34
|
+
cut_refs,
|
|
35
|
+
descriptor_ref,
|
|
36
|
+
occurrence_row,
|
|
37
|
+
record_id,
|
|
38
|
+
short,
|
|
39
|
+
spec_digest,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
PAGE = 25
|
|
43
|
+
AUTH = {"measured", "derived-exact", "derived-local", "bound", "supplied"}
|
|
44
|
+
LINK_KEYS = ("focus_id", "plan_id", "slice_id", "investigation_id", "analysis_id")
|
|
45
|
+
ARM_LABEL = {0: "sham (no edit)", 1: "A", 2: "B", 3: "A+B"}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _is_auth(value) -> bool:
|
|
49
|
+
"""A stored ``authority`` may be any JSON value (some records hold a dict there)."""
|
|
50
|
+
return isinstance(value, str) and value in AUTH
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _v2_number(value):
|
|
54
|
+
"""The v2 form ``{value, authority[, unit, proof]}`` as a ``Num``, or None. This is the only
|
|
55
|
+
form through which a stored body can carry a class."""
|
|
56
|
+
if _is_auth(value.get("authority")) and is_number(value.get("value")):
|
|
57
|
+
return num(value["value"], value["authority"], unit=as_str(value.get("unit")) or None,
|
|
58
|
+
proof=as_str(value.get("proof")) or None)
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _claims(value, path="", out=None, limit=4):
|
|
63
|
+
"""``num``-shaped claims in a v2 body, in a stable order."""
|
|
64
|
+
out = [] if out is None else out
|
|
65
|
+
if len(out) >= limit:
|
|
66
|
+
return out
|
|
67
|
+
if isinstance(value, dict):
|
|
68
|
+
claim = _v2_number(value)
|
|
69
|
+
if claim is not None:
|
|
70
|
+
out.append(NamedNum(name=path or "value", n=claim))
|
|
71
|
+
return out
|
|
72
|
+
for key in sorted(value):
|
|
73
|
+
_claims(value[key], f"{path}.{key}" if path else key, out, limit)
|
|
74
|
+
elif isinstance(value, list):
|
|
75
|
+
for i, item in enumerate(value):
|
|
76
|
+
_claims(item, f"{path}[{i}]", out, limit)
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
SUPPLIED_NOTE = "as recorded; this record carries no per-number authority"
|
|
81
|
+
CIRCUIT = "mdb-circuit-investigation-v1"
|
|
82
|
+
# (schema id, record kind, field path) -> (evidence class, where the field's meaning is defined).
|
|
83
|
+
# Only fields whose meaning the schema's writer defines are listed; "*" stands for one dynamic key
|
|
84
|
+
# (an arm mask). Every other bare float in a stored body is "supplied": nothing is guessed from a
|
|
85
|
+
# field's name. Writer: packages/mdb/src/mdb/circuit_investigation.py.
|
|
86
|
+
FIELD_CLASS = {
|
|
87
|
+
# measure() output of one native arm run (circuit_investigation.py:639-652)
|
|
88
|
+
(CIRCUIT, "comparison-arm", "measurement.value"): ("measured", "circuit_investigation.py:652"),
|
|
89
|
+
# gradient . (actual - source) delta, local autograd (circuit_investigation.py:696)
|
|
90
|
+
(CIRCUIT, "comparison-arm", "local_linear_prediction"): (
|
|
91
|
+
"derived-local", "circuit_investigation.py:696"),
|
|
92
|
+
# native effect minus the local prediction, a difference with a local term
|
|
93
|
+
# (circuit_investigation.py:697-701)
|
|
94
|
+
(CIRCUIT, "comparison-arm", "native_minus_local_prediction"): (
|
|
95
|
+
"derived-local", "circuit_investigation.py:697"),
|
|
96
|
+
# arm value minus sham value, both measured (circuit_investigation.py:739)
|
|
97
|
+
(CIRCUIT, "comparison", "effects.*"): ("derived-exact", "circuit_investigation.py:739"),
|
|
98
|
+
# measured[3] - measured[1] - measured[2] + measured[0] (circuit_investigation.py:728)
|
|
99
|
+
(CIRCUIT, "comparison", "interaction"): ("derived-exact", "circuit_investigation.py:728"),
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _field_class(schema, kind, path):
|
|
104
|
+
hit = FIELD_CLASS.get((schema, kind, path))
|
|
105
|
+
if hit is None and "." in path:
|
|
106
|
+
hit = FIELD_CLASS.get((schema, kind, path.rsplit(".", 1)[0] + ".*"))
|
|
107
|
+
return hit[0] if hit else None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _supplied(value, recorded, path, note=SUPPLIED_NOTE):
|
|
111
|
+
return num(value, "supplied", proof=f"stored in the record body at {path}",
|
|
112
|
+
note=note, recorded_authority=recorded or None).model_dump(mode="json")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
LABEL_ITEMS = 64
|
|
116
|
+
NOT_A_NUMBER = "stored value is not a number"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _forged(value, path):
|
|
120
|
+
"""A stored ``{v, ev}`` look-alike of the server's own wire shape: never passed through. Its
|
|
121
|
+
``v`` (when a finite number) is ``supplied`` and says which class the body claimed."""
|
|
122
|
+
claimed = value.get("ev")
|
|
123
|
+
text = claimed if isinstance(claimed, str) else str(claimed)
|
|
124
|
+
return _supplied(value["v"], claimed[:200] if isinstance(claimed, str) else None, path,
|
|
125
|
+
note=f"stored body claims class {text[:40]}")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def label_floats(value, *, schema, kind, recorded, path="", key=None, omitted=None):
|
|
129
|
+
"""Every number of a stored body as a labelled number, never guessed:
|
|
130
|
+
|
|
131
|
+
1. a v2 ``{value, authority}`` (authority one of the five classes, value a finite number)
|
|
132
|
+
keeps its class; a stored ``{v, ev}`` look-alike does not (it is ``supplied`` and says
|
|
133
|
+
what it claimed);
|
|
134
|
+
2. a field in ``FIELD_CLASS`` gets the class the table gives it;
|
|
135
|
+
3. any other number, int or float, is ``supplied`` with ``SUPPLIED_NOTE`` and the
|
|
136
|
+
record-level authority string (``recorded_authority``), never measured, unless its key
|
|
137
|
+
is in ``STRUCTURAL_KEYS`` and it is an int (an id, index or count);
|
|
138
|
+
4. a NaN/inf is an unresolved number saying so; a bool or a string is not a number.
|
|
139
|
+
A list longer than ``LABEL_ITEMS`` under a non-structural key is labelled up to that cap and
|
|
140
|
+
the remainder is recorded in ``omitted`` (when given)."""
|
|
141
|
+
if value is None or isinstance(value, (bool, str)):
|
|
142
|
+
return value
|
|
143
|
+
if isinstance(value, (int, float)):
|
|
144
|
+
if not is_number(value):
|
|
145
|
+
return nonfinite() if isinstance(value, float) else unresolved_num(
|
|
146
|
+
"stored number is out of range").model_dump(mode="json")
|
|
147
|
+
if key in STRUCTURAL_KEYS and isinstance(value, int):
|
|
148
|
+
return value
|
|
149
|
+
cls = _field_class(schema, kind, path)
|
|
150
|
+
if cls:
|
|
151
|
+
return num(value, cls, proof=f"stored in the record body at {path}"
|
|
152
|
+
).model_dump(mode="json")
|
|
153
|
+
return _supplied(value, recorded, path or "value")
|
|
154
|
+
if isinstance(value, dict):
|
|
155
|
+
if "ev" in value and "v" in value and is_number(value["v"]):
|
|
156
|
+
return _forged(value, path or "value")
|
|
157
|
+
claim = _v2_number(value)
|
|
158
|
+
if claim is not None:
|
|
159
|
+
return claim.model_dump(mode="json")
|
|
160
|
+
return {k: label_floats(v, schema=schema, kind=kind, recorded=recorded,
|
|
161
|
+
path=f"{path}.{k}" if path else str(k), key=k, omitted=omitted)
|
|
162
|
+
for k, v in value.items()}
|
|
163
|
+
if isinstance(value, list):
|
|
164
|
+
items = value
|
|
165
|
+
if key not in STRUCTURAL_KEYS and omitted is not None and len(items) > LABEL_ITEMS:
|
|
166
|
+
omitted.append(Omitted(field=path or "body", count=len(items) - LABEL_ITEMS,
|
|
167
|
+
reason="list items beyond the first; not labelled"))
|
|
168
|
+
items = items[:LABEL_ITEMS]
|
|
169
|
+
return [label_floats(v, schema=schema, kind=kind, recorded=recorded, path=path, key=key,
|
|
170
|
+
omitted=omitted) for v in items]
|
|
171
|
+
return value
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _measured(arm):
|
|
175
|
+
arm = as_dict(arm)
|
|
176
|
+
m = as_dict(arm.get("measurement"))
|
|
177
|
+
status = arm.get("status")
|
|
178
|
+
if status != "measured":
|
|
179
|
+
return unresolved_num(as_str(arm.get("reason")) or f"arm status {str(status)[:40]}")
|
|
180
|
+
value = m.get("value")
|
|
181
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
182
|
+
return unresolved_num(NONFINITE)
|
|
183
|
+
if not is_number(value):
|
|
184
|
+
return unresolved_num(NOT_A_NUMBER)
|
|
185
|
+
cls = _field_class(CIRCUIT, "comparison-arm", "measurement.value") or "measured"
|
|
186
|
+
return num(value, cls, unit=as_str(m.get("units")) or None)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _interaction(raw):
|
|
190
|
+
"""The comparison's ``interaction`` as a labelled number (derived-exact by FIELD_CLASS), or
|
|
191
|
+
None when absent; unresolved when stored but not a finite number."""
|
|
192
|
+
if "interaction" not in raw:
|
|
193
|
+
return None
|
|
194
|
+
value = raw["interaction"]
|
|
195
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
196
|
+
return unresolved_num(NONFINITE)
|
|
197
|
+
if not is_number(value):
|
|
198
|
+
return unresolved_num(NOT_A_NUMBER)
|
|
199
|
+
return num(value, _field_class(CIRCUIT, "comparison", "interaction"), unit="A+B-A-B+sham")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _placeholder(rid, kind, reason, order, state="refused") -> RecordSummary:
|
|
203
|
+
reason = as_str(reason)[:300]
|
|
204
|
+
marker = (unresolved_num(reason) if state != "refused" else
|
|
205
|
+
Num(v=None, ev="refused", reason=reason))
|
|
206
|
+
return RecordSummary(id=as_str(rid) or f"{kind}-{order}", schema="?", kind=as_str(kind) or "?",
|
|
207
|
+
title=reason[:96], status=state, authority="", order=order,
|
|
208
|
+
nums=[NamedNum(name="record", n=marker)])
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _ident(kind, raw):
|
|
212
|
+
"""The id a row answers to; never raises."""
|
|
213
|
+
raw = as_dict(raw)
|
|
214
|
+
key = {"record": None, "finding": "annotation_id", "slice": "slice_id",
|
|
215
|
+
"lifecycle": "lifecycle_id"}[kind]
|
|
216
|
+
return as_str(record_id(raw) if key is None else raw.get(key))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _summary(entry, order) -> RecordSummary:
|
|
220
|
+
"""The row for one entry; a body that cannot be projected is a refused placeholder row."""
|
|
221
|
+
try:
|
|
222
|
+
return _project_summary(entry, order)
|
|
223
|
+
except Exception as error: # noqa: BLE001 - one malformed stored row must not fail the list
|
|
224
|
+
kind, raw = entry
|
|
225
|
+
return _placeholder(_ident(kind, raw), "record" if kind == "record" else kind,
|
|
226
|
+
f"refused: record body could not be read ({type(error).__name__})",
|
|
227
|
+
order)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _project_summary(entry, order) -> RecordSummary:
|
|
231
|
+
kind, raw = entry
|
|
232
|
+
raw = as_dict(raw)
|
|
233
|
+
if kind == "record" and raw.get("unreadable"):
|
|
234
|
+
return _placeholder(record_id(raw), as_str(raw.get("kind")) or "?",
|
|
235
|
+
as_str(raw.get("unreadable")), order,
|
|
236
|
+
"refused" if raw.get("unreadable_state") == "refused"
|
|
237
|
+
else "unresolved").model_copy(update={
|
|
238
|
+
"schema_": as_str(raw.get("schema")) or "?"})
|
|
239
|
+
if kind == "record":
|
|
240
|
+
rid = record_id(raw)
|
|
241
|
+
nums = []
|
|
242
|
+
if raw.get("schema") in RECORD_SCHEMAS:
|
|
243
|
+
nums = _claims(raw.get("body"))
|
|
244
|
+
title = as_str(raw.get("kind")) + " " + as_str(as_dict(raw.get("body")).get(
|
|
245
|
+
"consumer"))
|
|
246
|
+
status, authority = "sealed", as_str(raw.get("authority"))
|
|
247
|
+
else:
|
|
248
|
+
title = " ".join(x for x in (as_str(raw.get("kind")), as_str(raw.get("component"))
|
|
249
|
+
or as_str(raw.get("view")) or as_str(raw.get("name")))
|
|
250
|
+
if x)
|
|
251
|
+
status = as_str(raw.get("terminal_status")) or as_str(raw.get("status")) or "recorded"
|
|
252
|
+
authority = as_str(raw.get("authority"))
|
|
253
|
+
if raw.get("kind") == "comparison-arm":
|
|
254
|
+
nums = [NamedNum(name="value", n=_measured(raw))]
|
|
255
|
+
if raw.get("kind") == "comparison":
|
|
256
|
+
interaction = _interaction(raw)
|
|
257
|
+
if interaction is not None:
|
|
258
|
+
nums = [NamedNum(name="interaction", n=interaction)]
|
|
259
|
+
refs = cut_refs(raw)
|
|
260
|
+
return RecordSummary(id=rid, schema=as_str(raw.get("schema")) or "?",
|
|
261
|
+
kind=as_str(raw.get("kind")) or "?",
|
|
262
|
+
title=title.strip()[:96], status=status, authority=authority,
|
|
263
|
+
cut=refs[0] if refs else None,
|
|
264
|
+
focus=as_str(raw.get("focus_id")) or None, order=order, nums=nums)
|
|
265
|
+
if kind == "finding":
|
|
266
|
+
details = as_dict(raw.get("details"))
|
|
267
|
+
return RecordSummary(id=_ident(kind, raw), schema=as_str(details.get("schema"))
|
|
268
|
+
or "finding", kind="finding",
|
|
269
|
+
title=as_str(raw.get("label"))[:96],
|
|
270
|
+
status=as_str(details.get("terminal_status")) or "recorded",
|
|
271
|
+
authority=as_str(as_dict(raw.get("provenance")).get("authority")),
|
|
272
|
+
cut=as_str(raw.get("cut_id")) or None,
|
|
273
|
+
focus=as_str(details.get("investigation_id")) or None, order=order)
|
|
274
|
+
if kind == "slice":
|
|
275
|
+
return RecordSummary(id=_ident(kind, raw), schema=as_str(raw.get("schema")) or "?",
|
|
276
|
+
kind="slice", title=as_str(raw.get("component")),
|
|
277
|
+
status="complete" if raw.get("complete") is True
|
|
278
|
+
else f"{len(as_list(raw.get('gaps')))} gaps",
|
|
279
|
+
authority=as_str(raw.get("authority")),
|
|
280
|
+
cut=as_str(raw.get("cut_id")) or None, order=order)
|
|
281
|
+
body = as_dict(raw.get("lifecycle"))
|
|
282
|
+
return RecordSummary(id=_ident(kind, raw), schema=as_str(body.get("schema")) or "?",
|
|
283
|
+
kind="symbol-lifecycle", title=as_str(body.get("symbol")),
|
|
284
|
+
status=as_str(as_dict(body.get("statuses")).get("terminal")) or "?",
|
|
285
|
+
authority=as_str(as_dict(raw.get("joins")).get("authority")),
|
|
286
|
+
order=order)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _with_addr(model, summary):
|
|
290
|
+
"""Attach the address of the summary's cut cell, so a click can move the cursor there."""
|
|
291
|
+
cell = model.cell_of_cut.get(summary.cut) if summary.cut else None
|
|
292
|
+
if cell:
|
|
293
|
+
summary.addr = cell_address(model, *cell)
|
|
294
|
+
return summary
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _entries(model):
|
|
298
|
+
out = [("record", r) for r in model.records()]
|
|
299
|
+
out += [("finding", f) for f in model.findings()]
|
|
300
|
+
out += [("slice", s) for s in model.slices()]
|
|
301
|
+
out += [("lifecycle", c) for c in model.lifecycles()]
|
|
302
|
+
out += [("record", r) for r in model.unreadable()]
|
|
303
|
+
return out
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def record_page(model, *, kind=None, page=0) -> RecordPage:
|
|
307
|
+
rows = [_with_addr(model, _summary(e, i)) for i, e in enumerate(_entries(model))]
|
|
308
|
+
kinds = Counter(r.kind for r in rows)
|
|
309
|
+
if kind:
|
|
310
|
+
rows = [r for r in rows if r.kind == kind]
|
|
311
|
+
pages = max(1, -(-len(rows) // PAGE))
|
|
312
|
+
if page < 0 or page >= pages:
|
|
313
|
+
raise ViewError("bad_page", f"page {page} is outside 0..{pages - 1}")
|
|
314
|
+
return RecordPage(rows=rows[page * PAGE:(page + 1) * PAGE], page=page, pages=pages,
|
|
315
|
+
total=len(rows), kinds=dict(sorted(kinds.items())))
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _mask(arm):
|
|
319
|
+
mask = as_int(arm.get("mask"))
|
|
320
|
+
return mask if mask is not None else -1
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _arms(model, comparison):
|
|
324
|
+
by_id = {record_id(r): r for r in model.records() if isinstance(r, dict)}
|
|
325
|
+
wanted = [a for a in as_list(comparison.get("arms")) if isinstance(a, str)]
|
|
326
|
+
arms = sorted((by_id[a] for a in wanted if a in by_id), key=_mask)
|
|
327
|
+
sham = next((a for a in arms if as_int(a.get("mask")) == 0), None)
|
|
328
|
+
base = _measured(sham) if sham else None
|
|
329
|
+
linear = as_dict(comparison.get("linearization")).get("status") == "native-primal-matched"
|
|
330
|
+
rows = []
|
|
331
|
+
for arm in arms:
|
|
332
|
+
value = _measured(arm)
|
|
333
|
+
if base is None or base.v is None or value.v is None:
|
|
334
|
+
effect = unresolved_num("no measured sham arm" if base is None or base.v is None
|
|
335
|
+
else "arm not measured")
|
|
336
|
+
else:
|
|
337
|
+
effect = num(value.v - base.v, "derived-exact", unit=value.unit,
|
|
338
|
+
proof="difference of measured arms")
|
|
339
|
+
prediction = residual = None
|
|
340
|
+
if linear and is_number(arm.get("local_linear_prediction")):
|
|
341
|
+
prediction = num(arm["local_linear_prediction"], "derived-local", unit=value.unit,
|
|
342
|
+
proof="local-autograd")
|
|
343
|
+
if is_number(arm.get("native_minus_local_prediction")):
|
|
344
|
+
residual = num(arm["native_minus_local_prediction"], "derived-local",
|
|
345
|
+
unit=value.unit, proof="native - local")
|
|
346
|
+
decision = as_dict(arm.get("measurement")).get("decision")
|
|
347
|
+
mask = _mask(arm)
|
|
348
|
+
rows.append(ArmRow(mask=mask, label=ARM_LABEL.get(mask, str(arm.get("mask"))[:24]),
|
|
349
|
+
status=as_str(arm.get("status")) or "?", value=value, effect=effect,
|
|
350
|
+
prediction=prediction, residual=residual,
|
|
351
|
+
decision=None if decision is None else str(decision)[:200],
|
|
352
|
+
record=as_str(record_id(arm)),
|
|
353
|
+
cut=as_str(arm.get("result_cut")) or None))
|
|
354
|
+
return rows
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _bad_pointer(why):
|
|
358
|
+
return PointerRef(digest=spec_digest({"kind": "unreadable-pointer", "why": why}),
|
|
359
|
+
status="frontier", reason=why)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _pointers(model, raw):
|
|
363
|
+
out = []
|
|
364
|
+
for pointer in as_list(raw.get("pointers")):
|
|
365
|
+
pointer = as_dict(pointer)
|
|
366
|
+
if pointer.get("kind") != "occurrence":
|
|
367
|
+
continue
|
|
368
|
+
try:
|
|
369
|
+
address = pointer["address"]
|
|
370
|
+
row = occurrence_row(model, address)
|
|
371
|
+
text = format_address(from_json(address, check_ports=False))
|
|
372
|
+
except Exception: # noqa: BLE001 - a stored pointer with no readable address
|
|
373
|
+
out.append(_bad_pointer("stored occurrence pointer has no readable address"))
|
|
374
|
+
continue
|
|
375
|
+
if row and row.get("blob_id"):
|
|
376
|
+
out.append(blob_ref(model, row["blob_id"], addr=text, via=["occurrence index"]))
|
|
377
|
+
else:
|
|
378
|
+
out.append(descriptor_ref(as_dict(pointer.get("value")), addr=text,
|
|
379
|
+
why="occurrence not materialised"))
|
|
380
|
+
found = []
|
|
381
|
+
|
|
382
|
+
def scan(value, depth=0):
|
|
383
|
+
if depth > 6 or len(found) >= 8:
|
|
384
|
+
return
|
|
385
|
+
if isinstance(value, dict):
|
|
386
|
+
if value.get("kind") == "tensor" and isinstance(value.get("sha256"), str):
|
|
387
|
+
found.append(value)
|
|
388
|
+
return
|
|
389
|
+
for v in value.values():
|
|
390
|
+
scan(v, depth + 1)
|
|
391
|
+
elif isinstance(value, list):
|
|
392
|
+
for v in value[:16]:
|
|
393
|
+
scan(v, depth + 1)
|
|
394
|
+
|
|
395
|
+
scan({k: v for k, v in raw.items() if k not in ("pointers",)})
|
|
396
|
+
out += [descriptor_ref(d, why="sealed descriptor") for d in found]
|
|
397
|
+
return out[:12]
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _refused_detail(summary, reason):
|
|
401
|
+
summary = summary.model_copy(update={"status": "refused", "nums": [NamedNum(
|
|
402
|
+
name="record", n=Num(v=None, ev="refused", reason=reason))]})
|
|
403
|
+
return RecordDetail(summary=summary, body={}, arms=None, pointers=[], links=[])
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _detail(model, entry, order, identifier):
|
|
407
|
+
kind, raw = entry
|
|
408
|
+
summary = _with_addr(model, _summary(entry, order))
|
|
409
|
+
raw = as_dict(raw)
|
|
410
|
+
if kind == "slice":
|
|
411
|
+
graph = as_dict(raw.get("graph"))
|
|
412
|
+
raw = {k: v for k, v in raw.items() if k != "graph"} | {
|
|
413
|
+
"graph": {"snapshot_id": graph.get("snapshot_id"),
|
|
414
|
+
"nodes": len(as_list(graph.get("nodes"))),
|
|
415
|
+
"edges": len(as_list(graph.get("edges")))}}
|
|
416
|
+
trimmed = {k: v for k, v in raw.items() if k not in ("model_identity", "execution")}
|
|
417
|
+
links = [Link(rel=k, id=raw[k]) for k in LINK_KEYS if isinstance(raw.get(k), str)]
|
|
418
|
+
links += [Link(rel="arm", id=a) for a in as_list(raw.get("arms")) if isinstance(a, str)]
|
|
419
|
+
arms = (_arms(model, raw) if raw.get("kind") == "comparison" and not raw.get("unreadable")
|
|
420
|
+
else None)
|
|
421
|
+
pointers = _pointers(model, raw)
|
|
422
|
+
for items in (16, 8, 4, 2):
|
|
423
|
+
omitted = []
|
|
424
|
+
body = bound_json(trimmed, field="body", omitted=omitted, max_items=items,
|
|
425
|
+
max_text=512 if items > 4 else 160)
|
|
426
|
+
body = label_floats(body, schema=as_str(raw.get("schema")),
|
|
427
|
+
kind=as_str(raw.get("kind")), recorded=as_str(raw.get("authority"))
|
|
428
|
+
or None, omitted=omitted)
|
|
429
|
+
detail = RecordDetail(summary=summary, body=body, arms=arms, pointers=pointers,
|
|
430
|
+
links=links[:32])
|
|
431
|
+
if len(canonical(detail.model_dump(mode="json", by_alias=True))) < 56 * 1024:
|
|
432
|
+
return detail, omitted
|
|
433
|
+
return detail, omitted
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
DRAWN_KINDS = ("circuit", "symbol-table")
|
|
437
|
+
V2_KEYS = ("value", "authority", "proof", "unit", "note", "reason")
|
|
438
|
+
STORED_BYTES = 60 * 1024
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _lean(value, *, schema, kind, recorded, path="", key=None):
|
|
442
|
+
"""A stored body with every number labelled as ``label_floats`` labels it, but keeping a v2
|
|
443
|
+
``{value, authority, ...}`` in its own (op) form, so the body is the op's JSON the Live view
|
|
444
|
+
draws. A v2 number's other keys (``bound``, ``within``) are kept and labelled too."""
|
|
445
|
+
if isinstance(value, dict):
|
|
446
|
+
if "ev" in value and "v" in value and is_number(value["v"]):
|
|
447
|
+
return _forged(value, path or "value")
|
|
448
|
+
if _v2_number(value) is not None:
|
|
449
|
+
out = {k: value[k] for k in V2_KEYS if k in value and (
|
|
450
|
+
k == "value" or isinstance(value[k], str))}
|
|
451
|
+
for k, v in value.items():
|
|
452
|
+
if k not in V2_KEYS:
|
|
453
|
+
out[k] = _lean(v, schema=schema, kind=kind, recorded=recorded,
|
|
454
|
+
path=f"{path}.{k}" if path else str(k), key=k)
|
|
455
|
+
return out
|
|
456
|
+
return {k: _lean(v, schema=schema, kind=kind, recorded=recorded,
|
|
457
|
+
path=f"{path}.{k}" if path else str(k), key=k) for k, v in value.items()}
|
|
458
|
+
if isinstance(value, list):
|
|
459
|
+
return [_lean(v, schema=schema, kind=kind, recorded=recorded, path=path, key=key)
|
|
460
|
+
for v in value]
|
|
461
|
+
return label_floats(value, schema=schema, kind=kind, recorded=recorded, path=path, key=key)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
class _PageRefused(PageError):
|
|
465
|
+
"""A stored child page that is missing or fails its checks (not an unknown node id)."""
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def _page_loader(model):
|
|
469
|
+
"""``circuit_pages.find``'s ``load`` for a recorded project: the page blob read from the
|
|
470
|
+
project store with numpy only, its payload and JSON digests checked against the pointer."""
|
|
471
|
+
def load(pointer):
|
|
472
|
+
if pointer.get("state") != "stored":
|
|
473
|
+
raise _PageRefused("this page was held in memory by a run without a project "
|
|
474
|
+
f"({as_str(pointer.get('reason')) or 'absent'}); the recorded "
|
|
475
|
+
"project does not hold it")
|
|
476
|
+
try:
|
|
477
|
+
array, info = blobs.tensor_blob(model.store_root, as_str(pointer.get("ref")))
|
|
478
|
+
raw = array.tobytes()
|
|
479
|
+
if (info["sha256"] != pointer.get("tensor_sha256") or info["dtype"] != "uint8"
|
|
480
|
+
or len(raw) != as_int(as_dict(pointer.get("bytes")).get("value"))):
|
|
481
|
+
raise ValueError("the blob differs from its pointer")
|
|
482
|
+
if hashlib.sha256(raw).hexdigest() != pointer.get("sha256"):
|
|
483
|
+
raise ValueError("the page differs from the pointer's sha256")
|
|
484
|
+
page = json.loads(raw)
|
|
485
|
+
if not isinstance(page, dict) or page.get("schema") != PAGE_SCHEMA:
|
|
486
|
+
raise ValueError("not a circuit page")
|
|
487
|
+
except (blobs.BlobError, OSError, ValueError, AttributeError, TypeError) as error:
|
|
488
|
+
raise _PageRefused(f"page {short(as_str(pointer.get('sha256')))} refused: "
|
|
489
|
+
f"{error}") from None
|
|
490
|
+
return page
|
|
491
|
+
return load
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def stored_body(model, identifier, node=None) -> StoredBody:
|
|
495
|
+
"""The whole sealed body of one ``circuit`` or ``symbol-table`` record (``StoredBody``).
|
|
496
|
+
Another kind, an unreadable row or a body over ``STORED_BYTES`` is refused, never cut: a
|
|
497
|
+
drawn circuit or table with nodes silently missing would not close. A circuit record is
|
|
498
|
+
paged (its root page is the body; a group that did not fit is a ``paged`` pointer to a child
|
|
499
|
+
page): ``node`` (``n12``) returns that node's page instead, ``body`` being the page
|
|
500
|
+
(``{schema, node, ...}``), read from the project store and checked against its sha256."""
|
|
501
|
+
for raw in model.records():
|
|
502
|
+
if not isinstance(raw, dict) or record_id(raw) != identifier:
|
|
503
|
+
continue
|
|
504
|
+
kind = as_str(raw.get("kind"))
|
|
505
|
+
if raw.get("unreadable"):
|
|
506
|
+
raise ViewError("unreadable", f"record {short(identifier)}: "
|
|
507
|
+
f"{as_str(raw.get('unreadable'))}", 409)
|
|
508
|
+
if kind not in DRAWN_KINDS or raw.get("schema") not in RECORD_SCHEMAS:
|
|
509
|
+
raise ViewError("not_drawn", f"record {short(identifier)} is a {kind or '?'} record; "
|
|
510
|
+
"only engine circuit and symbol-table records are drawn (the "
|
|
511
|
+
"Records drawer shows the rest)", 409)
|
|
512
|
+
body = as_dict(raw.get("body"))
|
|
513
|
+
shown, page_schema = body, as_str(body.get("schema"))
|
|
514
|
+
if node is not None:
|
|
515
|
+
if kind != "circuit":
|
|
516
|
+
raise ViewError("not_drawn", f"record {short(identifier)} is a {kind} record; "
|
|
517
|
+
"only a circuit has node pages", 409)
|
|
518
|
+
try:
|
|
519
|
+
count = as_dict(body.get("count")).get("value", body.get("count"))
|
|
520
|
+
shown = locate(as_dict(body.get("root")), as_int(count) or 0, node,
|
|
521
|
+
_page_loader(model))
|
|
522
|
+
except _PageRefused as error:
|
|
523
|
+
raise ViewError("page_refused", f"record {short(identifier)}: {error}",
|
|
524
|
+
409) from None
|
|
525
|
+
except PageError as error:
|
|
526
|
+
raise ViewError("no_node", f"record {short(identifier)}: {error}", 404) from None
|
|
527
|
+
page_schema = PAGE_SCHEMA
|
|
528
|
+
lean = _lean(shown, schema=as_str(raw.get("schema")), kind=kind,
|
|
529
|
+
recorded=as_str(raw.get("authority")) or None)
|
|
530
|
+
size = len(canonical(lean))
|
|
531
|
+
if size > STORED_BYTES:
|
|
532
|
+
raise ViewError("over_cap", f"record {short(identifier)}: its body is {size} bytes, "
|
|
533
|
+
f"over the {STORED_BYTES} the page draws at once; the REPL prints "
|
|
534
|
+
"it whole", 409)
|
|
535
|
+
ledger = body.get("ledger_id")
|
|
536
|
+
return StoredBody(id=identifier, kind=kind, record_schema=page_schema,
|
|
537
|
+
authority=as_str(raw.get("authority")),
|
|
538
|
+
consumer=as_str(body.get("consumer")) or None,
|
|
539
|
+
where=as_str(body.get("where")) or None, body=lean,
|
|
540
|
+
ledger_id=(as_int(ledger.get("value") if isinstance(ledger, dict)
|
|
541
|
+
else ledger) if ledger is not None else None),
|
|
542
|
+
node=node)
|
|
543
|
+
raise ViewError("not_found", f"record {short(identifier)} is not in session {model.sid}", 404)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def record_detail(model, identifier) -> tuple[RecordDetail, list]:
|
|
547
|
+
for order, entry in enumerate(_entries(model)):
|
|
548
|
+
kind, raw = entry
|
|
549
|
+
if _ident(kind, raw) != identifier:
|
|
550
|
+
continue
|
|
551
|
+
try:
|
|
552
|
+
return _detail(model, entry, order, identifier)
|
|
553
|
+
except Exception as error: # noqa: BLE001 - refused detail, never a 500
|
|
554
|
+
summary = _placeholder(identifier, "record" if kind == "record" else kind, "", order)
|
|
555
|
+
return _refused_detail(summary, "refused: record body could not be read "
|
|
556
|
+
f"({type(error).__name__})"), []
|
|
557
|
+
raise ViewError("not_found", f"record {short(identifier)} is not in session {model.sid}", 404)
|