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/_legacy.py ADDED
@@ -0,0 +1,97 @@
1
+ """The one place ``mdb serve`` reads a recorded project: thin calls into ``mdb.core.project_read``.
2
+
3
+ Historically this module wrapped the flat ``mdb.project`` lane modules; it now wraps the engine
4
+ reader (standard library + ``saturn`` + ``mdb.core``) and keeps its function names, so views
5
+ and tests that patch these names are unchanged. Every function is a read; none writes to the
6
+ project or creates a table.
7
+
8
+ Listing functions take ``refuse(kind, identifier, error)``: a bad row is reported through it and
9
+ skipped (strict when it is omitted). Cuts and receipts stay strict: a session whose execution
10
+ history does not verify is refused as a whole by ``Recorded``.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from ..core.project_read import ProjectReader
15
+ from ..core.project_read import lifecycle_reads as _lifecycle_reads
16
+
17
+
18
+ def open_project(root):
19
+ """A ``ProjectReader`` over ``root``: every sqlite connection is read-only (``mode=ro`` with
20
+ ``immutable=1`` unless a ``-wal`` file exists; ``PRAGMA query_only=ON``). A WAL project in an
21
+ unwritable directory raises ``ValueError`` at open."""
22
+ return ProjectReader(root)
23
+
24
+
25
+ def sessions(project):
26
+ """Session ids (``SELECT id FROM sessions``): a corrupt session row hides no other session."""
27
+ return project.sessions()
28
+
29
+
30
+ def session_row(project, sid):
31
+ """Session row: identity, execution, selected, debug_info (JSON text), revision."""
32
+ return project.session(sid)
33
+
34
+
35
+ def cut_ids(project, sid):
36
+ return project.cut_ids(sid)
37
+
38
+
39
+ def cut_descriptor(project, sid, cut):
40
+ """Verified cut metadata: execution_point, surface, parent, boundary, manifest."""
41
+ return project.cut_descriptor(sid, cut)
42
+
43
+
44
+ def receipts(project, sid):
45
+ """Verified native receipts as dicts."""
46
+ return project.receipts(sid)
47
+
48
+
49
+ def symbols(project, sid, refuse=None):
50
+ return project.symbols(sid) if refuse is None else project.symbols(sid, refuse=refuse)
51
+
52
+
53
+ def slice_ids(project, sid):
54
+ return project.slice_ids(sid)
55
+
56
+
57
+ def slice_record(project, sid, slice_id):
58
+ """Verified sealed slice dict."""
59
+ return project.slice_record(sid, slice_id)
60
+
61
+
62
+ def symbol_lifecycles(project, sid, refuse=None):
63
+ """Verified lifecycle rows (``lifecycle_id``, ``lifecycle``, ``joins``)."""
64
+ return (project.symbol_lifecycles(sid) if refuse is None
65
+ else project.symbol_lifecycles(sid, refuse=refuse))
66
+
67
+
68
+ def findings(project, sid, refuse=None):
69
+ """State annotations tagged ``finding`` (``annotation_id``, ``details``, ...)."""
70
+ return project.findings(sid) if refuse is None else project.findings(sid, refuse=refuse)
71
+
72
+
73
+ def session_graph(project, sid, refuse=None):
74
+ """The sealed session state graph (snapshot dict); rows that cannot be placed are left out
75
+ and reported through ``refuse``."""
76
+ return (project.session_graph(sid) if refuse is None
77
+ else project.session_graph(sid, refuse=refuse))
78
+
79
+
80
+ def store_root(project):
81
+ """The saturn LocalStore directory (read by ``serve.blobs``)."""
82
+ return project.store.root
83
+
84
+
85
+ def tensor_info(project, ref):
86
+ """Shape/dtype of a stored tensor (no bytes materialised)."""
87
+ return project.tensor_info(ref)
88
+
89
+
90
+ def db(project):
91
+ """Read-only sqlite connection context (serve only runs SELECTs through it)."""
92
+ return project._db()
93
+
94
+
95
+ def lifecycle_reads(body):
96
+ """Attention reads recorded in a symbol lifecycle body, as sealed read dicts."""
97
+ return _lifecycle_reads(body)
mdb/serve/app.py ADDED
@@ -0,0 +1,526 @@
1
+ """FastAPI application over a recorded project: ``create_app(project_path, live=None)``.
2
+
3
+ With ``live`` (a ``serve.live.LiveSession``: ``mdb serve --tiny|--model``) the server also holds
4
+ a live debugger under that session's id: ``POST .../op`` dispatches through the op registry on
5
+ the session's worker thread, ``POST .../console`` runs a REPL command line, ``POST
6
+ .../interrupt`` delivers Ctrl-C to the running op, ``GET .../live`` and ``.../live/timeline``
7
+ are the live frame and clock (``GET .../live/items`` pages through a frame list the frame
8
+ shortened; ``GET .../live/ledger`` lists the run's circuits, forecasts and declared symbols), ``POST .../reduce`` with an occurrence pointer reads the live run the way ``print``
9
+ does (``serve.live_reduce``; nothing is written to the project), and the events socket pushes
10
+ one ``op`` event per completed op. Without ``live`` every op whose effect is not ``read`` is
11
+ refused 403.
12
+
13
+ Messages never name the server's absolute project path: refusal details, op results and console
14
+ text show it as ``<project>`` (paths inside it stay relative to it).
15
+
16
+ Routes live under ``/api/v1``; every body is a canonical-JSON ``Envelope`` or a ``Refused``
17
+ (``{"refused": reason, "detail"?}``), at most 64 KiB (``CapMiddleware``). The built web app is
18
+ served from ``mdb/serve/static`` when present. ``create_app`` returns the FastAPI app wrapped in
19
+ ``guard.SecurityLayer`` (Host/Origin guard, request body limit, security headers on every
20
+ response, no-traceback 500s) as the outermost ASGI layer.
21
+ """
22
+ # No ``from __future__ import annotations`` here: FastAPI resolves route annotations at
23
+ # runtime, and ``WebSocket`` is imported inside ``create_app`` (FastAPI stays an optional extra).
24
+ import asyncio
25
+ import contextlib
26
+ import inspect
27
+ import signal
28
+ import threading
29
+ import time
30
+ from pathlib import Path
31
+
32
+ from .caps import CapMiddleware, bound_json, canonical, dump, envelope, refused, take
33
+ from .guard import BODY_LIMIT, CSP, SecurityLayer # noqa: F401 - CSP re-exported
34
+ from .recorded import Recorded, SessionUnreadable
35
+ from .reduce import ReduceError, Reducer
36
+ from .schema import (
37
+ CAP_BYTES,
38
+ ConsoleRequest,
39
+ ConsoleResult,
40
+ Event,
41
+ Interrupt,
42
+ LiveState,
43
+ Omitted,
44
+ OpRequest,
45
+ OpResult,
46
+ ReduceRequest,
47
+ ViewAvail,
48
+ )
49
+ from .views import frame as frame_view
50
+ from .views import graph as graph_view
51
+ from .views import live as live_view
52
+ from .views import records as records_view
53
+ from .views import sessions as sessions_view
54
+ from .views import symbols as symbols_view
55
+ from .views import timeline as timeline_view
56
+ from .views.common import ViewError
57
+
58
+ STATIC = Path(__file__).resolve().parent / "static"
59
+ MAX_BRANCH_NODES = 256
60
+ TICK = 0.2 # seconds between looks at the shutdown flag in the event sockets
61
+ WRITE_EFFECTS = ("navigate", "mutate", "native")
62
+
63
+
64
+ def create_app(project_path, *, read_only=True, static_dir=None, heartbeat=10.0, cap=CAP_BYTES,
65
+ port=None, allow_hosts=(), body_limit=BODY_LIMIT, live=None):
66
+ """The server as an ASGI app. ``port`` is the bound port (the Host guard accepts the loopback
67
+ names with it; None accepts any port on them, for embedding and tests); ``allow_hosts`` are
68
+ extra ``HOST[:PORT]`` values to accept (see ``guard``). ``live``: a ``LiveSession`` whose
69
+ debugger is attached with this project (live mode; ``read_only`` is then False)."""
70
+ from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
71
+ from fastapi.exceptions import RequestValidationError
72
+ from fastapi.responses import FileResponse, Response
73
+ from starlette.concurrency import run_in_threadpool
74
+ from starlette.exceptions import HTTPException as StarletteHTTPException
75
+
76
+ from .live import Busy, Interrupted
77
+
78
+ stopping = threading.Event() # set by ``app.state.stop()``: the event sockets say goodbye
79
+
80
+ if live is not None:
81
+ read_only = False
82
+ recorded = Recorded(project_path)
83
+ reducer = Reducer()
84
+ contexts = {} # session id -> mdb.ops.Context (no debugger attached: recorded project)
85
+ static = Path(static_dir) if static_dir else STATIC
86
+ @contextlib.asynccontextmanager
87
+ async def lifespan(_app):
88
+ """Under uvicorn, tell the event sockets to close the moment SIGTERM/SIGINT arrives:
89
+ uvicorn's graceful exit waits for open websockets, so an open browser tab made the
90
+ first signal look ignored. A running live op is interrupted too, or uvicorn waits for
91
+ its request until the graceful timeout. Uvicorn installs its handlers before the
92
+ lifespan starts; each is wrapped, not replaced. Off the main thread (tests) nothing is
93
+ wrapped."""
94
+ wrapped = []
95
+ loop = asyncio.get_running_loop()
96
+ if threading.current_thread() is threading.main_thread():
97
+ for name in ("SIGTERM", "SIGINT"):
98
+ number = getattr(signal, name)
99
+ previous = signal.getsignal(number)
100
+ if not callable(previous):
101
+ continue
102
+
103
+ def handler(sig, frame, previous=previous):
104
+ stopping.set()
105
+ if live is not None: # on the loop: the handler may interrupt live's lock
106
+ loop.call_soon_threadsafe(live.interrupt)
107
+ previous(sig, frame)
108
+
109
+ signal.signal(number, handler)
110
+ wrapped.append((number, handler, previous))
111
+ try:
112
+ yield
113
+ finally:
114
+ stopping.set()
115
+ for number, handler, previous in wrapped:
116
+ if signal.getsignal(number) is handler:
117
+ signal.signal(number, previous)
118
+
119
+ app = FastAPI(title="mdb serve", docs_url=None, redoc_url=None, openapi_url=None,
120
+ lifespan=lifespan)
121
+ app.state.recorded, app.state.read_only = recorded, read_only
122
+ app.state.reducer, app.state.live = reducer, live
123
+ app.state.stop = stopping.set # the server is going down: close the event sockets
124
+
125
+ roots = sorted({str(Path(project_path)), str(Path(project_path).expanduser().resolve()),
126
+ *((str(live.debugger.project.root),) if live is not None
127
+ and live.debugger.project is not None else ())}, key=len, reverse=True)
128
+
129
+ def scrub(value):
130
+ """``value`` with the absolute project path written ``<project>``."""
131
+ if isinstance(value, str):
132
+ for root in roots:
133
+ if root and root != "." and root in value:
134
+ value = value.replace(root, "<project>")
135
+ return value
136
+ if isinstance(value, dict):
137
+ return {k: scrub(v) for k, v in value.items()}
138
+ if isinstance(value, list):
139
+ return [scrub(v) for v in value]
140
+ return value
141
+
142
+ def respond(body, status=200):
143
+ if isinstance(body, dict) and "refused" in body:
144
+ body = scrub(body)
145
+ return Response(canonical(body), status_code=status, media_type="application/json")
146
+
147
+ def web_avail():
148
+ if (static / "index.html").is_file():
149
+ return ViewAvail(available=True)
150
+ return ViewAvail(available=False, reason="web build absent (mdb/serve/static); run "
151
+ "`npm run build` in packages/mdb/web of a checkout and install from "
152
+ "it (docs/INSTALL.md)")
153
+
154
+ def model(sid):
155
+ try:
156
+ return recorded.model(sid)
157
+ except KeyError as error:
158
+ raise ViewError("not_found", f"unknown session {sid!r}", 404) from error
159
+ except SessionUnreadable as error:
160
+ raise ViewError("session_unreadable", error.reason, 409) from error
161
+
162
+ def is_live(sid):
163
+ return live is not None and sid == live.sid
164
+
165
+ def not_live(sid, what):
166
+ if live is None:
167
+ return ViewError("not_live", f"{what} needs a live session; this server holds none "
168
+ "(start it with --tiny or --model)", 403)
169
+ return ViewError("not_live", f"{what}: session {sid!r} is recorded; the live session "
170
+ f"is {live.sid!r}", 403)
171
+
172
+ async def on_worker(future, http=None):
173
+ """Await a live job; a full queue is 409 ``busy``, an interrupted read 409. With ``http``
174
+ (the request), a client that disconnects before the job ends cancels that job
175
+ (``LiveSession.cancel``: a running op or console line is interrupted, a queued job never
176
+ runs), so an abandoned request does not hold the single worker."""
177
+ watcher = None
178
+ if http is not None:
179
+ async def watch_client():
180
+ while not future.done():
181
+ if await http.is_disconnected():
182
+ live.cancel(future)
183
+ return
184
+ await asyncio.sleep(0.05)
185
+
186
+ watcher = asyncio.ensure_future(watch_client())
187
+ try:
188
+ return await asyncio.wrap_future(future)
189
+ except Interrupted as error:
190
+ raise ViewError("interrupted", "the request was interrupted before it finished",
191
+ 409) from error
192
+ finally:
193
+ if watcher is not None:
194
+ watcher.cancel()
195
+
196
+ def submit(make, *args):
197
+ try:
198
+ return make(*args)
199
+ except Busy as error:
200
+ raise ViewError("busy", f"the live session is busy: {error}; retry after the "
201
+ "running op finishes (or interrupt it)", 409) from error
202
+
203
+ @app.exception_handler(ViewError)
204
+ async def _view_error(request: Request, error: ViewError):
205
+ return respond(refused(error.reason, error.detail), error.status)
206
+
207
+ @app.exception_handler(ReduceError)
208
+ async def _reduce_error(request: Request, error: ReduceError):
209
+ return respond(refused(error.reason, error.detail), error.status)
210
+
211
+ @app.exception_handler(RequestValidationError)
212
+ async def _invalid(request: Request, error: RequestValidationError):
213
+ detail = "; ".join(f"{'.'.join(str(p) for p in e.get('loc', ()))}: {e.get('msg')}"
214
+ for e in error.errors()[:8])
215
+ return respond(refused("invalid_request", detail), 422)
216
+
217
+ @app.exception_handler(StarletteHTTPException)
218
+ async def _http(request: Request, error: StarletteHTTPException):
219
+ reasons = {400: "bad_request", 404: "not_found", 405: "method_not_allowed",
220
+ 413: "over_limit", 422: "invalid_request"}
221
+ return respond(refused(reasons.get(error.status_code, "http_error"),
222
+ str(error.detail)[:300]), error.status_code)
223
+
224
+ @app.exception_handler(Exception)
225
+ async def _crash(request: Request, error: Exception):
226
+ # No exception text, path or traceback reaches the client; the guard layer logs it.
227
+ return respond(refused("internal_error", "the server failed on this request; see its "
228
+ "log"), 500)
229
+
230
+ @app.get("/api/v1/hello")
231
+ def hello():
232
+ return respond(envelope("hello", sessions_view.hello(
233
+ recorded, read_only=read_only, web=web_avail(),
234
+ live=None if live is None else live.sid)))
235
+
236
+ @app.get("/api/v1/sessions")
237
+ def sessions():
238
+ omitted = []
239
+ rows = take([sessions_view.session_row(recorded, s) for s in recorded.sessions()], 64,
240
+ "sessions", omitted)
241
+ return respond(envelope("sessions", rows, omitted))
242
+
243
+ @app.get("/api/v1/s/{sid}/capabilities")
244
+ def capabilities(sid: str):
245
+ return respond(envelope("capabilities", sessions_view.capabilities(model(sid))))
246
+
247
+ @app.get("/api/v1/s/{sid}/frame")
248
+ def frame(sid: str, addr: str | None = None):
249
+ block = frame_view.frame(model(sid), addr)
250
+ if is_live(sid):
251
+ # the recorded frame of the live session's project; the engine is attached
252
+ state = "running" if live.running else "paused"
253
+ block.live = LiveState(state=state, frontier=[
254
+ f"live session: the engine is attached ({state}, cursor {live.where or 'no run'})"
255
+ "; drive and read it from the Live view",
256
+ *(f.replace("replay needs the engine", "the Live view reads it from the engine")
257
+ for f in block.live.frontier if f != frame_view.OFFLINE)])
258
+ return respond(envelope("frame", block))
259
+
260
+ @app.get("/api/v1/s/{sid}/timeline")
261
+ def timeline(sid: str, lens: str = "cuts", x0: int | None = None, x1: int | None = None,
262
+ y0: int | None = None, y1: int | None = None, branch: str | None = None):
263
+ block, omitted = timeline_view.timeline(model(sid), lens=lens, x0=x0, x1=x1, y0=y0,
264
+ y1=y1, branch=branch)
265
+ return respond(envelope("timeline", block, omitted))
266
+
267
+ @app.get("/api/v1/s/{sid}/branches")
268
+ def branches(sid: str):
269
+ tree = frame_view.branches(model(sid))
270
+ omitted = []
271
+ tree.nodes = take(tree.nodes, MAX_BRANCH_NODES, "nodes", omitted,
272
+ reason="cuts beyond the first in index order")
273
+ tree.branches = take(tree.branches, 64, "branches", omitted)
274
+ return respond(envelope("branches", tree, omitted))
275
+
276
+ @app.get("/api/v1/s/{sid}/symbols")
277
+ def symbols(sid: str, at: str | None = None, q: str | None = None, page: int = 0):
278
+ return respond(envelope("symbols", symbols_view.symbol_page(model(sid), at=at, q=q,
279
+ page=page)))
280
+
281
+ @app.get("/api/v1/s/{sid}/symbols/{identifier}")
282
+ def symbol(sid: str, identifier: str):
283
+ return respond(envelope("symbol", symbols_view.symbol_detail(model(sid), identifier)))
284
+
285
+ @app.get("/api/v1/s/{sid}/graph")
286
+ def graph(sid: str, addr: str | None = None, zoom: str = "slice", depth: int = 3,
287
+ k: int = 48, slice: str | None = None):
288
+ return respond(envelope("graph", graph_view.graph(model(sid), addr=addr, zoom=zoom,
289
+ depth=depth, k=k, slice_id=slice)))
290
+
291
+ @app.get("/api/v1/s/{sid}/records")
292
+ def records(sid: str, kind: str | None = None, page: int = 0):
293
+ return respond(envelope("records", records_view.record_page(model(sid), kind=kind,
294
+ page=page)))
295
+
296
+ @app.get("/api/v1/s/{sid}/records/{identifier:path}")
297
+ def record(sid: str, identifier: str):
298
+ detail, omitted = records_view.record_detail(model(sid), identifier)
299
+ marker = next((n.n for n in detail.summary.nums if n.name == "record"), None)
300
+ if marker is not None and marker.ev in ("unresolved", "refused"):
301
+ return respond(envelope("record", detail, omitted, state=marker.ev,
302
+ reason=marker.reason))
303
+ return respond(envelope("record", detail, omitted))
304
+
305
+ @app.get("/api/v1/s/{sid}/stored/{identifier}")
306
+ def stored(sid: str, identifier: str, node: str | None = None):
307
+ """One engine record's whole body (circuit, symbol-table) for the recorded views;
308
+ ``node`` (a circuit's node id) returns that node's child page instead."""
309
+ return respond(envelope("stored", records_view.stored_body(model(sid), identifier,
310
+ node)))
311
+
312
+ @app.post("/api/v1/s/{sid}/reduce")
313
+ async def reduce(sid: str, request: ReduceRequest):
314
+ spec = dump(request.pointer)
315
+ from .live_reduce import names_origin, reduce_live
316
+
317
+ if is_live(sid) and spec["kind"] == "occurrence" and not names_origin(spec["address"]):
318
+
319
+ result = await on_worker(submit(live.call, lambda: reduce_live(
320
+ live, spec, request.op, request.params)))
321
+ return respond(envelope("reduce", result))
322
+ result = await run_in_threadpool(reducer.run, model(sid), spec, request.op,
323
+ request.params)
324
+ return respond(envelope("reduce", result))
325
+
326
+ def recorded_op(sid, request):
327
+ model(sid)
328
+ try:
329
+ from .. import ops
330
+ except ImportError as error:
331
+ return respond(refused("ops registry unavailable", str(error)), 501)
332
+ dispatch = getattr(ops, "dispatch", None)
333
+ if dispatch is None or not hasattr(ops, "Context") or not hasattr(ops, "registry"):
334
+ return respond(refused("ops registry unavailable",
335
+ "mdb.ops lacks dispatch/Context/registry"), 501)
336
+ if list(inspect.signature(dispatch).parameters)[:2] != ["ctx", "name"]:
337
+ return respond(refused("ops registry unavailable",
338
+ "mdb.ops.dispatch signature is not (ctx, name, args)"), 501)
339
+ found = ops.registry().get(request.op)
340
+ if found is None:
341
+ return respond(refused("unknown-op", f"no operation {request.op!r}"), 404)
342
+ if found.effect in WRITE_EFFECTS:
343
+ why = ("this server is read-only over a recorded project" if live is None else
344
+ f"session {sid!r} is recorded; the live session is {live.sid!r}")
345
+ return respond(refused("read_only", f"{request.op} has effect {found.effect}; "
346
+ f"{why}"), 403)
347
+ context = contexts.setdefault(sid, ops.Context())
348
+ try:
349
+ result = dispatch(context, request.op, request.args)
350
+ except ops.OpError as error:
351
+ return respond(refused(error.kind, error.message), 409)
352
+ except (AttributeError, TypeError, ValueError, LookupError) as error:
353
+ return respond(refused("op_failed", f"{type(error).__name__}: {error}"), 409)
354
+ omitted: list[Omitted] = []
355
+ data = OpResult(request_id=request.request_id, op=request.op, seq=0, where=None,
356
+ result=scrub(bound_json(dump(result), field="result", omitted=omitted)))
357
+ return respond(envelope("op", data, omitted))
358
+
359
+ @app.post("/api/v1/s/{sid}/op")
360
+ async def op(sid: str, request: OpRequest, http: Request):
361
+ if not is_live(sid):
362
+ return await run_in_threadpool(recorded_op, sid, request)
363
+ from .. import ops
364
+
365
+ if request.op not in ops.registry():
366
+ return respond(refused("unknown-op", f"no operation {request.op!r}"), 404)
367
+ body = await on_worker(submit(live.op, request.op, request.args), http)
368
+ result = scrub(body["result"])
369
+ state = result.get("state", "resolved")
370
+ state = state if state in ("resolved", "unresolved", "refused") else "refused"
371
+ reason = None if state == "resolved" else (
372
+ result.get("reason") or "a part of the result is unresolved; see data.result")
373
+ data = OpResult(request_id=request.request_id, op=request.op, seq=body["seq"],
374
+ where=body["where"], result=result)
375
+ return respond(envelope("op", data, state=state, reason=reason),
376
+ 409 if state == "refused" else 200)
377
+
378
+ @app.post("/api/v1/s/{sid}/console")
379
+ async def console(sid: str, request: ConsoleRequest, http: Request):
380
+ if not is_live(sid):
381
+ raise not_live(sid, "the console")
382
+ body = await on_worker(submit(live.console, request.line), http)
383
+ return respond(envelope("console", ConsoleResult(line=request.line, seq=body["seq"],
384
+ where=body["where"],
385
+ text=scrub(body["text"]))))
386
+
387
+ @app.post("/api/v1/s/{sid}/interrupt")
388
+ def interrupt(sid: str):
389
+ if not is_live(sid):
390
+ raise not_live(sid, "interrupt")
391
+ return respond(envelope("interrupt", Interrupt(**live.interrupt())))
392
+
393
+ @app.get("/api/v1/s/{sid}/live")
394
+ async def live_frame(sid: str):
395
+ if not is_live(sid):
396
+ raise not_live(sid, "the live frame")
397
+ frame_data, more = await on_worker(submit(live.call, lambda: live_view.frame(live)))
398
+ return respond(envelope("live", frame_data, more or None))
399
+
400
+ @app.get("/api/v1/s/{sid}/live/items")
401
+ async def live_items(sid: str, list: str, offset: int = 0, addr: str | None = None): # noqa: A002
402
+ if not is_live(sid):
403
+ raise not_live(sid, "live lists")
404
+ if list not in live_view.LISTS:
405
+ raise ViewError("bad_request", f"no live list {list!r}; lists: "
406
+ + ", ".join(live_view.LISTS), 400)
407
+ if offset < 0:
408
+ raise ViewError("bad_request", "offset is a non-negative integer", 400)
409
+ if list == "upstream" and not addr:
410
+ raise ViewError("bad_request", "the upstream list names a computed address (addr=)",
411
+ 400)
412
+
413
+ def page():
414
+ try:
415
+ return live_view.items(live, list, offset, addr)
416
+ except (ValueError, KeyError) as error:
417
+ raise ViewError("unresolved", f"{list}: {error}", 409) from error
418
+
419
+ return respond(envelope("live-items", await on_worker(submit(live.call, page))))
420
+
421
+ @app.get("/api/v1/s/{sid}/live/ledger")
422
+ async def live_ledger(sid: str, limit: int = live_view.LEDGER_LIMIT):
423
+ if not is_live(sid):
424
+ raise not_live(sid, "the live ledger")
425
+ if not 1 <= limit <= live_view.LEDGER_LIMIT:
426
+ raise ViewError("bad_request", f"limit is an integer in 1..{live_view.LEDGER_LIMIT}",
427
+ 400)
428
+ block, more = await on_worker(submit(live.call, lambda: live_view.ledger(live, limit)))
429
+ return respond(envelope("live-ledger", block, more or None))
430
+
431
+ @app.get("/api/v1/s/{sid}/live/timeline")
432
+ async def live_timeline(sid: str):
433
+ if not is_live(sid):
434
+ raise not_live(sid, "the live timeline")
435
+ block, left_out = await on_worker(submit(live.call, lambda: live_view.timeline(live)))
436
+ omitted = [Omitted(field="rows", count=left_out, reason="earliest rows")] \
437
+ if left_out else None
438
+ return respond(envelope("live-timeline", block, omitted))
439
+
440
+ @app.get("/api/v1/s/{sid}/export")
441
+ def export(sid: str):
442
+ model(sid)
443
+ from .export import export_walkthrough
444
+
445
+ return respond(export_walkthrough(), 501)
446
+
447
+ @app.websocket("/api/v1/s/{sid}/events")
448
+ async def events(websocket: WebSocket, sid: str):
449
+ await websocket.accept()
450
+ seq = 0
451
+
452
+ async def send(kind, data):
453
+ nonlocal seq
454
+ body = canonical(envelope("event", Event(type=kind, seq=seq, at=int(time.time() * 1000),
455
+ data=data)))
456
+ seq += 1
457
+ if len(body) > cap:
458
+ body = canonical(refused("over_cap", bytes=len(body), cap=cap))
459
+ await websocket.send_text(body.decode())
460
+
461
+ if is_live(sid):
462
+ events = live.subscribe()
463
+ try:
464
+ await send("hello", {"session": sid,
465
+ "live": "running" if live.running else "paused",
466
+ "seq": live.seq, "running": live.running})
467
+ quiet = time.monotonic()
468
+ while True:
469
+ try:
470
+ event = await asyncio.wait_for(events.get(), timeout=min(heartbeat, TICK))
471
+ except asyncio.TimeoutError:
472
+ if stopping.is_set():
473
+ await websocket.close(code=1001) # going away: lets the server stop
474
+ return
475
+ if time.monotonic() - quiet >= heartbeat:
476
+ await send("heartbeat", {"session": sid})
477
+ quiet = time.monotonic()
478
+ continue
479
+ await send("op", event)
480
+ quiet = time.monotonic()
481
+ except (WebSocketDisconnect, RuntimeError):
482
+ return
483
+ finally:
484
+ live.unsubscribe(events)
485
+ try:
486
+ try:
487
+ model(sid)
488
+ except ViewError as error:
489
+ await websocket.send_text(canonical(refused(error.reason, error.detail)).decode())
490
+ await websocket.close()
491
+ return
492
+ await send("hello", {"session": sid, "live": "offline",
493
+ "note": "recorded project; heartbeats only"})
494
+ quiet = time.monotonic()
495
+ while True:
496
+ await asyncio.sleep(min(heartbeat, TICK))
497
+ if stopping.is_set():
498
+ await websocket.close(code=1001)
499
+ return
500
+ if time.monotonic() - quiet >= heartbeat:
501
+ await send("heartbeat", {"session": sid})
502
+ quiet = time.monotonic()
503
+ except (WebSocketDisconnect, RuntimeError):
504
+ return
505
+
506
+ @app.get("/{path:path}", include_in_schema=False)
507
+ def web(path: str):
508
+ if path.startswith("api/"):
509
+ return respond(refused("not_found", f"no API route /{path}"), 404)
510
+ index = static / "index.html"
511
+ if not index.is_file():
512
+ return respond(refused("web_build_absent", web_avail().reason), 404)
513
+ try:
514
+ target = (static / path).resolve()
515
+ inside = path and target.is_file() and static.resolve() in target.parents
516
+ except (ValueError, OSError): # e.g. a NUL byte in the path
517
+ inside = False
518
+ if inside:
519
+ return FileResponse(target)
520
+ if path.startswith("assets/") or "." in path.rsplit("/", 1)[-1]:
521
+ # A missing file is a 404, never the SPA shell (a stale bundle must fail loudly).
522
+ return respond(refused("not_found", f"no static file /{path}"), 404)
523
+ return FileResponse(index)
524
+
525
+ app.add_middleware(CapMiddleware, cap=cap)
526
+ return SecurityLayer(app, port=port, allow_hosts=allow_hosts, body_limit=body_limit)