sensorium-trace 0.18.2__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 (135) hide show
  1. sensorium/__init__.py +0 -0
  2. sensorium/__main__.py +4 -0
  3. sensorium/_c/rt/sensorium_c_rt.c +1446 -0
  4. sensorium/_typescript/package-lock.json +68 -0
  5. sensorium/_typescript/package.json +39 -0
  6. sensorium/_typescript/src/bindings.mjs +792 -0
  7. sensorium/_typescript/src/cap.mjs +227 -0
  8. sensorium/_typescript/src/capabilities.mjs +40 -0
  9. sensorium/_typescript/src/dbg.mjs +348 -0
  10. sensorium/_typescript/src/escape.mjs +351 -0
  11. sensorium/_typescript/src/focus.mjs +135 -0
  12. sensorium/_typescript/src/hook.mjs +127 -0
  13. sensorium/_typescript/src/index.mjs +1 -0
  14. sensorium/_typescript/src/naming.mjs +63 -0
  15. sensorium/_typescript/src/positions.mjs +37 -0
  16. sensorium/_typescript/src/probe.mjs +246 -0
  17. sensorium/_typescript/src/qualname.mjs +236 -0
  18. sensorium/_typescript/src/redact.mjs +711 -0
  19. sensorium/_typescript/src/register.mjs +15 -0
  20. sensorium/_typescript/src/resolve.mjs +260 -0
  21. sensorium/_typescript/src/rt.mjs +798 -0
  22. sensorium/_typescript/src/setup.mjs +11 -0
  23. sensorium/_typescript/src/tally.mjs +164 -0
  24. sensorium/_typescript/src/tasks.mjs +175 -0
  25. sensorium/_typescript/src/transform.mjs +800 -0
  26. sensorium/_typescript/src/vite.mjs +99 -0
  27. sensorium/c/__init__.py +8 -0
  28. sensorium/c/cc.py +612 -0
  29. sensorium/c/cli.py +60 -0
  30. sensorium/c/convert.py +669 -0
  31. sensorium/c/decode.py +300 -0
  32. sensorium/c/driver.py +365 -0
  33. sensorium/c/dwarf.py +706 -0
  34. sensorium/c/format.py +271 -0
  35. sensorium/c/pkg.py +187 -0
  36. sensorium/c/plan.py +277 -0
  37. sensorium/cli.py +140 -0
  38. sensorium/driver.py +47 -0
  39. sensorium/exit.py +33 -0
  40. sensorium/invocations.py +83 -0
  41. sensorium/limits.py +253 -0
  42. sensorium/mcp/__init__.py +0 -0
  43. sensorium/mcp/audit.py +162 -0
  44. sensorium/mcp/child.py +240 -0
  45. sensorium/mcp/cmd.py +101 -0
  46. sensorium/mcp/jsonrpc.py +172 -0
  47. sensorium/mcp/result.py +187 -0
  48. sensorium/mcp/schema.py +390 -0
  49. sensorium/mcp/server.py +493 -0
  50. sensorium/mcp/tools.py +299 -0
  51. sensorium/paths.py +80 -0
  52. sensorium/query/__init__.py +0 -0
  53. sensorium/query/caps.py +150 -0
  54. sensorium/query/dbg_dialects.py +64 -0
  55. sensorium/query/diff_cmd.py +748 -0
  56. sensorium/query/diff_notes.py +117 -0
  57. sensorium/query/exceptions_c.py +263 -0
  58. sensorium/query/exceptions_cmd.py +788 -0
  59. sensorium/query/exceptions_group.py +571 -0
  60. sensorium/query/exceptions_invocation.py +487 -0
  61. sensorium/query/exceptions_rust.py +683 -0
  62. sensorium/query/exceptions_typescript.py +688 -0
  63. sensorium/query/expr.py +606 -0
  64. sensorium/query/failures_cmd.py +306 -0
  65. sensorium/query/flow_cmd.py +778 -0
  66. sensorium/query/flow_report.py +128 -0
  67. sensorium/query/flow_values.py +195 -0
  68. sensorium/query/fmt.py +280 -0
  69. sensorium/query/frame_cmd.py +237 -0
  70. sensorium/query/grep_cmd.py +156 -0
  71. sensorium/query/help.py +18 -0
  72. sensorium/query/info_cmd.py +527 -0
  73. sensorium/query/info_rust.py +214 -0
  74. sensorium/query/info_typescript.py +261 -0
  75. sensorium/query/js_inspect.py +394 -0
  76. sensorium/query/moves.py +254 -0
  77. sensorium/query/redact_cmd.py +304 -0
  78. sensorium/query/refocus_cmd.py +661 -0
  79. sensorium/query/refocus_env.py +493 -0
  80. sensorium/query/refocus_facts.py +269 -0
  81. sensorium/query/refocus_licence.py +187 -0
  82. sensorium/query/refocus_report.py +327 -0
  83. sensorium/query/refocus_rust.py +537 -0
  84. sensorium/query/refocus_threads.py +197 -0
  85. sensorium/query/refocus_typescript.py +756 -0
  86. sensorium/query/refocus_world.py +666 -0
  87. sensorium/query/runs_cmd.py +213 -0
  88. sensorium/query/rust_debug.py +176 -0
  89. sensorium/query/sites.py +171 -0
  90. sensorium/query/tree_cmd.py +511 -0
  91. sensorium/query/tree_threads.py +168 -0
  92. sensorium/query/vocab.py +723 -0
  93. sensorium/query/watch_cmd.py +657 -0
  94. sensorium/record/__init__.py +0 -0
  95. sensorium/record/boot.py +797 -0
  96. sensorium/record/boot_io.py +141 -0
  97. sensorium/record/budget.py +135 -0
  98. sensorium/record/capture.py +433 -0
  99. sensorium/record/children.py +755 -0
  100. sensorium/record/children_merge.py +179 -0
  101. sensorium/record/elide.py +55 -0
  102. sensorium/record/fingerprint.py +26 -0
  103. sensorium/record/thread_starts.py +261 -0
  104. sensorium/record/tracer.py +798 -0
  105. sensorium/record/tracer_exc.py +199 -0
  106. sensorium/record/tracer_frames.py +618 -0
  107. sensorium/redact.py +304 -0
  108. sensorium/redact_content.py +156 -0
  109. sensorium/redact_key.py +317 -0
  110. sensorium/redact_store.py +502 -0
  111. sensorium/redact_values.py +433 -0
  112. sensorium/store/__init__.py +0 -0
  113. sensorium/store/db.py +284 -0
  114. sensorium/store/gc.py +360 -0
  115. sensorium/store/payloads.py +69 -0
  116. sensorium/store/reader.py +438 -0
  117. sensorium/store/writer.py +283 -0
  118. sensorium/ts/__init__.py +10 -0
  119. sensorium/ts/build.py +783 -0
  120. sensorium/ts/cli.py +130 -0
  121. sensorium/ts/driver.py +472 -0
  122. sensorium/ts/focus.py +146 -0
  123. sensorium/ts/harness.py +314 -0
  124. sensorium/ts/ingest.py +380 -0
  125. sensorium/ts/invocation.py +252 -0
  126. sensorium/ts/pkg.py +167 -0
  127. sensorium/ts/redaction.py +64 -0
  128. sensorium/ts/spool.py +168 -0
  129. sensorium/ts/truncation.py +81 -0
  130. sensorium/ts/wrapper.py +255 -0
  131. sensorium_trace-0.18.2.dist-info/METADATA +245 -0
  132. sensorium_trace-0.18.2.dist-info/RECORD +135 -0
  133. sensorium_trace-0.18.2.dist-info/WHEEL +4 -0
  134. sensorium_trace-0.18.2.dist-info/entry_points.txt +3 -0
  135. sensorium_trace-0.18.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,788 @@
1
+ """Every raise and what became of it. "Silently swallowed" is the headline,
2
+ which is exactly why the bar for asserting it is high.
3
+
4
+ WHY THE OBVIOUS RULE IS WRONG
5
+ -----------------------------
6
+ The tempting rule -- "a RAISE whose exception has a later HANDLED and no
7
+ later RAISE was swallowed" -- is a false accusation generator. Measured
8
+ against real recorded traces, that head shape is produced by three different
9
+ program behaviours:
10
+
11
+ * a genuine swallow (``except Exception: pass``)
12
+ * a bare ``raise`` re-raise inside the handler
13
+ * an exception that was never caught at all and merely crossed a
14
+ ``finally``
15
+
16
+ CPython compiles ``finally`` as an implicit exception handler, so
17
+ EXCEPTION_HANDLED fires on entry to a ``finally`` block that has no
18
+ ``except`` anywhere near it. A never-caught exception crossing one
19
+ ``finally`` produces *two* HANDLED rows. ``await`` is the other implicit
20
+ handler, and arc 2 made it visible: the ``CLEANUP_THROW`` an await site is
21
+ compiled with fires the same event, so an exception thrown into a coroutine
22
+ parked at an ``await`` produces two HANDLED rows AT THE AWAIT LINE --
23
+ measured on CPython 3.14.4, both in the frame that then caught it and in an
24
+ inner frame that merely passed it on. The presence of a HANDLED row
25
+ therefore means nothing on its own. (The tracer does subscribe RERAISE, but
26
+ records no event for it -- it only keeps in-flight state -- so re-raises are
27
+ not directly visible either.)
28
+
29
+ THE DISCRIMINATOR
30
+ -----------------
31
+ Every HANDLED event carries a ``frame_id``, and that frame's ``closed_by``
32
+ says how the frame ended:
33
+
34
+ genuine swallow -> "return" (the frame completed normally)
35
+ bare re-raise -> "unwind" (+ unwind_exc naming the exception)
36
+ uncaught via finally -> "unwind"
37
+
38
+ So the rule is: an exception is SWALLOWED iff some HANDLED for it sits in a
39
+ frame whose ``closed_by == "return"``, and no later RAISE carries its
40
+ identity. If every HANDLED for it sits in an unwound frame, it kept going and
41
+ is never reported as swallowed.
42
+
43
+ A frame can also be unwound by an exception thrown INTO it -- a cancelled
44
+ task, a suspended generator being closed -- at a suspension point reached
45
+ *after* the handler ran. That unwind is not this exception leaving the frame:
46
+ it is a death delivered later, and the handler still kept what it caught. So a
47
+ frame whose state is cancelled/abandoned/thrown -- ``Trace.frame_state``
48
+ derives that from its last YIELD/RESUME row -- is a swallow too, unless the
49
+ exception thrown in IS this one, which is a re-raise and swallowed nothing.
50
+ Every verdict resting on that rule names the frame's own fate rather than
51
+ claiming it returned normally.
52
+
53
+ Both halves are load-bearing. ``except E as e: return e`` closes its frame by
54
+ "return" while handing the exception *out* of that frame, so a returning
55
+ handler frame alone does not mean the exception stopped there. With exact
56
+ identity that case is resolved rather than hedged: the later RAISE is
57
+ provably the same object, so it is reported as caught here and raised again.
58
+
59
+ EXCEPTION IDENTITY
60
+ ------------------
61
+ ``oid`` is ``id(exc)`` and CPython recycles addresses aggressively: measured
62
+ live, a ValueError and the RuntimeError raised two lines later in the same
63
+ frame shared an oid, and an ordinary retry loop gives three distinct
64
+ ValueError objects *one* address. Identity is therefore the recorder's
65
+ ``serial`` -- minted while the recorder holds the object, so one serial is one
66
+ object, provably. Traces recorded before serials existed fall back to
67
+ ``(type, msg, oid)``, hedge every verdict that turns on the difference, and
68
+ say so under a ``LEGACY TRACE`` banner.
69
+
70
+ Every lookup is scoped to the events between one RAISE and the next RAISE of
71
+ the same identity, so a loop raising an identical exception repeatedly still
72
+ pairs each raise with its own handler.
73
+
74
+ WHERE A SERIAL RUNS OUT
75
+ -----------------------
76
+ A serial proves that two rows *are* the same object. It cannot prove that two
77
+ rows are *different* objects, because the recorder remembers only a bounded
78
+ number of exceptions per thread and links a re-raise only within the thread
79
+ that handled it. Stash an exception, handle enough others to push it out of
80
+ that table, raise it again, and it comes back with a fresh serial.
81
+
82
+ So a differing serial is never read here as proof of a differing object.
83
+ Wherever that inference would be load-bearing -- "never re-raised", and "the
84
+ frame unwound with some *other* exception" -- the address and type are checked
85
+ too. An object keeps both for life, so nothing that is really the same object
86
+ slips past; a different object at a recycled address can trip it, and the
87
+ result is an honest hedge naming both readings rather than a verdict the run's
88
+ own uncaught header contradicts.
89
+
90
+ WHERE THE TRACE CANNOT SAY
91
+ --------------------------
92
+ Two shapes are recorded identically and are not separated here:
93
+
94
+ * ``except E as e: raise Wrapped() from e`` (a translation), and
95
+ * ``except E: pass`` followed later by an unrelated ``raise``
96
+
97
+ Both leave a HANDLED in a frame that then unwinds with a *different*
98
+ exception. ``capture_exc`` records type/msg/oid only, so ``__context__`` --
99
+ which would separate them -- is not in the trace. Both are reported as what
100
+ is actually known: handled here, frame later died of something else, cause
101
+ unestablished.
102
+
103
+ Likewise, a re-raise ultimately caught by *untraced* code leaves no record of
104
+ where it was caught. That prints ``propagated (handler not in traced code)``
105
+ rather than a guess. Generators and coroutines are framed from trace format 3
106
+ on, so a handler inside one is decided by the rules above like any other; a
107
+ trace recorded before that opened no frame for them, and a HANDLED in one has
108
+ no ``closed_by`` to read and gets no verdict. A frameless HANDLED on a format-3
109
+ trace is a different fact -- a frame already running when recording began --
110
+ and the refusal names whichever of the two the trace supports.
111
+
112
+ Control-flow exceptions (StopIteration, StopAsyncIteration, GeneratorExit)
113
+ were excluded at record time and never appear. SystemExit is not: a plain
114
+ ``sys.exit()`` is a real exception and shows up here, normally as propagated
115
+ out of traced code, because the recorder's own handler is untraced.
116
+ """
117
+ import shlex
118
+ from dataclasses import dataclass
119
+
120
+ from sensorium import paths
121
+ from sensorium.exit import ANSWERED, BAD_CALL, NEGATIVE, UNSETTLED
122
+ from sensorium.query.caps import print_truncated
123
+ from sensorium.query.fmt import fmt_event, fmt_exc, more_note, parse_eref
124
+ from sensorium.query.help import LIMIT_HELP
125
+ from sensorium.query.vocab import terms
126
+ from sensorium.store.reader import Trace
127
+
128
+ TAG_ORDER = ("swallowed", "uncaught", "re-raised", "propagated", "ambiguous")
129
+
130
+
131
+ def add_parser(sub) -> None:
132
+ p = sub.add_parser(
133
+ "exceptions", help="raises, handles, swallows",
134
+ description="Every raise classified swallowed, uncaught, "
135
+ "re-raised, propagated or ambiguous, with the "
136
+ "reason; SWALLOWED is claimed only when the "
137
+ "recording proves it.",
138
+ epilog="exit: 0 yes, 1 no, 2 fix the call, 3 change the recording")
139
+ p.add_argument("run", help="a run id (or a unique prefix), 'last', or "
140
+ "an invocation id as `runs` prints it; "
141
+ "--after is refused for an invocation")
142
+ p.add_argument("--after", default=None, help="event ref to resume from")
143
+ p.add_argument("--limit", type=int, default=50,
144
+ help=LIMIT_HELP)
145
+ p.set_defaults(func=run)
146
+
147
+
148
+ def exc_key(exc: dict, thread_id=None) -> tuple:
149
+ """Identity of one exception object.
150
+
151
+ `serial` is exact: the recorder mints it while holding a strong reference
152
+ to the object, so two distinct exceptions can never share one. It is
153
+ per-thread, hence the thread in the key.
154
+
155
+ `oid` is `id(exc)` and is NOT an identity -- CPython recycles addresses,
156
+ measurably so in a plain retry loop. Traces recorded before serials
157
+ existed fall back to it, and every verdict that would depend on the
158
+ difference is hedged and labelled rather than asserted.
159
+ """
160
+ s = exc.get("serial")
161
+ if s is not None:
162
+ return ("serial", thread_id, s)
163
+ return ("legacy", exc["type"], exc["msg"], exc["oid"])
164
+
165
+
166
+ def could_be_same(a: dict, b: dict) -> bool:
167
+ """Whether `b` could be `a`'s object recorded under a lost link.
168
+
169
+ A serial proves that two rows ARE one object. It cannot prove they are
170
+ two, because the recorder remembers a bounded number of exceptions per
171
+ thread and links a re-raise only within the thread that handled it: an
172
+ object it has forgotten comes back with a fresh serial. An object's
173
+ address and type, though, are fixed for its lifetime, so equality there is
174
+ a necessary condition for sameness and the cheapest sound way to ask "may
175
+ these be one object?".
176
+
177
+ Equal serials say the recorder did link the two rows, and are handled as
178
+ the proof they are before this is ever asked. Two legacy rows both answer
179
+ None there, which is why this is dormant on a legacy trace -- whose
180
+ identity already includes the address anyway.
181
+ """
182
+ return (a["oid"] == b["oid"] and a["type"] == b["type"]
183
+ and a.get("serial") != b.get("serial"))
184
+
185
+
186
+ @dataclass(frozen=True)
187
+ class Disposition:
188
+ tag: str # summary bucket, one of TAG_ORDER
189
+ verdict: str # the claim, printed under the RAISE
190
+ detail: str | None = None # the evidence or the refusal to conclude
191
+ #: The site the verdict is ABOUT -- the sink it names, the arm it names
192
+ #: -- as the site EVENT's identity `(file, line, qualname)`, for the Rust
193
+ #: grouping key (design N3, amended by ruling R-G12: the key holds the
194
+ #: place, not the `qualname Lline` the verdict prints, because two files
195
+ #: can carry one helper at one line and the first measurement merged
196
+ #: them). Set only by a rule whose SENTENCE names a place; `None` means
197
+ #: the verdict speaks of the chain rather than of a site, and the grouper
198
+ #: falls back to the chain's origin. Never parsed back out of `verdict`:
199
+ #: a site recovered by reading a sentence is a second, drifting spelling
200
+ #: of it. Unused by the Python rules (N7), which do not group.
201
+ site: tuple[str, int, str] | None = None
202
+ #: Why an AMBIGUOUS verdict says no more, as one key of
203
+ #: `exceptions_typescript.REASON_ORDER`; `None` on every other verdict.
204
+ reason: str | None = None
205
+
206
+
207
+ @dataclass(frozen=True)
208
+ class Index:
209
+ """Everything the classifier needs, read once."""
210
+ all_raises: list
211
+ raises: dict
212
+ handled: dict
213
+ uncaught: dict | None
214
+ uncaught_key: tuple | None
215
+ uncaught_origin: object | None
216
+ exit_status: object
217
+ incomplete: bool
218
+ exact: bool # every RAISE carries a recorder serial
219
+ by_addr: dict # (oid, type) -> the RAISE events at it
220
+
221
+ @classmethod
222
+ def build(cls, trace, meta: dict) -> "Index":
223
+ all_raises = [e for e in trace.events(kind="RAISE")
224
+ if (e.payload or {}).get("exc")]
225
+ exact = all("serial" in e.payload["exc"] for e in all_raises)
226
+ raises: dict = {}
227
+ by_addr: dict = {}
228
+ for r in all_raises:
229
+ exc = r.payload["exc"]
230
+ raises.setdefault(exc_key(exc, r.thread_id), []).append(r)
231
+ by_addr.setdefault((exc["oid"], exc["type"]), []).append(r)
232
+ handled: dict = {}
233
+ for h in trace.events(kind="HANDLED"):
234
+ exc = (h.payload or {}).get("exc")
235
+ if exc:
236
+ handled.setdefault(
237
+ exc_key(exc, h.thread_id), []).append(h)
238
+ unc = meta.get("uncaught") or None
239
+ # `boot` captures the uncaught record on the main thread, which is the
240
+ # only thread whose exceptions can escape `target()`.
241
+ ukey = exc_key(unc, trace.main_thread_id()) if unc else None
242
+ # The escaping object's origin is the LAST raise carrying its
243
+ # identity. With serials there is only ever one; on a legacy trace an
244
+ # earlier match may be address reuse, so the last is the safe pick.
245
+ origin = raises[ukey][-1] if ukey in raises else None
246
+ return cls(all_raises, raises, handled, unc, ukey, origin,
247
+ meta.get("exit_status", "?"), bool(meta.get("incomplete")),
248
+ exact, by_addr)
249
+
250
+ def unlinked_later(self, r) -> list:
251
+ """Later RAISEs that could be `r`'s object under another serial.
252
+
253
+ Every re-raise the recorder failed to link is in here -- along with,
254
+ occasionally, an unrelated exception of the same type at a recycled
255
+ address. That is the right way round: this list gates the one claim
256
+ ("never re-raised") that a missed link would make false, so an extra
257
+ entry costs a hedge rather than a false accusation.
258
+ """
259
+ exc = r.payload["exc"]
260
+ return [x for x in self.by_addr.get((exc["oid"], exc["type"]), ())
261
+ if x.id > r.id and could_be_same(exc, x.payload["exc"])]
262
+
263
+
264
+ def _at(trace, e) -> str:
265
+ q = trace.code(e.code_id).qualname if e.code_id is not None else "?"
266
+ return f"{q} L{e.line}"
267
+
268
+
269
+ def _frame_of(trace, e):
270
+ return trace.frame(e.frame_id) if e.frame_id is not None else None
271
+
272
+
273
+ def _uncaught(trace, idx, handled) -> Disposition:
274
+ detail = None
275
+ if handled:
276
+ ids = ", ".join(f"e{h.id}" for h in handled)
277
+ detail = (f"the {len(handled)} HANDLED row(s) here ({ids}) sit in "
278
+ "frames that unwound: finally/cleanup blocks entered while "
279
+ "it was in flight, not a catch")
280
+ return Disposition(
281
+ "uncaught",
282
+ f"uncaught -- left the program (exit {idx.exit_status}); "
283
+ "not swallowed", detail)
284
+
285
+
286
+ # The three §D2 states that mean "unwound by an exception thrown into the
287
+ # frame at its last RESUME" -- a death delivered after a suspension, not an
288
+ # exception leaving under its own power.
289
+ THROWN_IN_STATES = ("cancelled", "abandoned", "thrown")
290
+
291
+
292
+ def _closed_by_thrown_in_other(s, frame, key) -> bool:
293
+ """Spec D4 rule, read off the frame's derived state `s`: a frame unwound
294
+ by an exception THROWN IN at a later RESUME (cancelled/abandoned/thrown)
295
+ did not let THIS exception out -- the handler kept it; the frame then
296
+ died of something delivered after a YIELD. True only when that thrown
297
+ exception is not this one."""
298
+ if s.state not in THROWN_IN_STATES or s.exc is None:
299
+ return False
300
+ return exc_key(s.exc, frame.thread_id) != key
301
+
302
+
303
+ def _how_it_closed(s) -> str:
304
+ """How a rule-2 handler frame ended, in the words of the state the reader
305
+ derived. Rule 2 admits two endings and every verdict built on it names
306
+ one of them: "returned normally" would be false of a frame an exception
307
+ thrown in after the handler ran had killed, and that frame is the one the
308
+ reader is looking at. `thrown` is a state, not English -- the frame was
309
+ not "thrown", it was unwound by something thrown into it, which is also
310
+ the reader's next question, so the tail names it.
311
+
312
+ Every other state is refused rather than described. Rule 2 admits a frame
313
+ that closed by `return` (state `returned`) or one killed by an exception
314
+ thrown in later, and nothing else -- so any other state here means a new
315
+ caller, and the honest failure is a crash naming the state, not a
316
+ sentence saying a suspended or still-open frame "returned normally".
317
+ """
318
+ if s.state == "returned":
319
+ return "returned normally"
320
+ if s.state not in THROWN_IN_STATES:
321
+ raise AssertionError(
322
+ f"_how_it_closed called on a {s.state!r} frame: rule 2 admits "
323
+ "only 'returned' and the thrown-in states "
324
+ f"{THROWN_IN_STATES}")
325
+ how = (f"unwound by {s.exc['type']} thrown in at L{s.line}"
326
+ if s.state == "thrown" else f"{s.state} at L{s.line}")
327
+ return f"never returned (frame later {how})"
328
+
329
+
330
+ def _swallowed(trace, h, frame, closed) -> Disposition:
331
+ """Caught here, and it never left this frame.
332
+
333
+ Two frames reach this verdict. One returned normally -- the classic
334
+ swallow. The other was unwound by an exception thrown into it at a
335
+ suspension the handler had already passed, which is a death this
336
+ exception had no part in. `closed` says which, because saying nothing
337
+ would hide a frame that never finished.
338
+ """
339
+ return Disposition(
340
+ "swallowed",
341
+ f"SWALLOWED at e{h.id} {_at(trace, h)} -- caught in f{frame.id}, "
342
+ f"which {closed}; never re-raised")
343
+
344
+
345
+ def _link_lost(trace, h, frame, nxt, closed) -> Disposition:
346
+ """A handler frame rule 2 admitted (`closed` says how it ended), and a
347
+ later RAISE of the same type at the same address under a *different*
348
+ serial.
349
+
350
+ One object cannot hold two serials while the recorder still remembers it,
351
+ so either it forgot this one -- its table is bounded, and it links a
352
+ re-raise only within the thread that handled it -- or the later raise is a
353
+ new object at the address this one freed. The first reading makes
354
+ "never re-raised" false; the second makes it true; the trace supports
355
+ neither, so neither is asserted.
356
+ """
357
+ return Disposition(
358
+ "ambiguous",
359
+ f"handled at e{h.id} {_at(trace, h)} -- f{frame.id} {closed}, but a "
360
+ f"later RAISE (e{nxt.id}) is the same exception type at the same "
361
+ "address under a different recorder identity",
362
+ "the recorder links a re-raise only while it still holds the handled "
363
+ "exception, and it holds a bounded number per thread, so this is "
364
+ "either a swallow whose address a later exception reused or this same "
365
+ "object stored and raised again; the trace cannot tell them apart")
366
+
367
+
368
+ def _stored_or_reused(trace, h, frame, nxt, exact, closed) -> Disposition:
369
+ """A handler frame rule 2 admitted (`closed` says how it ended), with a
370
+ later RAISE of the same identity.
371
+
372
+ `except E as e: return e` closes its frame by "return" -- the swallow
373
+ signal -- while handing the exception out of it. With exact identity the
374
+ trace settles it: the later RAISE is provably this same object, so it was
375
+ caught here and raised again, and both facts are reported together.
376
+
377
+ Without serials the two readings cannot be separated (the later raise may
378
+ be a new object at a reused address), so neither is asserted.
379
+ """
380
+ if exact:
381
+ return Disposition(
382
+ "re-raised",
383
+ f"handled at e{h.id} {_at(trace, h)} in f{frame.id}, which "
384
+ f"{closed} -- then raised again at e{nxt.id}")
385
+ return Disposition(
386
+ "ambiguous",
387
+ f"handled at e{h.id} {_at(trace, h)} -- f{frame.id} {closed}, but a "
388
+ f"later RAISE (e{nxt.id}) carries the same identity",
389
+ "either it was swallowed there and that later raise is a new object "
390
+ "at a reused address, or it was handed out of the frame (`return e`) "
391
+ "and raised again; this trace has no serials, so it cannot tell them "
392
+ "apart")
393
+
394
+
395
+ def _reraised(trace, r, handled, nxt, exact) -> Disposition:
396
+ """Two RAISE rows carrying one identity: re-raised, or address reuse?
397
+
398
+ With serials there is no question -- one identity is one object, and this
399
+ is a re-raise.
400
+
401
+ Without them the answer is not derivable, and the shape that proves it is
402
+ a handler in *untraced* code: it ends the exception's flight and frees the
403
+ object while leaving no HANDLED row at all, after which a fresh exception
404
+ can take the address. Measured: two provably distinct ValueError('dup')
405
+ objects, one address, zero HANDLED rows. So on a legacy trace "no HANDLED
406
+ row in between" says nothing about whether the object survived, and the
407
+ same-statement test is only a heuristic.
408
+ """
409
+ if exact:
410
+ if handled:
411
+ h = handled[0]
412
+ return Disposition(
413
+ "re-raised",
414
+ f"handled at e{h.id} {_at(trace, h)}, then raised again at "
415
+ f"e{nxt.id}")
416
+ return Disposition(
417
+ "re-raised",
418
+ f"the same exception object is raised again at e{nxt.id}",
419
+ "no HANDLED row in between: the trace cannot say what caught it")
420
+ if not handled:
421
+ return Disposition(
422
+ "ambiguous",
423
+ f"e{nxt.id} carries the same type/message/oid, with no HANDLED "
424
+ "row in between",
425
+ "a handler in untraced code ends an exception without leaving a "
426
+ "HANDLED row, so this is either the same object raised again or a "
427
+ "new one at a reused address; re-record to resolve it")
428
+ h = handled[0]
429
+ if (r.code_id, r.line) == (nxt.code_id, nxt.line):
430
+ return Disposition(
431
+ "ambiguous",
432
+ f"handled at e{h.id} {_at(trace, h)} -- e{nxt.id} carries the "
433
+ "same identity, raised from the same statement",
434
+ "a loop re-running one raise frees each exception before the next "
435
+ "is allocated, so CPython hands the new one a reused address; "
436
+ "this trace has no serials, so it cannot say which happened")
437
+ return Disposition(
438
+ "re-raised",
439
+ f"handled at e{h.id} {_at(trace, h)}, then raised again at "
440
+ f"e{nxt.id}")
441
+
442
+
443
+ def _no_handler_found(trace, idx) -> Disposition:
444
+ if idx.incomplete:
445
+ return Disposition(
446
+ "ambiguous",
447
+ "unresolved -- the recording ended before its fate was recorded",
448
+ "no HANDLED row for it anywhere, and this run never finalized: "
449
+ "with no uncaught record the trace cannot say whether it was "
450
+ "caught or killed the process")
451
+ return Disposition(
452
+ "propagated", "propagated (handler not in traced code)",
453
+ "no HANDLED row for it anywhere in the trace, and it did not reach "
454
+ "the top of the program")
455
+
456
+
457
+ def _still_in_flight(trace, idx, h, frame) -> Disposition:
458
+ evidence = (f"handled at e{h.id} {_at(trace, h)}, but f{frame.id} unwound "
459
+ "with the same exception -- that HANDLED is a finally/cleanup "
460
+ "block, not a catch")
461
+ if idx.incomplete:
462
+ return Disposition(
463
+ "ambiguous",
464
+ "unresolved -- the recording ended before its fate was recorded",
465
+ evidence + "; and with no finalize pass there is no uncaught "
466
+ "record either")
467
+ return Disposition("propagated",
468
+ "propagated (handler not in traced code)", evidence)
469
+
470
+
471
+ def _maybe_still_in_flight(trace, h, frame) -> Disposition:
472
+ """The frame unwound with an exception at this one's address and type, but
473
+ under a different serial.
474
+
475
+ Same reasoning as `_link_lost`, on the other side: a long cleanup that
476
+ raises and handles more exceptions than the recorder retains can push the
477
+ exception it is cleaning up out of the identity table, so the frame it
478
+ finally leaves carries a fresh serial for the same object. Reporting that
479
+ as "this one did not leave the frame" would be false about the one thing
480
+ the reader came for.
481
+ """
482
+ return Disposition(
483
+ "ambiguous",
484
+ f"handled at e{h.id} {_at(trace, h)} -- f{frame.id} then unwound with "
485
+ f"{fmt_exc(frame.unwind_exc)}, at this exception's address under a "
486
+ "different recorder identity",
487
+ "the recorder forgets an exception once it has seen a bounded number "
488
+ "of others, so the trace cannot say whether that is this same "
489
+ "exception still propagating or a new one that displaced it")
490
+
491
+
492
+ def _displaced(trace, h, frame) -> Disposition:
493
+ return Disposition(
494
+ "ambiguous",
495
+ f"handled at e{h.id} {_at(trace, h)} -- f{frame.id} then unwound "
496
+ f"with {fmt_exc(frame.unwind_exc)}",
497
+ "the trace cannot say whether that replaced this exception or is "
498
+ f"unrelated to it; only that this one did not leave f{frame.id}")
499
+
500
+
501
+ def _unreadable_frame(trace, h, frame) -> Disposition:
502
+ if frame is None:
503
+ # Two different facts wear this shape, and the trace says which by
504
+ # its format rather than by assumption. Up to format 2 the recorder
505
+ # opened no frame for a generator or coroutine body at all. From
506
+ # format 3 it frames every activation whose START it sees, so the
507
+ # only frameless handler left is one whose frame was already running
508
+ # when recording began -- what `tree` reports as "(no frame: started
509
+ # before recording)".
510
+ why = ("recorded by a sensorium before coroutine frames existed "
511
+ "(format <= 2); no closed_by to read" if trace.format < 3 else
512
+ "handler's frame started before recording; no closed_by to "
513
+ "read")
514
+ return Disposition(
515
+ "ambiguous",
516
+ f"handled at e{h.id} {_at(trace, h)} -- no frame recorded", why)
517
+ if frame.closed_by is None:
518
+ return Disposition(
519
+ "ambiguous",
520
+ f"handled at e{h.id} {_at(trace, h)} -- f{frame.id} never closed",
521
+ "recording stopped while that frame was still running; the trace "
522
+ "cannot say what it did with the exception")
523
+ return Disposition(
524
+ "ambiguous",
525
+ f"handled at e{h.id} {_at(trace, h)} -- f{frame.id} unwound with no "
526
+ "captured exception",
527
+ "the trace cannot say which exception left that frame, so it cannot "
528
+ "say what became of this one")
529
+
530
+
531
+ def classify(trace, r, idx: Index) -> Disposition:
532
+ """What the trace supports about one RAISE -- and nothing more."""
533
+ key = exc_key(r.payload["exc"], r.thread_id)
534
+ later = [x for x in idx.raises.get(key, ()) if x.id > r.id]
535
+ bound = later[0].id if later else None
536
+ handled = [h for h in idx.handled.get(key, ())
537
+ if h.id > r.id and (bound is None or h.id < bound)]
538
+
539
+ # 1. The run's own uncaught record is captured from the live escaping
540
+ # object, and definitively rules out SWALLOWED.
541
+ if not later and key == idx.uncaught_key:
542
+ return _uncaught(trace, idx, handled)
543
+
544
+ pairs = [(h, _frame_of(trace, h)) for h in handled]
545
+
546
+ # 2. Caught in a frame that then returned normally: it stopped here --
547
+ # but only if nothing raises that identity again. `except E as e:
548
+ # return e` closes the frame by "return" while handing the exception
549
+ # out of it, so a later RAISE makes both readings live and neither
550
+ # assertable. Checked before the later-RAISE rule so that a loop whose
551
+ # exception address gets reused still reaches an honest verdict rather
552
+ # than being reported as one exception raised twice.
553
+ # A frame killed by some OTHER exception thrown into it after the
554
+ # handler ran counts here too: that unwind is not this one getting out.
555
+ for h, frame in pairs:
556
+ if frame is None:
557
+ continue
558
+ # Derived once per handler: the admission test and the verdict that
559
+ # follows it must read the same ending, and it costs a query.
560
+ st = trace.frame_state(frame)
561
+ if not (frame.closed_by == "return"
562
+ or _closed_by_thrown_in_other(st, frame, key)):
563
+ continue
564
+ closed = _how_it_closed(st)
565
+ if later:
566
+ return _stored_or_reused(trace, h, frame, later[0], idx.exact,
567
+ closed)
568
+ # "never re-raised" is the one claim a serial cannot establish on
569
+ # its own: a stored exception the recorder forgot comes back with
570
+ # a fresh one. Its address and type do not change, so they are
571
+ # what stands between this verdict and a false accusation.
572
+ unlinked = idx.unlinked_later(r)
573
+ if unlinked:
574
+ return _link_lost(trace, h, frame, unlinked[0], closed)
575
+ return _swallowed(trace, h, frame, closed)
576
+
577
+ # 3. The same identity raised again -- `raise e` by name, which fires
578
+ # RAISE where a bare `raise` would fire the unrecorded RERAISE. Only
579
+ # asserted where address reuse is ruled out or implausible; see
580
+ # _reraised.
581
+ if later:
582
+ return _reraised(trace, r, handled, later[0], idx.exact)
583
+
584
+ if not pairs:
585
+ return _no_handler_found(trace, idx)
586
+
587
+ # 4-6. No frame returned normally (rule 2 did not fire), so this exception
588
+ # was not cleanly swallowed. A handler frame that unwound while still
589
+ # carrying it only means it propagated PAST that frame -- not that it
590
+ # left traced code. Handlers fire inner-to-outer as an exception
591
+ # propagates, so its fate is decided by the OUTERMOST handler, the last
592
+ # HANDLED in this window. Judging from the first unwinding frame would
593
+ # report an intermediate re-raise as "propagated (handler not in traced
594
+ # code)" even when an outer traced frame caught it (and then died of
595
+ # something else) -- a verdict the trace's own later HANDLED contradicts.
596
+ framed = [(h, f) for h, f in pairs if f is not None]
597
+ if not framed:
598
+ return _unreadable_frame(trace, *pairs[0])
599
+ h, frame = framed[-1]
600
+ if frame.unwind_exc is None:
601
+ return _unreadable_frame(trace, h, frame)
602
+ # 4. The outermost handler frame unwound still carrying this exception: it
603
+ # never stopped anywhere in code we can see.
604
+ if exc_key(frame.unwind_exc, frame.thread_id) == key:
605
+ return _still_in_flight(trace, idx, h, frame)
606
+ # 5. ...or with something the recorder no longer links to this exception --
607
+ # a lost link or a reused address, not assertably a different object.
608
+ # Read as "some other exception", it would deny that this one left the
609
+ # frame, the same false claim rule 2 guards against from the far side.
610
+ if could_be_same(r.payload["exc"], frame.unwind_exc):
611
+ return _maybe_still_in_flight(trace, h, frame)
612
+ # 6. ...or with something else: caught at this handler, and the frame then
613
+ # died of an unrelated failure (or a translation -- indistinguishable).
614
+ return _displaced(trace, h, frame)
615
+
616
+
617
+ def _header(trace, idx) -> None:
618
+ print_truncated(trace)
619
+ if idx.all_raises and not idx.exact:
620
+ print("LEGACY TRACE: recorded before exceptions carried a serial, so "
621
+ "identity here falls back to (type, message, address)")
622
+ print(" CPython recycles addresses, so repeats below are hedged "
623
+ "rather than resolved; re-record to get exact identity")
624
+ if idx.incomplete:
625
+ print("INCOMPLETE: this recording never finalized, so it has no exit "
626
+ "status and no uncaught record")
627
+ print(" the absence of an uncaught exception below is therefore not "
628
+ "evidence that nothing escaped")
629
+ if idx.uncaught is None:
630
+ return
631
+ origin = idx.uncaught_origin
632
+ where = (f" raised at e{origin.id}" if origin
633
+ else " -- no recorded RAISE carries its identity")
634
+ print(f"uncaught: {fmt_exc(idx.uncaught)} "
635
+ f"(exit {idx.exit_status}){where}")
636
+
637
+
638
+ def _language_refusal(trace) -> str | None:
639
+ """Why this command cannot judge a trace another recorder wrote.
640
+
641
+ Not a vocabulary problem: the rules in this module are Python's
642
+ semantics. `Index` reads `exc["oid"]`, which a non-Python trace does not
643
+ carry; it lists only RAISE events, so an `Err` returned by `return
644
+ Err(..)` and absorbed by a caller's `.ok()` would come back as "no
645
+ exceptions recorded"; and rule 2 would report SWALLOWED for a frame that
646
+ re-returned an `Err` without `?`. Every one of those is a confident
647
+ wrong answer about the program, which is worse than no answer.
648
+
649
+ Amended 2026-09-09 (S5): one sentence lived here and interpolated
650
+ `trace.lang` into itself, so a THIRD language was told it needed "the
651
+ Rust disposition rules" and that the Python rules "would misread Err
652
+ values" -- neither of which is true of a TypeScript recording, whose
653
+ gap is exception IDENTITY (`exc["oid"]`). What a language is missing is
654
+ a fact about that language, so the sentence moved to its `vocab` column
655
+ (`Terms.exceptions_refusal`) and each one says what is actually absent
656
+ and which rung owes it.
657
+
658
+ NO LANGUAGE CARRIES ONE TODAY. Every column is `None`: Python's rules
659
+ are these, and `run` dispatches Rust, TypeScript and C above. Rust and
660
+ TypeScript still gate on `capabilities.err_flow`, so an older recording
661
+ of either refuses because of what it does not HOLD rather than because
662
+ of what nobody wrote. This function is therefore unreachable until a
663
+ language arrives with words and no rules -- which is exactly the state
664
+ it exists to describe, and why it and the `vocab` field stay.
665
+ """
666
+ return terms(trace).exceptions_refusal
667
+
668
+
669
+ def run(args) -> int:
670
+ if args.limit < 1:
671
+ print(f"--limit must be >= 1 (got {args.limit}); "
672
+ "there is no useful zero-row page")
673
+ return BAD_CALL
674
+ # Parsed before any work: a trace with no raises returns early below, and
675
+ # accepting a malformed --after there would silently answer a different
676
+ # question than the one asked.
677
+ after = parse_eref(args.after) if args.after else 0
678
+ try:
679
+ path = paths.find_trace(args.run)
680
+ except paths.NoSuchTrace:
681
+ # ONLY "this ref names no trace" opens the second namespace (design
682
+ # N6). An ambiguous run prefix, or a store with no traces at all,
683
+ # is already an answered question and keeps the answer it had: a
684
+ # ref that resolves to a TRACE, or that fails for any other reason,
685
+ # is never re-read as an invocation id. The `except` clause IS that
686
+ # test -- it read the message's first words before, which was right
687
+ # only until someone reworded them, and would then have failed by
688
+ # answering less rather than by failing.
689
+ #
690
+ # Local: `exceptions_invocation` imports this module's Rust sibling,
691
+ # which imports `Disposition` from here.
692
+ from sensorium.query import exceptions_invocation
693
+ # `InvocationLookupError` is a `TraceLookupError`, so a ref that
694
+ # names neither namespace is rendered by `cli.main` exactly as a
695
+ # bad run ref always has been -- one line on stderr, exit 2.
696
+ inv, members = exceptions_invocation.resolve_invocation(args.run)
697
+ return exceptions_invocation.run(args, inv, members)
698
+ trace = Trace.open(path)
699
+ if trace.lang == "rust":
700
+ # Dispatched on `lang` FIRST (design R9), before any Python rule
701
+ # touches the trace: an `Err` is a value being returned, and the
702
+ # rules below are written about an exception unwinding. The Rust
703
+ # module gates on `capabilities.err_flow` itself, so an older Rust
704
+ # recording still refuses -- with the capability sentence, because
705
+ # what it is missing is now a record rather than a rule.
706
+ #
707
+ # Local: `exceptions_rust` imports `Disposition` from this module,
708
+ # so a module-level import here would be a cycle.
709
+ from sensorium.query import exceptions_rust
710
+ return exceptions_rust.run(trace, args, after)
711
+ if trace.lang == "typescript":
712
+ # The same dispatch one language further out (design section 3):
713
+ # the words below index an exception on the address CPython gave
714
+ # the object, which this recorder does not carry -- its identity is
715
+ # a serial minted per thrown object. That module gates on
716
+ # `capabilities.err_flow` itself, so an 0.1.x TypeScript recording
717
+ # still refuses, with the capability sentence.
718
+ from sensorium.query import exceptions_typescript
719
+ return exceptions_typescript.run(trace, args, after)
720
+ if trace.lang == "c":
721
+ # A crash is a signal RAISE, not an exception object and not an
722
+ # `Err`. The rules below read `exc["oid"]`, which this recorder
723
+ # does not carry. Local for the same cycle as the two above:
724
+ # `exceptions_c` imports `Disposition` from this module.
725
+ from sensorium.query import exceptions_c
726
+ return exceptions_c.run(trace, args, after)
727
+ refusal = _language_refusal(trace)
728
+ if refusal:
729
+ # Unreachable today, and kept for the language that is not here
730
+ # yet: Python, Rust, TypeScript and C all dispatch above, so every
731
+ # `vocab` column's refusal is `None`. What a further language
732
+ # would be missing is a set of rules, not a record -- and the
733
+ # sentence its own column would carry is the one that says so.
734
+ print(refusal)
735
+ return UNSETTLED
736
+ idx = Index.build(trace, trace.meta)
737
+ _header(trace, idx)
738
+ if not idx.all_raises:
739
+ if idx.uncaught is None and not idx.incomplete:
740
+ # A finalized trace with no raise: the trace answered "none",
741
+ # unless a cap dropped calls and the raise may be one of them.
742
+ if trace.meta.get("trace_truncated"):
743
+ print("no RAISE events recorded (see TRUNCATED above)")
744
+ return UNSETTLED
745
+ print("no exceptions recorded")
746
+ return NEGATIVE
747
+ if idx.uncaught is None:
748
+ # The recording stopped early, so silence here is not "none" --
749
+ # it is a gap, and only a complete recording closes it.
750
+ print("no RAISE events recorded (see INCOMPLETE above)")
751
+ return UNSETTLED
752
+ # An exception escaped, but no RAISE row carries its identity, so
753
+ # the header could only say so ("-- no recorded RAISE carries its
754
+ # identity"). WHICH exception it was is exactly what this command
755
+ # answers, and this recording cannot say -- the same gap as the
756
+ # INCOMPLETE arm above, which is why an incomplete trace that DID
757
+ # capture an uncaught record lands here too rather than in it.
758
+ return UNSETTLED
759
+
760
+ scope = [r for r in idx.all_raises if r.id > after]
761
+ skipped = len(idx.all_raises) - len(scope)
762
+ if skipped:
763
+ print(f"raised ({len(scope)} of {len(idx.all_raises)}; {skipped} "
764
+ f"earlier raise(s) skipped by --after e{after}):")
765
+ else:
766
+ print(f"raised ({len(scope)}):")
767
+
768
+ tally: dict[str, int] = {}
769
+ shown, last = 0, after
770
+ for r in scope:
771
+ d = classify(trace, r, idx)
772
+ tally[d.tag] = tally.get(d.tag, 0) + 1
773
+ if shown < args.limit:
774
+ print(" " + fmt_event(trace, r))
775
+ print(" " + d.verdict)
776
+ if d.detail:
777
+ print(" " + d.detail)
778
+ shown, last = shown + 1, r.id
779
+ # Counted over every raise in scope, not just the printed ones, so the
780
+ # tally never shrinks because a page was clipped.
781
+ print("dispositions: " + ", ".join(f"{t} {tally[t]}" for t in TAG_ORDER
782
+ if tally.get(t)))
783
+ note = more_note(len(scope), shown,
784
+ f"sensorium exceptions {shlex.quote(args.run)} "
785
+ f"--after e{last} --limit {args.limit}")
786
+ if note:
787
+ print(note)
788
+ return ANSWERED