Skip to content

The agent that grows with you

fix(recovery): drain .recover dump stderr to a temp file, not a pipe

beardthelion54a769b433ab
diff --git a/hermes_cli/session_lost_and_found.py b/hermes_cli/session_lost_and_found.py
index d4c354c3fc4..2a67bafe718 100644
--- a/hermes_cli/session_lost_and_found.py
+++ b/hermes_cli/session_lost_and_found.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import logging
+import os
import re
import shutil
import sqlite3
@@ -218,22 +219,29 @@ def _cli_recover_attempts(source: Path, lf_path: Path, sqlite3_bin: str, *, time
for command in (".recover --ignore-freelist", ".recover"):
if lf_path.exists():
lf_path.unlink()
- dump = subprocess.Popen(
- [sqlite3_bin, "-readonly", str(source), command], stdout=subprocess.PIPE, stderr=subprocess.PIPE
- )
- load = subprocess.Popen(
- [sqlite3_bin, str(lf_path)], stdin=dump.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
- )
- assert dump.stdout is not None
- dump.stdout.close() # let dump receive SIGPIPE if load dies
- try:
- _, load_err = load.communicate(timeout=timeout)
- dump_err = dump.stderr.read() if dump.stderr is not None else b""
- dump.wait(timeout=60)
- except subprocess.TimeoutExpired:
- dump.kill()
- load.kill()
- raise LostAndFoundError(f"sqlite3 .recover timed out after {timeout:.0f}s")
+ # .recover reports per-page diagnostics on stderr; a heavily damaged source can emit
+ # far more than a pipe buffer holds, so stderr drains to a temp file — an undrained
+ # PIPE would block the dump child, stall load's stdin, and burn the whole timeout.
+ with tempfile.TemporaryFile(prefix="hermes-recover-dump-stderr-") as dump_stderr:
+ dump = subprocess.Popen(
+ [sqlite3_bin, "-readonly", str(source), command], stdout=subprocess.PIPE, stderr=dump_stderr
+ )
+ load = subprocess.Popen(
+ [sqlite3_bin, str(lf_path)], stdin=dump.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
+ )
+ assert dump.stdout is not None
+ dump.stdout.close() # let dump receive SIGPIPE if load dies
+ try:
+ _, load_err = load.communicate(timeout=timeout)
+ dump.wait(timeout=60)
+ dump_stderr.seek(0, os.SEEK_END)
+ tail_size = min(dump_stderr.tell(), 65536)
+ dump_stderr.seek(-tail_size, os.SEEK_END)
+ dump_err = dump_stderr.read()
+ except subprocess.TimeoutExpired:
+ dump.kill()
+ load.kill()
+ raise LostAndFoundError(f"sqlite3 .recover timed out after {timeout:.0f}s")
attempts.append({
"command": command, "dump_returncode": dump.returncode, "load_returncode": load.returncode,
"dump_stderr_tail": dump_err.decode("utf-8", "replace")[-2000:],
diff --git a/tests/hermes_cli/test_session_recovery_lost_and_found.py b/tests/hermes_cli/test_session_recovery_lost_and_found.py
index 0046804c1d8..c20c21c3158 100644
--- a/tests/hermes_cli/test_session_recovery_lost_and_found.py
+++ b/tests/hermes_cli/test_session_recovery_lost_and_found.py
@@ -10,6 +10,8 @@ from __future__ import annotations
import shutil
import sqlite3
+import sys
+import time
from pathlib import Path
import pytest
@@ -19,6 +21,7 @@ from hermes_cli import session_recovery
from hermes_cli import session_schema_history
from hermes_cli.session_lost_and_found import (
STUB_TITLE_PREFIX,
+ _cli_recover_attempts,
classify_lost_and_found_row,
map_lost_and_found_rows,
rebuild_fts_indexes,
@@ -1175,3 +1178,43 @@ def test_recovery_lane_refuses_to_verify_when_rows_matched_no_layout(
assert report["lost_and_found"]["unrecognized_layout_rows"] == 2
assert report["verified"] is False
assert any("matched no known physical column layout" in e for e in report["verification"]["errors"])
+
+
+# ── .recover stderr pipe must be drained while the child runs ──────────────
+
+
[email protected](sys.platform == "win32", reason="stub sqlite3 is a /bin/sh script")
+def test_recover_attempts_survive_dump_stderr_beyond_pipe_buffer(tmp_path: Path) -> None:
+ """A heavily damaged source makes ``.recover`` emit per-page diagnostics on
+ stderr. Past the OS pipe buffer (~64KB) an undrained stderr blocks the dump
+ child, its stdout never reaches EOF, and ``load.communicate()`` burns the
+ whole salvage timeout instead of finishing in milliseconds."""
+ stub = tmp_path / "sqlite3"
+ stub.write_text(
+ "#!/bin/sh\n"
+ 'if [ "$1" = "-readonly" ]; then\n'
+ " i=0\n"
+ " while [ $i -lt 3000 ]; do\n"
+ ' echo "lost and found page $i: orphan btree cell, unable to reconstruct row" >&2\n'
+ " i=$((i+1))\n"
+ " done\n"
+ ' echo "Error: near line 4000: file is not a database" >&2\n'
+ ' echo "CREATE TABLE t(x); INSERT INTO t VALUES(1);"\n'
+ "else\n"
+ " cat >/dev/null\n"
+ "fi\n",
+ encoding="utf-8",
+ )
+ stub.chmod(0o755)
+ source = tmp_path / "source.db"
+ source.write_bytes(b"corrupt")
+ lf_path = tmp_path / "lost_and_found.db"
+
+ started = time.monotonic()
+ attempts = _cli_recover_attempts(source, lf_path, str(stub), timeout=30.0)
+ assert time.monotonic() - started < 30.0
+
+ assert attempts[-1]["dump_returncode"] == 0
+ # The stderr tail is load-bearing: the caller keys the header-zeroing retry
+ # on "not a database" appearing in it, so the drain must preserve it.
+ assert "file is not a database" in attempts[-1]["dump_stderr_tail"]