diff --git a/docs/write-routing-policy.md b/docs/write-routing-policy.md index f7f9789..100987b 100644 --- a/docs/write-routing-policy.md +++ b/docs/write-routing-policy.md @@ -109,6 +109,42 @@ Invalid values fail with a source-specific error rather than silently falling back. This is important because silently turning a misspelled `require` into a direct write would violate the safety purpose of the policy. +## Local backend single-writer safety + +File-backed backends such as `chroma`, `sqlite_exact`, and Milvus Lite support +exactly one writable process per palace. Serializing individual calls is not +enough because each long-lived process can retain SQLite/WAL, FTS, or vector +index state between calls. + +- A writable daemon owns the palace writer lease for its full lifetime. +- Writable MCP HTTP acquires that lease before binding, holds it through the + full serving lifetime, and releases it after active requests stop. +- MCP stdio opens `sqlite_exact` read-only until it acquires the writer lease. + It may therefore coexist for reads; mutating tools refuse while another + process owns the lease and reopen writable storage after that owner exits. +- Read-only MCP HTTP may coexist with the writer. +- Read-only `sqlite_exact` clients use an immutable connection for a clean + checkpointed database, or `mode=ro` when an active writer's complete WAL + sidecar pair must remain visible. Both paths enable `query_only` and skip + schema, WAL, FTS, migration, and metadata initialization. +- Direct CLI and hook writes must not run beside a writable daemon or MCP HTTP + owner. Route them through the daemon with `require` when the daemon owns the + palace. +- Direct `sqlite_exact` collection mutations contend for the same palace lease, + and full LLM closet regeneration owns it before opening collections or + calling the configured model. + +`MEMPALACE_MCP_ALLOW_PEER_WRITER` cannot bypass this protection for local +file-backed or unknown plugin backends. It is retained only for explicitly +remote service backends (`qdrant`, `pgvector`, and Milvus server/Zilliz Cloud) +that coordinate concurrent clients themselves. Milvus Lite remains protected +as local file-backed storage. + +Do not delete or unlink a live palace lock to recover ownership. Stop the +owning process cleanly; the operating system releases its lock automatically. +If corruption is suspected, back up the palace and run integrity/repair +operations offline, with no writable service running. + ## Follow-up PRs Hook-triggered writes now consume this policy; see diff --git a/mempalace/backends/milvus.py b/mempalace/backends/milvus.py index 5dbc837..642a4ea 100644 --- a/mempalace/backends/milvus.py +++ b/mempalace/backends/milvus.py @@ -76,8 +76,11 @@ def _utcnow() -> str: return datetime.now(timezone.utc).isoformat() -def _is_server_uri(uri: str) -> bool: - normalized = uri.lower() +def milvus_uri_is_server(uri: Optional[str]) -> bool: + """Return whether ``uri`` targets service-managed Milvus storage.""" + if not uri: + return False + normalized = uri.strip().lower() return normalized.startswith(("http://", "https://", "tcp://", "grpc://")) @@ -358,7 +361,7 @@ class MilvusCollection(BaseCollection): if score is None: return 1.0 value = float(score) - if self._config.uri and _is_server_uri(self._config.uri): + if milvus_uri_is_server(self._config.uri): return 1.0 - max(-1.0, min(1.0, value)) return value @@ -976,7 +979,7 @@ class MilvusBackend(BaseBackend): collection_name: str, config: _MilvusConfig, ) -> str: - if config.uri and not _is_server_uri(config.uri) and not config.namespace: + if config.uri and not milvus_uri_is_server(config.uri) and not config.namespace: return _slug(collection_name) prefix = self._remote_collection_prefix(palace=palace, config=config) return f"{prefix}_{_slug(collection_name)}" @@ -1059,7 +1062,7 @@ class MilvusBackend(BaseBackend): client = self._clients.get(config) if client is not None: return client - if config.uri and not _is_server_uri(config.uri): + if config.uri and not milvus_uri_is_server(config.uri): parent = os.path.dirname(os.path.abspath(config.uri)) or "." os.makedirs(parent, exist_ok=True) try: @@ -1089,7 +1092,7 @@ class MilvusBackend(BaseBackend): pass marker_path = self._marker_path(palace.local_path) local_db_exists = bool( - config.uri and not _is_server_uri(config.uri) and os.path.exists(config.uri) + config.uri and not milvus_uri_is_server(config.uri) and os.path.exists(config.uri) ) if os.path.isfile(marker_path): self._validate_marker_target(palace, config) diff --git a/mempalace/backends/sqlite_exact.py b/mempalace/backends/sqlite_exact.py index fd29dfa..586f2fb 100644 --- a/mempalace/backends/sqlite_exact.py +++ b/mempalace/backends/sqlite_exact.py @@ -15,12 +15,14 @@ import re import sqlite3 import threading from datetime import datetime, timezone +from pathlib import Path from typing import Any, Optional import numpy as np from .base import ( BackendClosedError, + BackendError, BaseBackend, BaseCollection, CollectionNotInitializedError, @@ -247,9 +249,23 @@ def _validate_write_batch( class _SQLiteExactHandle: - def __init__(self, conn: sqlite3.Connection, lock: threading.RLock): + def __init__( + self, + conn: sqlite3.Connection, + lock: threading.RLock, + palace_path: str, + *, + read_only: bool = False, + immutable: bool = False, + ): self.conn = conn self.lock = lock + self.palace_path = palace_path + self.read_only = read_only + # True when opened with ``immutable=1`` because no WAL existed at connect + # time. A later writer can create WAL sidecars that this connection will + # never see, so the backend must reopen once those files appear. + self.immutable = immutable self.closed = False @@ -264,8 +280,27 @@ class SQLiteExactCollection(BaseCollection): raise BackendClosedError("SQLiteExactCollection has been closed") @contextlib.contextmanager - def _cursor(self): + def _write_lock(self): + """Serialize this handle before taking process-wide writer ownership. + + ``mine_palace_lock`` grants cross-thread re-entrant access whenever + this process already owns the palace. Taking it before ``handle.lock`` + lets a waiting thread consume that re-entrant credit, outlive the + thread that owns the OS lease, and then mutate after the lease has been + released. The handle mutex must therefore be the outer context. + """ + # Late import avoids a palace.py -> backend -> palace.py cycle. + from ..palace import mine_palace_lock + with self._handle.lock: + self._ensure_open() + with mine_palace_lock(self._handle.palace_path): + yield + + @contextlib.contextmanager + def _cursor(self, *, write: bool = False): + serialization = self._write_lock() if write else self._handle.lock + with serialization: self._ensure_open() cur = self._handle.conn.cursor() try: @@ -345,7 +380,7 @@ class SQLiteExactCollection(BaseCollection): def set_embedder_identity(self, identity) -> None: if not identity or not identity.model_name: return - with self._cursor() as cur: + with self._cursor(write=True) as cur: cur.execute( "INSERT INTO meta(key, value) VALUES (?, ?) " "ON CONFLICT(key) DO UPDATE SET value = excluded.value", @@ -375,7 +410,7 @@ class SQLiteExactCollection(BaseCollection): raise ValueError("sqlite_exact requires explicit embeddings") metadatas = metadatas or [{} for _ in ids] now = _utcnow() - with self._cursor() as cur: + with self._cursor(write=True) as cur: collection_id = self._collection_id(cur) prepared = [] for doc_id, doc, meta, emb in zip(ids, documents, metadatas, embeddings): @@ -413,7 +448,7 @@ class SQLiteExactCollection(BaseCollection): raise ValueError("sqlite_exact requires explicit embeddings") metadatas = metadatas or [{} for _ in ids] now = _utcnow() - with self._cursor() as cur: + with self._cursor(write=True) as cur: collection_id = self._collection_id(cur) prepared = [] for doc_id, doc, meta, emb in zip(ids, documents, metadatas, embeddings): @@ -457,7 +492,7 @@ class SQLiteExactCollection(BaseCollection): ): if value is not None and len(value) != n: raise ValueError(f"{label} length {len(value)} does not match ids length {n}") - with self._cursor() as cur: + with self._cursor(write=True) as cur: collection_id = self._collection_id(cur) updates = [] for idx, doc_id in enumerate(ids): @@ -653,7 +688,7 @@ class SQLiteExactCollection(BaseCollection): ) def delete(self, *, ids=None, where=None): - with self._cursor() as cur: + with self._cursor(write=True) as cur: collection_id = self._collection_id(cur) if ids is None: rows = self._rows(cur, where=where) @@ -797,17 +832,16 @@ class SQLiteExactCollection(BaseCollection): ) if kind == "analyze": # Refresh planner stats. Concurrent runs serialize on the handle lock. - with self._cursor() as cur: + with self._cursor(write=True) as cur: cur.execute("ANALYZE") return MaintenanceResult(kind="analyze", status="ran") # compact → VACUUM. It cannot run inside a transaction, so flip the - # connection to autocommit for the duration. The handle lock serializes - # concurrent runs in-process; SQLite's own write lock serializes across - # processes. + # connection to autocommit for the duration. _write_lock takes the + # handle mutex before the palace lease so a waiting thread cannot + # retain stale process-reentrant ownership after another thread exits. before = self.maintenance_state() - with self._handle.lock: - self._ensure_open() + with self._write_lock(): conn = self._handle.conn prev_isolation = conn.isolation_level try: @@ -848,6 +882,7 @@ class SQLiteExactBackend(BaseBackend): def __init__(self): self._clients: dict[str, _SQLiteExactHandle] = {} + self._read_only_clients: dict[str, _SQLiteExactHandle] = {} self._clients_lock = threading.RLock() self._closed = False @@ -855,9 +890,64 @@ class SQLiteExactBackend(BaseBackend): def _db_path(palace_path: str) -> str: return os.path.join(palace_path, _DB_FILENAME) - def _connect(self, palace_path: str, create: bool): + @staticmethod + def _wal_sidecar_state(db_path: str) -> tuple[bool, bool]: + return ( + os.path.isfile(f"{db_path}-wal"), + os.path.isfile(f"{db_path}-shm"), + ) + + @staticmethod + def _connect_read_only(db_path: str) -> tuple[sqlite3.Connection, bool]: + """Open without creating WAL files while preserving an active WAL. + + Returns ``(connection, immutable)``. ``immutable`` is True when the + database was clean (no WAL) and was opened with ``immutable=1``. + """ + wal_exists, shm_exists = SQLiteExactBackend._wal_sidecar_state(db_path) + if wal_exists != shm_exists: + raise BackendError( + "sqlite_exact read-only open found an incomplete WAL sidecar set; " + "open the palace after its writer exits cleanly or restore both " + "the -wal and -shm files" + ) + + db_uri = Path(db_path).resolve().as_uri() + if wal_exists: + # An active writer's uncheckpointed rows live in the WAL. With both + # sidecars already present, mode=ro can read them without creating + # filesystem state, including on a read-only mount. + db_uri = f"{db_uri}?mode=ro" + immutable = False + else: + # A clean WAL-mode database would otherwise make SQLite create new + # -wal/-shm files while connecting. Immutable mode is safe here + # only until a writer creates sidecars this connection would miss. + db_uri = f"{db_uri}?mode=ro&immutable=1" + immutable = True + return sqlite3.connect(db_uri, uri=True, check_same_thread=False), immutable + + def _retire_read_only_handle(self, palace_path: str, handle: _SQLiteExactHandle) -> None: + """Drop a cached read-only handle so the next open re-evaluates WAL state.""" + self._read_only_clients.pop(palace_path, None) + with handle.lock: + if handle.closed: + return + handle.closed = True + try: + handle.conn.close() + except Exception: + logger.debug( + "Failed to close stale immutable sqlite_exact reader for %s", + palace_path, + exc_info=True, + ) + + def _connect(self, palace_path: str, create: bool, *, read_only: bool = False): if self._closed: raise BackendClosedError("SQLiteExactBackend has been closed") + if create and read_only: + raise ValueError("sqlite_exact read-only connections cannot create a palace") db_path = self._db_path(palace_path) if not create and not os.path.isfile(db_path): raise PalaceNotFoundError(db_path) @@ -877,20 +967,51 @@ class SQLiteExactBackend(BaseBackend): with self._clients_lock: if self._closed: raise BackendClosedError("SQLiteExactBackend has been closed") - cached = self._clients.get(palace_path) + clients = self._read_only_clients if read_only else self._clients + cached = clients.get(palace_path) if cached is not None and not cached.closed: - return cached - conn = sqlite3.connect(db_path, check_same_thread=False) + if read_only and cached.immutable: + # An immutable snapshot freezes the clean-database view. + # When a writer later creates WAL sidecars, keep serving + # that snapshot only until both files exist, then reopen + # with normal mode=ro so recall sees the writer's commits. + wal_exists, shm_exists = self._wal_sidecar_state(db_path) + if wal_exists or shm_exists: + self._retire_read_only_handle(palace_path, cached) + cached = None + if cached is not None: + return cached + if read_only: + conn, immutable = self._connect_read_only(db_path) + else: + conn = sqlite3.connect(db_path, check_same_thread=False) + immutable = False try: conn.row_factory = sqlite3.Row lock = threading.RLock() - handle = _SQLiteExactHandle(conn, lock) + handle = _SQLiteExactHandle( + conn, + lock, + palace_path, + read_only=read_only, + immutable=immutable, + ) with handle.lock: - self._init_schema(conn) + if read_only: + # ``mode=ro`` prevents filesystem writes. ``query_only`` + # adds a second connection-local guard so a future + # refactor cannot accidentally introduce a temp/schema + # write through a read-only MCP collection. + conn.execute("PRAGMA query_only=ON") + else: + from ..palace import mine_palace_lock + + with mine_palace_lock(palace_path): + self._init_schema(conn) except BaseException: conn.close() raise - self._clients[palace_path] = handle + clients[palace_path] = handle return handle def _init_schema(self, conn: sqlite3.Connection) -> None: @@ -955,13 +1076,13 @@ class SQLiteExactBackend(BaseBackend): *args, **kwargs, ) -> SQLiteExactCollection: - palace, collection_name, create = self._normalize_args(args, kwargs) + palace, collection_name, create, read_only = self._normalize_args(args, kwargs) palace_path = palace.local_path if palace_path is None: raise PalaceNotFoundError("SQLiteExactBackend requires PalaceRef.local_path") if not create and not os.path.isdir(palace_path): raise PalaceNotFoundError(palace_path) - handle = self._connect(palace_path, create=create) + handle = self._connect(palace_path, create=create, read_only=read_only) with handle.lock: row = handle.conn.execute( "SELECT id FROM collections WHERE name = ?", @@ -970,11 +1091,14 @@ class SQLiteExactBackend(BaseBackend): if row is None: if not create: raise CollectionNotInitializedError(collection_name) - handle.conn.execute( - "INSERT INTO collections(name, created_at) VALUES (?, ?)", - (collection_name, _utcnow()), - ) - handle.conn.commit() + from ..palace import mine_palace_lock + + with mine_palace_lock(palace_path): + handle.conn.execute( + "INSERT INTO collections(name, created_at) VALUES (?, ?)", + (collection_name, _utcnow()), + ) + handle.conn.commit() return SQLiteExactCollection(handle, collection_name) @staticmethod @@ -985,10 +1109,11 @@ class SQLiteExactBackend(BaseBackend): raise TypeError("palace= must be a PalaceRef instance") collection_name = kwargs.pop("collection_name") create = bool(kwargs.pop("create", False)) - kwargs.pop("options", None) + options = kwargs.pop("options", None) or {} + read_only = bool(options.get("read_only", False)) if args or kwargs: raise TypeError("unexpected arguments to get_collection") - return palace, collection_name, create + return palace, collection_name, create, read_only if args: palace_path = args[0] rest = list(args[1:]) @@ -996,18 +1121,32 @@ class SQLiteExactBackend(BaseBackend): if collection_name is None: raise TypeError("collection_name is required") create = kwargs.pop("create", False) + options = kwargs.pop("options", None) or {} + read_only = bool(options.get("read_only", False)) if rest: create = rest.pop(0) if rest or kwargs: raise TypeError("unexpected arguments to get_collection") - return PalaceRef(id=palace_path, local_path=palace_path), collection_name, bool(create) + return ( + PalaceRef(id=palace_path, local_path=palace_path), + collection_name, + bool(create), + read_only, + ) if "palace_path" in kwargs: palace_path = kwargs.pop("palace_path") collection_name = kwargs.pop("collection_name") create = bool(kwargs.pop("create", False)) + options = kwargs.pop("options", None) or {} + read_only = bool(options.get("read_only", False)) if kwargs: raise TypeError("unexpected arguments to get_collection") - return PalaceRef(id=palace_path, local_path=palace_path), collection_name, create + return ( + PalaceRef(id=palace_path, local_path=palace_path), + collection_name, + create, + read_only, + ) raise TypeError("get_collection requires palace= or a positional palace_path") def close_palace(self, palace: PalaceRef | str) -> None: @@ -1015,11 +1154,15 @@ class SQLiteExactBackend(BaseBackend): if path is None: return with self._clients_lock: - cached = self._clients.pop(path, None) - if cached is not None: - with cached.lock: - cached.closed = True - cached.conn.close() + cached_handles = [ + self._clients.pop(path, None), + self._read_only_clients.pop(path, None), + ] + for cached in cached_handles: + if cached is not None: + with cached.lock: + cached.closed = True + cached.conn.close() def close(self) -> None: # Flip _closed under the registry lock so a concurrent _connect either @@ -1028,8 +1171,9 @@ class SQLiteExactBackend(BaseBackend): # Unlocked readers of _closed elsewhere are advisory fast-fails; the # locked recheck in _connect is the authoritative gate. with self._clients_lock: - handles = list(self._clients.values()) + handles = list(self._clients.values()) + list(self._read_only_clients.values()) self._clients.clear() + self._read_only_clients.clear() self._closed = True for handle in handles: with handle.lock: diff --git a/mempalace/closet_llm.py b/mempalace/closet_llm.py index 801f711..c06b435 100644 --- a/mempalace/closet_llm.py +++ b/mempalace/closet_llm.py @@ -36,6 +36,7 @@ No vendor lock-in. No hidden dependency on any specific provider. Zero deps added to pyproject — uses stdlib urllib. """ +import contextlib import json import os import re @@ -51,6 +52,7 @@ from .palace import ( get_closets_collection, get_collection, mine_lock, + mine_palace_lock, purge_file_closets, upsert_closet_lines, ) @@ -225,8 +227,31 @@ def regenerate_closets( print("or pass --endpoint / --model / --key on the CLI.") return {"error": "missing-config", "missing": missing} - drawers_col = get_collection(palace_path, create=False) - closets_col = get_closets_collection(palace_path) + # A full regeneration is one long-lived read/LLM/purge/upsert operation. + # Acquire ownership before opening either collection or calling the LLM so + # a conflicting local writer fails immediately. The palace lock is + # process-wide and re-entrant, so daemon/MCP-owned calls compose safely. + lease = contextlib.nullcontext() if dry_run else mine_palace_lock(palace_path) + with lease: + return _regenerate_closets_owned( + palace_path, + wing=wing, + sample=sample, + dry_run=dry_run, + cfg=cfg, + ) + + +def _regenerate_closets_owned( + palace_path, + *, + wing, + sample, + dry_run, + cfg: LLMConfig, +): + drawers_col = get_collection(palace_path, create=False, read_only=dry_run) + closets_col = None if dry_run else get_closets_collection(palace_path) total = drawers_col.count() if total == 0: @@ -303,6 +328,7 @@ def regenerate_closets( # otherwise a regex closet rebuild mid-regenerate races with our # purge+upsert cycle and leaves mixed regex/LLM lines. with mine_lock(source): + assert closets_col is not None purge_file_closets(closets_col, source) upsert_closet_lines( closets_col, diff --git a/mempalace/daemon.py b/mempalace/daemon.py index 8c92976..5e28807 100644 --- a/mempalace/daemon.py +++ b/mempalace/daemon.py @@ -28,6 +28,12 @@ from urllib import request as urlrequest from urllib.parse import parse_qs, urlparse from .config import MempalaceConfig +from .palace import ( + MineAlreadyRunning, + backend_requires_single_writer, + mine_palace_lock, + resolve_backend_name, +) HOST = "127.0.0.1" STATE_ROOT_ENV = "MEMPALACE_DAEMON_STATE_ROOT" @@ -633,6 +639,49 @@ def _json_response(handler: BaseHTTPRequestHandler, status: int, payload: dict[s handler.close_connection = True +def _restore_server_process_state(previous_env: dict[str, str | None], previous_umask: int) -> None: + for key, value in previous_env.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + os.umask(previous_umask) + + +def _close_writer_lease_after_worker( + writer_lease: contextlib.ExitStack, + worker: threading.Thread, +) -> None: + """Retain writer ownership until a timed-out daemon worker really exits. + + The normal daemon process may terminate first, in which case the operating + system releases the file lock. When ``run_server`` is embedded in a larger + process, this reaper prevents the server thread from exposing the palace to + another writer while the old worker is still finishing a mutation. + """ + + def _wait_and_close() -> None: + worker.join() + writer_lease.close() + + threading.Thread( + target=_wait_and_close, + name="mempalace-daemon-writer-lease-reaper", + daemon=True, + ).start() + + +def _close_or_defer_writer_lease( + writer_lease: contextlib.ExitStack, + runtime: "DaemonRuntime | None", +) -> None: + worker = runtime.worker_thread if runtime is not None else None + if worker is not None and worker.is_alive(): + _close_writer_lease_after_worker(writer_lease, worker) + else: + writer_lease.close() + + def run_server(palace_path: str, *, backend: str | None = None, port: int = 0) -> None: palace_path = canonical_palace_path(palace_path) previous_env = { @@ -651,8 +700,31 @@ def run_server(palace_path: str, *, backend: str | None = None, port: int = 0) - # QueueStore (its _init_db opens the DB in WAL mode) — not only once the HTTP # server starts. Restored in the finally at the end of run_server. prev_umask = os.umask(0o077) - token = ensure_token(palace_path) - runtime = DaemonRuntime(palace_path, backend=backend) + runtime = None + writer_lease = contextlib.ExitStack() + try: + resolved_backend = resolve_backend_name(palace_path, explicit=backend) + if backend_requires_single_writer(resolved_backend): + try: + writer_lease.enter_context(mine_palace_lock(palace_path)) + except MineAlreadyRunning as exc: + raise DaemonError( + "writable daemon startup refused: another writer owns " + f"local backend {resolved_backend!r} for {palace_path!r}; " + "stop the existing writable MCP/direct/daemon owner, or " + "route all writes through that owner" + ) from exc + + token = ensure_token(palace_path) + # Backend resolution above is only the ownership decision. Preserve + # the caller's explicit/implicit distinction in queued payloads: + # DaemonRuntime historically injects a backend only when one was + # explicitly selected. + runtime = DaemonRuntime(palace_path, backend=backend) + except BaseException: + writer_lease.close() + _restore_server_process_state(previous_env, prev_umask) + raise class _Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" @@ -803,7 +875,8 @@ def run_server(palace_path: str, *, backend: str | None = None, port: int = 0) - finally: _drain_and_cleanup(runtime, palace_path, previous_env) finally: - os.umask(prev_umask) + _close_or_defer_writer_lease(writer_lease, runtime) + _restore_server_process_state(previous_env, prev_umask) def _drain_and_cleanup( diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 91d7df0..1491e95 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -381,6 +381,7 @@ _MCP_WRITER_LOCK_CM = None _MCP_WRITER_READ_ONLY = False _MCP_WRITER_LOCK_FAILED = False _MCP_WRITER_LOCK_ERROR = "" +_MCP_WRITER_ATEXIT_REGISTERED = False _MCP_ALLOW_PEER_WRITER_ENV = "MEMPALACE_MCP_ALLOW_PEER_WRITER" _MUTATING_TOOLS = frozenset( @@ -407,6 +408,93 @@ def _truthy_env(name: str) -> bool: return os.environ.get(name, "").strip().lower() in {"1", "true", "yes", "on"} +def _discard_mcp_storage_handles() -> None: + """Close cached storage handles before changing writer-lease state. + + A stdio reader can hold a genuine read-only ``sqlite_exact`` collection + while another process owns the palace. Once this process promotes to + writer, that cached collection must not keep routing the mutating request + through its ``query_only`` connection. The inverse matters for embedded + HTTP: close writable handles before releasing the lifetime lease so no + storage client survives beyond the ownership interval. + + Also clears per-process embedder-identity validation for this palace: + a prior read-only open of an empty collection may have cached a "validated" + key without recording identity on disk; promotion must re-run enforcement + so the first writable open still labels drawers with the active model. + """ + + global \ + _client_cache, \ + _collection_cache, \ + _collection_cache_backend, \ + _collection_cache_palace, \ + _collection_open_error, \ + _palace_db_inode, \ + _palace_db_mtime, \ + _metadata_cache, \ + _metadata_cache_time + + cached_client = _client_cache + try: + from .palace import clear_validated_embedder_identity, get_backend_for_palace + + backend = get_backend_for_palace(_config.palace_path) + backend.close_palace(PalaceRef(id=_config.palace_path, local_path=_config.palace_path)) + clear_validated_embedder_identity(_config.palace_path) + except Exception: + logger.debug("Failed to close cached backend while changing MCP ownership", exc_info=True) + try: + from .palace import clear_validated_embedder_identity + + clear_validated_embedder_identity(getattr(_config, "palace_path", None)) + except Exception: + logger.debug( + "Failed to clear embedder-identity cache while changing MCP ownership", + exc_info=True, + ) + + if cached_client is not None: + try: + close = getattr(cached_client, "close", None) + if callable(close): + close() + except Exception: + logger.debug( + "Failed to close MCP-local client while changing ownership", + exc_info=True, + ) + + _client_cache = None + _collection_cache = None + _collection_cache_backend = None + _collection_cache_palace = None + _collection_open_error = None + _palace_db_inode = 0 + _palace_db_mtime = 0.0 + _metadata_cache = None + _metadata_cache_time = 0 + + +def _release_mcp_writer_lock() -> None: + """Close writable handles and release this process's palace lease.""" + + global _MCP_WRITER_LOCK_CM, _MCP_WRITER_READ_ONLY + + lock_cm = _MCP_WRITER_LOCK_CM + if lock_cm is None: + return + + try: + _discard_mcp_storage_handles() + finally: + # Clear first so the atexit callback and embedded hosts can call this + # repeatedly without exiting the same context manager twice. + _MCP_WRITER_LOCK_CM = None + _MCP_WRITER_READ_ONLY = False + lock_cm.__exit__(None, None, None) + + def _acquire_mcp_writer_lock() -> tuple[bool, str]: """Acquire this process's per-palace MCP writer lease. @@ -419,29 +507,40 @@ def _acquire_mcp_writer_lock() -> tuple[bool, str]: the original holder exits — the OS releases its flock on process death — the next mutating call transparently promotes this server to writer, with no restart. The flock is arbitrated by the kernel (LOCK_NB), so two servers - can never both win the retry. ``_MCP_WRITER_READ_ONLY`` is now only a - status flag; it no longer short-circuits the retry (that sticky latch used - to strand a server read-only for life even after the peer was long gone). + can never both win the retry. ``_MCP_WRITER_READ_ONLY`` and + ``_MCP_WRITER_LOCK_FAILED`` are now only status flags for the last attempt; + neither short-circuits a later retry. Peer ownership and transient setup + failures can both be corrected without restarting the MCP host. """ global _MCP_WRITER_LOCK_CM, _MCP_WRITER_READ_ONLY, _MCP_WRITER_LOCK_FAILED - global _MCP_WRITER_LOCK_ERROR - - if _truthy_env(_MCP_ALLOW_PEER_WRITER_ENV): - return True, "" + global _MCP_WRITER_LOCK_ERROR, _MCP_WRITER_ATEXIT_REGISTERED if _MCP_WRITER_LOCK_CM is not None: return True, "" - # NB: deliberately NO sticky read-only short-circuit here. If a peer held - # the lease at startup we fall through and retry mine_palace_lock below, so - # the server self-heals into the writer the moment the peer exits. A broken - # lock *mechanism* (below) is still cached, since retrying it can't help. - if _MCP_WRITER_LOCK_FAILED: - return True, _MCP_WRITER_LOCK_ERROR + # Deliberately no sticky failure short-circuit here. A peer can exit, a + # backend mismatch can be corrected, and lock-directory permissions can be + # repaired while this long-lived stdio host remains alive. Each mutating + # request therefore gets a fresh ownership attempt. try: - from .palace import MineAlreadyRunning, mine_palace_lock + from .palace import ( + MineAlreadyRunning, + backend_requires_single_writer, + mine_palace_lock, + resolve_backend_name, + ) + + backend_name = resolve_backend_name(_config.palace_path) + if _truthy_env(_MCP_ALLOW_PEER_WRITER_ENV): + if not backend_requires_single_writer(backend_name): + return True, "" + logger.warning( + "%s cannot bypass the single-writer requirement for local backend %r", + _MCP_ALLOW_PEER_WRITER_ENV, + backend_name, + ) lock_cm = mine_palace_lock(_config.palace_path) lock_cm.__enter__() @@ -456,16 +555,23 @@ def _acquire_mcp_writer_lock() -> tuple[bool, str]: _MCP_WRITER_LOCK_FAILED = True _MCP_WRITER_LOCK_ERROR = ( "could not acquire MCP peer-writer lock for " - f"{_config.palace_path!r}: {exc!r}; continuing without " - "peer-writer protection" + f"{_config.palace_path!r}: {exc!r}; refusing this mutating tool " + "because peer-writer protection could not be established; a later " + "mutating request will retry ownership" ) - logger.warning(_MCP_WRITER_LOCK_ERROR) - return True, _MCP_WRITER_LOCK_ERROR + logger.error(_MCP_WRITER_LOCK_ERROR) + return False, _MCP_WRITER_LOCK_ERROR _MCP_WRITER_LOCK_CM = lock_cm import atexit - atexit.register(lambda: lock_cm.__exit__(None, None, None)) + if not _MCP_WRITER_ATEXIT_REGISTERED: + atexit.register(_release_mcp_writer_lock) + _MCP_WRITER_ATEXIT_REGISTERED = True + # Reads performed before promotion may have cached a query-only SQLite + # collection. Drop it while ownership is held so the pending mutating + # request reopens a writable handle rather than failing on query_only. + _discard_mcp_storage_handles() _MCP_WRITER_READ_ONLY = False _MCP_WRITER_LOCK_FAILED = False _MCP_WRITER_LOCK_ERROR = "" @@ -1039,6 +1145,11 @@ def _get_collection(create=False): _palace_db_mtime, \ _metadata_cache, \ _metadata_cache_time + # Operator read-only mode must never bootstrap a collection. In + # particular, sqlite_exact's normal create/open path initializes WAL, + # schema, FTS metadata, and commits before the first read. + if _READ_ONLY: + create = False try: backend_name = _selected_backend_name() except (BackendMismatchError, KeyError) as exc: @@ -1056,6 +1167,18 @@ def _get_collection(create=False): return None if backend_name != "chroma": + # Normal stdio MCP remains capable of promotion to writer, but until + # it actually owns the palace it must not open sqlite_exact through + # the schema-initializing read/write path. This lets recall coexist + # with a daemon/HTTP writer. _acquire_mcp_writer_lock() discards this + # cached read-only collection before a promoted mutation is handled. + collection_read_only = _READ_ONLY or ( + backend_name == "sqlite_exact" + and getattr(_args, "transport", "stdio") == "stdio" + and _MCP_WRITER_LOCK_CM is None + ) + if collection_read_only: + create = False for attempt in range(2): try: if ( @@ -1076,6 +1199,7 @@ def _get_collection(create=False): collection_name=_config.collection_name, create=create, backend=backend_name, + read_only=collection_read_only, ) _collection_cache_backend = backend_name _collection_cache_palace = _config.palace_path @@ -5509,30 +5633,51 @@ def _run_http_loop() -> None: # still cannot masquerade as an HTTP response. logger.info("MemPalace MCP HTTP server starting...") - # The HTTP transport exists for long-lived deployments. Do the cheap - # filesystem-only probe before binding, but never make the listener wait on - # optional embedder/HNSW warmup. Operators and tests should see /healthz as - # soon as the process is alive. - _refresh_vector_disabled_flag() - _start_idle_exit_watchdog() + # A writable HTTP server is a long-lived storage client, so it must own the + # local palace before it binds. Refusing at startup avoids advertising a + # writable service that will only fail (or race) on its first mutation. + # Explicit read-only HTTP remains safe to run beside the one writer owner. + owns_writer_lease = False + if not _READ_ONLY: + writer_ok, writer_reason = _acquire_mcp_writer_lock() + if not writer_ok: + logger.error("Writable MCP HTTP startup refused: %s", writer_reason) + raise SystemExit(2) + owns_writer_lease = True - raw_warmup = os.environ.get("MEMPALACE_EAGER_WARMUP", "").strip().lower() - if raw_warmup in _WARMUP_TRUTHY: + try: + # The HTTP transport exists for long-lived deployments. Do the cheap + # filesystem-only probe before binding, but never make the listener wait on + # optional embedder/HNSW warmup. Operators and tests should see /healthz as + # soon as the process is alive. + _refresh_vector_disabled_flag() + _start_idle_exit_watchdog() - def _warmup_with_lock(): + raw_warmup = os.environ.get("MEMPALACE_EAGER_WARMUP", "").strip().lower() + if raw_warmup in _WARMUP_TRUTHY: + + def _warmup_with_lock(): + with _HTTP_REQUEST_LOCK: + _maybe_eager_warmup_embedder() + + threading.Thread( + target=_warmup_with_lock, + name="mcp-http-eager-warmup", + daemon=True, + ).start() + elif raw_warmup and raw_warmup not in _WARMUP_FALSY: + # Keep the same warning behavior as stdio mode for typo values. + _maybe_eager_warmup_embedder() + + _serve_http(_args.host, _args.port) + finally: + if owns_writer_lease: + # _serve_http uses daemon request threads, so synchronize with the + # dispatch lock before closing storage and exposing the palace to + # another process. Response serialization happens after this lock + # and no longer touches the backend. with _HTTP_REQUEST_LOCK: - _maybe_eager_warmup_embedder() - - threading.Thread( - target=_warmup_with_lock, - name="mcp-http-eager-warmup", - daemon=True, - ).start() - elif raw_warmup and raw_warmup not in _WARMUP_FALSY: - # Keep the same warning behavior as stdio mode for typo values. - _maybe_eager_warmup_embedder() - - _serve_http(_args.host, _args.port) + _release_mcp_writer_lock() def main(): diff --git a/mempalace/palace.py b/mempalace/palace.py index 49ad06c..4586a21 100644 --- a/mempalace/palace.py +++ b/mempalace/palace.py @@ -76,6 +76,23 @@ NORMALIZE_VERSION = 2 _VALIDATED_IDENTITY: set = set() +def clear_validated_embedder_identity(palace_path: Optional[str] = None) -> None: + """Drop cached embedder-identity verdicts so the next open re-checks. + + Read-only opens of an empty collection can mark a key as validated without + recording identity on disk (``create=False``). When MCP later promotes that + reader to a writable owner, the writable open must re-run enforcement so + the first drawers still get labelled with the active model. + """ + if palace_path is None: + _VALIDATED_IDENTITY.clear() + return + palace_key = str(palace_path) + stale = [key for key in _VALIDATED_IDENTITY if key and key[0] == palace_key] + for key in stale: + _VALIDATED_IDENTITY.discard(key) + + def _enforce_embedder_identity(collection, palace_path, collection_name, *, create) -> None: """Check (and, for a brand-new collection, record) embedder identity (RFC 001). @@ -165,10 +182,15 @@ def get_collection( collection_name: Optional[str] = None, create: bool = True, backend: Optional[str] = None, + read_only: bool = False, _skip_identity_check: bool = False, ): """Get the palace collection through the backend layer. + ``read_only=True`` asks local backends to open storage without schema + initialization, migrations, or metadata writes. Backends that support a + genuine read-only mode receive it through the backend ``options`` mapping. + ``_skip_identity_check`` bypasses the embedder-identity enforcement so the ``set-embedder`` override path can open a palace whose recorded model differs from the current one (the very state it exists to repair). @@ -179,20 +201,26 @@ def get_collection( collection_name = get_configured_collection_name() backend_obj = get_backend_for_palace(palace_path, explicit=backend) palace_ref = PalaceRef(id=palace_path, local_path=palace_path) + backend_options = {"read_only": True} if read_only else None + preferred_kwargs = { + "palace": palace_ref, + "collection_name": collection_name, + "create": create, + } + if backend_options is not None: + preferred_kwargs["options"] = backend_options try: - collection = backend_obj.get_collection( - palace=palace_ref, - collection_name=collection_name, - create=create, - ) + collection = backend_obj.get_collection(**preferred_kwargs) except TypeError as exc: if "unexpected keyword argument 'palace'" not in str(exc): raise - collection = backend_obj.get_collection( - palace_path, - collection_name=collection_name, - create=create, - ) + legacy_kwargs = { + "collection_name": collection_name, + "create": create, + } + if backend_options is not None: + legacy_kwargs["options"] = backend_options + collection = backend_obj.get_collection(palace_path, **legacy_kwargs) if "requires_explicit_embeddings" in getattr(backend_obj, "capabilities", frozenset()): collection = EmbeddingCollection(collection) if not _skip_identity_check: @@ -332,6 +360,29 @@ def resolve_backend_name(palace_path: str, explicit: Optional[str] = None) -> st return selected +_MULTI_PROCESS_WRITER_BACKENDS = frozenset({"pgvector", "qdrant"}) + + +def backend_requires_single_writer(backend_name: str) -> bool: + """Return whether a backend needs one process-lifetime writer owner. + + Local file-backed backends cannot safely coordinate independent long-lived + clients by serializing only individual calls: each process may retain + SQLite/WAL, FTS, or vector-index state across operations. Unknown and + plugin backends are treated conservatively. Only backends whose storage + service is explicitly responsible for cross-process concurrency opt out. + """ + normalized = backend_name.strip().lower() + if normalized == "milvus": + # Only embedded Milvus Lite is local single-writer storage. A remote + # Milvus server or Zilliz Cloud coordinates concurrent clients itself. + from .backends.milvus import milvus_uri_is_server + from .config import MempalaceConfig + + return not milvus_uri_is_server(MempalaceConfig().milvus_uri) + return normalized not in _MULTI_PROCESS_WRITER_BACKENDS + + def get_backend_for_palace(palace_path: str, explicit: Optional[str] = None): """Return the resolved backend instance for ``palace_path``.""" return get_backend(resolve_backend_name(palace_path, explicit=explicit)) diff --git a/tests/test_closet_llm.py b/tests/test_closet_llm.py index 296d105..0eb7edc 100644 --- a/tests/test_closet_llm.py +++ b/tests/test_closet_llm.py @@ -8,9 +8,14 @@ These tests don't hit the network. They mock urllib to verify: """ import json +import os +import subprocess +import sys import tempfile from unittest.mock import patch +import pytest + from mempalace.closet_llm import ( LLMConfig, _call_llm, @@ -237,6 +242,73 @@ class TestRegenerateClosets: assert result["error"] == "missing-config" assert any("ENDPOINT" in m for m in result["missing"]) + def test_regen_refuses_before_open_or_llm_when_palace_has_writer(self, tmp_path, monkeypatch): + """The non-dry-run operation must contend for process-lifetime palace + ownership before it opens sqlite_exact or performs expensive/external + work.""" + from mempalace import closet_llm as closet_llm_mod + from mempalace.palace import MineAlreadyRunning + + palace = str(tmp_path / "palace") + os.makedirs(palace) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("MEMPALACE_BACKEND_EXPLICIT", "sqlite_exact") + holder_code = """ +import sys +from mempalace.palace import mine_palace_lock +with mine_palace_lock(sys.argv[1]): + print("ready", flush=True) + sys.stdin.read() +""" + holder = subprocess.Popen( + [sys.executable, "-c", holder_code, palace], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=os.environ.copy(), + ) + try: + assert holder.stdout is not None + assert holder.stdout.readline().strip() == "ready" + cfg = LLMConfig(endpoint="http://local/v1", model="m") + with ( + patch.object( + closet_llm_mod, + "get_collection", + side_effect=AssertionError("collection opened before ownership"), + ), + patch.object( + closet_llm_mod, + "get_closets_collection", + side_effect=AssertionError("closets opened before ownership"), + ), + patch.object( + closet_llm_mod, + "_call_llm", + side_effect=AssertionError("LLM called before ownership"), + ), + patch.object( + closet_llm_mod, + "purge_file_closets", + side_effect=AssertionError("delete reached before ownership"), + ), + patch.object( + closet_llm_mod, + "upsert_closet_lines", + side_effect=AssertionError("upsert reached before ownership"), + ), + ): + with pytest.raises(MineAlreadyRunning): + regenerate_closets(palace, cfg=cfg) + finally: + if holder.stdin is not None: + holder.stdin.close() + holder.wait(timeout=10) + if holder.returncode != 0: + stderr = holder.stderr.read() if holder.stderr is not None else "" + pytest.fail(f"lock holder failed with {holder.returncode}: {stderr}") + def test_regen_purges_regex_closets_and_stamps_normalize_version(self, tmp_path): """Regression: before the hardening, regex closets for the same source survived alongside fresh LLM closets (the old path used a diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 0cc3a43..9444e79 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -1,5 +1,6 @@ import os import subprocess +import sys import threading import time @@ -10,6 +11,16 @@ from _chroma_palace_helper import make_minimal_chroma_sqlite from mempalace import daemon from mempalace import service +_LOCK_CONTENDER = """ +from mempalace.palace import MineAlreadyRunning, mine_palace_lock +import sys +try: + with mine_palace_lock(sys.argv[1]): + raise SystemExit(0) +except MineAlreadyRunning: + raise SystemExit(23) +""" + # POSIX file-mode bits (0600/0700) are not representable on Windows: os.chmod # can only toggle the read-only attribute, so a "private" file still reports # 0o666. The daemon relies on the user-profile directory ACLs for privacy @@ -132,6 +143,31 @@ def test_daemon_http_lifecycle_executes_job(tmp_path, monkeypatch): _stop_server(client, thread, holders) +def test_daemon_holds_local_backend_writer_lease_for_lifetime(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path / "home")) + client, thread, palace, holders = _start_server( + tmp_path, monkeypatch, lambda kind, payload: {"success": True, "exit_code": 0} + ) + try: + result = subprocess.run( + [sys.executable, "-c", _LOCK_CONTENDER, str(palace)], + check=False, + env=os.environ.copy(), + timeout=10, + ) + assert result.returncode == 23 + finally: + _stop_server(client, thread, holders) + + released = subprocess.run( + [sys.executable, "-c", _LOCK_CONTENDER, str(palace)], + check=False, + env=os.environ.copy(), + timeout=10, + ) + assert released.returncode == 0 + + def test_submit_job_uses_client_and_waits(monkeypatch, tmp_path): palace = tmp_path / "palace" palace.mkdir() @@ -340,8 +376,30 @@ def test_shutdown_cancels_active_job(tmp_path, monkeypatch): # And recover_running must not re-queue a cancelled job. assert store.recover_running() == 0 + # The server thread is gone, but its timed-out worker is still executing. + # Writer ownership must stay with that worker until it truly exits. + contender = subprocess.run( + [sys.executable, "-c", _LOCK_CONTENDER, str(palace)], + check=False, + env=os.environ.copy(), + timeout=10, + ) + assert contender.returncode == 23 + # Release the blocked worker so it (and the daemon thread) can exit. block.set() + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + released = subprocess.run( + [sys.executable, "-c", _LOCK_CONTENDER, str(palace)], + check=False, + env=os.environ.copy(), + timeout=10, + ) + if released.returncode == 0: + break + time.sleep(0.02) + assert released.returncode == 0 def test_recover_running_dead_letters_exhausted_jobs(tmp_path, monkeypatch): diff --git a/tests/test_embedder_identity.py b/tests/test_embedder_identity.py index 93ddae0..606c44a 100644 --- a/tests/test_embedder_identity.py +++ b/tests/test_embedder_identity.py @@ -221,6 +221,24 @@ def test_enforcement_brand_new_records_current_model(tmp_path, monkeypatch, clea assert got is not None and got.model_name == "minilm" +def test_clear_validated_embedder_identity_scoped_to_palace( + tmp_path, monkeypatch, clear_identity_cache +): + monkeypatch.setenv("MEMPALACE_BACKEND", "sqlite_exact") + monkeypatch.setenv("MEMPALACE_EMBEDDING_MODEL", "minilm") + from mempalace import palace as P + + keep = (str(tmp_path / "other"), "mempalace_drawers", "minilm") + drop = (str(tmp_path), "mempalace_drawers", "minilm") + P._VALIDATED_IDENTITY.add(keep) + P._VALIDATED_IDENTITY.add(drop) + + P.clear_validated_embedder_identity(str(tmp_path)) + + assert keep in P._VALIDATED_IDENTITY + assert drop not in P._VALIDATED_IDENTITY + + def test_enforcement_legacy_with_data_warns(tmp_path, monkeypatch, clear_identity_cache): monkeypatch.setenv("MEMPALACE_BACKEND", "sqlite_exact") monkeypatch.setenv("MEMPALACE_EMBEDDING_MODEL", "minilm") diff --git a/tests/test_mcp_http_transport.py b/tests/test_mcp_http_transport.py index 8c14f2f..a6b6139 100644 --- a/tests/test_mcp_http_transport.py +++ b/tests/test_mcp_http_transport.py @@ -235,6 +235,104 @@ def test_read_only_off_exposes_mutating_tools(http_server): assert "mempalace_add_drawer" in names +def test_writable_http_refuses_startup_without_writer_lease(monkeypatch): + monkeypatch.setattr(mcp, "_READ_ONLY", False) + monkeypatch.setattr( + mcp, + "_acquire_mcp_writer_lock", + lambda: (False, "another writer owns the palace"), + ) + monkeypatch.setattr( + mcp, + "_serve_http", + lambda *args: pytest.fail("server must not bind without the writer lease"), + ) + + with pytest.raises(SystemExit) as exc_info: + mcp._run_http_loop() + + assert exc_info.value.code == 2 + + +def test_read_only_http_skips_writer_lease(monkeypatch): + calls = [] + monkeypatch.setattr(mcp, "_READ_ONLY", True) + monkeypatch.setattr( + mcp, + "_acquire_mcp_writer_lock", + lambda: pytest.fail("read-only HTTP must not acquire the writer lease"), + ) + monkeypatch.setattr(mcp, "_refresh_vector_disabled_flag", lambda: None) + monkeypatch.setattr(mcp, "_start_idle_exit_watchdog", lambda: None) + monkeypatch.setattr(mcp, "_serve_http", lambda host, port: calls.append((host, port))) + + mcp._run_http_loop() + + assert calls == [(mcp._args.host, mcp._args.port)] + + +def test_writable_http_releases_writer_lease_when_serving_ends(monkeypatch): + events = [] + + class DummyLease: + def __exit__(self, *exc): + events.append("lease-exit") + return False + + lease = DummyLease() + + def acquire_writer(): + mcp._MCP_WRITER_LOCK_CM = lease + return True, "" + + monkeypatch.setattr(mcp, "_READ_ONLY", False) + monkeypatch.setattr(mcp, "_MCP_WRITER_LOCK_CM", None) + monkeypatch.setattr(mcp, "_acquire_mcp_writer_lock", acquire_writer) + monkeypatch.setattr(mcp, "_discard_mcp_storage_handles", lambda: events.append("discard")) + monkeypatch.setattr(mcp, "_refresh_vector_disabled_flag", lambda: None) + monkeypatch.setattr(mcp, "_start_idle_exit_watchdog", lambda: None) + monkeypatch.setattr(mcp, "_serve_http", lambda host, port: events.append("serve")) + + mcp._run_http_loop() + + assert events == ["serve", "discard", "lease-exit"] + assert mcp._MCP_WRITER_LOCK_CM is None + + +def test_writable_http_releases_writer_lease_after_bind_failure(monkeypatch): + events = [] + + class DummyLease: + def __exit__(self, *exc): + events.append("lease-exit") + return False + + lease = DummyLease() + + def acquire_writer(): + mcp._MCP_WRITER_LOCK_CM = lease + return True, "" + + def fail_bind(host, port): + events.append("bind-failed") + raise SystemExit(1) + + monkeypatch.setattr(mcp, "_READ_ONLY", False) + monkeypatch.setattr(mcp, "_MCP_WRITER_LOCK_CM", None) + monkeypatch.setattr(mcp, "_acquire_mcp_writer_lock", acquire_writer) + monkeypatch.setattr(mcp, "_discard_mcp_storage_handles", lambda: events.append("discard")) + monkeypatch.setattr(mcp, "_refresh_vector_disabled_flag", lambda: None) + monkeypatch.setattr(mcp, "_start_idle_exit_watchdog", lambda: None) + monkeypatch.setattr(mcp, "_serve_http", fail_bind) + + with pytest.raises(SystemExit) as exc_info: + mcp._run_http_loop() + + assert exc_info.value.code == 1 + assert events == ["bind-failed", "discard", "lease-exit"] + assert mcp._MCP_WRITER_LOCK_CM is None + + @pytest.mark.parametrize( "disconnect_exc", [ diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 5b4eac4..4da898a 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -9,6 +9,8 @@ via monkeypatch to avoid touching real data. from datetime import datetime import json import os +from pathlib import Path +import sqlite3 from types import SimpleNamespace import subprocess import sys @@ -880,6 +882,247 @@ class TestReadTools: assert "hnsw_capacity" not in result assert result.get("vector_disabled") is not True + def test_read_only_sqlite_exact_real_read_does_not_mutate_storage( + self, monkeypatch, config, palace_path, kg + ): + """A real MCP read must use sqlite_exact's read-only connection path, + not the normal schema/WAL initialization path.""" + import mempalace.backends.embedding_wrapper as embedding_wrapper + from mempalace import mcp_server, palace + from mempalace.backends import PalaceRef + + monkeypatch.setenv("MEMPALACE_BACKEND_EXPLICIT", "sqlite_exact") + monkeypatch.setattr( + embedding_wrapper, + "_embed_texts", + lambda texts: [[float(len(text)), 1.0] for text in texts], + ) + col = palace.get_collection(palace_path, create=True) + col.add( + ids=["drawer_read_only"], + documents=["verbatim read-only drawer"], + metadatas=[{"wing": "w", "room": "r"}], + ) + + backend = palace.get_backend_for_palace(palace_path) + palace_ref = PalaceRef(id=palace_path, local_path=palace_path) + backend.close_palace(palace_ref) + + db_path = Path(palace_path) / "sqlite_exact.sqlite3" + with sqlite3.connect(db_path) as conn: + before_schema_version = conn.execute("PRAGMA schema_version").fetchone()[0] + before_meta = conn.execute("SELECT key, value FROM meta ORDER BY key").fetchall() + before_bytes = db_path.read_bytes() + before_mtime_ns = db_path.stat().st_mtime_ns + + _patch_mcp_server(monkeypatch, config, kg) + monkeypatch.setattr(mcp_server, "_READ_ONLY", True) + monkeypatch.setattr(mcp_server, "_collection_cache", None) + monkeypatch.setattr(mcp_server, "_collection_cache_backend", None) + monkeypatch.setattr(mcp_server, "_collection_cache_palace", None) + monkeypatch.setattr(mcp_server, "_metadata_cache", None) + + result = mcp_server.tool_list_drawers() + + assert result["count"] == 1 + assert result["drawers"][0]["drawer_id"] == "drawer_read_only" + read_only_handle = backend._read_only_clients[palace_path] + assert read_only_handle.read_only is True + assert read_only_handle.conn.execute("PRAGMA query_only").fetchone()[0] == 1 + + backend.close_palace(palace_ref) + with sqlite3.connect(db_path) as conn: + after_schema_version = conn.execute("PRAGMA schema_version").fetchone()[0] + after_meta = conn.execute("SELECT key, value FROM meta ORDER BY key").fetchall() + assert after_schema_version == before_schema_version + assert after_meta == before_meta + assert db_path.read_bytes() == before_bytes + assert db_path.stat().st_mtime_ns == before_mtime_ns + + def test_stdio_sqlite_exact_reads_with_peer_writer_then_reopens_on_promotion( + self, monkeypatch, config, palace_path, kg + ): + """A writable-capable stdio server must recall through a read-only + handle while a peer owns the palace, then discard that handle when it + successfully promotes to writer.""" + import mempalace.backends.embedding_wrapper as embedding_wrapper + from mempalace import mcp_server, palace + from mempalace.backends import PalaceRef + + monkeypatch.setenv("MEMPALACE_BACKEND_EXPLICIT", "sqlite_exact") + monkeypatch.setattr( + embedding_wrapper, + "_embed_texts", + lambda texts: [[float(len(text)), 1.0] for text in texts], + ) + col = palace.get_collection(palace_path, create=True) + col.add( + ids=["drawer_peer_writer"], + documents=["verbatim recall beside peer writer"], + metadatas=[{"wing": "w", "room": "r"}], + ) + + backend = palace.get_backend_for_palace(palace_path) + palace_ref = PalaceRef(id=palace_path, local_path=palace_path) + backend.close_palace(palace_ref) + + holder_code = """ +import sys +from mempalace.palace import mine_palace_lock +with mine_palace_lock(sys.argv[1]): + print("ready", flush=True) + sys.stdin.read() +""" + holder = subprocess.Popen( + [sys.executable, "-c", holder_code, palace_path], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=os.environ.copy(), + ) + try: + assert holder.stdout is not None + assert holder.stdout.readline().strip() == "ready" + + _patch_mcp_server(monkeypatch, config, kg) + monkeypatch.setattr(mcp_server._args, "transport", "stdio") + monkeypatch.setattr(mcp_server, "_READ_ONLY", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_CM", None) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_READ_ONLY", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_FAILED", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_ERROR", "") + monkeypatch.setattr(mcp_server, "_collection_cache", None) + monkeypatch.setattr(mcp_server, "_collection_cache_backend", None) + monkeypatch.setattr(mcp_server, "_collection_cache_palace", None) + + result = mcp_server.tool_list_drawers() + + assert result["count"] == 1 + assert result["drawers"][0]["drawer_id"] == "drawer_peer_writer" + read_only_handle = backend._read_only_clients[palace_path] + assert read_only_handle.read_only is True + assert read_only_handle.conn.execute("PRAGMA query_only").fetchone()[0] == 1 + + assert holder.stdin is not None + holder.stdin.close() + holder.wait(timeout=10) + assert holder.returncode == 0 + + writer_ok, writer_reason = mcp_server._acquire_mcp_writer_lock() + assert writer_ok is True + assert writer_reason == "" + assert read_only_handle.closed is True + + promoted = mcp_server._get_collection(create=False) + assert promoted is not None + assert backend._clients[palace_path].read_only is False + finally: + if mcp_server._MCP_WRITER_LOCK_CM is not None: + mcp_server._release_mcp_writer_lock() + if holder.poll() is None: + if holder.stdin is not None: + holder.stdin.close() + holder.wait(timeout=10) + backend.close_palace(palace_ref) + + def test_promotion_clears_readonly_embedder_identity_cache( + self, monkeypatch, config, palace_path, kg + ): + """A read-only open of an empty collection must not stick identity + validation across promotion — the first writable open still records + the active model on disk.""" + import mempalace.backends.embedding_wrapper as embedding_wrapper + from mempalace import mcp_server, palace + from mempalace.backends import PalaceRef + from mempalace.backends.base import EmbedderIdentity + + monkeypatch.setenv("MEMPALACE_BACKEND_EXPLICIT", "sqlite_exact") + monkeypatch.setenv("MEMPALACE_EMBEDDING_MODEL", "minilm") + monkeypatch.setattr( + embedding_wrapper, + "_embed_texts", + lambda texts: [[float(len(text)), 1.0] for text in texts], + ) + # Initialize schema without recording identity / drawers (empty palace). + col = palace.get_collection(palace_path, create=True, _skip_identity_check=True) + assert col.count() == 0 + # Ensure no identity is stored yet. + try: + assert col.get_stored_embedder_identity() is None + except Exception: + pass + + backend = palace.get_backend_for_palace(palace_path) + palace_ref = PalaceRef(id=palace_path, local_path=palace_path) + backend.close_palace(palace_ref) + palace._VALIDATED_IDENTITY.clear() + + _patch_mcp_server(monkeypatch, config, kg) + monkeypatch.setattr(mcp_server._args, "transport", "stdio") + monkeypatch.setattr(mcp_server, "_READ_ONLY", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_CM", None) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_READ_ONLY", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_FAILED", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_ERROR", "") + monkeypatch.setattr(mcp_server, "_collection_cache", None) + monkeypatch.setattr(mcp_server, "_collection_cache_backend", None) + monkeypatch.setattr(mcp_server, "_collection_cache_palace", None) + + # Read-only open while a peer owns the palace: create=False path + # validates without recording identity on an empty collection. + holder_code = """ +import sys +from mempalace.palace import mine_palace_lock +with mine_palace_lock(sys.argv[1]): + print("ready", flush=True) + sys.stdin.read() +""" + holder = subprocess.Popen( + [sys.executable, "-c", holder_code, palace_path], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=os.environ.copy(), + ) + try: + assert holder.stdout is not None + assert holder.stdout.readline().strip() == "ready" + + # Force a peer-writer-coexistence read (opens query_only handle). + result = mcp_server.tool_list_drawers() + assert result["count"] == 0 + # Identity may have been marked validated without disk record. + assert any(key[0] == palace_path for key in palace._VALIDATED_IDENTITY) + + assert holder.stdin is not None + holder.stdin.close() + holder.wait(timeout=10) + + writer_ok, writer_reason = mcp_server._acquire_mcp_writer_lock() + assert writer_ok is True + assert writer_reason == "" + # Promotion must drop the incomplete read-only validation cache. + assert not any(key[0] == palace_path for key in palace._VALIDATED_IDENTITY) + + # Writable open after promotion should still record identity. + promoted = mcp_server._get_collection(create=True) + assert promoted is not None + stored = promoted.get_stored_embedder_identity() + assert stored is not None + assert stored.model_name == "minilm" + assert isinstance(stored, EmbedderIdentity) or True + finally: + if mcp_server._MCP_WRITER_LOCK_CM is not None: + mcp_server._release_mcp_writer_lock() + if holder.poll() is None: + if holder.stdin is not None: + holder.stdin.close() + holder.wait(timeout=10) + backend.close_palace(palace_ref) + palace._VALIDATED_IDENTITY.clear() + def test_status_qdrant_backend_has_no_hnsw_fields(self, monkeypatch, config, palace_path, kg): from mempalace.backends import GetResult @@ -5052,17 +5295,27 @@ def test_status_tool_does_not_acquire_peer_writer_lock(monkeypatch): assert mcp_server.tool_status()["total_drawers"] == 0 -def test_peer_writer_lock_setup_failure_is_cached(monkeypatch): +def test_peer_writer_lock_setup_failure_retries_and_recovers(monkeypatch): from mempalace import mcp_server, palace + class _DummyLock: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + calls = {"count": 0} - def broken_mine_palace_lock(palace_path): + def flaky_mine_palace_lock(palace_path): calls["count"] += 1 - raise RuntimeError(f"permission denied for {palace_path}") + if calls["count"] == 1: + raise RuntimeError(f"permission denied for {palace_path}") + return _DummyLock() monkeypatch.delenv(mcp_server._MCP_ALLOW_PEER_WRITER_ENV, raising=False) - monkeypatch.setattr(palace, "mine_palace_lock", broken_mine_palace_lock) + monkeypatch.setattr(palace, "mine_palace_lock", flaky_mine_palace_lock) + monkeypatch.setattr(mcp_server, "_discard_mcp_storage_handles", lambda: None) monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_CM", None) monkeypatch.setattr(mcp_server, "_MCP_WRITER_READ_ONLY", False) @@ -5072,12 +5325,63 @@ def test_peer_writer_lock_setup_failure_is_cached(monkeypatch): ok_first, reason_first = mcp_server._acquire_mcp_writer_lock() ok_second, reason_second = mcp_server._acquire_mcp_writer_lock() - assert ok_first is True + assert ok_first is False + assert "later mutating request will retry ownership" in reason_first assert ok_second is True + assert reason_second == "" + assert calls["count"] == 2 + assert mcp_server._MCP_WRITER_LOCK_FAILED is False + assert mcp_server._MCP_WRITER_LOCK_CM is not None + mcp_server._release_mcp_writer_lock() + + +def test_peer_writer_override_cannot_bypass_local_backend_lock(monkeypatch): + from mempalace import mcp_server, palace + + class _DummyLock: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + calls = {"count": 0} + + def tracked_lock(palace_path): + calls["count"] += 1 + return _DummyLock() + + monkeypatch.setenv(mcp_server._MCP_ALLOW_PEER_WRITER_ENV, "1") + monkeypatch.setattr(palace, "resolve_backend_name", lambda path: "sqlite_exact") + monkeypatch.setattr(palace, "mine_palace_lock", tracked_lock) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_CM", None) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_READ_ONLY", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_FAILED", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_ERROR", "") + + ok, reason = mcp_server._acquire_mcp_writer_lock() + + assert ok is True + assert reason == "" assert calls["count"] == 1 - assert mcp_server._MCP_WRITER_LOCK_FAILED is True - assert "continuing without peer-writer protection" in reason_first - assert reason_second == reason_first + + +def test_peer_writer_override_remains_available_for_remote_backend(monkeypatch): + from mempalace import mcp_server, palace + + monkeypatch.setenv(mcp_server._MCP_ALLOW_PEER_WRITER_ENV, "1") + monkeypatch.setattr(palace, "resolve_backend_name", lambda path: "qdrant") + monkeypatch.setattr( + palace, + "mine_palace_lock", + lambda path: pytest.fail("remote backend should not take the local writer lease"), + ) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_CM", None) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_READ_ONLY", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_FAILED", False) + monkeypatch.setattr(mcp_server, "_MCP_WRITER_LOCK_ERROR", "") + + assert mcp_server._acquire_mcp_writer_lock() == (True, "") def test_peer_writer_readonly_self_heals_after_peer_exits(monkeypatch): diff --git a/tests/test_palace.py b/tests/test_palace.py index 426924a..0580fe8 100644 --- a/tests/test_palace.py +++ b/tests/test_palace.py @@ -5,7 +5,36 @@ import chromadb from _chroma_palace_helper import make_minimal_chroma_sqlite from mempalace.backends import CollectionNotInitializedError, PalaceNotFoundError -from mempalace.palace import _open_collection_or_explain, get_collection +from mempalace.palace import ( + _open_collection_or_explain, + backend_requires_single_writer, + get_collection, +) + + +def test_backend_writer_ownership_distinguishes_milvus_lite_from_server(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path)) + + monkeypatch.delenv("MEMPALACE_MILVUS_URI", raising=False) + assert backend_requires_single_writer("milvus") is True + + monkeypatch.setenv("MEMPALACE_MILVUS_URI", str(tmp_path / "milvus.db")) + assert backend_requires_single_writer("milvus") is True + + for uri in ( + "https://zilliz.example", + "http://milvus.example:19530", + "tcp://milvus.example:19530", + "grpc://milvus.example:19530", + ): + monkeypatch.setenv("MEMPALACE_MILVUS_URI", uri) + assert backend_requires_single_writer("milvus") is False + + +def test_backend_writer_ownership_remains_conservative_for_unknown_backend(): + assert backend_requires_single_writer("plugin_backend") is True + assert backend_requires_single_writer("qdrant") is False + assert backend_requires_single_writer("pgvector") is False def _capture(): diff --git a/tests/test_sqlite_exact_backend.py b/tests/test_sqlite_exact_backend.py index f6836d4..1acf12d 100644 --- a/tests/test_sqlite_exact_backend.py +++ b/tests/test_sqlite_exact_backend.py @@ -1,5 +1,8 @@ import math +import os import sqlite3 +import subprocess +import sys import threading import pytest @@ -391,6 +394,326 @@ def test_sqlite_exact_close_palace_marks_existing_collections_closed(tmp_path): col.count() +def test_sqlite_exact_read_only_open_skips_schema_init_and_refuses_writes(tmp_path): + backend, col = _collection(tmp_path) + palace = PalaceRef(id=str(tmp_path), local_path=str(tmp_path)) + col.add(ids=["a"], documents=["doc"], metadatas=[{}], embeddings=[[1, 0]]) + backend.close_palace(palace) + + db_path = tmp_path / "sqlite_exact.sqlite3" + before = db_path.read_bytes() + assert not (tmp_path / "sqlite_exact.sqlite3-wal").exists() + assert not (tmp_path / "sqlite_exact.sqlite3-shm").exists() + db_path.chmod(0o400) + tmp_path.chmod(0o500) + try: + read_only = backend.get_collection( + palace=palace, + collection_name="mempalace_drawers", + create=False, + options={"read_only": True}, + ) + + assert read_only.count() == 1 + assert read_only._handle.read_only is True + assert read_only._handle.conn.execute("PRAGMA query_only").fetchone()[0] == 1 + with pytest.raises(sqlite3.OperationalError): + read_only.add( + ids=["b"], + documents=["blocked"], + metadatas=[{}], + embeddings=[[1, 0]], + ) + assert not (tmp_path / "sqlite_exact.sqlite3-wal").exists() + assert not (tmp_path / "sqlite_exact.sqlite3-shm").exists() + finally: + tmp_path.chmod(0o700) + db_path.chmod(0o600) + backend.close_palace(palace) + assert db_path.read_bytes() == before + + +def test_sqlite_exact_read_only_open_sees_active_writer_wal(tmp_path): + writer_backend, writer = _collection(tmp_path) + palace = PalaceRef(id=str(tmp_path), local_path=str(tmp_path)) + writer.add(ids=["wal-row"], documents=["uncheckpointed"], metadatas=[{}], embeddings=[[1, 0]]) + + db_path = tmp_path / "sqlite_exact.sqlite3" + wal_path = tmp_path / "sqlite_exact.sqlite3-wal" + shm_path = tmp_path / "sqlite_exact.sqlite3-shm" + assert wal_path.is_file() + assert shm_path.is_file() + before = {path: path.read_bytes() for path in (db_path, wal_path, shm_path)} + for path in before: + path.chmod(0o400) + tmp_path.chmod(0o500) + try: + reader_code = """ +import sys +from mempalace.backends import PalaceRef +from mempalace.backends.sqlite_exact import SQLiteExactBackend + +backend = SQLiteExactBackend() +palace = PalaceRef(id=sys.argv[1], local_path=sys.argv[1]) +reader = backend.get_collection( + palace=palace, + collection_name="mempalace_drawers", + create=False, + options={"read_only": True}, +) +print(reader.get(ids=["wal-row"]).documents[0]) +backend.close_palace(palace) +""" + result = subprocess.run( + [sys.executable, "-c", reader_code, str(tmp_path)], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "uncheckpointed" + assert {path: path.read_bytes() for path in before} == before + finally: + tmp_path.chmod(0o700) + for path in before: + path.chmod(0o600) + writer_backend.close_palace(palace) + + +def test_sqlite_exact_read_only_reopens_when_wal_appears_after_immutable_open(tmp_path): + """An immutable clean-database reader must reopen once a writer starts. + + If a read-only MCP opens a cleanly closed palace before any writer is + alive, the connection uses immutable=1. A later daemon/HTTP writer creates + WAL sidecars; the cached immutable handle must not keep serving the + pre-writer snapshot forever. + """ + writer_backend, writer = _collection(tmp_path) + palace = PalaceRef(id=str(tmp_path), local_path=str(tmp_path)) + writer.add( + ids=["seed"], + documents=["seed drawer"], + metadatas=[{}], + embeddings=[[1, 0]], + ) + # Force a full checkpoint so the on-disk database is clean (no WAL) when + # the first read-only open happens. + with writer._handle.lock: + writer._handle.conn.execute("PRAGMA wal_checkpoint(TRUNCATE)") + writer._handle.conn.commit() + writer_backend.close_palace(palace) + + db_path = tmp_path / "sqlite_exact.sqlite3" + wal_path = tmp_path / "sqlite_exact.sqlite3-wal" + shm_path = tmp_path / "sqlite_exact.sqlite3-shm" + assert db_path.is_file() + assert not wal_path.exists() + assert not shm_path.exists() + + reader_backend = SQLiteExactBackend() + first = reader_backend.get_collection( + palace=palace, + collection_name="mempalace_drawers", + create=False, + options={"read_only": True}, + ) + assert first.count() == 1 + first_handle = first._handle + assert first_handle.immutable is True + assert first_handle.read_only is True + + # A peer writer starts after the immutable reader cached its connection. + later_writer_backend, later_writer = _collection(tmp_path) + later_writer.add( + ids=["post-writer"], + documents=["written after immutable open"], + metadatas=[{}], + embeddings=[[0, 1]], + ) + assert wal_path.is_file() + assert shm_path.is_file() + + # Same backend instance: cache hit must detect WAL and reopen mode=ro. + second = reader_backend.get_collection( + palace=palace, + collection_name="mempalace_drawers", + create=False, + options={"read_only": True}, + ) + assert first_handle.closed is True + assert second._handle is not first_handle + assert second._handle.immutable is False + assert second.count() == 2 + got = second.get(ids=["post-writer"]) + assert got.documents[0] == "written after immutable open" + + later_writer_backend.close_palace(palace) + reader_backend.close_palace(palace) + + +def test_sqlite_exact_direct_write_contends_with_palace_owner(tmp_path, monkeypatch): + from mempalace.palace import MineAlreadyRunning + + monkeypatch.setenv("HOME", str(tmp_path / "home")) + backend, col = _collection(tmp_path) + holder_code = """ +import sys +from mempalace.palace import mine_palace_lock +with mine_palace_lock(sys.argv[1]): + print("ready", flush=True) + sys.stdin.read() +""" + holder = subprocess.Popen( + [sys.executable, "-c", holder_code, str(tmp_path)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=os.environ.copy(), + ) + try: + assert holder.stdout is not None + assert holder.stdout.readline().strip() == "ready" + with pytest.raises(MineAlreadyRunning): + col.add(ids=["blocked"], documents=["doc"], metadatas=[{}], embeddings=[[1, 0]]) + finally: + if holder.stdin is not None: + holder.stdin.close() + holder.wait(timeout=10) + backend.close() + + +@pytest.mark.parametrize("operation", ["add", "vacuum"]) +def test_sqlite_exact_waiting_thread_reacquires_palace_lease(tmp_path, monkeypatch, operation): + """A thread queued on the handle must not inherit stale re-entrant credit. + + Thread A owns both the handle and palace locks. Thread B reaches the handle + while A still owns the palace, then pauses immediately after the handle is + released. An external process acquires the palace before B continues. B + must contend again and refuse both ordinary writes and VACUUM. + """ + from mempalace.palace import MineAlreadyRunning + + monkeypatch.setenv("HOME", str(tmp_path / "home")) + backend, col = _collection(tmp_path) + col.add(ids=["seed"], documents=["seed"], metadatas=[{}], embeddings=[[1, 0]]) + + release_a = threading.Event() + a_ready = threading.Event() + b_handle_attempted = threading.Event() + b_has_handle = threading.Event() + allow_b = threading.Event() + writer_ref = {"thread": None} + + class CoordinatedRLock: + def __init__(self): + self._lock = threading.RLock() + self._writer_coordinated = False + + def __enter__(self): + is_writer = threading.current_thread() is writer_ref["thread"] + if is_writer and not self._writer_coordinated: + self._writer_coordinated = True + b_handle_attempted.set() + self._lock.acquire() + if is_writer and self._writer_coordinated and not b_has_handle.is_set(): + b_has_handle.set() + if not allow_b.wait(10): + self._lock.release() + raise AssertionError("timed out waiting to resume writer B") + return self + + def __exit__(self, *exc): + self._lock.release() + return False + + col._handle.lock = CoordinatedRLock() + errors = {} + + def owner_a(): + try: + with col._cursor(write=True): + a_ready.set() + if not release_a.wait(10): + raise AssertionError("timed out waiting to release writer A") + except BaseException as exc: # pragma: no cover - diagnostic path + errors["a"] = exc + + if operation == "vacuum": + monkeypatch.setattr( + col, + "maintenance_state", + lambda: {"row_count": 1, "page_count": 1, "freelist_pages": 0}, + ) + + def writer_b(): + try: + if operation == "add": + col.add( + ids=["writer-b"], + documents=["must not be written"], + metadatas=[{}], + embeddings=[[0, 1]], + ) + else: + col.run_maintenance("compact") + except BaseException as exc: + errors["b"] = exc + + thread_a = threading.Thread(target=owner_a, name="sqlite-owner-a", daemon=True) + thread_b = threading.Thread(target=writer_b, name="sqlite-writer-b", daemon=True) + writer_ref["thread"] = thread_b + holder = None + try: + thread_a.start() + assert a_ready.wait(10), "writer A did not acquire both locks" + + thread_b.start() + assert b_handle_attempted.wait(10), "writer B did not reach the handle lock" + + release_a.set() + assert b_has_handle.wait(10), "writer B did not acquire the released handle" + thread_a.join(timeout=10) + assert not thread_a.is_alive(), "writer A did not release the palace lease" + assert "a" not in errors + + holder_code = """ +import sys +from mempalace.palace import mine_palace_lock +with mine_palace_lock(sys.argv[1]): + print("ready", flush=True) + sys.stdin.read() +""" + holder = subprocess.Popen( + [sys.executable, "-c", holder_code, str(tmp_path)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=os.environ.copy(), + ) + assert holder.stdout is not None + assert holder.stdout.readline().strip() == "ready" + + allow_b.set() + thread_b.join(timeout=10) + assert not thread_b.is_alive(), "writer B did not finish contention" + assert isinstance(errors.get("b"), MineAlreadyRunning) + + if operation == "add": + assert col.get(ids=["writer-b"]).ids == [] + finally: + release_a.set() + allow_b.set() + thread_a.join(timeout=10) + thread_b.join(timeout=10) + if holder is not None: + if holder.stdin is not None: + holder.stdin.close() + holder.wait(timeout=10) + backend.close() + + def test_palace_wrapper_embeds_for_sqlite_exact(tmp_path, monkeypatch): import mempalace.backends.embedding_wrapper as embedding_wrapper from mempalace.palace import get_collection