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(vector-stores): formalize write lock contract (#5330)

LearningCircuit3ac7d0b2a052
diff --git a/src/local_deep_research/vector_stores/base.py b/src/local_deep_research/vector_stores/base.py
index 10dcece3e7..df3a276224 100644
--- a/src/local_deep_research/vector_stores/base.py
+++ b/src/local_deep_research/vector_stores/base.py
@@ -9,15 +9,16 @@ settings selector wired yet.
Scope / honest boundary
-----------------------
This abstraction covers the *vector-storage operations* — create / add /
-search / delete / reconstruct / persist / count. It deliberately does **not**
-cover the per-user file paths, on-disk integrity checksums, or the per-index
-write-lock + reload/merge concurrency model that :class:`LibraryRAGService`
-layers on top. Those are *local-file* concerns (see :attr:`is_local_file`): a
-future server-backed store (e.g. Qdrant) would set ``is_local_file = False``,
-no-op :meth:`persist` / :meth:`load`, and the service layer would skip the file
-lock + integrity machinery for it. So this base class makes adding a backend
-*easier* (a clean, verified query surface), not *free* — a real server backend
-still requires refactoring the file/lock/integrity layer in the service.
+search / delete / reconstruct / persist / count. Local-file constructors accept
+injected persistence resources, but this interface deliberately does **not**
+prescribe their per-user paths, integrity checksums, or reload/merge locking
+model that :class:`LibraryRAGService` layers on top. Those are *local-file*
+concerns (see :attr:`is_local_file`): a future server-backed store (e.g.
+Qdrant) would set ``is_local_file = False``, no-op :meth:`persist` /
+:meth:`load`, and the service layer would skip the file lock + integrity
+machinery for it. So this base class makes adding a backend *easier* (a clean,
+verified query surface), not *free* — a real server backend still requires
+refactoring the file/lock/integrity layer in the service.
Identity model
--------------
@@ -46,11 +47,37 @@ snippets from there by id (see ``LibraryRAGService`` / the search engines).
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import List, Optional, Sequence, Tuple
+from types import TracebackType
+from typing import Callable, List, Optional, Protocol, Self, Sequence, Tuple
import numpy as np
+IntegrityRecord = Callable[[Path], None]
+IntegrityVerify = Callable[[Path], Tuple[bool, Optional[str]]]
+
+
+class WriteLock(Protocol):
+ """Minimal lock capability used to guard a vector store's file writes.
+
+ Implementations MUST be reentrant. Write paths nest acquisition on a
+ single thread — the service layer holds the lock across a document
+ operation while the store's own reload/apply/persist choreography
+ re-acquires it — so a plain ``threading.Lock`` satisfies this Protocol
+ structurally but self-deadlocks at runtime. Use ``threading.RLock`` (or
+ a wrapper around one, as the production tracked lock is).
+ """
+
+ def __enter__(self) -> bool | Self: ...
+
+ def __exit__(
+ self,
+ exception_type: type[BaseException] | None,
+ exception: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None: ...
+
+
class BaseVectorStore(ABC):
"""Abstract interface for a per-collection vector index.
@@ -87,7 +114,10 @@ class BaseVectorStore(ABC):
index_type: str,
metric: str,
normalize: bool,
- **kwargs,
+ path: Optional[Path] = None,
+ lock: Optional[WriteLock] = None,
+ integrity_record: Optional[IntegrityRecord] = None,
+ integrity_verify: Optional[IntegrityVerify] = None,
) -> "BaseVectorStore":
"""Create a new, empty store for vectors of ``dimension``.
@@ -97,6 +127,11 @@ class BaseVectorStore(ABC):
metric: Distance metric (``"l2"``, ``"cosine"``, ``"dot_product"``).
normalize: Whether query/doc vectors are L2-normalized before use
(cosine similarity via inner product on normalized vectors).
+ path: Optional local persistence path.
+ lock: Optional reentrant lock for local persistence (see
+ :class:`WriteLock`).
+ integrity_record: Optional persisted-file integrity callback.
+ integrity_verify: Optional persisted-file integrity check.
"""
@classmethod
@@ -109,14 +144,18 @@ class BaseVectorStore(ABC):
index_type: str,
metric: str,
normalize: bool,
- **kwargs,
+ lock: Optional[WriteLock] = None,
+ integrity_record: Optional[IntegrityRecord] = None,
+ integrity_verify: Optional[IntegrityVerify] = None,
) -> "BaseVectorStore":
"""Load a persisted store from ``path`` (local-file stores only).
``dimension`` / ``index_type`` / ``metric`` / ``normalize`` describe how
the index was built (some backends persist this, some do not); callers
pass the values from settings so search-time normalization matches
- build-time normalization.
+ build-time normalization. ``lock`` / ``integrity_record`` /
+ ``integrity_verify`` are the same injected persistence resources as on
+ :meth:`create`.
"""
# ------------------------------------------------------------------ #
diff --git a/src/local_deep_research/vector_stores/facade.py b/src/local_deep_research/vector_stores/facade.py
index d1be88a5ce..3c1d386079 100644
--- a/src/local_deep_research/vector_stores/facade.py
+++ b/src/local_deep_research/vector_stores/facade.py
@@ -20,13 +20,11 @@ Exact-duplicate *files* are an ingestion-time concern, handled upstream.
"""
import hashlib
-import threading
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, field
from pathlib import Path
from typing import (
- Callable,
Iterator,
List,
Optional,
@@ -43,6 +41,7 @@ from sqlalchemy.orm import Session
from ..database.models.library import DocumentChunk
from ..database.session_context import get_user_db_session
+from .base import IntegrityRecord, IntegrityVerify, WriteLock
from .config import get_vector_store_class
@@ -60,9 +59,9 @@ class _BindKwargs(TypedDict):
metric: str
normalize: bool
path: Path
- lock: threading.Lock
- integrity_record: Callable[[Path], None]
- integrity_verify: Callable[[Path], Tuple[bool, Optional[str]]]
+ lock: WriteLock
+ integrity_record: IntegrityRecord
+ integrity_verify: IntegrityVerify
@dataclass
@@ -130,9 +129,9 @@ class VectorIndex:
collection_name: str,
dimension: int,
path: Path,
- lock: threading.Lock,
- integrity_record: Callable[[Path], None],
- integrity_verify: Callable[[Path], Tuple[bool, Optional[str]]],
+ lock: WriteLock,
+ integrity_record: IntegrityRecord,
+ integrity_verify: IntegrityVerify,
index_type: str = "flat",
metric: str = "cosine",
normalize: bool = True,
diff --git a/src/local_deep_research/vector_stores/implementations/faiss_store.py b/src/local_deep_research/vector_stores/implementations/faiss_store.py
index 52523e8cf8..8fa83f145b 100644
--- a/src/local_deep_research/vector_stores/implementations/faiss_store.py
+++ b/src/local_deep_research/vector_stores/implementations/faiss_store.py
@@ -15,11 +15,10 @@ the encrypted DB by that id.
import os
import tempfile
-import threading
import time
from contextlib import contextmanager
from pathlib import Path
-from typing import Callable, Iterator, List, Optional, Sequence, Tuple, cast
+from typing import Iterator, List, Optional, Sequence, Tuple, cast
import numpy as np
from faiss import (
@@ -38,7 +37,7 @@ from faiss import (
)
from loguru import logger
-from ..base import BaseVectorStore
+from ..base import BaseVectorStore, IntegrityRecord, IntegrityVerify, WriteLock
# HNSW connections-per-layer (parity with the previous wrapper's default).
_HNSW_M = 32
@@ -69,9 +68,10 @@ def _canon(value: Optional[str], default: str) -> str:
class FaissVectorStore(BaseVectorStore):
"""A single collection's FAISS index (``IndexIDMap2`` over a base index).
- Concurrency: the injected write lock is a ``threading.Lock`` — it serializes
- writers (and, via ``_read_guard``, readers) within ONE process only. This
- assumes a single-process deployment. Under a multi-process server (e.g.
+ Concurrency: the injected write lock (a reentrant :class:`WriteLock`; in
+ production a tracked ``threading.RLock`` wrapper) serializes writers (and,
+ via ``_read_guard``, readers) within ONE process only. This assumes a
+ single-process deployment. Under a multi-process server (e.g.
``gunicorn -w N``) two workers hold independent locks and a lost update is
possible; a cross-process (file) lock would be required for that deployment.
"""
@@ -104,20 +104,16 @@ class FaissVectorStore(BaseVectorStore):
# caller so this store never imports a lock registry or DB integrity
# model — it only owns the choreography, not the resources.
self._path: Optional[Path] = None
- self._lock: Optional[threading.Lock] = None
- self._integrity_record: Optional[Callable[[Path], None]] = None
- self._integrity_verify: Optional[
- Callable[[Path], Tuple[bool, Optional[str]]]
- ] = None
+ self._lock: Optional[WriteLock] = None
+ self._integrity_record: Optional[IntegrityRecord] = None
+ self._integrity_verify: Optional[IntegrityVerify] = None
def _bind(
self,
path: Optional[Path],
- lock: Optional[threading.Lock],
- integrity_record: Optional[Callable[[Path], None]],
- integrity_verify: Optional[
- Callable[[Path], Tuple[bool, Optional[str]]]
- ],
+ lock: Optional[WriteLock],
+ integrity_record: Optional[IntegrityRecord],
+ integrity_verify: Optional[IntegrityVerify],
) -> None:
"""Attach the persistence resources apply() needs (injected, not imported).
@@ -209,12 +205,9 @@ class FaissVectorStore(BaseVectorStore):
metric: str,
normalize: bool,
path: Optional[Path] = None,
- lock: Optional[threading.Lock] = None,
- integrity_record: Optional[Callable[[Path], None]] = None,
- integrity_verify: Optional[
- Callable[[Path], Tuple[bool, Optional[str]]]
- ] = None,
- **kwargs,
+ lock: Optional[WriteLock] = None,
+ integrity_record: Optional[IntegrityRecord] = None,
+ integrity_verify: Optional[IntegrityVerify] = None,
) -> "FaissVectorStore":
base = cls._build_base_index(dimension, index_type, metric)
store = cls(
@@ -236,12 +229,9 @@ class FaissVectorStore(BaseVectorStore):
index_type: str,
metric: str,
normalize: bool,
- lock: Optional[threading.Lock] = None,
- integrity_record: Optional[Callable[[Path], None]] = None,
- integrity_verify: Optional[
- Callable[[Path], Tuple[bool, Optional[str]]]
- ] = None,
- **kwargs,
+ lock: Optional[WriteLock] = None,
+ integrity_record: Optional[IntegrityRecord] = None,
+ integrity_verify: Optional[IntegrityVerify] = None,
) -> "FaissVectorStore":
"""Load a persisted ``IndexIDMap2`` from ``path`` (a ``.faiss`` file).
@@ -377,9 +367,11 @@ class FaissVectorStore(BaseVectorStore):
faiss is not safe for concurrent search-vs-add/remove on the *same*
index object; when this instance is bound for writes (a shared, cached
instance), reads take the same lock ``apply()`` uses. Internal callers
- that already hold the lock (e.g. ``_dedup_new``) must use the
- ``*_unlocked`` helpers, not these public methods, to avoid re-entrancy
- deadlock (``threading.Lock`` is not reentrant).
+ that already hold the lock (e.g. ``_dedup_new``) use the ``*_unlocked``
+ helpers, not these public methods — single-acquisition discipline, so
+ this store's own choreography never depends on the injected lock's
+ reentrancy (which the :class:`WriteLock` contract reserves for the
+ service layer's nested holds).
"""
if self._lock is not None:
with self._lock:
@@ -546,7 +538,7 @@ class FaissVectorStore(BaseVectorStore):
# Sweep stale temp files left by a previously hard-killed write. Within
# one process persist() runs under this index's write lock, so no
# in-process writer owns a ``<name>.*.tmp`` here. But that lock is
- # per-process (a threading.Lock in a per-process registry), so under
+ # per-process (an in-process lock in a per-process registry), so under
# ``gunicorn -w N`` a SECOND worker can be mid-persist for the SAME path
# with its temp not yet renamed — unlinking it would crash that write
# with FileNotFoundError at fsync. Only sweep temps OLDER than a generous
@@ -982,9 +974,10 @@ class FaissVectorStore(BaseVectorStore):
raise
self._poisoned = False
- # Fallback runs OUTSIDE the lock — self._lock is a non-reentrant
- # threading.Lock, so _apply_hnsw/_apply_locked (which re-acquire it)
- # must not be called while it is held. A concurrent write mutated the
+ # Fallback runs OUTSIDE the lock — _apply_hnsw/_apply_locked take the
+ # lock themselves, and holding it across them would both lean on the
+ # lock's reentrancy and defeat the off-lock build's purpose (keeping
+ # reads unblocked during the rebuild). A concurrent write mutated the
# index during our off-lock build, so the snapshot is stale: retry
# (bounded), then give up racing and rebuild fully locked (correct, just
# blocks reads for that attempt).