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,688 @@
1
+ """`exceptions` for `lang = typescript`: what became of every throw.
2
+
3
+ WHY THIS IS A SEPARATE MODULE
4
+ -----------------------------
5
+ The five words are the Python command's -- `swallowed`, `uncaught`,
6
+ `re-raised`, `propagated`, `ambiguous` -- and so is the rule's shape: a
7
+ handler in a frame that then returned, with no later raise of the same
8
+ exception, is the swallow candidate. What does not transfer is the
9
+ INDEXING. `exceptions_cmd.Index` keys an exception on ``exc["oid"]``, the
10
+ address CPython gave the object, and a TypeScript recording carries no
11
+ address at all; its identity is a `serial` minted per thrown object through
12
+ a `WeakMap` (`typescript/src/dbg.mjs`). And CPython fires HANDLED on
13
+ `finally` and on `await` cleanup, which is why the Python rules hedge every
14
+ handler; this recorder writes HANDLED only where a `catch` clause, a
15
+ rejection callback or a completing `finally` really took the failure, and
16
+ the `how` word says which. Running the Python rules over these rows would
17
+ have keyed every exception on a field that is not there.
18
+
19
+ WHAT THIS MODULE DECIDES, AND WHAT IT REFUSES TO
20
+ ------------------------------------------------
21
+ It decides DISPOSITIONS and nothing else. IDENTITY -- which rows are one
22
+ thrown object -- is the recorder's `serial`, read and never recomputed;
23
+ whether a bound `catch` let its error escape is decided by the transform
24
+ and rides the event as `how` (design R2, `typescript/src/escape.mjs`). Two
25
+ places deriving one fact is two places for it to drift, and each of those
26
+ has its own suite.
27
+
28
+ THE FIVE DISPOSITIONS (design R7, R8)
29
+ -------------------------------------
30
+ ``swallowed`` an absorbing handler took it and the frame holding that
31
+ handler then returned. The only accusation this command
32
+ makes, and the one E6-TS gates.
33
+ ``uncaught`` the process itself reported the rejection unhandled
34
+ (`meta.unhandled_rejections`, R1/R6).
35
+ ``re-raised`` a later raise carries the same serial. Every raise still
36
+ keeps its own block and its own tally entry, as the Python
37
+ output does, so a tally counts raises and stays comparable
38
+ line for line.
39
+ ``propagated`` it left the traced world: out of the test's own root frame,
40
+ where the harness got it, or out of a frame Node entered
41
+ with nothing traced beneath it.
42
+ ``ambiguous`` THE DEFAULT, each reason printed: an escaped or opaque
43
+ handler, a handler frame that never finished, a handler
44
+ frame that then failed for its own reasons, a primitive
45
+ with no identity, a recording that stopped mid-run, an
46
+ untraced catcher -- no handler row in the unit's own
47
+ window and the failure unwound into a traced parent that
48
+ caught it without a trace of its own (S5 rung 3) -- and
49
+ anything else. Nothing reaches SWALLOWED by falling
50
+ through.
51
+
52
+ WHERE THE TRACE CANNOT SAY
53
+ --------------------------
54
+ A thrown PRIMITIVE has nothing to hang a serial on, so every row of one
55
+ carries a fresh number. Within one frame a primitive raise pairs with the
56
+ next handler row carrying equal type and message (design §3.1); anything
57
+ wider -- across frames, or once a second raise of the same text exists --
58
+ is ambiguous, and two primitives are never merged on text (R11).
59
+
60
+ A shape the transform does not record produces no row, and the `how`
61
+ enumeration is the declaration of which ones it does
62
+ (`docs/trace-format/TYPESCRIPT-KEYS.md`). A handler in untraced code -- the
63
+ harness, a library, `.then(fn)` -- leaves nothing, so a failure it took
64
+ reads ambiguous or propagated, never a swallow. A rejection the process
65
+ reported unhandled and no row carries is counted in the header and judged
66
+ nowhere: it has no site, and inventing one is what R1 refuses.
67
+
68
+ The literal token `SWALLOWED` is printed by ONE sentence here -- `_swallowed`'s
69
+ verdict -- and by nothing else, not even by prose saying a shape is never
70
+ one: E6-TS collects the printed SWALLOWED lines and compares the set whole
71
+ (Rust's R15), so a detail line reading "never SWALLOWED" would enter that
72
+ count as an accusation nobody made.
73
+ """
74
+ import shlex
75
+ from pathlib import Path
76
+
77
+ from sensorium.exit import ANSWERED, UNSETTLED
78
+ from sensorium.query import caps
79
+ from sensorium.query.exceptions_cmd import Disposition
80
+ from sensorium.query.fmt import fmt_exc, more_note
81
+ from sensorium.query.vocab import terms
82
+
83
+ TAG_ORDER = ("swallowed", "uncaught", "re-raised", "propagated", "ambiguous")
84
+
85
+ #: Every reason an AMBIGUOUS line can carry, in printing order (design
86
+ #: §2.3). `unnamed` is rule 5's catch-all and the number rung 3 is
87
+ #: measured on; a reason without a key here is a test failure.
88
+ REASON_ORDER = ("escaped", "untraced catcher", "suspended", "translated",
89
+ "primitive", "orphan", "incomplete", "unnamed")
90
+
91
+ #: The `how` words that ABSORB a failure: the clause or callback took it
92
+ #: and nothing of it left by a route the transform can see.
93
+ ABSORBING = frozenset({"catch", "sink_empty_catch", "catch_callback",
94
+ "sink_empty_catch_callback", "sink_finally_return"})
95
+
96
+ #: The `how` words that do NOT: the binding, or a rendering of it, left the
97
+ #: handler (R2), or the handler is a function defined elsewhere and its
98
+ #: parameter's fate was never analysed (R4). One of these anywhere for a
99
+ #: serial is enough to keep every row of it out of a swallow (R8).
100
+ ESCAPING = frozenset({"catch_escaped", "catch_callback_escaped",
101
+ "catch_callback_opaque"})
102
+
103
+ #: `typeof`'s words. `object` with no message is `throw null`, the one
104
+ #: primitive whose `typeof` lies.
105
+ PRIMITIVE_TYPES = frozenset({"string", "number", "boolean", "undefined",
106
+ "symbol", "bigint"})
107
+
108
+
109
+ def _exc(e) -> dict:
110
+ return ((e.payload or {}).get("exc")) or {}
111
+
112
+
113
+ def _how(e) -> str:
114
+ return (e.payload or {}).get("how") or "?"
115
+
116
+
117
+ def _is_primitive(exc: dict) -> bool:
118
+ return (exc.get("type") in PRIMITIVE_TYPES
119
+ or (exc.get("type") == "object" and exc.get("msg") is None))
120
+
121
+
122
+ def _text(exc: dict) -> tuple:
123
+ return (exc.get("type"), exc.get("msg"))
124
+
125
+
126
+ def _site(trace, e) -> tuple:
127
+ """The site an event IS: `(file, line, qualname)` -- the code object's
128
+ file, the event's own line, and the code object's qualname.
129
+
130
+ The identity, not the rendering: two `loadConfig` helpers in two files
131
+ at one line print the same words and are not the same place (Rust's
132
+ ruling R-G12, which the grouper's key is keyed on). A code object this
133
+ trace does not carry is `("?", line, "?")`.
134
+ """
135
+ code = trace.code(e.code_id) if e.code_id is not None else None
136
+ return ((code.file if code is not None else "?"), e.line,
137
+ (code.qualname if code is not None else "?"))
138
+
139
+
140
+ def site_text(site) -> str:
141
+ """`qualname L<line>` -- the way every verdict here names a place, and
142
+ the only spelling of it, so the text the grouper compares cannot drift
143
+ from the text the verdict prints."""
144
+ _file, line, qualname = site
145
+ return f"{qualname} L{line}"
146
+
147
+
148
+ def site_file(site) -> str:
149
+ """The site's file, basename only: what a colliding block adds to tell
150
+ two same-named helpers apart on one line."""
151
+ return Path(site[0]).name
152
+
153
+
154
+ def _at(trace, e) -> str:
155
+ return site_text(_site(trace, e))
156
+
157
+
158
+ class Raise:
159
+ """One unit of judgement: a RAISE, or a handler row no raise minted.
160
+
161
+ ONE PER RAISE EVENT, not one per serial (design §3.3 rule 2): a rethrow
162
+ is its own block with its own verdict, and the origin's block says what
163
+ became of the last raise. `raises` is every raise of this serial, so a
164
+ unit can see the whole journey without the journey becoming the unit.
165
+ """
166
+
167
+ def __init__(self, origin, serial, raises, handled, escaping, absorbing,
168
+ *, orphan=False, primitive=False, unresolved=False):
169
+ self.origin = origin
170
+ self.serial = serial
171
+ self.raises = raises # every RAISE of this serial
172
+ self.handled = handled # the handlers in THIS window
173
+ self.escaping = escaping # escaping handlers, anywhere
174
+ self.absorbing = absorbing # absorbing handlers, anywhere
175
+ self.orphan = orphan
176
+ self.primitive = primitive
177
+ #: A primitive whose rows cannot be linked: another raise of the
178
+ #: same text exists, so which row is which throw is not on the wire.
179
+ self.primitive_rethrown = unresolved
180
+
181
+ @property
182
+ def next_raise(self):
183
+ return next((r for r in self.raises if r.id > self.origin.id), None)
184
+
185
+ @property
186
+ def last_raise(self):
187
+ return self.raises[-1] if self.raises else self.origin
188
+
189
+
190
+ class Index:
191
+ """Everything the rules read, gathered in one pass.
192
+
193
+ The pairing lives here rather than in the rules because it is a fact
194
+ about the RECORD -- which rows are one thrown object -- and the rules
195
+ are about what became of it. §3.1: an object's rows share a serial and
196
+ a window runs from one raise of it to the next, so a loop that rethrows
197
+ one object pairs each raise with its own handler; a primitive's rows
198
+ never share one and pair only within a frame, on equal text.
199
+ """
200
+
201
+ def __init__(self, trace):
202
+ self.trace = trace
203
+ meta = trace.meta
204
+ self.incomplete = bool(meta.get("incomplete"))
205
+ self.rejections = {r["serial"]: r
206
+ for r in (meta.get("unhandled_rejections") or [])
207
+ if r.get("serial") is not None}
208
+ raises, handled = [], []
209
+ for e in trace.events(kind=("RAISE", "HANDLED")):
210
+ if _exc(e):
211
+ (raises if e.kind == "RAISE" else handled).append(e)
212
+ self._raises_by_serial: dict = {}
213
+ for r in raises:
214
+ self._raises_by_serial.setdefault(
215
+ _exc(r).get("serial"), []).append(r)
216
+ self._raises = raises
217
+ self._prim_texts = [_text(_exc(r)) for r in raises
218
+ if _is_primitive(_exc(r))]
219
+ self._left = _unwound_by_serial(trace)
220
+ self.units = self._build(raises, handled)
221
+ self._by_origin = {u.origin.id: u for u in self.units}
222
+
223
+ def _build(self, raises, handled) -> list:
224
+ """One unit per raise, then one per SERIAL no raise minted.
225
+
226
+ Per serial and not per row: two handlers of one rejection are one
227
+ exception handled twice, and splitting them would let the absorbing
228
+ row be judged without seeing the escaping one (R8).
229
+ """
230
+ claimed: set = set()
231
+ units = [self._unit(r, handled, claimed) for r in raises]
232
+ orphans: dict = {}
233
+ for h in handled:
234
+ serial = _exc(h).get("serial")
235
+ if h.id in claimed or serial in self._raises_by_serial:
236
+ continue
237
+ # A row carrying no serial at all is nobody's sibling: keyed on
238
+ # its own id, so two of them are never merged into one story.
239
+ orphans.setdefault(serial if serial is not None else ("e", h.id),
240
+ []).append(h)
241
+ units += [self._orphan(rows) for rows in orphans.values()]
242
+ return sorted(units, key=lambda u: u.origin.id)
243
+
244
+ def _unit(self, r, handled, claimed) -> Raise:
245
+ exc = _exc(r)
246
+ serial = exc.get("serial")
247
+ if serial is None:
248
+ return Raise(r, None, [r], [], [], [])
249
+ if _is_primitive(exc):
250
+ mine = _primitive_partner(r, handled, self._raises)
251
+ claimed.update(h.id for h in mine)
252
+ return Raise(r, serial, [r], mine, _escaping(mine),
253
+ _absorbing(mine), primitive=True,
254
+ unresolved=self._prim_texts.count(_text(exc)) > 1)
255
+ siblings = self._raises_by_serial[serial]
256
+ end = next((x.id for x in siblings if x.id > r.id), None)
257
+ same = [h for h in handled if _exc(h).get("serial") == serial]
258
+ mine = [h for h in same
259
+ if h.id > r.id and (end is None or h.id < end)]
260
+ claimed.update(h.id for h in mine)
261
+ return Raise(r, serial, siblings, mine, _escaping(same),
262
+ _absorbing(same))
263
+
264
+ def _orphan(self, rows) -> Raise:
265
+ exc = _exc(rows[0])
266
+ prim = _is_primitive(exc)
267
+ return Raise(rows[0], exc.get("serial"), [], rows, _escaping(rows),
268
+ _absorbing(rows), orphan=True, primitive=prim,
269
+ unresolved=prim and _text(exc) in self._prim_texts)
270
+
271
+ def unit_of(self, event) -> Raise:
272
+ return self._by_origin[event.id]
273
+
274
+ def left_frame(self, serial):
275
+ """The OUTERMOST frame this serial left by throwing, or None.
276
+
277
+ Outermost, because that is how far the failure got: every frame it
278
+ unwound is on the wire and the one nearest the top of the stack is
279
+ the last word the recording has about where it went.
280
+ """
281
+ return self._left.get(serial)
282
+
283
+ def task_of(self, frame, event):
284
+ """The test a frame belongs to, or None where no test was running.
285
+
286
+ Read from the frame's own CALL row first -- that is the row the
287
+ converter stamped when it opened the frame -- and from the event
288
+ asking only where the frame's row carries none.
289
+ """
290
+ call = (self.trace.event(frame.call_event_id)
291
+ if frame.call_event_id is not None else None)
292
+ tid = (call.task_id if call is not None and call.task_id is not None
293
+ else event.task_id)
294
+ return self.trace.task(tid) if tid is not None else None
295
+
296
+
297
+ def _escaping(handled) -> list:
298
+ return [h for h in handled if _how(h) in ESCAPING]
299
+
300
+
301
+ def _absorbing(handled) -> list:
302
+ return [h for h in handled if _how(h) in ABSORBING]
303
+
304
+
305
+ def _primitive_partner(r, handled, raises) -> list:
306
+ """§3.1's one admitted pairing for a primitive: the next handler row in
307
+ the SAME frame carrying equal type and message, with NO raise between.
308
+
309
+ Nothing wider is admitted. A primitive caught a frame up cannot be told
310
+ from another throw of the same text, and a rule that paired them on
311
+ text would report a swallow the recording does not establish (R11). The
312
+ window closes at the next raise of any kind: once something else has
313
+ been thrown, which throw a later handler row belongs to is a question
314
+ about text, and text is not identity.
315
+ """
316
+ exc = _exc(r)
317
+ end = next((x.id for x in raises if x.id > r.id), None)
318
+ for h in handled:
319
+ if h.id <= r.id or (end is not None and h.id > end):
320
+ continue
321
+ if h.frame_id == r.frame_id and _text(_exc(h)) == _text(exc):
322
+ return [h]
323
+ return []
324
+
325
+
326
+ def _unwound_by_serial(trace) -> dict:
327
+ """serial -> the outermost frame that closed by throwing it."""
328
+ out: dict = {}
329
+ for f in trace.frames():
330
+ if f.closed_by != "unwind":
331
+ continue
332
+ serial = (f.unwind_exc or {}).get("serial")
333
+ if serial is None:
334
+ continue
335
+ best = out.get(serial)
336
+ if best is None or (f.depth, f.id) < (best.depth, best.id):
337
+ out[serial] = f
338
+ return out
339
+
340
+
341
+ # -- the rules, in order (design §3.3) --------------------------------------
342
+ def _uncaught(trace, unit, idx) -> Disposition | None:
343
+ """1. The process reported the rejection unhandled and no later raise
344
+ carries the serial. It has no site of its own where no raise minted it,
345
+ and the verdict says that rather than borrowing a handler's (R1)."""
346
+ if unit.serial not in idx.rejections or unit.next_raise is not None:
347
+ return None
348
+ if unit.orphan:
349
+ return Disposition(
350
+ "uncaught", "UNCAUGHT -- unhandled rejection; born outside "
351
+ "traced code (a reject() or a library)")
352
+ return Disposition(
353
+ "uncaught", "UNCAUGHT -- unhandled rejection; raised at "
354
+ f"{_at(trace, unit.origin)}")
355
+
356
+
357
+ def _reraised(trace, unit, idx) -> Disposition | None:
358
+ """2. A later raise carries this serial, so this row is a hop and not
359
+ an ending. The verdict points at what became of the LAST raise, whose
360
+ own block carries that verdict in full -- the recursion terminates
361
+ because the last raise has no later raise to find."""
362
+ nxt = unit.next_raise
363
+ if nxt is None:
364
+ return None
365
+ tag = classify(trace, idx.unit_of(unit.last_raise), idx).tag
366
+ # No detail: the route is the BLOCK's own last line, printed for every
367
+ # unit that has one by `exceptions_group.print_shape` (which is where
368
+ # the same line has always come from on a Rust block). Carrying it here
369
+ # as well would print one journey twice under one verdict.
370
+ return Disposition(
371
+ "re-raised",
372
+ f"RE-RAISED -- raised again at e{nxt.id} ({_at(trace, nxt)}) "
373
+ f"→ {tag}")
374
+
375
+
376
+ def _unresolved(trace, unit, idx) -> Disposition | None:
377
+ """§3.1, ahead of rules 3 and 4 because it is about IDENTITY and not
378
+ about fate: where a second raise of the same primitive text exists, no
379
+ row of it can be attached to any other, so neither the accusation nor
380
+ the claim that it left the traced world is available.
381
+
382
+ The trigger is trace-global and the sentence says both readings it
383
+ covers: two records of one text may be one throw rethrown OR two
384
+ unrelated throws, and nothing on the wire tells them apart (R11).
385
+ """
386
+ if not unit.primitive_rethrown:
387
+ return None
388
+ return Disposition(
389
+ "ambiguous",
390
+ "AMBIGUOUS -- a primitive carries no identity: two records with "
391
+ "this text may be one throw rethrown or two throws; not followed",
392
+ "every row of a thrown primitive carries a fresh serial, and two "
393
+ "of one text are never merged",
394
+ reason="primitive")
395
+
396
+
397
+ def _birth(trace, unit) -> str | None:
398
+ """Where a handler row no raise minted came from, in the words the
399
+ record supports: `exc.kind` is the whole of what says which."""
400
+ if not unit.orphan:
401
+ return None
402
+ if _exc(unit.origin).get("kind") == "rejection":
403
+ return "born outside a throw statement (a reject())"
404
+ return f"born outside traced code, at {_at(trace, unit.origin)}"
405
+
406
+
407
+ def _swallowed(trace, unit, idx) -> Disposition | None:
408
+ """3. An absorbing handler, a frame that then RETURNED, no later raise
409
+ of the serial, and no escaping handler for it anywhere.
410
+
411
+ The Python rule's thrown-in clause does not transfer: this wire's
412
+ RESUME carries no `thrown` key, so a handler frame that later unwound
413
+ for any reason is rule 5's, never this one's.
414
+ """
415
+ if unit.escaping or unit.next_raise is not None:
416
+ return None
417
+ h = next((h for h in unit.handled if _how(h) in ABSORBING), None)
418
+ if h is None:
419
+ return None
420
+ f = trace.frame(h.frame_id) if h.frame_id is not None else None
421
+ if f is None or f.closed_by != "return":
422
+ return None
423
+ return Disposition(
424
+ "swallowed",
425
+ f"SWALLOWED -- caught by {_how(h)} at e{h.id} ({_at(trace, h)}) in "
426
+ f"f{f.id}, which returned",
427
+ _birth(trace, unit), site=_site(trace, h))
428
+
429
+
430
+ def _still_open_absorber(trace, unit):
431
+ """The first absorbing handler IN THIS UNIT'S OWN WINDOW whose frame
432
+ did NOT close by returning, or None where every one of them did.
433
+
434
+ This is §3.3 rule 4's absorbing conjunct as coded (spec §14 R15),
435
+ scoped to the window by rung 3 (§2.2): `unit.handled` filtered to the
436
+ absorbing set, never `unit.absorbing`. What it is about is unchanged --
437
+ a handler that took the failure and has not finished -- and a frame
438
+ with no row at all still counts as one, because "it returned" is
439
+ exactly what such a row does not establish.
440
+
441
+ An EARLIER window's handler is not read here at all. For a rethrown
442
+ serial `unit.absorbing` carries every absorbing handler of it,
443
+ including the one whose frame was closed BY THIS VERY RETHROW: that
444
+ frame is the rethrow's predecessor, not an unfinished handler, and the
445
+ origin's own block already says `re-raised → <word>` about it. Reading
446
+ it made `catch (e) { console.error(e); throw e }` unwinding a test root
447
+ decline rule 4 and print a reason, about a failure the harness saw.
448
+
449
+ Rule 3's escaping conjunct and rule 4's escaping decline stay
450
+ trace-global, exactly as rung 2 wrote them: an escaped object can be
451
+ rethrown from anywhere, and a later accusation about it would be the
452
+ false one the escape rule exists to prevent.
453
+ """
454
+ for h in [h for h in unit.handled if _how(h) in ABSORBING]:
455
+ f = trace.frame(h.frame_id) if h.frame_id is not None else None
456
+ if f is None or f.closed_by != "return":
457
+ return h
458
+ return None
459
+
460
+
461
+ def _propagated(trace, unit, idx) -> Disposition | None:
462
+ """4. It left the traced world: the outermost frame it unwound has no
463
+ traced caller.
464
+
465
+ Both of §3.3's conjuncts are here, each for the same reason: this
466
+ verdict says nothing traced took the failure, and a recording holding a
467
+ handler row for that serial in this unit's own window (absorbing) or
468
+ anywhere in the trace (escaping) contradicts it. An ESCAPING handler is
469
+ rule 5's escaped verdict; an ABSORBING one whose frame never closed is
470
+ rule 5's suspended verdict -- a parked `.catch(async …)` callback is
471
+ ordinary JavaScript, and its frame unwinding below is not evidence that
472
+ the handler was untraced or that the harness ever saw the failure.
473
+ """
474
+ if unit.escaping or _still_open_absorber(trace, unit) is not None:
475
+ return None
476
+ f = idx.left_frame(unit.serial)
477
+ if f is None or f.parent_id is not None:
478
+ return None
479
+ task = idx.task_of(f, unit.origin)
480
+ if task is None:
481
+ return Disposition("propagated",
482
+ "PROPAGATED -- handler not in traced code")
483
+ name = task.name or terms(trace).unnamed_task
484
+ return Disposition(
485
+ "propagated", f'PROPAGATED -- to the harness: test "{name}" failed')
486
+
487
+
488
+ def _untraced_catcher(trace, unit, idx) -> Disposition | None:
489
+ """§2.1: no handler row in this window, the outermost frame the serial
490
+ left has a traced parent, and that parent is not the raise's own frame.
491
+ Names the footprint; claims nothing about what the untraced code did."""
492
+ if unit.handled or unit.escaping or unit.serial in idx.rejections:
493
+ return None
494
+ f = idx.left_frame(unit.serial)
495
+ if f is None or f.parent_id is None or f.parent_id == unit.origin.frame_id:
496
+ return None
497
+ p = trace.frame(f.parent_id)
498
+ if p is None:
499
+ return None
500
+ code = trace.code(p.code_id)
501
+ where = f"{code.qualname} ({Path(code.file).name})"
502
+ if p.closed_by == "return":
503
+ fate = f"its caller f{p.id} returned; not followed"
504
+ elif p.closed_by == "unwind":
505
+ fate = (f"its caller f{p.id} later unwound with "
506
+ f"{fmt_exc(p.unwind_exc)}: a translation by untraced code, "
507
+ "or a later failure, indistinguishable")
508
+ else:
509
+ fate = (f"its caller f{p.id} had not closed at the end of the "
510
+ "recording; not followed")
511
+ site = (code.file, code.firstlineno, code.qualname) # P3
512
+ return Disposition(
513
+ "ambiguous",
514
+ f"AMBIGUOUS -- caught by untraced code inside {where}: f{f.id} "
515
+ f"unwound, {fate}",
516
+ site=site, reason="untraced catcher")
517
+
518
+
519
+ def _ambiguous(trace, unit, idx) -> Disposition:
520
+ """5. Everything else, with the reason printed. Ambiguous by default is
521
+ what keeps a shape nobody wrote a rule for out of the accusation."""
522
+ if unit.escaping:
523
+ h = unit.escaping[0]
524
+ return Disposition(
525
+ "ambiguous",
526
+ f"AMBIGUOUS -- caught at e{h.id} ({_how(h)}), and the error or "
527
+ "a rendering of it left the handler; not followed",
528
+ site=_site(trace, h), reason="escaped")
529
+ named = _untraced_catcher(trace, unit, idx)
530
+ if named is not None:
531
+ return named
532
+ open_h = _handler_frame(trace, unit, lambda f: f.closed_by is None)
533
+ if open_h is not None:
534
+ h, f = open_h
535
+ state = trace.frame_state(f).state
536
+ tail = ("is still suspended at the end of the recording"
537
+ if state == "suspended"
538
+ else "had not closed at the end of the recording")
539
+ return Disposition("ambiguous",
540
+ f"AMBIGUOUS -- the handler's frame f{f.id} {tail}",
541
+ reason="suspended")
542
+ gone = _handler_frame(
543
+ trace, unit,
544
+ lambda f: (f.closed_by == "unwind"
545
+ and (f.unwind_exc or {}).get("serial") != unit.serial))
546
+ if gone is not None:
547
+ _h, f = gone
548
+ return Disposition(
549
+ "ambiguous",
550
+ f"AMBIGUOUS -- handler's frame f{f.id} later unwound with "
551
+ f"{fmt_exc(f.unwind_exc)}: a translation or a later failure, "
552
+ "indistinguishable",
553
+ reason="translated")
554
+ if idx.incomplete:
555
+ return Disposition(
556
+ "ambiguous",
557
+ "AMBIGUOUS -- this recording never finalized (INCOMPLETE)",
558
+ reason="incomplete")
559
+ # P2: the KEY follows the SENTENCE, so an orphan is keyed `orphan` only
560
+ # where it reaches this catch-all -- one escaping HANDLED above prints
561
+ # the escaped sentence and is counted under `escaped` beside every
562
+ # other verdict reading those words.
563
+ return Disposition(
564
+ "ambiguous",
565
+ "AMBIGUOUS -- no rule of this recorder reaches a verdict here",
566
+ reason="orphan" if unit.orphan else "unnamed")
567
+
568
+
569
+ def _handler_frame(trace, unit, pred):
570
+ """The first of this unit's handlers whose frame satisfies `pred`, as
571
+ `(handler, frame)` -- or None where no handler has such a frame."""
572
+ for h in unit.handled:
573
+ f = trace.frame(h.frame_id) if h.frame_id is not None else None
574
+ if f is not None and pred(f):
575
+ return h, f
576
+ return None
577
+
578
+
579
+ RULES = (_uncaught, _reraised, _unresolved, _swallowed, _propagated)
580
+
581
+
582
+ def classify(trace, unit, idx) -> Disposition:
583
+ """What the recording supports about one raise -- and nothing more."""
584
+ for rule in RULES:
585
+ d = rule(trace, unit, idx)
586
+ if d is not None:
587
+ return d
588
+ return _ambiguous(trace, unit, idx)
589
+
590
+
591
+ # -- rendering --------------------------------------------------------------
592
+ def _hops_line(trace, unit) -> str | None:
593
+ """One object's whole journey on one line, each stop naming the site
594
+ that recorded it. A single-raise unit gets no line: it would repeat the
595
+ head verbatim."""
596
+ if len(unit.raises) < 2:
597
+ return None
598
+ return "hops: " + " → ".join(f"e{e.id} ({_at(trace, e)})"
599
+ for e in unit.raises)
600
+
601
+
602
+ def _header(trace, idx) -> None:
603
+ caps.print_incomplete(
604
+ trace, "a throw whose fate was recorded after the cut is not below, "
605
+ "and its absence here is not evidence it had none")
606
+ if idx.rejections:
607
+ # The same line `info` prints, in the same words. A rejection no
608
+ # row carries is counted HERE and judged nowhere: it has no site,
609
+ # so it opens no block (R1) and a reader who saw only the tally
610
+ # would not know it happened.
611
+ print(f"unhandled rejections: {len(idx.rejections)}")
612
+
613
+
614
+ def run(trace, args, after: int) -> int:
615
+ """`exceptions` on a TypeScript trace. `exceptions_cmd.run` has already
616
+ validated `--limit`, resolved `--after` to the event id `after` and
617
+ opened the trace; the capability gate is the first thing that happens
618
+ here, before any rule reads an event."""
619
+ refusal = caps.require(trace, "err_flow", "exceptions")
620
+ if refusal:
621
+ # The command is spelled correctly and the trace is readable: the
622
+ # recorder declares it wrote no throw-flow record, so the reader's
623
+ # next move is a recording made by one that does.
624
+ print(f"REFUSED: {refusal}")
625
+ return UNSETTLED
626
+ idx = Index(trace)
627
+ _header(trace, idx)
628
+ if not idx.units:
629
+ # Silence on a recording that stopped mid-run is a gap, not a
630
+ # "none" -- `caps.none_status` is the shared rule for which.
631
+ if idx.incomplete:
632
+ print("no RAISE events recorded (see INCOMPLETE above)")
633
+ elif trace.meta.get("trace_truncated"):
634
+ print("no exceptions recorded (see TRUNCATED above)")
635
+ else:
636
+ print("no exceptions recorded")
637
+ return caps.none_status(trace)
638
+
639
+ scope = [u for u in idx.units if u.origin.id > after]
640
+ skipped = len(idx.units) - len(scope)
641
+ if skipped:
642
+ print(f"raised ({len(scope)} of {len(idx.units)}; {skipped} earlier "
643
+ f"raise(s) skipped by --after e{after}):")
644
+ else:
645
+ print(f"raised ({len(scope)}):")
646
+
647
+ # One block per SHAPE, not per raise (§3.4, which adopts the Rust
648
+ # grouper's grain): `--after` has already chosen the raises in scope,
649
+ # and the groups form over exactly those. Fifty raises absorbed by one
650
+ # `catch` are one fact about one place, and fifty blocks saying it are
651
+ # the table an adjudicator would otherwise build by hand.
652
+ #
653
+ # Local: `exceptions_group` imports this module for its renderer, so a
654
+ # module-level import here would be a cycle.
655
+ from sensorium.query.exceptions_group import (TYPESCRIPT, group_units,
656
+ print_shapes)
657
+ # Both tallies come from the grouping pass, which classified every unit
658
+ # in scope exactly once: counting them a second time here would be a
659
+ # second judgement of one record, and the two could disagree.
660
+ shapes, tally, reasons = group_units(trace, scope, idx, classify,
661
+ TYPESCRIPT)
662
+ shown = print_shapes(trace, shapes, args.limit)
663
+ # Counted over every raise in scope, not just the printed ones and not
664
+ # per shape: the tally never shrinks because a page was clipped, and it
665
+ # stays comparable line for line with every per-raise record already
666
+ # written.
667
+ print("dispositions: " + ", ".join(f"{t} {tally[t]}" for t in TAG_ORDER
668
+ if tally.get(t)))
669
+ # §2.3: under the tally, and only where there is an ambiguity to
670
+ # explain. Zero entries are omitted -- a reason nothing wore is not a
671
+ # fact about this run -- and the order is the table's, never the
672
+ # counting order, so two answers are comparable key by key.
673
+ if reasons:
674
+ print("ambiguous by reason: " + ", ".join(
675
+ f"{r} {reasons[r]}" for r in REASON_ORDER if reasons.get(r)))
676
+ # Paging RAISES THE LIMIT rather than naming an event to resume after:
677
+ # `--after` cuts raises, and a cursor that cut a group in half would
678
+ # re-show it as a partial block still labelled with the whole count.
679
+ # The reader's OWN `--after` is carried through (R-G7): dropping it
680
+ # made the continuation answer over a wider scope than the question
681
+ # asked, which is a hint that lies about what it will show.
682
+ scoped = f"--after e{after} " if after else ""
683
+ note = more_note(len(shapes), shown,
684
+ f"sensorium exceptions {shlex.quote(args.run)} "
685
+ f"{scoped}--limit {len(shapes)}")
686
+ if note:
687
+ print(note)
688
+ return ANSWERED