Debian Codegraph @

docs/plans/crash-recovery-design.md

raw
1 # Crash recovery and bug reporting
2
3 The design behind [#687](https://github.com/tconbeer/harlequin/issues/687): never dump a raw
4 traceback at a user, preserve their work when something goes wrong, and make the report they send us
5 worth reading.
6
7 ## The problem
8
9 An uncaught exception on Harlequin's message pump falls straight through `AppBase._handle_exception`
10 (`app_base.py:68`) into Textual's `_fatal_error()`, which renders a `rich.traceback.Traceback`
11 **with `show_locals=True`** and prints it to stderr. That is intimidating, it tells the user nothing
12 about what to do next, and it puts local variables — connection strings, tokens, query results — on
13 the terminal. Replacing it is a privacy fix as much as a UX one.
14
15 `hsql` has the same hole from the other end. `main()` (`hsql/__init__.py`) catches `ClickException`,
16 `Abort` and `KeyboardInterrupt`; anything else escapes to Python's own handler, which prints a
17 traceback and exits 1 — and 1 is `ExitCode.QUERY`, so a bug in Harlequin is indistinguishable from
18 "the database rejected the SQL." A caller scripting against hsql's exit codes cannot tell the two
19 apart.
20
21 Three problems compound it:
22
23 - **The user's work is lost.** `write_editor_cache` is called from exactly one place,
24 `Harlequin.action_quit()` (`app.py:970`). A crash, a `kill -9`, a closed terminal or a dropped ssh
25 session loses every open buffer — as does the `self.exit(return_code=2)` path.
26 - **The reports we get are thin.** `bug_report.md` asks for version, adapter, shell, terminal, OS,
27 locale and install method as free text, so most reports arrive missing half of it.
28 - **A crash at startup could repeat forever.** [#745](https://github.com/tconbeer/harlequin/issues/745)
29 crashed *inside* `EditorCollection.on_mount` while replaying cached buffers. Saving buffers on
30 crash without a guard turns a one-time crash into a crash loop, which is worse than what we have
31 now.
32
33 Outcome: a crash exits cleanly with a short panel naming a crash report file; the user's buffers
34 survive and come back on the next launch; a crash *while restoring* those buffers cannot repeat; and
35 the report drops into an issue template built to receive it.
36
37 ## The two ideas that carry it
38
39 **A per-process recovery file, separate from the shared cache.** Checkpoints go to
40 `recovery-<pid>.pickle`, never to `cache-1.pickle`. Two Harlequins on one machine keep today's
41 comprehensible "last clean quit wins" semantics instead of thrashing a shared file every minute, and
42 a checkpoint can never overwrite what another process wrote when it quit cleanly.
43
44 **Rename before replay.** `os.replace` the recovery file to `<name>.replayed` *before* unpickling and
45 replaying it. If unpickling or replaying crashes, the next start finds nothing to replay. That is the
46 whole crash-loop guard — one line, no session sentinel, no PID-liveness check, and correct across
47 concurrent processes by construction.
48
49 **Where the crash message goes.** Textual's `panic()` calls `_close_messages_no_wait()`, so the
50 message pump is gone the moment we handle the exception: an in-app modal is unreachable from
51 `_handle_exception`, and attempting one re-enters an app that has already proven it is broken. The
52 message is a rich `Panel` at `_exit_renderables[0]`, printed to stderr after the terminal is
53 restored — the same mechanism `AppBase.__init__` already uses for a bad theme.
54
55 ## `editor_cache.py`
56
57 ```python
58 CHECKPOINT_INTERVAL_SECONDS = 60.0
59 RECOVERY_STALE_SECONDS = 3 * CHECKPOINT_INTERVAL_SECONDS
60
61 def write_cache(cache: Cache) -> bool # now atomic, and never raises
62 def get_recovery_file() -> Path # cache dir / f"recovery-{os.getpid()}.pickle"
63 def write_recovery(cache: Cache) -> bool
64 def clear_recovery() -> None
65 def adopt_recovery() -> tuple[Cache | None, Path | None]
66 ```
67
68 `CACHE_VERSION` stays `1` — the pickled shape does not change.
69
70 - **Atomic write.** Both writers go through `_write_pickle(cache, path)`: a temp file in the same
71 directory (carrying the pid, so a killed process leaves at most one bounded stray),
72 `flush()` + `os.fsync()`, then `os.replace()`. Same-directory means a same-volume rename, atomic on
73 POSIX and on Windows. The `fsync` is what stops a power loss leaving a zero-length file.
74 - **Never raises.** Returns `False` on `OSError` / `pickle.PicklingError`. Both callers run where an
75 exception would itself take the app down. On Windows `os.replace` raises `PermissionError` when
76 another process holds the destination open, so a checkpoint has to be allowed to skip silently.
77 - **`adopt_recovery()`** globs `recovered-*.pickle` (written by the crash handler) newest first, then
78 `recovery-*.pickle` whose mtime is older than `RECOVERY_STALE_SECONDS` — that age test is how a
79 live sibling process's file is left alone, without a PID-liveness check that would be wrong on
80 Windows and wrong under PID reuse. It renames the chosen file to `.replayed` **before** unpickling
81 it, and returns `(cache, replayed_path)` so the app can say where the buffers came from.
82 Everything wrapped → `(None, None)`.
83
84 Derive `get_recovery_file()` from the same `user_cache_dir` call as `get_cache_file()`, so
85 `tests/functional_tests/test_cache.py:43`'s existing monkeypatch covers the new files for free.
86
87 ## Checkpointing (`app.py`)
88
89 - `on_mount`: `self.set_interval(CHECKPOINT_INTERVAL_SECONDS, self._checkpoint_editor_cache)`.
90 - `_checkpoint_editor_cache()`:
91 - bail when `getattr(self, "editor_collection", None)` is None or not mounted — the collection is
92 created in `compose()`, not `__init__`;
93 - build `Cache(focus_index=..., buffers=...)` on the message pump (the `buffers` property queries
94 widgets — `code_editor.py:294` calls `_save_loaded_buffer()` first);
95 - **bail when every buffer is blank.** A startup crash gives `buffers == []`, and writing that over
96 a good recovery file destroys exactly the work this feature exists to save;
97 - bail when `cache == self._last_checkpointed_cache`. `Cache`/`BufferState` are dataclasses and
98 `Selection` is a NamedTuple, so `==` is an exact content comparison — no dirty flag to keep in
99 sync across tab swaps;
100 - `write_recovery(cache)`, synchronously. Pickling a few SQL buffers is microseconds; a thread
101 worker would add ordering hazards (two checkpoints racing; `exclusive=True` cancelling one
102 mid-flight while its thread still completes the write) for no measured win.
103 - `action_quit()` keeps its `write_editor_cache(...)` and then calls `clear_recovery()`.
104
105 ## Restoring (`components/code_editor.py`)
106
107 `EditorCollection.__init__` keeps `self.startup_cache = load_cache()` and adds
108 `self.recovered_cache, self.recovered_from = adopt_recovery()`. **Two separate module-level names**,
109 not folded into `load_cache()`, so `tests/functional_tests/conftest.py`'s `no_use_buffer_cache`
110 fixture stays the one seam.
111
112 `on_mount` prefers `recovered_cache` over `startup_cache` when present — a recovered session started
113 from the cache, so it is strictly newer — and then notifies: *"Recovered buffers from a session that
114 ended unexpectedly."* The shared `cache-1.pickle` is left untouched, so if the recovered content is
115 itself the problem, the last clean-quit state is still on disk.
116
117 ## `environment.py` (new, headless)
118
119 Facts about the running installation, shared by `hsql --info`, the crash report, and (later) the
120 Debug Info screen. No textual, no rich; `adapter_facts` defers `harlequin.plugins` into its body as
121 `info._adapters` already does.
122
123 ```python
124 def harlequin_version() -> str
125 def python_facts() -> dict[str, str] # version, implementation, executable
126 def platform_facts() -> dict[str, str] # system, release, machine
127 def terminal_facts() -> dict[str, Any] # term, term_program(+version), colorterm, shell,
128 # wsl_distro, ssh (bool), locale, size
129 def install_facts() -> dict[str, Any] # installer, in_venv
130 def adapter_facts(only: str | None = None) -> dict[str, dict[str, Any]]
131 def runtime_report() -> dict[str, Any]
132 ```
133
134 - `terminal_facts()` reports `ssh: True/False` and **never the value of `SSH_CONNECTION`**, which
135 holds IP addresses. `size` from `shutil.get_terminal_size()`.
136 - `install_facts()` reads `distribution("harlequin").read_text("INSTALLER")` (pip/uv/pipx write it)
137 and `sys.prefix != sys.base_prefix` — that answers the bug template's install-method checkbox
138 automatically.
139 - `adapter_facts` is `info._adapters` + `info._capabilities` moved verbatim, minus the
140 `diagnostics.note()` call, which a shared module cannot make.
141
142 `hsql/modes/info.py` then calls these instead of building the facts itself, and keeps its stderr note
143 by walking `adapter_facts()`'s result for entries with an `error`. **Acceptance criterion:
144 `hsql --info`'s JSON is byte-identical.** `terminal_facts` and `install_facts` are *not* added to
145 that document — it is an agent-facing contract with a generated reference pinned by
146 `test_cli_reference.py`, and `TERM` means nothing to a non-interactive program.
147
148 Add `harlequin.environment` and `harlequin.crash` to the `source_modules` of the "adapter API is
149 reachable without the TUI" import-linter contract, and to `HEADLESS_IMPORTS` in
150 `tests/unit_tests/test_import_hygiene.py`. Both have to stay headless anyway, because `hsql` imports
151 them.
152
153 ## `crash.py` (new, headless)
154
155 ```python
156 CRASH_REPORT_KEEP = 10
157 ISSUE_URL = "https://github.com/tconbeer/harlequin/issues/new?template=crash_report.md"
158
159 def get_crash_report_dir() -> Path
160 def root_cause(error: BaseException) -> BaseException
161 def build_crash_report(error: BaseException, context: Mapping[str, Any],
162 program: str = "harlequin") -> str
163 def write_crash_report(report: str) -> Path | None
164 def crash_message(report_path: Path | None, error: BaseException, saved: bool,
165 program: str = "harlequin") -> str
166 ```
167
168 - **Location.** `platformdirs.user_log_path(appname="harlequin", appauthor=False)` —
169 `~/Library/Logs/harlequin` on macOS, `~/.local/state/harlequin/log` on Linux,
170 `%LOCALAPPDATA%\harlequin\Logs` on Windows. Not the cache dir: a cache is what a user is told to
171 delete when things go wrong, and this is the file we are asking them to keep. Match `config.py`'s
172 `appauthor=False` — `editor_cache`/`catalog_cache` omit it and so nest twice on Windows; don't copy
173 that.
174 - **`root_cause`** unwraps a Textual `WorkerFailed` via `getattr(error, "error", None)` rather than
175 importing it, so this module stays headless. It matters: `database_tree.py:498` (`_loader`) and
176 `code_editor.py:88` (`read_symbols`) are the two `@work` decorators in `src/` that omit
177 `exit_on_error=False`, so they *do* reach `_handle_exception`, wrapped. A report naming
178 `WorkerFailed` is a useless report.
179 - **Content**, in order: a header telling the user to review the file before sharing and linking
180 `ISSUE_URL`; `runtime_report()`; the `context` the caller supplied; `traceback.format_exception`
181 for the root cause and, when different, the wrapper — **no `show_locals`**; and last, under a
182 heading that says what it is, the SQL in the active buffer.
183 - **Plain text, not markdown**, written as `crash-{utc:%Y%m%dT%H%M%SZ}-{pid}.log`. The user pastes
184 this into a fenced block in an issue, and a markdown report's own ` ``` ` fences would break out of
185 it. Sections are delimited with plain `=== SECTION ===` rules for the same reason.
186 - **The active buffer's SQL is included deliberately.** It is usually what is needed to reproduce a
187 TUI bug, the file is local, and the user chooses whether to paste it. The tradeoff is real — SQL
188 holds table names and literals — so it goes last, under an explicit heading, and both the panel and
189 the issue template say to review before sharing. Only the *active* buffer; the rest live in the
190 recovery file.
191 - **Redaction.** The whole assembled string goes through `redact.redact_text()` once at the end — one
192 choke point, matching `hsql/diagnostics.py::_write`'s discipline.
193 - **Pruning.** Newest `CRASH_REPORT_KEEP` kept. Distinct filenames per crash, so a loop cannot
194 destroy the evidence. `write_crash_report` returns `None` and raises nothing when the directory is
195 unwritable.
196
197 `exception.py` gains `class HarlequinCrashError(HarlequinError): pass`, so the panel is
198 `pretty_error_message(HarlequinCrashError(crash_message(...), title="Harlequin crashed."))` — no new
199 rendering code, rich stays lazily imported, and it looks like every other Harlequin panel.
200
201 ## The handler (`app_base.py`)
202
203 Two hooks with working base implementations, so `keys_app.py` gets crash reports too:
204
205 ```python
206 def _save_work_on_crash(self) -> bool:
207 """Persist anything the user would lose. False if there was nothing to save."""
208 return False
209
210
211 def _crash_context(self) -> dict[str, Any]:
212 """What this app was doing, for the crash report."""
213 return {}
214
215
216 def _handle_exception(self, error: Exception) -> None:
217 if self._exit or self._crash_handled:
218 return
219 self._crash_handled = True
220
221 saved = False
222 try:
223 saved = self._save_work_on_crash()
224 except BaseException:
225 pass
226
227 report_path = None
228 try:
229 report = build_crash_report(error, self._crash_context())
230 report_path = write_crash_report(report)
231 except BaseException:
232 pass
233
234 try:
235 self.bell()
236 self._return_code = 1
237 # run_test re-raises from these
238 if self._exception is None:
239 self._exception = error
240 self._exception_event.set()
241 message = crash_message(report_path, error, saved)
242 panel = HarlequinCrashError(message, title="Harlequin crashed.")
243 self.panic(pretty_error_message(panel))
244 except BaseException:
245 # last resort: the user gets *something*
246 super()._handle_exception(error)
247 return
248
249 # textual run --dev, i.e. `make serve`: append the full traceback at index 1
250 if "debug" in self.features:
251 super()._handle_exception(error)
252 ```
253
254 `self._crash_handled = False` is set at the **top** of `AppBase.__init__`, before the theme
255 `try/except` that can call `self.exit()`. Order matters: save work first (most valuable, most likely
256 to fail), report second, render last. Every stage is independently wrapped — **the crash handler must
257 not be able to raise**, since it runs inside an `except` block, and raising there is how a bug-fix
258 change becomes the bug.
259
260 `panic()` puts the friendly panel at index 0, which is exactly what `_print_error_renderables` shows
261 outside debug mode; in debug mode `super()` appends the traceback and all renderables print. One code
262 path, both audiences. A second exception returns immediately.
263
264 **`Harlequin` overrides both hooks:**
265
266 - `_save_work_on_crash()` builds the same guarded `Cache` as the checkpoint, falling back to
267 `self._last_checkpointed_cache` if building it raises (plausible — the crash may be *in* the
268 editor, and `buffers` calls `_save_loaded_buffer()`), writes it, and renames it to
269 `recovered-<utc>.pickle` so the next start adopts it regardless of age. Separately, in its own
270 `try`, calls `update_catalog_cache(...)`: query history is user work too. Returns whether anything
271 was written, so the message does not claim a save that did not happen.
272 - `_crash_context()` returns adapter class + module + distribution version, adapter entry-point name,
273 profile name, keymaps, theme, whether a connection was open, buffer count, `str(self.size)`, and
274 the recovery path. All cheap, all wrapped. It deliberately does **not** call `adapter_facts()` —
275 importing every installed adapter mid-crash is slow and a fresh place to crash.
276
277 `Harlequin.__init__` gains `adapter_name: str | None = None`; `cli.py` already computes it at line
278 492 but passes only the instance.
279
280 ### Textual internals this leans on
281
282 `textual==8.2.8`, pinned exactly. Each use site gets a comment naming what it is for, and each has a
283 test that fails loudly rather than silently reverting us to raw tracebacks:
284
285 | Internal | Why | Tripwire |
286 |---|---|---|
287 | `self._exit` | existing guard for exceptions after `exit()` | unchanged |
288 | `self._return_code = 1` | so `cli.py` can forward it | test asserts `app.return_code == 1` |
289 | `self._exception` / `_exception_event` | **`run_test` re-raises from these.** Not setting them turns every crashing functional test silently green | the crash test is written as `with pytest.raises(RuntimeError)` |
290 | `self.panic(...)` | appends to `_exit_renderables`, closes the pump | test asserts our panel is at index 0 and no traceback is |
291 | `"debug" in self.features` | `parse_features(os.getenv("TEXTUAL",""))` | test parametrizes over `features` |
292
293 Deliberately untouched: `_fatal_error`, `_print_error_renderables`, `_exit_renderables` (written only
294 through `panic()`), `_close_messages_no_wait` (called only through `panic()`).
295
296 ## `cli.py`
297
298 - **Arm redaction.** Immediately after `config = merge_profile_with_cli(...)` (~line 509) and
299 *before* the `config.pop(...)` cascade strips `conn_str` and the adapter options:
300 `hide_secrets_in(config, adapter_cls.ADAPTER_OPTIONS)`. Today that function is called from exactly
301 one place — `hsql/cli.py:447` — so in an IDE process `redact_text()` masks nothing. Without this,
302 the crash report is not safe to paste.
303 - **Forward the exit code.** `tui.run()` → `ctx.exit(tui.return_code or 0)`, and the same for
304 `app.run()` in the keys-app callback. This also closes a live bug: `self.exit(return_code=2, ...)`
305 on a bad theme, a bad `viewer_max_rows` or a failed connection currently exits **0**.
306 - Pass `adapter_name=adapter_name` to `Harlequin(...)`.
307
308 ## hsql
309
310 hsql gets the same treatment at its own boundary, reusing `crash.py` (which is headless, so the
311 `hsql does not reach the TUI` contract holds).
312
313 **A new exit code.** `diagnostics.ExitCode` gains:
314
315 ```python
316 CRASH = 70
317 """hsql hit a bug in itself. `sysexits.h`'s EX_SOFTWARE."""
318 ```
319
320 70 rather than the next free small integer: `sysexits.h` reserves it for an internal software error,
321 and it cannot be confused with the 1–4 hsql already documents or with 130.
322
323 **`exit_code_for()` does not change.** It maps *caught* failures, and an unrecognized error caught
324 while running a query genuinely is a query failure — that is what `QUERY` means. `CRASH` belongs only
325 at the boundary where nothing else caught the error at all.
326
327 **`main()` (`hsql/__init__.py`) gains a final handler**, after the `ClickException` and
328 `Abort`/`KeyboardInterrupt` clauses:
329
330 ```python
331 except BaseException as e:
332 report_path = write_crash_report(build_crash_report(e, _crash_context(argv), program="hsql"))
333 diagnostics.report_crash(report_path)
334 sys.exit(ExitCode.CRASH)
335 ```
336
337 - `_crash_context(argv)` carries the argv, the resolved subcommand or mode, and the adapter and
338 profile names if the run got far enough to know them. **argv passes through
339 `redact.redact_conn_str()` before `redact_text()`** — a crash during parsing happens before
340 `hide_secrets_in()` runs at `hsql/cli.py:447`, so the registered-secret set is empty and the
341 span-masking is the only thing that catches a DSN typed on the command line.
342 - `diagnostics.report_crash(path)` is the one new stderr line, going through `_write()` like
343 everything else on that stream: what happened, where the report is, and the issue link. Plain text,
344 no panel — hsql writes no box drawing.
345 - No buffer section: hsql has no buffers. The `-c` / `-f` SQL is already in the redacted argv.
346
347 **Not in scope for hsql**, and worth its own pass later: the broad `except Exception` handlers inside
348 `hsql/cli.py` route an internal bug through `exit_code_for()` and so still report it as `QUERY`. The
349 `main()` boundary is the clean win; narrowing those handlers is a separate audit.
350
351 ## The crash report issue template
352
353 New `.github/ISSUE_TEMPLATE/crash_report.md`, which the crash message and `crash.ISSUE_URL` point at.
354 It is deliberately *not* `bug_report.md` with a paste box bolted on: the whole environment block
355 `bug_report.md` asks for as free text is already in the report, so this template asks for the file
356 and the two things the file cannot know — what the user was doing, and whether they can reproduce it.
357
358 ```markdown
359 ---
360 name: Crash Report
361 about: Harlequin or hsql exited unexpectedly and wrote a crash report.
362 title: 'Crash: '
363 labels: 'bug'
364 assignees: ''
365
366 ---
367 **Before proceeding, please acknowledge**:
368 - [ ] I have searched Issues and Discussions in this repo for this error.
369
370 **Paste your crash report below.**
371
372 Harlequin and `hsql` write a crash report and print its path when they exit
373 unexpectedly. If you still have that message on screen, the path is in it.
374 Otherwise, the reports are here:
375
376 | OS | Location |
377 |---|---|
378 | macOS | `~/Library/Logs/harlequin/` |
379 | Linux | `~/.local/state/harlequin/log/` |
380 | Windows | `%LOCALAPPDATA%\harlequin\Logs\` |
381
382 The newest `crash-*.log` is the one you want.
383
384 > [!IMPORTANT]
385 > Please read the report before pasting it. It contains your configuration
386 > (with passwords masked) and the SQL that was in your active buffer.
387
388 <details>
389 <summary>Crash report</summary>
390
391 ```
392 PASTE YOUR CRASH REPORT HERE
393 ```
394
395 </details>
396
397 **What were you doing when it crashed?**
398 Steps to reproduce it, if you know them.
399
400 **Anything else?**
401 Screenshots, or anything the report doesn't cover.
402
403 **Contributing**
404 Are you interested in contributing a fix?
405 - [ ] Yes
406 - [ ] Maybe
407 - [ ] No
408 ```
409
410 `bug_report.md` gains one line under its acknowledgements pointing here: *"Did Harlequin exit with an
411 error and print a crash report path? Use the Crash Report template instead."*
412
413 ## Ordered commits
414
415 Each is independently green under `make check`.
416
417 1. `write_cache` atomic and non-raising. `editor_cache.py` only; no behavior change visible to the app.
418 2. Recovery file + rename-before-replay. `editor_cache.py`, `code_editor.py`, `app.py`'s
419 `clear_recovery`, conftest patches. Nothing writes a recovery file yet, so this is provably inert
420 on the happy path.
421 3. The checkpoint timer — commit 2's machinery gets a producer.
422 4. `environment.py` + the `info.py` refactor. Acceptance: `hsql --info` byte-identical. Import-linter
423 contract and `HEADLESS_IMPORTS` in the same commit.
424 5. `crash.py`, `HarlequinCrashError`, `AppBase._handle_exception`, `Harlequin`'s two hooks,
425 `hide_secrets_in`, `ctx.exit(return_code)`, and the `test_cli.py` fixture fix.
426 6. `ExitCode.CRASH`, `diagnostics.report_crash`, the `main()` handler, hsql's `_crash_context`.
427 7. `.github/ISSUE_TEMPLATE/crash_report.md` and the `bug_report.md` pointer.
428
429 ## Test infrastructure — the landmine
430
431 `run_test`'s re-raise path goes through `_handle_exception`, so **every failing functional test in
432 the suite would write a crash report into the developer's real `user_log_dir`.** Add to
433 `tests/conftest.py`, autouse and session-wide with no marker opt-out, in the spirit of the existing
434 `no_discovered_config`:
435
436 ```python
437 @pytest.fixture(autouse=True)
438 def crash_reports_go_to_tmp(monkeypatch, tmp_path) -> Path:
439 """Every crash a test causes writes here, not into the developer's log dir."""
440 report_dir = tmp_path / "crash-reports"
441 monkeypatch.setattr("harlequin.crash.get_crash_report_dir", lambda: report_dir)
442 return report_dir
443 ```
444
445 Extend `tests/functional_tests/conftest.py::no_use_buffer_cache` in the same commit as the
446 checkpoint timer: patch `harlequin.components.code_editor.adopt_recovery` → `lambda: (None, None)`
447 and `harlequin.app.write_recovery` / `clear_recovery` → no-ops. Keep calling the existing
448 `harlequin.app.write_editor_cache` name so the current patch keeps working.
449
450 `tests/unit_tests/test_cli.py::mock_harlequin` is `MagicMock(spec=Harlequin)`, so `tui.return_code`
451 is a MagicMock and `ctx.exit(mock)` makes `res.exit_code` a MagicMock — **about fifteen existing
452 assertions break.** Set `mock_harlequin.return_value.return_code = 0` in the fixture, and add a test
453 that `return_code = 1` produces `res.exit_code == 1`.
454
455 ## Tests to add
456
457 **`tests/unit_tests/test_editor_cache.py`** (new): no `*.tmp` left behind; a `pickle.dump` that
458 raises leaves the previous cache byte-identical and returns `False`; an unwritable directory returns
459 `False`; `adopt_recovery` renames to `.replayed` *before* returning (the crash-loop guarantee); it
460 ignores a fresh `recovery-<pid>.pickle` and adopts a stale one; it always adopts `recovered-*`.
461
462 **`tests/unit_tests/test_crash.py`** (new): the report names the exception type, message, version and
463 frames; **it prints no secret** — `hide_secrets_in({"conn_str": ["postgres://u:hunter2-and-more@h/db"]})`,
464 raise an error quoting the DSN, assert the secret is absent and `********` present, mirroring
465 `test_the_debug_screen_prints_no_secret`; the report contains no ` ``` ` fence, so it pastes into one;
466 `root_cause` unwraps a `WorkerFailed`; `write_crash_report` prunes to `CRASH_REPORT_KEEP` and returns
467 `None` on `PermissionError`.
468
469 **`tests/functional_tests/test_crash.py`** (new), injecting through `_handle_exception` directly:
470
471 ```python
472 with pytest.raises(RuntimeError):
473 async with app.run_test() as pilot:
474 ...
475 app._handle_exception(RuntimeError("boom"))
476 await pilot.pause()
477 ```
478
479 Assert `app.return_code == 1`; one crash file in the redirected dir; a recovery file holding the
480 buffer text (`@pytest.mark.use_cache`); `"boom"` and the report path in the rendered
481 `_exit_renderables[0]`; `"Traceback (most recent call last)"` **not** in it. Plus: two exceptions in a
482 row produce one report and no recursion; a `write_crash_report` that raises still exits 1 with a
483 panel; `Harlequin(...)` constructed but never run returns `False` from `_save_work_on_crash` without
484 raising (crash before mount); a blank-buffer checkpoint leaves a good recovery file unchanged; and
485 the crash loop — plant a `recovered-*.pickle`, make `action_new_buffer` raise, run and crash, then run
486 a second app and assert one empty buffer and the poisoned file now `.replayed`.
487
488 **`tests/unit_tests/test_hsql.py`**: a callback that raises exits `ExitCode.CRASH` (70) and not
489 `QUERY`; the stderr line names the report path; a DSN passed as `CONN_STR` does not appear in a
490 report written before `hide_secrets_in` has run.
491
492 **No snapshot churn.** Nothing renders in-app except the recovery toast, which is a standard Textual
493 notification; the crash message reaches stderr after the app is gone.
494
495 ## Verification
496
497 ```bash
498 localedef -i en_US -f UTF-8 en_US.UTF-8 # fresh container only
499 make check # ruff, pytest 3.10 + 3.12, mypy
500 uv run lint-imports
501 uv run pytest tests/unit_tests/test_import_hygiene.py tests/unit_tests/test_crash.py \
502 tests/unit_tests/test_editor_cache.py
503 uv run pytest tests/functional_tests/test_crash.py tests/functional_tests/test_cache.py -n0
504 ```
505
506 By hand:
507
508 1. `uv run harlequin f1.db`, type SQL, wait past the checkpoint interval, `kill -9`, restart — the
509 SQL is back and the toast says where it came from.
510 2. Temporarily raise from a key handler and run **without** dev mode (`uv run harlequin f1.db`, not
511 `make serve`): the panel prints instead of a traceback, `echo $?` is 1, and the report at the
512 named path holds the traceback. Repeat with a profile carrying a password and confirm it is masked
513 and that no local variables appear.
514 3. Temporarily raise from `EditorCollection.on_mount`, crash, remove the raise, restart twice: the
515 second start is clean and the poisoned file is `.replayed`.
516 4. `make serve` and crash: the full traceback still prints for developers.
517 5. Temporarily raise from an hsql mode: `echo $?` is 70, the stderr line names the report, and a DSN
518 on the command line is masked in it.
519 6. Paste a real report into the crash report template's fenced block on a scratch issue and confirm
520 it renders as one block.
521
522 ## Known risks
523
524 - **Partial-replay convergence.** If a crash happens partway through replaying recovered buffers,
525 `_save_work_on_crash` may write a new `recovered-*.pickle` holding the subset that loaded. The next
526 start replays fewer buffers, so it converges and terminates — and salvages what it can — but it can
527 take more than one restart.
528 - **Behavior change: both commands now exit non-zero where they exited 0.** `harlequin` returns 1 on a
529 crash and 2 on a config or connection error; `hsql` returns 70 where it previously let Python exit
530 1. Correct, but user-visible, so both get a changelog line.
531 - **The report names `sys.executable`, the config path and `SHELL`**, all of which reveal a username —
532 and all of which `hsql --info` already prints, so this is consistent rather than new.
533
534 ## Deliberately out of scope
535
536 - **`_handle_worker_error` swallows unknown worker errors**
537 ([#1117](https://github.com/tconbeer/harlequin/issues/1117)). `app.py:576` branches on two worker
538 names with no `else`, so any other worker error vanishes silently. The fix needs its own triage of
539 which workers can fail benignly, so it is filed separately.
540 - **Debug Info screen work** — environment rows and a "copy a bug report" binding. Cheap once
541 `environment.py` exists, but it is the only piece with snapshot churn: a visible version or Python
542 row bakes `2.12.2` and `3.10.14` into `Debug Info Screen.svg`, which then fails on every CI Python
543 and after every release. If picked up, put the rows in a **collapsed** `Collapsible` (collapsed
544 children never reach the SVG) and back them with a non-snapshot unit test. Drive-by finding for
545 whoever does: `DebugInfoScreen.move_focus()` queries `#collapsible-client-adapter-details`, which
546 `AdapterDebugInfo.parse_info()` never produces — dead code with a latent `NoMatches`.
547 - **Narrowing hsql's broad `except Exception` handlers** so an internal bug caught inside `cli.py`
548 reports `CRASH` rather than `QUERY`.
549 - A prefilled GitHub issue URL (the ~8KB URL cap cannot carry a traceback) and converting the
550 templates into YAML issue forms.
551 - A `harlequin --debug` flag: the report already holds the full traceback, and `TEXTUAL=debug` /
552 `make serve` already prints it inline.