Skip to content

The agent that grows with you

fix(sessions): backfill legacy message_uid in bounded slices instead of one startup UPDATE

kshitijk4poor07cd98e77c8e
diff --git a/hermes_state_schema.py b/hermes_state_schema.py
index 330e4dbc2bc..8f1884390ce 100644
--- a/hermes_state_schema.py
+++ b/hermes_state_schema.py
@@ -43,6 +43,11 @@ _FTS_HOLDER_FUTILE_SECONDS = 1800.0
# retries are non-blocking probes whose spacing doubles up to the cap.
_FTS_STALE_RETRY_SECONDS = 60.0
_FTS_STALE_RETRY_MAX_SECONDS = 3600.0
+# message_uid legacy backfill: rows per UPDATE (short write-lock holds) and the extra time one open may spend.
+_MESSAGE_UID_BACKFILL_DONE = "message_uid_backfill"
+_MESSAGE_UID_BACKFILL_CURSOR = "message_uid_backfill_id"
+_MESSAGE_UID_BACKFILL_CHUNK = 2000
+_MESSAGE_UID_BACKFILL_BUDGET_S = 1.0
def _holder_cmdline(pid: int) -> str:
@@ -986,7 +991,8 @@ class SessionSchemaMixin:
now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()
cursor.executemany(
"INSERT OR IGNORE INTO state_meta (key, value) VALUES (?, ?)",
- [("store_instance_id", str(uuid.uuid4())), ("store_created_at_utc", now_iso)],
+ [("store_instance_id", str(uuid.uuid4())), ("store_created_at_utc", now_iso),
+ (_MESSAGE_UID_BACKFILL_DONE, "1")], # a fresh store has no legacy rows to backfill
)
else:
self._run_data_migrations(cursor, row[0], fts5_available)
@@ -1051,19 +1057,7 @@ class SessionSchemaMixin:
if current_version < 25:
# v25: de-duplicate system prompt snapshots (old column stays a read fallback).
self._dedupe_legacy_system_prompts(cursor)
- if current_version < 31 and cursor.execute(
- "SELECT 1 FROM state_meta WHERE key = 'message_uid_backfill' LIMIT 1"
- ).fetchone() is None:
- # v31: ``messages.message_uid`` — the durable per-message id. New rows are minted at insert
- # (``_insert_message_rows``, or the ``messages_message_uid_insert`` trigger for an older
- # writer); rows written before the column existed get theirs here, once, so every row a v31
- # store hands to a consumer carries one. Non-deterministic per row: two rows never share a
- # backfilled uid. Its own marker: a store whose schema_version cannot advance (no FTS5) must
- # not repeat the full-table scan on every open.
- cursor.execute(
- "UPDATE messages SET message_uid = lower(hex(randomblob(16))) WHERE message_uid IS NULL"
- )
- self.set_meta("message_uid_backfill", "1", cursor=cursor)
+ self._advance_message_uid_backfill(cursor)
fts_migrations_complete = True
if current_version < 30 and fts5_available:
# v29: cron sessions leave the trigram substring index (they stay in the word index);
@@ -1114,6 +1108,33 @@ class SessionSchemaMixin:
if current_version < SCHEMA_VERSION and fts_migrations_complete and fts5_available:
cursor.execute("UPDATE schema_version SET version = ?", (SCHEMA_VERSION,))
+ def _advance_message_uid_backfill(self, cursor: sqlite3.Cursor) -> None:
+ """Mint ``message_uid`` onto rows written before the column existed, one bounded slice per open.
+
+ A single full-table UPDATE held the write lock for 261 s on an 835k-row / 4.8 GB store, so every
+ sibling process timed out with "database is locked". Id-range chunks commit one at a time (the
+ writer connection is autocommit) and an open spends at most ``_MESSAGE_UID_BACKFILL_BUDGET_S``
+ after its first chunk, so a large store converges over later opens. Until then a legacy row
+ simply has no uid, which every reader already treats as "no identity yet"."""
+ if cursor.execute(
+ "SELECT 1 FROM state_meta WHERE key = ? LIMIT 1", (_MESSAGE_UID_BACKFILL_DONE,)
+ ).fetchone() is not None:
+ return
+ row = cursor.execute("SELECT value FROM state_meta WHERE key = ?", (_MESSAGE_UID_BACKFILL_CURSOR,)).fetchone()
+ done_through = int(row[0]) if row else 0
+ high = cursor.execute("SELECT MAX(id) FROM messages").fetchone()[0] or 0
+ deadline = time.monotonic() + _MESSAGE_UID_BACKFILL_BUDGET_S
+ while done_through < high:
+ upper = done_through + _MESSAGE_UID_BACKFILL_CHUNK
+ cursor.execute(
+ "UPDATE messages SET message_uid = lower(hex(randomblob(16))) "
+ "WHERE id > ? AND id <= ? AND message_uid IS NULL", (done_through, upper))
+ done_through = upper
+ if done_through < high and time.monotonic() >= deadline:
+ self.set_meta(_MESSAGE_UID_BACKFILL_CURSOR, str(done_through), cursor=cursor)
+ return
+ self.set_meta(_MESSAGE_UID_BACKFILL_DONE, "1", cursor=cursor)
+
def _migrate_v22_session_model_usage(self, cursor: sqlite3.Cursor) -> None:
"""v22: ``task`` joins the session_model_usage PRIMARY KEY ('' = main loop; aux calls
named). SQLite cannot ALTER a PK, so rebuild; existing rows → task=''."""
diff --git a/tests/hermes_state/test_message_uid.py b/tests/hermes_state/test_message_uid.py
index 2803bdfe62a..3a870c44b77 100644
--- a/tests/hermes_state/test_message_uid.py
+++ b/tests/hermes_state/test_message_uid.py
@@ -83,52 +83,35 @@ class TestMintAndRestore:
db.append_messages_batch("s", [msg])
assert _rows(db, "s")[0]["message_uid"] == "0" * 32
- def test_legacy_rows_are_backfilled_once_on_open(self, tmp_path):
+ def test_legacy_rows_are_backfilled_in_bounded_slices_across_opens(self, tmp_path, monkeypatch):
+ """A single full-table UPDATE held the write lock for minutes on a large store; each open now
+ mints at most one chunk past its time budget, keeps earlier uids, and converges."""
+ import hermes_state_schema
+
+ monkeypatch.setattr(hermes_state_schema, "_MESSAGE_UID_BACKFILL_CHUNK", 2)
+ monkeypatch.setattr(hermes_state_schema, "_MESSAGE_UID_BACKFILL_BUDGET_S", 0.0)
path = tmp_path / "legacy.db"
first = SessionDB(db_path=path)
try:
- _seed(first, "s")
- # Rows written by a build that predates the column: NULL uid, schema behind v31, no marker.
+ _seed(first, "s", n=5)
+ # Rows written by a build that predates the column: NULL uid, no backfill marker.
first._conn.execute("UPDATE messages SET message_uid = NULL")
- first._conn.execute("UPDATE schema_version SET version = 30")
first._conn.execute("DELETE FROM state_meta WHERE key = 'message_uid_backfill'")
first._conn.commit()
finally:
first.close()
- second = SessionDB(db_path=path)
- try:
- uids = [r["message_uid"] for r in _rows(second, "s")]
- assert all(u and UID_RE.match(u) for u in uids)
- assert len(set(uids)) == len(uids)
- assert second._conn.execute("SELECT version FROM schema_version").fetchone()[0] >= 31
- assert second.get_meta("message_uid_backfill") == "1"
- # Idempotent: a second open keeps the backfilled values.
- second.close()
- third = SessionDB(db_path=path)
+ seen = []
+ for _ in range(3):
+ handle = SessionDB(db_path=path)
try:
- assert [r["message_uid"] for r in _rows(third, "s")] == uids
+ seen.append([r["message_uid"] for r in _rows(handle, "s")])
+ done = handle.get_meta("message_uid_backfill")
finally:
- third.close()
- finally:
- second.close()
-
- def test_the_backfill_marker_gates_the_scan_when_the_version_cannot_advance(self, tmp_path):
- """A store whose schema_version stays behind (no FTS5) must not rescan on every open: the marker,
- not the version, says the one-time backfill ran."""
- path = tmp_path / "marked.db"
- first = SessionDB(db_path=path)
- try:
- _seed(first, "s")
- first._conn.execute("UPDATE messages SET message_uid = NULL")
- first._conn.execute("UPDATE schema_version SET version = 30")
- first.set_meta("message_uid_backfill", "1")
- finally:
- first.close()
- second = SessionDB(db_path=path)
- try:
- assert [r["message_uid"] for r in _rows(second, "s")] == [None] * 4
- finally:
- second.close()
+ handle.close()
+ assert [sum(u is not None for u in uids) for uids in seen] == [2, 4, 5]
+ assert seen[1][:2] == seen[0][:2] and seen[2][:4] == seen[1][:4]
+ assert all(UID_RE.match(u) for u in seen[2]) and len(set(seen[2])) == 5
+ assert done == "1"
def test_a_row_inserted_without_a_uid_by_an_older_writer_gets_one(self, db):
"""The store mints for a build that predates the column (its INSERT binds no uid)."""