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,151 @@
|
|
|
1
|
+
"""Hello, session list and per-session capabilities."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from ... import __version__
|
|
5
|
+
from ...core import address as addresses
|
|
6
|
+
from ..schema import (
|
|
7
|
+
CAP_BYTES,
|
|
8
|
+
SCHEMAS,
|
|
9
|
+
Capabilities,
|
|
10
|
+
Hello,
|
|
11
|
+
LensInfo,
|
|
12
|
+
Num,
|
|
13
|
+
PortInfo,
|
|
14
|
+
SessionSummary,
|
|
15
|
+
ViewAvail,
|
|
16
|
+
num,
|
|
17
|
+
unresolved,
|
|
18
|
+
)
|
|
19
|
+
from ..stored import as_dict, as_str
|
|
20
|
+
from .common import ViewError, short
|
|
21
|
+
|
|
22
|
+
LENSES = {
|
|
23
|
+
"cuts": ("retained cuts", "cuts",
|
|
24
|
+
"cuts retained at this boundary; 0 = the recording passed here and kept none"),
|
|
25
|
+
"receipts": ("native transitions", "transitions",
|
|
26
|
+
"receipt transitions that started at this boundary"),
|
|
27
|
+
"symbols": ("symbol registrations", "registrations",
|
|
28
|
+
"registered symbol locations and reads; no registration is not absence"),
|
|
29
|
+
"records": ("records", "records", "sealed records and findings naming a cut here"),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def ops_available():
|
|
34
|
+
try:
|
|
35
|
+
from ... import ops # noqa: F401
|
|
36
|
+
except ImportError as error:
|
|
37
|
+
return ViewAvail(available=False, reason=f"ops registry unavailable ({error})")
|
|
38
|
+
if not hasattr(ops, "dispatch"):
|
|
39
|
+
return ViewAvail(available=False, reason="mdb.ops has no dispatch()")
|
|
40
|
+
return ViewAvail(available=True)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def session_summary(model) -> SessionSummary:
|
|
44
|
+
identity = model.identity
|
|
45
|
+
name = identity if isinstance(identity, str) else (
|
|
46
|
+
as_str(as_dict(identity).get("name")) or str(identity))
|
|
47
|
+
from .frame import default_address
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
home = default_address(model)
|
|
51
|
+
except ViewError:
|
|
52
|
+
home = None
|
|
53
|
+
return SessionSummary(
|
|
54
|
+
id=model.sid, family=as_str(model.execution.get("family")) or None,
|
|
55
|
+
adapter=as_str(model.execution.get("adapter")) or None, granularity=model.granularity,
|
|
56
|
+
model=short(str(name), 16), cuts=len(model.cuts), receipts=len(model.receipts),
|
|
57
|
+
symbols=len(model.symbols()), records=len(model.records()) + len(model.findings()),
|
|
58
|
+
selected=model.selected, home=home)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def session_row(recorded, sid) -> SessionSummary:
|
|
62
|
+
"""One session's summary; a session that cannot be read is a refused entry, never an error
|
|
63
|
+
for the list."""
|
|
64
|
+
from ..recorded import SessionUnreadable
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
return session_summary(recorded.model(sid))
|
|
68
|
+
except (SessionUnreadable, KeyError) as error:
|
|
69
|
+
reason = error.reason if isinstance(error, SessionUnreadable) else "session not found"
|
|
70
|
+
return SessionSummary(id=sid, family=None, adapter=None, granularity=None, model="",
|
|
71
|
+
cuts=0, receipts=0, symbols=0, records=0, selected="", home=None,
|
|
72
|
+
state="refused", reason=reason)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def lens_infos(model) -> list[LensInfo]:
|
|
76
|
+
has = {"cuts": bool(model.cuts), "receipts": bool(model.receipts),
|
|
77
|
+
"symbols": bool(model.symbols() or model.lifecycles()),
|
|
78
|
+
"records": bool(model.records() or model.findings())}
|
|
79
|
+
return [LensInfo(id=k, label=v[0], unit=v[1], hasData=has[k], note=v[2])
|
|
80
|
+
for k, v in LENSES.items()]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def layer_count(model) -> Num:
|
|
84
|
+
"""The model's decoder layer count with its evidence class: ``measured`` when the cut surface's
|
|
85
|
+
layer clock says it, ``derived-local`` (a lower bound) when it is only the highest recorded
|
|
86
|
+
layer index, ``unresolved`` when nothing recorded names it."""
|
|
87
|
+
if model.layers_status == "known":
|
|
88
|
+
return num(model.n_layers, "measured", unit="layers", proof=model.layer_note)
|
|
89
|
+
if model.layers_status == "inferred":
|
|
90
|
+
return num(model.n_layers, "derived-local", unit="layers (at least)",
|
|
91
|
+
proof=model.layer_note)
|
|
92
|
+
return unresolved(model.layer_note, unit="layers")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def capabilities(model) -> Capabilities:
|
|
96
|
+
ports = []
|
|
97
|
+
for name, slot in sorted(model.slots.items()):
|
|
98
|
+
ports.append(PortInfo(name=name, role=slot.get("role"),
|
|
99
|
+
kind=(slot.get("schema") or {}).get("kind"),
|
|
100
|
+
writable=slot.get("writable"), recorded=True))
|
|
101
|
+
for name in addresses.DEFAULT_PORTS + addresses.DEFAULT_GLOBALS:
|
|
102
|
+
ports.append(PortInfo(name=name, role="port", kind="occurrence", writable=None,
|
|
103
|
+
recorded=False, addr=f"t*.L*.{name}" if name in
|
|
104
|
+
addresses.DEFAULT_PORTS else f"t*.{name}"))
|
|
105
|
+
slices = model.slices()
|
|
106
|
+
views = {
|
|
107
|
+
"timeline": ViewAvail(available=bool(model.cuts)),
|
|
108
|
+
"symbols": ViewAvail(available=bool(model.symbols()),
|
|
109
|
+
reason=None if model.symbols() else "no symbol bindings recorded"),
|
|
110
|
+
"graph": ViewAvail(available=bool(slices) or bool(model.cuts),
|
|
111
|
+
reason=None if slices else "no slices recorded; session graph only"),
|
|
112
|
+
"records": ViewAvail(available=bool(model.records() or model.findings()),
|
|
113
|
+
reason=None if model.records() or model.findings()
|
|
114
|
+
else "no sealed records or findings in this session"),
|
|
115
|
+
"pipeline": ViewAvail(available=False, reason="needs the engine's port program"),
|
|
116
|
+
"compare": ViewAvail(available=False, reason="no compare view yet; use the compare op"),
|
|
117
|
+
}
|
|
118
|
+
return Capabilities(
|
|
119
|
+
session=model.sid, axes=model.axes(), layers=layer_count(model), ports=ports,
|
|
120
|
+
lenses=lens_infos(model),
|
|
121
|
+
views=views,
|
|
122
|
+
reduce={"ops": ["stats", "topk", "slice", "histogram", "tile", "project"],
|
|
123
|
+
"pointers": ["slot", "blob", "occurrence"],
|
|
124
|
+
"limits": {"topk": 64, "slice": 4096, "histogram": 256, "tile": 64}},
|
|
125
|
+
ops=ops_available())
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def hello(recorded, *, read_only, web, live=None) -> Hello:
|
|
129
|
+
"""``live``: the live session id (``mdb serve --tiny|--model``), else None."""
|
|
130
|
+
from ..recorded import SessionUnreadable
|
|
131
|
+
|
|
132
|
+
sessions = recorded.sessions()
|
|
133
|
+
models = []
|
|
134
|
+
for sid in sessions:
|
|
135
|
+
try:
|
|
136
|
+
models.append(recorded.model(sid))
|
|
137
|
+
except (SessionUnreadable, KeyError):
|
|
138
|
+
continue # listed as refused in /sessions; it offers no view here
|
|
139
|
+
caps = {
|
|
140
|
+
"timeline": ViewAvail(available=any(m.cuts for m in models)),
|
|
141
|
+
"symbols": ViewAvail(available=any(m.symbols() for m in models)),
|
|
142
|
+
"graph": ViewAvail(available=any(m.cuts for m in models)),
|
|
143
|
+
"records": ViewAvail(available=any(m.records() or m.findings() for m in models)),
|
|
144
|
+
"reduce": ViewAvail(available=True),
|
|
145
|
+
"ops": ops_available(),
|
|
146
|
+
"live": ViewAvail(available=True) if live else ViewAvail(
|
|
147
|
+
available=False, reason="recorded project; no engine attached"),
|
|
148
|
+
}
|
|
149
|
+
return Hello(version=__version__, schemas=dict(SCHEMAS), cap=CAP_BYTES,
|
|
150
|
+
sessions=len(sessions), readOnly=read_only, capabilities=caps, web=web,
|
|
151
|
+
live=live)
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Symbol table view: bindings joined with lifecycles and the attention reads they record."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from saturn.values import digest
|
|
5
|
+
|
|
6
|
+
from .. import _legacy
|
|
7
|
+
from ..schema import (
|
|
8
|
+
LifePoint,
|
|
9
|
+
Lifetime,
|
|
10
|
+
ReadEdge,
|
|
11
|
+
ReaderView,
|
|
12
|
+
ReadSourceView,
|
|
13
|
+
SymbolDetail,
|
|
14
|
+
SymbolPage,
|
|
15
|
+
SymbolRow,
|
|
16
|
+
UseView,
|
|
17
|
+
num,
|
|
18
|
+
unresolved,
|
|
19
|
+
)
|
|
20
|
+
from ..stored import as_dict, as_str, is_number
|
|
21
|
+
from .common import ViewError, address_cell, location_address, parse
|
|
22
|
+
|
|
23
|
+
PAGE = 25
|
|
24
|
+
LIST = 8
|
|
25
|
+
UNBOUND_REASON = ("not measured in this recording: the unbound share of a value needs the "
|
|
26
|
+
"engine's per-port captures at the cursor")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _reads(model, lifecycle_record):
|
|
30
|
+
"""``SymbolRead`` dicts derived from an attention lifecycle (empty when it has none)."""
|
|
31
|
+
return _legacy.lifecycle_reads(lifecycle_record["lifecycle"])
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _edge(model, read):
|
|
35
|
+
body = read
|
|
36
|
+
reader, source = body["reader"], body["source"]
|
|
37
|
+
results = body["causal"]["results"]
|
|
38
|
+
verdict = results[-1]["verdict"] if results else "untested"
|
|
39
|
+
step = reader.get("receiver_row")
|
|
40
|
+
addr = None
|
|
41
|
+
if isinstance(step, int):
|
|
42
|
+
src = source["rows"][0] if len(source["rows"]) == 1 else None
|
|
43
|
+
addr = f"t{step}.L{reader['block']}.p[h{reader['head']}" + (
|
|
44
|
+
f",src={src}]" if src is not None else "]")
|
|
45
|
+
return ReadEdge(
|
|
46
|
+
id=body["fingerprint"],
|
|
47
|
+
source=ReadSourceView(name=source["name"], rows=source["rows"],
|
|
48
|
+
assignment=source["assignment"]),
|
|
49
|
+
reader=ReaderView(block=reader["block"], head=reader["head"],
|
|
50
|
+
kvGroup=reader.get("kv_group"), step=reader.get("step"),
|
|
51
|
+
receivers=reader.get("receivers")),
|
|
52
|
+
mass=num(body["mass"], "measured", unit="probability"),
|
|
53
|
+
massKind=body["mass_kind"], verdict=verdict, addr=addr)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _point(model, cut, label, point=None):
|
|
57
|
+
cell = model.place(point) if point else model.cell_of_cut.get(cut)
|
|
58
|
+
clock = {"token": cell[0], "layer": cell[1]} if cell else {"token": None, "layer": None}
|
|
59
|
+
return LifePoint(cut=cut, clock=clock, label=label)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _row(model, binding, by_binding) -> SymbolRow:
|
|
63
|
+
fp = binding["fingerprint"]
|
|
64
|
+
related = by_binding.get(fp, [])
|
|
65
|
+
reads, uses, defs, reads_at = [], [], [], []
|
|
66
|
+
for loc in binding["locations"]:
|
|
67
|
+
for cut, desc in model.cuts.items():
|
|
68
|
+
if loc.get("execution_point") == digest(desc["execution_point"]):
|
|
69
|
+
defs.append(_point(model, cut, "bound at " + loc["slot"]))
|
|
70
|
+
break
|
|
71
|
+
for record in related:
|
|
72
|
+
body = record["lifecycle"]
|
|
73
|
+
for d in body["definitions"]:
|
|
74
|
+
defs.append(_point(model, d["source_cut"], "definition " + d["occurrence_id"]))
|
|
75
|
+
for u in body["uses"]:
|
|
76
|
+
meta = u.get("metadata") or {}
|
|
77
|
+
reads_at.append(_point(model, u.get("result_cut"), "use " + u["use_id"],
|
|
78
|
+
meta.get("native_operation_point")))
|
|
79
|
+
joins = {j["use"]: j for j in record["joins"]["uses"]}
|
|
80
|
+
for u in body["uses"]:
|
|
81
|
+
j = joins.get(u["use_id"], {})
|
|
82
|
+
uses.append(UseView(id=u["use_id"], consumer=u["consumer"],
|
|
83
|
+
support=j.get("consumer_support", "unknown"),
|
|
84
|
+
closure=j.get("receipt_closure")))
|
|
85
|
+
reads += _reads(model, record)
|
|
86
|
+
edges = sorted((_edge(model, r) for r in reads), key=lambda e: -(e.mass.v or 0.0))
|
|
87
|
+
locations = [location_address(model, loc) for loc in binding["locations"]]
|
|
88
|
+
statuses = [r["lifecycle"]["statuses"] for r in related]
|
|
89
|
+
confidence = binding.get("confidence")
|
|
90
|
+
return SymbolRow(
|
|
91
|
+
id=fp, symbol=binding["symbol"], context=binding["context"],
|
|
92
|
+
status=binding["status"],
|
|
93
|
+
assignment="supplied" if binding["status"] == "supplied" else (
|
|
94
|
+
edges[0].source.assignment if edges else None),
|
|
95
|
+
claim=binding["claim"],
|
|
96
|
+
confidence=num(confidence, "supplied") if is_number(confidence) else None,
|
|
97
|
+
abstainReason=binding.get("abstain_reason"),
|
|
98
|
+
locations=locations[:LIST], locationsMore=max(0, len(locations) - LIST),
|
|
99
|
+
readers=edges[:LIST], readersMore=max(0, len(edges) - LIST),
|
|
100
|
+
uses=uses[:LIST], usesMore=max(0, len(uses) - LIST),
|
|
101
|
+
verdict=(statuses[-1]["terminal"] if statuses else "no lifecycle recorded"),
|
|
102
|
+
lifetime=Lifetime(defs=_dedupe(defs)[:LIST], reads=_dedupe(reads_at)[:LIST]),
|
|
103
|
+
evidence=list(binding.get("evidence") or [])[:LIST],
|
|
104
|
+
evidenceMore=max(0, len(binding.get("evidence") or []) - LIST),
|
|
105
|
+
fingerprint=fp, lifecycles=[r["lifecycle_id"] for r in related][:LIST])
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def build_rows(model):
|
|
109
|
+
lifecycles = model.lifecycles()
|
|
110
|
+
by_binding = {}
|
|
111
|
+
for record in lifecycles:
|
|
112
|
+
try:
|
|
113
|
+
by_binding.setdefault(record["lifecycle"]["binding_fingerprint"], []).append(record)
|
|
114
|
+
except (KeyError, TypeError) as error:
|
|
115
|
+
model._problem("lifecycle", record.get("lifecycle_id"), error)
|
|
116
|
+
rows = []
|
|
117
|
+
for binding in model.symbols():
|
|
118
|
+
try:
|
|
119
|
+
rows.append(_row(model, binding, by_binding))
|
|
120
|
+
except Exception as error: # noqa: BLE001 - one malformed binding is one refused row
|
|
121
|
+
model._problem("symbol", binding.get("fingerprint"), error)
|
|
122
|
+
return rows, by_binding
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _dedupe(points):
|
|
126
|
+
seen, out = set(), []
|
|
127
|
+
for p in points:
|
|
128
|
+
key = (p.cut, p.clock.get("token"), p.clock.get("layer"))
|
|
129
|
+
if key not in seen:
|
|
130
|
+
seen.add(key)
|
|
131
|
+
out.append(p)
|
|
132
|
+
return out
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def symbol_cells(model):
|
|
136
|
+
"""``{(x, y): [binding fingerprints]}`` for the timeline symbol lens."""
|
|
137
|
+
rows, _ = build_rows(model)
|
|
138
|
+
cells = {}
|
|
139
|
+
for row in rows:
|
|
140
|
+
for point in [*row.lifetime.defs, *row.lifetime.reads]:
|
|
141
|
+
x, y = point.clock.get("token"), point.clock.get("layer")
|
|
142
|
+
if x is not None and y is not None:
|
|
143
|
+
cells.setdefault((x, y), []).append(row.id)
|
|
144
|
+
return cells
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def symbol_page(model, *, at=None, q=None, page=0) -> SymbolPage:
|
|
148
|
+
rows, _ = build_rows(model)
|
|
149
|
+
if at:
|
|
150
|
+
x, _ = address_cell(model, parse(at))
|
|
151
|
+
if x is not None:
|
|
152
|
+
rows = [r for r in rows if any(p.clock.get("token") is not None and
|
|
153
|
+
p.clock["token"] <= x for p in r.lifetime.defs)]
|
|
154
|
+
if q:
|
|
155
|
+
needle = q.lower()
|
|
156
|
+
rows = [r for r in rows if needle in r.symbol.lower() or needle in r.claim.lower()]
|
|
157
|
+
total = len(rows)
|
|
158
|
+
pages = max(1, -(-total // PAGE))
|
|
159
|
+
if page < 0 or page >= pages:
|
|
160
|
+
raise ViewError("bad_page", f"page {page} is outside 0..{pages - 1}")
|
|
161
|
+
return SymbolPage(rows=rows[page * PAGE:(page + 1) * PAGE], page=page, pages=pages,
|
|
162
|
+
total=total, at=at, q=q, unbound=unresolved(UNBOUND_REASON),
|
|
163
|
+
coverage="registered bindings only; no match is not evidence of absence")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def symbol_detail(model, identifier) -> SymbolDetail:
|
|
167
|
+
rows, by_binding = build_rows(model)
|
|
168
|
+
row = next((r for r in rows if r.id == identifier), None)
|
|
169
|
+
if row is None:
|
|
170
|
+
raise ViewError("not_found", f"symbol {identifier} is not bound in {model.sid}", 404)
|
|
171
|
+
binding = next(b for b in model.symbols() if b["fingerprint"] == identifier)
|
|
172
|
+
related = by_binding.get(identifier, [])
|
|
173
|
+
slices = []
|
|
174
|
+
for record in related:
|
|
175
|
+
slices += [d["slice_id"] for d in record["joins"]["definitions"] if d.get("slice_id")]
|
|
176
|
+
for sliced in model.slices():
|
|
177
|
+
if (sliced.get("symbol_binding") or {}).get("fingerprint") == identifier:
|
|
178
|
+
slices.append(sliced["slice_id"])
|
|
179
|
+
statuses = {k: v for k, v in as_dict(as_dict(related[-1]["lifecycle"]).get(
|
|
180
|
+
"statuses")).items() if isinstance(v, str)} if related else {}
|
|
181
|
+
compact = {k: v for k, v in binding.items() if k not in ("locations",)}
|
|
182
|
+
return SymbolDetail(row=row, binding=compact, slices=list(dict.fromkeys(slices))[:LIST],
|
|
183
|
+
statuses=statuses,
|
|
184
|
+
claimBoundary=as_str(as_dict(related[-1]["lifecycle"]).get(
|
|
185
|
+
"claim_boundary")) or None if related else None)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Timeline: one lens over the first two clock axes (token row x depth boundary).
|
|
2
|
+
|
|
3
|
+
Cells the recording never reached are not listed; ``fill`` states their evidence class
|
|
4
|
+
(``unresolved``) and why. A listed cell with ``v = 0`` means the recording passed through that
|
|
5
|
+
boundary and the lens counted nothing there, which is a recorded fact, not a missing value.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections import Counter
|
|
10
|
+
|
|
11
|
+
from ..caps import take
|
|
12
|
+
from ..schema import TimelineBlock, TimelineCell, TokenCell, Window, unresolved
|
|
13
|
+
from .common import ViewError, cut_refs
|
|
14
|
+
from .sessions import LENSES, lens_infos
|
|
15
|
+
from .symbols import symbol_cells
|
|
16
|
+
|
|
17
|
+
MAX_SPAN_X, MAX_SPAN_Y, MAX_CELLS = 512, 256, 1500
|
|
18
|
+
NOT_REACHED = "not reached in the recorded history (no cut or native transition here)"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _branch_scope(model, branch):
|
|
22
|
+
if branch is None:
|
|
23
|
+
return list(model.cut_ids), model.receipts
|
|
24
|
+
cuts = model.branch_cuts(branch)
|
|
25
|
+
if not cuts:
|
|
26
|
+
raise ViewError("unknown_branch", f"no branch {branch!r} in session {model.sid}", 404)
|
|
27
|
+
keep = set(cuts)
|
|
28
|
+
return cuts, [r for r in model.receipts if r.get("result") in keep]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _counts(model, lens, cuts, receipts):
|
|
32
|
+
reached = set()
|
|
33
|
+
for cut in cuts:
|
|
34
|
+
if model.cell_of_cut.get(cut):
|
|
35
|
+
reached.add(model.cell_of_cut[cut])
|
|
36
|
+
transitions = Counter()
|
|
37
|
+
for receipt in receipts:
|
|
38
|
+
for step in receipt.get("transitions") or []:
|
|
39
|
+
for key in ("before", "after"):
|
|
40
|
+
cell = model.place(step.get(key))
|
|
41
|
+
if cell:
|
|
42
|
+
reached.add(cell)
|
|
43
|
+
cell = model.place(step.get("before"))
|
|
44
|
+
if cell:
|
|
45
|
+
transitions[cell] += 1
|
|
46
|
+
cut_count = Counter(model.cell_of_cut[c] for c in cuts if model.cell_of_cut.get(c))
|
|
47
|
+
record_count = Counter()
|
|
48
|
+
for record in [*model.records(), *model.findings()]:
|
|
49
|
+
for cut in cut_refs(record):
|
|
50
|
+
if cut in cuts and model.cell_of_cut.get(cut):
|
|
51
|
+
record_count[model.cell_of_cut[cut]] += 1
|
|
52
|
+
symbols = {cell: len(ids) for cell, ids in symbol_cells(model).items()}
|
|
53
|
+
if lens == "cuts":
|
|
54
|
+
values = {cell: cut_count.get(cell, 0) for cell in reached}
|
|
55
|
+
elif lens == "receipts":
|
|
56
|
+
values = {cell: transitions.get(cell, 0) for cell in reached}
|
|
57
|
+
elif lens == "records":
|
|
58
|
+
values = {cell: record_count.get(cell, 0) for cell in reached}
|
|
59
|
+
else:
|
|
60
|
+
values = dict(symbols)
|
|
61
|
+
return reached, values, cut_count, record_count, symbols
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _glyphs(model, cell, cuts, cut_count, record_count, symbols):
|
|
65
|
+
out = []
|
|
66
|
+
if cut_count.get(cell):
|
|
67
|
+
out.append("cut")
|
|
68
|
+
if model.selected in cuts and model.cell_of_cut.get(model.selected) == cell:
|
|
69
|
+
out.append("selected")
|
|
70
|
+
branches = {model.branch[c] for c in cuts if model.cell_of_cut.get(c) == cell}
|
|
71
|
+
parents = {model.branch.get(model.cuts[c]["parent"]) for c in cuts
|
|
72
|
+
if model.cell_of_cut.get(c) == cell and model.cuts[c]["parent"]}
|
|
73
|
+
if len(branches) > 1 or (branches and parents and branches - parents - {None}):
|
|
74
|
+
out.append("fork")
|
|
75
|
+
if symbols.get(cell):
|
|
76
|
+
out.append("symbol")
|
|
77
|
+
if record_count.get(cell):
|
|
78
|
+
out.append("record")
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def timeline(model, *, lens="cuts", x0=None, x1=None, y0=None, y1=None, branch=None):
|
|
83
|
+
if lens not in LENSES:
|
|
84
|
+
raise ViewError("unknown_lens", f"lens is one of {', '.join(LENSES)}")
|
|
85
|
+
axes = model.axes()
|
|
86
|
+
nx, ny = len(axes[0].ticks), len(axes[1].ticks)
|
|
87
|
+
x0 = 0 if x0 is None else x0
|
|
88
|
+
y0 = 0 if y0 is None else y0
|
|
89
|
+
x1 = min(nx, x0 + MAX_SPAN_X) if x1 is None else x1
|
|
90
|
+
y1 = min(ny, y0 + MAX_SPAN_Y) if y1 is None else y1
|
|
91
|
+
if not (0 <= x0 <= x1 and 0 <= y0 <= y1):
|
|
92
|
+
raise ViewError("bad_window", "window needs 0 <= x0 <= x1 and 0 <= y0 <= y1")
|
|
93
|
+
if x1 - x0 > MAX_SPAN_X or y1 - y0 > MAX_SPAN_Y:
|
|
94
|
+
raise ViewError("bad_window", f"window spans at most {MAX_SPAN_X} x {MAX_SPAN_Y} cells")
|
|
95
|
+
cuts, receipts = _branch_scope(model, branch)
|
|
96
|
+
reached, values, cut_count, record_count, symbols = _counts(model, lens, cuts, receipts)
|
|
97
|
+
unit = LENSES[lens][1]
|
|
98
|
+
if lens == "symbols":
|
|
99
|
+
fill = unresolved("no registered symbol location or read here; absence not established",
|
|
100
|
+
unit=unit)
|
|
101
|
+
else:
|
|
102
|
+
fill = unresolved(NOT_REACHED, unit=unit)
|
|
103
|
+
cells, omitted = [], []
|
|
104
|
+
for (x, y), v in sorted(values.items()):
|
|
105
|
+
if x0 <= x < x1 and y0 <= y < y1:
|
|
106
|
+
cells.append(TimelineCell(x=x, y=y, v=float(v), ev="measured",
|
|
107
|
+
glyphs=_glyphs(model, (x, y), cuts, cut_count,
|
|
108
|
+
record_count, symbols)))
|
|
109
|
+
cells = take(cells, MAX_CELLS, "cells", omitted,
|
|
110
|
+
reason="cells beyond the first (row-major); request a smaller window")
|
|
111
|
+
tokens = []
|
|
112
|
+
for x in range(x0, min(x1, nx)):
|
|
113
|
+
if model.tokens is not None and x < len(model.tokens):
|
|
114
|
+
tokens.append(TokenCell(x=x, id=model.tokens[x], ev="measured"))
|
|
115
|
+
else:
|
|
116
|
+
tokens.append(TokenCell(x=x, id=None, ev="unresolved",
|
|
117
|
+
reason=model.tokens_reason or "row beyond the tokens slot"))
|
|
118
|
+
block = TimelineBlock(lens=lens, lenses=lens_infos(model), unit=unit, axes=axes[:2],
|
|
119
|
+
win=Window(x0=x0, x1=x1, y0=y0, y1=y1), cells=cells, fill=fill,
|
|
120
|
+
tokens=tokens, branch=branch)
|
|
121
|
+
return block, omitted
|