Skip to content

The agent that grows with you

fix(gateway): never replay a written spool row whose file cannot be deleted

unsupportedpastels2c542f7948a0
diff --git a/gateway/shutdown_flush.py b/gateway/shutdown_flush.py
index c30b50b29a6..e395fc5bd99 100644
--- a/gateway/shutdown_flush.py
+++ b/gateway/shutdown_flush.py
@@ -35,6 +35,9 @@ AGENT_HISTORY_REASON = "shutdown-with-unpersisted-agent-history"
QUARANTINE_SUFFIX = ".bad"
# Monotonic tiebreaker so same-second spool files replay in drop order.
_TRANSCRIPT_SPOOL_SEQ = itertools.count()
+# Spool files whose row was written but which could not be deleted. Replaying one again would write
+# its row twice, so both replay passes skip it for the rest of this process.
+_REPLAYED_UNREMOVABLE: set[Path] = set()
def _get_flush_dir():
@@ -155,6 +158,8 @@ def drain_transcript_spool(session_id: str, replay, *, db_known_failing: bool =
return 0, 0
entries = []
for path in candidates:
+ if path in _REPLAYED_UNREMOVABLE:
+ continue
try:
payload = json.loads(path.read_text(encoding="utf-8-sig"))
except Exception:
@@ -184,7 +189,7 @@ def drain_transcript_spool(session_id: str, replay, *, db_known_failing: bool =
"keeping spool file for retry: %s", path, session_id, exc)
remaining = len(ordered) - idx
break
- path.unlink(missing_ok=True)
+ _remove_replayed(path, session_id)
replayed += 1
if replayed:
logger.info("Replayed %d spooled transcript message(s) for %s after DB recovery", replayed,
@@ -258,6 +263,18 @@ def is_row_rejection(exc: BaseException) -> bool:
return isinstance(exc, (TypeError, ValueError, AttributeError, OverflowError))
+def _remove_replayed(path: Path, session_id: str) -> None:
+ """Delete a spool file whose row was just written. If it cannot be deleted, this process never
+ replays it again, and replay goes on with the files after it, which are still older than any
+ live row. Nothing on disk marks it, so a restart writes the row a second time."""
+ try:
+ path.unlink(missing_ok=True)
+ except OSError as exc:
+ _REPLAYED_UNREMOVABLE.add(path)
+ logger.error("Spooled transcript row for %s was written, but %s could not be deleted (%s); "
+ "delete it by hand, or the next start writes that row again", session_id, path, exc)
+
+
def _quarantine_spool_file(path: Path, session_id: str, exc: BaseException) -> None:
"""Move a spool file whose row the database rejected out of every replay, so it cannot hold its
session's later rows back on every write and every restart. It stays on disk for manual recovery."""
@@ -327,6 +344,8 @@ def recover_pending_spool(session_db=None, *, session_resolver=None) -> tuple[in
blocked_sessions: Dict[str, int] = {}
try:
for path in flush_files:
+ if path in _REPLAYED_UNREMOVABLE:
+ continue
# One unparseable payload or rejected append must only skip THIS file: the file is
# never unlinked, so aborting the pass would re-poison every later boot.
try:
@@ -340,7 +359,7 @@ def recover_pending_spool(session_db=None, *, session_resolver=None) -> tuple[in
session_resolver=session_resolver,
blocked_sessions=blocked_sessions):
recovered += 1
- path.unlink(missing_ok=True)
+ _remove_replayed(path, payload.get("session_key", ""))
# health: allow BLE001 -- per-file boundary moved unchanged from recover_pending_to_db; a traceback per locked-DB file would only add noise
except Exception as exc:
logger.warning("Failed to recover pending message from %s: %s", path, exc)
diff --git a/tests/gateway/test_shutdown_flush_recovery.py b/tests/gateway/test_shutdown_flush_recovery.py
index 70b1faabe0c..08f906f5af6 100644
--- a/tests/gateway/test_shutdown_flush_recovery.py
+++ b/tests/gateway/test_shutdown_flush_recovery.py
@@ -34,6 +34,7 @@ def flush_dir(tmp_path, monkeypatch):
monkeypatch.setattr(
"gateway.shutdown_flush._get_flush_dir", lambda: directory
)
+ monkeypatch.setattr("gateway.shutdown_flush._REPLAYED_UNREMOVABLE", set())
return directory
@@ -105,6 +106,18 @@ def _contents(mock_db) -> list:
return [c.kwargs["content"] for c in mock_db.append_message.call_args_list]
+def _fail_unlink_for(monkeypatch, name: str) -> None:
+ """Make deleting the spool file *name* fail, as on a directory that stopped being writable."""
+ real_unlink = Path.unlink
+
+ def unlink(self, missing_ok=False):
+ if self.name == name:
+ raise PermissionError(13, "Permission denied", str(self))
+ return real_unlink(self, missing_ok=missing_ok)
+
+ monkeypatch.setattr(Path, "unlink", unlink)
+
+
def test_replays_in_drop_order_not_file_name_order(flush_dir):
"""SessionDB restores by AUTOINCREMENT id, so append order IS the order the user sees
after recovery. Production names are ``pending-<uuid4>.json``; these names sort opposite
@@ -356,6 +369,46 @@ def test_transient_no_more_rows_error_keeps_the_row_for_retry(flush_dir, make_st
assert not store._dirty_transcripts
+def test_a_replayed_file_that_cannot_be_deleted_is_not_replayed_again(flush_dir, make_store, monkeypatch):
+ """Its row is already written, so replaying it before the next live write duplicates that row.
+ The files after it are still older than the live row, so they must land first."""
+ _write_spool(flush_dir, "pending-aaa.json", "sess-1",
+ {"role": "user", "content": "old0"}, ts=100, seq=0)
+ second = _write_spool(flush_dir, "pending-bbb.json", "sess-1",
+ {"role": "user", "content": "old1"}, ts=100, seq=1)
+ _fail_unlink_for(monkeypatch, "pending-aaa.json")
+ mock_db = MagicMock()
+ store = make_store(mock_db)
+ store.mark_spooled_drop_sessions({"sess-1"})
+
+ store.append_to_transcript("sess-1", {"role": "user", "content": "live"})
+ store.mark_spooled_drop_sessions({"sess-1"})
+ store.append_to_transcript("sess-1", {"role": "user", "content": "live-2"})
+
+ assert _contents(mock_db) == ["old0", "old1", "live", "live-2"]
+ assert not second.exists()
+ assert not store._dirty_transcripts
+
+
+def test_boot_recovery_counts_and_never_repeats_a_file_it_could_not_delete(
+ flush_dir, make_store, boot_db, monkeypatch):
+ """Boot recovery wrote the row, so it is recovered; the live drain must not write it again."""
+ _write_spool(flush_dir, "pending-aaa.json", "sess-1",
+ {"role": "user", "content": "old0"}, ts=100, seq=0)
+ _write_spool(flush_dir, "pending-bbb.json", "sess-1",
+ {"role": "user", "content": "old1"}, ts=100, seq=1)
+ _fail_unlink_for(monkeypatch, "pending-aaa.json")
+ mock_db = MagicMock()
+ boot_db(mock_db)
+ store = make_store(mock_db)
+
+ assert _boot(store) == 2
+ store.mark_spooled_drop_sessions({"sess-1"})
+ store.append_to_transcript("sess-1", {"role": "user", "content": "live"})
+
+ assert _contents(mock_db) == ["old0", "old1", "live"]
+
+
def test_repairable_spool_replay_failure_still_reaches_fts_rebuild(flush_dir, make_store):
"""A spool replay failure must keep its own type, so the FTS rebuild still runs. After the
repair the older spooled row is written before the live one."""