Skip to content

The agent that grows with you

fix(install-state): a locked state.db is not prior use

alt-glitch65ccdf736972
diff --git a/hermes_cli/install_state.py b/hermes_cli/install_state.py
index 430946524b5..51441c673c0 100644
--- a/hermes_cli/install_state.py
+++ b/hermes_cli/install_state.py
@@ -318,15 +318,26 @@ def _provider_login(home: _Root) -> bool:
return False
+_DB_BUSY_SECONDS = 1.0
+_DB_BUSY_ERRORS = frozenset({"SQLITE_BUSY", "SQLITE_LOCKED"})
+
+
def _messages(home: _Root) -> bool:
db = home.path / "state.db"
if not db.is_file():
return False
# Read-only URI, never the state registry: that opens a writer and migrates a schema we do not own.
- with contextlib.closing(sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True, timeout=1)) as conn:
- if conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='messages'").fetchone() is None:
+ try:
+ with contextlib.closing(sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True, timeout=_DB_BUSY_SECONDS)) as conn:
+ if conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='messages'").fetchone() is None:
+ return False
+ return conn.execute("SELECT 1 FROM messages LIMIT 1").fetchone() is not None
+ except sqlite3.OperationalError as exc:
+ # Still locked after sqlite's own retries: a first boot is creating or healing this database
+ # right now. A lock is not a message, and reading it as "unreadable" would cost a new user the trial.
+ if getattr(exc, "sqlite_errorname", "") in _DB_BUSY_ERRORS:
return False
- return conn.execute("SELECT 1 FROM messages LIMIT 1").fetchone() is not None
+ raise
CHECKS: tuple[tuple[Evidence, Callable[[_Root], bool]], ...] = (
diff --git a/tests/hermes_cli/test_install_state.py b/tests/hermes_cli/test_install_state.py
index 41ac79522f1..5555bccda70 100644
--- a/tests/hermes_cli/test_install_state.py
+++ b/tests/hermes_cli/test_install_state.py
@@ -138,3 +138,19 @@ def test_gateway_service_definitions_name_their_homes(tmp_path, monkeypatch):
str(tmp_path / "*gateway*")))
assert set(install_state._service_homes()) == {home, Path(f"{home}-win")}
+
+
+def test_a_state_db_another_process_holds_locked_is_not_use(machine, monkeypatch):
+ other, _places = machine
+ db = other / "state.db"
+ sqlite3.connect(db).execute("CREATE TABLE messages (id INTEGER)").connection.close()
+ monkeypatch.setattr(install_state, "_DB_BUSY_SECONDS", 0.05, raising=False)
+ # A first boot creating or healing this state.db holds a write lock while the probe runs.
+ holder = sqlite3.connect(db, isolation_level=None)
+ holder.execute("PRAGMA journal_mode=DELETE")
+ holder.execute("BEGIN EXCLUSIVE")
+ try:
+ assert install_state.probe().fresh
+ finally:
+ holder.execute("ROLLBACK")
+ holder.close()