model-debugger 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. mdb/__init__.py +43 -0
  2. mdb/__main__.py +5 -0
  3. mdb/analysis/__init__.py +34 -0
  4. mdb/analysis/circuits/__init__.py +6 -0
  5. mdb/analysis/circuits/build.py +690 -0
  6. mdb/analysis/circuits/test.py +600 -0
  7. mdb/analysis/features/__init__.py +5 -0
  8. mdb/analysis/features/basis.py +685 -0
  9. mdb/analysis/features/sae.py +374 -0
  10. mdb/analysis/features/watch.py +268 -0
  11. mdb/analysis/measure/__init__.py +7 -0
  12. mdb/analysis/measure/branches.py +806 -0
  13. mdb/analysis/measure/bridge.py +379 -0
  14. mdb/analysis/measure/changes.py +201 -0
  15. mdb/analysis/measure/compare.py +348 -0
  16. mdb/analysis/measure/donors.py +193 -0
  17. mdb/analysis/measure/novelty.py +227 -0
  18. mdb/analysis/measure/paths.py +146 -0
  19. mdb/analysis/measure/pools.py +454 -0
  20. mdb/analysis/measure/readout.py +387 -0
  21. mdb/analysis/measure/reads.py +455 -0
  22. mdb/analysis/measure/sweep.py +215 -0
  23. mdb/analysis/numerics/__init__.py +6 -0
  24. mdb/analysis/numerics/accumulation.py +180 -0
  25. mdb/analysis/numerics/finite.py +1712 -0
  26. mdb/analysis/numerics/labels.py +80 -0
  27. mdb/analysis/numerics/pooling.py +89 -0
  28. mdb/analysis/numerics/stability.py +183 -0
  29. mdb/analysis/numerics/summary.py +306 -0
  30. mdb/analysis/numerics/units.py +86 -0
  31. mdb/analysis/numerics/verdict.py +244 -0
  32. mdb/analysis/numerics/why_frames.py +162 -0
  33. mdb/analysis/predict/__init__.py +7 -0
  34. mdb/analysis/predict/capture.py +265 -0
  35. mdb/analysis/predict/consumers.py +52 -0
  36. mdb/analysis/predict/explain.py +776 -0
  37. mdb/analysis/predict/forecast.py +635 -0
  38. mdb/analysis/predict/plan.py +248 -0
  39. mdb/analysis/predict/propagate.py +596 -0
  40. mdb/analysis/predict/rounding.py +95 -0
  41. mdb/analysis/predict/rowmodel.py +817 -0
  42. mdb/analysis/predict/supplied.py +103 -0
  43. mdb/analysis/predict/verify.py +433 -0
  44. mdb/analysis/predict/whatif.py +840 -0
  45. mdb/analysis/symbols/__init__.py +7 -0
  46. mdb/analysis/symbols/binding.py +138 -0
  47. mdb/analysis/symbols/candidates.py +320 -0
  48. mdb/analysis/symbols/circuit_map.py +592 -0
  49. mdb/analysis/symbols/components.py +436 -0
  50. mdb/analysis/symbols/frame.py +451 -0
  51. mdb/analysis/symbols/hop.py +439 -0
  52. mdb/analysis/symbols/liveness.py +292 -0
  53. mdb/analysis/symbols/probe.py +393 -0
  54. mdb/analysis/symbols/rows.py +400 -0
  55. mdb/analysis/symbols/sealed.py +149 -0
  56. mdb/analysis/symbols/subspace.py +380 -0
  57. mdb/analysis/symbols/symbol_finite.py +417 -0
  58. mdb/analysis/symbols/symbol_runs.py +683 -0
  59. mdb/analysis/symbols/table.py +1110 -0
  60. mdb/cli.py +105 -0
  61. mdb/core/__init__.py +4 -0
  62. mdb/core/address.py +1353 -0
  63. mdb/core/bounded.py +101 -0
  64. mdb/core/checkpoint_schema.py +202 -0
  65. mdb/core/checkpoint_store.py +377 -0
  66. mdb/core/circuit_pages.py +117 -0
  67. mdb/core/custody.py +629 -0
  68. mdb/core/errors.py +51 -0
  69. mdb/core/foreign_names.py +152 -0
  70. mdb/core/graph_seal.py +426 -0
  71. mdb/core/index.py +403 -0
  72. mdb/core/kinds.py +255 -0
  73. mdb/core/locate.py +161 -0
  74. mdb/core/migrate.py +280 -0
  75. mdb/core/neuronpedia.py +116 -0
  76. mdb/core/plugins.py +78 -0
  77. mdb/core/pointers.py +621 -0
  78. mdb/core/project.py +248 -0
  79. mdb/core/project_read.py +1038 -0
  80. mdb/core/recipe.py +457 -0
  81. mdb/core/records.py +1027 -0
  82. mdb/core/resolve.py +296 -0
  83. mdb/core/settings.py +718 -0
  84. mdb/engine/__init__.py +21 -0
  85. mdb/engine/attention_observer.py +53 -0
  86. mdb/engine/attention_port.py +903 -0
  87. mdb/engine/breakpoints.py +1465 -0
  88. mdb/engine/bundle.py +137 -0
  89. mdb/engine/checkpoint.py +1265 -0
  90. mdb/engine/core_file.py +306 -0
  91. mdb/engine/edits.py +323 -0
  92. mdb/engine/holds.py +256 -0
  93. mdb/engine/models.py +172 -0
  94. mdb/engine/ports.py +1424 -0
  95. mdb/engine/refs.py +223 -0
  96. mdb/engine/run.py +2162 -0
  97. mdb/engine/selfcheck.py +347 -0
  98. mdb/engine/trace.py +536 -0
  99. mdb/interop/__init__.py +17 -0
  100. mdb/interop/circuit_tracer_graph.py +253 -0
  101. mdb/interop/circuit_tracer_names.py +44 -0
  102. mdb/interop/clone.py +22 -0
  103. mdb/interop/names.py +295 -0
  104. mdb/interop/nn.py +431 -0
  105. mdb/interop/pyvene_compat.py +40 -0
  106. mdb/interop/pyvene_names.py +82 -0
  107. mdb/interop/tl.py +149 -0
  108. mdb/interop/verify.py +85 -0
  109. mdb/machines/__init__.py +53 -0
  110. mdb/machines/x86/__init__.py +13 -0
  111. mdb/machines/x86/address.py +171 -0
  112. mdb/machines/x86/binary.py +285 -0
  113. mdb/machines/x86/grid.py +188 -0
  114. mdb/machines/x86/index.py +184 -0
  115. mdb/machines/x86/interchange.py +156 -0
  116. mdb/machines/x86/lanes.py +281 -0
  117. mdb/machines/x86/method.py +252 -0
  118. mdb/machines/x86/method_v2.py +105 -0
  119. mdb/machines/x86/mlp.py +430 -0
  120. mdb/machines/x86/records.py +138 -0
  121. mdb/machines/x86/session.py +631 -0
  122. mdb/machines/x86/trace.py +351 -0
  123. mdb/ops/__init__.py +31 -0
  124. mdb/ops/builtin.py +1977 -0
  125. mdb/ops/context.py +60 -0
  126. mdb/ops/debugger.py +926 -0
  127. mdb/ops/errors.py +8 -0
  128. mdb/ops/features.py +513 -0
  129. mdb/ops/graph.py +58 -0
  130. mdb/ops/inspect.py +906 -0
  131. mdb/ops/lines.py +496 -0
  132. mdb/ops/named.py +672 -0
  133. mdb/ops/predict.py +450 -0
  134. mdb/ops/registry.py +332 -0
  135. mdb/ops/sets.py +988 -0
  136. mdb/ops/sweep.py +574 -0
  137. mdb/repl/__init__.py +5 -0
  138. mdb/repl/__main__.py +244 -0
  139. mdb/repl/config.py +213 -0
  140. mdb/repl/remote.py +324 -0
  141. mdb/repl/render.py +1699 -0
  142. mdb/repl/shell.py +409 -0
  143. mdb/serve/__init__.py +17 -0
  144. mdb/serve/__main__.py +180 -0
  145. mdb/serve/_legacy.py +97 -0
  146. mdb/serve/app.py +526 -0
  147. mdb/serve/blobs.py +280 -0
  148. mdb/serve/caps.py +148 -0
  149. mdb/serve/export.py +9 -0
  150. mdb/serve/guard.py +216 -0
  151. mdb/serve/live.py +412 -0
  152. mdb/serve/live_reduce.py +90 -0
  153. mdb/serve/recorded.py +515 -0
  154. mdb/serve/reduce.py +449 -0
  155. mdb/serve/schema.py +969 -0
  156. mdb/serve/states.py +125 -0
  157. mdb/serve/static/assets/index-BJpByNCO.js +58 -0
  158. mdb/serve/static/assets/index-H9zlNeqq.css +1 -0
  159. mdb/serve/static/index.html +14 -0
  160. mdb/serve/static/manifest.json +5 -0
  161. mdb/serve/stored.py +34 -0
  162. mdb/serve/typegen.py +131 -0
  163. mdb/serve/views/__init__.py +1 -0
  164. mdb/serve/views/common.py +201 -0
  165. mdb/serve/views/frame.py +235 -0
  166. mdb/serve/views/graph.py +224 -0
  167. mdb/serve/views/live.py +402 -0
  168. mdb/serve/views/records.py +557 -0
  169. mdb/serve/views/sessions.py +151 -0
  170. mdb/serve/views/symbols.py +185 -0
  171. mdb/serve/views/timeline.py +121 -0
  172. model_debugger-0.4.0.dist-info/METADATA +1516 -0
  173. model_debugger-0.4.0.dist-info/RECORD +177 -0
  174. model_debugger-0.4.0.dist-info/WHEEL +4 -0
  175. model_debugger-0.4.0.dist-info/entry_points.txt +2 -0
  176. model_debugger-0.4.0.dist-info/licenses/LICENSE +202 -0
  177. model_debugger-0.4.0.dist-info/licenses/NOTICE +6 -0
@@ -0,0 +1,152 @@
1
+ """Foreign names of mdb cells, rows and reads.
2
+
3
+ Pure text, no imports above ``core``: ``analysis.symbols.table`` attaches these to every table row,
4
+ ``interop.names`` re-exports them beside its port table (``residual_names`` lives there, since
5
+ it needs the port table). TransformerLens names are the bridge-native hooks of
6
+ ``interop.names.NAMES``; nnsight paths are module paths of a Hugging Face Qwen2/Qwen3/Llama.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ # ``verified`` says how a mapping is known: ``measured`` (tests/test_interop_symtab.py reads the
14
+ # same value through the tool and mdb on tiny Qwen2/Qwen3, within float32 rounding), or
15
+ # ``unverified`` (written from the library's documentation; not installed or not tested here).
16
+ # Neuronpedia ids come from an explicit mapping, basis metadata or the local SAELens
17
+ # registry. They remain labelled ``supplied``; model/source ids are never guessed.
18
+
19
+ MEASURED_MAP = "measured"
20
+ UNVERIFIED_MAP = "unverified"
21
+ SUPPLIED_MAP = "supplied"
22
+
23
+ _CELL_PORT = {
24
+ # mdb cache tensor -> (TL hook, TL index, nnsight path, nnsight index)
25
+ # v: the cache holds v_proj's output (no v norm on Qwen2/Qwen3/Llama)
26
+ "v": ("blocks.{l}.attn.v.hook_out", "[:, {r}, {g}, :]",
27
+ "model.model.layers[{l}].self_attn.v_proj.output", "[:, {r}, {lo}:{hi}]"),
28
+ # k: the cache holds the rotated (and k-normed) key
29
+ "k": ("blocks.{l}.attn.hook_rot_k", "[:, {r}, {g}, :]",
30
+ "model.model.layers[{l}].self_attn.source.attention_interface_1.inputs[0][2]",
31
+ "[:, {g}, {r}, :]"),
32
+ }
33
+
34
+
35
+ def cell_names(layer: int, kv: int, row: int, port: str = "v", *,
36
+ head_dim: int) -> dict[str, Any]:
37
+ """Foreign names of the cache cell ``cache.L<layer>.<port>[kv<kv>,row=<row>]``: the
38
+ TransformerLens hook and index, the nnsight path and index, and a pyvene representation
39
+ spec (``interop.pyvene_names``: ``head_value_output`` with unit ``h.pos``), all
40
+ ``measured`` on tiny Qwen3 (``tests/test_interop_symtab.py``). A key cell has no pyvene
41
+ counterpart: pyvene's key components are k_proj's output, before k_norm and RoPE."""
42
+ if port not in _CELL_PORT:
43
+ raise KeyError(f"cache port {port!r} is k or v")
44
+ tl_hook, tl_index, nn_path, nn_index = _CELL_PORT[port]
45
+ fill = {"l": layer, "r": row, "g": kv, "lo": kv * head_dim, "hi": (kv + 1) * head_dim}
46
+ out = {
47
+ "address": f"cache.L{layer}.{port}[kv{kv},row={row}]",
48
+ "tl": {"hook": tl_hook.format(**fill), "index": tl_index.format(**fill),
49
+ "legacy": (f"blocks.{layer}.attn.hook_{port}" if port == "v" else None),
50
+ "verified": MEASURED_MAP},
51
+ "nnsight": {"path": nn_path.format(**fill), "index": nn_index.format(**fill),
52
+ "verified": MEASURED_MAP},
53
+ "pyvene": ({"layer": layer, "component": "head_value_output", "unit": "h.pos",
54
+ "unit_locations": {"h": [[kv]], "pos": [[row]]},
55
+ "verified": MEASURED_MAP,
56
+ "note": "Qwen3 needs interop.pyvene_names.qwen3_shim(); pyvene 0.1.8"}
57
+ if port == "v" else
58
+ {"state": "no counterpart",
59
+ "reason": "pyvene's key_output / head_key_output is k_proj's output, before "
60
+ "k_norm and RoPE; the cache holds the rotated key"}),
61
+ }
62
+ return out
63
+
64
+
65
+ def row_names(row: int) -> dict[str, Any]:
66
+ """Foreign names of a whole token row ``t<row>`` (every layer's k and v cells)."""
67
+ return {
68
+ "address": f"t{row}",
69
+ "tl": {"hook": "blocks.*.attn.v.hook_out", "index": f"[:, {row}, :, :]",
70
+ "keys": "blocks.*.attn.hook_rot_k", "embed": f"hook_embed[:, {row}]",
71
+ "verified": MEASURED_MAP},
72
+ "nnsight": {"path": "model.model.layers[*].self_attn.v_proj.output",
73
+ "index": f"[:, {row}, :]",
74
+ "embed": f"model.model.embed_tokens.output[:, {row}]",
75
+ "verified": MEASURED_MAP},
76
+ "pyvene": {"component": "value_output", "unit": "pos", "unit_locations": [[row]],
77
+ "layers": "every layer", "verified": MEASURED_MAP},
78
+ }
79
+
80
+
81
+ def read_names(row: int, layer: int, head: int, source: int | None = None) -> dict[str, Any]:
82
+ """Foreign names of the read ``t<row>.L<layer>.h<head>`` (of ``source``, or every source):
83
+ its attention weight in TL ``hook_pattern`` and nnsight's ``self_attn.output[1]``."""
84
+ s = ":" if source is None else str(source)
85
+ return {"address": f"t{row}.L{layer}.h{head}" + ("" if source is None else f"<-t{source}"),
86
+ "tl": {"hook": f"blocks.{layer}.attn.hook_pattern",
87
+ "index": f"[:, {head}, {row}, {s}]", "verified": MEASURED_MAP},
88
+ "nnsight": {"path": f"model.model.layers[{layer}].self_attn.output[1]",
89
+ "index": f"[:, {head}, {row}, {s}]", "verified": MEASURED_MAP}}
90
+
91
+
92
+ def neuronpedia_url(mapping: dict[str, Any] | None, release: str | None, sae_id: str | None,
93
+ feature: int, *, metadata: dict[str, Any] | None = None) -> dict[str, Any]:
94
+ """Offline feature link: explicit mapping > basis metadata > installed SAELens registry."""
95
+ from .neuronpedia import feature_url
96
+
97
+ return feature_url(mapping, release, sae_id, feature, metadata=metadata)
98
+
99
+
100
+ def ct_node(layer: int, row: int, feature: int) -> dict[str, Any]:
101
+ """A circuit-tracer attribution-graph node for transcoder feature ``feature`` of layer
102
+ ``layer`` at position ``row`` (circuit-tracer 0.5.0 ``Node.feature_node`` id
103
+ ``{layer}_{feature}_{pos}``). The transcoder reads mdb's ``t<row>.L<layer>.n`` (Qwen3
104
+ ``mlp.hook_in`` = post_attention_layernorm output) and writes into ``t<row>.L<layer>.m``
105
+ (``mlp.hook_out``); both measured on tiny Qwen3 through circuit-tracer's own nnsight
106
+ mapping."""
107
+ return {"layer": layer, "position": row, "feature": int(feature),
108
+ "id": f"{layer}_{int(feature)}_{row}", "reads": f"t{row}.L{layer}.n",
109
+ "writes": f"t{row}.L{layer}.m", "verified": MEASURED_MAP}
110
+
111
+
112
+ def ct_error_node(layer: int, row: int) -> dict[str, Any]:
113
+ """The circuit-tracer error node of layer ``layer`` at ``row`` (id ``0_{layer}_{pos}``):
114
+ ``t<row>.L<layer>.m`` minus the transcoder's reconstruction."""
115
+ return {"layer": layer, "position": row, "id": f"0_{layer}_{row}",
116
+ "address": f"t{row}.L{layer}.m", "verified": MEASURED_MAP}
117
+
118
+
119
+ def ct_token_node(row: int, token: int) -> dict[str, Any]:
120
+ """The circuit-tracer embedding node of ``token`` at ``row`` (id ``E_{token}_{pos}``):
121
+ mdb's ``t<row>.emb``."""
122
+ return {"position": row, "token": int(token), "id": f"E_{int(token)}_{row}",
123
+ "address": f"t{row}.emb", "verified": MEASURED_MAP}
124
+
125
+
126
+ def ct_logit_node(row: int, token: int, layers: int) -> dict[str, Any]:
127
+ """The circuit-tracer logit node (id ``{layers + 1}_{token}_{pos}``): mdb's
128
+ ``t<row>.logits[i=<token>]``."""
129
+ return {"position": row, "token": int(token), "id": f"{layers + 1}_{int(token)}_{row}",
130
+ "address": f"t{row}.logits[i={int(token)}]", "verified": MEASURED_MAP}
131
+
132
+
133
+ def binding_names(cells: list[Any], *, head_dim: int, kv_heads: int, layers: int,
134
+ limit: int = 8) -> dict[str, Any]:
135
+ """Foreign names for a binding's cells (``reads.Source`` items): a whole row gets
136
+ ``row_names``; a cell set lists up to ``limit`` cells' ``cell_names`` and counts the
137
+ rest."""
138
+ out: list[dict[str, Any]] = []
139
+ total = 0
140
+ for cell in cells:
141
+ if cell.layers is None and cell.kv is None and cell.ports is None:
142
+ total += 1
143
+ if len(out) < limit:
144
+ out.append(row_names(cell.row))
145
+ continue
146
+ for layer in (cell.layers if cell.layers is not None else range(layers)):
147
+ for kv in (cell.kv if cell.kv is not None else range(kv_heads)):
148
+ for port in (cell.ports or ("k", "v")):
149
+ total += 1
150
+ if len(out) < limit:
151
+ out.append(cell_names(layer, kv, cell.row, port, head_dim=head_dim))
152
+ return {"cells": out, "omitted": max(0, total - len(out))}
mdb/core/graph_seal.py ADDED
@@ -0,0 +1,426 @@
1
+ """Content-addressed state graphs: build and verify the ``mdb-state-graph-*-v1`` seals.
2
+
3
+ Standard library only. This is the read side of the history graph format (nodes, edges, events
4
+ and sealed snapshots) that recorded projects store in slices and that a session graph is built in:
5
+ the same canonical JSON, the same identities, the same structural checks. It builds plain dicts
6
+ (``to_dict`` shapes), never executes anything and holds no model state.
7
+
8
+ Normalisation follows the format: text fields are stripped, evidence classes are lower-case with
9
+ ``-``, sequences become lists, mappings need text keys, floats must be finite. Anything else is a
10
+ ``GraphSealError`` (a ``ValueError``).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ import math
17
+ from collections.abc import Iterable, Mapping
18
+
19
+ SCHEMA = "mdb-state-graph-v1"
20
+ SNAPSHOT_SCHEMA = "mdb-state-graph-snapshot-v1"
21
+ EVENT_SCHEMA = "mdb-state-graph-event-v1"
22
+ NODE_SCHEMA = "mdb-state-graph-node-v1"
23
+ EDGE_SCHEMA = "mdb-state-graph-edge-v1"
24
+ BINDING_SCHEMA = "mdb-state-graph-binding-v1"
25
+ EVIDENCE_SCHEMA = "mdb-state-graph-evidence-v1"
26
+
27
+ NODE_KINDS = frozenset({"source", "state", "action", "output"})
28
+ EXECUTION_RELATIONS = frozenset({"parent", "continues", "reads", "writes", "derived_from",
29
+ "invalidates", "observed_effect"})
30
+ KNOWLEDGE_RELATIONS = frozenset({"supports", "contradicts", "describes", "hypothesizes",
31
+ "related_to", "annotates"})
32
+ EVIDENCE_CLASSES = frozenset({"declared", "observed", "causally-tested", "hypothesis"})
33
+
34
+
35
+ class GraphSealError(ValueError):
36
+ """A graph value cannot be represented, or a sealed graph does not verify."""
37
+
38
+
39
+ # --------------------------------------------------------------------------- canonical JSON
40
+
41
+ def plain(value, label="value"):
42
+ """Strict JSON copy: text keys, finite floats, sequences as lists."""
43
+ if value is None or isinstance(value, (str, bool, int)):
44
+ return value
45
+ if isinstance(value, float):
46
+ if not math.isfinite(value):
47
+ raise GraphSealError(f"{label} contains a non-finite number")
48
+ return value
49
+ if isinstance(value, Mapping):
50
+ out = {}
51
+ for key, item in value.items():
52
+ if not isinstance(key, str):
53
+ raise GraphSealError(f"{label} contains a non-string key")
54
+ out[key] = plain(item, f"{label}.{key}")
55
+ return out
56
+ if isinstance(value, (list, tuple)):
57
+ return [plain(item, f"{label}[]") for item in value]
58
+ raise GraphSealError(f"{label} contains unsupported {type(value).__name__}")
59
+
60
+
61
+ def canonical(value) -> bytes:
62
+ return json.dumps(plain(value), ensure_ascii=True, allow_nan=False, separators=(",", ":"),
63
+ sort_keys=True).encode("utf-8")
64
+
65
+
66
+ def digest(value) -> str:
67
+ return hashlib.sha256(canonical(value)).hexdigest()
68
+
69
+
70
+ def _text(value, label):
71
+ if not isinstance(value, str) or not value.strip():
72
+ raise GraphSealError(f"{label} must be non-empty text")
73
+ return value.strip()
74
+
75
+
76
+ def _strings(values, label):
77
+ if values is None:
78
+ return []
79
+ if isinstance(values, (str, bytes, bytearray)):
80
+ raise GraphSealError(f"{label} must be a sequence of strings")
81
+ out = [_text(value, f"{label}[]") for value in values]
82
+ if len(out) != len(set(out)):
83
+ raise GraphSealError(f"{label} contains duplicate values")
84
+ return out
85
+
86
+
87
+ def sha(value, label):
88
+ text = _text(value, label).lower().removeprefix("sha256:")
89
+ text = text.removeprefix("cas://sha256/")
90
+ if len(text) != 64 or any(c not in "0123456789abcdef" for c in text):
91
+ raise GraphSealError(f"{label} must be a SHA-256 digest")
92
+ return text
93
+
94
+
95
+ def _ref_fingerprint(text):
96
+ """``source_fingerprint`` of a text reference: the digest of a ``cas://sha256/`` ref."""
97
+ if text.startswith("cas://sha256/"):
98
+ candidate = text.removeprefix("cas://sha256/")
99
+ if len(candidate) == 64 and all(c in "0123456789abcdefABCDEF" for c in candidate):
100
+ return candidate.lower()
101
+ return None
102
+
103
+
104
+ # --------------------------------------------------------------------------- values
105
+
106
+ def binding(model=None, session=None, clock=None, version=None, metadata=None):
107
+ return {"schema": BINDING_SCHEMA, "model": plain(model, "binding.model"),
108
+ "session": plain(session, "binding.session"), "clock": plain(clock, "binding.clock"),
109
+ "version": plain(version, "binding.version"),
110
+ "metadata": plain({} if metadata is None else metadata, "binding.metadata")}
111
+
112
+
113
+ def binding_from(value):
114
+ """A binding dict from a stored binding mapping (``None`` is the empty binding)."""
115
+ if value is None:
116
+ return binding()
117
+ if not isinstance(value, Mapping):
118
+ raise GraphSealError("binding must be a JSON object")
119
+ return binding(value.get("model", value.get("model_id")),
120
+ value.get("session", value.get("session_id")),
121
+ value.get("clock", value.get("time")),
122
+ value.get("version", value.get("version_id")), value.get("metadata", {}))
123
+
124
+
125
+ def evidence(evidence_class="declared", *, condition=None, sign=None, dose=None, effect=None,
126
+ receipt_refs=(), metadata=None):
127
+ cls = _text(evidence_class, "evidence_class").lower().replace("_", "-")
128
+ if cls not in EVIDENCE_CLASSES:
129
+ raise GraphSealError(f"unsupported evidence class {cls!r}")
130
+ return {"schema": EVIDENCE_SCHEMA, "class": cls,
131
+ "condition": plain({} if condition is None else condition, "evidence.condition"),
132
+ "sign": plain(sign, "evidence.sign"), "dose": plain(dose, "evidence.dose"),
133
+ "effect": plain(effect, "evidence.effect"),
134
+ "receipt_refs": _strings(receipt_refs, "receipt_refs"),
135
+ "metadata": plain({} if metadata is None else metadata, "evidence.metadata")}
136
+
137
+
138
+ def evidence_from(value):
139
+ if value is None:
140
+ return evidence()
141
+ if isinstance(value, str):
142
+ return evidence(value)
143
+ if not isinstance(value, Mapping):
144
+ raise GraphSealError("evidence must be a class string or JSON object")
145
+ return evidence(value.get("evidence_class", value.get("class", value.get("class_", "declared"))),
146
+ condition=value.get("condition", {}), sign=value.get("sign"),
147
+ dose=value.get("dose"), effect=value.get("effect"),
148
+ receipt_refs=tuple(value.get("receipt_refs", value.get("receipts", ())) or ()),
149
+ metadata=value.get("metadata", {}))
150
+
151
+
152
+ def _evidence_list(values):
153
+ if values is None:
154
+ return []
155
+ if isinstance(values, (Mapping, str)):
156
+ values = (values,)
157
+ return [evidence_from(v) for v in values]
158
+
159
+
160
+ def node(kind, content, *, binding_=None, evidence_=None, labels=()):
161
+ """A node dict (``to_dict`` shape) with its content-addressed ``node_id``."""
162
+ kind = _text(kind, "node.kind").lower()
163
+ if kind not in NODE_KINDS:
164
+ raise GraphSealError(f"unsupported node kind {kind!r}")
165
+ body = {"schema": NODE_SCHEMA, "kind": kind, "content": plain(content, "node.content"),
166
+ "binding": binding_ if binding_ is not None else binding(),
167
+ "evidence": _evidence_list(evidence_), "labels": _strings(labels, "node.labels")}
168
+ identifier = digest(body)
169
+ return {**body, "node_id": identifier, "fingerprint": identifier}
170
+
171
+
172
+ def edge(source, target, relation, *, graph="execution", evidence_=None, binding_=None,
173
+ metadata=None):
174
+ relation = _text(relation, "edge.relation")
175
+ graph = _text(graph, "edge.graph").lower()
176
+ if graph not in {"execution", "knowledge"}:
177
+ raise GraphSealError("edge.graph must be 'execution' or 'knowledge'")
178
+ if graph == "execution" and relation not in EXECUTION_RELATIONS:
179
+ raise GraphSealError(f"unsupported execution relation {relation!r}")
180
+ if graph == "knowledge" and relation not in KNOWLEDGE_RELATIONS:
181
+ raise GraphSealError(f"unsupported knowledge relation {relation!r}")
182
+ body = {"schema": EDGE_SCHEMA, "source": _text(source, "edge.source"),
183
+ "target": _text(target, "edge.target"), "relation": relation, "graph": graph,
184
+ "evidence": _evidence_list(evidence_),
185
+ "binding": binding_ if binding_ is not None else binding(),
186
+ "metadata": plain({} if metadata is None else metadata, "edge.metadata")}
187
+ identifier = digest(body)
188
+ return {**body, "edge_id": identifier, "fingerprint": identifier}
189
+
190
+
191
+ def node_from(value):
192
+ """Re-derive a stored node; raises when its ``node_id`` differs from its content."""
193
+ if not isinstance(value, Mapping) or value.get("schema") != NODE_SCHEMA:
194
+ raise GraphSealError("graph node schema changed")
195
+ out = node(value.get("kind"), value.get("content", {}),
196
+ binding_=binding_from(value.get("binding", {})),
197
+ evidence_=tuple(value.get("evidence", ())), labels=tuple(value.get("labels", ())))
198
+ if value.get("node_id", value.get("fingerprint")) != out["node_id"]:
199
+ raise GraphSealError("graph node content hash changed")
200
+ return out
201
+
202
+
203
+ def edge_from(value):
204
+ if not isinstance(value, Mapping) or value.get("schema") != EDGE_SCHEMA:
205
+ raise GraphSealError("graph edge schema changed")
206
+ out = edge(value.get("source"), value.get("target"), value.get("relation"),
207
+ graph=value.get("graph", "execution"), evidence_=tuple(value.get("evidence", ())),
208
+ binding_=binding_from(value.get("binding", {})), metadata=value.get("metadata", {}))
209
+ if value.get("edge_id", value.get("fingerprint")) != out["edge_id"]:
210
+ raise GraphSealError("graph edge content hash changed")
211
+ return out
212
+
213
+
214
+ # --------------------------------------------------------------------------- structure
215
+
216
+ def dag_errors(nodes: Mapping[str, Mapping], edges: Iterable[Mapping]) -> list[str]:
217
+ """Structural problems of the execution graph (one parent, acyclic, typed endpoints)."""
218
+ execution = [e for e in edges if e["graph"] == "execution"]
219
+ adjacency = {n: [] for n in nodes}
220
+ incoming = {}
221
+ for e in execution:
222
+ if e["source"] not in nodes or e["target"] not in nodes:
223
+ continue
224
+ adjacency[e["source"]].append(e["target"])
225
+ if e["relation"] in {"parent", "continues"}:
226
+ incoming[e["target"]] = incoming.get(e["target"], 0) + 1
227
+ errors = [f"node {t} has {c} parent/continues inputs; use one Action node with multiple reads"
228
+ for t, c in incoming.items() if c > 1]
229
+ color = {n: 0 for n in nodes}
230
+ for start in sorted(nodes):
231
+ if color[start]:
232
+ continue
233
+ stack = [(start, iter(adjacency[start]))]
234
+ color[start] = 1
235
+ while stack:
236
+ current, children = stack[-1]
237
+ for target in children:
238
+ if color[target] == 1:
239
+ errors.append(f"execution lineage cycle includes {current} -> {target}")
240
+ elif color[target] == 0:
241
+ color[target] = 1
242
+ stack.append((target, iter(adjacency[target])))
243
+ break
244
+ else:
245
+ color[current] = 2
246
+ stack.pop()
247
+ for e in execution:
248
+ if e["source"] not in nodes or e["target"] not in nodes:
249
+ continue
250
+ if e["relation"] == "reads" and nodes[e["target"]]["kind"] != "action":
251
+ errors.append(f"reads edge target {e['target']} is not an action")
252
+ if e["relation"] in {"writes", "observed_effect"} and nodes[e["source"]]["kind"] != "action":
253
+ errors.append(f"{e['relation']} edge source {e['source']} is not an action")
254
+ for n in nodes.values():
255
+ if n["kind"] != "action":
256
+ continue
257
+ content = n["content"] if isinstance(n["content"], Mapping) else {}
258
+ inputs, output = content.get("inputs") or [], content.get("output")
259
+ if any(not isinstance(i, str) or i not in nodes for i in inputs):
260
+ errors.append(f"action {n['node_id']} references an unknown input")
261
+ if output is not None and output not in nodes:
262
+ errors.append(f"action {n['node_id']} references an unknown output")
263
+ if output is not None and not any(e["source"] == n["node_id"] and e["target"] == output
264
+ and e["relation"] == "writes" for e in execution):
265
+ errors.append(f"action {n['node_id']} declares output without a writes edge")
266
+ return list(dict.fromkeys(errors))
267
+
268
+
269
+ def _event_errors(events, nodes, edges):
270
+ errors, previous = [], None
271
+ for sequence, event in enumerate(events):
272
+ body = {k: v for k, v in event.items() if k != "event_id"}
273
+ if event.get("sequence") != sequence or event.get("previous_event") != previous:
274
+ errors.append(f"event {sequence} sequence/chain changed")
275
+ if event.get("schema") != EVENT_SCHEMA or event.get("event_id") != digest(body):
276
+ errors.append(f"event {sequence} hash changed")
277
+ if event.get("kind") not in {"node", "edge"}:
278
+ errors.append(f"event {sequence} has an unsupported kind")
279
+ if event.get("kind") == "node" and event.get("object_id") not in nodes:
280
+ errors.append(f"event {sequence} references an unknown node")
281
+ if event.get("kind") == "edge" and event.get("object_id") not in edges:
282
+ errors.append(f"event {sequence} references an unknown edge")
283
+ previous = event.get("event_id")
284
+ return errors
285
+
286
+
287
+ def _snapshot_body(version, graph_id, binding_, nodes, edges, events, parent, metadata):
288
+ return {"schema": SNAPSHOT_SCHEMA, "version": version, "graph_id": graph_id,
289
+ "binding": binding_, "nodes": [nodes[k] for k in sorted(nodes)],
290
+ "edges": [edges[k] for k in sorted(edges)], "events": events,
291
+ "parent_snapshot": parent, "metadata": metadata}
292
+
293
+
294
+ def verify_snapshot(value) -> dict:
295
+ """Verify a stored sealed snapshot (every node, edge, event and the snapshot id) and return
296
+ ``{"nodes", "edges", "snapshot_id"}``; raises ``GraphSealError`` on any mismatch."""
297
+ if not isinstance(value, Mapping) or value.get("schema") != SNAPSHOT_SCHEMA:
298
+ raise GraphSealError("graph snapshot schema changed")
299
+ nodes_in, edges_in = value.get("nodes", ()), value.get("edges", ())
300
+ nodes = [node_from(item) for item in nodes_in]
301
+ edges = [edge_from(item) for item in edges_in]
302
+ version = value.get("version")
303
+ if isinstance(version, bool) or not isinstance(version, int) or version < 0:
304
+ raise GraphSealError("snapshot version must be a non-negative integer")
305
+ graph_id = _text(value.get("graph_id"), "graph_id")
306
+ by_node = {n["node_id"]: n for n in nodes}
307
+ by_edge = {e["edge_id"]: e for e in edges}
308
+ if len(by_node) != len(nodes) or len(by_edge) != len(edges):
309
+ raise GraphSealError("snapshot contains duplicate identities")
310
+ events = []
311
+ for event in value.get("events", ()):
312
+ if not isinstance(event, Mapping):
313
+ raise GraphSealError("snapshot.events must contain JSON objects")
314
+ events.append(plain(event, "snapshot.event"))
315
+ parent = value.get("parent_snapshot")
316
+ parent = None if parent is None else sha(parent, "parent_snapshot")
317
+ body = _snapshot_body(version, graph_id, binding_from(value.get("binding", {})), by_node,
318
+ by_edge, events, parent, plain(value.get("metadata", {}),
319
+ "snapshot.metadata"))
320
+ snapshot_id = digest(body)
321
+ if value.get("snapshot_id", value.get("fingerprint")) != snapshot_id:
322
+ raise GraphSealError("graph snapshot content hash changed")
323
+ errors = [f"edge {e['edge_id']} references an unknown node" for e in edges
324
+ if e["source"] not in by_node or e["target"] not in by_node]
325
+ errors += _event_errors(events, by_node, by_edge) + dag_errors(by_node, edges)
326
+ if errors:
327
+ raise GraphSealError("; ".join(dict.fromkeys(errors)))
328
+ return {"nodes": nodes, "edges": edges, "snapshot_id": snapshot_id}
329
+
330
+
331
+ # --------------------------------------------------------------------------- builder
332
+
333
+ class GraphBuilder:
334
+ """Append-only graph with the event chain of the format; ``seal`` returns the snapshot dict.
335
+
336
+ Only the constructors a recorded project's session graph uses: sources, states, actions,
337
+ outputs and edges between nodes already added.
338
+ """
339
+
340
+ def __init__(self, *, metadata=None):
341
+ self.binding = binding()
342
+ self.graph_id = digest({"schema": SCHEMA, "binding": self.binding, "version": 0})
343
+ self.metadata = plain(metadata or {}, "graph.metadata")
344
+ self.nodes, self.edges, self.events = {}, {}, []
345
+
346
+ def _event(self, kind, object_id):
347
+ previous = self.events[-1]["event_id"] if self.events else None
348
+ body = {"schema": EVENT_SCHEMA, "sequence": len(self.events), "kind": kind,
349
+ "object_id": object_id, "previous_event": previous}
350
+ self.events.append({**body, "event_id": digest(body)})
351
+
352
+ def add_node(self, value):
353
+ identifier = value["node_id"]
354
+ existing = self.nodes.get(identifier)
355
+ if existing is not None:
356
+ if existing != value:
357
+ raise GraphSealError("content-addressed node identity collision")
358
+ return identifier
359
+ self.nodes[identifier] = value
360
+ self._event("node", identifier)
361
+ return identifier
362
+
363
+ def _known(self, identifier, label):
364
+ if not isinstance(identifier, str) or identifier not in self.nodes:
365
+ raise GraphSealError(f"unknown {label} {identifier!r}")
366
+ return identifier
367
+
368
+ def add_edge(self, source, target, relation, *, graph=None, evidence_=None, metadata=None):
369
+ source = self._known(source, "edge.source")
370
+ target = self._known(target, "edge.target")
371
+ relation = _text(relation, "edge.relation")
372
+ graph = graph or ("execution" if relation in EXECUTION_RELATIONS else "knowledge")
373
+ value = edge(source, target, relation, graph=graph,
374
+ evidence_=evidence() if evidence_ is None else evidence_, metadata=metadata)
375
+ identifier = value["edge_id"]
376
+ existing = self.edges.get(identifier)
377
+ if existing is not None:
378
+ if existing != value:
379
+ raise GraphSealError("content-addressed edge identity collision")
380
+ return identifier
381
+ self.edges[identifier] = value
382
+ self._event("edge", identifier)
383
+ return identifier
384
+
385
+ @staticmethod
386
+ def source_node(source_ref, *, binding_=None, metadata=None, evidence_=None, labels=()):
387
+ ref = _text(source_ref, "source")
388
+ return node("source", {"source_ref": ref, "source_fingerprint": _ref_fingerprint(ref),
389
+ "metadata": metadata or {}},
390
+ binding_=binding_, evidence_=evidence_, labels=labels)
391
+
392
+ @staticmethod
393
+ def state_node(cut_ref, fingerprint, *, binding_=None, metadata=None):
394
+ return node("state", {"state_ref": _text(cut_ref, "state"),
395
+ "state_fingerprint": sha(fingerprint, "state.fingerprint"),
396
+ "metadata": metadata or {}}, binding_=binding_)
397
+
398
+ @staticmethod
399
+ def output_node(output_ref, *, binding_=None, metadata=None, evidence_=None, labels=()):
400
+ return node("output", {"output_ref": _text(output_ref, "output_ref"),
401
+ "metadata": metadata or {}},
402
+ binding_=binding_, evidence_=evidence_, labels=labels)
403
+
404
+ def add_action(self, act_ref, *, inputs=(), output=None, receipt_refs=(), binding_=None,
405
+ metadata=None, evidence_class="declared"):
406
+ inputs = [self._known(i, "action input") for i in inputs]
407
+ output = None if output is None else self._known(output, "action output")
408
+ content = {"act_ref": _text(act_ref, "act_ref"), "action": None, "inputs": inputs,
409
+ "output": output, "receipt_refs": _strings(receipt_refs, "action.receipt_refs"),
410
+ "reads": [], "writes": [], "invalidates": [], "metadata": metadata or {}}
411
+ ev = evidence(evidence_class)
412
+ action = self.add_node(node("action", content, binding_=binding_, evidence_=[ev]))
413
+ for item in inputs:
414
+ self.add_edge(item, action, "reads", evidence_=[ev])
415
+ if output is not None:
416
+ self.add_edge(action, output, "writes", evidence_=[ev])
417
+ return action
418
+
419
+ def seal(self):
420
+ errors = dag_errors(self.nodes, self.edges.values())
421
+ if errors:
422
+ raise GraphSealError("; ".join(errors))
423
+ body = _snapshot_body(0, self.graph_id, self.binding, self.nodes, self.edges,
424
+ list(self.events), None, self.metadata)
425
+ identifier = digest(body)
426
+ return {**body, "snapshot_id": identifier, "fingerprint": identifier}