Skip to content

The agent that grows with you

fix(backup): import SQLite databases without replacing the live inode

joaomarcosd47fe28fc5c7
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 1f49582a2ee..5ecc8520fa5 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -1286,6 +1286,94 @@ def _extract_member_atomically(
raise
+def _count_session_rows(path: Path) -> Optional[Tuple[int, int]]:
+ """Return ``(sessions, messages)`` stored in the session database *path*.
+
+ Read-only and best effort. ``None`` means "unknown" — a missing file, a
+ database that is not a Hermes session store, or one that cannot be read.
+ Callers must never read ``None`` as "zero rows": acting on an unreadable
+ database would mask the very loss this count exists to surface. Same
+ contract as :func:`_count_cron_jobs`.
+ """
+ if not path.is_file():
+ return None
+ try:
+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ except sqlite3.Error:
+ return None
+ try:
+ sessions = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]
+ messages = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
+ return int(sessions), int(messages)
+ except (sqlite3.Error, TypeError, ValueError):
+ return None
+ finally:
+ conn.close()
+
+
+def _import_db_member(
+ zf: zipfile.ZipFile,
+ member: str,
+ target: Path,
+ new_file_mode: Optional[int] = None,
+) -> None:
+ """Publish a SQLite ``.db`` member onto *target* without replacing its inode.
+
+ ``_extract_member_atomically`` publishes with a rename. For an ordinary
+ file that is the safest write available; for a live SQLite database it is
+ the #65942 / #90950 corruption class. A gateway, dashboard, or WebUI
+ process holding the database open keeps its descriptor on the now-unlinked
+ inode: it goes on serving pre-import pages and writing sessions that no
+ other process will ever see, and any sidecar WAL left beside the new file
+ describes the database that was just unlinked. Nothing fails, so nothing
+ is reported — the sessions simply are not there afterwards (issue #100960).
+
+ ``hermes import`` is the disaster-recovery path, so that failure mode lands
+ on users who have already lost something once. Route the member through
+ the same ``_safe_restore_db`` page copy that ``/snapshot restore`` has used
+ since #65942: the live inode is preserved, every open connection converges
+ on the imported data, and the sidecars are handled there. A target that
+ does not exist yet has no holders and no inode worth preserving, so it
+ takes the ordinary atomic publish.
+
+ Raises ``OSError`` when the database could not be replaced safely, so the
+ caller reports a skipped file instead of counting a silent success.
+ """
+ if not target.exists():
+ _extract_member_atomically(zf, member, target, new_file_mode)
+ return
+
+ # The database keeps its own mode/ownership: the bytes come from the
+ # archive but the file does not, so the archive has no say in either.
+ mode = _preserve_file_mode(target)
+ owner = _preserve_file_owner(target)
+
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(target.parent), prefix=f".{target.name[:80]}.", suffix=".dbimport"
+ )
+ try:
+ with os.fdopen(fd, "wb") as dst:
+ # Stream: a multi-gigabyte state.db member must not be held in
+ # memory in one piece.
+ with zf.open(member) as src:
+ shutil.copyfileobj(src, dst)
+ dst.flush()
+ os.fsync(dst.fileno())
+ if not _safe_restore_db(Path(tmp_name), target):
+ raise OSError(
+ "live-safe restore refused or failed; the existing database was "
+ "left untouched. Stop the gateway/dashboard processes holding it "
+ "open and re-run the import."
+ )
+ _restore_file_owner(target, owner)
+ _restore_file_mode(target, mode)
+ finally:
+ try:
+ os.unlink(tmp_name)
+ except OSError:
+ pass
+
+
def run_import(args) -> None:
"""Restore a Hermes backup from a zip file."""
zip_path = Path(args.zipfile).expanduser().resolve()
@@ -1348,6 +1436,10 @@ def run_import(args) -> None:
restored = 0
restored_external = 0
skipped_runtime: list[str] = []
+ # (rel, live_counts, imported_counts) for every session database the
+ # import replaced with one holding fewer rows. A restore is allowed to
+ # do that — it just must not do it silently (issue #100960).
+ db_shrunk: list[tuple[str, tuple[int, int], tuple[int, int]]] = []
home_dir = Path.home().resolve()
# Resolved once: every member is published via a temp file, and mkstemp
# would otherwise create newly restored files as 0600.
@@ -1416,7 +1508,16 @@ def run_import(args) -> None:
try:
target.parent.mkdir(parents=True, exist_ok=True)
- _extract_member_atomically(zf, member, target, new_file_mode)
+ if target.suffix == ".db":
+ # Count before the write: afterwards the rows this import
+ # drops are gone and there is nothing left to compare.
+ before = _count_session_rows(target)
+ _import_db_member(zf, member, target, new_file_mode)
+ after = _count_session_rows(target)
+ if before and after and after[1] < before[1]:
+ db_shrunk.append((rel, before, after))
+ else:
+ _extract_member_atomically(zf, member, target, new_file_mode)
if target.name in _SECRET_FILE_NAMES:
os.chmod(target, 0o600)
restored += 1
@@ -1446,6 +1547,21 @@ def run_import(args) -> None:
if len(errors) > 10:
print(f" ... and {len(errors) - 10} more")
+ if db_shrunk:
+ # The backup predates work that is now overwritten. Say so: the
+ # reported incident was twelve sessions disappearing with nothing
+ # logged anywhere (issue #100960).
+ print("\n ⚠ Session data replaced by older backup contents:")
+ for rel, before, after in db_shrunk:
+ print(
+ f" {rel}: {before[0]} session(s) / {before[1]} message(s)"
+ f" -> {after[0]} / {after[1]}"
+ )
+ print(
+ " Anything recorded after the backup was taken is not in it. "
+ "Recover from a newer backup or snapshot: hermes snapshot list"
+ )
+
if skipped_runtime:
print(
f"\n Preserved {len(skipped_runtime)} runtime state "
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index aa4c80056b9..2bb28260707 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -2225,3 +2225,150 @@ class TestImportHonorsHermesHomeOverride:
backup_mod.run_import(args)
assert calls and calls[0].get("context") == "import"
+
+
+# ---------------------------------------------------------------------------
+# Live session database import (issue #100960)
+# ---------------------------------------------------------------------------
+
+def _write_session_db(path: Path, sessions: int, messages_per_session: int) -> None:
+ """Create a minimal Hermes-shaped session database at *path*."""
+ conn = sqlite3.connect(str(path))
+ try:
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS sessions "
+ "(session_id TEXT PRIMARY KEY, message_count INTEGER)"
+ )
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS messages "
+ "(id INTEGER PRIMARY KEY, session_id TEXT, content TEXT)"
+ )
+ for s in range(sessions):
+ sid = f"sess-{s}"
+ conn.execute(
+ "INSERT INTO sessions VALUES (?, ?)", (sid, messages_per_session)
+ )
+ for m in range(messages_per_session):
+ conn.execute(
+ "INSERT INTO messages (session_id, content) VALUES (?, ?)",
+ (sid, f"{sid}-msg-{m}"),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
+class TestImportLiveSessionDatabase:
+ """`hermes import` must not swap the inode of a database Hermes holds open.
+
+ Publishing state.db with a rename leaves any live gateway/dashboard/WebUI
+ connection reading and writing the unlinked inode, so its sessions vanish
+ from the database everyone else opens and nothing is logged (#100960).
+ """
+
+ def _zip_with_db(self, zip_path: Path, db_path: Path) -> None:
+ with zipfile.ZipFile(zip_path, "w") as zf:
+ zf.write(db_path, "state.db")
+
+ def _prepare(self, tmp_path, monkeypatch, live=(3, 4), backup=(2, 2)):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+
+ live_db = home / "state.db"
+ _write_session_db(live_db, *live)
+
+ staged = tmp_path / "backup-state.db"
+ _write_session_db(staged, *backup)
+ zip_path = tmp_path / "backup.zip"
+ self._zip_with_db(zip_path, staged)
+ return home, live_db, zip_path
+
+ def test_live_holder_sees_imported_rows(self, tmp_path, monkeypatch):
+ """A connection open across the import converges on the imported data."""
+ from hermes_cli.backup import run_import
+
+ home, live_db, zip_path = self._prepare(tmp_path, monkeypatch)
+
+ holder = sqlite3.connect(str(live_db))
+ # Read first so the connection has cached pages of the pre-import file.
+ assert holder.execute("SELECT COUNT(*) FROM messages").fetchone()[0] == 12
+ inode_before = os.stat(live_db).st_ino
+
+ try:
+ run_import(Namespace(zipfile=str(zip_path), force=True))
+ assert holder.execute("SELECT COUNT(*) FROM messages").fetchone()[0] == 4
+ finally:
+ holder.close()
+
+ assert os.stat(live_db).st_ino == inode_before
+ assert _count_rows(live_db) == (2, 4)
+
+ def test_older_backup_reports_replaced_sessions(self, tmp_path, monkeypatch, capsys):
+ """Importing a backup that predates recorded work says what it dropped."""
+ from hermes_cli.backup import run_import
+
+ home, live_db, zip_path = self._prepare(tmp_path, monkeypatch)
+ run_import(Namespace(zipfile=str(zip_path), force=True))
+
+ out = capsys.readouterr().out
+ assert "Session data replaced by older backup contents" in out
+ assert "3 session(s) / 12 message(s) -> 2 / 4" in out
+
+ def test_newer_backup_reports_nothing(self, tmp_path, monkeypatch, capsys):
+ """No warning when the import does not shrink the database."""
+ from hermes_cli.backup import run_import
+
+ home, live_db, zip_path = self._prepare(
+ tmp_path, monkeypatch, live=(1, 1), backup=(3, 4)
+ )
+ run_import(Namespace(zipfile=str(zip_path), force=True))
+
+ out = capsys.readouterr().out
+ assert "Session data replaced by older backup contents" not in out
+
+ def test_refused_restore_is_reported_and_leaves_db_intact(
+ self, tmp_path, monkeypatch, capsys
+ ):
+ """A refused live-safe restore is a warning, not a counted success."""
+ import hermes_cli.backup as backup_mod
+
+ home, live_db, zip_path = self._prepare(tmp_path, monkeypatch)
+ monkeypatch.setattr(backup_mod, "_safe_restore_db", lambda src, dst: False)
+
+ backup_mod.run_import(Namespace(zipfile=str(zip_path), force=True))
+
+ out = capsys.readouterr().out
+ assert "files skipped" in out
+ assert "state.db" in out
+ # The pre-import database is still the one on disk.
+ assert _count_rows(live_db) == (3, 12)
+
+ def test_missing_target_takes_the_plain_publish(self, tmp_path, monkeypatch):
+ """A fresh install has no inode to preserve; the member still lands."""
+ from hermes_cli.backup import run_import
+
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+
+ staged = tmp_path / "backup-state.db"
+ _write_session_db(staged, 2, 3)
+ zip_path = tmp_path / "backup.zip"
+ self._zip_with_db(zip_path, staged)
+
+ run_import(Namespace(zipfile=str(zip_path), force=True))
+ assert _count_rows(home / "state.db") == (2, 6)
+
+
+def _count_rows(db_path: Path) -> tuple[int, int]:
+ conn = sqlite3.connect(str(db_path))
+ try:
+ return (
+ conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0],
+ conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0],
+ )
+ finally:
+ conn.close()
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index 0d107524e73..63734a2d6a3 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -1018,6 +1018,21 @@ Restore a previously created Hermes backup into your Hermes home directory. All
Stop the gateway before importing to avoid conflicts with running processes.
:::
+### SQLite databases
+
+`.db` members (`state.db`, `kanban.db`, `response_store.db`, …) are not published with a rename like ordinary files. Renaming would replace the file's inode while a gateway, dashboard, or WebUI process still holds the old one open: that process would keep reading pre-import pages and keep writing sessions nobody else can see, and those sessions would simply be absent from the database everyone opens next — with nothing logged. Instead the imported pages are written **into the existing database file**, the same way `/snapshot restore` does it, so every open connection converges on the imported data.
+
+If the live database cannot be replaced safely — the page copy failed *and* another process still holds the file open — the import leaves that database untouched and lists it under `Warnings (N files skipped)`. Stop the holding processes and re-run.
+
+Importing an older backup over newer work is still allowed, but it is no longer silent. When the imported `state.db` holds fewer messages than the one it replaced, the summary reports it:
+
+```
+ ⚠ Session data replaced by older backup contents:
+ state.db: 12 session(s) / 8912 message(s) -> 3 / 24
+ Anything recorded after the backup was taken is not in it.
+ Recover from a newer backup or snapshot: hermes snapshot list
+```
+
### Examples
```bash
hermes import ~/hermes-backup-20260423.zip # Prompts before overwriting existing config