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
mdb/ops/named.py
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
"""Named symbols declared from a transplant result.
|
|
2
|
+
|
|
3
|
+
A transplant is a ``whatif`` or ``compare`` edit that writes a value taken from another run (or
|
|
4
|
+
another address of the same run) at one source occurrence, ``t18.L20.v[kv0] = clean:t18.L20.
|
|
5
|
+
v[kv0]``, and measures a consumer natively. ``symbol NAME = whatif`` (the last ``whatif`` of
|
|
6
|
+
this session), ``symbol NAME = compare.a|compare.b`` (a side of the last ``compare``) or
|
|
7
|
+
``symbol NAME = EACH:ITEM`` (one item's whatif of an ``each`` result, in memory or stored)
|
|
8
|
+
turns it into a reusable name. The ``symbol`` record (``core.kinds.SYMBOL``) binds:
|
|
9
|
+
|
|
10
|
+
* ``role``: the writer, row-free (``L20.v[kv0]``: port, layer and selector, or a cache cell
|
|
11
|
+
with ``row=@``), and its readers as ``reads`` lists them at the consumer's row (mass
|
|
12
|
+
``measured``, effect ``derived-exact P19``, causal verdict ``measured``), or why not;
|
|
13
|
+
* ``row``: the source row, role-relative (``t@word``) when the run's prompt is an item of a
|
|
14
|
+
loaded prompt set with a role at that row (or ``role=NAME`` names it, ``supplied``),
|
|
15
|
+
otherwise absolute, with the prompt's and the prefix's sha256;
|
|
16
|
+
* ``consumer`` and ``evidence``: the measured effect that justifies the name (base, edited,
|
|
17
|
+
delta ``measured``; the verdict). A result whose verdict is not ``effect`` is refused: no
|
|
18
|
+
record is made (a name stands for a measured effect, never for its absence);
|
|
19
|
+
* ``origin``: the donor value (run, address, sha256, cut, recipe), the run, its prefill
|
|
20
|
+
procedure and its edits, where the result came from.
|
|
21
|
+
|
|
22
|
+
Use: the name stands for its address where an address is expected (``print NAME``, ``whatif
|
|
23
|
+
NAME = clean:NAME --consumer C``, ``break NAME``, ``reads NAME``...); ``registry.dispatch``
|
|
24
|
+
calls ``expand`` before the op, and the result lists each use under ``symbol_uses``. The row
|
|
25
|
+
binds on the run the address is read in (``ORIGIN:NAME``: on run ORIGIN): its declaring prompt;
|
|
26
|
+
a prompt-set item with the same tokens and the role; the same tokens before the row. Inside
|
|
27
|
+
``each``, ``NAME`` binds through the item's role (``t@word``; ``@pair:NAME`` through the pair's)
|
|
28
|
+
and an absolute symbol through the item's prefix. A use that does not bind is refused with the
|
|
29
|
+
reason. Records are pointers and labelled numbers only (64 KiB).
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import re
|
|
35
|
+
import weakref
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from mdb.core.pointers import RecordError, seal_digest
|
|
39
|
+
|
|
40
|
+
from .context import Context
|
|
41
|
+
from .errors import BadArgs, OpError, Refused
|
|
42
|
+
from .registry import hook
|
|
43
|
+
|
|
44
|
+
SCHEMA = "mdb-symbol-v1"
|
|
45
|
+
MAX_READERS = 8
|
|
46
|
+
MAX_EDITS = 16
|
|
47
|
+
_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
48
|
+
_ADDRESS_LIKE = re.compile(r"(?:t|L|h|kv)\d+")
|
|
49
|
+
RESERVED = frozenset({"Unbound", "last", "pair", "cache", "whatif", "compare", "show", "delete",
|
|
50
|
+
"cursor", "M"})
|
|
51
|
+
_REFERENCE = re.compile(r"(?P<kind>whatif|compare\.(?P<side>[ab]))|"
|
|
52
|
+
r"(?P<each>each\d+|[0-9a-f]{12,64}):(?P<item>[A-Za-z_][A-Za-z0-9_]*)")
|
|
53
|
+
_OCCURRENCE = re.compile(r"t(?P<row>\d+)\.(?P<writer>L(?P<layer>\d+)\.(?P<port>\w+)"
|
|
54
|
+
r"(?:\[(?P<sel>[^\]]*)\])?)")
|
|
55
|
+
_CELL = re.compile(r"cache\.L(?P<layer>\d+)\.(?P<port>k|v)\[(?P<sel>[^\]]*)\]")
|
|
56
|
+
# the verbs whose arguments are addresses (or ADDR = VALUE sides): a name there is expanded
|
|
57
|
+
ADDRESS_ARGS = {
|
|
58
|
+
"print": ("address",), "x": ("address",), "display": ("address",), "frame": ("address",),
|
|
59
|
+
"backtrace": ("address",), "explain": ("address",), "forecast": ("target",),
|
|
60
|
+
"until": ("target",), "advance": ("target",), "seek": ("target",), "break": ("pattern",),
|
|
61
|
+
"tbreak": ("pattern",), "watch": ("address",), "set": ("target", "value"),
|
|
62
|
+
"whatif": ("target", "value"), "compare": ("a", "b"), "reads": ("source",),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
_STORE: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() # debugger -> {name: record}
|
|
66
|
+
_LAST: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() # ctx -> {op: (result, run)}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def store(debugger: Any) -> dict[str, dict[str, Any]]:
|
|
70
|
+
"""The named symbols of ``debugger`` (name -> sealed ``symbol`` record)."""
|
|
71
|
+
if debugger not in _STORE:
|
|
72
|
+
_STORE[debugger] = {}
|
|
73
|
+
return _STORE[debugger]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_reference(text: str) -> bool:
|
|
77
|
+
"""Whether the right side of ``symbol NAME = ...`` names a result, not addresses."""
|
|
78
|
+
return _REFERENCE.fullmatch(text.strip()) is not None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# --------------------------------------------------------------------------- binding
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _sha(tokens: list[int]) -> str:
|
|
85
|
+
return seal_digest([int(t) for t in tokens])
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _tokens(run: Any) -> list[int]:
|
|
89
|
+
return [int(t) for t in run.tokens]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def address_at(body: dict[str, Any], row: int | str) -> str:
|
|
93
|
+
"""The symbol's address at ``row`` (an int, or ``@ROLE`` for a template)."""
|
|
94
|
+
writer = body["role"]["writer"]
|
|
95
|
+
if writer["form"] == "cell":
|
|
96
|
+
return writer["address"].replace("row=@", f"row={row}")
|
|
97
|
+
return f"t{row}.{writer['address']}"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _set_items(debugger: Any, tokens: list[int], role: str) -> list[tuple[str, int]]:
|
|
101
|
+
"""``(set/item, row)`` of every loaded prompt-set item with these tokens and this role."""
|
|
102
|
+
from . import sets
|
|
103
|
+
|
|
104
|
+
found = []
|
|
105
|
+
for name, found_set in sorted(sets.sets_of(debugger).items()):
|
|
106
|
+
for item in found_set.items:
|
|
107
|
+
if role not in item.roles:
|
|
108
|
+
continue
|
|
109
|
+
try:
|
|
110
|
+
same = debugger.tokens(item.prompt) == tokens
|
|
111
|
+
except Refused:
|
|
112
|
+
continue
|
|
113
|
+
if same:
|
|
114
|
+
found.append((f"{name}/{item.name}", int(item.roles[role])))
|
|
115
|
+
return found
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def bind(debugger: Any, record: dict[str, Any], tokens: list[int]) -> tuple[int, str]:
|
|
119
|
+
"""``(row, how)`` of a symbol on a prompt, or ``Refused`` with the reason."""
|
|
120
|
+
body = record["body"]
|
|
121
|
+
row = body["row"]
|
|
122
|
+
name = body["name"]
|
|
123
|
+
if _sha(tokens) == row["prompt_sha256"]:
|
|
124
|
+
return row["row"], "its declaring prompt"
|
|
125
|
+
if row["rule"] == "role":
|
|
126
|
+
role = row["role"]
|
|
127
|
+
if role == "last":
|
|
128
|
+
return len(tokens) - 1, "role @last"
|
|
129
|
+
found = _set_items(debugger, tokens, role)
|
|
130
|
+
rows = sorted({r for _, r in found})
|
|
131
|
+
if len(rows) == 1:
|
|
132
|
+
return rows[0], f"role @{role} of {found[0][0]}"
|
|
133
|
+
if len(rows) > 1:
|
|
134
|
+
raise Refused(f"symbol {name}: role @{role} names rows {rows} in the loaded set items "
|
|
135
|
+
f"with this prompt ({', '.join(f for f, _ in found)})")
|
|
136
|
+
at = row["row"]
|
|
137
|
+
if at < len(tokens) and _sha(tokens[:at]) == row["prefix_sha256"]:
|
|
138
|
+
return at, f"same tokens as its declaring prompt before row {at}"
|
|
139
|
+
what = (f"role @{row['role']} (row {at} of its declaring prompt)" if row["rule"] == "role"
|
|
140
|
+
else f"absolute row t{at} (no role named that row when it was declared)")
|
|
141
|
+
tried = ("no loaded prompt-set item with role "
|
|
142
|
+
f"@{row['role']} has this prompt, and " if row["rule"] == "role" else "")
|
|
143
|
+
raise Refused(f"symbol {name} binds {what}; on this prompt ({len(tokens)} tokens) {tried}"
|
|
144
|
+
f"the tokens before row {at} differ from its declaring prompt's, so the row "
|
|
145
|
+
"is not known: use it inside `each SET ...` where the item's role binds it, or "
|
|
146
|
+
"declare it from a run of this prompt")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _bind_run(ctx: Any, record: dict[str, Any], origin: str | None) -> tuple[int, str, Any]:
|
|
150
|
+
debugger = ctx.debugger
|
|
151
|
+
if origin is None:
|
|
152
|
+
run = ctx.run
|
|
153
|
+
if run is None:
|
|
154
|
+
raise Refused(f"symbol {record['body']['name']}: no live run to bind it on")
|
|
155
|
+
else:
|
|
156
|
+
run = (getattr(debugger, "runs", None) or {}).get(origin)
|
|
157
|
+
if run is None:
|
|
158
|
+
known = ", ".join(getattr(debugger, "runs", None) or ()) or "none"
|
|
159
|
+
raise Refused(f"symbol {record['body']['name']} in {origin}:: {origin} is not a live "
|
|
160
|
+
f"run of this debugger (runs: {known}); a symbol binds its row on a "
|
|
161
|
+
"live run's prompt")
|
|
162
|
+
row, how = bind(debugger, record, _tokens(run))
|
|
163
|
+
return row, how, run
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _pattern(names: list[str]) -> re.Pattern:
|
|
167
|
+
joined = "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True))
|
|
168
|
+
return re.compile(r"(?<![\w.@$:\[\"'\-])(?:(?P<origin>[A-Za-z_][\w\-]*):)?"
|
|
169
|
+
rf"(?P<name>{joined})(?![\w.\[:\"'\-])")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _assigns(text: str) -> bool:
|
|
173
|
+
depth = 0
|
|
174
|
+
for char in text:
|
|
175
|
+
depth += char == "["
|
|
176
|
+
depth -= char == "]"
|
|
177
|
+
if char == "=" and depth == 0:
|
|
178
|
+
return True
|
|
179
|
+
return False
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def expand(ctx: Any, text: str, *, notes: list[dict[str, Any]] | None = None) -> str:
|
|
183
|
+
"""``text`` with every symbol name (and ``ORIGIN:NAME``) replaced by its address on the
|
|
184
|
+
run it is read in; ``Refused`` when one does not bind."""
|
|
185
|
+
debugger = getattr(ctx, "debugger", None)
|
|
186
|
+
named = _STORE.get(debugger) if debugger is not None else None
|
|
187
|
+
if not named:
|
|
188
|
+
return text
|
|
189
|
+
|
|
190
|
+
def one(match: re.Match) -> str:
|
|
191
|
+
record = named[match["name"]]
|
|
192
|
+
origin = match["origin"]
|
|
193
|
+
row, how, run = _bind_run(ctx, record, origin)
|
|
194
|
+
address = address_at(record["body"], row)
|
|
195
|
+
note: dict[str, Any] = {"symbol": match["name"],
|
|
196
|
+
"address": f"{origin}:{address}" if origin else address,
|
|
197
|
+
"row": row, "how": how}
|
|
198
|
+
tokens = _tokens(run)
|
|
199
|
+
if row < len(tokens):
|
|
200
|
+
note["token"] = tokens[row]
|
|
201
|
+
if ctx.tokenizer is not None:
|
|
202
|
+
note["text"] = ctx.tokenizer.decode([tokens[row]])
|
|
203
|
+
if notes is not None:
|
|
204
|
+
notes.append(note)
|
|
205
|
+
return f"{origin}:{address}" if origin else address
|
|
206
|
+
|
|
207
|
+
return _pattern(list(named)).sub(one, text)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def expand_for_item(debugger: Any, text: str, tokens: list[int]) -> str:
|
|
211
|
+
"""``text`` for one prompt-set item (``each``): a role symbol becomes its role template
|
|
212
|
+
(``t@word.L20.v[kv0]``, bound by the item's roles next), an absolute one its row when the
|
|
213
|
+
item's tokens before it are the declaring prompt's; ``ORIGIN:NAME`` binds on run ORIGIN.
|
|
214
|
+
``Refused`` with the reason otherwise."""
|
|
215
|
+
named = _STORE.get(debugger)
|
|
216
|
+
if not named:
|
|
217
|
+
return text
|
|
218
|
+
|
|
219
|
+
def one(match: re.Match) -> str:
|
|
220
|
+
record = named[match["name"]]
|
|
221
|
+
body = record["body"]
|
|
222
|
+
if match["origin"]:
|
|
223
|
+
row, _, _ = _bind_run(Context(debugger), record, match["origin"])
|
|
224
|
+
return f"{match['origin']}:{address_at(body, row)}"
|
|
225
|
+
if body["row"]["rule"] == "role":
|
|
226
|
+
return address_at(body, f"@{body['row']['role']}")
|
|
227
|
+
row, _ = bind(debugger, record, tokens)
|
|
228
|
+
return address_at(body, row)
|
|
229
|
+
|
|
230
|
+
return _pattern(list(named)).sub(one, text)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _before(ctx: Any, name: str, values: dict[str, Any]) -> tuple[dict[str, Any], list]:
|
|
234
|
+
fields = ADDRESS_ARGS.get(name)
|
|
235
|
+
debugger = getattr(ctx, "debugger", None)
|
|
236
|
+
if not fields or debugger is None or not _STORE.get(debugger):
|
|
237
|
+
return values, []
|
|
238
|
+
notes: list[dict[str, Any]] = []
|
|
239
|
+
out = dict(values)
|
|
240
|
+
for key in fields:
|
|
241
|
+
value = out.get(key)
|
|
242
|
+
if not isinstance(value, str) or (name == "compare" and not _assigns(value)):
|
|
243
|
+
continue # a compare side without `=` is a checkpoint name, not an address
|
|
244
|
+
out[key] = expand(ctx, value, notes=notes)
|
|
245
|
+
return out, notes[:16]
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _after(ctx: Any, name: str, result: dict[str, Any]) -> None:
|
|
249
|
+
run = getattr(ctx, "run", None)
|
|
250
|
+
if name in ("whatif", "compare") and run is not None:
|
|
251
|
+
_LAST.setdefault(ctx, {})[name] = (result, weakref.ref(run))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
hook(before=_before, after=_after)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# --------------------------------------------------------------------------- declaring
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def check_name(ctx: Any, name: str) -> None:
|
|
261
|
+
program = ctx.run.program if ctx.run is not None else ctx.debugger.program
|
|
262
|
+
from .builtin import GLOBALS
|
|
263
|
+
|
|
264
|
+
if not _NAME.fullmatch(name) or name in RESERVED or _ADDRESS_LIKE.fullmatch(name) \
|
|
265
|
+
or name in program.names or name in GLOBALS:
|
|
266
|
+
raise Refused(f"a symbol name is a word ([A-Za-z_][A-Za-z0-9_]*) that is not an address, "
|
|
267
|
+
f"a port, a stop or reserved ({', '.join(sorted(RESERVED))}), not {name!r}")
|
|
268
|
+
runs = getattr(ctx.debugger, "runs", None) or {}
|
|
269
|
+
if name in runs:
|
|
270
|
+
raise Refused(f"{name} is a run of this debugger; a symbol needs another name")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _source(text: str) -> dict[str, Any]:
|
|
274
|
+
"""The writer of a source address: row, row-free address, form, reads source."""
|
|
275
|
+
text = text.strip()
|
|
276
|
+
match = _OCCURRENCE.fullmatch(text)
|
|
277
|
+
if match is not None:
|
|
278
|
+
row, layer, port, sel = (int(match["row"]), int(match["layer"]), match["port"],
|
|
279
|
+
match["sel"])
|
|
280
|
+
reads = why = None
|
|
281
|
+
if port in ("k", "v"):
|
|
282
|
+
if sel is None:
|
|
283
|
+
reads = f"t{row}.L{layer}.{port}"
|
|
284
|
+
elif re.fullmatch(r"kv\d+", sel):
|
|
285
|
+
reads = f"cache.L{layer}.{port}[{sel},row={row}]"
|
|
286
|
+
else:
|
|
287
|
+
why = (f"reads follows whole KV heads; the source selects [{sel}]")
|
|
288
|
+
else:
|
|
289
|
+
why = (f"reads follows cache cells (k, v); a {port} value is read by the later stops "
|
|
290
|
+
"of its own row, not by attention")
|
|
291
|
+
return {"row": row, "layer": layer, "port": port, "form": "occurrence",
|
|
292
|
+
"writer": match["writer"], "reads": reads, "why": why, "text": text}
|
|
293
|
+
match = _CELL.fullmatch(text)
|
|
294
|
+
if match is None:
|
|
295
|
+
raise Refused(f"a symbol's source is a port occurrence t<r>.L<l>.<port>[sel] or a cache "
|
|
296
|
+
f"cell cache.L<l>.k|v[...,row=<r>], not {text!r}")
|
|
297
|
+
parts = [p.strip() for p in match["sel"].split(",") if p.strip()]
|
|
298
|
+
rows = [p for p in parts if p.startswith("row=")]
|
|
299
|
+
if len(rows) != 1 or not rows[0][4:].isdigit():
|
|
300
|
+
raise Refused(f"a symbol binds one source row; {text} selects "
|
|
301
|
+
f"{rows[0] if rows else 'no row'}")
|
|
302
|
+
row = int(rows[0][4:])
|
|
303
|
+
rest = [p for p in parts if not p.startswith("row=")]
|
|
304
|
+
writer = f"cache.L{match['layer']}.{match['port']}[" + ",".join(
|
|
305
|
+
"row=@" if p.startswith("row=") else p for p in parts) + "]"
|
|
306
|
+
whole = all(re.fullmatch(r"kv\d+", p) for p in rest)
|
|
307
|
+
return {"row": row, "layer": int(match["layer"]), "port": match["port"], "form": "cell",
|
|
308
|
+
"writer": writer, "text": text,
|
|
309
|
+
"reads": (f"cache.L{match['layer']}.{match['port']}[{','.join(rest + [f'row={row}'])}]"
|
|
310
|
+
if whole else None),
|
|
311
|
+
"why": None if whole else f"reads follows whole KV heads; the source selects {text}"}
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _num(item: Any) -> Any:
|
|
315
|
+
"""A labelled number as stored: ``{value, authority[, proof]}`` or a state with a reason."""
|
|
316
|
+
if isinstance(item, dict) and "value" in item and "authority" in item:
|
|
317
|
+
return {k: item[k] for k in ("value", "authority", "proof") if k in item}
|
|
318
|
+
if isinstance(item, dict) and item.get("state"):
|
|
319
|
+
return {"state": item["state"], "reason": str(item.get("reason", item["state"]))}
|
|
320
|
+
return {"state": "unresolved", "reason": "not in the result"}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _consumer(text: str) -> dict[str, Any]:
|
|
324
|
+
match = re.fullmatch(r"t(?P<row>\d+)\.(?P<rest>.+)", text)
|
|
325
|
+
out: dict[str, Any] = {"address": text}
|
|
326
|
+
if match is not None:
|
|
327
|
+
out["row"] = int(match["row"])
|
|
328
|
+
return out
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _from_whatif(result: dict[str, Any], label: str) -> dict[str, Any]:
|
|
332
|
+
edit = result["edit"]
|
|
333
|
+
address = edit["address"]
|
|
334
|
+
if "[" not in address and edit.get("selection"):
|
|
335
|
+
address = f"{address}[{edit['selection']}]"
|
|
336
|
+
origin = edit.get("origin")
|
|
337
|
+
donor = edit.get("source")
|
|
338
|
+
if edit.get("op") != "replace" or not (isinstance(origin, dict) or isinstance(donor, str)):
|
|
339
|
+
raise Refused(f"{label} is not a transplant: it {edit.get('op')}s "
|
|
340
|
+
f"{'a scalar' if not isinstance(donor, str) else donor} at {address}; a "
|
|
341
|
+
"symbol is declared from a replace whose value is another run's (ORIGIN:"
|
|
342
|
+
"ADDR) or another address's")
|
|
343
|
+
effect = result.get("effect") or {}
|
|
344
|
+
consumer = dict(result["consumer"])
|
|
345
|
+
measured = result["measured"]
|
|
346
|
+
evidence = {"op": "whatif", "base": _num(measured["base"]),
|
|
347
|
+
"edited": _num(measured["edited"]), "delta": _num(measured["delta"]),
|
|
348
|
+
"exact": _num(effect.get("exact")), "emulated": _num(effect.get("emulated")),
|
|
349
|
+
"floor": _num(effect.get("floor")), "verdict": effect.get("verdict"),
|
|
350
|
+
"basis": effect.get("basis", ""), "record": result.get("record", "")}
|
|
351
|
+
procedure = ((result.get("sealed_record") or {}).get("body") or {}).get("procedure")
|
|
352
|
+
return {"source": address, "donor": donor, "origin": origin, "evidence": evidence,
|
|
353
|
+
"consumer": {k: consumer[k] for k in ("address", "row", "kind", "indices")
|
|
354
|
+
if k in consumer},
|
|
355
|
+
"where": result.get("where"), "procedure": procedure,
|
|
356
|
+
"note": effect.get("note") or effect.get("reason")}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _from_compare(ctx: Any, run: Any, result: dict[str, Any], side: str) -> dict[str, Any]:
|
|
360
|
+
from .builtin import resolve_target
|
|
361
|
+
from .predict import parse_assignment
|
|
362
|
+
|
|
363
|
+
text = result["sides"][side]
|
|
364
|
+
if not _assigns(text):
|
|
365
|
+
raise Refused(f"compare side {side} is the checkpoint {text!r}, not a transplant")
|
|
366
|
+
address, value, op, _ = parse_assignment(text)
|
|
367
|
+
if (op or "replace") != "replace" or not isinstance(value, str):
|
|
368
|
+
raise Refused(f"compare side {side} ({text}) is not a transplant: a symbol is declared "
|
|
369
|
+
"from a replace whose value is another run's (ORIGIN:ADDR) or address's")
|
|
370
|
+
local = ctx if ctx.run is run else Context(ctx.debugger, run)
|
|
371
|
+
found = resolve_target(local, address)
|
|
372
|
+
verdict = result["verdicts"][side]
|
|
373
|
+
evidence = {"op": "compare", "base": _num(result["measured"]["base"]["value"]),
|
|
374
|
+
"edited": _num(result["measured"][side]["value"]),
|
|
375
|
+
"delta": _num(result["effects"][side]), "floor": _num(verdict.get("floor")),
|
|
376
|
+
"verdict": verdict.get("verdict"), "basis": verdict.get("basis", ""),
|
|
377
|
+
"record": ""}
|
|
378
|
+
from mdb.core.kinds import procedure
|
|
379
|
+
|
|
380
|
+
return {"source": found.text, "donor": value, "origin": None, "evidence": evidence,
|
|
381
|
+
"consumer": _consumer(result["consumer"]), "where": result.get("where"),
|
|
382
|
+
"procedure": procedure(run), "note": None}
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _reference(ctx: Any, text: str) -> tuple[dict[str, Any], Any, Any, str]:
|
|
386
|
+
"""``(transplant, run, item, from)`` for a result reference."""
|
|
387
|
+
from . import sets
|
|
388
|
+
from .registry import dispatch
|
|
389
|
+
|
|
390
|
+
match = _REFERENCE.fullmatch(text.strip())
|
|
391
|
+
if match["each"]:
|
|
392
|
+
try:
|
|
393
|
+
found = dispatch(ctx, "promptset", {"action": "result", "name": match["each"],
|
|
394
|
+
"arg": match["item"]})
|
|
395
|
+
summary = dispatch(ctx, "promptset", {"action": "result",
|
|
396
|
+
"name": match["each"]})["summary"]
|
|
397
|
+
except OpError as error:
|
|
398
|
+
raise Refused(f"{text}: {error}") from None
|
|
399
|
+
result = found["result"]
|
|
400
|
+
if result.get("op") != "whatif":
|
|
401
|
+
raise Refused(f"{text} is a {result.get('op')} result; a symbol is declared from an "
|
|
402
|
+
"item's whatif")
|
|
403
|
+
known = sets.sets_of(ctx.debugger).get(summary["set"])
|
|
404
|
+
if known is None or match["item"] not in {i.name for i in known.items}:
|
|
405
|
+
raise Refused(f"{text}: set {summary['set']} is not loaded, so the item's roles are "
|
|
406
|
+
"unknown; load it again (set load)")
|
|
407
|
+
bound = sets.Bound(ctx.debugger, known.item(match["item"]))
|
|
408
|
+
run = (getattr(ctx.debugger, "runs", None) or {}).get(f"{summary['set']}-{match['item']}")
|
|
409
|
+
if run is not None and _tokens(run) != bound.tokens:
|
|
410
|
+
run = None
|
|
411
|
+
return _from_whatif(result, text), run, bound, f"{text} (set {summary['set']})"
|
|
412
|
+
entry = _LAST.get(ctx, {}).get("whatif" if match["kind"] == "whatif" else "compare")
|
|
413
|
+
if entry is None:
|
|
414
|
+
raise Refused(f"no {match['kind'].split('.')[0]} result in this session yet: run one "
|
|
415
|
+
"(whatif ADDR = ORIGIN:ADDR --consumer C), then symbol NAME = "
|
|
416
|
+
f"{match['kind']}")
|
|
417
|
+
result, ref = entry
|
|
418
|
+
run = ref()
|
|
419
|
+
if match["kind"] == "whatif":
|
|
420
|
+
return _from_whatif(result, "the last whatif"), run, None, "the last whatif"
|
|
421
|
+
if run is None:
|
|
422
|
+
raise Refused("the run of the last compare is gone; run compare again")
|
|
423
|
+
side = match["side"].upper()
|
|
424
|
+
return _from_compare(ctx, run, result, side), run, None, f"side {side} of the last compare"
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _row_rule(ctx: Any, tokens: list[int], row: int, role: str | None, item: Any
|
|
428
|
+
) -> dict[str, Any]:
|
|
429
|
+
if item is not None:
|
|
430
|
+
names = sorted(r for r, v in item.roles.items() if v == row and r != "last")
|
|
431
|
+
where = {name: f"set item {item.item.name}" for name in names}
|
|
432
|
+
else:
|
|
433
|
+
where = _roles_at(ctx.debugger, tokens, row)
|
|
434
|
+
names = sorted(where)
|
|
435
|
+
if not names and row == len(tokens) - 1:
|
|
436
|
+
names, where = ["last"], {"last": "the prompt's last row"}
|
|
437
|
+
if role is not None:
|
|
438
|
+
if names and role not in names:
|
|
439
|
+
raise Refused(f"role={role}: row {row} is role {', '.join('@' + n for n in names)} "
|
|
440
|
+
f"of {where[names[0]]}, not @{role}")
|
|
441
|
+
source = where.get(role, "supplied (role= on the declaration)")
|
|
442
|
+
return {"rule": "role", "role": role, "role_source": source}
|
|
443
|
+
if len(names) > 1:
|
|
444
|
+
raise Refused(f"row {row} is roles {', '.join('@' + n for n in names)}: name one with "
|
|
445
|
+
"role=NAME")
|
|
446
|
+
if names:
|
|
447
|
+
return {"rule": "role", "role": names[0], "role_source": where[names[0]]}
|
|
448
|
+
return {"rule": "absolute"}
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _roles_at(debugger: Any, tokens: list[int], row: int) -> dict[str, str]:
|
|
452
|
+
"""Role name -> ``set/item`` of the loaded set items with these tokens and a role at row."""
|
|
453
|
+
from . import sets
|
|
454
|
+
|
|
455
|
+
out: dict[str, str] = {}
|
|
456
|
+
for name, found_set in sorted(sets.sets_of(debugger).items()):
|
|
457
|
+
for item in found_set.items:
|
|
458
|
+
roles = [r for r, v in item.roles.items() if v == row]
|
|
459
|
+
if not roles:
|
|
460
|
+
continue
|
|
461
|
+
try:
|
|
462
|
+
same = debugger.tokens(item.prompt) == tokens
|
|
463
|
+
except Refused:
|
|
464
|
+
continue
|
|
465
|
+
if same:
|
|
466
|
+
for role in roles:
|
|
467
|
+
out.setdefault(role, f"set item {name}/{item.name}")
|
|
468
|
+
return out
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _readers(ctx: Any, run: Any, source: dict[str, Any], consumer: dict[str, Any], top: int,
|
|
472
|
+
causal: bool) -> dict[str, Any]:
|
|
473
|
+
from .registry import dispatch
|
|
474
|
+
|
|
475
|
+
if source["reads"] is None:
|
|
476
|
+
return {"state": "unresolved", "reason": source["why"]}
|
|
477
|
+
if run is None:
|
|
478
|
+
return {"state": "unresolved",
|
|
479
|
+
"reason": "the run the result was measured on is gone (released or replaced); "
|
|
480
|
+
"keep it (each ... keep, or declare before moving on) to list readers"}
|
|
481
|
+
here = int(run.where.split(".")[0][1:])
|
|
482
|
+
row = consumer.get("row")
|
|
483
|
+
if row is None or row > here:
|
|
484
|
+
return {"state": "unresolved",
|
|
485
|
+
"reason": f"the cursor {run.where} is before the consumer's row t{row}: reads "
|
|
486
|
+
f"lists the reads made there; run until t{row}.logits and declare "
|
|
487
|
+
"again"}
|
|
488
|
+
local = ctx if ctx.run is run else Context(ctx.debugger, run)
|
|
489
|
+
try:
|
|
490
|
+
found = dispatch(local, "reads", {"source": source["reads"], "rows": str(row),
|
|
491
|
+
"consumer": consumer["address"], "top": top,
|
|
492
|
+
"causal": causal})
|
|
493
|
+
except OpError as error:
|
|
494
|
+
return {"state": "refused", "reason": f"reads {source['reads']}: {error}"}
|
|
495
|
+
listed = []
|
|
496
|
+
for read in found["reads"][:top]:
|
|
497
|
+
entry: dict[str, Any] = {"name": read["name"], "row": read["row"],
|
|
498
|
+
"layer": read["layer"], "mass": _num(read["mass"]),
|
|
499
|
+
"effect": _num(read.get("to_consumer"))}
|
|
500
|
+
check = read.get("causal") if causal else None
|
|
501
|
+
if isinstance(check, dict) and "delta" in check:
|
|
502
|
+
entry["causal"] = {"verdict": str(check.get("verdict", "unresolved")),
|
|
503
|
+
"delta": _num(check["delta"])}
|
|
504
|
+
elif isinstance(check, dict):
|
|
505
|
+
entry["causal"] = {"verdict": str(check.get("verdict") or check.get("state")
|
|
506
|
+
or "unresolved"),
|
|
507
|
+
"reason": str(check.get("reason", ""))}
|
|
508
|
+
listed.append(entry)
|
|
509
|
+
omitted = found.get("omitted") or {}
|
|
510
|
+
out: dict[str, Any] = {
|
|
511
|
+
"state": "resolved", "source": source["reads"], "rows": [row],
|
|
512
|
+
"consumer": consumer["address"], "at": run.where,
|
|
513
|
+
"count": len(found["reads"]) + int(omitted.get("count", 0) or 0), "listed": listed,
|
|
514
|
+
"authority": "as reads reports them: mass measured, effect derived-exact P19 (the read's "
|
|
515
|
+
"exact share of the consumer), causal verdict measured (the read removed "
|
|
516
|
+
"natively)"}
|
|
517
|
+
if found.get("not_computed"):
|
|
518
|
+
out["not_computed"] = list(found["not_computed"])[:8]
|
|
519
|
+
return out
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def declare(ctx: Any, name: str, reference: str, *, role: str | None = None, readers: int = 6,
|
|
523
|
+
causal: bool = True) -> dict[str, Any]:
|
|
524
|
+
"""``symbol NAME = REFERENCE``: seal a ``symbol`` record from a transplant result."""
|
|
525
|
+
from mdb.core.records import seal_record
|
|
526
|
+
|
|
527
|
+
from .inspect import _edit_list, _symbol_store
|
|
528
|
+
|
|
529
|
+
debugger = ctx.debugger
|
|
530
|
+
if debugger is None:
|
|
531
|
+
raise Refused("symbols need an attached model")
|
|
532
|
+
check_name(ctx, name)
|
|
533
|
+
if name in _symbol_store(ctx):
|
|
534
|
+
raise Refused(f"{name} is a declared cell symbol (symbol {name} = ADDR...); delete it or "
|
|
535
|
+
"choose another name")
|
|
536
|
+
transplant, run, item, came_from = _reference(ctx, reference)
|
|
537
|
+
evidence = transplant["evidence"]
|
|
538
|
+
if evidence["verdict"] != "effect":
|
|
539
|
+
note = f" ({transplant['note']})" if transplant.get("note") else ""
|
|
540
|
+
raise Refused(f"not declared: {came_from} has verdict {evidence['verdict']!r}{note}; a "
|
|
541
|
+
"symbol stands for a measured effect (verdict effect), so no record is made")
|
|
542
|
+
source = _source(transplant["source"])
|
|
543
|
+
tokens = item.tokens if item is not None else _tokens(run) if run is not None else None
|
|
544
|
+
if tokens is None:
|
|
545
|
+
raise Refused(f"the run of {came_from} is gone; its prompt is unknown")
|
|
546
|
+
row = source["row"]
|
|
547
|
+
rule = _row_rule(ctx, tokens, row, role, item)
|
|
548
|
+
row_view: dict[str, Any] = {"row": row, **rule, "prompt_rows": len(tokens),
|
|
549
|
+
"prompt_sha256": _sha(tokens), "prefix_sha256": _sha(tokens[:row])}
|
|
550
|
+
if row < len(tokens):
|
|
551
|
+
row_view["token"] = tokens[row]
|
|
552
|
+
if ctx.tokenizer is not None:
|
|
553
|
+
row_view["text"] = ctx.tokenizer.decode([tokens[row]])
|
|
554
|
+
writer = {"layer": source["layer"], "port": source["port"], "form": source["form"],
|
|
555
|
+
"address": source["writer"]}
|
|
556
|
+
body: dict[str, Any] = {"schema": SCHEMA, "name": name}
|
|
557
|
+
body["row"] = row_view
|
|
558
|
+
template = (f"@{rule['role']}" if rule["rule"] == "role" else row)
|
|
559
|
+
row_view["address"] = address_at({"role": {"writer": writer}}, template)
|
|
560
|
+
body["role"] = {
|
|
561
|
+
"writer": writer,
|
|
562
|
+
"meaning": "the writer (port and selector at its layer, or the cache cell) without its "
|
|
563
|
+
"row; the readers are the reads of the source at the consumer's row",
|
|
564
|
+
"readers": _readers(ctx, run, source, transplant["consumer"], readers, causal),
|
|
565
|
+
}
|
|
566
|
+
body["consumer"] = transplant["consumer"]
|
|
567
|
+
body["evidence"] = {**evidence, "edit": f"{source['text']} = {transplant['donor']}",
|
|
568
|
+
"authority": "base, edited and delta measured natively; the verdict is "
|
|
569
|
+
"the result's own (P20)"}
|
|
570
|
+
origin: dict[str, Any] = {"from": came_from, "where": transplant.get("where") or ""}
|
|
571
|
+
if isinstance(transplant["origin"], dict):
|
|
572
|
+
donor = transplant["origin"]
|
|
573
|
+
origin["donor"] = {k: donor[k] for k in ("origin", "via", "address", "sha256", "cut",
|
|
574
|
+
"recipe", "where") if donor.get(k) is not None}
|
|
575
|
+
else:
|
|
576
|
+
origin["donor"] = {"address": str(transplant["donor"])}
|
|
577
|
+
if run is not None:
|
|
578
|
+
origin["run"] = getattr(run, "name", None) or ""
|
|
579
|
+
edits = _edit_list(run)
|
|
580
|
+
origin["edits"] = {k: v[:MAX_EDITS] for k, v in edits.items()}
|
|
581
|
+
if transplant.get("procedure"):
|
|
582
|
+
body["procedure"] = transplant["procedure"]
|
|
583
|
+
body["origin"] = origin
|
|
584
|
+
adapter = run.adapter if run is not None else debugger.adapter
|
|
585
|
+
session = getattr(debugger, "session_id", None)
|
|
586
|
+
project = getattr(debugger, "project", None)
|
|
587
|
+
writable = project is not None and not project.read_only and session is not None
|
|
588
|
+
try:
|
|
589
|
+
record = seal_record(session_id=session if writable else f"mdb-symbol:{_sha(tokens)[:32]}",
|
|
590
|
+
kind="symbol", model_identity=adapter.model_identity,
|
|
591
|
+
execution=dict(adapter.execution), authority="measured", body=body,
|
|
592
|
+
run=run)
|
|
593
|
+
except RecordError as error:
|
|
594
|
+
raise Refused(f"symbol {name}: the record exceeds the record bound: {error}") from None
|
|
595
|
+
store(debugger)[name] = record
|
|
596
|
+
out: dict[str, Any] = {"action": "declare", "symbol": name, "record": record["id"],
|
|
597
|
+
"body": body}
|
|
598
|
+
if writable:
|
|
599
|
+
from mdb.core import index
|
|
600
|
+
|
|
601
|
+
out["stored"] = [index.put_record(project, record)]
|
|
602
|
+
return out
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def show(ctx: Any, name: str) -> dict[str, Any]:
|
|
606
|
+
from .predict import record_view
|
|
607
|
+
|
|
608
|
+
debugger = ctx.debugger
|
|
609
|
+
named = store(debugger) if debugger is not None else {}
|
|
610
|
+
if name not in named:
|
|
611
|
+
raise Refused(f"no named symbol {name!r} (have: {', '.join(sorted(named)) or 'none'})")
|
|
612
|
+
record = named[name]
|
|
613
|
+
return {"action": "show", "symbol": name, "record": record_view(record),
|
|
614
|
+
"here": here(ctx, record)}
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def here(ctx: Any, record: dict[str, Any]) -> dict[str, Any]:
|
|
618
|
+
"""The symbol's binding on the current run: its address and how, or the refusal."""
|
|
619
|
+
if getattr(ctx, "run", None) is None:
|
|
620
|
+
return {"state": "refused", "reason": "no live run"}
|
|
621
|
+
try:
|
|
622
|
+
row, how, _ = _bind_run(ctx, record, None)
|
|
623
|
+
except Refused as error:
|
|
624
|
+
return {"state": "refused", "reason": str(error)}
|
|
625
|
+
return {"address": address_at(record["body"], row), "row": row, "how": how}
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def delete(ctx: Any, name: str) -> dict[str, Any]:
|
|
629
|
+
named = store(ctx.debugger) if ctx.debugger is not None else {}
|
|
630
|
+
if name not in named:
|
|
631
|
+
raise Refused(f"no named symbol {name!r} (have: {', '.join(sorted(named)) or 'none'})")
|
|
632
|
+
record = named.pop(name)
|
|
633
|
+
return {"action": "delete", "symbol": name, "record": record["id"],
|
|
634
|
+
"note": "removed from this session; a record stored in a project stays there"}
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def listing(ctx: Any) -> list[dict[str, Any]]:
|
|
638
|
+
"""One line per named symbol for ``symbols``: source, evidence and its binding here."""
|
|
639
|
+
debugger = getattr(ctx, "debugger", None)
|
|
640
|
+
out = []
|
|
641
|
+
for name, record in sorted(store(debugger).items() if debugger is not None else ()):
|
|
642
|
+
body = record["body"]
|
|
643
|
+
out.append({"symbol": name, "source": body["row"]["address"],
|
|
644
|
+
"consumer": body["consumer"]["address"],
|
|
645
|
+
"delta": body["evidence"]["delta"], "verdict": body["evidence"]["verdict"],
|
|
646
|
+
"record": record["id"], "here": here(ctx, record)})
|
|
647
|
+
return out[:16]
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def parse_args(rest: str) -> dict[str, Any]:
|
|
651
|
+
"""The words after ``symbol NAME = REFERENCE``: ``role=R readers=K causal=false``."""
|
|
652
|
+
out: dict[str, Any] = {}
|
|
653
|
+
for word in rest.split():
|
|
654
|
+
key, equals, value = word.partition("=")
|
|
655
|
+
if not equals or key not in ("role", "readers", "causal"):
|
|
656
|
+
raise BadArgs("write symbol NAME = whatif|compare.a|compare.b|EACH:ITEM [role=R] "
|
|
657
|
+
"[readers=K] [causal=false]")
|
|
658
|
+
if key == "readers":
|
|
659
|
+
if not value.isdigit():
|
|
660
|
+
raise BadArgs("readers must be an integer")
|
|
661
|
+
out[key] = int(value)
|
|
662
|
+
elif key == "causal":
|
|
663
|
+
if value.lower() not in ("true", "false", "on", "off", "1", "0"):
|
|
664
|
+
raise BadArgs("causal must be true or false")
|
|
665
|
+
out[key] = value.lower() in ("true", "on", "1")
|
|
666
|
+
else:
|
|
667
|
+
out[key] = value
|
|
668
|
+
return out
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
__all__ = ["ADDRESS_ARGS", "MAX_READERS", "SCHEMA", "address_at", "bind", "declare", "delete",
|
|
672
|
+
"expand", "expand_for_item", "is_reference", "listing", "show", "store"]
|