The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): quarantine only rows sqlite cannot bind
unsupportedpastels55b61dedb895
diff --git a/gateway/session_transcript.py b/gateway/session_transcript.pyindex da8e114e28f..9d33ba85b1c 100644--- a/gateway/session_transcript.py+++ b/gateway/session_transcript.py@@ -48,8 +48,10 @@ _BOUND_TEXT_KEYS = ("role", "tool_name", "tool_call_id", "reasoning", "reasoningdef _bindable_text(value: Any) -> Any:- """*value* when sqlite can bind it as is, else its JSON text (``str`` if that fails too)."""- if value is None or isinstance(value, (str, int, float)):+ """*value* when sqlite can bind it as is, else its JSON text (``str`` if that fails too). An int+ outside sqlite's signed 64-bit range raises OverflowError even for a TEXT column."""+ if value is None or isinstance(value, (str, float)) or (+ isinstance(value, int) and -2**63 <= value < 2**63):return valuetry:return json.dumps(value, default=str)diff --git a/gateway/shutdown_flush.py b/gateway/shutdown_flush.pyindex 10836a2b2bd..c30b50b29a6 100644--- a/gateway/shutdown_flush.py+++ b/gateway/shutdown_flush.py@@ -247,13 +247,15 @@ def _spool_sort_key(payload: Dict[str, Any], name: str) -> tuple:def is_row_rejection(exc: BaseException) -> bool:"""True when the database refused this row's own values, so no retry can succeed: a value sqlite- cannot bind, or a malformed field that fails before the write. Lock, I/O, corruption and routing- failures stay retryable, and so do constraint failures, which can be session-wide."""- if isinstance(exc, sqlite3.InterfaceError):- return True- if isinstance(exc, sqlite3.ProgrammingError):- return "binding parameter" in str(exc).lower()- return isinstance(exc, (TypeError, ValueError, AttributeError))+ cannot bind (an unsupported type, or an int outside 64 bits), or a malformed field that fails+ before the write. Lock, I/O, corruption and routing failures stay retryable, and so do constraint+ failures, which can be session-wide. Only a binding message counts among sqlite errors:+ ``InterfaceError("no more rows available")`` is WAL contention that ``SessionDB`` retries and+ re-raises unchanged once its patience runs out."""+ if isinstance(exc, sqlite3.Error):+ return (isinstance(exc, (sqlite3.InterfaceError, sqlite3.ProgrammingError))+ and "binding parameter" in str(exc).lower())+ return isinstance(exc, (TypeError, ValueError, AttributeError, OverflowError))def _quarantine_spool_file(path: Path, session_id: str, exc: BaseException) -> None:diff --git a/tests/gateway/test_shutdown_flush_recovery.py b/tests/gateway/test_shutdown_flush_recovery.pyindex 23d58aefcd3..70b1faabe0c 100644--- a/tests/gateway/test_shutdown_flush_recovery.py+++ b/tests/gateway/test_shutdown_flush_recovery.py@@ -20,6 +20,7 @@ from gateway.shutdown_flush import (TRANSCRIPT_CAP_DROP_REASON,_order_flush_files,drain_transcript_spool,+ is_row_rejection,recover_gateway_pending,recover_pending_to_db,)@@ -273,13 +274,16 @@ def test_a_poisoned_spool_row_does_not_stop_later_live_rows(flush_dir, tmp_path,{"role": "tool", "content": "result", "tool_call_id": {"bad": 1}}, ts=100, seq=0)_write_spool(flush_dir, "pending-aaa.json", "sess-1",{"role": "user", "content": "older"}, ts=100, seq=1)+ # sqlite cannot bind an int past 64 bits, even into a TEXT column.+ _write_spool(flush_dir, "pending-ccc.json", "sess-1",+ {"role": "tool", "content": "big id", "tool_call_id": 2**100}, ts=100, seq=2)boot_db(db)store = make_store(db)- assert _boot(store) == 2+ assert _boot(store) == 3store.append_to_transcript("sess-1", {"role": "user", "content": "live"})- assert [m["content"] for m in db.get_messages("sess-1")] == ["result", "older", "live"]+ assert [m["content"] for m in db.get_messages("sess-1")] == ["result", "older", "big id", "live"]assert not list(flush_dir.iterdir())assert not store._dirty_transcriptsfinally:@@ -317,6 +321,41 @@ def test_a_row_the_database_rejects_is_quarantined_not_retried(flush_dir, make_sassert not store._dirty_transcripts+def test_only_errors_about_the_rows_own_values_are_rejections():+ """A rejection is quarantined for good, so it must be an error no retry can clear."""+ assert is_row_rejection(sqlite3.ProgrammingError("Error binding parameter 4: type 'dict' is not supported"))+ assert is_row_rejection(sqlite3.InterfaceError("Error binding parameter 3 - probably unsupported type"))+ assert is_row_rejection(OverflowError("Python int too large to convert to SQLite INTEGER"))+ assert not is_row_rejection(sqlite3.InterfaceError("no more rows available"))+ assert not is_row_rejection(sqlite3.OperationalError("database is locked"))+ assert not is_row_rejection(sqlite3.IntegrityError("FOREIGN KEY constraint failed"))+ assert not is_row_rejection(sqlite3.DatabaseError("database disk image is malformed"))+++def test_transient_no_more_rows_error_keeps_the_row_for_retry(flush_dir, make_store, boot_db):+ """SessionDB retries 'no more rows available' as WAL contention and re-raises it unchanged once+ its patience runs out. The row itself is valid, so at boot and in the live drain it must stay on+ disk and be written once the contention clears, not be quarantined."""+ transient = sqlite3.InterfaceError("no more rows available")+ path = _write_spool(flush_dir, "pending-aaa.json", "sess-1",+ {"role": "user", "content": "old"}, ts=100, seq=0)+ mock_db = MagicMock()+ mock_db.append_message.side_effect = [transient, transient, 1, 1, 1]+ boot_db(mock_db)+ store = make_store(mock_db)++ assert _boot(store) == 0+ assert path.exists()+ store.append_to_transcript("sess-1", {"role": "user", "content": "live"})+ assert _contents(mock_db) == ["old", "old"]+ assert path.exists()++ store.append_to_transcript("sess-1", {"role": "user", "content": "live-2"})+ assert _contents(mock_db) == ["old", "old", "old", "live", "live-2"]+ assert not list(flush_dir.iterdir())+ assert not store._dirty_transcripts++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 therepair the older spooled row is written before the live one."""