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.

refactor(database): name authorization epoch projection explicitly (#7725)

Chanhyo Junga27d5169436c
diff --git a/src/local_deep_research/database/authorization_epoch.py b/src/local_deep_research/database/authorization_epoch.py
new file mode 100644
index 0000000000..2ae4c7241a
--- /dev/null
+++ b/src/local_deep_research/database/authorization_epoch.py
@@ -0,0 +1,41 @@
+"""Read-only authorization identity projection for encrypted user databases.
+
+The durable token, pending/committed epoch, and fencing state machine lives
+in ``rekey_lock``. These projections read without taking its sidecar lock;
+its pending-first reads prevent a concurrent commit and pending cleanup
+from exposing a superseded epoch as a stable authorization identity.
+"""
+
+from pathlib import Path
+
+from .rekey_lock import RekeyRecoveryRequiredError, read_rekey_epoch_state
+
+
+def read_authorization_epoch(db_path: Path) -> str:
+ """Project the epoch that may authorize identities without repairing state."""
+ state = read_rekey_epoch_state(db_path)
+ committed_epoch = state.committed_epoch
+ if committed_epoch is None or (
+ state.pending_epoch is not None
+ and state.pending_epoch != committed_epoch
+ ):
+ raise RekeyRecoveryRequiredError(db_path)
+ return committed_epoch
+
+
+def read_user_authorization_epoch(username: str) -> str:
+ """Resolve a user's database path and project its authorization epoch.
+
+ The path MUST be resolved through ``db_manager`` (lazy-imported to
+ keep this module's import graph shallow): the manager may carry a
+ pinned ``data_dir`` override while ``get_data_directory()`` resolves
+ dynamically from the environment, and epochs are written beside the
+ databases under the MANAGER's resolution. Reading via the env-only
+ path projected a different directory whenever the two diverged
+ (any process that pinned the override), which would fence perfectly
+ healthy sessions with ``RekeyRecoveryRequiredError``.
+ """
+ from .encrypted_db import db_manager
+
+ db_path = db_manager._get_user_db_path(username)
+ return read_authorization_epoch(db_path)
diff --git a/src/local_deep_research/database/rekey_epoch.py b/src/local_deep_research/database/rekey_epoch.py
index 91e8caeaf5..b545d0d00a 100644
--- a/src/local_deep_research/database/rekey_epoch.py
+++ b/src/local_deep_research/database/rekey_epoch.py
@@ -1,41 +1,11 @@
-"""Durable authorization identity projection for encrypted user databases.
+"""Compatibility imports for the authorization epoch projections.
-Nothing in the application imports this module yet: it is the read side
-for session and socket identity fencing, which the FastAPI layer does not
-perform yet (a planned follow-up). Its readers do not take the rekey
-sidecar lock, which is why ``read_rekey_epoch_state`` reads pending-first.
+New callers should use ``authorization_epoch``. Durable rekey state and
+fencing remain in ``rekey_lock``.
"""
-from pathlib import Path
-
-from .rekey_lock import RekeyRecoveryRequiredError, read_rekey_epoch_state
-
-
-def read_authorization_epoch(db_path: Path) -> str:
- """Project the epoch that may authorize identities without repairing state."""
- state = read_rekey_epoch_state(db_path)
- committed_epoch = state.committed_epoch
- if committed_epoch is None or (
- state.pending_epoch is not None
- and state.pending_epoch != committed_epoch
- ):
- raise RekeyRecoveryRequiredError(db_path)
- return committed_epoch
-
-
-def read_user_authorization_epoch(username: str) -> str:
- """Resolve a user's database path and project its authorization epoch.
-
- The path MUST be resolved through ``db_manager`` (lazy-imported to
- keep this module's import graph shallow): the manager may carry a
- pinned ``data_dir`` override while ``get_data_directory()`` resolves
- dynamically from the environment, and epochs are written beside the
- databases under the MANAGER's resolution. Reading via the env-only
- path projected a different directory whenever the two diverged
- (any process that pinned the override), which would fence perfectly
- healthy sessions with ``RekeyRecoveryRequiredError``.
- """
- from .encrypted_db import db_manager
-
- db_path = db_manager._get_user_db_path(username)
- return read_authorization_epoch(db_path)
+from .authorization_epoch import (
+ RekeyRecoveryRequiredError as RekeyRecoveryRequiredError,
+ read_authorization_epoch as read_authorization_epoch,
+ read_user_authorization_epoch as read_user_authorization_epoch,
+)
diff --git a/tests/database/test_rekey_epoch.py b/tests/database/test_rekey_epoch.py
index 04af9dcb3c..5ad8ee35f9 100644
--- a/tests/database/test_rekey_epoch.py
+++ b/tests/database/test_rekey_epoch.py
@@ -1,6 +1,10 @@
from __future__ import annotations
import errno
+import importlib
+import importlib.util
+import subprocess
+import sys
import os
from pathlib import Path
from uuid import UUID
@@ -213,3 +217,84 @@ def test_projection_cannot_tear_into_the_superseded_epoch(
# .epoch first saw E1, then no pending file, and authorized E1)
assert writer_ran
assert epoch == _EPOCH_TWO
+
+
+def test_authorization_epoch_import_contract() -> None:
+ name = "local_deep_research.database.authorization_epoch"
+ assert importlib.util.find_spec(name) is not None
+ canonical = importlib.import_module(name)
+ legacy = importlib.import_module("local_deep_research.database.rekey_epoch")
+ assert canonical.read_authorization_epoch is legacy.read_authorization_epoch
+ assert (
+ canonical.read_user_authorization_epoch
+ is legacy.read_user_authorization_epoch
+ )
+ assert canonical.RekeyRecoveryRequiredError is RekeyRecoveryRequiredError
+ assert legacy.RekeyRecoveryRequiredError is RekeyRecoveryRequiredError
+
+
[email protected](params=["authorization_epoch", "rekey_epoch"], autouse=True)
+def projection_import_path(request, monkeypatch):
+ module = importlib.import_module(
+ f"local_deep_research.database.{request.param}"
+ )
+ monkeypatch.setattr(
+ sys.modules[__name__],
+ "read_authorization_epoch",
+ module.read_authorization_epoch,
+ )
+ monkeypatch.setattr(
+ sys.modules[__name__],
+ "read_user_authorization_epoch",
+ module.read_user_authorization_epoch,
+ )
+
+
+def test_projection_import_stays_shallow() -> None:
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-B",
+ "-c",
+ "import sys; import local_deep_research.database.authorization_epoch; import local_deep_research.database.rekey_epoch; assert 'local_deep_research.database.encrypted_db' not in sys.modules",
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+
+
+def test_user_projection_uses_pinned_manager_directory(tmp_path, monkeypatch):
+ from local_deep_research.database.encrypted_db import db_manager
+
+ pinned = tmp_path / "pinned"
+ environment = tmp_path / "environment"
+ monkeypatch.setenv("LDR_DATA_DIR", str(environment))
+ monkeypatch.setattr(db_manager, "_data_dir_override", pinned)
+ db_path = db_manager._get_user_db_path("alice")
+ assert db_path == pinned / get_user_database_filename("alice")
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ _write_epoch_state(db_path, committed=_EPOCH_TWO, pending=None)
+ assert read_user_authorization_epoch("alice") == _EPOCH_TWO
+
+
+def test_pending_first_projection_preserves_metadata(tmp_path, monkeypatch):
+ db_path = tmp_path / "alice.db"
+ _write_epoch_state(db_path, committed=_EPOCH_ONE, pending=_EPOCH_TWO)
+ before = {path.name: path.read_bytes() for path in tmp_path.iterdir()}
+ real_open = os.open
+ reads = []
+
+ def record_open(path, flags, *args, **kwargs):
+ if os.fspath(path).endswith((".rekey.pending", ".rekey.epoch")):
+ reads.append(Path(path).name)
+ return real_open(path, flags, *args, **kwargs)
+
+ monkeypatch.setattr(os, "open", record_open)
+ with pytest.raises(RekeyRecoveryRequiredError):
+ read_authorization_epoch(db_path)
+ assert reads == ["alice.db.rekey.pending", "alice.db.rekey.epoch"]
+ assert {
+ path.name: path.read_bytes() for path in tmp_path.iterdir()
+ } == before