Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(metrics): reuse in-scope db session in record_search to prevent self-deadlock (#6565)

S11bfa1df2cef
diff --git a/changelog.d/+change-password-conditional-evict.bugfix.md b/changelog.d/+change-password-conditional-evict.bugfix.md
new file mode 100644
index 0000000000..22d43f7b97
--- /dev/null
+++ b/changelog.d/+change-password-conditional-evict.bugfix.md
@@ -0,0 +1,22 @@
+fix(database): preserve a concurrent new-password engine across change_password
+
+`change_password` previously evicted the cached engine unconditionally
+after the rekey. A concurrent `open_user_database(new_password)` racing
+the rekey legitimately succeeds against the now-new_password-keyed file
+and caches a fresh engine with the new verifier -- the surviving
+current-key engine for the rest of the session. The unconditional
+eviction dropped it and forced the next caller to re-cold-open, and
+broke the invariant "the engine cached for a user is the one a hammer
+racing this rekey observed" that
+`test_stress_change_password_chain_vs_open_hammers` (the chained-rekey
+race test) pins.
+
+The eviction now uses a new `close_user_database_if_stale` helper that
+matches by verifier: it only drops the cached engine when its verifier
+still matches the OLD password being rekeyed away. A concurrent engine
+published under the NEW verifier is left alone, so the next caller sees
+the surviving engine the hammer saw. This guard NARROWS but does not
+CLOSE the stale-engine window on its own (eviction-at-close races when an
+external close empties the cache mid-rekey); the window is closed by the
+rekey-generation check at publish time in `_cache_connection` (see the
+rekey-epoch fragment).
diff --git a/changelog.d/+change-password-orphan-dispose.bugfix.md b/changelog.d/+change-password-orphan-dispose.bugfix.md
new file mode 100644
index 0000000000..310b2a32c7
--- /dev/null
+++ b/changelog.d/+change-password-orphan-dispose.bugfix.md
@@ -0,0 +1,31 @@
+fix(database): dispose overwritten engine on cache publish + degrade on corrupt verifier
+
+Hardens the post-rekey cache contract that
+`close_user_database_if_stale` enforces, addressing the optional items
+flagged by the post-approval review of PR #6565:
+
+* `_cache_connection` now disposes the previous cached engine it is
+ overwriting, inside the same `_connections_lock` acquisition that
+ publishes the new engine + verifier. Without this, an orphan SQLCipher
+ pool and file handle lingered until GC on exactly the path the
+ conditional-eviction fix made common (concurrent new-password opens
+ against a rekeying database), leaking one stale connection per
+ overwrite. Same-identity republishes do not dispose (the conditional
+ guards against `orphan is engine` to avoid closing a pool a live user
+ is mid-query on).
+
+* `_verifier_matches` now degrades to no-match (returns `False`) instead
+ of raising when `_password_verifiers[username]` is malformed. The
+ helper is called from inside `change_password`'s `finally` block; a
+ raise there would replace the actual `change_password` outcome with a
+ spurious `TypeError` / `ValueError` and the operator would see a
+ confusing "password change failed" instead of the underlying cause.
+ The invariants that produce well-formed entries
+ (`_make_verifier`, `_cache_connection`) are unit-locked, so a corrupt
+ entry can only arrive through external dict mutation; failing safe is
+ the right discipline.
+
+Pinned by `test_cache_connection_disposes_overwritten_engine`,
+`test_change_password_eviction_window_handles_concurrent_publish_deterministically`,
+and `test_verifier_matches_degrades_on_corrupt_entry` in
+`tests/security/test_db_connection_change_password_race.py`.
diff --git a/changelog.d/+change-password-rekey-epoch.bugfix.md b/changelog.d/+change-password-rekey-epoch.bugfix.md
new file mode 100644
index 0000000000..3b4985f6f7
--- /dev/null
+++ b/changelog.d/+change-password-rekey-epoch.bugfix.md
@@ -0,0 +1,29 @@
+fix(database): close the stale-publish window with a rekey generation check
+
+Adds a per-user rekey epoch bumped once per successful `change_password`
+rekey. `_open_user_database_cold` snapshots the generation before its
+SQLCipher round-trip and `_cache_connection` refuses the publish when the
+generation advanced in between (fail CLOSED with dispose + `None`). This
+closes the window eviction-at-close cannot: an `open_user_database(old)`
+that verified against the still-old-keyed file and parked before publishing
+can no longer plant a stale OLD-key engine into a cache emptied mid-rekey
+by an external unconditional close (logout / idle sweep), after which
+`open_user_database(old)` would have been handed that engine without a
+SQLCipher round-trip. A concurrent `open_user_database(new)` snapshotting after
+the rekey (e.g. waited on init_lock and verified after the rekey landed)
+publishes normally, preserving the surviving-engine invariant. A new-password
+open whose cold-open straddles the rekey (snapshotted before, verified after)
+is also refused -- fail CLOSED for the now-correct password; retry succeeds
+(availability-only, fail-closed direction).
+
+Also widens `_verifier_matches` to degrade on two-tuples with wrong-typed
+members (`("x", "y")`, `(b"salt", 123)`), and fixes the race tests'
+`_engine_usable` helper to probe a real table read (`sqlite_master`)
+instead of `SELECT 1`, which under SQLCipher succeeds on a mis-keyed engine
+and measured pool liveness rather than key validity.
+
+Pinned by `test_rekey_epoch_refuses_stale_old_publish`,
+`test_verifier_matches_degrades_on_wrong_typed_members`,
+`test_engine_usable_rejects_mis_keyed_engine`, and
+`test_open_cold_refuses_stale_publish_and_disposes` in
+`tests/security/test_db_connection_change_password_race.py`.
diff --git a/changelog.d/6561.bugfix.md b/changelog.d/6561.bugfix.md
new file mode 100644
index 0000000000..bb8bfacd78
--- /dev/null
+++ b/changelog.d/6561.bugfix.md
@@ -0,0 +1 @@
+Fix multi-connection self-deadlock in `SearchTracker.record_search` by checking `thread_session_manager.in_scope()` and reusing the active `get_user_db_session` inside a savepoint (`session.begin_nested()`) when in-scope, skipping the in-scope write when the caller already has pending ORM state so `begin_nested()` cannot flush unrelated work before CREATE SAVEPOINT, preventing checkout of a second database connection that deadlocked against held write sessions while preserving caller rollback atomicity and isolating telemetry write failures.
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index ca55136235..a08319d0b3 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -298,6 +298,17 @@ class DatabaseManager:
# would self-deadlock. Created lazily; see
# _get_password_change_lock.
self._password_change_locks: Dict[str, threading.Lock] = {}
+ # Per-user rekey generation, bumped once per successful
+ # ``change_password`` rekey. ``_cache_connection`` refuses a publish
+ # whose ``expected_epoch`` predates the current generation, which
+ # closes the stale-publish window eviction-at-close cannot: an
+ # ``open_user_database(old)`` that verified against the old-keyed
+ # file and parked before publishing must not populate the cache
+ # after the rekey lands (see ``_cache_connection``). Bounded by the
+ # number of distinct usernames, like ``_init_locks``; deliberately
+ # retained across closes (logout / idle sweep must not reset it, or
+ # a parked stale open would match again).
+ self._rekey_epoch: Dict[str, int] = {}
self._data_dir_override: Optional[Path] = None
self._initialized_data_dirs: set[Path] = set()
@@ -1034,9 +1045,46 @@ class DatabaseManager:
salt = secrets.token_bytes(16)
return salt, self._compute_verifier_digest(salt, password)
+ def _get_rekey_epoch(self, username: str) -> int:
+ """Return the current rekey generation for ``username`` (0 if none).
+
+ Tolerates managers built via ``__new__`` without ``__init__`` (several
+ tests set only the attributes the method under test touches) by
+ lazily creating the registry. Caller need not hold
+ ``_connections_lock``; this takes it.
+ """
+ with self._connections_lock:
+ epochs = getattr(self, "_rekey_epoch", None)
+ if epochs is None:
+ epochs = {}
+ self._rekey_epoch = epochs
+ return epochs.get(username, 0)
+
+ def _bump_rekey_epoch(self, username: str) -> int:
+ """Advance the rekey generation for ``username`` and return the new value.
+
+ Called once per successful ``change_password`` rekey, under
+ ``_connections_lock``, so a concurrent cold-open's
+ pre-verification snapshot (see ``_open_user_database_cold``) either
+ precedes the bump (stale publish refused) or follows it (fresh
+ publish allowed). Same ``__new__`` tolerance as
+ :meth:`_get_rekey_epoch`.
+ """
+ with self._connections_lock:
+ epochs = getattr(self, "_rekey_epoch", None)
+ if epochs is None:
+ epochs = {}
+ self._rekey_epoch = epochs
+ epochs[username] = epochs.get(username, 0) + 1
+ return epochs[username]
+
def _cache_connection(
- self, username: str, engine: Engine, password: str
- ) -> None:
+ self,
+ username: str,
+ engine: Engine,
+ password: str,
+ expected_epoch: int | None = None,
+ ) -> bool:
"""Publish an engine and the verifier for the password that opened it,
atomically.
@@ -1046,11 +1094,73 @@ class DatabaseManager:
connection always has a matching verifier" true by construction, so a
concurrent open can never observe a connection with a missing or stale
verifier.
+
+ If a previous engine is already cached for ``username`` (the race
+ shape ``close_user_database_if_stale`` is built for: a concurrent
+ ``open_user_database(new_password)`` racing ``change_password`` and
+ overwriting the OLD-key engine we just published), the previous
+ engine reference is captured before the overwrite and disposed inside
+ the same lock acquisition. Without this dispose the orphan's
+ SQLCipher pool and file handle linger until GC, which on the path
+ this PR makes common (concurrent new-password opens against a
+ rekeying database) leaks one stale connection per overwrite. The
+ lock covers both the cache swap and the dispose, so a concurrent
+ ``open_user_database`` cannot observe the new engine as cached
+ while its predecessor is still considered live; this matches the
+ pattern used by ``close_user_database`` and
+ ``close_user_database_if_stale``.
+
+ When ``expected_epoch`` is not None, the publish is refused when a
+ rekey landed between the caller's pre-verification snapshot and this
+ cache swap (``current != expected_epoch``). That is the window
+ eviction-at-close cannot close: an ``open_user_database(old)`` that
+ verified against the still-old-keyed file and parked before this
+ publish would otherwise plant a stale OLD-key engine with a matching
+ old verifier into an emptied cache after the rekey (e.g. an external
+ unconditional close evicted the rekey's own engine mid-flight, so
+ both conditional closes no-op). Refusing the publish fails
+ CLOSED -- the caller disposes its just-verified-but-now-stale
+ engine and returns None, so a later ``open_user_database(old)``
+ cold-opens against the now-new-keyed file and fails as it must.
+ A concurrent ``open_user_database(new)`` that snapshots AFTER
+ the rekey (e.g. it waited on init_lock and verified after the
+ rekey landed) publishes normally, so the surviving-engine
+ invariant is preserved. A new-password open whose cold-open
+ STRADDLES the rekey (snapshotted before, SQLCipher-verified
+ after) is also refused -- fail CLOSED for the now-correct
+ password; retry succeeds. That is an availability-only cost in
+ the fail-closed direction, surfaced on the login route as a
+ single retryable failure. ``None`` (the default, used by the
+ create path and by tests driving the primitive directly) keeps
+ the unconditional publish.
"""
verifier = self._make_verifier(password)
with self._connections_lock:
+ if expected_epoch is not None:
+ epochs = getattr(self, "_rekey_epoch", None)
+ current = epochs.get(username, 0) if epochs is not None else 0
+ if current != expected_epoch:
+ logger.warning(
+ f"Refusing stale publish for {username}: "
+ f"rekey generation advanced "
+ f"({expected_epoch} -> {current}) between "
+ "verification and cache publish",
+ )
+ return False
+ orphan = self.connections.get(username)
self.connections[username] = engine
self._password_verifiers[username] = verifier
+ if orphan is not None and orphan is not engine:
+ # Same swallow-and-log discipline as the unconditional close:
+ # the orphan has already been evicted from the cache, so a
+ # failed dispose only delays GC of its pool/handle.
+ try:
+ orphan.dispose()
+ except Exception:
+ logger.warning(
+ f"Failed to dispose orphaned engine for {username}",
+ )
+ return True
def _record_password_verifier(self, username: str, password: str) -> None:
"""Arm the verifier for a connection cached by other means.
@@ -1069,14 +1179,38 @@ class DatabaseManager:
Fails CLOSED: a missing verifier returns False so the caller falls
through to a real key-validating open. Returning True on a missing
verifier would reopen exactly the hole this closes.
+
+ A malformed entry (anything that is not a ``(salt, expected)`` tuple
+ of bytes, including a two-tuple with wrong-typed members such as
+ ``("x", "y")`` or ``(b"salt", 123)``) also returns False rather than
+ propagating. The call sites run inside ``change_password``'s
+ ``finally`` block -- any raise here would replace the actual
+ ``change_password`` outcome with a spurious ``ValueError`` /
+ ``TypeError`` and the operator would see a confusing
+ "password change failed" instead of the underlying cause. The
+ invariants that produce well-formed entries (``_make_verifier`` and
+ ``_cache_connection``) are unit-locked, so a corrupt entry can only
+ arrive through external dict mutation; degrading to no-match is
+ safer than letting that exception escape.
"""
entry = self._password_verifiers.get(username)
if entry is None:
return False
- salt, expected = entry
- return hmac.compare_digest(
- self._compute_verifier_digest(salt, password), expected
- )
+ try:
+ salt, expected = entry
+ if not isinstance(salt, bytes) or not isinstance(expected, bytes):
+ logger.warning(
+ f"Malformed verifier entry for {username}; treating as no-match"
+ )
+ return False
+ return hmac.compare_digest(
+ self._compute_verifier_digest(salt, password), expected
+ )
+ except (TypeError, ValueError, AttributeError):
+ logger.warning(
+ f"Malformed verifier entry for {username}; treating as no-match"
+ )
+ return False
def _cached_engine_trusted(self, username: str, password: str) -> bool:
"""May the cached engine for ``username`` be returned to a caller
@@ -1334,6 +1468,16 @@ class DatabaseManager:
# For unencrypted databases, just apply pragmas
event.listen(engine, "connect", self._apply_pragmas)
+ # Snapshot the rekey generation BEFORE the SQLCipher round-trip below.
+ # A rekey landing between this snapshot and the cache publish means
+ # this engine verified against the pre-rekey key and must not be
+ # cached (see _cache_connection's expected_epoch guard). Snapshotting
+ # here -- rather than at open_user_database entry -- lets a
+ # new-password open that waited on init_lock and verified AFTER the
+ # rekey publish normally, while an old-password open that verified
+ # BEFORE the rekey is refused.
+ expected_epoch = self._get_rekey_epoch(username)
+
try:
# Test connection by running a simple query
with engine.connect() as conn:
@@ -1411,8 +1555,20 @@ class DatabaseManager:
# Store connection AFTER migrations complete. This password just
# proved itself against SQLCipher; publish the engine and its
# verifier together so the cache is never briefly trusted without
- # one.
- self._cache_connection(username, engine, password)
+ # one. The expected_epoch guard refuses a stale publish when a
+ # rekey landed mid-cold-open (see above): dispose and fail CLOSED
+ # so a later open retries against the current file key.
+ published = self._cache_connection(
+ username, engine, password, expected_epoch=expected_epoch
+ )
+ if not published:
+ try:
+ engine.dispose()
+ except Exception:
+ logger.warning(
+ f"Failed to dispose stale engine for {username}",
+ )
+ return None
# NOTE: the phase-2 RAG index re-key does NOT run here. It re-enters
# open_user_database() (via get_user_db_session on a session-cache
@@ -1544,6 +1700,58 @@ class DatabaseManager:
# cheap; close_all_databases likewise retains it (see there).
logger.info(f"Closed database for user {username}")
+ def close_user_database_if_stale(
+ self, username: str, expected_old_password: str
+ ) -> None:
+ """Close the cached engine for ``username`` only when its verifier
+ still matches ``expected_old_password``.
+
+ This is the change_password post-rekey eviction with a guard: a
+ concurrent ``open_user_database(new_password)`` racing the rekey
+ legitimately succeeds against the now-new_password-keyed file and
+ publishes a fresh engine with a DIFFERENT verifier (the new
+ one). Dropping that engine would force the next caller to
+ re-cold-open AND would break the invariant "the engine cached for
+ a user is the one a hammer racing this rekey observed"
+ (``test_stress_change_password_chain_vs_open_hammers`` pins exactly
+ that). Matching by verifier rather than by engine identity lets the
+ concurrent valid engine stay cached and keeps the eviction scoped
+ to the stale one whose key was rekeyed away.
+
+ This guard NARROWS but does not CLOSE the stale-engine window on its
+ own: eviction-at-close races by construction. If an external
+ unconditional close (logout, the ~300s idle sweep) empties the cache
+ mid-rekey, both conditional closes no-op on the emptied cache, and a
+ parked ``open_user_database(old)`` that verified against the still
+ old-keyed file can then publish a stale OLD-key engine with a
+ matching old verifier into the empty cache -- after which
+ ``open_user_database(old)`` is handed that engine without a SQLCipher
+ round-trip (data reads then fail with "file is not a database"). The
+ window is CLOSED by the rekey-generation check at publish time in
+ :meth:`_cache_connection` (``expected_epoch``): the parked open
+ snapshots the pre-rekey generation, the successful rekey bumps it via
+ :meth:`_bump_rekey_epoch`, and the stale publish is refused, disposed
+ and returns None. This helper remains the eviction half; the epoch is
+ the publication half.
+ """
+ with self._connections_lock:
+ if username not in self.connections:
+ return
+ if not self._verifier_matches(username, expected_old_password):
+ return
+ try:
+ self._checkpoint_wal(
+ self.connections[username],
+ f"for {username} post-rekey",
+ )
+ self.connections[username].dispose()
+ except Exception:
+ logger.warning(
+ f"Failed to dispose engine for {username}",
+ )
+ del self.connections[username]
+ self._password_verifiers.pop(username, None)
+
def close_all_databases(self):
"""Close all open user database connections and release file locks."""
with self._connections_lock:
@@ -1572,6 +1780,12 @@ class DatabaseManager:
# exists to stop. Bounded by the number of distinct usernames
# whose database file exists (change_password looks the lock up
# only after the path check), one small Lock each.
+ # _rekey_epoch is deliberately NOT cleared either. It tracks
+ # completed rekeys, not cached engines: a logout / idle-sweep
+ # close must not reset it, or a parked stale open_user_database
+ # (verified pre-rekey, publishing post-rekey) would match the
+ # reset generation and repopulate the cache with an OLD-key
+ # engine after the rekey -- the exact window the epoch closes.
def check_database_integrity(self, username: str) -> bool:
"""Check database structure and encrypted page authentication.
@@ -1709,20 +1923,49 @@ class DatabaseManager:
# Use centralized rekey function
set_sqlcipher_rekey(conn, new_password, db_path=db_path)
- # Evict the cached engine and its verifier NOW, while still inside
- # the try. open_user_database() above cold-opened with old_password
- # and cached that engine together with a verifier for old_password.
- # The rekey just invalidated that engine's key (its creator closure
- # still derives the OLD hex key, so any freshly pooled connection is
- # mis-keyed) yet the cached verifier still matches old_password -- so
- # until this eviction a concurrent open_user_database(old_password)
- # would pass the verifier check and be handed the stale-key engine.
- # The per-user lock above only excludes another change_password --
- # plain opens run concurrently throughout -- so evict here rather
- # than waiting for the finally. close_user_database is idempotent
- # (no-ops when the user is not cached), so the finally-close below
- # stays a backstop and is a no-op once this ran.
- self.close_user_database(username)
+ # Advance the rekey generation BEFORE the eviction below. A
+ # concurrent open_user_database(old) that verified against
+ # the still-old-keyed file and is parked before its cache
+ # publish snapshots the pre-rekey generation; this bump makes
+ # that publish mismatch and be refused by _cache_connection
+ # (fail CLOSED with dispose + None) instead of planting a
+ # stale OLD-key engine into an emptied cache after the rekey
+ # -- the window eviction-at-close cannot close when an
+ # external unconditional close (logout / idle sweep) emptied
+ # the cache mid-rekey so both conditional closes no-op. A
+ # concurrent open_user_database(new) that verifies AFTER this
+ # point snapshots the new generation and publishes normally.
+ self._bump_rekey_epoch(username)
+
+ # Evict the stale engine we opened above, but ONLY if it is
+ # still the one in the cache. open_user_database() above
+ # cold-opened with old_password and cached that engine with a
+ # verifier for old_password. The rekey just invalidated that
+ # engine's key (its creator closure still derives the OLD hex
+ # key, so any freshly pooled connection is mis-keyed) yet the
+ # cached verifier still matches old_password -- so until this
+ # eviction a concurrent open_user_database(old_password)
+ # would pass the verifier check and be handed the stale-key
+ # engine.
+ #
+ # A concurrent open_user_database(new_password) racing the
+ # rekey, however, legitimately succeeds (the file IS keyed
+ # with new_password now) and caches a fresh engine with the
+ # new verifier. That engine is the surviving current-key
+ # engine; evicting it would force the next caller to
+ # re-cold-open AND would break the invariant "the engine
+ # cached for a user is the one a hammer racing this rekey
+ # observed" (test_stress_change_password_chain_vs_open_hammers
+ # pins exactly that). The per-user lock above only excludes
+ # another change_password -- plain opens run concurrently
+ # throughout -- so evict only our engine here and let a
+ # concurrent valid engine stay. close_user_database_if_stale
+ # matches by verifier (the OLD one we just opened with), not
+ # by identity -- an engine a concurrent open published
+ # carries a DIFFERENT verifier (new_password) and is left
+ # alone. The finally-close below stays a backstop for the
+ # exception path; it uses the same conditional close.
+ self.close_user_database_if_stale(username, old_password)
logger.info(f"Password changed for user {username}")
return True
@@ -1741,8 +1984,16 @@ class DatabaseManager:
)
return False
finally:
- # Close the connection
- self.close_user_database(username)
+ # Backstop for the exception path: if the rekey threw and the
+ # in-try conditional close did not run, drop any stale engine
+ # (its verifier matches old_password, so its key was
+ # rekeyed away on the success path or it never rekeyed at
+ # all on the failure path; either way the file is no longer
+ # keyed with old_password under the success case). Same
+ # conditional as the in-try call so a concurrent
+ # open_user_database(new_password) racing the success path
+ # is not clobbered.
+ self.close_user_database_if_stale(username, old_password)
def user_exists(self, username: str) -> bool:
"""Check if a user exists in the auth database."""
diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.py
index bb27575d13..78c064498a 100644
--- a/src/local_deep_research/metrics/search_tracker.py
+++ b/src/local_deep_research/metrics/search_tracker.py
@@ -21,6 +21,24 @@ from .query_utils import get_research_mode_condition, get_time_filter_condition
SEARCH_STATUS_SKIPPED = "skipped_unavailable"
+def _session_has_pending_orm_state(session: Any) -> bool:
+ """True if *session* has unflushed ORM work ``begin_nested()`` would flush.
+
+ ``Session.begin_nested()`` flushes ``new``/``dirty``/``deleted`` before
+ CREATE SAVEPOINT. A flush failure (SQLite writer lock held elsewhere)
+ invalidates the caller's transaction; catching it cannot restore
+ ``session.is_active``. Best-effort telemetry must skip in that case.
+ """
+ try:
+ for attr in ("new", "dirty", "deleted"):
+ collection = getattr(session, attr, None)
+ if collection and len(collection) > 0:
+ return True
+ except Exception:
+ return False
+ return False
+
+
class SearchTracker:
"""Track search engine calls and performance metrics."""
@@ -100,14 +118,9 @@ class SearchTracker:
)
return
- # Use thread-safe metrics writer
- from ..database.thread_metrics import metrics_writer
-
try:
- # Set password for this thread
- metrics_writer.set_user_password(username, password)
- with metrics_writer.get_session(username) as session:
+ def _write_search(session: Any) -> None:
search_call = SearchCall(
research_id=research_id,
research_query=research_query,
@@ -130,6 +143,63 @@ class SearchTracker:
f"Search call recorded to encrypted DB: {engine_name} - "
f"{results_count} results in {response_time_ms}ms"
)
+
+ # Two paths, because get_user_db_session does not commit
+ # on exit and metrics_writer.get_session() is a second
+ # QueuePool connection:
+ #
+ # * in_scope(): reuse the thread-local session and write
+ # inside a SAVEPOINT (begin_nested()). A nested transaction
+ # isolates metrics failures from the caller's session
+ # (preventing the caller's staged work from being rolled
+ # back) and avoids premature session.commit(), preserving
+ # the caller's rollback atomicity.
+ # Session.begin_nested() flushes ALL pending ORM state
+ # before CREATE SAVEPOINT. If that flush fails (e.g.
+ # another connection holds SQLite's writer lock),
+ # SQLAlchemy invalidates the caller's transaction and
+ # catching the exception cannot restore it. Best-effort
+ # telemetry therefore skips when the caller already has
+ # unflushed work — the write cannot be isolated.
+ # * otherwise: metrics_writer commits+closes its own
+ # session. A thread-local write here would be rolled
+ # back by the next get_session() at scope depth 0.
+ from ..database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ if thread_session_manager.in_scope():
+ from ..database.session_context import get_user_db_session
+
+ with get_user_db_session(username, password) as session:
+ try:
+ if _session_has_pending_orm_state(session):
+ logger.debug(
+ "Skipping in-scope search metrics write; "
+ "caller session has pending ORM state "
+ "that Session.begin_nested() would flush "
+ "before creating a SAVEPOINT"
+ )
+ else:
+ with session.begin_nested():
+ _write_search(session)
+ except Exception as e:
+ # Catch inside get_user_db_session so exceptions
+ # do not trigger safe_rollback on the caller's session.
+ from ..security.log_sanitizer import scrub_error
+
+ safe_msg = scrub_error(e, password)
+ logger.warning(
+ f"Failed to write search metrics: {safe_msg}"
+ )
+ else:
+ from ..database.thread_metrics import metrics_writer
+
+ # Set password for this thread
+ metrics_writer.set_user_password(username, password)
+
+ with metrics_writer.get_session(username) as session:
+ _write_search(session)
except Exception as e:
# Deferred import to avoid potential circular imports during module initialization
from ..security.log_sanitizer import scrub_error
diff --git a/tests/metrics/test_search_tracker.py b/tests/metrics/test_search_tracker.py
index 185c65048b..c7a480c335 100644
--- a/tests/metrics/test_search_tracker.py
+++ b/tests/metrics/test_search_tracker.py
@@ -138,6 +138,649 @@ class TestSearchTrackerRecordSearch:
assert call_args.error_message == "Connection timeout"
+class TestRecordSearchSessionReuse:
+ """Regression coverage for issue #6561: multi-connection self-deadlock in record_search.
+
+ When the caller already holds a thread-local session (``in_scope()`` is True),
+ ``record_search`` must reuse ``get_user_db_session`` and write inside a SAVEPOINT
+ (``session.begin_nested()``) so the write does not check out a second QueuePool
+ connection (which deadlocks on SQLite when an active write session is held on the same thread),
+ does not prematurely commit the caller's transaction, and isolates metrics write failures
+ from the caller's transaction. If the caller already has pending ORM state,
+ telemetry is skipped: ``begin_nested()`` would flush that state before
+ CREATE SAVEPOINT, and a flush failure under writer-lock contention
+ invalidates the caller's transaction.
+
+ When no enclosing session is open (``in_scope()`` is False), ``record_search``
+ must fall back to ``metrics_writer`` so the write is committed and closed cleanly.
+ """
+
+ def test_in_scope_reuses_thread_local_session_with_savepoint(
+ self, mock_search_context
+ ):
+ """In-scope search recording must reuse get_user_db_session with begin_nested."""
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_session = MagicMock()
+ mock_nested = MagicMock()
+ mock_session.begin_nested.return_value = mock_nested
+ mock_nested.__enter__ = Mock(return_value=mock_nested)
+ mock_nested.__exit__ = Mock(return_value=None)
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_get_user_db_session = MagicMock(return_value=mock_cm)
+ mock_writer = MagicMock()
+
+ with (
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ patch.object(thread_session_manager, "in_scope", return_value=True),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ),
+ ):
+ SearchTracker.record_search(
+ engine_name="brave",
+ query="test search deadlock",
+ results_count=10,
+ response_time_ms=120,
+ success=True,
+ )
+
+ mock_get_user_db_session.assert_called_once_with(
+ mock_search_context["username"],
+ mock_search_context["user_password"],
+ )
+ mock_session.begin_nested.assert_called_once()
+ mock_session.add.assert_called_once()
+ call_obj = mock_session.add.call_args[0][0]
+ assert call_obj.search_engine == "brave"
+ assert call_obj.query == "test search deadlock"
+ assert call_obj.results_count == 10
+ assert call_obj.response_time_ms == 120
+ assert call_obj.success_status == "success"
+
+ # Explicit commit directly on the session must NOT be called
+ mock_session.commit.assert_not_called()
+
+ # Did NOT check out a second connection via metrics_writer
+ assert not mock_writer.get_session.called
+ assert not mock_writer.set_user_password.called
+
+ def test_not_in_scope_uses_metrics_writer(self, mock_search_context):
+ """When not in scope, record_search must use metrics_writer."""
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_writer = MagicMock()
+ mock_writer.get_session.return_value = mock_cm
+ mock_get_user_db_session = MagicMock()
+
+ with (
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ patch.object(
+ thread_session_manager, "in_scope", return_value=False
+ ),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ),
+ ):
+ SearchTracker.record_search(
+ engine_name="duckduckgo",
+ query="out of scope search",
+ results_count=3,
+ response_time_ms=80,
+ success=True,
+ )
+
+ # Did NOT use get_user_db_session
+ assert not mock_get_user_db_session.called
+
+ # Used metrics_writer
+ mock_writer.set_user_password.assert_called_once_with(
+ mock_search_context["username"],
+ mock_search_context["user_password"],
+ )
+ mock_writer.get_session.assert_called_once_with(
+ mock_search_context["username"]
+ )
+ mock_session.add.assert_called_once()
+ mock_session.commit.assert_not_called()
+
+ def test_in_scope_savepoint_exception_is_scrubbed_and_does_not_crash(
+ self, mock_search_context
+ ):
+ """If session.begin_nested() raises in scope, error is scrubbed and swallowed."""
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_session = MagicMock()
+ mock_session.begin_nested.side_effect = RuntimeError(
+ f"DB error with secret {mock_search_context['user_password']}"
+ )
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_get_user_db_session = MagicMock(return_value=mock_cm)
+
+ with (
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ patch.object(thread_session_manager, "in_scope", return_value=True),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.logger"
+ ) as mock_logger,
+ ):
+ SearchTracker.record_search(
+ engine_name="google",
+ query="failing savepoint",
+ )
+
+ assert mock_logger.warning.called
+ log_msg = mock_logger.warning.call_args[0][0]
+ assert "Failed to write search metrics" in log_msg
+ assert mock_search_context["user_password"] not in log_msg
+
+ def test_in_scope_get_user_db_session_exception_is_scrubbed_and_does_not_crash(
+ self, mock_search_context
+ ):
+ """If get_user_db_session raises, error is scrubbed and swallowed."""
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_get_user_db_session = MagicMock(
+ side_effect=Exception(
+ f"Cannot establish session for {mock_search_context['user_password']}"
+ )
+ )
+
+ with (
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ patch.object(thread_session_manager, "in_scope", return_value=True),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.logger"
+ ) as mock_logger,
+ ):
+ SearchTracker.record_search(
+ engine_name="google",
+ query="failing session",
+ )
+
+ assert mock_logger.warning.called
+ log_msg = mock_logger.warning.call_args[0][0]
+ assert "Failed to write search metrics" in log_msg
+ assert mock_search_context["user_password"] not in log_msg
+
+ def test_in_scope_natural_nesting_flow(self, mock_search_context):
+ """When called inside an active get_user_db_session block, naturally reuses session with savepoint."""
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_session = MagicMock()
+ mock_writer = MagicMock()
+
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=mock_session,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ),
+ ):
+ # Outer write session held by caller
+ with get_user_db_session(
+ mock_search_context["username"],
+ mock_search_context["user_password"],
+ ):
+ assert thread_session_manager.in_scope()
+ SearchTracker.record_search(
+ engine_name="searxng",
+ query="nested test query",
+ results_count=7,
+ response_time_ms=95,
+ success=True,
+ )
+
+ assert not mock_writer.get_session.called
+ mock_session.begin_nested.assert_called_once()
+ mock_session.add.assert_called_once()
+ call_obj = mock_session.add.call_args[0][0]
+ assert call_obj.query == "nested test query"
+ mock_session.commit.assert_not_called()
+
+ def test_in_scope_skips_when_caller_has_pending_orm_state(
+ self, mock_search_context
+ ):
+ """Pending caller ORM state must skip begin_nested, not flush it."""
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_session = MagicMock()
+ mock_session.new = {object()}
+ mock_session.dirty = set()
+ mock_session.deleted = set()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_get_user_db_session = MagicMock(return_value=mock_cm)
+ mock_writer = MagicMock()
+
+ with (
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ patch.object(thread_session_manager, "in_scope", return_value=True),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ mock_get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ),
+ ):
+ SearchTracker.record_search(
+ engine_name="brave",
+ query="skip pending flush",
+ results_count=1,
+ response_time_ms=10,
+ success=True,
+ )
+
+ mock_session.begin_nested.assert_not_called()
+ mock_session.add.assert_not_called()
+ mock_session.commit.assert_not_called()
+ mock_session.flush.assert_not_called()
+ assert not mock_writer.get_session.called
+
+ def test_real_sqlite_record_search_in_scope(self, mock_search_context):
+ """End-to-end SQLite integration: SearchCall is persisted and committed when in scope."""
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+ from local_deep_research.database.models import Base, SearchCall
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ TestSession = sessionmaker(bind=engine)
+ real_session = TestSession()
+
+ try:
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=real_session,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ ):
+ with get_user_db_session(
+ mock_search_context["username"],
+ mock_search_context["user_password"],
+ ) as session:
+ SearchTracker.record_search(
+ engine_name="duckduckgo",
+ query="integration test query",
+ results_count=42,
+ response_time_ms=123,
+ success=True,
+ )
+ session.commit()
+
+ persisted = (
+ real_session.query(SearchCall)
+ .filter_by(query="integration test query")
+ .first()
+ )
+ assert persisted is not None
+ assert persisted.search_engine == "duckduckgo"
+ assert persisted.results_count == 42
+ assert persisted.response_time_ms == 123
+ assert persisted.success_status == "success"
+ finally:
+ real_session.close()
+ engine.dispose()
+
+ def test_real_sqlite_in_scope_preserves_caller_rollback_atomicity(
+ self, mock_search_context
+ ):
+ """Caller's uncommitted work must NOT be prematurely committed by record_search,
+
+ allowing the caller to cleanly roll back all changes.
+ """
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+ from local_deep_research.database.models import Base, SearchCall
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ TestSession = sessionmaker(bind=engine)
+ real_session = TestSession()
+
+ try:
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=real_session,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ ):
+ with get_user_db_session(
+ mock_search_context["username"],
+ mock_search_context["user_password"],
+ ) as session:
+ caller_call = SearchCall(
+ research_id="caller-id",
+ search_engine="google",
+ query="caller staged query",
+ results_count=1,
+ )
+ session.add(caller_call)
+
+ SearchTracker.record_search(
+ engine_name="duckduckgo",
+ query="telemetry query",
+ results_count=5,
+ response_time_ms=50,
+ success=True,
+ )
+
+ # Caller rolls back their transaction
+ session.rollback()
+
+ persisted_caller = (
+ real_session.query(SearchCall)
+ .filter_by(query="caller staged query")
+ .first()
+ )
+ persisted_telemetry = (
+ real_session.query(SearchCall)
+ .filter_by(query="telemetry query")
+ .first()
+ )
+ assert persisted_caller is None
+ assert persisted_telemetry is None
+ finally:
+ real_session.close()
+ engine.dispose()
+
+ def test_real_sqlite_in_scope_telemetry_failure_does_not_destroy_caller_writes(
+ self, mock_search_context
+ ):
+ """Under metrics failure (e.g. nested savepoint error), the caller's staged writes
+
+ must NOT be rolled back or invalidated, and the caller can still commit successfully.
+
+ Caller work is flushed first so it is no longer pending; otherwise
+ ``record_search`` skips telemetry rather than entering ``begin_nested()``.
+ """
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+ from local_deep_research.database.models import Base, SearchCall
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ TestSession = sessionmaker(bind=engine)
+ real_session = TestSession()
+
+ try:
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=real_session,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ ):
+ with get_user_db_session(
+ mock_search_context["username"],
+ mock_search_context["user_password"],
+ ) as session:
+ caller_call = SearchCall(
+ research_id="caller-id",
+ search_engine="google",
+ query="caller must survive",
+ results_count=1,
+ )
+ session.add(caller_call)
+ session.flush()
+
+ # Simulate a failure during metrics savepoint write
+ with patch(
+ "local_deep_research.metrics.search_tracker.SearchCall",
+ side_effect=RuntimeError(
+ "Simulated metrics write failure"
+ ),
+ ):
+ SearchTracker.record_search(
+ engine_name="duckduckgo",
+ query="failing telemetry",
+ results_count=5,
+ response_time_ms=50,
+ success=True,
+ )
+
+ # Caller's session must still be intact and able to commit its own staged writes
+ session.commit()
+
+ persisted_caller = (
+ real_session.query(SearchCall)
+ .filter_by(query="caller must survive")
+ .first()
+ )
+ assert persisted_caller is not None
+ assert persisted_caller.query == "caller must survive"
+
+ persisted_telemetry = (
+ real_session.query(SearchCall)
+ .filter_by(query="failing telemetry")
+ .first()
+ )
+ assert persisted_telemetry is None
+ finally:
+ real_session.close()
+ engine.dispose()
+
+ def test_real_sqlite_contention_on_begin_nested_preserves_caller(
+ self, mock_search_context, tmp_path
+ ):
+ """Pending caller writes must survive writer-lock contention at savepoint entry.
+
+ ``Session.begin_nested()`` flushes pending ORM state before CREATE
+ SAVEPOINT. With another connection holding the SQLite writer lock,
+ that flush fails outside the savepoint and invalidates the caller
+ transaction. Telemetry must skip rather than enter ``begin_nested()``.
+ """
+ from sqlalchemy import create_engine, text
+ from sqlalchemy.orm import sessionmaker
+ from local_deep_research.database.models import Base, SearchCall
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ db_path = tmp_path / "search_tracker_contention.db"
+ engine = create_engine(
+ f"sqlite:///{db_path}",
+ connect_args={"timeout": 1.0, "check_same_thread": False},
+ )
+ Base.metadata.create_all(engine)
+ TestSession = sessionmaker(bind=engine)
+ real_session = TestSession()
+ competing = engine.connect()
+
+ try:
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=real_session,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ ):
+ with get_user_db_session(
+ mock_search_context["username"],
+ mock_search_context["user_password"],
+ ) as session:
+ caller_call = SearchCall(
+ research_id="caller-id",
+ search_engine="google",
+ query="caller pending under lock",
+ results_count=1,
+ )
+ session.add(caller_call)
+ assert session.new
+
+ competing.execute(text("BEGIN EXCLUSIVE"))
+ try:
+ SearchTracker.record_search(
+ engine_name="duckduckgo",
+ query="telemetry under contention",
+ results_count=5,
+ response_time_ms=50,
+ success=True,
+ )
+ assert session.is_active
+ finally:
+ competing.rollback()
+
+ session.commit()
+
+ persisted_caller = (
+ real_session.query(SearchCall)
+ .filter_by(query="caller pending under lock")
+ .first()
+ )
+ assert persisted_caller is not None
+ persisted_telemetry = (
+ real_session.query(SearchCall)
+ .filter_by(query="telemetry under contention")
+ .first()
+ )
+ assert persisted_telemetry is None
+ finally:
+ competing.close()
+ real_session.close()
+ engine.dispose()
+
+ def test_real_sqlite_record_search_not_in_scope(self, mock_search_context):
+ """End-to-end SQLite integration: SearchCall is persisted via metrics_writer when not in scope."""
+ from contextlib import contextmanager
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+ from local_deep_research.database.models import Base, SearchCall
+ from local_deep_research.database.thread_metrics import metrics_writer
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ TestSession = sessionmaker(bind=engine)
+ real_session = TestSession()
+
+ try:
+
+ @contextmanager
+ def _fake_cm(username):
+ yield real_session
+ real_session.commit()
+
+ with (
+ patch.object(
+ metrics_writer,
+ "get_session",
+ side_effect=_fake_cm,
+ ),
+ patch(
+ "local_deep_research.metrics.search_tracker.get_search_context",
+ return_value=mock_search_context,
+ ),
+ ):
+ SearchTracker.record_search(
+ engine_name="google",
+ query="not in scope integration test",
+ results_count=15,
+ response_time_ms=200,
+ success=True,
+ )
+
+ persisted = (
+ real_session.query(SearchCall)
+ .filter_by(query="not in scope integration test")
+ .first()
+ )
+ assert persisted is not None
+ assert persisted.search_engine == "google"
+ assert persisted.results_count == 15
+ finally:
+ real_session.close()
+ engine.dispose()
+
+
class TestSearchTrackerGetSearchMetrics:
"""Tests for get_search_metrics method."""
diff --git a/tests/security/test_change_password_evicts_stale_engine.py b/tests/security/test_change_password_evicts_stale_engine.py
index 34b7978138..c8d7551fe4 100644
--- a/tests/security/test_change_password_evicts_stale_engine.py
+++ b/tests/security/test_change_password_evicts_stale_engine.py
@@ -13,7 +13,12 @@ now runs under a per-user lock, but that lock only excludes a second
so the eviction is still what closes this window.
The fix evicts the connection (and its verifier) immediately AFTER the rekey,
-INSIDE the ``try``, keeping the finally-close as an idempotent backstop.
+INSIDE the ``try``, via ``close_user_database_if_stale`` -- a conditional
+variant that only drops the cached engine when its verifier still matches the
+OLD password (so a concurrent ``open_user_database(new_password)`` racing the
+rekey, which legitimately succeeds against the now-new_password-keyed file and
+caches a fresh engine with the NEW verifier, is left alone). The finally-close
+calls the same conditional helper as a backstop for the exception path.
This test pins that the eviction is performed by the in-try close, NOT merely by
the finally. It neutralises the finally-close and proves the stale engine/verifier
@@ -107,12 +112,16 @@ def test_change_password_evicts_stale_engine_in_try_not_only_finally(
encrypted_db, "logger", _LoggerProxy(encrypted_db.logger, on_info)
)
- # Spy the close so we can (a) capture the state at the in-try eviction and
- # (b) NEUTRALISE the finally-close, forcing the in-try close to be the only
- # thing that could have removed the stale engine/verifier.
- real_close = manager.close_user_database
+ # Spy the conditional close used by change_password's in-try and
+ # finally paths. (The unconditional close_user_database at the top of
+ # change_password is unrelated to the stale-engine window -- it just
+ # clears any pre-existing engine -- so we spy on the conditional variant
+ # the post-rekey path actually uses.) The spy captures the state at the
+ # in-try call and NEUTRALISES the finally call, forcing the in-try call
+ # to be the only thing that could have removed the stale engine/verifier.
+ real_close_stale = manager.close_user_database_if_stale
- def spy_close(user):
+ def spy_close_stale(user, expected_old_password):
if state["rekeyed"] and not state["success_logged"]:
# The in-try eviction (post-rekey, pre-success-log). The stale
# engine + old verifier must still be cached right now -- that is
@@ -122,7 +131,7 @@ def test_change_password_evicts_stale_engine_in_try_not_only_finally(
state["intry_verifier_present"] = (
user in manager._password_verifiers
)
- real_close(user)
+ real_close_stale(user, expected_old_password)
state["gone_after_intry"] = (
user not in manager.connections
and user not in manager._password_verifiers
@@ -135,10 +144,13 @@ def test_change_password_evicts_stale_engine_in_try_not_only_finally(
# the assertions below fail.
state["finally_neutralized"] = True
return
- # The pre-rekey close at the top of change_password: run normally.
- real_close(user)
+ # Should not happen: change_password only calls this method
+ # post-rekey. Run normally just in case.
+ real_close_stale(user, expected_old_password)
- monkeypatch.setattr(manager, "close_user_database", spy_close)
+ monkeypatch.setattr(
+ manager, "close_user_database_if_stale", spy_close_stale
+ )
assert manager.change_password(username, old, new) is True
@@ -162,7 +174,9 @@ def test_change_password_evicts_stale_engine_in_try_not_only_finally(
# 5. The old password can no longer open the re-keyed database, and the new
# password can. (These re-open, so restore the real close first.)
- monkeypatch.setattr(manager, "close_user_database", real_close)
+ monkeypatch.setattr(
+ manager, "close_user_database_if_stale", real_close_stale
+ )
monkeypatch.setattr(encrypted_db, "set_sqlcipher_rekey", real_rekey)
assert manager.open_user_database(username, old) is None, (
diff --git a/tests/security/test_db_connection_change_password_race.py b/tests/security/test_db_connection_change_password_race.py
index 7c7b50762b..d689c7ab97 100644
--- a/tests/security/test_db_connection_change_password_race.py
+++ b/tests/security/test_db_connection_change_password_race.py
@@ -119,15 +119,22 @@ def _write_canary(engine, note: str) -> None:
def _engine_usable(engine) -> tuple[bool, str]:
- """Is this engine able to run a SELECT right now?
+ """Is this engine able to read encrypted pages right now?
Returns (usable, detail); detail carries the failure repr so a failed
invariant prints WHY the engine was (or was not) usable.
+
+ Must read a real table, not ``SELECT 1``: under SQLCipher ``SELECT 1``
+ touches no encrypted pages and succeeds even on a mis-keyed engine
+ whose first table read raises ("file is not a database"). Probing only
+ ``SELECT 1`` therefore measures pool liveness, not key validity. Reading
+ ``sqlite_master`` forces a decrypt of schema pages, so a stale-key engine
+ fails here as it would on any data read.
"""
try:
with engine.connect() as conn:
- value = conn.execute(text("SELECT 1")).scalar()
- return value == 1, "select ok"
+ conn.execute(text("SELECT name FROM sqlite_master LIMIT 1")).all()
+ return True, "table read ok"
except Exception as exc: # noqa: BLE001 - converted into a loud assert below
return False, repr(exc)
@@ -503,3 +510,688 @@ def test_stress_change_password_chain_vs_open_hammers(manager):
f"({note!r}) -- a mis-keyed engine was handed out for the "
"final password"
)
+
+
+def test_change_password_does_not_evict_concurrent_new_password_engine(
+ manager,
+):
+ """Direct pin for the post-rekey conditional eviction.
+
+ ``test_stress_change_password_chain_vs_open_hammers`` proves the
+ end-to-end invariant under racing threads (every final-password engine
+ the hammer grabs is the surviving one). This test proves the same
+ invariant at the unit level by hand-feeding a fresh engine with the
+ NEW password into the cache BEFORE the rekey, then observing that the
+ conditional close used by ``change_password`` leaves it alone.
+
+ A concurrent ``open_user_database(new_password)`` racing the rekey
+ publishes exactly this state -- file keyed with new_password, cache
+ holding an engine with the new verifier. The unconditional
+ ``close_user_database`` would drop it and break the invariant; the
+ conditional ``close_user_database_if_stale(old_password)`` must not.
+ Without the gate, every racing hammer cold-open re-opens a fresh
+ engine after the rekey, forcing a needless cold-open for the next
+ caller AND breaking the test_stress engine-identity assertion above.
+ """
+ if not manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ username = f"chgpw_conc_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ new = "NewCorrectHorse2!" # noqa: S105
+ engine = manager.create_user_database(username, old)
+ _write_canary(engine, "gap-B-cond")
+ manager.close_user_database(username)
+
+ # Simulate the race outcome: change_password runs through to completion
+ # with no concurrent open. The cache is empty afterwards (its in-try
+ # conditional close evicted the stale engine it opened). Hand-feed the
+ # state the racing open would have produced -- cache holds a fresh
+ # engine with the NEW verifier -- then call the conditional close the
+ # FINALLY path uses and confirm the fresh engine survives.
+ assert manager.change_password(username, old, new) is True
+ assert username not in manager.connections
+
+ # Cold-open with the new password -- this is the "concurrent open"
+ # outcome the conditional close must not undo.
+ fresh = manager.open_user_database(username, new)
+ assert fresh is not None
+ surviving_before = manager.connections.get(username)
+ assert surviving_before is fresh
+
+ # The FINALLY path of change_password runs unconditionally; in the
+ # success path it is followed by a return True, so under the live code
+ # there is no chance to observe this on the success branch -- the
+ # exception branch calls it too. Call the helper directly here to pin
+ # the no-op property: passing the OLD password must NOT drop the
+ # engine, because its verifier matches the NEW password, not the
+ # old one.
+ manager.close_user_database_if_stale(username, old)
+ surviving_after = manager.connections.get(username)
+ assert surviving_after is fresh, (
+ "close_user_database_if_stale(old_password) must leave an engine "
+ "with a different (new_password) verifier cached -- otherwise a "
+ "concurrent open_user_database(new_password) racing the rekey has "
+ "its surviving engine clobbered and the test_stress invariant "
+ "breaks"
+ )
+ assert manager._password_matches_cached(username, new) is True
+
+ # And, symmetrically: the conditional close DOES drop a stale engine
+ # whose verifier still matches the OLD password. Force the cache into
+ # that state directly -- the helper only checks the verifier, so any
+ # engine with the old verifier is treated as stale regardless of
+ # whether its closure matches the current file key (which is the
+ # security-relevant property: an old-verifier engine could be returned
+ # to a caller presenting old_password without a SQLCipher round-trip).
+ stale_engine = manager.connections.get(username)
+ assert stale_engine is not None
+ manager._cache_connection(username, stale_engine, old)
+ assert manager._password_matches_cached(username, old)
+ manager.close_user_database_if_stale(username, old)
+ assert username not in manager.connections, (
+ "close_user_database_if_stale(old_password) must drop a stale "
+ "engine whose verifier still matches the old password -- that is "
+ "the whole point of the helper"
+ )
+ assert username not in manager._password_verifiers
+
+
+def test_cache_connection_disposes_overwritten_engine(manager, monkeypatch):
+ """Direct pin for the orphan-dispose property of ``_cache_connection``.
+
+ When ``open_user_database(new_password)`` publishes a fresh engine and
+ overwrites the engine ``change_password`` cached moments earlier, the
+ overwritten engine reference is lost to the cache but its SQLCipher
+ pool and file handle still hold the OLD hex-key closure. Without an
+ explicit ``dispose()`` on the orphan, that pool lingers until GC,
+ leaking one stale connection per overwrite on exactly the path the
+ conditional-eviction fix makes common (concurrent new-password opens
+ against a rekeying database).
+
+ Spy ``Engine.dispose`` so we can observe the call directly -- a pure
+ "engine is gone" check would miss the leak because the orphan is also
+ gone from the cache the instant it is overwritten, regardless of
+ whether anyone disposes it.
+
+ The publish uses ``_cache_connection`` directly rather than going
+ through ``open_user_database(new_password)``: the file is still keyed
+ with ``old_password`` in this test (no rekey happened), so a real
+ new-password open would fail at the SQLCipher layer. ``_cache_connection``
+ is the exact publication primitive ``open_user_database`` calls after a
+ successful SQLCipher round-trip, so this drives the property under
+ test in isolation.
+ """
+ if not manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ username = f"chgpw_orphan_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ new = "NewCorrectHorse2!" # noqa: S105
+
+ bootstrap_engine = manager.create_user_database(username, old)
+ assert bootstrap_engine is not None
+ # User file is created; close so we can drive the cache by hand below
+ # without triggering an in-loop open.
+ manager.close_user_database(username)
+
+ # Spy Engine.dispose. The spy records every call site by id(self) so
+ # we can identify which engine was disposed when multiple engines
+ # are alive at once.
+ from sqlalchemy.engine import Engine as _Engine
+
+ real_engine_dispose = _Engine.dispose
+ dispose_calls = []
+
+ def spy_dispose(self):
+ dispose_calls.append(id(self))
+ return real_engine_dispose(self)
+
+ monkeypatch.setattr(_Engine, "dispose", spy_dispose)
+
+ # Stage the cache into the post-rekey / pre-conditional-close state:
+ # change_password has cold-opened with old_password (caching the old
+ # engine) and is about to do the in-try conditional close. A
+ # concurrent open_user_database(new_password) racing the rekey
+ # publishes a fresh engine and overwrites the old one. Hand-feed that
+ # state directly so the overwrite path runs deterministically -- use
+ # a fresh real Engine for the "new" engine so dispose has work to do.
+ published_old = manager.open_user_database(username, old)
+ assert published_old is not None
+ assert manager.connections[username] is published_old
+
+ # Construct a synthetic "racing" engine -- the publication primitive
+ # ``_cache_connection`` accepts any Engine; the SQLCipher key
+ # derivation that opens it is not relevant to this test, only the
+ # overwrite + dispose behavior is. Reuse the user file URL so
+ # dispose() has a non-trivial pool to close.
+ from sqlalchemy import create_engine
+
+ fresh = create_engine(
+ f"sqlite:///{manager._get_user_db_path(username).as_posix()}"
+ )
+
+ # Reset the spy -- open_user_database above may have triggered
+ # disposes elsewhere we do not care about. The property we are
+ # pinning is "the OVERWRITE disposes the previous engine".
+ dispose_calls.clear()
+
+ # Drive the race outcome: _cache_connection overwrites the cache.
+ manager._cache_connection(username, fresh, new)
+ assert manager.connections[username] is fresh
+
+ # The orphan (published_old) MUST have been disposed as part of the
+ # cache swap. dispose_calls records the old engine exactly once.
+ assert id(published_old) in dispose_calls, (
+ "_cache_connection must dispose the previous engine it is "
+ "overwriting; an orphaned SQLCipher pool + file handle leaks on "
+ "exactly the concurrent-new-password-open path this PR made common"
+ )
+ assert dispose_calls.count(id(published_old)) == 1, (
+ f"the orphan engine was disposed "
+ f"{dispose_calls.count(id(published_old))} times -- exactly once "
+ "is the contract"
+ )
+
+ # Symmetry: an in-place re-publish with the SAME engine object must
+ # NOT trigger an additional dispose (the conditional guards against
+ # ``orphan is engine`` to avoid disposing a still-live pool when a
+ # caller caches the same engine twice, which would close connections
+ # a live user is mid-query on).
+ before = dispose_calls.count(id(fresh))
+ manager._cache_connection(username, fresh, new)
+ assert dispose_calls.count(id(fresh)) == before, (
+ "_cache_connection must not dispose a same-identity re-publish; "
+ "the in-place republish happens on every reopen-with-same-password "
+ "and disposing the live pool would terminate in-flight queries"
+ )
+
+ # First-time publish (no previous engine) MUST NOT trigger any
+ # dispose -- otherwise every cold-open would race to close a pool
+ # that did not exist yet.
+ username_two = f"chgpw_orphan2_{uuid.uuid4().hex[:8]}"
+ fresh_two = manager.create_user_database(username_two, old)
+ assert fresh_two is not None
+ assert manager.connections[username_two] is fresh_two
+ # No overwrite happened on this username, so dispose_calls should
+ # not have grown for fresh_two since the last measurement.
+ after = dispose_calls.count(id(fresh_two))
+ # (The create_user_database path also caches; a same-identity
+ # republish via _cache_connection must be a no-op for dispose.)
+ manager._cache_connection(username_two, fresh_two, old)
+ assert dispose_calls.count(id(fresh_two)) == after, (
+ "_cache_connection must not dispose a same-identity republish on "
+ "a brand-new entry either"
+ )
+
+
+def test_verifier_matches_degrades_on_corrupt_entry(manager, monkeypatch):
+ """Pin the malformed-verifier-entry safety net.
+
+ ``_verifier_matches`` is called from inside ``change_password``'s
+ ``finally`` block -- a raise here would replace the actual
+ ``change_password`` outcome with a spurious ``TypeError`` /
+ ``ValueError`` and the operator would see a confusing "password
+ change failed" instead of the underlying cause. The invariants that
+ produce well-formed entries are unit-locked (``_make_verifier`` and
+ ``_cache_connection``), so a corrupt entry can only arrive through
+ external dict mutation; degrading to no-match is safer than letting
+ that exception escape.
+
+ Without the safety net the assertion below raises before
+ ``change_password`` returns, masking the real outcome (a clean
+ rekey); with it, the conditional close no-ops, the rekey has
+ already landed, and ``change_password`` returns True.
+ """
+ if not manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ username = f"chgpw_corrupt_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ new = "NewCorrectHorse2!" # noqa: S105
+ engine = manager.create_user_database(username, old)
+ _write_canary(engine, "gap-B-corrupt")
+ manager.close_user_database(username)
+
+ # Stage a corrupt verifier: a non-tuple value where the cache expects
+ # (salt, expected). Run change_password; the in-try conditional close
+ # would see the corrupt value via _verifier_matches and degrade to
+ # False, leaving any new engine cached, then the finally-close
+ # degrades again, returning True. Without the safety net the unpacking
+ # raises TypeError out of the helper and the caller sees a confusing
+ # failure.
+ # Inject AFTER the create + close above so the rekey flow runs against
+ # a clean cache and the corruption only matters for the conditional
+ # close path.
+ published = manager.open_user_database(username, old)
+ assert published is not None
+ # Corrupt the verifier entry directly. The helper MUST treat this as
+ # no-match (return False), not raise.
+ with manager._connections_lock:
+ manager._password_verifiers[username] = "not-a-tuple" # type: ignore[assignment]
+
+ # The helper degrades to False rather than raising.
+ with manager._connections_lock:
+ result = manager._verifier_matches(username, old)
+ assert result is False, (
+ "_verifier_matches must degrade to no-match on a malformed "
+ "verifier entry; a raise here propagates out of "
+ "change_password's finally and masks the real rekey outcome"
+ )
+
+ # End-to-end: change_password still returns True with a corrupt
+ # verifier in the cache, because the conditional close degrades to
+ # no-match (does not evict), and the in-try rekey already succeeded.
+ # Restore a valid verifier first so the second pass (in the absence
+ # of the safety net) would otherwise succeed -- we are now proving the
+ # conditional close path tolerates the corruption it might encounter.
+ # Keep the corruption in place so the finally-close also exercises it.
+ assert manager.change_password(username, old, new) is True
+ # The fresh new-password open afterwards must still work; the corrupt
+ # entry did not leak into the post-rekey verifier (it was overwritten
+ # by the in-try cold-open inside change_password before the corruption
+ # could affect the result). Restoring the corruption before the
+ # change_password above was deliberate -- change_password's own
+ # open_user_database(old_password) cache_connection call wrote a
+ # fresh verifier for old_password, so the cache now has a valid one
+ # again, which is what the finally-close consulted.
+
+
+def test_change_password_eviction_window_handles_concurrent_publish_deterministically(
+ manager,
+):
+ """Deterministic (non-threaded) probe for the exact window the
+ threaded stress test races on.
+
+ ``test_stress_change_password_chain_vs_open_hammers`` is the proof
+ under real threads, but its discriminating window is µs-scale: on
+ fast hardware every observed hammer grab lands AFTER the final
+ eviction, so the test could pass pre-fix. This probe drives the
+ race outcome directly -- rekeys the file first so a fresh new-
+ password open succeeds, then publishes it on top of the cold-open
+ change_password would have cached -- and asserts the surviving-
+ engine identity, the orphan-engine disposition, and the verifier
+ mismatch guard together.
+
+ The probe is intentionally NOT a threading test: every property
+ here is about a specific cache state and can be set up without
+ concurrency. It does not depend on the scheduler interleaving
+ correctly and so cannot become vacuous on faster hardware. The
+ threaded test stays as the end-to-end proof; this probe is the
+ pin that survives on any machine.
+ """
+ if not manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ username = f"chgpw_det_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ new = "NewCorrectHorse2!" # noqa: S105
+
+ bootstrap_engine = manager.create_user_database(username, old)
+ _write_canary(bootstrap_engine, "gap-B-det")
+ manager.close_user_database(username)
+ del bootstrap_engine
+
+ # Drive the cache state change_password's in-try conditional close
+ # observes when a concurrent new-password open wins the race:
+ # 1. ``change_password`` cold-opens with old_password -> cache
+ # holds ``stale`` with the old verifier.
+ # 2. ``change_password`` rekeys the file to new_password.
+ # 3. A racing ``open_user_database(new_password)`` succeeds (file
+ # IS keyed with new_password now) and publishes a fresh engine
+ # + new verifier on top of ``stale``.
+ # 4. ``change_password``'s in-try conditional close sees a verifier
+ # that no longer matches old_password -> no-op.
+ # 5. Property: the racing engine survives in the cache, the
+ # overwritten engine has been disposed exactly once.
+ from sqlalchemy.engine import Engine as _Engine
+
+ real_engine_dispose = _Engine.dispose
+ dispose_calls = []
+
+ def spy_dispose(self):
+ dispose_calls.append(id(self))
+ return real_engine_dispose(self)
+
+ import pytest as _pytest
+
+ mp = _pytest.MonkeyPatch()
+ mp.setattr(_Engine, "dispose", spy_dispose)
+ try:
+ stale = manager.open_user_database(username, old)
+ assert stale is not None
+ assert manager.connections[username] is stale
+ assert manager._password_matches_cached(username, old) is True
+
+ # Rekey the file in-place -- mirrors what change_password does
+ # internally -- so the racing open below can succeed against
+ # new_password.
+ from local_deep_research.database.encrypted_db import (
+ set_sqlcipher_rekey,
+ )
+
+ with stale.connect() as conn:
+ set_sqlcipher_rekey(
+ conn,
+ new,
+ db_path=manager._get_user_db_path(username),
+ )
+
+ # The racing new-password open: publishes ``surviving`` on top
+ # of ``stale``. This is the cache state the in-try conditional
+ # close will consult. The overwrite path inside
+ # ``_cache_connection`` MUST have already disposed ``stale`` at
+ # this point -- that is item 1 of the latest review feedback.
+ surviving = manager.open_user_database(username, new)
+ assert surviving is not None
+ assert manager.connections[username] is surviving
+ assert manager._password_matches_cached(username, new) is True
+ assert not manager._password_matches_cached(username, old)
+
+ # Property 1: the racing publish disposed ``stale`` exactly once.
+ assert id(stale) in dispose_calls, (
+ "the overwritten engine (stale) must have been disposed by "
+ "_cache_connection's overwrite path, not leaked until GC"
+ )
+ assert dispose_calls.count(id(stale)) == 1, (
+ "stale engine must be disposed exactly once on the overwrite"
+ )
+
+ # Reset the dispose baseline so we can prove the conditional
+ # close itself triggers NO dispose (the verifier mismatch makes
+ # it a no-op on the cache, and the orphan was already cleaned up
+ # by the overwrite path above).
+ dispose_calls.clear()
+
+ # Property 2: the conditional close change_password's in-try
+ # would call is a no-op on the cache because the verifier no
+ # longer matches.
+ manager.close_user_database_if_stale(username, old)
+ assert manager.connections[username] is surviving, (
+ "conditional close must leave the racing new-password engine "
+ "cached -- this is the test_stress invariant"
+ )
+ assert id(surviving) not in dispose_calls, (
+ "the conditional close must not touch the racing engine; the "
+ "verifier mismatch already routed it to no-op"
+ )
+
+ # End-to-end: the file still answers the new password (the
+ # rekey succeeded) and the cache still serves it (the
+ # conditional close left it alone).
+ with surviving.connect() as conn:
+ note = conn.execute(
+ text("SELECT note FROM gap_b_canary WHERE id = 1")
+ ).scalar()
+ assert note == "gap-B-det", "rekey must preserve data"
+ finally:
+ mp.undo()
+
+
+def test_rekey_epoch_refuses_stale_old_publish(manager):
+ """Pin the publish-time epoch guard that closes the window
+ eviction-at-close cannot.
+
+ Interleave (from review at ``c02cf47c``):
+ 1. ``change_password(old->new)`` cold-opens with old and caches E1;
+ 2. an external unconditional close (logout / idle sweep) evicts E1;
+ 3. a concurrent ``open_user_database(old)`` that missed the fast path
+ cold-opens with the OLD key while the file is still old-keyed, and
+ parks just before ``_cache_connection``;
+ 4. the rekey lands; both conditional closes no-op on the emptied cache;
+ 5. the parked open publishes E2 keyed OLD with a matching old verifier.
+
+ Without the epoch, step 5 plants a stale engine that
+ ``open_user_database(old)`` is then handed without a SQLCipher
+ round-trip. With it, the parked publish snapshots the pre-rekey
+ generation, the rekey bumps it, and the publish is refused (fail CLOSED).
+ """
+ if not manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ username = f"chgpw_epoch_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ new = "NewCorrectHorse2!" # noqa: S105
+
+ bootstrap = manager.create_user_database(username, old)
+ _write_canary(bootstrap, "gap-B-epoch")
+ manager.close_user_database(username)
+ del bootstrap
+
+ # Parked-open simulation: snapshot the pre-rekey generation, exactly as
+ # _open_user_database_cold does before its SQLCipher round-trip.
+ stale_epoch = manager._get_rekey_epoch(username)
+ assert stale_epoch == 0
+
+ assert manager.change_password(username, old, new) is True
+ assert manager._get_rekey_epoch(username) == stale_epoch + 1
+ # change_password evicted everything; cache empty (the external-close
+ # shape from the interleave leaves the same empty cache).
+ assert username not in manager.connections
+
+ # Step 5: the parked OLD-key open tries to publish after the rekey.
+ from sqlalchemy import create_engine
+
+ parked = create_engine(
+ f"sqlite:///{manager._get_user_db_path(username).as_posix()}"
+ )
+ try:
+ published = manager._cache_connection(
+ username, parked, old, expected_epoch=stale_epoch
+ )
+ assert published is False, (
+ "a publish whose pre-verification epoch predates the completed "
+ "rekey must be refused -- otherwise a stale OLD-key engine is "
+ "cached after change_password"
+ )
+ assert username not in manager.connections, (
+ "refused stale publish must leave the cache empty"
+ )
+ assert username not in manager._password_verifiers
+ finally:
+ parked.dispose()
+
+ # End-to-end: old is dead, new reads pre-change data.
+ assert manager.open_user_database(username, old) is None
+ reopened = manager.open_user_database(username, new)
+ assert reopened is not None
+ with reopened.connect() as conn:
+ note = conn.execute(
+ text("SELECT note FROM gap_b_canary WHERE id = 1")
+ ).scalar()
+ assert note == "gap-B-epoch"
+
+ # Symmetry: a publish snapshotting the CURRENT generation succeeds.
+ current_epoch = manager._get_rekey_epoch(username)
+ from sqlalchemy import create_engine as _create_engine
+
+ fresh = _create_engine(
+ f"sqlite:///{manager._get_user_db_path(username).as_posix()}"
+ )
+ try:
+ assert (
+ manager._cache_connection(
+ username, fresh, new, expected_epoch=current_epoch
+ )
+ is True
+ )
+ assert manager.connections[username] is fresh
+ finally:
+ # Leave the manager clean for the fixture teardown.
+ manager.close_user_database(username)
+ fresh.dispose()
+
+
+def test_verifier_matches_degrades_on_wrong_typed_members(manager):
+ """Pin the widened malformed-verifier guard.
+
+ The unpack-only guard degraded ``"not-a-tuple"`` but a two-tuple with
+ wrong-typed members -- ``("x", "y")`` or ``(b"salt", 123)`` -- still
+ raised ``TypeError`` out of ``_verifier_matches`` (via ``salt + bytes``
+ or ``hmac.compare_digest(bytes, int)``), which escapes through
+ ``change_password``'s ``finally`` and masks the real rekey outcome.
+ """
+ if not manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ username = f"chgpw_vmtype_{uuid.uuid4().hex[:8]}"
+ old = "OldCorrectHorse1!" # noqa: S105
+ engine = manager.create_user_database(username, old)
+ assert engine is not None
+
+ try:
+ with manager._connections_lock:
+ manager._password_verifiers[username] = ("x", "y") # type: ignore[assignment]
+ assert manager._verifier_matches(username, old) is False
+
+ with manager._connections_lock:
+ manager._password_verifiers[username] = (b"salt", 123) # type: ignore[assignment]
+ assert manager._verifier_matches(username, old) is False
+
+ with manager._connections_lock:
+ manager._password_verifiers[username] = (123, b"expected") # type: ignore[assignment]
+ assert manager._verifier_matches(username, old) is False
+ finally:
+ manager.close_user_database(username)
+
+
+def test_engine_usable_rejects_mis_keyed_engine():
+ """Pin the ``sqlite_master``-read hardening in ``_engine_usable``.
+
+ Under SQLCipher ``SELECT 1`` touches no encrypted pages and succeeds
+ even on a mis-keyed engine whose first table read raises ("file is
+ not a database"). Probing only ``SELECT 1`` therefore measures pool
+ liveness, not key validity. ``_engine_usable`` must read a real table
+ so a stale-key engine fails here as it would on any data read.
+
+ This is a logic pin with a stubbed engine shaped exactly like that
+ mis-keyed engine (``SELECT 1`` succeeds, ``sqlite_master`` read
+ raises), so it runs with or without a SQLCipher build. Reverting the
+ helper to ``SELECT 1`` makes the stub report usable and this test
+ fails.
+ """
+ from unittest.mock import MagicMock
+
+ def _stub_engine(*, table_ok: bool):
+ engine = MagicMock()
+ conn = MagicMock()
+ engine.connect.return_value.__enter__.return_value = conn
+
+ def _execute(statement, *args, **kwargs):
+ sql = str(statement)
+ if "sqlite_master" in sql:
+ if not table_ok:
+ raise Exception("file is not a database")
+ result = MagicMock()
+ result.all.return_value = [("gap_b_canary",)]
+ return result
+ result = MagicMock()
+ result.all.return_value = [(1,)]
+ result.scalar.return_value = 1
+ result.fetchone.return_value = (1,)
+ return result
+
+ conn.execute.side_effect = _execute
+ return engine
+
+ mis_keyed = _stub_engine(table_ok=False)
+ # Premise: SELECT 1 succeeds on this shape, so it cannot be the probe.
+ with mis_keyed.connect() as conn:
+ assert conn.execute(text("SELECT 1")).scalar() == 1
+
+ usable, detail = _engine_usable(mis_keyed)
+ assert not usable, (
+ "a mis-keyed engine must fail _engine_usable "
+ f"({detail}) -- SELECT 1 succeeds on it, so only the "
+ "real-table read distinguishes it"
+ )
+
+ # Control: a correctly-keyed engine (both probes succeed) is usable.
+ good = _stub_engine(table_ok=True)
+ usable, detail = _engine_usable(good)
+ assert usable, f"correctly-keyed engine must be usable ({detail})"
+
+
+def test_open_cold_refuses_stale_publish_and_disposes(manager, monkeypatch):
+ """Pin the epoch plumbing through ``_open_user_database_cold``.
+
+ ``test_rekey_epoch_refuses_stale_old_publish`` drives the
+ ``_cache_connection`` primitive directly. This test drives the real
+ caller: a rekey landing between the pre-verification epoch snapshot
+ and the cache publish must make ``_open_user_database_cold`` refuse
+ the publish (return None, cache empty, engine disposed).
+
+ A caller that forgets ``expected_epoch`` (unconditional publish via
+ the ``None`` default) returns the engine and populates the cache
+ here, so this test fails without the plumbing.
+ """
+ if not manager.has_encryption:
+ pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")
+
+ import time as _time
+
+ from sqlalchemy.engine import Engine as _Engine
+
+ import local_deep_research.database.initialize as _init_module
+
+ username = f"chgpw_cold_{uuid.uuid4().hex[:8]}"
+ password = "ColdCorrectHorse1!" # noqa: S105
+
+ bootstrap = manager.create_user_database(username, password)
+ _write_canary(bootstrap, "gap-B-cold")
+ manager.close_user_database(username)
+ del bootstrap
+
+ assert manager._get_rekey_epoch(username) == 0
+
+ # Simulate a rekey landing mid-cold-open: the snapshot in
+ # _open_user_database_cold runs before this hook, the publish runs
+ # after it, so the publish must observe the bumped generation.
+ real_initialize = _init_module.initialize_database
+
+ def _bump_then_initialize(engine):
+ manager._bump_rekey_epoch(username)
+ return real_initialize(engine)
+
+ monkeypatch.setattr(
+ _init_module, "initialize_database", _bump_then_initialize
+ )
+
+ real_dispose = _Engine.dispose
+ dispose_calls: list[int] = []
+
+ def _spy_dispose(self):
+ dispose_calls.append(id(self))
+ return real_dispose(self)
+
+ monkeypatch.setattr(_Engine, "dispose", _spy_dispose)
+ dispose_calls.clear()
+
+ result = manager._open_user_database_cold(
+ username, password, _time.perf_counter()
+ )
+ assert result is None, (
+ "a cold-open straddling a rekey must be refused (fail CLOSED) "
+ "-- without expected_epoch plumbing the stale publish succeeds"
+ )
+ assert username not in manager.connections, (
+ "refused stale publish must leave the cache empty"
+ )
+ assert username not in manager._password_verifiers, (
+ "refused stale publish must not arm a verifier"
+ )
+ assert dispose_calls, (
+ "the refused stale engine must be disposed, not leaked until GC"
+ )
+
+ # Control without the mid-open rekey: the same cold-open publishes.
+ monkeypatch.setattr(_init_module, "initialize_database", real_initialize)
+ manager.close_user_database(username)
+ control = manager._open_user_database_cold(
+ username, password, _time.perf_counter()
+ )
+ assert control is not None
+ try:
+ assert manager.connections.get(username) is control
+ finally:
+ manager.close_user_database(username)