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
mdb/serve/blobs.py ADDED
@@ -0,0 +1,280 @@
1
+ """Read recorded tensors with numpy only (no torch), verifying every digest on the way.
2
+
3
+ Two sources in a project store (saturn ``LocalStore`` layout):
4
+
5
+ * ``tensors/<ref>.safetensors``: single tensors by content address (``put_tensor``). Parsed
6
+ here with the same checks as ``LocalStore._read_tensor`` (file sha256 = ref, payload sha256 =
7
+ header metadata) because ``get_tensor`` needs torch for bfloat16; bf16 is widened exactly to
8
+ float32 (it is the top half of a float32).
9
+ * cut slots: ``cuts/<cut>.json`` -> slot page ``pages/<page>.json`` -> ``blobs/<blob>.safetensors``.
10
+ ``LocalStore.load`` hydrates these through ``safetensors.torch``; this module parses the same
11
+ bytes with numpy and checks the tensor's sha256 against the page's sealed value descriptor.
12
+
13
+ Arrays above ``MAX_ELEMENTS`` are refused, never partially read: the safetensors header is read
14
+ first (a few KiB) and the element count is checked against the limit BEFORE the payload is read
15
+ or hashed, so a huge blob costs one small read.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ from pathlib import Path
22
+
23
+ MAX_ELEMENTS = 1 << 26
24
+ MAX_HEADER = 16 << 20 # a safetensors header above this is malformed, not worth reading
25
+ MAX_FILE = 1 << 30 # largest blob file this server will read and hash
26
+ MAX_JSON = 16 << 20 # largest cut manifest / slot page this server will parse
27
+
28
+ _CODES = {"F64": "float64", "F32": "float32", "F16": "float16", "BF16": "bfloat16",
29
+ "I64": "int64", "I32": "int32", "I16": "int16", "I8": "int8", "U8": "uint8",
30
+ "U16": "uint16", "U32": "uint32", "U64": "uint64", "BOOL": "bool"}
31
+
32
+
33
+ class BlobError(LookupError):
34
+ """A tensor cannot be produced. ``refused``: found but failing verification; ``limit``:
35
+ over the size limit (refused before any payload was read)."""
36
+
37
+ def __init__(self, reason, *, refused=False, limit=False):
38
+ super().__init__(reason)
39
+ self.reason, self.refused, self.limit = reason, refused or limit, limit
40
+
41
+
42
+ def _hex(value, label):
43
+ if not isinstance(value, str) or len(value) != 64 or set(value) - set("0123456789abcdef"):
44
+ raise BlobError(f"{label} is not a sha256 hex id")
45
+ return value
46
+
47
+
48
+ def _store_file(path: Path) -> bool:
49
+ """True when ``path`` is a regular file whose real path stays under the store root (the
50
+ grandparent of every ``<root>/<dir>/<name>`` file). A symlink pointing outside the store is
51
+ treated exactly like a missing file: same answer whether or not its target exists."""
52
+ try:
53
+ real = path.resolve(strict=True)
54
+ return real.is_file() and real.is_relative_to(path.parent.parent.resolve())
55
+ except (OSError, RuntimeError, ValueError):
56
+ return False
57
+
58
+
59
+ def _read_verified(path: Path, identifier: str, label: str, max_bytes: int = MAX_FILE) -> bytes:
60
+ try:
61
+ size = path.stat().st_size if _store_file(path) else None
62
+ except OSError:
63
+ size = None
64
+ if size is None:
65
+ raise BlobError(f"{label} {identifier[:12]} is not in the store")
66
+ if size > max_bytes:
67
+ raise BlobError(f"{label} {identifier[:12]} is {size} bytes (> {max_bytes}); refused "
68
+ "before reading", limit=True)
69
+ try:
70
+ raw = path.read_bytes()
71
+ except OSError as error:
72
+ raise BlobError(f"{label} {identifier[:12]} cannot be read ({error.strerror})") from error
73
+ if hashlib.sha256(raw).hexdigest() != identifier:
74
+ raise BlobError(f"{label} {identifier[:12]} digest mismatch", refused=True)
75
+ return raw
76
+
77
+
78
+ def _json_file(path: Path, label: str, *, verify: str | None = None):
79
+ """The parsed JSON of a small store file; every failure is a ``BlobError``."""
80
+ if verify is not None:
81
+ raw = _read_verified(path, verify, label, MAX_JSON)
82
+ else:
83
+ try:
84
+ if not _store_file(path):
85
+ raise BlobError(f"{label} {path.stem[:12]} is not in the store")
86
+ if path.stat().st_size > MAX_JSON:
87
+ raise BlobError(f"{label} {path.stem[:12]} is over {MAX_JSON} bytes", limit=True)
88
+ raw = path.read_bytes()
89
+ except OSError as error:
90
+ raise BlobError(f"{label} {path.stem[:12]} cannot be read "
91
+ f"({error.strerror})") from error
92
+ try:
93
+ value = json.loads(raw)
94
+ except (ValueError, RecursionError) as error:
95
+ raise BlobError(f"{label} {path.stem[:12]} is not JSON", refused=True) from error
96
+ if not isinstance(value, dict):
97
+ raise BlobError(f"{label} {path.stem[:12]} is not a JSON object", refused=True)
98
+ return value
99
+
100
+
101
+ def _count(shape, name):
102
+ if not isinstance(shape, list) or any(
103
+ isinstance(n, bool) or not isinstance(n, int) or n < 0 for n in shape):
104
+ raise BlobError(f"tensor {name!r} has a malformed shape", refused=True)
105
+ count = 1
106
+ for n in shape:
107
+ count *= n
108
+ return count
109
+
110
+
111
+ def _precheck(path: Path, name: str, label: str):
112
+ """Read only the safetensors header of ``path`` and refuse an over-limit tensor before the
113
+ payload is read or hashed. A missing file is left to ``_read_verified``."""
114
+ if not _store_file(path):
115
+ return
116
+ try:
117
+ with path.open("rb") as handle:
118
+ head = handle.read(8)
119
+ if len(head) < 8:
120
+ return
121
+ size = int.from_bytes(head, "little")
122
+ if size < 2 or size > MAX_HEADER:
123
+ return # the verified read reports it as malformed
124
+ header = json.loads(handle.read(size))
125
+ except (OSError, ValueError, RecursionError):
126
+ return
127
+ entry = header.get(name) if isinstance(header, dict) else None
128
+ if not isinstance(entry, dict):
129
+ return
130
+ count = _count(entry.get("shape"), name)
131
+ if count > MAX_ELEMENTS:
132
+ raise BlobError(f"{label} tensor has {count} elements (> {MAX_ELEMENTS}); refused "
133
+ "before reading its payload", limit=True)
134
+
135
+
136
+ def _from_bytes(payload: bytes, dtype: str, shape):
137
+ import numpy as np
138
+
139
+ count = 1
140
+ for n in shape:
141
+ count *= n
142
+ if count > MAX_ELEMENTS:
143
+ raise BlobError(f"tensor has {count} elements (> {MAX_ELEMENTS}); refused", limit=True)
144
+ if dtype == "bfloat16":
145
+ raw = np.frombuffer(payload, dtype="<u2").astype(np.uint32) << 16
146
+ return raw.view(np.float32).reshape(shape)
147
+ little = np.dtype(dtype).newbyteorder("<")
148
+ return np.frombuffer(payload, dtype=little).reshape(shape).astype(np.dtype(dtype))
149
+
150
+
151
+ def _safetensors(raw: bytes):
152
+ if len(raw) < 8:
153
+ raise BlobError("safetensors file is truncated", refused=True)
154
+ size = int.from_bytes(raw[:8], "little")
155
+ if size < 2 or 8 + size > len(raw):
156
+ raise BlobError("safetensors header is malformed", refused=True)
157
+ try:
158
+ header = json.loads(raw[8:8 + size])
159
+ except ValueError as error:
160
+ raise BlobError("safetensors header is not JSON", refused=True) from error
161
+ return header, raw[8 + size:]
162
+
163
+
164
+ def _entry(header, data, name):
165
+ entry = header.get(name)
166
+ if not isinstance(entry, dict) or entry.get("dtype") not in _CODES:
167
+ raise BlobError(f"tensor {name!r} is absent from its blob", refused=True)
168
+ offsets = entry.get("data_offsets")
169
+ if not isinstance(offsets, list) or len(offsets) != 2 or any(
170
+ isinstance(v, bool) or not isinstance(v, int) for v in offsets):
171
+ raise BlobError(f"tensor {name!r} has malformed offsets", refused=True)
172
+ begin, end = offsets
173
+ _count(entry.get("shape"), name)
174
+ if not 0 <= begin <= end <= len(data):
175
+ raise BlobError("tensor offsets fall outside the blob", refused=True)
176
+ return _CODES[entry["dtype"]], list(entry["shape"]), data[begin:end]
177
+
178
+
179
+ def tensor_blob(store_root: Path, ref: str):
180
+ """``(array, info)`` for a ``put_tensor`` blob."""
181
+ ref = _hex(ref, "tensor ref")
182
+ path = Path(store_root) / "tensors" / f"{ref}.safetensors"
183
+ _precheck(path, "tensor", "tensor")
184
+ raw = _read_verified(path, ref, "tensor")
185
+ header, data = _safetensors(raw)
186
+ meta = header.get("__metadata__") or {}
187
+ dtype, shape, payload = _entry(header, data, "tensor")
188
+ if hashlib.sha256(payload).hexdigest() != meta.get("sha256"):
189
+ raise BlobError("tensor payload digest mismatch", refused=True)
190
+ array = _from_bytes(payload, dtype, shape)
191
+ return array, {"shape": shape, "dtype": dtype, "sha256": meta["sha256"],
192
+ "via": [f"tensors/{ref[:12]}", "payload sha256 verified"]}
193
+
194
+
195
+ def _navigate(encoded, described, item, slot):
196
+ if encoded.get("kind") == "tensor":
197
+ if item is not None:
198
+ raise BlobError(f"slot {slot!r} holds one tensor; no item index")
199
+ return encoded["name"], described
200
+ if encoded.get("kind") in ("list", "tuple"):
201
+ items, descs = encoded.get("items") or [], (described or {}).get("items") or []
202
+ if item is None:
203
+ raise BlobError(f"slot {slot!r} is a sequence of {len(items)}; give an item index")
204
+ if not 0 <= item < len(items) or items[item].get("kind") != "tensor":
205
+ raise BlobError(f"slot {slot!r} has no tensor at item {item}")
206
+ return items[item]["name"], descs[item] if item < len(descs) else None
207
+ if encoded.get("kind") == "scalar":
208
+ raise BlobError(f"slot {slot!r} holds no tensor at this cut (scalar "
209
+ f"{encoded.get('value')!r})")
210
+ raise BlobError(f"slot {slot!r} has unsupported kind {encoded.get('kind')!r}")
211
+
212
+
213
+ def _slot_page(root: Path, cut: str, slot: str):
214
+ """``(page_id, page)`` of a retained slot after checking the cut manifest and page digests."""
215
+ from saturn.values import digest
216
+
217
+ cut = _hex(cut, "cut id")
218
+ metadata = _json_file(root / "cuts" / f"{cut}.json", "cut")
219
+ try:
220
+ sealed = metadata.get("fingerprint") == cut and digest(metadata.get("manifest")) == cut
221
+ except (TypeError, ValueError) as error:
222
+ raise BlobError("cut manifest is malformed", refused=True) from error
223
+ if not sealed:
224
+ raise BlobError("cut manifest digest mismatch", refused=True)
225
+ slots = metadata.get("slots")
226
+ page_id = slots.get(slot) if isinstance(slots, dict) else None
227
+ if page_id is None:
228
+ raise BlobError(f"cut {cut[:12]} retains no slot {slot!r}")
229
+ page = _json_file(root / "pages" / f"{_hex(page_id, 'page')}.json", "slot page",
230
+ verify=page_id)
231
+ return page_id, page
232
+
233
+
234
+ def _navigated(page, item, slot):
235
+ try:
236
+ return _navigate(page.get("encoded") or {}, page.get("value"), item, slot)
237
+ except (KeyError, TypeError, AttributeError) as error:
238
+ raise BlobError(f"slot {slot!r} has a malformed page", refused=True) from error
239
+
240
+
241
+ def cut_slot(store_root: Path, cut: str, slot: str, item: int | None = None):
242
+ """``(array, info)`` for one tensor of a retained cut slot."""
243
+ root = Path(store_root)
244
+ page_id, page = _slot_page(root, cut, slot)
245
+ name, described = _navigated(page, item, slot)
246
+ blob = page.get("tensor_blob")
247
+ if blob is None:
248
+ raise BlobError(f"slot {slot!r} page has no tensor blob", refused=True)
249
+ path = root / "blobs" / f"{_hex(blob, 'blob')}.safetensors"
250
+ _precheck(path, name, "slot")
251
+ header, data = _safetensors(_read_verified(path, blob, "slot blob"))
252
+ dtype, shape, payload = _entry(header, data, name)
253
+ described = described if isinstance(described, dict) else {}
254
+ expected = described.get("sha256")
255
+ if expected is None or hashlib.sha256(payload).hexdigest() != expected:
256
+ raise BlobError("slot tensor bytes differ from the sealed descriptor", refused=True)
257
+ if list(described.get("shape") or shape) != shape:
258
+ raise BlobError("slot tensor shape differs from the sealed descriptor", refused=True)
259
+ array = _from_bytes(payload, dtype, shape)
260
+ return array, {"shape": shape, "dtype": dtype, "sha256": expected,
261
+ "via": [f"cut {cut[:12]}", f"slot {slot}" + ("" if item is None else
262
+ f"[{item}]"),
263
+ f"page {page_id[:12]}", f"blob {blob[:12]}",
264
+ "tensor sha256 verified against the sealed descriptor"]}
265
+
266
+
267
+ def slot_info(store_root: Path, cut: str, slot: str, item: int | None = None):
268
+ """Shape/dtype of a cut slot tensor from its sealed page descriptor (no tensor bytes read).
269
+
270
+ Raises ``BlobError`` (never another exception) when the cut, page or tensor blob is missing:
271
+ the caller reports that as unresolved."""
272
+ root = Path(store_root)
273
+ _, page = _slot_page(root, cut, slot)
274
+ _, described = _navigated(page, item, slot)
275
+ blob = page.get("tensor_blob")
276
+ if blob is None or not _store_file(root / "blobs" / f"{_hex(blob, 'blob')}.safetensors"):
277
+ raise BlobError(f"slot {slot!r} tensor blob is not in the store")
278
+ described = described if isinstance(described, dict) else {}
279
+ return {"shape": described.get("shape"), "dtype": str(described.get("dtype", "")).replace(
280
+ "torch.", "")}
mdb/serve/caps.py ADDED
@@ -0,0 +1,148 @@
1
+ """The 64 KiB response cap, canonical JSON, envelopes and explicit ``omitted`` bookkeeping.
2
+
3
+ Every API response is canonical JSON (sorted keys, no whitespace, UTF-8, no NaN). The ASGI
4
+ middleware ``CapMiddleware`` measures each ``/api/`` response body and replaces one that is over
5
+ the cap with ``{"refused": "over_cap", "bytes": N, "cap": CAP}`` (HTTP 413). It never truncates.
6
+ Views also bound their own lists (``take``) and say what they left out (``Omitted``).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import math
13
+ from typing import Any
14
+
15
+ from .schema import CAP_BYTES, SCHEMAS, Omitted, Refused, unresolved
16
+
17
+ NONFINITE = "non-finite in the stored body"
18
+
19
+
20
+ def nonfinite() -> dict:
21
+ """The wire form of a NaN/inf from a stored body: an unresolved number that says why."""
22
+ return unresolved(NONFINITE).model_dump(mode="json")
23
+
24
+
25
+ def canonical(value: Any) -> bytes:
26
+ """Canonical JSON bytes. Text is UTF-8; a string no UTF-8 can hold (a lone surrogate in a
27
+ stored body) makes the whole value fall back to ``\\uXXXX`` escapes, still valid JSON, so the
28
+ bytes counted against the cap are the bytes sent."""
29
+ try:
30
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
31
+ allow_nan=False).encode("utf-8")
32
+ except UnicodeEncodeError:
33
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True,
34
+ allow_nan=False).encode("ascii")
35
+
36
+
37
+ def dump(model) -> Any:
38
+ """Plain JSON of a pydantic model (wire names)."""
39
+ if hasattr(model, "model_dump"):
40
+ return model.model_dump(mode="json", by_alias=True)
41
+ if isinstance(model, list):
42
+ return [dump(m) for m in model]
43
+ return model
44
+
45
+
46
+ def envelope(view: str, data, omitted: list[Omitted] | None = None, *, state: str = "resolved",
47
+ reason: str | None = None) -> dict:
48
+ """``{schema, state, data, digest, bytes, omitted?, reason?}``; digest and bytes are over
49
+ canonical data. ``state`` is resolved, unresolved or refused; a state other than resolved
50
+ must carry a ``reason``."""
51
+ if state != "resolved" and not reason:
52
+ raise ValueError(f"a {state} envelope says why")
53
+ plain = dump(data)
54
+ raw = canonical(plain)
55
+ out = {"schema": SCHEMAS[view], "state": state, "data": plain,
56
+ "digest": hashlib.sha256(raw).hexdigest(),
57
+ "bytes": len(raw)}
58
+ if reason:
59
+ out["reason"] = reason
60
+ if omitted:
61
+ out["omitted"] = [dump(o) for o in omitted]
62
+ return out
63
+
64
+
65
+ def refused(reason: str, detail: str | None = None, **extra) -> dict:
66
+ model = Refused(refused=reason, detail=None if detail is None else str(detail)[:2000], **extra)
67
+ return model.model_dump(mode="json", exclude_none=True)
68
+
69
+
70
+ def take(items, limit: int, field: str, omitted: list[Omitted], *, reason: str | None = None):
71
+ """The first ``limit`` items; records how many were left out under ``field``."""
72
+ items = list(items)
73
+ if len(items) > limit:
74
+ omitted.append(Omitted(field=field, count=len(items) - limit, reason=reason))
75
+ return items[:limit]
76
+ return items
77
+
78
+
79
+ def bound_json(value: Any, *, field: str, omitted: list[Omitted], max_items: int = 16,
80
+ max_text: int = 512, depth: int = 0) -> Any:
81
+ """A JSON value with long lists and strings cut, each cut recorded in ``omitted``."""
82
+ if depth > 8:
83
+ omitted.append(Omitted(field=field, count=1, reason="nested deeper than 8 levels"))
84
+ return None
85
+ if isinstance(value, dict):
86
+ out = {}
87
+ keys = sorted(value)
88
+ if len(keys) > 4 * max_items:
89
+ omitted.append(Omitted(field=field, count=len(keys) - 4 * max_items,
90
+ reason="keys beyond the first (sorted)"))
91
+ keys = keys[:4 * max_items]
92
+ for key in keys:
93
+ out[key] = bound_json(value[key], field=f"{field}.{key}", omitted=omitted,
94
+ max_items=max_items, max_text=max_text, depth=depth + 1)
95
+ return out
96
+ if isinstance(value, (list, tuple)):
97
+ items = list(value)
98
+ if len(items) > max_items:
99
+ omitted.append(Omitted(field=field, count=len(items) - max_items,
100
+ reason="list items beyond the first"))
101
+ items = items[:max_items]
102
+ return [bound_json(v, field=f"{field}[{i}]", omitted=omitted, max_items=max_items,
103
+ max_text=max_text, depth=depth + 1) for i, v in enumerate(items)]
104
+ if isinstance(value, str) and len(value) > max_text:
105
+ omitted.append(Omitted(field=field, count=len(value) - max_text,
106
+ reason="characters beyond the first"))
107
+ return value[:max_text]
108
+ if isinstance(value, float) and not math.isfinite(value):
109
+ return nonfinite()
110
+ return value
111
+
112
+
113
+ class CapMiddleware:
114
+ """Pure ASGI middleware: buffer ``/api/`` HTTP bodies and refuse ones over the cap."""
115
+
116
+ def __init__(self, app, cap: int = CAP_BYTES):
117
+ self.app, self.cap = app, cap
118
+
119
+ async def __call__(self, scope, receive, send):
120
+ if scope["type"] != "http" or not scope.get("path", "").startswith("/api/"):
121
+ await self.app(scope, receive, send)
122
+ return
123
+ start, chunks = {}, []
124
+
125
+ async def capture(message):
126
+ if message["type"] == "http.response.start":
127
+ start.update(message)
128
+ return
129
+ if message["type"] == "http.response.body":
130
+ chunks.append(message.get("body", b""))
131
+ if message.get("more_body"):
132
+ return
133
+ body = b"".join(chunks)
134
+ status, headers = start["status"], list(start.get("headers", []))
135
+ if len(body) > self.cap:
136
+ body = canonical(refused("over_cap", bytes=len(body), cap=self.cap))
137
+ status = 413
138
+ headers = [(k, v) for k, v in headers if k.lower() != b"content-type"]
139
+ headers.append((b"content-type", b"application/json"))
140
+ headers = [(k, v) for k, v in headers if k.lower() != b"content-length"]
141
+ headers.append((b"content-length", str(len(body)).encode()))
142
+ await send({"type": "http.response.start", "status": status,
143
+ "headers": headers})
144
+ await send({"type": "http.response.body", "body": body})
145
+ return
146
+ await send(message)
147
+
148
+ await self.app(scope, receive, capture)
mdb/serve/export.py ADDED
@@ -0,0 +1,9 @@
1
+ """Walkthrough export (static bundle of records and pointers). Not available yet: the route refuses."""
2
+ from __future__ import annotations
3
+
4
+ from .caps import refused
5
+
6
+
7
+ def export_walkthrough():
8
+ return refused("not_implemented",
9
+ "walkthrough export has no command yet; nothing was written")
mdb/serve/guard.py ADDED
@@ -0,0 +1,216 @@
1
+ """The outermost ASGI layer of ``mdb serve``: who may talk to the server, how much they may
2
+ send, and the security headers on every response (including 4xx and the catch-all 500).
3
+
4
+ Pure ASGI (no framework import), wrapped *around* the FastAPI app so that responses produced by
5
+ Starlette's own error middleware (the 500 path) pass through it too.
6
+
7
+ * Host guard (``http`` and ``websocket``): the ``Host`` header must be one of the loopback names
8
+ with the bound port (``127.0.0.1:P``, ``localhost:P``, ``[::1]:P``; the bare forms when ``P``
9
+ is 80) or an explicit ``--allow-host``; an ``Origin`` header, when present, must be
10
+ ``http://`` plus one of those hosts. This is what stops DNS rebinding and cross-site requests
11
+ from a browser: a foreign page can reach loopback, but it cannot make the browser send a
12
+ loopback ``Host``/``Origin``. A request whose ``Sec-Fetch-Site`` (set by the browser, not by
13
+ page script) is anything but ``same-origin`` or ``none`` is refused too: a cross-site
14
+ ``<img>``/``<script>`` GET carries no ``Origin`` but does carry ``Sec-Fetch-Site:
15
+ cross-site``, and could otherwise queue work on a live session. A request without the header
16
+ (curl, older browsers) is judged by Host/Origin alone. Refusals are 403
17
+ (``host_not_allowed``, ``origin_not_allowed``, ``cross_site``); a missing ``Host`` is 400; a
18
+ WebSocket is closed before it is accepted.
19
+ * Body limit: request bodies above ``body_limit`` bytes are refused 413 ``over_limit``. Streamed
20
+ bytes are counted (``Content-Length`` is not trusted) and nothing past the limit is buffered.
21
+ * Headers: CSP, ``X-Content-Type-Options``, ``Referrer-Policy``, ``Cross-Origin-Resource-Policy``
22
+ and ``Cache-Control`` on every HTTP response. An exception that escapes the app becomes a 500
23
+ ``internal_error`` that names no exception text, path or traceback (those go to the log).
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+
29
+ from .caps import canonical, refused
30
+
31
+ LOG = logging.getLogger("mdb.serve")
32
+ BODY_LIMIT = 256 * 1024
33
+ CSP = ("default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; "
34
+ "connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; "
35
+ "frame-ancestors 'none'")
36
+ LOOPBACK_NAMES = ("127.0.0.1", "localhost", "[::1]")
37
+ FETCH_SITES = ("same-origin", "none") # Sec-Fetch-Site values accepted when the header is sent
38
+
39
+
40
+ def _split(entry):
41
+ """``(name, port or None)`` of ``HOST``, ``HOST:PORT``, ``[v6]`` or ``[v6]:PORT``."""
42
+ entry = entry.strip().lower()
43
+ if entry.startswith("["):
44
+ name, _, rest = entry.partition("]")
45
+ return name + "]", (rest[1:] if rest.startswith(":") else None) or None
46
+ name, _, port = entry.partition(":")
47
+ return name, port or None
48
+
49
+
50
+ def allowed_hosts(port, extra=()):
51
+ """The accepted ``Host`` header values (lower case) for a bound ``port``.
52
+
53
+ ``extra`` entries are ``HOST`` (taken as ``HOST:port``) or ``HOST:PORT`` (exact). The bare
54
+ form of a name is accepted only when the port is 80. ``port`` None (embedding and tests;
55
+ the CLI always passes the real port) leaves the loopback names to ``HostMatcher.ok``."""
56
+ hosts = set()
57
+ for entry in (*LOOPBACK_NAMES, *extra):
58
+ name, given = _split(entry)
59
+ if not name:
60
+ continue
61
+ if given is not None:
62
+ hosts.add(f"{name}:{given}")
63
+ elif port is not None:
64
+ hosts.add(f"{name}:{port}")
65
+ if port == 80:
66
+ hosts.add(name)
67
+ return hosts
68
+
69
+
70
+ class HostMatcher:
71
+ def __init__(self, port, extra=()):
72
+ self.port, self.exact = port, allowed_hosts(port, extra)
73
+
74
+ def ok(self, host: str) -> bool:
75
+ host = host.strip().lower()
76
+ if host in self.exact:
77
+ return True
78
+ if self.port is None:
79
+ name, given = _split(host)
80
+ return name in LOOPBACK_NAMES and given is not None and given.isdigit()
81
+ return False
82
+
83
+
84
+ _DUPLICATE = object()
85
+
86
+
87
+ def _header(scope, name: bytes):
88
+ """The header's value, None when absent, ``_DUPLICATE`` when it occurs more than once."""
89
+ found = [value for key, value in scope.get("headers") or () if key == name]
90
+ if len(found) > 1:
91
+ return _DUPLICATE
92
+ return found[0].decode("latin-1") if found else None
93
+
94
+
95
+ class _BodyTooLarge(Exception):
96
+ pass
97
+
98
+
99
+ class SecurityLayer:
100
+ def __init__(self, app, *, port=None, allow_hosts=(), body_limit=BODY_LIMIT, csp=CSP):
101
+ self.app, self.hosts, self.body_limit, self.csp = app, HostMatcher(port, allow_hosts), \
102
+ body_limit, csp
103
+ self.state = getattr(app, "state", None)
104
+
105
+ # -- helpers
106
+ def _security_headers(self, path):
107
+ return [(b"content-security-policy", self.csp.encode()),
108
+ (b"x-content-type-options", b"nosniff"),
109
+ (b"referrer-policy", b"no-referrer"),
110
+ (b"cross-origin-resource-policy", b"same-origin"),
111
+ (b"cache-control", b"no-store" if path.startswith("/api/") else b"no-cache")]
112
+
113
+ async def _respond(self, scope, send, status, reason, detail, **extra):
114
+ body = canonical(refused(reason, detail, **extra))
115
+ headers = [(b"content-type", b"application/json"),
116
+ (b"content-length", str(len(body)).encode()),
117
+ *self._security_headers(scope.get("path", ""))]
118
+ await send({"type": "http.response.start", "status": status, "headers": headers})
119
+ await send({"type": "http.response.body", "body": body})
120
+
121
+ def _check(self, scope):
122
+ """``(status, reason, detail)`` when the request must be refused, else None."""
123
+ host = _header(scope, b"host")
124
+ site = _header(scope, b"sec-fetch-site")
125
+ if host is _DUPLICATE or _header(scope, b"origin") is _DUPLICATE or site is _DUPLICATE:
126
+ return 403, "duplicate_header", ("a Host, Origin or Sec-Fetch-Site header occurs "
127
+ "more than once")
128
+ if host is None or not host.strip():
129
+ return 400, "missing_host", "the request has no Host header"
130
+ if not self.hosts.ok(host):
131
+ return 403, "host_not_allowed", "this server answers only to its own loopback " \
132
+ "address (or an --allow-host); a foreign Host is refused"
133
+ origin = _header(scope, b"origin")
134
+ if origin is not None:
135
+ origin = origin.strip().lower()
136
+ if not origin.startswith("http://") or not self.hosts.ok(origin[len("http://"):]):
137
+ return 403, "origin_not_allowed", "the Origin is not this server"
138
+ if site is not None and site.strip().lower() not in FETCH_SITES:
139
+ return 403, "cross_site", ("the browser says this request comes from another site "
140
+ f"(Sec-Fetch-Site: {site.strip()[:32]}); only this "
141
+ "server's own pages may call it")
142
+ return None
143
+
144
+ # -- ASGI
145
+ async def __call__(self, scope, receive, send):
146
+ kind = scope["type"]
147
+ if kind not in ("http", "websocket"):
148
+ await self.app(scope, receive, send)
149
+ return
150
+ verdict = self._check(scope)
151
+ if verdict is not None:
152
+ if kind == "websocket":
153
+ await receive() # websocket.connect
154
+ await send({"type": "websocket.close", "code": 1008})
155
+ else:
156
+ await self._respond(scope, send, *verdict)
157
+ return
158
+ if kind == "websocket":
159
+ await self.app(scope, receive, send)
160
+ return
161
+ await self._http(scope, receive, send)
162
+
163
+ async def _http(self, scope, receive, send):
164
+ state = {"started": False, "over": False}
165
+ limit = self.body_limit
166
+
167
+ async def refuse_over(received):
168
+ state["over"] = True
169
+ if not state["started"]:
170
+ state["started"] = True
171
+ await self._respond(scope, send, 413, "over_limit",
172
+ f"request body is over the {limit} byte limit"
173
+ + ("" if received is None else f" (saw {received} bytes)"),
174
+ cap=limit)
175
+
176
+ declared = _header(scope, b"content-length")
177
+ if declared is not None and declared.strip().isdigit() and int(declared) > limit:
178
+ await refuse_over(None)
179
+ return
180
+ seen = 0
181
+
182
+ async def guarded_receive():
183
+ nonlocal seen
184
+ if state["over"]:
185
+ return {"type": "http.disconnect"}
186
+ message = await receive()
187
+ if message["type"] == "http.request":
188
+ seen += len(message.get("body", b""))
189
+ if seen > limit:
190
+ await refuse_over(seen)
191
+ return {"type": "http.disconnect"}
192
+ return message
193
+
194
+ async def guarded_send(message):
195
+ if state["over"]:
196
+ return
197
+ if message["type"] == "http.response.start":
198
+ state["started"] = True
199
+ skip = {b"content-security-policy", b"x-content-type-options", b"referrer-policy",
200
+ b"cross-origin-resource-policy", b"cache-control"}
201
+ headers = [(k, v) for k, v in message.get("headers", []) if k.lower() not in skip]
202
+ message = {**message, "headers": headers
203
+ + self._security_headers(scope.get("path", ""))}
204
+ await send(message)
205
+
206
+ try:
207
+ await self.app(scope, guarded_receive, guarded_send)
208
+ except Exception: # noqa: BLE001 - nothing may escape to the client as a traceback
209
+ if state["over"]:
210
+ return
211
+ LOG.exception("unhandled error serving %s %s", scope.get("method"),
212
+ scope.get("path"))
213
+ if not state["started"]:
214
+ state["started"] = True
215
+ await self._respond(scope, send, 500, "internal_error",
216
+ "the server failed on this request; see its log")