fix(state): without FTS5, a sibling writer only defers the one-time backfill instead of failing the open
Follow-up to #161753 (@kshitijk4poor's lock re-raise). Without FTS5 the chain never stamps schema_version, so the gated backfills rerun on every open; re-raising a lock error there turned a sibling writer that outlasted the lock patience into a failed open. Re-raise only when this open stamps.
This commit is contained in:
@@ -1190,14 +1190,16 @@ def _stamp_settled_fts_layout(holder: StoreHolder, cursor: sqlite3.Cursor) -> No
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _best_effort_backfill(version: int, swallow: type[Exception] = sqlite3.OperationalError):
|
||||
"""Suppress *swallow* from a best-effort backfill, except a SQLite lock error: the chain stamps
|
||||
``schema_version`` at its end, so a swallowed lock error dropped the backfill for good. Re-raised,
|
||||
it sends the open into ``_connect_and_init_with_lock_patience``'s bounded retry before the stamp."""
|
||||
def _best_effort_backfill(version: int, *, stamps: bool, swallow: type[Exception] = sqlite3.OperationalError):
|
||||
"""Suppress *swallow* from a best-effort backfill. A SQLite lock error is re-raised only when this
|
||||
open *stamps* ``schema_version``: a swallowed one would drop the backfill for good, so it goes to
|
||||
``_connect_and_init_with_lock_patience``'s bounded retry before the stamp. Without FTS5 the version
|
||||
never advances and the gate reruns the backfill on the next open, so a lock only defers it; raising
|
||||
there failed the whole open once a sibling writer outlasted the retry budget."""
|
||||
try:
|
||||
yield
|
||||
except swallow as exc:
|
||||
if isinstance(exc, sqlite3.OperationalError) and is_sqlite_lock_error(exc):
|
||||
if stamps and isinstance(exc, sqlite3.OperationalError) and is_sqlite_lock_error(exc):
|
||||
raise
|
||||
logger.debug("v%d data migration skipped: %s", version, exc)
|
||||
|
||||
@@ -1215,7 +1217,7 @@ def _run_data_migrations(holder: StoreHolder, cursor: sqlite3.Cursor, current_ve
|
||||
# only for source archaeology; unreachable while SCHEMA_VERSION >= 23.
|
||||
if current_version < 16:
|
||||
# v16: tag delegate subagent rows so pickers stay clean after parent deletes orphan them.
|
||||
with _best_effort_backfill(16):
|
||||
with _best_effort_backfill(16, stamps=fts5_available):
|
||||
cursor.execute(
|
||||
"UPDATE sessions SET model_config = json_set("
|
||||
"COALESCE(model_config, '{}'), '$._delegate_from', parent_session_id) "
|
||||
@@ -1237,11 +1239,11 @@ def _run_data_migrations(holder: StoreHolder, cursor: sqlite3.Cursor, current_ve
|
||||
# v18: best-effort gateway metadata backfill from sessions.json.
|
||||
# Backfill display_name / origin_json / expiry_finalized from sessions.json so pre-migration
|
||||
# gateway sessions are discoverable from state.db without the JSON index. See #9006.
|
||||
with _best_effort_backfill(18, swallow=Exception):
|
||||
with _best_effort_backfill(18, stamps=fts5_available, swallow=Exception):
|
||||
_backfill_gateway_metadata_from_sessions_json(holder, cursor)
|
||||
if current_version < 20:
|
||||
# v20: seed session_model_usage from sessions aggregates (OR IGNORE: newer rows win).
|
||||
with _best_effort_backfill(20):
|
||||
with _best_effort_backfill(20, stamps=fts5_available):
|
||||
cursor.execute(_SESSION_MODEL_USAGE_V20_SEED_SQL)
|
||||
if current_version < 22:
|
||||
_migrate_v22_session_model_usage(holder, cursor)
|
||||
@@ -1263,7 +1265,7 @@ def _run_data_migrations(holder: StoreHolder, cursor: sqlite3.Cursor, current_ve
|
||||
# Skip compression continuations of subagent rows: a misrouted child resumed as the chat wrote
|
||||
# its continuation as source='subagent' without the marker, and it must stay a continuation.
|
||||
# json_valid: one malformed model_config would make json_set raise and drop the whole UPDATE.
|
||||
with _best_effort_backfill(33):
|
||||
with _best_effort_backfill(33, stamps=fts5_available):
|
||||
cursor.execute(
|
||||
"UPDATE sessions SET model_config = json_set("
|
||||
"COALESCE(model_config, '{}'), '$._delegate_from', parent_session_id) "
|
||||
|
||||
@@ -127,3 +127,35 @@ def test_a_real_sibling_write_lock_never_drops_the_subagent_retag(tmp_path, monk
|
||||
finally:
|
||||
raw.close()
|
||||
assert json.loads(model_config).get("_delegate_from") == "parent"
|
||||
|
||||
|
||||
def test_without_fts5_a_sibling_write_lock_defers_the_retag_instead_of_failing_the_open(tmp_path, monkeypatch):
|
||||
"""Without FTS5 the version never advances, so the v33 re-tag reruns on every open: a sibling
|
||||
holding the write lock past the open's patience must only defer it, never fail the open."""
|
||||
path = tmp_path / "state.db"
|
||||
holder = StoreHolder(db_path=path)
|
||||
create_session(holder, "parent", source="cli")
|
||||
create_session(holder, "child", source="subagent")
|
||||
holder._execute_write(lambda conn: conn.execute(
|
||||
"UPDATE sessions SET parent_session_id = 'parent', model_config = '{}' WHERE id = 'child'"))
|
||||
holder._execute_write(lambda conn: conn.execute("UPDATE schema_version SET version = 32"))
|
||||
holder.close()
|
||||
monkeypatch.setattr(_schema, "_sqlite_supports_fts5", lambda holder, cursor: False)
|
||||
monkeypatch.setattr(StoreHolder, "_WRITE_PATIENCE_S", 0.5)
|
||||
|
||||
sibling = sqlite3.connect(str(path), isolation_level=None)
|
||||
sibling.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
StoreHolder(db_path=path).close()
|
||||
finally:
|
||||
sibling.execute("COMMIT")
|
||||
sibling.close()
|
||||
assert _schema_version(path) == 32
|
||||
|
||||
StoreHolder(db_path=path).close()
|
||||
raw = sqlite3.connect(str(path))
|
||||
try:
|
||||
model_config = raw.execute("SELECT model_config FROM sessions WHERE id = 'child'").fetchone()[0]
|
||||
finally:
|
||||
raw.close()
|
||||
assert json.loads(model_config).get("_delegate_from") == "parent", "the deferred re-tag never ran"
|
||||
|
||||
@@ -359,7 +359,7 @@ The `schema_version` table stores a single integer. Simple column additions are
|
||||
|
||||
Versions not listed above were declarative column additions handled by `_reconcile_columns()` (version bump only, no data migration).
|
||||
|
||||
The data-migration chain stamps `schema_version` once, at its end, and not at all while FTS5 is unavailable; once stamped, the version-gated backfills (v16/v18/v20/v25/v33) never run again. v16, v20 and v33 skip on a non-lock `OperationalError` and v18 on any non-lock exception, as before. A SQLite lock error from a sibling process holding the write lock propagates instead, so the open's lock-patience loop retries the whole open, up to its deadline, before the stamp. The v25 prompt dedupe still stops on any `OperationalError`, a lock included; rows it did not reach keep the inline `system_prompt` as a read fallback.
|
||||
The data-migration chain stamps `schema_version` once, at its end, and not at all while FTS5 is unavailable; once stamped, the version-gated backfills (v16/v18/v20/v25/v33) never run again. v16, v20 and v33 skip on a non-lock `OperationalError` and v18 on any non-lock exception, as before. A SQLite lock error from a sibling process holding the write lock propagates instead, so the open's lock-patience loop retries the whole open, up to its deadline, before the stamp. While FTS5 is unavailable the version is never stamped, so a lock error there only skips the backfill for this open (the next open reruns it) and never fails the open. The v25 prompt dedupe still stops on any `OperationalError`, a lock included; rows it did not reach keep the inline `system_prompt` as a read fallback.
|
||||
|
||||
Declarative column adds use `ALTER TABLE ADD COLUMN` wrapped in try/except to handle the column-already-exists case (idempotent).
|
||||
|
||||
|
||||
Reference in New Issue
Block a user