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/core/project_read.py
ADDED
|
@@ -0,0 +1,1038 @@
|
|
|
1
|
+
"""Read-only reader of a recorded mdb project (``project.sqlite`` + saturn ``store/``).
|
|
2
|
+
|
|
3
|
+
Standard library, ``saturn`` and ``mdb.core`` only: no model, no framework, no write. This is
|
|
4
|
+
what ``mdb serve`` reads a project through. It opens SQLite strictly read-only and verifies every
|
|
5
|
+
row it returns against its seal and its session binding, the same checks the project writer's own
|
|
6
|
+
readers make, so a served value is never an unverified row.
|
|
7
|
+
|
|
8
|
+
Rows are verified one at a time. Every listing method takes ``refuse``: a callable
|
|
9
|
+
``refuse(kind, identifier, error)``. Without it the first bad row raises (strict, like the writer's
|
|
10
|
+
readers); with it a bad row is reported and skipped and the healthy rows are still returned. Cuts
|
|
11
|
+
and receipts are always strict: they are the session's execution history, and a session missing
|
|
12
|
+
part of it is refused as a whole by callers.
|
|
13
|
+
|
|
14
|
+
What is verified, per row:
|
|
15
|
+
|
|
16
|
+
* sessions: the row exists (``ValueError("unknown project session: ...")`` otherwise).
|
|
17
|
+
* cuts: the index manifest equals the store's sealed manifest (``LocalStore.inspect``), the
|
|
18
|
+
manifest is bound to the session's model identity and execution, and the stored execution point
|
|
19
|
+
and surface describe to the sealed ones.
|
|
20
|
+
* receipts: the body re-seals to its id and equals the stored receipt bytes.
|
|
21
|
+
* symbol bindings: ``SymbolBinding`` round-trip, fingerprint equals the row id, bound to the
|
|
22
|
+
session's model identity and execution digest.
|
|
23
|
+
* slices: seal equals the id, the session matches, the embedded graph snapshot verifies.
|
|
24
|
+
* legacy circuit records: ``mdb.core.records.verify_legacy`` plus kind, session, model identity
|
|
25
|
+
and execution.
|
|
26
|
+
* state annotations: the sealed index (schema, digest, session binding) and each object (bytes
|
|
27
|
+
digest, canonical bytes, body digest, id, qualified label, index summary, session binding;
|
|
28
|
+
no path outside the session directory, no symlink).
|
|
29
|
+
* symbol lifecycles: lifecycle seal (bounded canonical JSON), binding round-trip and fingerprint,
|
|
30
|
+
child occurrence/use seals and binding, session binding, the recorded receipt/consumer join of
|
|
31
|
+
every use and definition re-derived from verified cuts and receipts, and slice links resolved.
|
|
32
|
+
Not re-derived here (the lifecycle writer checks them when it records): clock witnesses,
|
|
33
|
+
invalidation clocks, location subsets and slot-metadata support of the binding.
|
|
34
|
+
* watch events: the event seal.
|
|
35
|
+
|
|
36
|
+
``session_graph`` returns the sealed session history graph (execution + knowledge) with the same
|
|
37
|
+
node, edge, event and snapshot identities the project writer's graph has for the same rows; a row
|
|
38
|
+
that cannot be placed (unreadable, or referring to a row that is not in the graph) is left out and
|
|
39
|
+
reported through ``refuse``.
|
|
40
|
+
"""
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import json
|
|
44
|
+
import math
|
|
45
|
+
import os
|
|
46
|
+
import sqlite3
|
|
47
|
+
from collections.abc import Callable, Mapping
|
|
48
|
+
from contextlib import contextmanager
|
|
49
|
+
from hashlib import sha256
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
|
|
52
|
+
from saturn.values import canonical, describe, digest
|
|
53
|
+
|
|
54
|
+
from . import graph_seal as gs
|
|
55
|
+
from .pointers import _sealed, _sha, check_bounded
|
|
56
|
+
|
|
57
|
+
Refuse = Callable[[str, str, BaseException], None]
|
|
58
|
+
|
|
59
|
+
LIFECYCLE_SCHEMA = "mdb-symbol-lifecycle-v1"
|
|
60
|
+
CIRCUIT_SCHEMA = "mdb-circuit-investigation-v1"
|
|
61
|
+
ANNOTATION_SCHEMA = "mdb-state-annotation-v1"
|
|
62
|
+
ANNOTATION_INDEX_SCHEMA = "mdb-state-annotation-index-v1"
|
|
63
|
+
READ_SCHEMA = "mdb-symbol-read-v2"
|
|
64
|
+
UNKNOWN_CAUSAL_LABEL = "unknown (observed only; no intervention)"
|
|
65
|
+
JOIN_FIELDS = frozenset({"definitions", "uses", "cuts", "receipts", "native_payload_reads",
|
|
66
|
+
"external_references", "authority", "causal_effect"})
|
|
67
|
+
COORDINATE_CLOCKS = frozenset({"execution-point", "token-position", "token", "depth",
|
|
68
|
+
"decoder-depth", "layer"})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ProjectReadError(ValueError):
|
|
72
|
+
"""A stored row does not verify, or the project cannot be opened read-only."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _strict(kind, identifier, error):
|
|
76
|
+
raise error
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# --------------------------------------------------------------------------- bounded JSON
|
|
80
|
+
|
|
81
|
+
_LC_DEPTH, _LC_ITEMS, _LC_STRING, _LC_TOTAL = 12, 512, 16 * 1024, 256 * 1024
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _lc_plain(value, depth=0):
|
|
85
|
+
"""The lifecycle record's bounded JSON normalisation (text keys, finite floats, limits)."""
|
|
86
|
+
if depth > _LC_DEPTH:
|
|
87
|
+
raise ProjectReadError("lifecycle exceeds metadata nesting limit")
|
|
88
|
+
if value is None or isinstance(value, (bool, int)):
|
|
89
|
+
return value
|
|
90
|
+
if isinstance(value, str):
|
|
91
|
+
if len(value.encode("utf-8")) > _LC_STRING:
|
|
92
|
+
raise ProjectReadError("lifecycle string is too large")
|
|
93
|
+
return value
|
|
94
|
+
if isinstance(value, float):
|
|
95
|
+
if not math.isfinite(value):
|
|
96
|
+
raise ProjectReadError("lifecycle contains a non-finite number")
|
|
97
|
+
return value
|
|
98
|
+
if isinstance(value, Mapping):
|
|
99
|
+
if len(value) > _LC_ITEMS:
|
|
100
|
+
raise ProjectReadError("lifecycle has too many metadata keys")
|
|
101
|
+
out = {}
|
|
102
|
+
for key, item in value.items():
|
|
103
|
+
if not isinstance(key, str) or not key.strip():
|
|
104
|
+
raise ProjectReadError("lifecycle contains a non-text key")
|
|
105
|
+
out[key] = _lc_plain(item, depth + 1)
|
|
106
|
+
return out
|
|
107
|
+
if isinstance(value, (list, tuple)):
|
|
108
|
+
if len(value) > _LC_ITEMS:
|
|
109
|
+
raise ProjectReadError("lifecycle has too many metadata items")
|
|
110
|
+
return [_lc_plain(item, depth + 1) for item in value]
|
|
111
|
+
raise ProjectReadError(f"lifecycle contains unsupported {type(value).__name__}")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def lifecycle_digest(value) -> str:
|
|
115
|
+
"""Seal digest of symbol lifecycle records (and their occurrences and uses)."""
|
|
116
|
+
encoded = json.dumps(_lc_plain(value), sort_keys=True, separators=(",", ":"),
|
|
117
|
+
ensure_ascii=False, allow_nan=False).encode("utf-8")
|
|
118
|
+
if len(encoded) > _LC_TOTAL:
|
|
119
|
+
raise ProjectReadError("lifecycle record exceeds the bounded metadata budget")
|
|
120
|
+
return sha256(encoded).hexdigest()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _sealed_child(value, label):
|
|
124
|
+
if not isinstance(value, Mapping):
|
|
125
|
+
raise ProjectReadError(f"{label} is not an object")
|
|
126
|
+
body = {k: v for k, v in value.items() if k != "fingerprint"}
|
|
127
|
+
if value.get("fingerprint") != lifecycle_digest(body):
|
|
128
|
+
raise ProjectReadError(f"{label} fingerprint mismatch")
|
|
129
|
+
return value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# Key order of the lifecycle writer's ``to_dict`` (stored rows are canonical, i.e. key-sorted).
|
|
133
|
+
# Readers that truncate by position (``bound_json``) depend on it; opaque mappings inside a
|
|
134
|
+
# record (metadata, readings, observations) keep their stored order, as the writer's do.
|
|
135
|
+
_LC_KEYS = ("schema", "symbol", "binding", "binding_fingerprint", "definitions", "uses",
|
|
136
|
+
"statuses", "invalidations", "claim_boundary", "authority", "metadata", "fingerprint")
|
|
137
|
+
_OCC_KEYS = ("schema", "occurrence_id", "binding_fingerprint", "binding", "session_id",
|
|
138
|
+
"source_cut", "result_cut", "branch", "execution", "receipt", "locations",
|
|
139
|
+
"location_set", "coalition", "location_sets", "clock", "spectral_address",
|
|
140
|
+
"vm_bundle", "cot_refs", "definition_refs", "evidence_refs", "status",
|
|
141
|
+
"validity_status", "validity_support", "authority", "metadata", "fingerprint")
|
|
142
|
+
_USE_KEYS = ("schema", "use_id", "binding_fingerprint", "session_id", "consumer", "source_cut",
|
|
143
|
+
"parent_cut", "result_cut", "branch", "execution", "receipt", "locations", "clock",
|
|
144
|
+
"signed_observations", "evidence_refs", "status", "validity_status",
|
|
145
|
+
"validity_support", "authority", "metadata", "fingerprint")
|
|
146
|
+
_CLOCK_KEYS = ("schema", "clock_id", "kind", "domain", "reading", "provenance",
|
|
147
|
+
"validity_status", "validity_support", "lifetime", "status", "metadata",
|
|
148
|
+
"fingerprint")
|
|
149
|
+
_INVALIDATION_KEYS = ("scope", "reason", "status", "evidence_refs", "clock", "metadata")
|
|
150
|
+
_LOCATION_KEYS = ("slot", "selector", "role", "execution_point", "state_schema")
|
|
151
|
+
_AUTHORITY_KEYS = ("write", "causal_effect")
|
|
152
|
+
_STATUS_KEYS = ("mechanics", "instrument", "trend", "terminal")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _ordered(value, keys, nested=None):
|
|
156
|
+
if not isinstance(value, dict):
|
|
157
|
+
return value
|
|
158
|
+
out = {k: value[k] for k in keys if k in value}
|
|
159
|
+
out.update({k: v for k, v in value.items() if k not in out})
|
|
160
|
+
for key, order in (nested or {}).items():
|
|
161
|
+
if key in out:
|
|
162
|
+
out[key] = order(out[key])
|
|
163
|
+
return out
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _ordered_binding(value):
|
|
167
|
+
from saturn.symbols import SymbolBinding
|
|
168
|
+
|
|
169
|
+
return value if not isinstance(value, dict) else SymbolBinding.from_dict(value).to_dict()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _ordered_clock(value):
|
|
173
|
+
return _ordered(value, _CLOCK_KEYS)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _locations(values):
|
|
177
|
+
return [_ordered(v, _LOCATION_KEYS) for v in values] if isinstance(values, list) else values
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _event_order(keys):
|
|
181
|
+
def order(value):
|
|
182
|
+
return _ordered(value, keys, {"binding": _ordered_binding, "locations": _locations,
|
|
183
|
+
"clock": _ordered_clock,
|
|
184
|
+
"authority": lambda a: _ordered(a, _AUTHORITY_KEYS)})
|
|
185
|
+
return order
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _lifecycle_order(body):
|
|
189
|
+
"""``body`` with the writer's key order (the content is unchanged)."""
|
|
190
|
+
def each(order):
|
|
191
|
+
return lambda rows: [order(r) for r in rows] if isinstance(rows, list) else rows
|
|
192
|
+
return _ordered(body, _LC_KEYS, {
|
|
193
|
+
"binding": _ordered_binding, "definitions": each(_event_order(_OCC_KEYS)),
|
|
194
|
+
"uses": each(_event_order(_USE_KEYS)),
|
|
195
|
+
"statuses": lambda s: _ordered(s, _STATUS_KEYS),
|
|
196
|
+
"invalidations": each(lambda i: _ordered(i, _INVALIDATION_KEYS,
|
|
197
|
+
{"clock": _ordered_clock})),
|
|
198
|
+
"authority": lambda a: _ordered(a, _AUTHORITY_KEYS)})
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _annotation_text(value, label):
|
|
202
|
+
if not isinstance(value, str) or not value.strip() or len(value) > 512 \
|
|
203
|
+
or any(ord(c) < 32 for c in value):
|
|
204
|
+
raise ProjectReadError(f"{label} must be short non-empty text")
|
|
205
|
+
return value.strip()
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _safe_path(root: Path, path: Path) -> Path:
|
|
209
|
+
if not path.is_absolute() or ".." in path.parts or not path.is_relative_to(root):
|
|
210
|
+
raise ProjectReadError("annotation path is outside the session root")
|
|
211
|
+
if path.resolve(strict=False) != path:
|
|
212
|
+
raise ProjectReadError("annotation path is outside the session root")
|
|
213
|
+
for candidate in (path, *path.parents):
|
|
214
|
+
if candidate == root:
|
|
215
|
+
break
|
|
216
|
+
if candidate.is_symlink():
|
|
217
|
+
raise ProjectReadError("annotation path traverses a symlink")
|
|
218
|
+
return path
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _receipt_id(value):
|
|
222
|
+
if value is not None and not isinstance(value, str):
|
|
223
|
+
raise ProjectReadError("native reference must be a string")
|
|
224
|
+
return value.removeprefix("cas://sha256/") if value else None
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# --------------------------------------------------------------------------- reader
|
|
228
|
+
|
|
229
|
+
class ProjectReader:
|
|
230
|
+
"""A recorded project opened read-only: every connection is ``mode=ro`` + ``query_only``.
|
|
231
|
+
|
|
232
|
+
* no ``-wal`` file next to the database: ``file:...?mode=ro&immutable=1`` (SQLite takes no
|
|
233
|
+
locks and creates no side file; the database is assumed not to change while read);
|
|
234
|
+
* a ``-wal`` file exists: ``mode=ro``, which needs a writable directory for SQLite's ``-shm``
|
|
235
|
+
wal-index; when the directory is not writable this raises ``ValueError`` at open.
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
read_only = True
|
|
239
|
+
|
|
240
|
+
def __init__(self, root):
|
|
241
|
+
self.root = Path(root).expanduser().resolve()
|
|
242
|
+
if (self.root / "project.sqlite-wal").exists() and not os.access(self.root, os.W_OK):
|
|
243
|
+
raise ValueError(
|
|
244
|
+
f"{self.root} is a WAL-mode project (it has a project.sqlite-wal file) in a "
|
|
245
|
+
"directory that is not writable; SQLite needs to create its -shm wal-index there "
|
|
246
|
+
"to read it. Make the directory writable, or serve a rollback-journal copy of the "
|
|
247
|
+
"project (sqlite3 project.sqlite 'PRAGMA journal_mode=DELETE').")
|
|
248
|
+
if not (self.root / "project.sqlite").is_file() or not (self.root / "store").is_dir():
|
|
249
|
+
raise ValueError("read-only project requires an existing index and store")
|
|
250
|
+
from saturn.store import LocalStore
|
|
251
|
+
|
|
252
|
+
self.store = LocalStore(self.root / "store")
|
|
253
|
+
with self._db() as db:
|
|
254
|
+
if db.execute("PRAGMA user_version").fetchone()[0] != 3:
|
|
255
|
+
raise ValueError("read-only project requires schema 3; migrate a writable copy first")
|
|
256
|
+
|
|
257
|
+
@contextmanager
|
|
258
|
+
def _db(self):
|
|
259
|
+
path = self.root / "project.sqlite"
|
|
260
|
+
mode = "mode=ro" if path.with_name(path.name + "-wal").exists() else "mode=ro&immutable=1"
|
|
261
|
+
db = sqlite3.connect(path.as_uri() + "?" + mode, uri=True, timeout=30)
|
|
262
|
+
db.row_factory = sqlite3.Row
|
|
263
|
+
try:
|
|
264
|
+
db.execute("PRAGMA query_only=ON")
|
|
265
|
+
with db:
|
|
266
|
+
yield db
|
|
267
|
+
finally:
|
|
268
|
+
db.close()
|
|
269
|
+
|
|
270
|
+
@staticmethod
|
|
271
|
+
def _json(value):
|
|
272
|
+
return canonical(value).decode("utf-8")
|
|
273
|
+
|
|
274
|
+
def _tables(self, db):
|
|
275
|
+
return {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
|
276
|
+
|
|
277
|
+
# ----------------------------------------------------------------------- sessions and cuts
|
|
278
|
+
|
|
279
|
+
def sessions(self):
|
|
280
|
+
"""Session ids (one corrupt session row never hides the others)."""
|
|
281
|
+
with self._db() as db:
|
|
282
|
+
return [row["id"] for row in db.execute("SELECT id FROM sessions ORDER BY id")]
|
|
283
|
+
|
|
284
|
+
def session(self, sid):
|
|
285
|
+
with self._db() as db:
|
|
286
|
+
row = db.execute("SELECT * FROM sessions WHERE id=?", (sid,)).fetchone()
|
|
287
|
+
if row is None:
|
|
288
|
+
raise ValueError(f"unknown project session: {sid}")
|
|
289
|
+
return dict(row)
|
|
290
|
+
|
|
291
|
+
def _binding(self, sid):
|
|
292
|
+
row = self.session(sid)
|
|
293
|
+
return json.loads(row["identity"]), json.loads(row["execution"])
|
|
294
|
+
|
|
295
|
+
def cut_ids(self, sid):
|
|
296
|
+
self.session(sid)
|
|
297
|
+
with self._db() as db:
|
|
298
|
+
return [r[0] for r in db.execute(
|
|
299
|
+
"SELECT id FROM cuts WHERE session_id=? ORDER BY rowid", (sid,))]
|
|
300
|
+
|
|
301
|
+
def cut_descriptor(self, sid, cut_id):
|
|
302
|
+
"""Verified native cut metadata (no tensor page is read)."""
|
|
303
|
+
with self._db() as db:
|
|
304
|
+
row = db.execute("SELECT manifest FROM cuts WHERE session_id=? AND id=?",
|
|
305
|
+
(sid, cut_id)).fetchone()
|
|
306
|
+
if row is None:
|
|
307
|
+
raise ValueError("cut is not retained in this project session")
|
|
308
|
+
manifest = self.store.inspect(cut_id)
|
|
309
|
+
if self._json(manifest) != row[0]:
|
|
310
|
+
raise ValueError("project cut index differs from native cut")
|
|
311
|
+
identity, execution = self._binding(sid)
|
|
312
|
+
if manifest["model_identity"] != identity or manifest["execution"] != execution:
|
|
313
|
+
raise ValueError("native cut differs from the project session binding")
|
|
314
|
+
metadata = json.loads((self.store.root / "cuts" / f"{cut_id}.json").read_bytes())
|
|
315
|
+
point = metadata.get("execution_point")
|
|
316
|
+
if describe(point) != manifest.get("execution_point"):
|
|
317
|
+
raise ValueError("native execution point differs from its sealed manifest")
|
|
318
|
+
surface = metadata.get("surface")
|
|
319
|
+
if (None if surface is None else describe(surface)) != manifest.get("surface"):
|
|
320
|
+
raise ValueError("native surface differs from its sealed manifest")
|
|
321
|
+
return {"fingerprint": cut_id, "manifest": manifest,
|
|
322
|
+
"model_identity": manifest["model_identity"], "parent": manifest["parent"],
|
|
323
|
+
"boundary": manifest["boundary"], "execution_point": point or {},
|
|
324
|
+
"surface": surface or {}}
|
|
325
|
+
|
|
326
|
+
def receipts(self, sid):
|
|
327
|
+
"""Verified native receipts as dicts (``Receipt.to_dict()``), insertion order."""
|
|
328
|
+
from saturn.core import Receipt
|
|
329
|
+
|
|
330
|
+
self.session(sid)
|
|
331
|
+
with self._db() as db:
|
|
332
|
+
rows = list(db.execute(
|
|
333
|
+
"SELECT id, body FROM receipts WHERE session_id=? ORDER BY rowid", (sid,)))
|
|
334
|
+
out = []
|
|
335
|
+
for row in rows:
|
|
336
|
+
data = json.loads(row["body"])
|
|
337
|
+
fingerprint = data.pop("fingerprint")
|
|
338
|
+
receipt = Receipt(canonical(data))
|
|
339
|
+
if receipt.fingerprint != fingerprint or fingerprint != row["id"]:
|
|
340
|
+
raise ValueError("project receipt seal changed")
|
|
341
|
+
raw = (self.store.root / "receipts" / f"{fingerprint}.json").read_bytes()
|
|
342
|
+
if raw != canonical(receipt.to_dict()):
|
|
343
|
+
raise ValueError("native receipt bytes differ from the project index")
|
|
344
|
+
out.append(receipt.to_dict())
|
|
345
|
+
return out
|
|
346
|
+
|
|
347
|
+
def tensor_info(self, ref):
|
|
348
|
+
"""Shape/dtype of a stored tensor (verified descriptor; no tensor is built)."""
|
|
349
|
+
return self.store.tensor_info(ref)
|
|
350
|
+
|
|
351
|
+
# ----------------------------------------------------------------------- symbols and slices
|
|
352
|
+
|
|
353
|
+
def _symbol(self, sid, identifier, body, identity, execution):
|
|
354
|
+
from saturn.symbols import SymbolBinding
|
|
355
|
+
|
|
356
|
+
value = SymbolBinding.from_dict(json.loads(body)).to_dict()
|
|
357
|
+
if value["fingerprint"] != identifier:
|
|
358
|
+
raise ValueError("project symbol index differs from its seal")
|
|
359
|
+
if value["model_identity"] != identity or value["execution"] != digest(execution):
|
|
360
|
+
raise ValueError("project symbol differs from its session binding")
|
|
361
|
+
return value
|
|
362
|
+
|
|
363
|
+
def symbols(self, sid, *, refuse: Refuse = _strict):
|
|
364
|
+
"""Verified symbol bindings (``SymbolBinding.to_dict()``), insertion order."""
|
|
365
|
+
identity, execution = self._binding(sid)
|
|
366
|
+
with self._db() as db:
|
|
367
|
+
rows = db.execute("SELECT id, body FROM symbols WHERE session_id=? ORDER BY rowid",
|
|
368
|
+
(sid,)).fetchall()
|
|
369
|
+
out = []
|
|
370
|
+
for row in rows:
|
|
371
|
+
try:
|
|
372
|
+
out.append(self._symbol(sid, row["id"], row["body"], identity, execution))
|
|
373
|
+
except (ValueError, KeyError, TypeError, AttributeError, RecursionError) as error:
|
|
374
|
+
refuse("symbol", str(row["id"]), error)
|
|
375
|
+
return out
|
|
376
|
+
|
|
377
|
+
def slice_ids(self, sid):
|
|
378
|
+
self.session(sid)
|
|
379
|
+
with self._db() as db:
|
|
380
|
+
return [r[0] for r in db.execute(
|
|
381
|
+
"SELECT id FROM slices WHERE session_id=? ORDER BY rowid", (sid,))]
|
|
382
|
+
|
|
383
|
+
def slice_record(self, sid, identifier):
|
|
384
|
+
self.session(sid)
|
|
385
|
+
with self._db() as db:
|
|
386
|
+
row = db.execute("SELECT body FROM slices WHERE session_id=? AND id=?",
|
|
387
|
+
(sid, identifier)).fetchone()
|
|
388
|
+
if row is None:
|
|
389
|
+
raise ValueError("slice is not retained in this project session")
|
|
390
|
+
body = json.loads(row[0])
|
|
391
|
+
if not isinstance(body, dict) or digest(body) != identifier \
|
|
392
|
+
or body.get("session_id") != sid:
|
|
393
|
+
raise ValueError("project slice seal changed")
|
|
394
|
+
gs.verify_snapshot(body.get("graph"))
|
|
395
|
+
return {"slice_id": identifier, **body}
|
|
396
|
+
|
|
397
|
+
def slices(self, sid, *, refuse: Refuse = _strict):
|
|
398
|
+
out = []
|
|
399
|
+
for identifier in self.slice_ids(sid):
|
|
400
|
+
try:
|
|
401
|
+
out.append(self.slice_record(sid, identifier))
|
|
402
|
+
except (ValueError, KeyError, TypeError, AttributeError, RecursionError) as error:
|
|
403
|
+
refuse("slice", str(identifier), error)
|
|
404
|
+
return out
|
|
405
|
+
|
|
406
|
+
# ----------------------------------------------------------------------- circuit records
|
|
407
|
+
|
|
408
|
+
def circuit_records(self, sid, *, refuse: Refuse = _strict):
|
|
409
|
+
"""Verified legacy ``circuit_records`` rows ``{record_id, **body}``, insertion order."""
|
|
410
|
+
from .records import verify_legacy
|
|
411
|
+
|
|
412
|
+
identity, execution = self._binding(sid)
|
|
413
|
+
with self._db() as db:
|
|
414
|
+
if "circuit_records" not in self._tables(db):
|
|
415
|
+
return []
|
|
416
|
+
rows = db.execute("SELECT id, kind, body FROM circuit_records WHERE session_id=? "
|
|
417
|
+
"ORDER BY rowid", (sid,)).fetchall()
|
|
418
|
+
out = []
|
|
419
|
+
for row in rows:
|
|
420
|
+
try:
|
|
421
|
+
body = json.loads(row["body"])
|
|
422
|
+
value = verify_legacy(body, row["id"])
|
|
423
|
+
if (body.get("schema") != CIRCUIT_SCHEMA or body.get("session_id") != sid
|
|
424
|
+
or body.get("kind") != row["kind"]
|
|
425
|
+
or body.get("model_identity") != identity
|
|
426
|
+
or body.get("execution") != execution):
|
|
427
|
+
raise ProjectReadError("circuit record seal or session binding changed")
|
|
428
|
+
out.append(value)
|
|
429
|
+
except (ValueError, KeyError, TypeError, AttributeError, RecursionError) as error:
|
|
430
|
+
refuse("circuit-record", str(row["id"]), error)
|
|
431
|
+
return out
|
|
432
|
+
|
|
433
|
+
# ----------------------------------------------------------------------- annotations
|
|
434
|
+
|
|
435
|
+
def _annotation_binding(self, sid):
|
|
436
|
+
identity, execution = self._binding(sid)
|
|
437
|
+
return {"session_id": sid, "family": "saturn-pub", "lane": "public-session",
|
|
438
|
+
"model_identity_sha256": digest({"model_id": identity, "execution": execution}),
|
|
439
|
+
"publication_mode": "project"}
|
|
440
|
+
|
|
441
|
+
def _annotation_index(self, sid):
|
|
442
|
+
"""``(session root, session binding, index entries)`` of the state-annotation sidecar."""
|
|
443
|
+
root = (self.root / "sessions" / digest(sid)).resolve()
|
|
444
|
+
binding = self._annotation_binding(sid)
|
|
445
|
+
sidecar = _safe_path(root, root / "state-annotations")
|
|
446
|
+
index_path = _safe_path(root, sidecar / "index.json")
|
|
447
|
+
objects = _safe_path(root, sidecar / "objects")
|
|
448
|
+
if sidecar.is_symlink() or objects.is_symlink():
|
|
449
|
+
raise ProjectReadError("annotation namespace cannot be a symlink")
|
|
450
|
+
if not index_path.exists():
|
|
451
|
+
return root, binding, []
|
|
452
|
+
if index_path.is_symlink():
|
|
453
|
+
raise ProjectReadError("annotation index cannot be a symlink")
|
|
454
|
+
try:
|
|
455
|
+
index = json.loads(index_path.read_bytes())
|
|
456
|
+
except (OSError, ValueError, UnicodeDecodeError) as error:
|
|
457
|
+
raise ProjectReadError("annotation index is unreadable") from error
|
|
458
|
+
if not isinstance(index, dict) or set(index) != {
|
|
459
|
+
"schema", "session_binding", "entries", "content_sha256"}:
|
|
460
|
+
raise ProjectReadError("annotation index shape is invalid")
|
|
461
|
+
body = {k: v for k, v in index.items() if k != "content_sha256"}
|
|
462
|
+
if index["schema"] != ANNOTATION_INDEX_SCHEMA or index["content_sha256"] != gs.digest(body):
|
|
463
|
+
raise ProjectReadError("annotation index seal changed")
|
|
464
|
+
if index["session_binding"] != binding:
|
|
465
|
+
raise ProjectReadError("annotation index session binding changed")
|
|
466
|
+
if not isinstance(index["entries"], list) or any(
|
|
467
|
+
not isinstance(e, Mapping) for e in index["entries"]):
|
|
468
|
+
raise ProjectReadError("annotation index entries are invalid")
|
|
469
|
+
return root, binding, index["entries"]
|
|
470
|
+
|
|
471
|
+
@staticmethod
|
|
472
|
+
def _annotation(root, binding, entry):
|
|
473
|
+
path = _safe_path(root, root / _annotation_text(entry.get("object_path"),
|
|
474
|
+
"annotation object path"))
|
|
475
|
+
if path.is_symlink():
|
|
476
|
+
raise ProjectReadError("annotation object cannot be a symlink")
|
|
477
|
+
try:
|
|
478
|
+
raw = path.read_bytes()
|
|
479
|
+
annotation = json.loads(raw)
|
|
480
|
+
except (OSError, ValueError, UnicodeDecodeError) as error:
|
|
481
|
+
raise ProjectReadError("annotation object is unreadable") from error
|
|
482
|
+
if not isinstance(annotation, dict):
|
|
483
|
+
raise ProjectReadError("annotation object is not an object")
|
|
484
|
+
if sha256(raw).hexdigest() != entry.get("object_sha256") or gs.canonical(annotation) != raw:
|
|
485
|
+
raise ProjectReadError("annotation object bytes changed")
|
|
486
|
+
payload = {k: v for k, v in annotation.items()
|
|
487
|
+
if k not in {"annotation_id", "qualified_label", "body_sha256"}}
|
|
488
|
+
body_sha256 = gs.digest(payload)
|
|
489
|
+
expected_id = f"state-annotation://sha256/{body_sha256}"
|
|
490
|
+
expected_label = f"{payload['namespace']}::{payload['label']}@sha256:{body_sha256}"
|
|
491
|
+
if (annotation.get("schema") != ANNOTATION_SCHEMA
|
|
492
|
+
or annotation.get("body_sha256") != body_sha256
|
|
493
|
+
or annotation.get("annotation_id") != expected_id
|
|
494
|
+
or annotation.get("qualified_label") != expected_label
|
|
495
|
+
or entry.get("annotation_id") != expected_id
|
|
496
|
+
or entry.get("qualified_label") != expected_label
|
|
497
|
+
or entry.get("body_sha256") != body_sha256):
|
|
498
|
+
raise ProjectReadError("annotation object seal changed")
|
|
499
|
+
expected_entry = {
|
|
500
|
+
"annotation_id": annotation["annotation_id"],
|
|
501
|
+
"qualified_label": annotation["qualified_label"], "label": annotation["label"],
|
|
502
|
+
"namespace": annotation["namespace"], "cut_id": annotation["cut_id"],
|
|
503
|
+
"role": annotation["role"], "stage": annotation["stage"], "tags": annotation["tags"],
|
|
504
|
+
"body_sha256": annotation["body_sha256"], "object_sha256": sha256(raw).hexdigest(),
|
|
505
|
+
"object_path": path.relative_to(root).as_posix()}
|
|
506
|
+
if dict(entry) != expected_entry:
|
|
507
|
+
raise ProjectReadError("annotation index summary differs from its sealed object")
|
|
508
|
+
if annotation.get("session_binding") != binding:
|
|
509
|
+
raise ProjectReadError("annotation object session binding changed")
|
|
510
|
+
return annotation
|
|
511
|
+
|
|
512
|
+
def annotations(self, sid, *, tag=None, refuse: Refuse = _strict):
|
|
513
|
+
"""``(index entry, verified annotation)`` pairs in index order (optionally one tag)."""
|
|
514
|
+
try:
|
|
515
|
+
root, binding, entries = self._annotation_index(sid)
|
|
516
|
+
except (ValueError, OSError) as error:
|
|
517
|
+
refuse("annotation", "index", error)
|
|
518
|
+
return []
|
|
519
|
+
out = []
|
|
520
|
+
for entry in entries:
|
|
521
|
+
ident = str(entry.get("annotation_id") or entry.get("qualified_label") or "?")
|
|
522
|
+
try:
|
|
523
|
+
if tag is not None and tag not in entry.get("tags", []):
|
|
524
|
+
continue
|
|
525
|
+
out.append((dict(entry), self._annotation(root, binding, entry)))
|
|
526
|
+
except (ValueError, KeyError, TypeError, AttributeError, OSError,
|
|
527
|
+
RecursionError) as error:
|
|
528
|
+
refuse("annotation", ident, error)
|
|
529
|
+
return out
|
|
530
|
+
|
|
531
|
+
def findings(self, sid, *, refuse: Refuse = _strict):
|
|
532
|
+
"""Annotations tagged ``finding`` (verified objects), index order."""
|
|
533
|
+
return [annotation for _, annotation in self.annotations(
|
|
534
|
+
sid, tag="finding", refuse=lambda kind, ident, error: refuse("finding", ident, error))]
|
|
535
|
+
|
|
536
|
+
# ----------------------------------------------------------------------- watch events
|
|
537
|
+
|
|
538
|
+
def watch_events(self, sid, *, refuse: Refuse = _strict):
|
|
539
|
+
info = json.loads(self.session(sid)["debug_info"])
|
|
540
|
+
events = info.get("watch_events", []) if isinstance(info, dict) else []
|
|
541
|
+
if not isinstance(events, list):
|
|
542
|
+
refuse("watch-event", "watch_events", ProjectReadError("watch_events is not a list"))
|
|
543
|
+
return []
|
|
544
|
+
out = []
|
|
545
|
+
for position, event in enumerate(events):
|
|
546
|
+
try:
|
|
547
|
+
if not isinstance(event, dict):
|
|
548
|
+
raise ProjectReadError("watch event is not an object")
|
|
549
|
+
body = {k: v for k, v in event.items()
|
|
550
|
+
if k not in {"fingerprint", "boundary", "authority"}}
|
|
551
|
+
if digest(body) != event["fingerprint"]:
|
|
552
|
+
raise ProjectReadError("project watch event seal changed")
|
|
553
|
+
out.append(event)
|
|
554
|
+
except (ValueError, KeyError, TypeError, RecursionError) as error:
|
|
555
|
+
ident = event.get("fingerprint") if isinstance(event, dict) else None
|
|
556
|
+
refuse("watch-event", str(ident or position), error)
|
|
557
|
+
return out
|
|
558
|
+
|
|
559
|
+
# ----------------------------------------------------------------------- symbol lifecycles
|
|
560
|
+
|
|
561
|
+
def symbol_lifecycles(self, sid, *, refuse: Refuse = _strict):
|
|
562
|
+
"""Verified lifecycle rows ``{lifecycle_id, lifecycle, joins}``, insertion order."""
|
|
563
|
+
self.session(sid)
|
|
564
|
+
with self._db() as db:
|
|
565
|
+
if "symbol_lifecycles" not in self._tables(db):
|
|
566
|
+
return []
|
|
567
|
+
rows = db.execute("SELECT id, body, joins FROM symbol_lifecycles WHERE session_id=? "
|
|
568
|
+
"ORDER BY rowid", (sid,)).fetchall()
|
|
569
|
+
context = {}
|
|
570
|
+
out = []
|
|
571
|
+
for row in rows:
|
|
572
|
+
try:
|
|
573
|
+
out.append(self._lifecycle(sid, row["id"], row["body"], row["joins"], context))
|
|
574
|
+
except (ValueError, KeyError, TypeError, AttributeError, OSError,
|
|
575
|
+
RecursionError) as error:
|
|
576
|
+
refuse("lifecycle", str(row["id"]), error)
|
|
577
|
+
return out
|
|
578
|
+
|
|
579
|
+
def _lifecycle(self, sid, identifier, body_text, joins_text, context):
|
|
580
|
+
from saturn.symbols import SymbolBinding
|
|
581
|
+
|
|
582
|
+
body = json.loads(body_text)
|
|
583
|
+
if not isinstance(body, dict) or body.get("schema") != LIFECYCLE_SCHEMA:
|
|
584
|
+
raise ProjectReadError("unsupported symbol lifecycle schema")
|
|
585
|
+
if body.get("fingerprint") != lifecycle_digest(
|
|
586
|
+
{k: v for k, v in body.items() if k != "fingerprint"}) \
|
|
587
|
+
or body["fingerprint"] != identifier:
|
|
588
|
+
raise ProjectReadError("symbol lifecycle index differs from its seal")
|
|
589
|
+
binding = body.get("binding")
|
|
590
|
+
if not isinstance(binding, dict) or SymbolBinding.from_dict(binding).to_dict() != binding:
|
|
591
|
+
raise ProjectReadError("lifecycle binding does not round-trip")
|
|
592
|
+
binding_fp = binding["fingerprint"]
|
|
593
|
+
if body.get("binding_fingerprint") != binding_fp or binding["symbol"] != body.get("symbol"):
|
|
594
|
+
raise ProjectReadError("lifecycle binding fingerprint mismatch")
|
|
595
|
+
identity, execution = self._binding(sid)
|
|
596
|
+
if binding["model_identity"] != identity or binding["execution"] != digest(execution):
|
|
597
|
+
raise ProjectReadError("lifecycle belongs to another model or execution")
|
|
598
|
+
definitions = body.get("definitions") or []
|
|
599
|
+
uses = body.get("uses") or []
|
|
600
|
+
if not isinstance(definitions, list) or not isinstance(uses, list):
|
|
601
|
+
raise ProjectReadError("lifecycle events are not lists")
|
|
602
|
+
ids = []
|
|
603
|
+
for row in definitions:
|
|
604
|
+
_sealed_child(row, "symbol occurrence")
|
|
605
|
+
ids.append(row.get("occurrence_id"))
|
|
606
|
+
for row in uses:
|
|
607
|
+
_sealed_child(row, "symbol use")
|
|
608
|
+
ids.append(row.get("use_id"))
|
|
609
|
+
if len(ids) != len(set(map(str, ids))):
|
|
610
|
+
raise ProjectReadError("lifecycle occurrence/use IDs must be unique")
|
|
611
|
+
for row in (*definitions, *uses):
|
|
612
|
+
if row.get("binding_fingerprint") != binding_fp:
|
|
613
|
+
raise ProjectReadError("lifecycle record belongs to another binding")
|
|
614
|
+
if row.get("session_id") != sid:
|
|
615
|
+
raise ProjectReadError("lifecycle event belongs to another project session")
|
|
616
|
+
if row.get("execution") is not None and row["execution"] != binding["execution"]:
|
|
617
|
+
raise ProjectReadError("symbol event execution changed")
|
|
618
|
+
recorded = json.loads(joins_text)
|
|
619
|
+
if not isinstance(recorded, dict) or set(recorded) != JOIN_FIELDS:
|
|
620
|
+
raise ProjectReadError("lifecycle join contains unsupported fields")
|
|
621
|
+
joins = self._joins(sid, body, binding, definitions, uses, context)
|
|
622
|
+
self._check_joins(sid, recorded, joins, binding_fp)
|
|
623
|
+
return {"lifecycle_id": identifier, "lifecycle": _lifecycle_order(body),
|
|
624
|
+
"joins": recorded}
|
|
625
|
+
|
|
626
|
+
def _joins(self, sid, body, binding, definitions, uses, context):
|
|
627
|
+
"""Re-derive the receipt/consumer join of every recorded event from verified rows."""
|
|
628
|
+
if "receipts" not in context:
|
|
629
|
+
context["receipts"] = {r["fingerprint"]: r for r in self.receipts(sid)}
|
|
630
|
+
context["cuts"] = {}
|
|
631
|
+
native_receipts, cut_cache = context["receipts"], context["cuts"]
|
|
632
|
+
cuts, receipts = set(), {}
|
|
633
|
+
|
|
634
|
+
def cut(identifier):
|
|
635
|
+
if not isinstance(identifier, str):
|
|
636
|
+
raise ProjectReadError("event cut reference must be a string")
|
|
637
|
+
if identifier not in cut_cache:
|
|
638
|
+
cut_cache[identifier] = self.cut_descriptor(sid, identifier)
|
|
639
|
+
cuts.add(identifier)
|
|
640
|
+
return cut_cache[identifier]
|
|
641
|
+
|
|
642
|
+
def receipt(row, is_use):
|
|
643
|
+
ident = _receipt_id(row.get("receipt"))
|
|
644
|
+
if ident is None:
|
|
645
|
+
return None
|
|
646
|
+
if ident not in native_receipts:
|
|
647
|
+
raise ProjectReadError("lifecycle receipt is not retained in this session")
|
|
648
|
+
native = native_receipts[ident]
|
|
649
|
+
if (native.get("model_identity") != binding["model_identity"]
|
|
650
|
+
or digest(native.get("execution")) != binding["execution"]):
|
|
651
|
+
raise ProjectReadError("native receipt belongs to another model or execution")
|
|
652
|
+
if native.get("status") == "refused":
|
|
653
|
+
raise ProjectReadError("refused receipt cannot describe a completed symbol event")
|
|
654
|
+
referenced = {native.get(k) for k in ("parent", "result", "candidate")} - {None}
|
|
655
|
+
if row.get("result_cut") and row["result_cut"] != native.get("result"):
|
|
656
|
+
raise ProjectReadError("symbol result cut differs from its native receipt")
|
|
657
|
+
if row.get("parent_cut") and row["parent_cut"] != native.get("parent"):
|
|
658
|
+
raise ProjectReadError("symbol parent cut differs from its native receipt")
|
|
659
|
+
if row.get("source_cut") and row["source_cut"] not in referenced and not is_use:
|
|
660
|
+
raise ProjectReadError("definition cut is not referenced by its native receipt")
|
|
661
|
+
receipts[ident] = native
|
|
662
|
+
return ident
|
|
663
|
+
|
|
664
|
+
for row in (*definitions, *uses):
|
|
665
|
+
for key in ("source_cut", "result_cut", "parent_cut"):
|
|
666
|
+
if row.get(key):
|
|
667
|
+
cut(row[key])
|
|
668
|
+
for invalidation in body.get("invalidations") or []:
|
|
669
|
+
clock = invalidation.get("clock") if isinstance(invalidation, Mapping) else None
|
|
670
|
+
if isinstance(clock, Mapping):
|
|
671
|
+
source = _receipt_id(clock.get("metadata", {}).get("source_cut"))
|
|
672
|
+
if source is not None:
|
|
673
|
+
cut(source)
|
|
674
|
+
out_definitions, out_uses = [], []
|
|
675
|
+
for row in definitions:
|
|
676
|
+
cut(row.get("source_cut"))
|
|
677
|
+
if not row.get("locations"):
|
|
678
|
+
raise ProjectReadError("definition has no locations in the qualified binding")
|
|
679
|
+
item ={"occurrence": row.get("occurrence_id"), "source_cut": row.get("source_cut"),
|
|
680
|
+
"receipt": receipt(row, False), "support": "metadata-support-verified",
|
|
681
|
+
"slice_basis": "full-root-binding-declared-dataflow"}
|
|
682
|
+
spectral = row.get("spectral_address")
|
|
683
|
+
if spectral:
|
|
684
|
+
if "canonical_key" in spectral:
|
|
685
|
+
if spectral["canonical_key"]["symbol_id"] != body["symbol"]:
|
|
686
|
+
raise ProjectReadError("spectral symbol differs from the binding")
|
|
687
|
+
item["spectral_support"] = ("typed-identity-verified; "
|
|
688
|
+
"supplied-native-association")
|
|
689
|
+
else:
|
|
690
|
+
item["spectral_support"] = "opaque-unjoined-reference"
|
|
691
|
+
bundle = row.get("vm_bundle")
|
|
692
|
+
if bundle:
|
|
693
|
+
if "schema" in bundle:
|
|
694
|
+
expected = (("model_identity", "id", binding["model_identity"]),
|
|
695
|
+
("abi_identity", "execution", binding["execution"]),
|
|
696
|
+
("input_identity", "source_cut", row.get("source_cut")),
|
|
697
|
+
("input_identity", "context", binding.get("context")))
|
|
698
|
+
for part, name, value in expected:
|
|
699
|
+
if name in bundle[part] and bundle[part][name] != value:
|
|
700
|
+
raise ProjectReadError("VM bundle differs from the native source")
|
|
701
|
+
exact = (bundle["model_identity"] == {"id": binding["model_identity"]}
|
|
702
|
+
and bundle["abi_identity"].get("execution") == binding["execution"]
|
|
703
|
+
and bundle["input_identity"].get("source_cut") == row.get("source_cut")
|
|
704
|
+
and bundle["input_identity"].get("context") == binding.get("context"))
|
|
705
|
+
item["vm_support"] = ("native-source-metadata-matched" if exact else
|
|
706
|
+
"bundle-seal-verified; source-association-unverified")
|
|
707
|
+
else:
|
|
708
|
+
item["vm_support"] = "opaque-unjoined-reference"
|
|
709
|
+
out_definitions.append(item)
|
|
710
|
+
for row in uses:
|
|
711
|
+
if row.get("source_cut"):
|
|
712
|
+
cut(row["source_cut"])
|
|
713
|
+
receipt_id = receipt(row, True)
|
|
714
|
+
closed = bool(receipt_id and row.get("parent_cut") and row.get("result_cut"))
|
|
715
|
+
if receipt_id and not closed and row.get("status") in {"observed", "validated"}:
|
|
716
|
+
raise ProjectReadError("observed symbol use requires receipt parent/result closure")
|
|
717
|
+
declared = set()
|
|
718
|
+
for key in ("parent_cut", "result_cut"):
|
|
719
|
+
if row.get(key):
|
|
720
|
+
consumer = cut(row[key])["surface"].get("consumer")
|
|
721
|
+
if consumer:
|
|
722
|
+
declared.add(consumer)
|
|
723
|
+
if closed:
|
|
724
|
+
for step in receipts[receipt_id].get("transitions", []):
|
|
725
|
+
consumer = step.get("native_operation", {}).get("consumer")
|
|
726
|
+
if consumer:
|
|
727
|
+
declared.add(consumer)
|
|
728
|
+
if declared and row.get("consumer") not in declared:
|
|
729
|
+
raise ProjectReadError("symbol consumer differs from the native contract")
|
|
730
|
+
out_uses.append({
|
|
731
|
+
"use": row.get("use_id"), "source_cut": row.get("source_cut"),
|
|
732
|
+
"result_cut": row.get("result_cut"), "receipt": receipt_id,
|
|
733
|
+
"consumer": row.get("consumer"),
|
|
734
|
+
"consumer_support": ("native-contract-matched" if declared and closed
|
|
735
|
+
else "unverified-label"),
|
|
736
|
+
"receipt_closure": "native-parent-result-matched" if closed else "incomplete",
|
|
737
|
+
"support": "recorded-consumer-association"})
|
|
738
|
+
return {"definitions": out_definitions, "uses": out_uses, "cuts": sorted(cuts),
|
|
739
|
+
"receipts": sorted(receipts), "native_payload_reads": 0,
|
|
740
|
+
"external_references": ("retained descriptors; external payload availability "
|
|
741
|
+
"unverified"),
|
|
742
|
+
"authority": "read-only-evidence-index", "causal_effect": "not-established"}
|
|
743
|
+
|
|
744
|
+
def _check_joins(self, sid, recorded, joins, binding_fp):
|
|
745
|
+
if not isinstance(recorded["definitions"], list) or not isinstance(recorded["uses"], list):
|
|
746
|
+
raise ProjectReadError("lifecycle join changed")
|
|
747
|
+
for definition in recorded["definitions"]:
|
|
748
|
+
if not isinstance(definition, dict):
|
|
749
|
+
raise ProjectReadError("lifecycle definition join changed")
|
|
750
|
+
if definition.get("slice_id"):
|
|
751
|
+
sliced = self.slice_record(sid, definition["slice_id"])
|
|
752
|
+
if (sliced["cut_id"] != definition["source_cut"]
|
|
753
|
+
or sliced["symbol_binding"]["fingerprint"] != binding_fp
|
|
754
|
+
or sliced["complete"] != definition.get("slice_complete")
|
|
755
|
+
or sliced["scope"] != definition.get("slice_scope")):
|
|
756
|
+
raise ProjectReadError("lifecycle slice differs from its native source")
|
|
757
|
+
stripped = [{k: v for k, v in row.items()
|
|
758
|
+
if k not in {"slice_id", "slice_complete", "slice_scope"}}
|
|
759
|
+
for row in recorded["definitions"]]
|
|
760
|
+
if len(stripped) != len(joins["definitions"]):
|
|
761
|
+
raise ProjectReadError("lifecycle definition join changed")
|
|
762
|
+
expected = [current if "slice_basis" in saved else
|
|
763
|
+
{k: v for k, v in current.items() if k != "slice_basis"}
|
|
764
|
+
for saved, current in zip(stripped, joins["definitions"])]
|
|
765
|
+
if stripped != expected:
|
|
766
|
+
raise ProjectReadError("lifecycle definition join changed")
|
|
767
|
+
if len(recorded["uses"]) != len(joins["uses"]):
|
|
768
|
+
raise ProjectReadError("lifecycle use join changed")
|
|
769
|
+
expected = [current if isinstance(saved, dict) and "receipt_closure" in saved else
|
|
770
|
+
{k: v for k, v in current.items() if k != "receipt_closure"}
|
|
771
|
+
for saved, current in zip(recorded["uses"], joins["uses"])]
|
|
772
|
+
if recorded["uses"] != expected:
|
|
773
|
+
raise ProjectReadError("lifecycle use join changed")
|
|
774
|
+
for field in JOIN_FIELDS - {"definitions", "uses"}:
|
|
775
|
+
if joins[field] != recorded[field]:
|
|
776
|
+
raise ProjectReadError("lifecycle native reference join changed")
|
|
777
|
+
|
|
778
|
+
# ----------------------------------------------------------------------- session graph
|
|
779
|
+
|
|
780
|
+
def session_graph(self, sid, *, refuse: Refuse = _strict):
|
|
781
|
+
"""The sealed session history graph (snapshot dict), built from verified rows only.
|
|
782
|
+
|
|
783
|
+
Order and identities follow the project writer's session graph: cut states, their
|
|
784
|
+
``continues`` edges, receipt actions, state annotations, symbol bindings, slices, legacy
|
|
785
|
+
circuit records, watch events. Cuts and receipts are strict (a failure raises); any other
|
|
786
|
+
row that is unreadable or refers to a row not in the graph is left out and reported
|
|
787
|
+
through ``refuse`` (records referring to a left-out record are left out in turn).
|
|
788
|
+
"""
|
|
789
|
+
row = self.session(sid)
|
|
790
|
+
identity = json.loads(row["identity"])
|
|
791
|
+
session_binding = gs.binding(session=sid)
|
|
792
|
+
g = gs.GraphBuilder(metadata={"source": "mdb-project",
|
|
793
|
+
"execution_authority": "native-runtime"})
|
|
794
|
+
nodes, cuts = {}, {}
|
|
795
|
+
for identifier in self.cut_ids(sid):
|
|
796
|
+
cut = self.cut_descriptor(sid, identifier)
|
|
797
|
+
cuts[identifier] = cut
|
|
798
|
+
nodes[identifier] = g.add_node(g.state_node(
|
|
799
|
+
f"cas://sha256/{identifier}", identifier,
|
|
800
|
+
binding_=gs.binding(model=cut["model_identity"], session=sid,
|
|
801
|
+
clock=dict(cut["execution_point"])),
|
|
802
|
+
metadata={"native_format": "saturn-pub", "boundary": cut["boundary"]}))
|
|
803
|
+
for identifier, cut in cuts.items():
|
|
804
|
+
if cut["parent"] in nodes:
|
|
805
|
+
g.add_edge(nodes[cut["parent"]], nodes[identifier], "continues",
|
|
806
|
+
evidence_=gs.evidence("observed"))
|
|
807
|
+
receipt_binding = gs.binding(model=identity, session=sid)
|
|
808
|
+
for data in self.receipts(sid):
|
|
809
|
+
parent, result = data.get("parent"), data.get("result")
|
|
810
|
+
output = (nodes.get(result) if data.get("operation") not in {"restore", "abort"}
|
|
811
|
+
and result != parent else None)
|
|
812
|
+
inputs = [nodes[parent]] if parent in nodes else []
|
|
813
|
+
if data.get("operation") in {"commit", "abort"}:
|
|
814
|
+
candidate = nodes.get(data.get("candidate"))
|
|
815
|
+
if candidate and candidate not in inputs:
|
|
816
|
+
inputs.append(candidate)
|
|
817
|
+
ref = f"cas://sha256/{data['fingerprint']}"
|
|
818
|
+
action = g.add_action(ref, inputs=inputs, output=output, receipt_refs=(ref,),
|
|
819
|
+
binding_=receipt_binding, metadata={"native_receipt": data},
|
|
820
|
+
evidence_class="observed")
|
|
821
|
+
if data.get("operation") == "restore" and result in nodes:
|
|
822
|
+
g.add_edge(action, nodes[result], "describes", graph="knowledge",
|
|
823
|
+
evidence_=gs.evidence("observed"), metadata={"role": "restore-target"})
|
|
824
|
+
|
|
825
|
+
def attempt(kind, ident, build):
|
|
826
|
+
try:
|
|
827
|
+
return build()
|
|
828
|
+
except (ValueError, KeyError, TypeError, AttributeError, RecursionError) as error:
|
|
829
|
+
refuse(kind, ident, error)
|
|
830
|
+
return None
|
|
831
|
+
|
|
832
|
+
# ---- gather and verify every knowledge row first; place them in writer order after
|
|
833
|
+
records = {r["record_id"]: r for r in self.circuit_records(sid, refuse=refuse)}
|
|
834
|
+
record_nodes = {rid: attempt("circuit-record", rid, lambda r=r: g.source_node(
|
|
835
|
+
"circuit://sha256/" + r["record_id"], binding_=session_binding,
|
|
836
|
+
labels=("circuit-" + r["kind"],),
|
|
837
|
+
metadata={"record_id": r["record_id"], "kind": r["kind"],
|
|
838
|
+
"focus_id": r.get("focus_id"),
|
|
839
|
+
"terminal_status": r.get("terminal_status", "not-established")}))
|
|
840
|
+
for rid, r in records.items()}
|
|
841
|
+
record_nodes = {rid: n for rid, n in record_nodes.items() if n is not None}
|
|
842
|
+
|
|
843
|
+
def record_refs(r):
|
|
844
|
+
refs = []
|
|
845
|
+
for key in ("focus_id", "plan_id"):
|
|
846
|
+
if r.get(key):
|
|
847
|
+
refs.append(r[key])
|
|
848
|
+
arms = r.get("arms", [])
|
|
849
|
+
if not isinstance(arms, list):
|
|
850
|
+
raise ProjectReadError("circuit record arms is not a list")
|
|
851
|
+
refs += arms
|
|
852
|
+
for key in ("supporting_cut", "input_cut", "result_cut"):
|
|
853
|
+
hash(r.get(key))
|
|
854
|
+
return refs
|
|
855
|
+
|
|
856
|
+
changed = True
|
|
857
|
+
while changed:
|
|
858
|
+
changed = False
|
|
859
|
+
for rid in list(record_nodes):
|
|
860
|
+
try:
|
|
861
|
+
refs = record_refs(records[rid])
|
|
862
|
+
missing = [x for x in refs if not isinstance(x, str) or x not in record_nodes]
|
|
863
|
+
if missing:
|
|
864
|
+
raise ProjectReadError("circuit graph has an unresolved record reference")
|
|
865
|
+
except (ValueError, TypeError) as error:
|
|
866
|
+
refuse("circuit-record", rid, error)
|
|
867
|
+
del record_nodes[rid]
|
|
868
|
+
changed = True
|
|
869
|
+
|
|
870
|
+
annotations = []
|
|
871
|
+
for entry, annotation in self.annotations(sid, refuse=refuse):
|
|
872
|
+
ident = entry.get("annotation_id", "?")
|
|
873
|
+
|
|
874
|
+
def build(entry=entry, annotation=annotation):
|
|
875
|
+
details = annotation.get("details", {})
|
|
876
|
+
slice_id = details.get("slice_id")
|
|
877
|
+
investigation = details.get("investigation_id")
|
|
878
|
+
if entry["cut_id"] not in nodes:
|
|
879
|
+
raise ProjectReadError("annotation names a cut that is not in the session")
|
|
880
|
+
if investigation and (not isinstance(investigation, str)
|
|
881
|
+
or investigation not in record_nodes):
|
|
882
|
+
raise ProjectReadError("finding has an unresolved circuit record")
|
|
883
|
+
node = g.source_node(entry["annotation_id"], labels=(entry["label"],),
|
|
884
|
+
binding_=session_binding, metadata=annotation)
|
|
885
|
+
return node, entry["cut_id"], slice_id, investigation
|
|
886
|
+
built = attempt("annotation", str(ident), build)
|
|
887
|
+
if built is not None:
|
|
888
|
+
annotations.append(built)
|
|
889
|
+
|
|
890
|
+
symbols = {}
|
|
891
|
+
for value in self.symbols(sid, refuse=refuse):
|
|
892
|
+
node = attempt("symbol", value["fingerprint"], lambda v=value: g.source_node(
|
|
893
|
+
f"symbol://sha256/{v['fingerprint']}", binding_=session_binding, metadata=v,
|
|
894
|
+
labels=(v["symbol"],)))
|
|
895
|
+
if node is not None:
|
|
896
|
+
symbols[value["fingerprint"]] = node
|
|
897
|
+
|
|
898
|
+
slices = []
|
|
899
|
+
for sliced in self.slices(sid, refuse=refuse):
|
|
900
|
+
identifier = sliced["slice_id"]
|
|
901
|
+
|
|
902
|
+
def build(sliced=sliced, identifier=identifier):
|
|
903
|
+
if sliced["cut_id"] not in nodes:
|
|
904
|
+
raise ProjectReadError("slice names a cut that is not in the session")
|
|
905
|
+
symbol = None
|
|
906
|
+
if sliced["symbol_binding"]:
|
|
907
|
+
symbol = sliced["symbol_binding"]["fingerprint"]
|
|
908
|
+
if symbol not in symbols:
|
|
909
|
+
raise ProjectReadError("slice names a symbol binding not in the graph")
|
|
910
|
+
node = g.source_node(f"slice://sha256/{identifier}", binding_=session_binding,
|
|
911
|
+
labels=(sliced["component"],),
|
|
912
|
+
metadata={"slice_id": identifier,
|
|
913
|
+
"graph_snapshot": sliced["graph"]["snapshot_id"],
|
|
914
|
+
"support": sliced["support"],
|
|
915
|
+
"complete": sliced["complete"]})
|
|
916
|
+
return identifier, node, sliced["cut_id"], symbol
|
|
917
|
+
built = attempt("slice", identifier, build)
|
|
918
|
+
if built is not None:
|
|
919
|
+
slices.append(built)
|
|
920
|
+
|
|
921
|
+
watches = []
|
|
922
|
+
for event in self.watch_events(sid, refuse=refuse):
|
|
923
|
+
ident = str(event.get("fingerprint"))
|
|
924
|
+
|
|
925
|
+
def build(event=event):
|
|
926
|
+
target = event["cut"]
|
|
927
|
+
hash(target)
|
|
928
|
+
node = g.output_node(f"watch://sha256/{event['fingerprint']}",
|
|
929
|
+
binding_=receipt_binding, metadata=event,
|
|
930
|
+
evidence_=gs.evidence("observed"),
|
|
931
|
+
labels=("diagnostic-watch",))
|
|
932
|
+
return node, target
|
|
933
|
+
built = attempt("watch-event", ident, build)
|
|
934
|
+
if built is not None:
|
|
935
|
+
watches.append(built)
|
|
936
|
+
|
|
937
|
+
# ---- place, in the writer's order
|
|
938
|
+
annotation_ids = []
|
|
939
|
+
for node, cut_id, slice_id, investigation in annotations:
|
|
940
|
+
source = g.add_node(node)
|
|
941
|
+
g.add_edge(source, nodes[cut_id], "annotates", graph="knowledge")
|
|
942
|
+
annotation_ids.append((source, slice_id, investigation))
|
|
943
|
+
for fingerprint, node in symbols.items():
|
|
944
|
+
symbols[fingerprint] = g.add_node(node)
|
|
945
|
+
for identifier, node, cut_id, symbol in slices:
|
|
946
|
+
source = g.add_node(node)
|
|
947
|
+
g.add_edge(source, nodes[cut_id], "describes", graph="knowledge")
|
|
948
|
+
if symbol is not None:
|
|
949
|
+
g.add_edge(symbols[symbol], source, "describes", graph="knowledge")
|
|
950
|
+
for annotation, slice_id, _ in annotation_ids:
|
|
951
|
+
if slice_id and slice_id == identifier:
|
|
952
|
+
g.add_edge(annotation, source, "related_to", graph="knowledge")
|
|
953
|
+
placed = {rid: g.add_node(node) for rid, node in record_nodes.items()}
|
|
954
|
+
for rid, node in placed.items():
|
|
955
|
+
r = records[rid]
|
|
956
|
+
for key in ("focus_id", "plan_id"):
|
|
957
|
+
if r.get(key):
|
|
958
|
+
g.add_edge(node, placed[r[key]], "related_to", graph="knowledge")
|
|
959
|
+
for key in ("supporting_cut", "input_cut", "result_cut"):
|
|
960
|
+
if r.get(key) in nodes:
|
|
961
|
+
g.add_edge(node, nodes[r[key]], "describes", graph="knowledge")
|
|
962
|
+
for arm in r.get("arms", []):
|
|
963
|
+
g.add_edge(node, placed[arm], "related_to", graph="knowledge")
|
|
964
|
+
for annotation, _, investigation in annotation_ids:
|
|
965
|
+
if investigation:
|
|
966
|
+
g.add_edge(annotation, placed[investigation], "related_to", graph="knowledge")
|
|
967
|
+
for node, target in watches:
|
|
968
|
+
output = g.add_node(node)
|
|
969
|
+
if target in nodes:
|
|
970
|
+
g.add_edge(output, nodes[target], "describes", graph="knowledge",
|
|
971
|
+
evidence_=gs.evidence("observed"))
|
|
972
|
+
return g.seal()
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
# --------------------------------------------------------------------------- symbol reads
|
|
976
|
+
|
|
977
|
+
def lifecycle_reads(body) -> list[dict]:
|
|
978
|
+
"""Attention reads recorded in a verified symbol lifecycle body, as sealed
|
|
979
|
+
``mdb-symbol-read-v2`` dicts (one per query-head use; causal status ``unknown``).
|
|
980
|
+
|
|
981
|
+
The read source is the project binding: rows from ``uses[].metadata.source_row`` (``[0]``
|
|
982
|
+
when none), assignment ``supplied``. Empty when the lifecycle carries no attention trace or no
|
|
983
|
+
uses, or when a use does not hold exactly one ``source_mass`` observation.
|
|
984
|
+
"""
|
|
985
|
+
try:
|
|
986
|
+
return _lifecycle_reads(body)
|
|
987
|
+
except (ValueError, KeyError, TypeError, AttributeError, RecursionError):
|
|
988
|
+
return []
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _lifecycle_reads(body):
|
|
992
|
+
metadata = body.get("metadata") or {}
|
|
993
|
+
trace = metadata.get("attention_trace")
|
|
994
|
+
uses = body.get("uses")
|
|
995
|
+
if not trace or not uses:
|
|
996
|
+
return []
|
|
997
|
+
layer = trace.get("layer")
|
|
998
|
+
if layer is None:
|
|
999
|
+
return []
|
|
1000
|
+
binding_fp = body["binding_fingerprint"]
|
|
1001
|
+
_sha(binding_fp, "binding fingerprint")
|
|
1002
|
+
rows = sorted({int(u["metadata"].get("source_row", 0)) for u in uses
|
|
1003
|
+
if isinstance(u.get("metadata"), dict) and "source_row" in u["metadata"]})
|
|
1004
|
+
rows = check_bounded([int(r) for r in (rows or [0])], "source rows")
|
|
1005
|
+
if not body.get("symbol") or any(r < 0 for r in rows):
|
|
1006
|
+
raise ProjectReadError("a read source needs a name and non-negative token rows")
|
|
1007
|
+
source = {"name": body["symbol"], "rows": rows, "assignment": "supplied",
|
|
1008
|
+
"provenance": check_bounded({"by": "project binding " + str(binding_fp)[:12]},
|
|
1009
|
+
"source provenance"),
|
|
1010
|
+
"binding_fingerprint": None}
|
|
1011
|
+
out = []
|
|
1012
|
+
for use in uses:
|
|
1013
|
+
meta = dict(use["metadata"])
|
|
1014
|
+
masses = [o["value"] for o in use["signed_observations"]
|
|
1015
|
+
if isinstance(o, Mapping) and o.get("observable") == "source_mass"]
|
|
1016
|
+
if len(masses) != 1:
|
|
1017
|
+
raise ProjectReadError("use lacks exactly one observed mass")
|
|
1018
|
+
block, head = int(layer), int(meta["query_head"])
|
|
1019
|
+
if block < 0 or head < 0:
|
|
1020
|
+
raise ProjectReadError("reader block/head must be non-negative integers")
|
|
1021
|
+
mass = masses[0]
|
|
1022
|
+
if isinstance(mass, bool) or not isinstance(mass, (int, float)) or not math.isfinite(mass):
|
|
1023
|
+
raise ProjectReadError("observed mass must be a finite number")
|
|
1024
|
+
reader = {"block": block, "head": head, "step": None, "steps": None,
|
|
1025
|
+
"kv_group": meta.get("kv_head"), "block_label": f"layer.{layer}",
|
|
1026
|
+
"receivers": "query row", "receiver_row": meta.get("receiver_row")}
|
|
1027
|
+
read = {"schema": READ_SCHEMA, "source": source, "reader": reader, "mass": float(mass),
|
|
1028
|
+
"mass_kind": "attention probability on source row", "surface": "project-session",
|
|
1029
|
+
"backend": "qwen-gqa", "binding_fingerprint": binding_fp,
|
|
1030
|
+
"use_id": use["use_id"], "use_fingerprint": use["fingerprint"],
|
|
1031
|
+
"lifecycle_fingerprint": body["fingerprint"], "sets": [],
|
|
1032
|
+
"causal": {"status": "unknown", "label": UNKNOWN_CAUSAL_LABEL, "results": []},
|
|
1033
|
+
"evidence": check_bounded(list(use.get("evidence_refs") or ()), "read evidence"),
|
|
1034
|
+
"metadata": check_bounded({"trace_fingerprint": meta.get("trace_fingerprint")},
|
|
1035
|
+
"read metadata"),
|
|
1036
|
+
"model": None}
|
|
1037
|
+
out.append(_sealed(read, "symbol read"))
|
|
1038
|
+
return out
|