Skip to content

The agent that grows with you

fix(restore): fail closed on in-process holders before unlinking state.db sidecars

Tekniumada3c28d45c6
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 29dc4d43827..e7751f92afe 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -749,6 +749,11 @@ def _safe_restore_db(src: Path, dst: Path) -> bool:
logger.warning("SQLite safe restore failed for %s -> %s: %s", src, dst, exc)
# Fallback: unlink+move (the old approach). This still works for
# the common case where no other process holds the DB open.
+ from hermes_cli.sqlite_safe_read import (
+ LiveConnectionError,
+ offline_file_access,
+ )
+
try:
holders = _foreign_db_holder_pids(dst)
if holders:
@@ -764,23 +769,43 @@ def _safe_restore_db(src: Path, dst: Path) -> bool:
dst, holders,
)
return False
- tmp = dst.parent / f".{dst.name}.snap_restore"
- shutil.copy2(src, tmp)
- dst.unlink(missing_ok=True)
- # Drop the destination's sidecars before installing the
- # snapshot. The snapshot is a checkpointed ``sqlite3.backup()``
- # image (see ``_safe_copy_db``) that owns no WAL, so any
- # ``-wal``/``-shm`` still sitting here describes the database we
- # just unlinked — an ungracefully killed gateway leaves them
- # behind, which is exactly when a restore gets run. SQLite
- # replays that foreign WAL over the restored file on the next
- # open and the database comes up "malformed" (or silently
- # resurrects post-snapshot rows). Same reasoning as
- # ``_EXCLUDED_SUFFIXES``, applied to the restore destination.
- for _sidecar_suffix in ("-wal", "-shm", "-journal"):
- dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)
- shutil.move(str(tmp), str(dst))
+ # The foreign-pid scan above deliberately excludes THIS process,
+ # but an in-process SessionDB (the agent's own handle during
+ # /snapshot restore, a second SessionDB instance, a read pool)
+ # is exactly as much of a live holder: unlinking the DB and its
+ # sidecars under it leaves this process on deleted-inode fds —
+ # the same #90950 split brain, produced first-party (proven live
+ # on main: `/proc/self/fd` shows `state.db-wal (deleted)` right
+ # after this fallback ran under a tracked connection).
+ # ``offline_file_access`` fails CLOSED when any tracked
+ # connection to *dst* is live and holds the connection-lifecycle
+ # lock across the whole swap so no new connection can appear
+ # mid-replace.
+ with offline_file_access(dst, what="unlink+move restore of"):
+ tmp = dst.parent / f".{dst.name}.snap_restore"
+ shutil.copy2(src, tmp)
+ dst.unlink(missing_ok=True)
+ # Drop the destination's sidecars before installing the
+ # snapshot. The snapshot is a checkpointed ``sqlite3.backup()``
+ # image (see ``_safe_copy_db``) that owns no WAL, so any
+ # ``-wal``/``-shm`` still sitting here describes the database we
+ # just unlinked — an ungracefully killed gateway leaves them
+ # behind, which is exactly when a restore gets run. SQLite
+ # replays that foreign WAL over the restored file on the next
+ # open and the database comes up "malformed" (or silently
+ # resurrects post-snapshot rows). Same reasoning as
+ # ``_EXCLUDED_SUFFIXES``, applied to the restore destination.
+ for _sidecar_suffix in ("-wal", "-shm", "-journal"):
+ dst.with_name(dst.name + _sidecar_suffix).unlink(missing_ok=True)
+ shutil.move(str(tmp), str(dst))
return True
+ except LiveConnectionError as exc2:
+ logger.error(
+ "Refusing unlink+move restore of %s: %s Close the in-process "
+ "database handles (or restart Hermes) and retry.",
+ dst, exc2,
+ )
+ return False
except Exception as exc2:
logger.error("Fallback restore also failed for %s -> %s: %s", src, dst, exc2)
return False
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 3cb2fe1cef7..c23024515ad 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -1996,18 +1996,20 @@ def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:
restored image cannot be silently overwritten by the corrupt database's WAL
replay — see :func:`_clear_stale_sqlite_sidecars`.
- Refuses (returns ``False``) while another process still holds the database
- or its sidecars open: copying a snapshot over a live writer's inode makes
- the writer's page cache and WAL index disagree with the file bytes, and
- its next checkpoint writes pages at offsets that no longer mean what it
- thinks — the #90950 page-1 clobber. ``None`` (scan unavailable) proceeds:
- the updater has already drained gateways, and refusing on "unknown" would
- disable auto-restore on every non-Linux host.
+ Refuses (returns ``False``) while another process — or a live connection
+ in THIS process — still holds the database or its sidecars open: copying a
+ snapshot over a live writer's inode makes the writer's page cache and WAL
+ index disagree with the file bytes, and its next checkpoint writes pages
+ at offsets that no longer mean what it thinks — the #90950 page-1 clobber.
+ ``None`` (scan unavailable) proceeds: the updater has already drained
+ gateways, and refusing on "unknown" would disable auto-restore on every
+ non-Linux host.
Returns ``True`` when the restored file passes an integrity check. Raises
``OSError`` if the copy itself fails, which callers already report.
"""
from hermes_cli.backup import _foreign_db_holder_pids, verify_sqlite_integrity
+ from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access
holders = _foreign_db_holder_pids(state_path)
if holders:
@@ -2017,8 +2019,25 @@ def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:
"then restore manually with /snapshot restore."
)
return False
- _clear_stale_sqlite_sidecars(state_path)
- shutil.copy2(snap_state, state_path)
+ # The foreign-pid scan excludes THIS process on purpose, but an
+ # in-process SessionDB handle is exactly as much of a live holder:
+ # unlinking the -wal/-shm and copy2-ing over the main file under it
+ # leaves this process checkpointing through deleted-inode sidecars —
+ # the #90950 split brain produced first-party (proven live on main:
+ # `/proc/self/fd` shows `state.db-wal (deleted)` right after this ran
+ # under a tracked connection). ``offline_file_access`` fails CLOSED on
+ # any tracked live connection and holds the connection-lifecycle lock
+ # across the sidecar clear + copy so none can appear mid-swap.
+ try:
+ with offline_file_access(state_path, what="restore a snapshot over"):
+ _clear_stale_sqlite_sidecars(state_path)
+ shutil.copy2(snap_state, state_path)
+ except LiveConnectionError as exc:
+ print(
+ f" ✗ Auto-restore refused: {exc} Close the in-process database "
+ "handles (or restart Hermes) and retry."
+ )
+ return False
restored = verify_sqlite_integrity(
state_path, check_header=True, run_pragma=True
)
diff --git a/tests/hermes_cli/test_restore_own_holder_guard.py b/tests/hermes_cli/test_restore_own_holder_guard.py
new file mode 100644
index 00000000000..0535633d908
--- /dev/null
+++ b/tests/hermes_cli/test_restore_own_holder_guard.py
@@ -0,0 +1,133 @@
+"""Regression tests: restore paths must fail closed under an IN-PROCESS
+live connection to the destination database (#90837 / #90950 own-holder gap).
+
+The foreign-pid scan (`_foreign_db_holder_pids`) excludes the calling
+process by design, so before the fix both restore paths would unlink the
+destination DB and its -wal/-shm sidecars while THIS process held a tracked
+connection — leaving the process on deleted-inode fds (the split-brain
+fingerprint from issue #90837's field reports).
+"""
+
+import os
+import sqlite3
+import sys
+
+import pytest
+
+from hermes_cli import backup as backup_mod
+from hermes_cli import update_cmd
+from hermes_cli.sqlite_safe_read import connect_tracked
+
+
+def _make_db(path, marker):
+ conn = sqlite3.connect(str(path))
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("CREATE TABLE t (v TEXT)")
+ conn.execute("INSERT INTO t VALUES (?)", (marker,))
+ conn.commit()
+ conn.close()
+
+
+def _read_marker(path):
+ conn = sqlite3.connect(str(path))
+ try:
+ return conn.execute("SELECT v FROM t LIMIT 1").fetchone()[0]
+ finally:
+ conn.close()
+
+
+def _own_deleted_fds(needle):
+ """Paths of this process's fds pointing at deleted files matching needle."""
+ if not sys.platform.startswith("linux"):
+ return []
+ out = []
+ fd_dir = f"/proc/{os.getpid()}/fd"
+ for fd in os.listdir(fd_dir):
+ try:
+ target = os.readlink(f"{fd_dir}/{fd}")
+ except OSError:
+ continue
+ if needle in target and "(deleted)" in target:
+ out.append(target)
+ return out
+
+
+def live_held_db(tmp_path):
+ """A WAL-mode dst held open by a tracked connection in this process,
+ with a corrupt header so the backup-API restore path genuinely fails
+ (which is what routes _safe_restore_db into its unlink+move fallback)."""
+ dst = tmp_path / "state.db"
+ src = tmp_path / "snap.db"
+ _make_db(src, "snapshot-good")
+ _make_db(dst, "live-old")
+ held = connect_tracked(
+ dst, connect_fn=sqlite3.connect, check_same_thread=False
+ )
+ held.execute("PRAGMA journal_mode=WAL")
+ held.execute("INSERT INTO t VALUES ('held-write')")
+ held.commit()
+ assert (tmp_path / "state.db-wal").exists()
+ with open(dst, "r+b") as fh: # offline-fixture mutation, doomed file
+ fh.write(b"\x00" * 100)
+ try:
+ yield src, dst
+ finally:
+ try:
+ held.close()
+ except Exception:
+ pass
+
+
+def test_safe_restore_fallback_refuses_under_own_live_connection(live_held_db):
+ src, dst = live_held_db
+ wal = dst.with_name(dst.name + "-wal")
+ wal_ino = wal.stat().st_ino
+
+ assert backup_mod._safe_restore_db(src, dst) is False
+
+ # The held generation must survive: same WAL inode, no deleted-fd ghosts.
+ assert wal.exists() and wal.stat().st_ino == wal_ino
+ assert _own_deleted_fds(str(dst.name)) == []
+
+
+def test_update_autorestore_refuses_under_own_live_connection(
+ live_held_db, capsys
+):
+ src, dst = live_held_db
+ wal = dst.with_name(dst.name + "-wal")
+ wal_ino = wal.stat().st_ino
+
+ assert update_cmd._restore_state_db_from_snapshot(dst, src) is False
+
+ out = capsys.readouterr().out
+ assert "Auto-restore refused" in out
+ assert wal.exists() and wal.stat().st_ino == wal_ino
+ assert _own_deleted_fds(str(dst.name)) == []
+
+
+def test_safe_restore_fallback_still_works_without_holder(tmp_path):
+ dst = tmp_path / "state.db"
+ src = tmp_path / "snap.db"
+ _make_db(src, "snapshot-good")
+ _make_db(dst, "live-old")
+ with open(dst, "r+b") as fh:
+ fh.write(b"\x00" * 100)
+
+ assert backup_mod._safe_restore_db(src, dst) is True
+ assert _read_marker(dst) == "snapshot-good"
+
+
+def test_update_autorestore_still_works_without_holder(tmp_path):
+ dst = tmp_path / "state.db"
+ src = tmp_path / "snap.db"
+ _make_db(src, "snapshot-good")
+ _make_db(dst, "live-old")
+ # Stale WAL from a crashed writer must still be cleared.
+ dst.with_name(dst.name + "-wal").write_bytes(b"\x00" * 1024)
+ with open(dst, "r+b") as fh:
+ fh.write(b"\x00" * 100)
+
+ assert update_cmd._restore_state_db_from_snapshot(dst, src) is True
+ assert _read_marker(dst) == "snapshot-good"
+ assert not dst.with_name(dst.name + "-wal").exists()