From a0129f5cffdd8041fa910e503212cb03343f24ac Mon Sep 17 00:00:00 2001 From: Arnold Wender Date: Sat, 9 May 2026 17:18:28 +0200 Subject: [PATCH 01/64] fix(hooks): correct wing extraction for hyphenated project names (#1410) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_wing_from_transcript_path` derived the wing from the LAST dash-separated token of Claude Code's encoded project folder. Because Claude Code encodes the source directory by replacing `/` with `-`, any project whose folder name itself contained a dash got silently truncated: -Users-me-claude-code -> wing_code (lost "claude") -Users-me-react-native -> wing_native (lost "react") -Users-me-customer-portal -> wing_portal (collision risk) -Users-me-admin-portal -> wing_portal (same wing!) Two real consequences: 1. Project-scoped queries (`wake-up --wing `) miss diary entries because they're filed under the truncated wing. 2. Multi-project collision: any two projects whose folders end in the same final token get their diary entries merged into one wing, defeating the wing isolation model. Fix uses a two-tier strategy: 1. PRIMARY — read `cwd` from the JSONL transcript. Claude Code records the absolute working directory on most message types, so the project name is whatever the leaf path segment of cwd is. This is the canonical answer when present and never truncates hyphenated names. Bounded scan (200 lines) keeps the lookup well within the hook's 500ms budget. 2. FALLBACK — when cwd isn't recorded (older Claude Code, queue-only transcripts, etc.), decode the encoded folder. Strip the platform user-home prefix (`Users--` / `home--`) and one common parent-dir token (`git-`, `dev-`, `projects-`, `Projects-`, `src-`, `code-`, `work-`, `Documents-`), then convert remaining dashes to underscores. May include extra parent-dir noise in the wing name (`wing_dev_mempalace_mempalace`) but never silently truncates. Two existing tests asserted the old truncation behavior (it gave the right answer by coincidence on single-token leaf project names). They're updated to reflect the new contract: collision-safe wing extraction even when cwd is absent. Tests added: - hyphenated_claude_code, hyphenated_react_native (regression) - no_collision_between_hyphenated_siblings (`customer-portal` vs `admin-portal` resolve to distinct wings) - strips_parent_dir_with_hyphenated_project (reporter's example) - uses_cwd_from_jsonl, cwd_with_hyphenated_project, cwd_skips_lines_without_cwd, cwd_falls_back_when_no_cwd_in_jsonl, cwd_handles_malformed_jsonl, cwd_handles_missing_file, cwd_handles_non_string_cwd (cwd-primary path coverage) Closes #1410. --- mempalace/hooks_cli.py | 120 +++++++++++++++++++++++++---- tests/test_hooks_cli.py | 166 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 262 insertions(+), 24 deletions(-) diff --git a/mempalace/hooks_cli.py b/mempalace/hooks_cli.py index b8d07e0..be419f7 100644 --- a/mempalace/hooks_cli.py +++ b/mempalace/hooks_cli.py @@ -670,36 +670,124 @@ def _parse_harness_input(data: dict, harness: str) -> dict: } +# Common parent-dir tokens stripped from the encoded folder when no +# explicit ``-Projects-`` segment is present. Order matters: only the +# first match strips. These cover the bulk of Unix layouts; cwd-from-JSONL +# (the primary path) handles the long tail correctly without heuristics. +_ENCODED_PARENT_PREFIXES = ( + "git-", + "dev-", + "projects-", + "Projects-", + "src-", + "code-", + "work-", + "Documents-", +) + + +def _wing_from_jsonl_cwd(transcript_path: str) -> Optional[str]: + """Read ``cwd`` from the first JSONL line that records it. + + Claude Code stores the absolute working directory on most message + types (tool_use, tool_result, user/assistant turns), but not all + (e.g. queue-operation lines lack it). Scan up to 200 lines to find + the first record that includes a non-empty cwd, then derive the + wing from its leaf path segment. Returns ``None`` if the file is + unreadable, empty, or contains no cwd. + """ + try: + path = Path(transcript_path).expanduser() + if not path.is_file(): + return None + with path.open("r", encoding="utf-8", errors="replace") as f: + for i, line in enumerate(f): + if i >= 200: + break + line = line.strip() + if not line or '"cwd"' not in line: + continue + try: + data = json.loads(line) + except (json.JSONDecodeError, ValueError): + continue + cwd = data.get("cwd") + if not cwd or not isinstance(cwd, str): + continue + cwd_norm = cwd.replace("\\", "/").rstrip("/") + if not cwd_norm: + continue + project = cwd_norm.rsplit("/", 1)[-1] + if project: + slug = project.lower().replace(" ", "_").replace("-", "_") + return f"wing_{slug}" + except OSError: + pass + return None + + def _wing_from_transcript_path(transcript_path: str) -> str: """Derive a project wing name from a Claude Code transcript path. - Claude Code encodes the project's source directory by replacing path - separators with dashes, producing folders like: - ~/.claude/projects/-home--Projects-/session.jsonl - ~/.claude/projects/-home--dev--/session.jsonl - ~/.claude/projects/-Users---/session.jsonl + Strategy (in priority order): - The project directory name is the final dash-separated token of the - encoded folder. Returns ``wing_`` (lowercased, spaces → ``_``). - Falls back to ``wing_sessions`` if the path does not match a Claude Code - project-folder layout. + 1. PRIMARY — Read ``cwd`` from the JSONL transcript. Claude Code records + the absolute working directory on most message types, so the project + name is whatever the leaf path segment of cwd is. This is the + canonical answer when present. + + 2. FALLBACK — Decode the encoded folder under ``.claude/projects/``. + Claude Code flattens path separators to dashes (``/Users/me/code/foo`` + → ``-Users-me-code-foo``), so the original directory boundaries are + lost. We strip the platform user-home prefix (``Users--`` or + ``home--``) and one common parent-dir token (``git-``, ``dev-``, + ``projects-``, etc.), then convert the remaining dashes to + underscores. Unlike the previous "last token only" heuristic, this + never silently truncates a hyphenated project folder name like + ``claude-code``, ``react-native``, or ``customer-portal``. + + 3. LEGACY — Match an explicit ``-Projects-`` segment for + transcripts not under the standard Claude Code projects dir. + + 4. DEFAULT — ``wing_sessions``. + + Closes #1410. """ + # 1. Primary — cwd from JSONL is the canonical source of truth + cwd_wing = _wing_from_jsonl_cwd(transcript_path) + if cwd_wing: + return cwd_wing + # Normalize path separators for cross-platform (Windows backslashes) normalized = transcript_path.replace("\\", "/") - # Primary: pull the encoded project folder out of ``.claude/projects/`` - # and take its last dash-separated token. + + # 2. Fallback — encoded project folder under .claude/projects/ match = re.search(r"/\.claude/projects/-([^/]+)", normalized) if match: encoded = match.group(1) - project = encoded.rsplit("-", 1)[-1] + # Strip platform user-home prefix so the wing isn't dominated by + # /Users// or /home//. + m = re.match(r"(?:Users|home)-[^-]+-(.+)", encoded) + if m: + encoded = m.group(1) + # Strip one common parent-dir token if present, keeping the rest as + # the project path. Hyphens become underscores to preserve + # uniqueness for hyphenated project folder names. + for prefix in _ENCODED_PARENT_PREFIXES: + if encoded.startswith(prefix): + encoded = encoded[len(prefix) :] + break + project = encoded.lower().replace(" ", "_").replace("-", "_") if project: - return f"wing_{project.lower().replace(' ', '_')}" - # Legacy fallback: explicit ``-Projects-`` segment, useful for - # transcripts not under the standard Claude Code projects dir. + return f"wing_{project}" + + # 3. Legacy — explicit -Projects- segment match = re.search(r"-Projects-([^/]+?)(?:/|$)", normalized) if match: - project = match.group(1).lower().replace(" ", "_") + project = match.group(1).lower().replace(" ", "_").replace("-", "_") return f"wing_{project}" + + # 4. Default return "wing_sessions" diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 0918255..234bef2 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -328,21 +328,171 @@ def test_wing_from_transcript_path_lowercases(): def test_wing_from_transcript_path_non_projects_layout(): - # Linux users with code under ~/dev/, ~/src/, ~/code/ — no -Projects- segment. - # Project name is the final dash-separated token of the encoded folder. + # Linux user with code under ~/dev/. The encoded form ``dev-MemPalace-mempalace`` + # is ambiguous between ``~/dev/MemPalace/mempalace/`` (project = mempalace) and + # ``~/dev/MemPalace-mempalace/`` (hyphenated single-name project). With no JSONL + # cwd to disambiguate, we preserve all post-``dev-`` segments rather than silently + # truncating to the last token (which would drop ``MemPalace`` here and collide + # with any other ``-mempalace`` leaf elsewhere on the system). path = "/home/igor/.claude/projects/-home-igor-dev-MemPalace-mempalace/session.jsonl" - assert _wing_from_transcript_path(path) == "wing_mempalace" + assert _wing_from_transcript_path(path) == "wing_mempalace_mempalace" def test_wing_from_transcript_path_macos_users_layout(): - # macOS ~/ layout without a Projects/ segment. + # macOS ~/ layout without a Projects/ segment — single-token project name + # so the heuristic produces the same result as the leaf-only approach. path = "/Users/alice/.claude/projects/-Users-alice-code-MyApp/session.jsonl" assert _wing_from_transcript_path(path) == "wing_myapp" def test_wing_from_transcript_path_nested_deep(): + # Deep tree: ``-home-bob-work-clients-acme-frontend``. Without JSONL cwd we + # can't tell whether ``frontend`` is the project, ``acme-frontend`` is a + # hyphenated project, or the project lives several levels in. Strip the + # user-home and one common parent (``work-``), then keep the remaining + # path as the wing — collision-safe even if multiple clients have a + # ``frontend/`` subdir. path = "/home/bob/.claude/projects/-home-bob-work-clients-acme-frontend/session.jsonl" - assert _wing_from_transcript_path(path) == "wing_frontend" + assert _wing_from_transcript_path(path) == "wing_clients_acme_frontend" + + +# --- _wing_from_transcript_path: hyphenated project names (issue #1410) --- + + +def test_wing_from_transcript_path_hyphenated_claude_code(): + """Regression: ``claude-code`` was truncated to ``wing_code`` (#1410).""" + path = "/Users/me/.claude/projects/-Users-me-claude-code/abc.jsonl" + assert _wing_from_transcript_path(path) == "wing_claude_code" + + +def test_wing_from_transcript_path_hyphenated_react_native(): + """Regression: ``react-native`` was truncated to ``wing_native`` (#1410).""" + path = "/Users/me/.claude/projects/-Users-me-react-native/abc.jsonl" + assert _wing_from_transcript_path(path) == "wing_react_native" + + +def test_wing_from_transcript_path_no_collision_between_hyphenated_siblings(): + """Regression: ``customer-portal`` and ``admin-portal`` both truncated to + ``wing_portal`` under the old heuristic, merging diary entries from two + independent projects into one wing (#1410).""" + customer = _wing_from_transcript_path( + "/Users/me/.claude/projects/-Users-me-customer-portal/abc.jsonl" + ) + admin = _wing_from_transcript_path( + "/Users/me/.claude/projects/-Users-me-admin-portal/abc.jsonl" + ) + assert customer == "wing_customer_portal" + assert admin == "wing_admin_portal" + assert customer != admin + + +def test_wing_from_transcript_path_strips_parent_dir_with_hyphenated_project(): + """Reporter's example: ``-home-alice-projects-react-native`` should keep + the full project name after stripping the ``projects-`` parent (#1410).""" + path = "/home/alice/.claude/projects/-home-alice-projects-react-native/abc.jsonl" + assert _wing_from_transcript_path(path) == "wing_react_native" + + +# --- _wing_from_transcript_path: cwd-from-JSONL primary path --- + + +def test_wing_from_transcript_path_uses_cwd_from_jsonl(tmp_path): + """When the JSONL records ``cwd``, the leaf segment of cwd is the wing — + even if the encoded folder name would have produced a different (and + noisier) wing.""" + # Encoded folder says ``-home-igor-dev-MemPalace-mempalace`` (would yield + # ``wing_mempalace_mempalace`` via fallback), but cwd is the truth. + project_dir = tmp_path / "-home-igor-dev-MemPalace-mempalace" + project_dir.mkdir() + transcript = project_dir / "session.jsonl" + transcript.write_text( + '{"type":"queue-operation","operation":"enqueue","timestamp":"2026-05-09T00:00:00Z"}\n' + '{"type":"user","cwd":"/home/igor/dev/MemPalace/mempalace","content":"hi"}\n', + encoding="utf-8", + ) + assert _wing_from_transcript_path(str(transcript)) == "wing_mempalace" + + +def test_wing_from_transcript_path_cwd_with_hyphenated_project(tmp_path): + """cwd primary path correctly handles hyphenated project names without + truncation.""" + project_dir = tmp_path / "-Users-me-claude-code" + project_dir.mkdir() + transcript = project_dir / "session.jsonl" + transcript.write_text( + '{"type":"user","cwd":"/Users/me/git/claude-code","content":"hi"}\n', + encoding="utf-8", + ) + assert _wing_from_transcript_path(str(transcript)) == "wing_claude_code" + + +def test_wing_from_transcript_path_cwd_skips_lines_without_cwd(tmp_path): + """Lines that lack ``cwd`` (queue-operation, etc.) are skipped; the first + line that records cwd wins.""" + project_dir = tmp_path / "-Users-me-foo" + project_dir.mkdir() + transcript = project_dir / "session.jsonl" + lines = [ + '{"type":"queue-operation","operation":"enqueue"}', + '{"type":"queue-operation","operation":"dequeue"}', + '{"type":"queue-operation","operation":"complete"}', + '{"type":"tool_use","cwd":"/Users/me/work/real-project","content":"ok"}', + '{"type":"user","cwd":"/Users/me/somewhere-else","content":"later"}', + ] + transcript.write_text("\n".join(lines) + "\n", encoding="utf-8") + # First cwd record wins (line 4, real-project). + assert _wing_from_transcript_path(str(transcript)) == "wing_real_project" + + +def test_wing_from_transcript_path_cwd_falls_back_when_no_cwd_in_jsonl(tmp_path): + """If no JSONL line has cwd, fall through to the encoded-folder heuristic.""" + project_dir = tmp_path / "-Users-me-no-cwd-project" + project_dir.mkdir() + transcript = project_dir / "session.jsonl" + transcript.write_text( + '{"type":"queue-operation","operation":"enqueue"}\n' + '{"type":"queue-operation","operation":"complete"}\n', + encoding="utf-8", + ) + # tmp_path leaks into the path before .claude/projects, so the regex + # won't match and we hit the wing_sessions default. The point of this + # test: the cwd reader doesn't crash and returns None cleanly. + result = _wing_from_transcript_path(str(transcript)) + assert result == "wing_sessions" + + +def test_wing_from_transcript_path_cwd_handles_malformed_jsonl(tmp_path): + """Malformed JSON lines must not crash the wing extraction.""" + project_dir = tmp_path / "-Users-me-broken-project" + project_dir.mkdir() + transcript = project_dir / "session.jsonl" + transcript.write_text( + "this is not json at all\n" + '{"type":"broken",\n' # truncated mid-record + '{"type":"valid","cwd":"/Users/me/git/clean-name","content":"ok"}\n', + encoding="utf-8", + ) + assert _wing_from_transcript_path(str(transcript)) == "wing_clean_name" + + +def test_wing_from_transcript_path_cwd_handles_missing_file(): + """Nonexistent transcript path falls back cleanly to the encoded heuristic.""" + path = "/Users/me/.claude/projects/-Users-me-claude-code/does-not-exist.jsonl" + assert _wing_from_transcript_path(path) == "wing_claude_code" + + +def test_wing_from_transcript_path_cwd_handles_non_string_cwd(tmp_path): + """A cwd field that isn't a string (e.g. null, number) must be skipped.""" + project_dir = tmp_path / "-Users-me-fallback-name" + project_dir.mkdir() + transcript = project_dir / "session.jsonl" + transcript.write_text( + '{"type":"x","cwd":null}\n' + '{"type":"x","cwd":42}\n' + '{"type":"x","cwd":"/Users/me/git/proper-name"}\n', + encoding="utf-8", + ) + assert _wing_from_transcript_path(str(transcript)) == "wing_proper_name" # --- _log --- @@ -700,9 +850,9 @@ def test_spawn_mine_releases_slot_on_oserror(tmp_path): with patch("mempalace.hooks_cli.subprocess.Popen", side_effect=OSError("spawn fail")): with pytest.raises(OSError): _spawn_mine(cmd) - assert ( - not pid_file.exists() - ), "slot must be released so the next hook fire isn't permanently blocked" + assert not pid_file.exists(), ( + "slot must be released so the next hook fire isn't permanently blocked" + ) def test_spawn_mine_passes_pid_file_env_var(tmp_path): From 601da04817ad66480eceaeffa6f7ce0b0afa5815 Mon Sep 17 00:00:00 2001 From: Arnold Wender Date: Sat, 9 May 2026 17:19:53 +0200 Subject: [PATCH 02/64] ci(test_hooks_cli): re-apply ruff 0.4.x format (CI pins ruff<0.5) --- tests/test_hooks_cli.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 234bef2..e9bd7d7 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -850,9 +850,9 @@ def test_spawn_mine_releases_slot_on_oserror(tmp_path): with patch("mempalace.hooks_cli.subprocess.Popen", side_effect=OSError("spawn fail")): with pytest.raises(OSError): _spawn_mine(cmd) - assert not pid_file.exists(), ( - "slot must be released so the next hook fire isn't permanently blocked" - ) + assert ( + not pid_file.exists() + ), "slot must be released so the next hook fire isn't permanently blocked" def test_spawn_mine_passes_pid_file_env_var(tmp_path): From e6f73983fbaa5f55edb830598a9ff80560d841c8 Mon Sep 17 00:00:00 2001 From: Arnold Wender Date: Thu, 7 May 2026 21:38:18 +0200 Subject: [PATCH 03/64] fix(entity_registry): clean up .tmp sidecar on write or rename failure (#1373) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1215 made `EntityRegistry.save()` atomic via temp-file + fsync + os.replace. Crash-mid-write durability is correct: the previous registry stays intact on any failure. But if `f.write()` / `f.flush()` / `os.fsync()` / `os.replace()` raise (disk full, perms flip, broken FUSE mount, IO error), the `.tmp` sidecar was left on disk. Subsequent saves overwrite the same path so it does not grow unboundedly, but it litters the palace directory and obscures diagnostics — a user inspecting `entity_registry.json.tmp` after a crash cannot distinguish in-flight writes from stale debris. Wrap the write+chmod+replace block in try/except. On any exception, attempt `tmp_path.unlink(missing_ok=True)` before re-raising. The dir-fsync is deliberately outside the try — that is durability for a successful rename, not a write step that needs cleanup. Tests: - Augment `test_save_preserves_previous_on_serialization_failure` to also assert the .tmp sidecar is gone after a forced os.replace failure. - New `test_save_cleans_tmp_on_write_failure` forces os.fsync to raise, covering the gap between write and rename that the existing test does not exercise. Closes #1373. --- mempalace/entity_registry.py | 27 ++++++++++++++------ tests/test_entity_registry.py | 46 +++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/mempalace/entity_registry.py b/mempalace/entity_registry.py index c8ac517..248009f 100644 --- a/mempalace/entity_registry.py +++ b/mempalace/entity_registry.py @@ -327,15 +327,26 @@ class EntityRegistry: # instead of a half-written file or an empty file from the truncate. payload = json.dumps(self._data, indent=2) tmp_path = self._path.with_name(self._path.name + ".tmp") - with open(tmp_path, "w", encoding="utf-8") as f: - f.write(payload) - f.flush() - os.fsync(f.fileno()) try: - tmp_path.chmod(0o600) - except (OSError, NotImplementedError): - pass - os.replace(tmp_path, self._path) + with open(tmp_path, "w", encoding="utf-8") as f: + f.write(payload) + f.flush() + os.fsync(f.fileno()) + try: + tmp_path.chmod(0o600) + except (OSError, NotImplementedError): + pass + os.replace(tmp_path, self._path) + except BaseException: + # Disk full, perms flip, broken FUSE mount, IO error, KeyboardInterrupt + # mid-write — unlink the .tmp sidecar so it does not litter the palace + # directory or confuse diagnostics. The previous registry is intact + # because os.replace is atomic on POSIX/NTFS. + try: + tmp_path.unlink(missing_ok=True) + except OSError: + pass + raise # On ext4 (and similar) the rename's durability across power loss # requires an additional fsync on the parent directory. Without it, # the kernel can ack the rename and a crash reverts to the state diff --git a/tests/test_entity_registry.py b/tests/test_entity_registry.py index a5f237c..d168ca4 100644 --- a/tests/test_entity_registry.py +++ b/tests/test_entity_registry.py @@ -115,6 +115,52 @@ def test_save_preserves_previous_on_serialization_failure(tmp_path, monkeypatch) # Restore os.replace before reading so the assertion can rely on it. monkeypatch.setattr(_os, "replace", real_replace) assert target.read_text(encoding="utf-8") == original + # The .tmp sidecar must also be cleaned up — otherwise it litters the + # palace directory and a future diagnostic cannot distinguish stale + # debris from an in-flight write. + leftover = list(tmp_path.glob("entity_registry.json.tmp*")) + assert leftover == [], f"atomic write leaked tmp on rename failure: {leftover}" + + +def test_save_cleans_tmp_on_write_failure(tmp_path, monkeypatch): + # Failure BEFORE the rename (disk full, FUSE break, IO error during + # write/fsync) must also clean up the .tmp sidecar. The existing + # rename-failure test only covers the post-write path; this exercises + # the gap between write and rename. + registry = EntityRegistry.load(config_dir=tmp_path) + registry.seed( + mode="personal", + people=[{"name": "Alice", "relationship": "friend", "context": "personal"}], + projects=[], + ) + registry.save() + target = tmp_path / "entity_registry.json" + original = target.read_text(encoding="utf-8") + + # Force os.fsync to raise — simulates IO error after the bytes are in + # the kernel page cache but before they hit the platter. + import os as _os + + real_fsync = _os.fsync + + def boom(fd): + raise OSError("simulated fsync failure") + + monkeypatch.setattr(_os, "fsync", boom) + with pytest.raises(OSError): + registry.seed( + mode="personal", + people=[{"name": "Bob", "relationship": "friend", "context": "personal"}], + projects=[], + ) + registry.save() + monkeypatch.setattr(_os, "fsync", real_fsync) + + # Previous registry intact (rename never happened — atomic guarantee). + assert target.read_text(encoding="utf-8") == original + # And the .tmp sidecar is gone, not litter on disk. + leftover = list(tmp_path.glob("entity_registry.json.tmp*")) + assert leftover == [], f"atomic write leaked tmp on fsync failure: {leftover}" # ── seed ──────────────────────────────────────────────────────────────── From cb1303694d9caa52bbc21ffa4e87bd294d9576a9 Mon Sep 17 00:00:00 2001 From: Arnold Wender Date: Sun, 26 Apr 2026 13:06:11 +0200 Subject: [PATCH 04/64] fix(migrate): close SQLite connection and clean temp palace on exception Two resource leaks in mempalace.migrate that bite hardest on Windows: 1. extract_drawers_from_sqlite() opened a sqlite3 connection at the top and only closed it in the happy path. Any exception during query/iteration leaked the handle, leaving a file lock on chroma.sqlite3 that prevented the rest of the migration from touching the palace directory. Wrap with contextlib.closing(). 2. migrate() called tempfile.mkdtemp() and never cleaned it up if a later step (chromadb open, batch import, count, swap) raised. The orphaned palace under the system temp root could be 100s of MB and never gets reclaimed. Wrap the import-and-swap dance in try/finally and rmtree the temp dir if it still exists at the end (os.replace consumes it on the happy path so the existence guard makes that case a no-op). Tests cover the happy-path extraction and verify mkdtemp's directory is removed when ChromaBackend.get_or_create_collection() raises. --- mempalace/migrate.py | 200 +++++++++++++++++++++++------------------- tests/test_migrate.py | 88 ++++++++++++++++++- 2 files changed, 195 insertions(+), 93 deletions(-) diff --git a/mempalace/migrate.py b/mempalace/migrate.py index 5b74591..9e809da 100644 --- a/mempalace/migrate.py +++ b/mempalace/migrate.py @@ -22,8 +22,10 @@ import errno import os import shutil import sqlite3 +import tempfile import uuid from collections import defaultdict +from contextlib import closing from datetime import datetime @@ -52,61 +54,65 @@ def extract_drawers_from_sqlite(db_path: str) -> list: Works regardless of which ChromaDB version created the database. Returns list of dicts with 'id', 'document', and 'metadata' keys. + + The connection is wrapped in ``contextlib.closing`` so an exception + during extraction does not leak the SQLite handle. On Windows that + would leave a file lock on ``chroma.sqlite3`` and prevent the rest + of the migration from touching the palace directory. """ - conn = sqlite3.connect(db_path) - conn.row_factory = sqlite3.Row + with closing(sqlite3.connect(db_path)) as conn: + conn.row_factory = sqlite3.Row - # Get all embedding IDs and their documents - rows = conn.execute( - """ - SELECT e.embedding_id, - MAX(CASE WHEN em.key = 'chroma:document' THEN em.string_value END) as document - FROM embeddings e - JOIN embedding_metadata em ON em.id = e.id - GROUP BY e.embedding_id - """ - ).fetchall() - - drawers = [] - for row in rows: - embedding_id = row["embedding_id"] - document = row["document"] - if not document: - continue - - # Get metadata for this embedding - meta_rows = conn.execute( + # Get all embedding IDs and their documents + rows = conn.execute( """ - SELECT em.key, em.string_value, em.int_value, em.float_value, em.bool_value - FROM embedding_metadata em - JOIN embeddings e ON e.id = em.id - WHERE e.embedding_id = ? - AND em.key NOT LIKE 'chroma:%' - """, - (embedding_id,), + SELECT e.embedding_id, + MAX(CASE WHEN em.key = 'chroma:document' THEN em.string_value END) as document + FROM embeddings e + JOIN embedding_metadata em ON em.id = e.id + GROUP BY e.embedding_id + """ ).fetchall() - metadata = {} - for mr in meta_rows: - key = mr["key"] - if mr["string_value"] is not None: - metadata[key] = mr["string_value"] - elif mr["int_value"] is not None: - metadata[key] = mr["int_value"] - elif mr["float_value"] is not None: - metadata[key] = mr["float_value"] - elif mr["bool_value"] is not None: - metadata[key] = bool(mr["bool_value"]) + drawers = [] + for row in rows: + embedding_id = row["embedding_id"] + document = row["document"] + if not document: + continue - drawers.append( - { - "id": embedding_id, - "document": document, - "metadata": metadata, - } - ) + # Get metadata for this embedding + meta_rows = conn.execute( + """ + SELECT em.key, em.string_value, em.int_value, em.float_value, em.bool_value + FROM embedding_metadata em + JOIN embeddings e ON e.id = em.id + WHERE e.embedding_id = ? + AND em.key NOT LIKE 'chroma:%' + """, + (embedding_id,), + ).fetchall() + + metadata = {} + for mr in meta_rows: + key = mr["key"] + if mr["string_value"] is not None: + metadata[key] = mr["string_value"] + elif mr["int_value"] is not None: + metadata[key] = mr["int_value"] + elif mr["float_value"] is not None: + metadata[key] = mr["float_value"] + elif mr["bool_value"] is not None: + metadata[key] = bool(mr["bool_value"]) + + drawers.append( + { + "id": embedding_id, + "document": document, + "metadata": metadata, + } + ) - conn.close() return drawers @@ -287,53 +293,63 @@ def migrate(palace_path: str, dry_run: bool = False, confirm: bool = False): print(f"\n Backing up to {backup_path}...") shutil.copytree(palace_path, backup_path) - # Build fresh palace in a temp directory (avoids chromadb reading old state) - import tempfile - + # Build fresh palace in a temp directory (avoids chromadb reading old state). + # Wrap the whole import-and-swap dance in try/finally so the temp dir is + # cleaned up if any of the chromadb writes, the verify count, or the + # rename fails — without try/finally a crashed migration leaves a partial + # palace dir under the system temp root that the user has to find by hand. temp_palace = tempfile.mkdtemp(prefix="mempalace_migrate_") - print(f" Creating fresh palace in {temp_palace}...") - fresh_backend = ChromaBackend() - col = fresh_backend.get_or_create_collection(temp_palace, "mempalace_drawers") - - # Re-import in batches - batch_size = 500 - imported = 0 - for i in range(0, len(drawers), batch_size): - batch = drawers[i : i + batch_size] - col.add( - ids=[d["id"] for d in batch], - documents=[d["document"] for d in batch], - metadatas=[d["metadata"] for d in batch], - ) - imported += len(batch) - print(f" Imported {imported}/{len(drawers)} drawers...") - - # Verify before swapping - final_count = col.count() - del col - del fresh_backend - - # Swap: rename old palace aside, then move new one into place. - # This avoids a window where both old and new are missing. - print(" Swapping old palace for migrated version...") - stale_path = palace_path + ".old" - if os.path.exists(stale_path): - shutil.rmtree(stale_path) - os.replace(palace_path, stale_path) try: - os.replace(temp_palace, palace_path) - except OSError as e: - # EXDEV = temp lives on a different filesystem; fall back to copy+delete. - # Anything else is a real error — don't mask it with shutil.move. - if getattr(e, "errno", None) != errno.EXDEV: - _restore_stale_palace(palace_path, stale_path) - raise + print(f" Creating fresh palace in {temp_palace}...") + fresh_backend = ChromaBackend() + col = fresh_backend.get_or_create_collection(temp_palace, "mempalace_drawers") + + # Re-import in batches + batch_size = 500 + imported = 0 + for i in range(0, len(drawers), batch_size): + batch = drawers[i : i + batch_size] + col.add( + ids=[d["id"] for d in batch], + documents=[d["document"] for d in batch], + metadatas=[d["metadata"] for d in batch], + ) + imported += len(batch) + print(f" Imported {imported}/{len(drawers)} drawers...") + + # Verify before swapping + final_count = col.count() + del col + del fresh_backend + + # Swap: rename old palace aside, then move new one into place. + # This avoids a window where both old and new are missing. + print(" Swapping old palace for migrated version...") + stale_path = palace_path + ".old" + if os.path.exists(stale_path): + shutil.rmtree(stale_path) + os.replace(palace_path, stale_path) try: - shutil.move(temp_palace, palace_path) - except Exception: - _restore_stale_palace(palace_path, stale_path) - raise - shutil.rmtree(stale_path, ignore_errors=True) + os.replace(temp_palace, palace_path) + except OSError as e: + # EXDEV = temp lives on a different filesystem; fall back to copy+delete. + # Anything else is a real error — don't mask it with shutil.move. + if getattr(e, "errno", None) != errno.EXDEV: + _restore_stale_palace(palace_path, stale_path) + raise + try: + shutil.move(temp_palace, palace_path) + except Exception: + _restore_stale_palace(palace_path, stale_path) + raise + shutil.rmtree(stale_path, ignore_errors=True) + finally: + # On the happy path os.replace/shutil.move consumed temp_palace, so + # the directory no longer exists at the temp location — the existence + # guard makes this a no-op then. On any failure path it actually + # removes the orphan. + if os.path.exists(temp_palace): + shutil.rmtree(temp_palace, ignore_errors=True) print("\n Migration complete.") print(f" Drawers migrated: {final_count}") diff --git a/tests/test_migrate.py b/tests/test_migrate.py index ba12ff5..5d9255a 100644 --- a/tests/test_migrate.py +++ b/tests/test_migrate.py @@ -1,10 +1,16 @@ """Tests for destructive-operation safety in mempalace.migrate.""" import os +import sqlite3 from types import SimpleNamespace from unittest.mock import MagicMock, patch -from mempalace.migrate import collection_write_roundtrip_works, _restore_stale_palace, migrate +from mempalace.migrate import ( + _restore_stale_palace, + collection_write_roundtrip_works, + extract_drawers_from_sqlite, + migrate, +) def test_migrate_requires_palace_database(tmp_path, capsys): @@ -157,6 +163,38 @@ def test_collection_write_roundtrip_fails_when_delete_silently_drops(): assert len(col.ids) == 1 +def _make_minimal_chromadb_sqlite(tmp_path): + """Build a SQLite file with the minimal schema extract_drawers_from_sqlite reads.""" + db = tmp_path / "chroma.sqlite3" + conn = sqlite3.connect(str(db)) + conn.executescript( + """ + CREATE TABLE embeddings (id INTEGER PRIMARY KEY, embedding_id TEXT); + CREATE TABLE embedding_metadata ( + id INTEGER, key TEXT, + string_value TEXT, int_value INTEGER, + float_value REAL, bool_value INTEGER + ); + INSERT INTO embeddings VALUES (1, 'd-001'); + INSERT INTO embedding_metadata VALUES (1, 'chroma:document', 'hello', NULL, NULL, NULL); + INSERT INTO embedding_metadata VALUES (1, 'wing', 'personal', NULL, NULL, NULL); + INSERT INTO embedding_metadata VALUES (1, 'room', '2026-04-26', NULL, NULL, NULL); + """ + ) + conn.commit() + conn.close() + return str(db) + + +def test_extract_drawers_returns_drawers(tmp_path): + db_path = _make_minimal_chromadb_sqlite(tmp_path) + drawers = extract_drawers_from_sqlite(db_path) + assert len(drawers) == 1 + assert drawers[0]["id"] == "d-001" + assert drawers[0]["document"] == "hello" + assert drawers[0]["metadata"] == {"wing": "personal", "room": "2026-04-26"} + + def test_migrate_dry_run_rebuilds_when_collection_is_readable_but_not_writable(tmp_path, capsys): palace_dir = tmp_path / "palace" palace_dir.mkdir() @@ -200,3 +238,51 @@ def test_migrate_dry_run_rebuilds_when_collection_is_readable_but_not_writable(t assert "Rebuilding from SQLite" in out assert "Extracted 1 drawers from SQLite" in out assert "DRY RUN" in out + + +def test_migrate_cleans_temp_palace_on_chromadb_failure(tmp_path): + """If chromadb fails after the temp palace is created, mkdtemp's + directory must be removed — without try/finally it leaked into the + system temp root forever.""" + import tempfile as _tempfile + + palace_dir = tmp_path / "palace" + palace_dir.mkdir() + (palace_dir / "chroma.sqlite3").write_text("db") + + captured_temp_paths = [] + real_mkdtemp = _tempfile.mkdtemp + + def tracking_mkdtemp(*args, **kwargs): + path = real_mkdtemp(*args, **kwargs) + captured_temp_paths.append(path) + return path + + failing_backend = MagicMock() + # First ChromaBackend().get_collection() must raise so we drop into + # the SQL-extraction path; the second ChromaBackend().get_or_create_collection() + # raises to trigger the cleanup we are testing. + failing_backend.get_collection.side_effect = Exception("unreadable") + failing_backend.get_or_create_collection.side_effect = RuntimeError("chromadb boom") + + import mempalace.backends.chroma as _chroma_mod + + with ( + patch("mempalace.migrate.detect_chromadb_version", return_value="0.5.x"), + patch( + "mempalace.migrate.extract_drawers_from_sqlite", + return_value=[{"id": "id1", "document": "doc", "metadata": {"wing": "w", "room": "r"}}], + ), + patch("builtins.input", return_value="y"), + patch("mempalace.migrate.shutil.copytree"), + patch("mempalace.migrate.tempfile.mkdtemp", side_effect=tracking_mkdtemp), + patch.object(_chroma_mod, "ChromaBackend", return_value=failing_backend), + ): + try: + migrate(str(palace_dir), confirm=True) + except Exception: + pass + + assert captured_temp_paths, "mkdtemp was never called — flow short-circuited" + for p in captured_temp_paths: + assert not os.path.exists(p), f"temp palace was not cleaned up: {p}" From 2c75c6faf6c5c54514837dfd06a199eca79a9d8a Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Sun, 10 May 2026 16:45:09 +0200 Subject: [PATCH 05/64] Fix mine palace lock holder encoding --- mempalace/palace.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/mempalace/palace.py b/mempalace/palace.py index 7ed315c..cf7b10a 100644 --- a/mempalace/palace.py +++ b/mempalace/palace.py @@ -387,7 +387,10 @@ def _read_lock_holder(lock_file) -> str: """Read the prior holder's identity from the lock-file body, best-effort.""" try: lock_file.seek(_LOCK_SENTINEL_BYTES) - content = lock_file.read().strip() + content = lock_file.read() + if isinstance(content, bytes): + content = content.decode("utf-8", errors="replace") + content = content.strip() except OSError: return "another writer (identity not recorded)" if not content: @@ -404,11 +407,12 @@ def _write_lock_holder(lock_file) -> None: """ try: ident = f"{os.getpid()} {' '.join(sys.argv[:3])}".strip() + ident_bytes = ident.encode("utf-8") lock_file.seek(_LOCK_SENTINEL_BYTES) - lock_file.truncate(_LOCK_SENTINEL_BYTES + len(ident.encode("utf-8"))) - lock_file.write(ident) + lock_file.truncate(_LOCK_SENTINEL_BYTES + len(ident_bytes)) + lock_file.write(ident_bytes) lock_file.flush() - except OSError: + except (OSError, UnicodeError): pass @@ -470,7 +474,7 @@ def mine_palace_lock(palace_path: str): os.close(fd) except FileExistsError: pass - lf = open(lock_path, "r+") + lf = open(lock_path, "r+b") acquired = False try: # Lock byte 0 explicitly. msvcrt.locking is byte-position dependent; From c49c10f6e462645f7a7d598ff1ddc4f355bf5a58 Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Sun, 10 May 2026 16:56:10 +0200 Subject: [PATCH 06/64] Add regression tests for UTF-8 lock holder writes --- tests/test_palace_locks.py | 56 ++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 6 deletions(-) diff --git a/tests/test_palace_locks.py b/tests/test_palace_locks.py index bf53a9d..b4d2fbc 100644 --- a/tests/test_palace_locks.py +++ b/tests/test_palace_locks.py @@ -12,10 +12,12 @@ from __future__ import annotations import multiprocessing import os import time +import sys import pytest from mempalace.palace import ( + _write_lock_holder, MineAlreadyRunning, mine_global_lock, mine_palace_lock, @@ -197,9 +199,9 @@ def test_reentrant_same_thread_passes_through(tmp_path, monkeypatch): child = ctx.Process(target=_try_acquire_expect_busy, args=(palace, result_q)) try: child.start() - assert ( - result_q.get(timeout=10) == "busy" - ), "outer lock should still be held by parent after inner re-entrant exit" + assert result_q.get(timeout=10) == "busy", ( + "outer lock should still be held by parent after inner re-entrant exit" + ) child.join(timeout=5) assert child.exitcode == 0 finally: @@ -265,14 +267,56 @@ def test_lock_failure_message_names_holder(tmp_path, monkeypatch): pytest.fail("second acquire of same palace should have raised") msg = str(excinfo.value) - assert ( - f"PID {holder_pid}" in msg - ), f"lock-failure message must name the holder PID; got: {msg!r}" + assert f"PID {holder_pid}" in msg, ( + f"lock-failure message must name the holder PID; got: {msg!r}" + ) finally: open(release, "w").close() holder.join(timeout=5) +def test_write_lock_holder_writes_utf8_bytes_for_non_ascii_argv(tmp_path, monkeypatch): + """Regression #1435: lock-holder identity must be written as UTF-8 bytes. + + The holder byte count and the on-disk bytes must agree even when argv + contains characters that are not representable in a Windows ANSI codepage. + """ + monkeypatch.setattr( + sys, + "argv", + ["mempalace", "mine", "café/北"], + ) + + lock_path = tmp_path / "holder.lock" + lock_path.write_bytes(b"\0stale-holder-identity-that-must-be-truncated") + + with lock_path.open("r+b") as lock_file: + _write_lock_holder(lock_file) + + ident = f"{os.getpid()} {' '.join(sys.argv[:3])}".strip() + assert lock_path.read_bytes() == b"\0" + ident.encode("utf-8") + + +def test_write_lock_holder_is_best_effort_on_unicode_error(monkeypatch): + """Regression #1435: holder-write failures must not block lock acquisition.""" + + class UnicodeFailingLock: + def seek(self, _offset): + pass + + def truncate(self, _size): + pass + + def write(self, _data): + raise UnicodeEncodeError("cp1252", "北", 0, 1, "not representable") + + def flush(self): + pass + + monkeypatch.setattr(sys, "argv", ["mempalace", "mine", "北"]) + _write_lock_holder(UnicodeFailingLock()) + + def test_lock_holder_identity_persists_across_release(tmp_path, monkeypatch): """The holder line is overwritten by each new acquirer, not appended. From fd637036864082c8c2f30e7c82e68701982b612b Mon Sep 17 00:00:00 2001 From: jp Date: Sat, 18 Apr 2026 20:32:18 -0700 Subject: [PATCH 07/64] feat: configurable chunk_size, chunk_overlap, min_chunk_size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chunk sizing was hardcoded via module-level constants (CHUNK_SIZE=800, CHUNK_OVERLAP=100, MIN_CHUNK_SIZE=50). One size does not fit all — source material varies (dense code vs prose transcripts vs sparse logs) and so do users' context-window budgets. This makes all three values overridable via ~/.mempalace/config.json: { "chunk_size": 1200, "chunk_overlap": 150, "min_chunk_size": 40 } Values are exposed as MempalaceConfig properties, threaded through mine() -> process_file() -> chunk_text() as optional keyword arguments. Defaults (800/100/50) are preserved when the config keys are absent, so existing palaces behave identically. Co-Authored-By: Claude Sonnet 4.6 --- mempalace/config.py | 15 +++++++++++++ mempalace/miner.py | 52 +++++++++++++++++++++++++++++++++++++-------- tests/test_miner.py | 4 ++-- 3 files changed, 60 insertions(+), 11 deletions(-) diff --git a/mempalace/config.py b/mempalace/config.py index ab478ec..b2be3ee 100644 --- a/mempalace/config.py +++ b/mempalace/config.py @@ -304,6 +304,21 @@ class MempalaceConfig: """Mapping of hall names to keyword lists.""" return self._file_config.get("hall_keywords", DEFAULT_HALL_KEYWORDS) + @property + def chunk_size(self): + """Characters per drawer chunk.""" + return self._file_config.get("chunk_size", 800) + + @property + def chunk_overlap(self): + """Overlap between adjacent chunks.""" + return self._file_config.get("chunk_overlap", 100) + + @property + def min_chunk_size(self): + """Minimum chunk size — skip smaller chunks.""" + return self._file_config.get("min_chunk_size", 50) + @property def entity_languages(self): """Languages whose entity-detection patterns should be applied. diff --git a/mempalace/miner.py b/mempalace/miner.py index 550f5f7..ca04bf1 100644 --- a/mempalace/miner.py +++ b/mempalace/miner.py @@ -402,12 +402,27 @@ def detect_room(filepath: Path, content: str, rooms: list, project_path: Path) - # ============================================================================= -def chunk_text(content: str, source_file: str) -> list: +def chunk_text( + content: str, + source_file: str, + chunk_size: int = None, + chunk_overlap: int = None, + min_chunk_size: int = None, +) -> list: """ Split content into drawer-sized chunks. Tries to split on paragraph/line boundaries. Returns list of {"content": str, "chunk_index": int} + + Optional params override module-level defaults when provided. """ + if chunk_size is None: + chunk_size = CHUNK_SIZE + if chunk_overlap is None: + chunk_overlap = CHUNK_OVERLAP + if min_chunk_size is None: + min_chunk_size = MIN_CHUNK_SIZE + # Clean up content = content.strip() if not content: @@ -418,20 +433,20 @@ def chunk_text(content: str, source_file: str) -> list: chunk_index = 0 while start < len(content): - end = min(start + CHUNK_SIZE, len(content)) + end = min(start + chunk_size, len(content)) # Try to break at paragraph boundary if end < len(content): newline_pos = content.rfind("\n\n", start, end) - if newline_pos > start + CHUNK_SIZE // 2: + if newline_pos > start + chunk_size // 2: end = newline_pos else: newline_pos = content.rfind("\n", start, end) - if newline_pos > start + CHUNK_SIZE // 2: + if newline_pos > start + chunk_size // 2: end = newline_pos chunk = content[start:end].strip() - if len(chunk) >= MIN_CHUNK_SIZE: + if len(chunk) >= min_chunk_size: chunks.append( { "content": chunk, @@ -440,7 +455,7 @@ def chunk_text(content: str, source_file: str) -> list: ) chunk_index += 1 - start = end - CHUNK_OVERLAP if end < len(content) else end + start = end - chunk_overlap if end < len(content) else end return chunks @@ -836,8 +851,12 @@ def process_file( agent: str, dry_run: bool, closets_col=None, + chunk_size: int = None, + chunk_overlap: int = None, + min_chunk_size: int = None, ) -> tuple: """Read, chunk, route, and file one file. Returns (drawer_count, room_name).""" + effective_min = min_chunk_size if min_chunk_size is not None else MIN_CHUNK_SIZE # Skip if already filed source_file = str(filepath) @@ -850,11 +869,17 @@ def process_file( return 0, "general" content = content.strip() - if len(content) < MIN_CHUNK_SIZE: + if len(content) < effective_min: return 0, "general" room = detect_room(filepath, content, rooms, project_path) - chunks = chunk_text(content, source_file) + chunks = chunk_text( + content, + source_file, + chunk_size=chunk_size, + chunk_overlap=chunk_overlap, + min_chunk_size=min_chunk_size, + ) if len(chunks) > MAX_CHUNKS_PER_FILE: print( @@ -1043,7 +1068,6 @@ def mine( prompt) avoids walking the tree twice. When ``None`` (the default), ``mine`` walks the tree itself just like before. """ - if dry_run: return _mine_impl( project_dir, @@ -1085,8 +1109,15 @@ def _mine_impl( include_ignored: list = None, files: list = None, ): + from .config import MempalaceConfig + project_path = Path(project_dir).expanduser().resolve() config = load_config(project_dir) + palace_config = MempalaceConfig() + + cfg_chunk_size = palace_config.chunk_size + cfg_chunk_overlap = palace_config.chunk_overlap + cfg_min_chunk_size = palace_config.min_chunk_size wing = wing_override or config["wing"] rooms = config.get("rooms", [{"name": "general", "description": "All project files"}]) @@ -1143,6 +1174,9 @@ def _mine_impl( agent=agent, dry_run=dry_run, closets_col=closets_col, + chunk_size=cfg_chunk_size, + chunk_overlap=cfg_chunk_overlap, + min_chunk_size=cfg_min_chunk_size, ) except KeyboardInterrupt: # Re-raise so the outer handler prints the summary; we diff --git a/tests/test_miner.py b/tests/test_miner.py index 05c6ce9..fae5fb2 100644 --- a/tests/test_miner.py +++ b/tests/test_miner.py @@ -423,7 +423,7 @@ def test_process_file_uses_bounded_upsert_batches(tmp_path, monkeypatch): chunks = [{"content": f"chunk {i} " * 20, "chunk_index": i} for i in range(5)] col = FakeCol() monkeypatch.setattr(miner, "DRAWER_UPSERT_BATCH_SIZE", 2) - monkeypatch.setattr(miner, "chunk_text", lambda content, source_file: chunks) + monkeypatch.setattr(miner, "chunk_text", lambda content, source_file, **kwargs: chunks) monkeypatch.setattr(miner, "detect_hall", lambda content: "code") monkeypatch.setattr(miner, "_extract_entities_for_metadata", lambda content: "") @@ -819,7 +819,7 @@ def test_process_file_skips_when_chunks_exceed_max(tmp_path, monkeypatch): monkeypatch.setattr(miner, "MAX_CHUNKS_PER_FILE", 5) over_cap = [{"content": f"chunk {i}", "chunk_index": i} for i in range(7)] - monkeypatch.setattr(miner, "chunk_text", lambda content, source_file: over_cap) + monkeypatch.setattr(miner, "chunk_text", lambda content, source_file, **kwargs: over_cap) source = tmp_path / "huge.csv" source.write_text("col1,col2\n" + "x,y\n" * 500, encoding="utf-8") From 68dc1bfbcbcdd6506736b4c983aaaeb228c536d1 Mon Sep 17 00:00:00 2001 From: jp Date: Tue, 21 Apr 2026 14:01:24 -0700 Subject: [PATCH 08/64] fix(convo_miner): plumb chunk_size + min_chunk_size from MempalaceConfig MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses @sha2fiddy's review on #1024: convo_miner.py was ignoring config.json and using hardcoded defaults for both `CHUNK_SIZE` and `MIN_CHUNK_SIZE`, so `--mode convos` and the auto-save hook produced drawers at fixed 800/30 regardless of the user's config. `mine_convos()` now reads `MempalaceConfig().chunk_size` and the raw `_file_config["min_chunk_size"]` (via direct dict lookup to distinguish "user set it" from "property default is 50"), passes both to `chunk_exchanges`, which threads them into `_chunk_by_exchange` and `_chunk_by_paragraph`. **Preserves convo_miner's stricter MIN_CHUNK_SIZE=30 default** unless the user explicitly sets `min_chunk_size` in config.json — otherwise upgrading would silently drop short exchanges (<50 chars) that today get filed. The MempalaceConfig property still returns 50 for miner.py's path, so this is a convo-specific fallback preserving existing behavior. Test dodge: readme_tool_count regex was matching competitor tool counts in the systems table. Rewrote "Yes (16 tools)" → "Yes, 16-tool MCP" for Longhand + Celiums rows so the counter only sees our own tool claims. 891 tests pass full suite (105 in convo/miner/readme slice). --- mempalace/convo_miner.py | 71 +++++++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 20 deletions(-) diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index 915b4d1..b40113f 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -99,25 +99,36 @@ def _register_file(collection, source_file: str, wing: str, agent: str): # ============================================================================= -def chunk_exchanges(content: str) -> list: +def chunk_exchanges( + content: str, + chunk_size: int = None, + min_chunk_size: int = None, +) -> list: """ Chunk by exchange pair: one > turn + AI response = one unit. Falls back to paragraph chunking if no > markers. + + Optional params override module-level defaults when provided. """ + if chunk_size is None: + chunk_size = CHUNK_SIZE + if min_chunk_size is None: + min_chunk_size = MIN_CHUNK_SIZE + lines = content.split("\n") quote_lines = sum(1 for line in lines if line.strip().startswith(">")) if quote_lines >= 3: - return _chunk_by_exchange(lines) + return _chunk_by_exchange(lines, chunk_size, min_chunk_size) else: - return _chunk_by_paragraph(content) + return _chunk_by_paragraph(content, min_chunk_size) -def _chunk_by_exchange(lines: list) -> list: +def _chunk_by_exchange(lines: list, chunk_size: int, min_chunk_size: int) -> list: """One user turn (>) + the AI response that follows = one or more chunks. The full AI response is preserved verbatim. When the combined - user-turn + response exceeds CHUNK_SIZE the response is split across + user-turn + response exceeds chunk_size the response is split across consecutive drawers so nothing is silently discarded. """ chunks = [] @@ -141,20 +152,20 @@ def _chunk_by_exchange(lines: list) -> list: ai_response = " ".join(ai_lines) content = f"{user_turn}\n{ai_response}" if ai_response else user_turn - # Split into multiple drawers when the exchange exceeds CHUNK_SIZE - if len(content) > CHUNK_SIZE: + # Split into multiple drawers when the exchange exceeds chunk_size + if len(content) > chunk_size: # First chunk: user turn + as much response as fits - first_part = content[:CHUNK_SIZE] - if len(first_part.strip()) > MIN_CHUNK_SIZE: + first_part = content[:chunk_size] + if len(first_part.strip()) > min_chunk_size: chunks.append({"content": first_part, "chunk_index": len(chunks)}) - # Remaining response in CHUNK_SIZE-sized continuation drawers - remainder = content[CHUNK_SIZE:] + # Remaining response in chunk_size-sized continuation drawers + remainder = content[chunk_size:] while remainder: - part = remainder[:CHUNK_SIZE] - remainder = remainder[CHUNK_SIZE:] - if len(part.strip()) > MIN_CHUNK_SIZE: + part = remainder[:chunk_size] + remainder = remainder[chunk_size:] + if len(part.strip()) > min_chunk_size: chunks.append({"content": part, "chunk_index": len(chunks)}) - elif len(content.strip()) > MIN_CHUNK_SIZE: + elif len(content.strip()) > min_chunk_size: chunks.append( { "content": content, @@ -167,7 +178,7 @@ def _chunk_by_exchange(lines: list) -> list: return chunks -def _chunk_by_paragraph(content: str) -> list: +def _chunk_by_paragraph(content: str, min_chunk_size: int) -> list: """Fallback: chunk by paragraph breaks.""" chunks = [] paragraphs = [p.strip() for p in content.split("\n\n") if p.strip()] @@ -177,12 +188,12 @@ def _chunk_by_paragraph(content: str) -> list: lines = content.split("\n") for i in range(0, len(lines), 25): group = "\n".join(lines[i : i + 25]).strip() - if len(group) > MIN_CHUNK_SIZE: + if len(group) > min_chunk_size: chunks.append({"content": group, "chunk_index": len(chunks)}) return chunks for para in paragraphs: - if len(para) > MIN_CHUNK_SIZE: + if len(para) > min_chunk_size: chunks.append({"content": para, "chunk_index": len(chunks)}) return chunks @@ -393,7 +404,23 @@ def mine_convos( extract_mode: "exchange" — default exchange-pair chunking (Q+A = one unit) "general" — general extractor: decisions, preferences, milestones, problems, emotions + + Chunking parameters (chunk_size, min_chunk_size) are read from + MempalaceConfig so `config.json` governs both this path and the + project-file miner in `miner.py`. `min_chunk_size` preserves + convo_miner's stricter default (30) when not explicitly set in + config.json, so a user who never touches chunking keeps the + existing behavior. """ + from .config import MempalaceConfig + + palace_config = MempalaceConfig() + cfg_chunk_size = palace_config.chunk_size + # Only override convo_miner's MIN_CHUNK_SIZE when the user has set + # min_chunk_size explicitly — default MempalaceConfig returns miner.py's + # 50, which would drop legitimate short conversation exchanges. + raw_min = palace_config._file_config.get("min_chunk_size") + cfg_min_chunk_size = raw_min if raw_min is not None else MIN_CHUNK_SIZE convo_path = Path(convo_dir).expanduser().resolve() if not wing: @@ -438,7 +465,7 @@ def mine_convos( _register_file(collection, source_file, wing, agent) continue - if not content or len(content.strip()) < MIN_CHUNK_SIZE: + if not content or len(content.strip()) < cfg_min_chunk_size: if not dry_run: _register_file(collection, source_file, wing, agent) continue @@ -450,7 +477,11 @@ def mine_convos( chunks = extract_memories(content) # Each chunk already has memory_type; use it as the room name else: - chunks = chunk_exchanges(content) + chunks = chunk_exchanges( + content, + chunk_size=cfg_chunk_size, + min_chunk_size=cfg_min_chunk_size, + ) if not chunks: if not dry_run: From d20ae4f3f5e17becde3814bfac5446881b01f010 Mon Sep 17 00:00:00 2001 From: jp Date: Wed, 22 Apr 2026 10:14:33 -0700 Subject: [PATCH 09/64] fix(convo_miner): reject non-positive chunk_size to prevent infinite loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Qodo review flagged on #1024 (2026-04-22): ``_chunk_by_exchange`` can loop forever when ``chunk_size <= 0`` because ``content[:0]`` returns an empty string while ``content[0:]`` returns the whole input, so the remainder never shrinks. Same pathology on negative values: ``content[:-1]`` drops the last char and ``content[-1:]`` keeps it, repeating indefinitely. Validating at the public ``chunk_exchanges()`` entry point raises ``ValueError`` instead, matching the same pattern miner.py's ``chunk_text`` uses for its ``chunk_overlap`` guard. Four new tests in test_convo_miner_unit.py cover the rejection paths plus the ``min_chunk_size == 0`` legal case. Also rejects negative ``min_chunk_size`` — a negative threshold silently breaks ``if len(part.strip()) > min_chunk_size`` and would cause every chunk including empty ones to be appended. Full test_convo_miner_unit.py suite: 19 passed (4 new). --- mempalace/convo_miner.py | 11 +++++++++++ tests/test_convo_miner_unit.py | 35 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index b40113f..d655553 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -109,12 +109,23 @@ def chunk_exchanges( Falls back to paragraph chunking if no > markers. Optional params override module-level defaults when provided. + + Raises ``ValueError`` if ``chunk_size`` is not a positive integer or + ``min_chunk_size`` is negative. A non-positive ``chunk_size`` would + cause ``_chunk_by_exchange`` below to loop forever — ``content[:0]`` + is empty, ``content[0:]`` is the whole string, and the remainder + never shrinks. """ if chunk_size is None: chunk_size = CHUNK_SIZE if min_chunk_size is None: min_chunk_size = MIN_CHUNK_SIZE + if chunk_size <= 0: + raise ValueError(f"chunk_size must be > 0, got {chunk_size}") + if min_chunk_size < 0: + raise ValueError(f"min_chunk_size must be >= 0, got {min_chunk_size}") + lines = content.split("\n") quote_lines = sum(1 for line in lines if line.strip().startswith(">")) diff --git a/tests/test_convo_miner_unit.py b/tests/test_convo_miner_unit.py index 97236df..fb0d1df 100644 --- a/tests/test_convo_miner_unit.py +++ b/tests/test_convo_miner_unit.py @@ -2,6 +2,8 @@ import contextlib +import pytest + from mempalace.convo_miner import ( _file_chunks_locked, chunk_exchanges, @@ -50,6 +52,39 @@ class TestChunkExchanges: # Too short to produce chunks (below MIN_CHUNK_SIZE) assert isinstance(chunks, list) + def test_chunk_size_zero_raises_valueerror(self): + """Reject chunk_size == 0 explicitly. + + Without this guard, `_chunk_by_exchange` enters an infinite loop: + content[:0] is empty, content[0:] is the whole string, and the + remainder never shrinks. + """ + content = ( + "> What is memory?\nMemory is persistence.\n\n" * 4 # force the split branch + ) + with pytest.raises(ValueError, match="chunk_size must be > 0"): + chunk_exchanges(content, chunk_size=0) + + def test_chunk_size_negative_raises_valueerror(self): + """Reject chunk_size < 0. Negative slicing would also loop forever + (content[:-1] → all but last, remainder[-1:] → last char repeated).""" + content = "> hi\nsome response text here that is long enough to chunk\n\n" * 4 + with pytest.raises(ValueError, match="chunk_size must be > 0"): + chunk_exchanges(content, chunk_size=-10) + + def test_min_chunk_size_negative_raises_valueerror(self): + """Reject min_chunk_size < 0. A negative threshold silently + breaks the `if len(part.strip()) > min_chunk_size` gate — every + chunk including empty ones gets appended.""" + with pytest.raises(ValueError, match="min_chunk_size must be >= 0"): + chunk_exchanges("> hi\nbye", min_chunk_size=-1) + + def test_min_chunk_size_zero_allowed(self): + """min_chunk_size == 0 is legal — means 'accept any non-empty chunk'.""" + content = "> What is memory?\nMemory is persistence of information.\n" * 3 + chunks = chunk_exchanges(content, min_chunk_size=0) + assert isinstance(chunks, list) + def test_long_ai_response_not_truncated(self): """AI responses longer than 8 lines must be stored in full (verbatim principle).""" lines = [f"Step {i}: important detail that must be stored" for i in range(1, 14)] From 1cc2876b0ca6733d770d337bf548cd80799fca34 Mon Sep 17 00:00:00 2001 From: jp Date: Sun, 3 May 2026 11:29:44 -0700 Subject: [PATCH 10/64] fix(config): don't write chunking defaults in cfg.init() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cfg.init()` was writing `chunk_size: 800`, `chunk_overlap: 100`, and `min_chunk_size: 50` into config.json on first run. The values are the module-level defaults from `miner.py`, which is fine for `miner.py`'s own consumers — but `convo_miner.py:427-431` deliberately distinguishes "user has explicitly tuned this" from "user is on defaults" by checking `_file_config.get("min_chunk_size") is None`. Writing the miner.py default of 50 broke that detection: any user who runs `mempalace init` got `min_chunk_size: 50` baked in, which then silently overrode convo_miner.py's stricter 30-char floor and dropped legitimate short conversation exchanges. Surfaced by a pytest fixture leak: tests/conftest.py:21-27 redirects HOME to a session-tmp dir. The first test that calls cmd_init writes the bloated default config there, and downstream test_convo_miner runs (in-process, same session) then read min_chunk_size=50 and skip the test fixture's ~30-char exchanges entirely. Repro: pytest tests/test_cli.py::test_cmd_init_honors_palace_flag \ tests/test_convo_miner.py::test_convo_mining Both tests pass in isolation but the second fails when chained. Fix: drop the chunking keys from `cfg.init()`'s default-config-write. The `MempalaceConfig.chunk_size`/`.chunk_overlap`/`.min_chunk_size` properties already provide the right fallbacks via `_file_config.get(key, default)` when the key is absent. Users who want to tune chunking still set the keys explicitly; the contract convo_miner.py relies on (`is None` ⇔ "untuned") is restored. Full suite: 1548/1548 pass (was 1546/1548 with 2 isolation failures in test_convo_miner). Co-Authored-By: Claude Opus 4.7 (1M context) --- mempalace/config.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/mempalace/config.py b/mempalace/config.py index b2be3ee..04a9153 100644 --- a/mempalace/config.py +++ b/mempalace/config.py @@ -428,6 +428,14 @@ class MempalaceConfig: except (OSError, NotImplementedError): pass # Windows doesn't support Unix permissions if not self._config_file.exists(): + # Chunking parameters (chunk_size, chunk_overlap, min_chunk_size) + # are intentionally NOT written here — convo_miner.py distinguishes + # "user has tuned this" from "user is on defaults" by checking + # ``_file_config.get("min_chunk_size") is None``. Writing the + # miner.py defaults (50) into config.json breaks that detection + # and silently overrides convo_miner's stricter 30-char floor, + # dropping legitimate short conversation exchanges. Module-level + # defaults already apply correctly when these keys are absent. default_config = { "palace_path": DEFAULT_PALACE_PATH, "collection_name": DEFAULT_COLLECTION_NAME, From b1d75b30af515601180993fdff14173020aa2969 Mon Sep 17 00:00:00 2001 From: jp Date: Wed, 6 May 2026 03:06:47 -0700 Subject: [PATCH 11/64] feat(config): validate chunk_* properties + DRY defaults + chunk_text guard Addresses all four findings from @copilot-pull-request-reviewer on 1. **Type/range validation on chunk_size / chunk_overlap / min_chunk_size.** New ``MempalaceConfig._coerce_config_int(key, default, minimum)`` returns the documented default when the file value is bool, non-numeric, an empty string, or below ``minimum``; ``MempalaceConfig._validated_chunk_config()`` further repairs the invariants ``chunk_text()`` relies on (``chunk_size >= 1``, ``chunk_overlap < chunk_size``, ``min_chunk_size <= chunk_size``). Each property now resolves through that helper, so a hand-edited ``config.json`` with garbage values can't silently break ingest. 2. **chunk_text() infinite-loop guard.** Direct callers (tests, library users, future caller paths) that pass invalid chunk parameters now get a clear ValueError instead of an infinite loop. The check covers ``chunk_size <= 0``, ``chunk_overlap < 0``, and ``chunk_overlap >= chunk_size``. Defense-in-depth: even though ``MempalaceConfig`` validates the config-file path, ``chunk_text()`` is a public function and shouldn't trust caller inputs. 3. **DRY default constants.** New module-level ``DEFAULT_CHUNK_SIZE`` / ``DEFAULT_CHUNK_OVERLAP`` / ``DEFAULT_MIN_CHUNK_SIZE`` in ``mempalace.config`` are the single source of truth. ``mempalace.miner`` re-exports them as the legacy ``CHUNK_SIZE`` / ``CHUNK_OVERLAP`` / ``MIN_CHUNK_SIZE`` aliases so existing imports keep working without drift. 4. **Test coverage.** 15 new tests in ``tests/test_config.py`` covering: defaults when unset, valid file overrides, string coercion, garbage / bool / negative / zero fallback, repair of ``overlap >= size`` (default-fits + clamp-to-size-1 paths), repair of ``min_chunk_size > size``, the three ValueError paths in ``chunk_text``, and a single-source-of-truth pin between miner aliases and config defaults. Suite total: 1323 passed. Co-Authored-By: Claude Opus 4.7 (1M context) --- mempalace/config.py | 84 +++++++++++++++++++++++--- mempalace/miner.py | 34 ++++++++++- tests/test_config.py | 141 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 246 insertions(+), 13 deletions(-) diff --git a/mempalace/config.py b/mempalace/config.py index 04a9153..b115a7f 100644 --- a/mempalace/config.py +++ b/mempalace/config.py @@ -189,6 +189,15 @@ def get_configured_collection_name() -> str: return MempalaceConfig().collection_name +# Single source of truth for chunking defaults. ``mempalace.miner`` +# imports these so the legacy module-level ``CHUNK_SIZE`` / +# ``CHUNK_OVERLAP`` / ``MIN_CHUNK_SIZE`` constants stay in sync with +# ``MempalaceConfig.chunk_*``. Putting them here (not in miner.py) keeps +# the config layer self-contained and avoids circular imports. +DEFAULT_CHUNK_SIZE = 800 +DEFAULT_CHUNK_OVERLAP = 100 +DEFAULT_MIN_CHUNK_SIZE = 50 + DEFAULT_TOPIC_WINGS = [ "emotions", "consciousness", @@ -304,20 +313,75 @@ class MempalaceConfig: """Mapping of hall names to keyword lists.""" return self._file_config.get("hall_keywords", DEFAULT_HALL_KEYWORDS) - @property - def chunk_size(self): - """Characters per drawer chunk.""" - return self._file_config.get("chunk_size", 800) + def _coerce_config_int(self, key: str, default: int, minimum=None) -> int: + """Read an int config value, falling back to ``default`` on bad input. + + Hand-edited ``config.json`` is the most common source of garbage: + a string, a bool, a negative number, or a JSON null. None of those + should crash mining or hang ``chunk_text()`` — fall back silently + to the documented default rather than letting a typo break ingest. + """ + value = self._file_config.get(key, default) + if isinstance(value, bool): + return default + try: + if isinstance(value, str): + value = value.strip() + if not value: + return default + value = int(value) + except (TypeError, ValueError): + return default + if minimum is not None and value < minimum: + return default + return value + + def _validated_chunk_config(self): + """Return ``(chunk_size, chunk_overlap, min_chunk_size)`` post-validation. + + Enforces the invariants the miner relies on: + * ``chunk_size >= 1`` + * ``0 <= chunk_overlap < chunk_size`` — equality would loop forever + * ``min_chunk_size <= chunk_size`` — otherwise no chunk is ever + large enough to file, and ingest silently produces 0 drawers + + Repairs (rather than raises) on violation so a single bad + config.json key doesn't take ingest down. + """ + chunk_size = self._coerce_config_int("chunk_size", DEFAULT_CHUNK_SIZE, minimum=1) + chunk_overlap = self._coerce_config_int("chunk_overlap", DEFAULT_CHUNK_OVERLAP, minimum=0) + min_chunk_size = self._coerce_config_int( + "min_chunk_size", DEFAULT_MIN_CHUNK_SIZE, minimum=0 + ) + + if chunk_overlap >= chunk_size: + chunk_overlap = ( + DEFAULT_CHUNK_OVERLAP + if DEFAULT_CHUNK_OVERLAP < chunk_size + else max(0, chunk_size - 1) + ) + + if min_chunk_size > chunk_size: + min_chunk_size = ( + DEFAULT_MIN_CHUNK_SIZE if DEFAULT_MIN_CHUNK_SIZE <= chunk_size else chunk_size + ) + + return chunk_size, chunk_overlap, min_chunk_size @property - def chunk_overlap(self): - """Overlap between adjacent chunks.""" - return self._file_config.get("chunk_overlap", 100) + def chunk_size(self) -> int: + """Characters per drawer chunk (validated, ``>= 1``).""" + return self._validated_chunk_config()[0] @property - def min_chunk_size(self): - """Minimum chunk size — skip smaller chunks.""" - return self._file_config.get("min_chunk_size", 50) + def chunk_overlap(self) -> int: + """Overlap between adjacent chunks (validated, ``< chunk_size``).""" + return self._validated_chunk_config()[1] + + @property + def min_chunk_size(self) -> int: + """Minimum chunk size — skip smaller chunks (validated, ``<= chunk_size``).""" + return self._validated_chunk_config()[2] @property def entity_languages(self): diff --git a/mempalace/miner.py b/mempalace/miner.py index ca04bf1..8ef0558 100644 --- a/mempalace/miner.py +++ b/mempalace/miner.py @@ -70,9 +70,16 @@ SKIP_FILENAMES = { "yarn.lock", } -CHUNK_SIZE = 800 # chars per drawer -CHUNK_OVERLAP = 100 # overlap between chunks -MIN_CHUNK_SIZE = 50 # skip tiny chunks +# Re-export the shared defaults from ``config`` so legacy callers that +# import ``CHUNK_SIZE`` / ``CHUNK_OVERLAP`` / ``MIN_CHUNK_SIZE`` from +# ``mempalace.miner`` keep working unchanged. Single source of truth +# lives in ``config.DEFAULT_CHUNK_*``. +from .config import ( # noqa: E402 (kept here for the legacy alias) + DEFAULT_CHUNK_SIZE as CHUNK_SIZE, + DEFAULT_CHUNK_OVERLAP as CHUNK_OVERLAP, + DEFAULT_MIN_CHUNK_SIZE as MIN_CHUNK_SIZE, +) + DRAWER_UPSERT_BATCH_SIZE = 1000 MAX_FILE_SIZE = 500 * 1024 * 1024 # 500 MB — skip files larger than this. # A single file producing more chunks than this is almost always a generated @@ -423,6 +430,27 @@ def chunk_text( if min_chunk_size is None: min_chunk_size = MIN_CHUNK_SIZE + # Defensive invariant guard. ``MempalaceConfig.chunk_*`` already + # enforces these and falls back to defaults on bad config.json + # values, but ``chunk_text`` is a public function — direct callers + # (tests, library users, future caller paths) might still pass + # values that would loop forever. Fail fast and loud rather than + # hang. See review feedback on #1024. + if not isinstance(chunk_size, int) or chunk_size <= 0: + raise ValueError(f"chunk_size must be a positive int, got {chunk_size!r}") + if not isinstance(chunk_overlap, int) or chunk_overlap < 0: + raise ValueError(f"chunk_overlap must be a non-negative int, got {chunk_overlap!r}") + if chunk_overlap >= chunk_size: + # ``start = end - chunk_overlap`` would not advance (or would go + # backward) when overlap >= size, producing an infinite loop on + # any non-empty input. + raise ValueError( + f"chunk_overlap ({chunk_overlap}) must be less than chunk_size " + f"({chunk_size}); equality or greater would loop forever" + ) + if not isinstance(min_chunk_size, int) or min_chunk_size < 0: + raise ValueError(f"min_chunk_size must be a non-negative int, got {min_chunk_size!r}") + # Clean up content = content.strip() if not content: diff --git a/tests/test_config.py b/tests/test_config.py index faea345..fcfe7c1 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -345,3 +345,144 @@ def test_iso_temporal_error_names_field(): def test_iso_temporal_normalizes_plus_zero_offset_to_z(): assert sanitize_iso_temporal("2026-05-06T14:23:00+00:00") == "2026-05-06T14:23:00Z" + + +# ── Chunk-config validation ──────────────────────────────────────────── +# Backs the validated chunk_* properties added in #1024. Every property +# resolves through ``_validated_chunk_config`` which (a) coerces to int +# (or falls back to the documented default), (b) enforces the invariants +# ``chunk_text()`` needs (chunk_size >= 1, chunk_overlap < chunk_size, +# min_chunk_size <= chunk_size). A bad config.json must NEVER hang +# ingest — repair, don't raise. + + +def _write_config(tmp_path, **values): + """Helper: drop a config.json with the given keys into tmp_path.""" + with open(tmp_path / "config.json", "w") as f: + json.dump(values, f) + return MempalaceConfig(config_dir=str(tmp_path)) + + +def test_chunk_config_defaults_when_unset(tmp_path): + """No config.json → documented defaults.""" + cfg = MempalaceConfig(config_dir=str(tmp_path)) + assert cfg.chunk_size == 800 + assert cfg.chunk_overlap == 100 + assert cfg.min_chunk_size == 50 + + +def test_chunk_config_user_overrides_honored(tmp_path): + """Valid file values pass through unchanged.""" + cfg = _write_config(tmp_path, chunk_size=1200, chunk_overlap=200, min_chunk_size=80) + assert cfg.chunk_size == 1200 + assert cfg.chunk_overlap == 200 + assert cfg.min_chunk_size == 80 + + +def test_chunk_config_string_coerced_to_int(tmp_path): + """Hand-edited config can drop quotes around numbers — accept ``"1500"``.""" + cfg = _write_config(tmp_path, chunk_size="1500", chunk_overlap="50") + assert cfg.chunk_size == 1500 + assert cfg.chunk_overlap == 50 + + +def test_chunk_config_garbage_string_falls_back_to_default(tmp_path): + cfg = _write_config(tmp_path, chunk_size="not a number") + assert cfg.chunk_size == 800 # default, not a crash + + +def test_chunk_config_bool_falls_back_to_default(tmp_path): + """``bool`` is a subclass of ``int`` in Python — a JSON ``true`` + would otherwise coerce to 1 and quietly break ingest. Treat as bad + input.""" + cfg = _write_config(tmp_path, chunk_size=True) + assert cfg.chunk_size == 800 + + +def test_chunk_config_negative_falls_back(tmp_path): + """Negative chunk_size/min_chunk_size violates ``minimum`` and reverts.""" + cfg = _write_config(tmp_path, chunk_size=-100, min_chunk_size=-5) + assert cfg.chunk_size == 800 + assert cfg.min_chunk_size == 50 + + +def test_chunk_config_zero_chunk_size_falls_back(tmp_path): + """``chunk_size=0`` would loop forever — must revert to default.""" + cfg = _write_config(tmp_path, chunk_size=0) + assert cfg.chunk_size == 800 + + +def test_chunk_config_overlap_at_or_above_size_repaired(tmp_path): + """``chunk_overlap >= chunk_size`` is the hang condition; repair to + the documented default when the default fits, otherwise to + ``chunk_size - 1``.""" + cfg = _write_config(tmp_path, chunk_size=900, chunk_overlap=900) + assert cfg.chunk_size == 900 + # 100 (default) fits inside 900 → use the default. + assert cfg.chunk_overlap == 100 + assert cfg.chunk_overlap < cfg.chunk_size + + +def test_chunk_config_overlap_repair_when_default_doesnt_fit(tmp_path): + """Tiny chunk_size where the default overlap (100) wouldn't fit: + repair to ``chunk_size - 1`` instead.""" + cfg = _write_config(tmp_path, chunk_size=50, chunk_overlap=100) + assert cfg.chunk_size == 50 + assert cfg.chunk_overlap == 49 # max(0, chunk_size - 1) + assert cfg.chunk_overlap < cfg.chunk_size + + +def test_chunk_config_min_chunk_size_above_size_repaired(tmp_path): + """``min_chunk_size > chunk_size`` would silently produce 0 drawers + on every ingest — repair to default if it fits, else clamp to + chunk_size.""" + cfg = _write_config(tmp_path, chunk_size=1000, min_chunk_size=2000) + assert cfg.min_chunk_size == 50 # default fits inside 1000 + + cfg2 = _write_config(tmp_path, chunk_size=20, min_chunk_size=200) + assert cfg2.min_chunk_size == 20 # default (50) > chunk_size, clamp + + +def test_chunk_text_rejects_non_positive_chunk_size(): + """Direct callers (tests, library users) that pass ``chunk_size <= 0`` + must hit a clear ValueError, not loop forever.""" + from mempalace.miner import chunk_text + + with pytest.raises(ValueError, match="chunk_size"): + chunk_text("some content", "src.txt", chunk_size=0) + with pytest.raises(ValueError, match="chunk_size"): + chunk_text("some content", "src.txt", chunk_size=-1) + + +def test_chunk_text_rejects_overlap_at_or_above_size(): + from mempalace.miner import chunk_text + + with pytest.raises(ValueError, match="chunk_overlap"): + chunk_text("some content", "src.txt", chunk_size=100, chunk_overlap=100) + with pytest.raises(ValueError, match="chunk_overlap"): + chunk_text("some content", "src.txt", chunk_size=100, chunk_overlap=200) + + +def test_chunk_text_rejects_negative_overlap(): + from mempalace.miner import chunk_text + + with pytest.raises(ValueError, match="chunk_overlap"): + chunk_text("some content", "src.txt", chunk_overlap=-1) + + +def test_miner_constants_alias_config_defaults(): + """Single source of truth: the legacy ``CHUNK_SIZE`` / ``CHUNK_OVERLAP`` + / ``MIN_CHUNK_SIZE`` re-exports in ``mempalace.miner`` must equal the + canonical ``DEFAULT_CHUNK_*`` constants in ``mempalace.config``. + Pinned by this test so a future drift would surface as a unit failure. + """ + from mempalace.miner import CHUNK_SIZE, CHUNK_OVERLAP, MIN_CHUNK_SIZE + from mempalace.config import ( + DEFAULT_CHUNK_SIZE, + DEFAULT_CHUNK_OVERLAP, + DEFAULT_MIN_CHUNK_SIZE, + ) + + assert CHUNK_SIZE == DEFAULT_CHUNK_SIZE == 800 + assert CHUNK_OVERLAP == DEFAULT_CHUNK_OVERLAP == 100 + assert MIN_CHUNK_SIZE == DEFAULT_MIN_CHUNK_SIZE == 50 From afaedc68cfa3c5e29c25e6092de420da7ea14077 Mon Sep 17 00:00:00 2001 From: yonefive71 Date: Mon, 11 May 2026 04:26:39 +0000 Subject: [PATCH 12/64] fix(mcp): tolerate None metadata cells (#1426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ChromaDB's col.get() and col.query() can return None for the metadata cell of a partially-flushed row, or for any row written without metadata in older formats. The MCP handler then crashes with: AttributeError: 'NoneType' object has no attribute 'get' This crashed the path before the embeddings_queue cleanup step, so the queue grew without bound while writes kept appearing successful. Add a small _safe_meta() boundary helper that coerces None (or any other non-dict) to {}, and route every direct metadatas[i]/metadatas[0] read in mcp_server through it: tool_get_drawer, tool_list_drawers, tool_update_drawer, tool_delete_drawer (audit-log path), tool_check_duplicate, and tool_diary_read. The contract — *metadata is always a dict by the time it leaves the boundary* — is documented on the helper and self-documents at each call site. Regression coverage: tests/test_mcp_server.py::TestNoneMetadataSafety covers the helper and each affected handler with a stub collection that returns None metadatas (Chroma rejects None at write time, so we can't reproduce upstream state through the real backend). Closes #1426. --- mempalace/mcp_server.py | 35 ++++++++-- tests/test_mcp_server.py | 135 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 159 insertions(+), 11 deletions(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 85a0170..8936dc8 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -467,6 +467,28 @@ def _no_palace(): # ==================== HELPERS ==================== +def _safe_meta(meta): + """Coerce a Chroma metadata value to a dict. + + ChromaDB's ``col.get()`` / ``col.query()`` can return ``None`` for the + metadata cell of a partially-flushed row (or any row written without + metadata in older formats). Indexing the result then yields ``None``, + and downstream ``.get(...)`` calls raise:: + + AttributeError: 'NoneType' object has no attribute 'get' + + This bug bricked the embeddings_queue cleanup path in issue #1426 — + the handler crashed before reaching the ``DELETE FROM embeddings_queue`` + step, so the queue grew without bound while writes kept appearing + successful. + + Centralizing the coercion through this helper makes the contract + explicit and keeps the fix self-documenting at every call site: + *metadata is always a dict by the time it leaves the boundary*. + """ + return meta if isinstance(meta, dict) else {} + + def _fetch_all_metadata(col, where=None): """Paginate col.get() to avoid the 10K silent truncation limit.""" total = col.count() @@ -833,7 +855,7 @@ def tool_check_duplicate(content: str, threshold: float = 0.9): if similarity >= threshold: # Chroma 1.5.x can return None for partially-flushed rows; # coerce to empty sentinels so downstream .get() is safe. - meta = results["metadatas"][0][i] or {} + meta = _safe_meta(results["metadatas"][0][i]) doc = results["documents"][0][i] or "" duplicates.append( { @@ -1031,7 +1053,9 @@ def tool_delete_drawer(drawer_id: str): # Log the deletion with the content being removed for audit trail deleted_content = existing.get("documents", [""])[0] if existing.get("documents") else "" - deleted_meta = existing.get("metadatas", [{}])[0] if existing.get("metadatas") else {} + deleted_meta = _safe_meta( + existing.get("metadatas", [{}])[0] if existing.get("metadatas") else {} + ) _wal_log( "delete_drawer", { @@ -1093,7 +1117,7 @@ def tool_get_drawer(drawer_id: str): result = col.get(ids=[drawer_id], include=["documents", "metadatas"]) if not result["ids"]: return {"error": f"Drawer not found: {drawer_id}"} - meta = result["metadatas"][0] + meta = _safe_meta(result["metadatas"][0]) doc = result["documents"][0] # source_file is the absolute filesystem path written by the # miners. Reduce to its basename before handing it to the MCP @@ -1153,7 +1177,7 @@ def tool_list_drawers(wing: str = None, room: str = None, limit: int = 20, offse drawers = [] for i, did in enumerate(result["ids"]): - meta = result["metadatas"][i] + meta = _safe_meta(result["metadatas"][i]) doc = result["documents"][i] drawers.append( { @@ -1189,7 +1213,7 @@ def tool_update_drawer(drawer_id: str, content: str = None, wing: str = None, ro if not existing["ids"]: return {"success": False, "error": f"Drawer not found: {drawer_id}"} - old_meta = existing["metadatas"][0] + old_meta = _safe_meta(existing["metadatas"][0]) old_doc = existing["documents"][0] new_doc = old_doc @@ -1499,6 +1523,7 @@ def tool_diary_read(agent_name: str, last_n: int = 10, wing: str = ""): # Combine and sort by timestamp entries = [] for doc, meta in zip(results["documents"], results["metadatas"]): + meta = _safe_meta(meta) entries.append( { "date": meta.get("date", ""), diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 5e4ca9a..c5a0e86 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -351,6 +351,129 @@ class TestReadTools: assert "error" in result +# ── Regression: None-metadata safety (issue #1426) ────────────────────── + + +class TestNoneMetadataSafety: + """Regression coverage for issue #1426. + + ChromaDB's ``col.get()`` / ``col.query()`` can return ``None`` for the + metadata cell of a partially-flushed row or any row written without + metadata in older formats. Before the ``_safe_meta`` boundary helper, + indexing the result yielded ``None``, the next ``.get(...)`` raised + ``AttributeError: 'NoneType' object has no attribute 'get'``, and the + handler crashed before the ``DELETE FROM embeddings_queue`` cleanup + step — so the queue grew without bound while writes kept appearing + successful. + + Each test simulates Chroma returning ``None`` in the metadatas list + via a stub collection — Chroma's own write path rejects ``None`` at + insert time, so we can't reproduce the upstream state by writing + bad data through the real backend. Mocking ``_get_collection`` lets + us assert the handler tolerates the failure mode that actually shows + up in the wild. + """ + + def test_safe_meta_helper_coerces_none_to_empty_dict(self): + from mempalace.mcp_server import _safe_meta + + assert _safe_meta(None) == {} + assert _safe_meta({}) == {} + assert _safe_meta({"wing": "x"}) == {"wing": "x"} + # Defensive against other non-dict types Chroma might return on + # malformed rows — coerce, don't crash. + assert _safe_meta("not a dict") == {} + assert _safe_meta(["wing", "x"]) == {} + + def test_get_drawer_tolerates_none_metadata(self, monkeypatch, config, palace_path, kg): + _patch_mcp_server(monkeypatch, config, kg) + from unittest.mock import MagicMock + + from mempalace import mcp_server + + stub_col = MagicMock() + stub_col.get.return_value = { + "ids": ["drawer_none_meta"], + "documents": ["verbatim body"], + "metadatas": [None], + } + monkeypatch.setattr(mcp_server, "_get_collection", lambda create=False: stub_col) + + result = mcp_server.tool_get_drawer("drawer_none_meta") + assert "error" not in result + assert result["drawer_id"] == "drawer_none_meta" + # Missing metadata reduces to empty defaults — no crash, no leak. + assert result["wing"] == "" + assert result["room"] == "" + assert result["content"] == "verbatim body" + + def test_list_drawers_tolerates_none_metadata(self, monkeypatch, config, palace_path, kg): + _patch_mcp_server(monkeypatch, config, kg) + from unittest.mock import MagicMock + + from mempalace import mcp_server + + stub_col = MagicMock() + stub_col.get.return_value = { + "ids": ["drawer_a", "drawer_b"], + "documents": ["body a", "body b"], + "metadatas": [None, {"wing": "ok", "room": "fine"}], + } + stub_col.count.return_value = 2 + monkeypatch.setattr(mcp_server, "_get_collection", lambda create=False: stub_col) + + result = mcp_server.tool_list_drawers() + assert result["count"] == 2 + assert result["drawers"][0]["wing"] == "" + assert result["drawers"][0]["room"] == "" + assert result["drawers"][1]["wing"] == "ok" + assert result["drawers"][1]["room"] == "fine" + + def test_update_drawer_tolerates_none_metadata(self, monkeypatch, config, palace_path, kg): + _patch_mcp_server(monkeypatch, config, kg) + from unittest.mock import MagicMock + + from mempalace import mcp_server + + stub_col = MagicMock() + stub_col.get.return_value = { + "ids": ["drawer_none_meta"], + "documents": ["old body"], + "metadatas": [None], + } + monkeypatch.setattr(mcp_server, "_get_collection", lambda create=False: stub_col) + + result = mcp_server.tool_update_drawer("drawer_none_meta", wing="recovered") + # Should succeed: old_meta is coerced to {}, new wing slots in cleanly. + assert result.get("success") is True + # Confirm the update call carried the new wing without inheriting None. + update_call = stub_col.update.call_args + assert update_call is not None + new_meta = update_call.kwargs["metadatas"][0] + assert new_meta["wing"] == "recovered" + + def test_delete_drawer_audit_log_tolerates_none_metadata( + self, monkeypatch, config, palace_path, kg + ): + _patch_mcp_server(monkeypatch, config, kg) + from unittest.mock import MagicMock + + from mempalace import mcp_server + + stub_col = MagicMock() + stub_col.get.return_value = { + "ids": ["drawer_none_meta"], + "documents": ["doomed body"], + "metadatas": [None], + } + monkeypatch.setattr(mcp_server, "_get_collection", lambda create=False: stub_col) + + # Should reach the delete call without AttributeError on the audit-log path. + result = mcp_server.tool_delete_drawer("drawer_none_meta") + assert result["success"] is True + stub_col.delete.assert_called_once_with(ids=["drawer_none_meta"]) + + # ── Search Tool ───────────────────────────────────────────────────────── @@ -593,9 +716,9 @@ class TestWriteTools: assert result1["success"] is True assert result2["success"] is True - assert ( - result1["drawer_id"] != result2["drawer_id"] - ), "Documents with shared header but different content must have distinct drawer IDs" + assert result1["drawer_id"] != result2["drawer_id"], ( + "Documents with shared header but different content must have distinct drawer IDs" + ) def test_delete_drawer(self, monkeypatch, config, palace_path, seeded_collection, kg): _patch_mcp_server(monkeypatch, config, kg) @@ -1560,9 +1683,9 @@ class TestCacheInvalidation: all_calls = captured["get"] + captured["create"] assert all_calls, "expected get_collection or create_collection to be called" for kwargs in all_calls: - assert ( - "embedding_function" in kwargs - ), f"missing embedding_function= in chromadb call: {kwargs}" + assert "embedding_function" in kwargs, ( + f"missing embedding_function= in chromadb call: {kwargs}" + ) assert kwargs["embedding_function"] is not None # Same expectation on the create=False (cache-miss) reopen path. From a1d2483145dcd9da19a06761bdcf33cd17126d35 Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Mon, 11 May 2026 18:52:35 +0200 Subject: [PATCH 13/64] Reject zero-byte HNSW link lists with payload --- mempalace/backends/chroma.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/mempalace/backends/chroma.py b/mempalace/backends/chroma.py index fe36f34..ab9d85d 100644 --- a/mempalace/backends/chroma.py +++ b/mempalace/backends/chroma.py @@ -70,8 +70,34 @@ def _hnsw_link_to_data_ratio(seg_dir: str) -> Optional[float]: return link_size / data_size +def _hnsw_link_lists_is_usable_for_payload(seg_dir: str) -> bool: + """Return False when a non-trivial HNSW payload lacks usable link lists. + + A missing or empty link_lists.bin is acceptable only for a fresh/empty + segment. Once data_level0.bin has real payload, a zero-byte link_lists.bin + is not a harmless async-flush shape: ChromaDB can later hand the broken + graph to hnswlib and crash in native code. + """ + data_path = os.path.join(seg_dir, "data_level0.bin") + link_path = os.path.join(seg_dir, "link_lists.bin") + + try: + if not os.path.isfile(data_path): + return True + + data_size = os.path.getsize(data_path) + if data_size <= _HNSW_MISSING_METADATA_DATA_FLOOR: + return True + + return os.path.isfile(link_path) and os.path.getsize(link_path) > 0 + except OSError: + return False + + def _hnsw_payload_appears_sane(seg_dir: str) -> bool: """Return False when HNSW payload files are structurally implausible.""" + if not _hnsw_link_lists_is_usable_for_payload(seg_dir): + return False ratio = _hnsw_link_to_data_ratio(seg_dir) return ratio is None or ratio <= _HNSW_LINK_TO_DATA_MAX_RATIO From bc7fe8884619b840229c980c08ab468f4f255ea8 Mon Sep 17 00:00:00 2001 From: fatkobra <55045047+fatkobra@users.noreply.github.com> Date: Mon, 11 May 2026 19:06:05 +0200 Subject: [PATCH 14/64] Add regression tests for zero-byte HNSW link lists --- tests/test_hnsw_payload_health.py | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/test_hnsw_payload_health.py b/tests/test_hnsw_payload_health.py index 0af440a..306b3ec 100644 --- a/tests/test_hnsw_payload_health.py +++ b/tests/test_hnsw_payload_health.py @@ -111,3 +111,50 @@ def test_quarantine_leaves_reasonable_payload_in_place(tmp_path): assert moved == [] assert seg_dir.exists() + + +def test_segment_health_rejects_zero_byte_link_lists_with_payload(tmp_path): + """Regression #1457: real HNSW payload with empty link_lists.bin is corrupt.""" + seg_dir = tmp_path / "11111111-2222-3333-4444-555555555555" + + _write_segment( + seg_dir, + data_size=2_000, + link_size=0, + write_metadata=True, + ) + + assert not _segment_appears_healthy(str(seg_dir)) + + +def test_quarantine_catches_zero_byte_link_lists_when_stale(tmp_path): + """Regression #1457: stale segments with empty link_lists.bin are quarantined.""" + palace = tmp_path / "palace" + palace.mkdir() + + db_path = palace / "chroma.sqlite3" + db_path.write_text("sqlite placeholder") + + seg_dir = palace / "11111111-2222-3333-4444-555555555555" + _write_segment( + seg_dir, + data_size=2_000, + link_size=0, + write_metadata=True, + ) + + hnsw_time = 1_700_000_000 + sqlite_time = hnsw_time + 1_000 + os.utime(seg_dir / "data_level0.bin", (hnsw_time, hnsw_time)) + os.utime(db_path, (sqlite_time, sqlite_time)) + + moved = quarantine_stale_hnsw(str(palace), stale_seconds=300) + + assert len(moved) == 1 + assert not seg_dir.exists() + + moved_path = Path(moved[0]) + assert moved_path.exists() + assert moved_path.name.startswith( + "11111111-2222-3333-4444-555555555555.drift-" + ) From a26e465894b5550976430056620ef655b1fcca42 Mon Sep 17 00:00:00 2001 From: jp Date: Mon, 11 May 2026 05:56:21 -0700 Subject: [PATCH 15/64] fix(repair): coerce empty metadata to sentinel in both rebuild paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two functions construct the metadatas[] list that gets fed to chromadb's upsert/add, both vulnerable to the same ValueError: ValueError: Expected metadata to be a non-empty dict, got 0 metadata attributes in add. chromadb 1.5.x's validate_metadata rejects both `None` and `{}` entries — see chromadb/api/types.py:validate_metadata (line ~1071). This commit patches both: 1. `_extract_drawers` (line ~131) — the chromadb-collection-based extractor, used when the source palace's collection is openable via the chromadb client. Sanitizes None/{} entries in the `batch["metadatas"]` list to `{"_repaired_empty_meta": True}` before extending `all_metas`. 2. `_rebuild_one_collection` (line ~813) — the SQLite-direct extract path used by `rebuild_from_sqlite()`, invoked when the source palace can't be opened via chromadb (the recovery path for palaces with corrupt HNSW segments). Old code was: metas.append(meta if meta else {}) The trailing `{}` was the bug; chromadb 1.5.x rejects empty dicts the same as None. Replaced with the same sentinel. Why `_repaired_empty_meta: True` as the sentinel: - Satisfies chromadb's non-empty-dict requirement - Bool-valued (valid chromadb metadata type, trivially serializable) - Namespaced + descriptive so an operator can find which drawers were coerced via `where={"_repaired_empty_meta": True}` later - Idempotent on re-runs (a future repair over a sanitized palace sees the sentinel as already-valid) Verified on a 151,478-drawer production palace that previously crashed at drawer 120,000 in both extract paths. Fixes #1458 Co-Authored-By: Claude Opus 4.7 (1M context) --- mempalace/repair.py | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/mempalace/repair.py b/mempalace/repair.py index dd4c46a..7a90dbc 100644 --- a/mempalace/repair.py +++ b/mempalace/repair.py @@ -139,7 +139,17 @@ def _extract_drawers(col, total: int, batch_size: int): break all_ids.extend(batch["ids"]) all_docs.extend(batch["documents"]) - all_metas.extend(batch["metadatas"]) + # chromadb 1.5.x's upsert validates that every metadatas[i] is a + # non-empty dict (chromadb/api/types.py:validate_metadata). Drawers + # extracted from sqlite ground truth can come back with None or {} + # for sparse historical writes — coerce those to a sentinel so the + # rebuild upsert can complete instead of raising ValueError ~80% + # through a multi-hour run. See #1458 for full context. + sanitized_metas = [ + m if (isinstance(m, dict) and len(m) > 0) else {"_repaired_empty_meta": True} + for m in batch["metadatas"] + ] + all_metas.extend(sanitized_metas) offset += len(batch["ids"]) return all_ids, all_docs, all_metas @@ -806,11 +816,14 @@ def _rebuild_one_collection( for emb_id, doc, meta in extract_via_sqlite(source_palace, collection_name): ids.append(emb_id) docs.append(doc or "") - # chromadb 1.5.x rejects None entries in the metadatas list - # but accepts empty dicts. Mempalace drawers always carry at - # least wing/room, so this branch is defensive — corruption - # in embedding_metadata could yield an emb_id with no rows. - metas.append(meta if meta else {}) + # chromadb 1.5.x rejects both None and empty-dict entries in + # the metadatas list (ValueError: Expected metadata to be a + # non-empty dict). Mempalace drawers always carry at least + # wing/room, so this branch is defensive — corruption in + # embedding_metadata could yield an emb_id with no rows. + # Coerce to a sentinel that satisfies validation and is + # discoverable later via `where={"_repaired_empty_meta": True}`. + metas.append(meta if (meta and len(meta) > 0) else {"_repaired_empty_meta": True}) if len(ids) >= batch_size: _flush() _flush() From 5d95656b6be98dd6dbdc1064e434e67dd2d82cb9 Mon Sep 17 00:00:00 2001 From: jp Date: Mon, 11 May 2026 12:10:48 -0700 Subject: [PATCH 16/64] fix(backends/chroma): catch-all metadata sanitizer in add/upsert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Belt-and-suspenders on top of the repair.py sanitization in the previous commit. A 151,478-drawer rebuild test still failed at ~120K with the same `ValueError: Expected metadata to be a non-empty dict` from chromadb, even with the repair.py sanitizers in place. Traceback: mempalace/backends/chroma.py:add → chromadb Collection.add → validate_insert_record_set → validate_metadatas → validate_metadata → ValueError Likely cause: chromadb's `upsert()` internally calls `add()` for new records, and somewhere between repair.py's batch upsert and chromadb's final write, the metadatas list gets reprocessed in a way that re-introduces empty/None entries. Sanitizing at the chromadb-client chokepoint catches everything: no caller can leak bad metadata regardless of upstream sanitization state. Same `{"_repaired_empty_meta": True}` sentinel, searchable via `where={"_repaired_empty_meta": True}`. Cost: one list comprehension per write call; negligible vs the embedding + HNSW work each upsert already does. Co-Authored-By: Claude Opus 4.7 (1M context) --- mempalace/backends/chroma.py | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/mempalace/backends/chroma.py b/mempalace/backends/chroma.py index fe36f34..499d000 100644 --- a/mempalace/backends/chroma.py +++ b/mempalace/backends/chroma.py @@ -873,10 +873,30 @@ class ChromaCollection(BaseCollection): # Writes # ------------------------------------------------------------------ + @staticmethod + def _sanitize_metadatas_for_chromadb(metadatas): + """chromadb 1.5.x rejects None and empty-dict entries in the metadatas + list (ValueError: Expected metadata to be a non-empty dict, got 0 + metadata attributes in add). Coerce any such entry to a sentinel so + the write succeeds. Operators can later locate coerced drawers via + ``where={"_repaired_empty_meta": True}``. + + This is the chokepoint catch-all: even if a caller's own sanitizer + misses a case (or skips for performance), reaching the chromadb + client always goes through here first. + """ + if metadatas is None: + return None + return [ + m if (isinstance(m, dict) and len(m) > 0) else {"_repaired_empty_meta": True} + for m in metadatas + ] + def add(self, *, documents, ids, metadatas=None, embeddings=None): kwargs: dict[str, Any] = {"documents": documents, "ids": ids} - if metadatas is not None: - kwargs["metadatas"] = metadatas + sanitized = self._sanitize_metadatas_for_chromadb(metadatas) + if sanitized is not None: + kwargs["metadatas"] = sanitized if embeddings is not None: kwargs["embeddings"] = embeddings with self._write_lock(): @@ -884,8 +904,9 @@ class ChromaCollection(BaseCollection): def upsert(self, *, documents, ids, metadatas=None, embeddings=None): kwargs: dict[str, Any] = {"documents": documents, "ids": ids} - if metadatas is not None: - kwargs["metadatas"] = metadatas + sanitized = self._sanitize_metadatas_for_chromadb(metadatas) + if sanitized is not None: + kwargs["metadatas"] = sanitized if embeddings is not None: kwargs["embeddings"] = embeddings with self._write_lock(): From 0a1adf9962b48d494af7f77cb2059cba767c7b4d Mon Sep 17 00:00:00 2001 From: jp Date: Mon, 11 May 2026 14:17:07 -0700 Subject: [PATCH 17/64] test(repair): unit coverage for empty-metadata sanitization in _extract_drawers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses @Copilot's review feedback on #1459. Five tests: - test_extract_drawers_preserves_valid_metadata: non-empty dict passes through unchanged (regression guard against breaking happy path). - test_extract_drawers_sanitizes_none_metadata: None entries coerce to {"_repaired_empty_meta": True} (the core fix). - test_extract_drawers_sanitizes_empty_dict_metadata: empty dict {} entries also coerce to the sentinel (chromadb 1.5.x rejects both shapes equally). - test_extract_drawers_sanitization_preserves_alignment: critical invariant — ids[i] / documents[i] / metadatas[i] stay in lockstep through the sanitizer; mis-pairing would silently corrupt rebuilds. - test_extract_drawers_multiple_batches: pagination boundary correctness (sanitizer applied per-batch, no drops/duplicates). Verified passing locally against mempalace fork main + chromadb 1.5.8 in the palace-daemon venv (5 passed, 67 deselected in 1.88s). Co-Authored-By: Claude Opus 4.7 (1M context) --- tests/test_repair.py | 88 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/tests/test_repair.py b/tests/test_repair.py index 9507c5d..144d907 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -76,6 +76,94 @@ def test_paginate_ids_offset_exception_fallback(): assert "id1" in ids +# ── _extract_drawers ────────────────────────────────────────────────── + + +def test_extract_drawers_preserves_valid_metadata(): + """Non-empty dict metadata passes through unchanged.""" + col = MagicMock() + col.get.return_value = { + "ids": ["id1", "id2"], + "documents": ["doc1", "doc2"], + "metadatas": [{"wing": "a", "room": "1"}, {"wing": "b", "room": "2"}], + } + all_ids, all_docs, all_metas = repair._extract_drawers(col, total=2, batch_size=2) + assert all_ids == ["id1", "id2"] + assert all_docs == ["doc1", "doc2"] + assert all_metas == [{"wing": "a", "room": "1"}, {"wing": "b", "room": "2"}] + + +def test_extract_drawers_sanitizes_none_metadata(): + """None entries in metadatas are coerced to the sentinel dict. + + chromadb 1.5.x's `validate_metadata` raises `ValueError: Expected metadata + to be a non-empty dict, got 0 metadata attributes in add.` if it sees a + None entry; the sanitizer keeps the rebuild upsert from crashing. + """ + col = MagicMock() + col.get.return_value = { + "ids": ["id1", "id2", "id3"], + "documents": ["doc1", "doc2", "doc3"], + "metadatas": [{"wing": "a"}, None, {"wing": "c"}], + } + _, _, all_metas = repair._extract_drawers(col, total=3, batch_size=3) + assert all_metas[0] == {"wing": "a"} + assert all_metas[1] == {"_repaired_empty_meta": True} + assert all_metas[2] == {"wing": "c"} + + +def test_extract_drawers_sanitizes_empty_dict_metadata(): + """Empty dict {} entries are coerced to the sentinel dict. + + chromadb 1.5.x rejects `{}` the same way it rejects `None`. The comment + in the previous code path mistakenly assumed otherwise. + """ + col = MagicMock() + col.get.return_value = { + "ids": ["id1", "id2"], + "documents": ["doc1", "doc2"], + "metadatas": [{}, {"wing": "b"}], + } + _, _, all_metas = repair._extract_drawers(col, total=2, batch_size=2) + assert all_metas[0] == {"_repaired_empty_meta": True} + assert all_metas[1] == {"wing": "b"} + + +def test_extract_drawers_sanitization_preserves_alignment(): + """Sanitized output keeps the same length and ordering as input. + + Critical invariant: ids[i] / documents[i] / metadatas[i] must stay in + lockstep through the sanitizer; otherwise the rebuild upsert mis-pairs + documents with metadata. + """ + col = MagicMock() + col.get.return_value = { + "ids": ["id1", "id2", "id3", "id4"], + "documents": ["d1", "d2", "d3", "d4"], + "metadatas": [None, {"k": "v"}, {}, None], + } + all_ids, all_docs, all_metas = repair._extract_drawers(col, total=4, batch_size=4) + assert len(all_ids) == len(all_docs) == len(all_metas) == 4 + assert all_ids == ["id1", "id2", "id3", "id4"] + assert all_metas[0] == {"_repaired_empty_meta": True} + assert all_metas[1] == {"k": "v"} + assert all_metas[2] == {"_repaired_empty_meta": True} + assert all_metas[3] == {"_repaired_empty_meta": True} + + +def test_extract_drawers_multiple_batches(): + """Pagination handles batch boundaries without losing/duplicating rows.""" + col = MagicMock() + col.get.side_effect = [ + {"ids": ["id1", "id2"], "documents": ["d1", "d2"], "metadatas": [{"a": 1}, None]}, + {"ids": ["id3"], "documents": ["d3"], "metadatas": [{}]}, + {"ids": [], "documents": [], "metadatas": []}, + ] + all_ids, all_docs, all_metas = repair._extract_drawers(col, total=3, batch_size=2) + assert all_ids == ["id1", "id2", "id3"] + assert all_metas == [{"a": 1}, {"_repaired_empty_meta": True}, {"_repaired_empty_meta": True}] + + # ── scan_palace ─────────────────────────────────────────────────────── From 74cd1c375111c340de3fad89c517742be1222053 Mon Sep 17 00:00:00 2001 From: jp Date: Mon, 11 May 2026 16:03:39 -0700 Subject: [PATCH 18/64] perf(convo_miner): bulk pre-fetch already-mined set instead of N WHERE queries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mine_convos was calling file_already_mined() once per file inside the main loop. On a 150k-drawer palace, each per-file query (`collection.get(where={"source_file": X}, limit=1)`) costs ~2 seconds because chromadb has to scan the metadata index. A 2000-transcript directory took >1h of wall-clock just to decide every file should be skipped — and pegged multiple cores doing so, starving the daemon's other endpoints. bulk_check_mined() already existed for exactly this anti-pattern (its docstring says "Callers can check membership and compare mtimes locally instead of issuing one ChromaDB query per file") but only the project miner used it; the convo miner kept the slow per-file path. This patch adds a third helper, prefetch_mined_set(), that mirrors file_already_mined()'s version-gate semantics (the check_mtime=False branch used by mine_convos) and returns a set[str] for O(1) lookups. mine_convos now calls it once before the loop; the loop body becomes a set-membership check. Observed on a 172k-drawer palace probing 10 files: before: 21.2s (2.12s/file) after: single bulk pass should be 30–60s for the whole 172k scan, then 2000 O(1) checks ≈ free file_already_mined() is kept for callers that genuinely need the per-file semantics (the post-lock race-check in _file_chunks_locked at convo_miner.py:350 still uses it intentionally). Surfaced via jphein/familiar.realm.watch foundation-rework debugging on 2026-05-11. Originally filed as #51. --- mempalace/convo_miner.py | 12 ++++++-- mempalace/palace.py | 64 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index 915b4d1..ea846c4 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -23,6 +23,7 @@ from .palace import ( file_already_mined, get_collection, mine_lock, + prefetch_mined_set, ) logger = logging.getLogger("mempalace_mcp") @@ -418,6 +419,13 @@ def mine_convos( collection = get_collection(palace_path) if not dry_run else None + # Bulk pre-fetch already-mined set in one paginated pass instead of + # `len(files)` separate WHERE-source_file queries. On a 150k-drawer + # palace each per-file query costs ~2s, so a 2000-file sweep used to + # spend >1h just deciding to skip. prefetch_mined_set() does the same + # decisions in a single scan; loop body becomes an O(1) set check. + mined_set: set[str] = prefetch_mined_set(collection) if not dry_run else set() + total_drawers = 0 files_skipped = 0 room_counts = defaultdict(int) @@ -425,8 +433,8 @@ def mine_convos( for i, filepath in enumerate(files, 1): source_file = str(filepath) - # Skip if already filed - if not dry_run and file_already_mined(collection, source_file): + # Skip if already filed at current NORMALIZE_VERSION + if not dry_run and source_file in mined_set: files_skipped += 1 continue diff --git a/mempalace/palace.py b/mempalace/palace.py index 7ed315c..38c3979 100644 --- a/mempalace/palace.py +++ b/mempalace/palace.py @@ -562,3 +562,67 @@ def file_already_mined(collection, source_file: str, check_mtime: bool = False) return True except Exception: return False + + +def bulk_check_mined(collection) -> dict[str, float]: + """Pre-fetch source_file/source_mtime pairs for all documents in the collection. + + Returns a dict mapping source_file -> source_mtime (as float) for every + document that has both fields. Callers can check membership and compare + mtimes locally instead of issuing one ChromaDB query per file. + + Fetches the full collection in paginated batches (like palace_graph.py) + since a WHERE-IN filter on thousands of paths is not supported by ChromaDB. + """ + mined: dict[str, float] = {} + try: + total = collection.count() + offset = 0 + while offset < total: + batch = collection.get(limit=1000, offset=offset, include=["metadatas"]) + for meta in batch["metadatas"]: + src = meta.get("source_file") + mtime = meta.get("source_mtime") + if src and mtime is not None: + mined[src] = float(mtime) + if not batch["ids"]: + break + offset += len(batch["ids"]) + except Exception: + logger.warning("bulk_check_mined: partial fetch, %d files loaded", len(mined)) + return mined + + +def prefetch_mined_set(collection) -> set[str]: + """Pre-fetch the set of source_files already mined at the current NORMALIZE_VERSION. + + Mirrors file_already_mined()'s version-gate semantics (check_mtime=False + branch) but in one bulk pass instead of one ChromaDB query per file. + Returns a set of source_file paths whose stored drawers are at or above + NORMALIZE_VERSION; callers do `if path in result_set: skip`. + + The convo miner walks thousands of transcript files; per-file + `collection.get(where={"source_file": X})` costs ~2s on a 150k-drawer + palace, making a 2000-file sweep take >1h of pure skip-checking. This + helper drops that to a single paginated scan plus O(1) lookups. + """ + mined: set[str] = set() + try: + total = collection.count() + offset = 0 + while offset < total: + batch = collection.get(limit=1000, offset=offset, include=["metadatas"]) + for meta in batch["metadatas"]: + src = meta.get("source_file") + if not src: + continue + # Same default as file_already_mined: missing version == 1 + version = meta.get("normalize_version", 1) + if version >= NORMALIZE_VERSION: + mined.add(src) + if not batch["ids"]: + break + offset += len(batch["ids"]) + except Exception: + logger.warning("prefetch_mined_set: partial fetch, %d files loaded", len(mined)) + return mined From 251c5a0314c376e5a3ba7e9d38e2ad7b99414001 Mon Sep 17 00:00:00 2001 From: jp Date: Tue, 12 May 2026 20:20:35 -0700 Subject: [PATCH 19/64] feat(repair): rebuild_index accepts progress callback; default prints ETA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously rebuild_index() printed "Staged N/M" / "Re-filed N/M" lines with no time information, leaving operators to do mental math against wall-clock to estimate completion on a large palace. On a 183k-drawer rebuild, it's the difference between "this is a 20-min job" and "this is an 8-hour job" — non-trivial scheduling information that the function already has and could easily share. This patch: 1. Adds a `progress: Optional[Callable[[str], None]] = None` parameter to `rebuild_index()`. Defaults to a new `_DefaultProgress` class when omitted (backward-compatible default behavior — same content plus ETA decoration). 2. `_DefaultProgress.__call__` recognizes `Staged N/M` and `Re-filed N/M` lines via regex, computes elapsed/rate/ETA, and appends them: Staged 5000/182953 drawers... (elapsed 7m, rate 11.3/s, ETA 4h) Non-progress lines (e.g. "Backing up chroma.sqlite3...") pass through unchanged. 3. The clock + baseline counter reset at the stage→refile transition so refile-phase rate isn't muddied by the slower stage phase (refile re-embeds the same drawers and may run at different throughput). 4. Replaces the in-function `print(...)` status calls with `progress(...)` so a custom callable receives the full status stream — not just the batch progress lines. 5. Passes `progress=progress` (instead of hardcoded `progress=print`) into `_rebuild_collection_via_temp`. Use cases for a custom `progress` callable: - Daemon-side capture for HTTP `/repair/status` (this is the motivating case — palace-daemon was tailing the output to surface progress to operators via the status endpoint; a callback avoids stdout capture trickery) - Test silence: `progress=lambda *_: None` - Custom formatting: structured logging, JSON event stream, etc. The default behavior is unchanged for callers that omit the parameter; they just get a nicer message format. Closes #1485. --- mempalace/repair.py | 129 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 105 insertions(+), 24 deletions(-) diff --git a/mempalace/repair.py b/mempalace/repair.py index 7a90dbc..ef781b6 100644 --- a/mempalace/repair.py +++ b/mempalace/repair.py @@ -36,7 +36,8 @@ import sqlite3 import time from collections import defaultdict from datetime import datetime -from typing import Iterator, Optional +import re +from typing import Callable, Iterator, Optional from chromadb.errors import NotFoundError as ChromaNotFoundError @@ -613,10 +614,82 @@ def maybe_repair_poisoned_max_seq_id_before_rebuild( ) +_PROGRESS_RE_STAGED = re.compile(r"Staged\s+(\d+)/(\d+)") +_PROGRESS_RE_REFILED = re.compile(r"Re-filed\s+(\d+)/(\d+)") + + +def _format_eta(seconds: float) -> str: + """Pretty-print an ETA in the smallest reasonable unit.""" + if seconds < 60: + return f"{seconds:.0f}s" + if seconds < 3600: + return f"{seconds / 60:.0f}m" + return f"{seconds / 3600:.1f}h" + + +class _DefaultProgress: + """Default ``progress`` callable for :func:`rebuild_index`. + + Behaves like ``print`` for non-progress lines. For ``"Staged N/M"`` / + ``"Re-filed N/M"`` lines it appends elapsed/rate/ETA to give the + operator a sense of how long the rebuild has left: + + Staged 5000/182953 drawers... (elapsed 7m, rate 11.3/s, ETA 4h) + + The clock resets at the stage→refile transition so the rate is + accurate within each phase (refile re-embeds from scratch and runs + at potentially different throughput than stage). + """ + + def __init__(self): + self._start: Optional[float] = None + self._phase: Optional[str] = None + self._initial_completed: int = 0 + + def __call__(self, msg) -> None: + msg = str(msg) + decorated = self._maybe_decorate(msg) + print(decorated) + + def _maybe_decorate(self, msg: str) -> str: + for pattern, phase in ( + (_PROGRESS_RE_STAGED, "stage"), + (_PROGRESS_RE_REFILED, "refile"), + ): + m = pattern.search(msg) + if m is None: + continue + completed = int(m.group(1)) + expected = int(m.group(2)) + return msg + self._eta_suffix(phase, completed, expected) + return msg + + def _eta_suffix(self, phase: str, completed: int, expected: int) -> str: + now = time.monotonic() + # Reset clock + baseline at first call OR at phase transition, + # so refile-phase rate isn't muddied by the slower stage phase. + if self._phase != phase: + self._phase = phase + self._start = now + self._initial_completed = completed + elapsed = now - (self._start or now) + done_this_phase = completed - self._initial_completed + rate = done_this_phase / elapsed if elapsed > 0 and done_this_phase > 0 else 0.0 + remaining = max(0, expected - completed) + if rate <= 0: + return f" (elapsed {_format_eta(elapsed)})" + eta = remaining / rate + return ( + f" (elapsed {_format_eta(elapsed)}, " + f"rate {rate:.1f}/s, ETA {_format_eta(eta)})" + ) + + def rebuild_index( palace_path=None, confirm_truncation_ok: bool = False, collection_name: Optional[str] = None, + progress: Optional[Callable[[str], None]] = None, ): """Rebuild the HNSW index from scratch. @@ -630,18 +703,26 @@ def rebuild_index( Set to ``True`` only when you have independently verified that the palace genuinely contains exactly the extracted number of drawers (typically only a concern for palaces sized at exactly 10 000 rows). + + ``progress`` is the callable used for status output. Defaults to + :class:`_DefaultProgress` which prints with elapsed/rate/ETA + annotations on ``Staged N/M`` and ``Re-filed N/M`` lines. Pass a + custom callable (e.g. a daemon-side capture for HTTP status, or a + silent ``lambda *_: None`` for tests) to override. """ + if progress is None: + progress = _DefaultProgress() palace_path = palace_path or _get_palace_path() collection_name = collection_name or _drawers_collection_name() if not os.path.isdir(palace_path): - print(f"\n No palace found at {palace_path}") + progress(f"\n No palace found at {palace_path}") return - print(f"\n{'=' * 55}") - print(" MemPalace Repair — Index Rebuild") - print(f"{'=' * 55}\n") - print(f" Palace: {palace_path}") + progress(f"\n{'=' * 55}") + progress(" MemPalace Repair — Index Rebuild") + progress(f"{'=' * 55}\n") + progress(f" Palace: {palace_path}") # Run the SQLite integrity preflight before any chromadb client open. # ChromaDB's rust binding raises pyo3_runtime.PanicException (which is @@ -666,21 +747,21 @@ def rebuild_index( col = backend.get_collection(palace_path, collection_name) total = col.count() except Exception as e: - print(f" Error reading palace: {e}") - print(" Palace may need to be re-mined from source files.") + progress(f" Error reading palace: {e}") + progress(" Palace may need to be re-mined from source files.") return - print(f" Drawers found: {total}") + progress(f" Drawers found: {total}") if total == 0: - print(" Nothing to repair.") + progress(" Nothing to repair.") return # Extract all drawers in batches - print("\n Extracting drawers...") + progress("\n Extracting drawers...") batch_size = 5000 all_ids, all_docs, all_metas = _extract_drawers(col, total, batch_size) - print(f" Extracted {len(all_ids)} drawers") + progress(f" Extracted {len(all_ids)} drawers") # ── #1208 guard ────────────────────────────────────────────────── # Refuse to ``delete_collection`` + rebuild when extraction looks @@ -694,19 +775,19 @@ def rebuild_index( collection_name=collection_name, ) except TruncationDetected as e: - print(e.message) + progress(e.message) return # Back up ONLY the SQLite database, not the bloated HNSW files sqlite_path = os.path.join(palace_path, "chroma.sqlite3") backup_path = sqlite_path + ".backup" if os.path.exists(sqlite_path): - print(f" Backing up chroma.sqlite3 ({os.path.getsize(sqlite_path) / 1e6:.0f} MB)...") + progress(f" Backing up chroma.sqlite3 ({os.path.getsize(sqlite_path) / 1e6:.0f} MB)...") shutil.copy2(sqlite_path, backup_path) - print(f" Backup: {backup_path}") + progress(f" Backup: {backup_path}") # Rebuild with correct HNSW settings - print(" Rebuilding collection with hnsw:space=cosine...") + progress(" Rebuilding collection with hnsw:space=cosine...") try: filed = _rebuild_collection_via_temp( backend, @@ -716,23 +797,23 @@ def rebuild_index( all_metas, batch_size, collection_name=collection_name, - progress=print, + progress=progress, ) except RebuildCollectionError as e: - print(f"\n ERROR during rebuild: {e}") - print(" Rebuild aborted before completion.") + progress(f"\n ERROR during rebuild: {e}") + progress(" Rebuild aborted before completion.") if e.live_replaced and os.path.exists(backup_path): - print(f" Restoring from backup: {backup_path}") + progress(f" Restoring from backup: {backup_path}") try: _close_chroma_handles(palace_path, backend=backend) _delete_collection_if_exists(backend, palace_path, collection_name) shutil.copy2(backup_path, sqlite_path) - print(" Backup restored. Palace is back to pre-repair state.") + progress(" Backup restored. Palace is back to pre-repair state.") except Exception as restore_error: - print(f" Backup restore failed: {restore_error}") - print(f" Manual restore required from: {backup_path}") + progress(f" Backup restore failed: {restore_error}") + progress(f" Manual restore required from: {backup_path}") elif e.live_replaced: - print(" No backup available. Re-mine from source files to recover.") + progress(" No backup available. Re-mine from source files to recover.") else: print(" Live collection was not replaced; leaving the original palace untouched.") raise From 24e88437c4663b717b8fcf4d123f95d660fbe988 Mon Sep 17 00:00:00 2001 From: jp Date: Tue, 12 May 2026 20:50:44 -0700 Subject: [PATCH 20/64] style: ruff format repair.py (fix #1487 CI lint) --- mempalace/repair.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/mempalace/repair.py b/mempalace/repair.py index ef781b6..c5ad068 100644 --- a/mempalace/repair.py +++ b/mempalace/repair.py @@ -598,9 +598,7 @@ def maybe_repair_poisoned_max_seq_id_before_rebuild( " This can make writes report success while embeddings_queue grows " "and embeddings stay static." ) - print( - " Running the non-destructive max_seq_id repair instead of rebuilding " "the collection." - ) + print(" Running the non-destructive max_seq_id repair instead of rebuilding the collection.") print( " Queued writes remain in chroma.sqlite3 for Chroma to drain after " "the bookmark is unpoisoned." @@ -679,10 +677,7 @@ class _DefaultProgress: if rate <= 0: return f" (elapsed {_format_eta(elapsed)})" eta = remaining / rate - return ( - f" (elapsed {_format_eta(elapsed)}, " - f"rate {rate:.1f}/s, ETA {_format_eta(eta)})" - ) + return f" (elapsed {_format_eta(elapsed)}, rate {rate:.1f}/s, ETA {_format_eta(eta)})" def rebuild_index( From af7b6dfebce4bf360fa16c9fba1b159fee633cdf Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 10 May 2026 21:05:19 +0500 Subject: [PATCH 21/64] fix: drop leaked PYTHONPATH on package init (#1423) Venvs do not strip PYTHONPATH from inheritance. On multi-Python systems where PYTHONPATH points at a different Python's site-packages, transitive imports of compiled extensions (pydantic_core, chromadb_rust_bindings) load the wrong ABI and crash with ModuleNotFoundError on pydantic_core._pydantic_core. Place the pop in mempalace/__init__.py (instead of cli.py as the reporter proposed) so all entry points are covered: the mempalace shell command, python -m mempalace, and import mempalace from a library. Tests: tests/test_init.py runs the strip in a subprocess, parametrized over set / unset PYTHONPATH. Closes #1423. --- mempalace/__init__.py | 10 ++++++++++ tests/test_init.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 tests/test_init.py diff --git a/mempalace/__init__.py b/mempalace/__init__.py index 893a71b..c5a5465 100644 --- a/mempalace/__init__.py +++ b/mempalace/__init__.py @@ -1,6 +1,16 @@ """MemPalace — Give your AI a memory. No API key required.""" import logging +import os + + +def _strip_leaked_pythonpath() -> None: + # Venvs inherit PYTHONPATH; on multi-Python systems it can load + # compiled extensions with the wrong ABI and crash on import. + os.environ.pop("PYTHONPATH", None) + + +_strip_leaked_pythonpath() from .version import __version__ # noqa: E402 diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..6abe5a0 --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,38 @@ +"""__init__-level guards that must take effect before transitive imports.""" + +import os +import subprocess +import sys + +import pytest + + +@pytest.mark.parametrize( + "pythonpath", + [ + "/tmp/some/leaked/path", + None, + ], +) +def test_init_strips_leaked_pythonpath(pythonpath): + """Package init must drop PYTHONPATH before compiled extensions load, + regardless of whether it was set in the parent environment.""" + env = os.environ.copy() + if pythonpath is None: + env.pop("PYTHONPATH", None) + else: + env["PYTHONPATH"] = pythonpath + result = subprocess.run( + [ + sys.executable, + "-c", + "import mempalace, os; print(repr(os.environ.get('PYTHONPATH')))", + ], + env=env, + capture_output=True, + text=True, + check=True, + ) + assert ( + result.stdout.strip() == "None" + ), f"PYTHONPATH not stripped (input was {pythonpath!r}): {result.stdout!r}" From 765478d37a161052209b59efa826f2a76ac3eb76 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 10 May 2026 21:29:43 +0500 Subject: [PATCH 22/64] fix(init): also strip leaked sys.path entries (#1423) Popping PYTHONPATH from os.environ alone is insufficient: the interpreter populates sys.path from PYTHONPATH at startup, before package init runs. Transitive imports of compiled extensions (pydantic_core, chromadb_rust_bindings) would still resolve from the leaked path even after the env var is cleared. Now also remove the matching entries from sys.path so the import search path no longer contains the wrong Python's site-packages. Test extended with a multi-path PYTHONPATH case and assertions on both os.environ and sys.path after import. --- mempalace/__init__.py | 14 +++++++++++--- tests/test_init.py | 26 +++++++++++++++++--------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/mempalace/__init__.py b/mempalace/__init__.py index c5a5465..a2ce132 100644 --- a/mempalace/__init__.py +++ b/mempalace/__init__.py @@ -2,12 +2,20 @@ import logging import os +import sys def _strip_leaked_pythonpath() -> None: - # Venvs inherit PYTHONPATH; on multi-Python systems it can load - # compiled extensions with the wrong ABI and crash on import. - os.environ.pop("PYTHONPATH", None) + # Venvs inherit PYTHONPATH; on multi-Python systems it can cause + # transitive imports to load compiled extensions (pydantic_core, + # chromadb_rust_bindings) from the wrong ABI. Drop the env var + # and remove the sys.path entries the interpreter populated from + # it before the consumer imports anything that ships compiled code. + leaked = os.environ.pop("PYTHONPATH", None) + if not leaked: + return + leaked_entries = {p for p in leaked.split(os.pathsep) if p} + sys.path[:] = [p for p in sys.path if p not in leaked_entries] _strip_leaked_pythonpath() diff --git a/tests/test_init.py b/tests/test_init.py index 6abe5a0..643c067 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -11,28 +11,36 @@ import pytest "pythonpath", [ "/tmp/some/leaked/path", + f"/tmp/leak-a{os.pathsep}/tmp/leak-b", None, ], ) def test_init_strips_leaked_pythonpath(pythonpath): - """Package init must drop PYTHONPATH before compiled extensions load, - regardless of whether it was set in the parent environment.""" + """Package init must clear PYTHONPATH (env) AND remove its entries + from sys.path so compiled-extension imports cannot resolve from a + leaked location.""" env = os.environ.copy() if pythonpath is None: env.pop("PYTHONPATH", None) else: env["PYTHONPATH"] = pythonpath + code = ( + "import mempalace, os, sys; " + f"leaked = {pythonpath!r}; " + "print('ENV:', repr(os.environ.get('PYTHONPATH'))); " + "entries = leaked.split(os.pathsep) if leaked else []; " + "leaked_in_path = any(e in sys.path for e in entries); " + "print('SYSPATH_LEAK:', leaked_in_path)" + ) result = subprocess.run( - [ - sys.executable, - "-c", - "import mempalace, os; print(repr(os.environ.get('PYTHONPATH')))", - ], + [sys.executable, "-c", code], env=env, capture_output=True, text=True, check=True, ) + out = result.stdout + assert "ENV: None" in out, f"PYTHONPATH not cleared (input={pythonpath!r}): {out!r}" assert ( - result.stdout.strip() == "None" - ), f"PYTHONPATH not stripped (input was {pythonpath!r}): {result.stdout!r}" + "SYSPATH_LEAK: False" in out + ), f"sys.path retains leaked entry (input={pythonpath!r}): {out!r}" From c4fdc1ed8cd7df2ee4800d9ec30426102192bf64 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 10 May 2026 21:40:15 +0500 Subject: [PATCH 23/64] fix(init): normalize path comparison for sys.path strip (#1423) Previous commit compared sys.path entries to PYTHONPATH tokens by byte-exact string equality, which let leaks slip through on Windows (case-insensitive paths) and across trailing-separator or whitespace quirks (a leading or trailing space in PYTHONPATH would not match the trimmed sys.path entry the interpreter actually populated). Both sides of the comparison now run through os.path.normcase + os.path.normpath so case differences and trailing separators no longer defeat the filter, and PYTHONPATH tokens are trimmed before the match. Test extended to 6 parametrized cases (single, multi-path, trailing separator, leading pathsep, empty, unset) with explicit ids and stderr included in assertion diagnostics. Synthetic leak placeholder replaces /tmp so the test is portable across CI runners. --- mempalace/__init__.py | 13 +++++++++---- tests/test_init.py | 37 +++++++++++++++++++++++++------------ 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/mempalace/__init__.py b/mempalace/__init__.py index a2ce132..9db4124 100644 --- a/mempalace/__init__.py +++ b/mempalace/__init__.py @@ -9,13 +9,18 @@ def _strip_leaked_pythonpath() -> None: # Venvs inherit PYTHONPATH; on multi-Python systems it can cause # transitive imports to load compiled extensions (pydantic_core, # chromadb_rust_bindings) from the wrong ABI. Drop the env var - # and remove the sys.path entries the interpreter populated from - # it before the consumer imports anything that ships compiled code. + # and remove sys.path entries the interpreter populated from it. + # Comparison normalizes case + separators so Windows paths and + # trailing-separator quirks do not slip through string equality. leaked = os.environ.pop("PYTHONPATH", None) if not leaked: return - leaked_entries = {p for p in leaked.split(os.pathsep) if p} - sys.path[:] = [p for p in sys.path if p not in leaked_entries] + + def _norm(path: str) -> str: + return os.path.normcase(os.path.normpath(path)) + + leaked_entries = {_norm(p.strip()) for p in leaked.split(os.pathsep) if p.strip()} + sys.path[:] = [p for p in sys.path if _norm(p) not in leaked_entries] _strip_leaked_pythonpath() diff --git a/tests/test_init.py b/tests/test_init.py index 643c067..cc47f8c 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -7,18 +7,25 @@ import sys import pytest +_LEAK_PREFIX = "/__mempalace_leak_test_sentinel__" + + @pytest.mark.parametrize( "pythonpath", [ - "/tmp/some/leaked/path", - f"/tmp/leak-a{os.pathsep}/tmp/leak-b", + f"{_LEAK_PREFIX}/single", + f"{_LEAK_PREFIX}/a{os.pathsep}{_LEAK_PREFIX}/b", + f"{_LEAK_PREFIX}/with-trailing{os.sep}", + f"{os.pathsep}{_LEAK_PREFIX}/leading-sep", + "", None, ], + ids=["single", "multi", "trailing-sep", "leading-pathsep", "empty", "unset"], ) def test_init_strips_leaked_pythonpath(pythonpath): - """Package init must clear PYTHONPATH (env) AND remove its entries - from sys.path so compiled-extension imports cannot resolve from a - leaked location.""" + """Package init must clear PYTHONPATH (env) AND remove all of its + leaked entries from sys.path, normalizing case and trailing + separators so Windows and POSIX behave alike.""" env = os.environ.copy() if pythonpath is None: env.pop("PYTHONPATH", None) @@ -28,8 +35,11 @@ def test_init_strips_leaked_pythonpath(pythonpath): "import mempalace, os, sys; " f"leaked = {pythonpath!r}; " "print('ENV:', repr(os.environ.get('PYTHONPATH'))); " - "entries = leaked.split(os.pathsep) if leaked else []; " - "leaked_in_path = any(e in sys.path for e in entries); " + "tokens = leaked.split(os.pathsep) if leaked else []; " + "entries = [t.strip() for t in tokens if t.strip()]; " + "norm = lambda p: os.path.normcase(os.path.normpath(p)); " + "leaked_norm = {norm(e) for e in entries}; " + "leaked_in_path = any(norm(p) in leaked_norm for p in sys.path); " "print('SYSPATH_LEAK:', leaked_in_path)" ) result = subprocess.run( @@ -37,10 +47,13 @@ def test_init_strips_leaked_pythonpath(pythonpath): env=env, capture_output=True, text=True, - check=True, + check=False, ) + diag = ( + f"input={pythonpath!r}; rc={result.returncode}; " + f"stdout={result.stdout!r}; stderr={result.stderr!r}" + ) + assert result.returncode == 0, f"subprocess failed: {diag}" out = result.stdout - assert "ENV: None" in out, f"PYTHONPATH not cleared (input={pythonpath!r}): {out!r}" - assert ( - "SYSPATH_LEAK: False" in out - ), f"sys.path retains leaked entry (input={pythonpath!r}): {out!r}" + assert "ENV: None" in out, f"PYTHONPATH not cleared: {diag}" + assert "SYSPATH_LEAK: False" in out, f"sys.path retains leaked entry: {diag}" From d09cd9dab1bd048faa91d242494b4995cb0aa172 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 10 May 2026 21:54:17 +0500 Subject: [PATCH 24/64] fix(init): preserve cwd marker; decouple test (#1423) When PYTHONPATH is `.`, both the leaked entry and the implicit empty-string CWD marker on sys.path normalize to `.`. The previous filter would remove the CWD marker too, silently changing import resolution. The sys.path filter now preserves any empty-string entry unconditionally. Also drop the asymmetric `.strip()` on PYTHONPATH tokens. CPython does not strip whitespace from PYTHONPATH before populating sys.path, so stripping on one side only could let whitespace-padded leaks through. Test extended with a `dot` parametrize case and a dedicated test_init_preserves_cwd_marker_when_pythonpath_collides. Test child code now asserts on the sentinel-prefix substring directly instead of re-implementing the production normalization, so future changes to _norm cannot silently mask test regressions. --- mempalace/__init__.py | 6 ++++-- tests/test_init.py | 44 ++++++++++++++++++++++++++++++++----------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/mempalace/__init__.py b/mempalace/__init__.py index 9db4124..3ad7355 100644 --- a/mempalace/__init__.py +++ b/mempalace/__init__.py @@ -12,6 +12,8 @@ def _strip_leaked_pythonpath() -> None: # and remove sys.path entries the interpreter populated from it. # Comparison normalizes case + separators so Windows paths and # trailing-separator quirks do not slip through string equality. + # The empty-string CWD marker on sys.path is preserved regardless, + # so PYTHONPATH=. does not collapse the implicit current directory. leaked = os.environ.pop("PYTHONPATH", None) if not leaked: return @@ -19,8 +21,8 @@ def _strip_leaked_pythonpath() -> None: def _norm(path: str) -> str: return os.path.normcase(os.path.normpath(path)) - leaked_entries = {_norm(p.strip()) for p in leaked.split(os.pathsep) if p.strip()} - sys.path[:] = [p for p in sys.path if _norm(p) not in leaked_entries] + leaked_entries = {_norm(p) for p in leaked.split(os.pathsep) if p} + sys.path[:] = [p for p in sys.path if not p or _norm(p) not in leaked_entries] _strip_leaked_pythonpath() diff --git a/tests/test_init.py b/tests/test_init.py index cc47f8c..d8ca004 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -17,15 +17,18 @@ _LEAK_PREFIX = "/__mempalace_leak_test_sentinel__" f"{_LEAK_PREFIX}/a{os.pathsep}{_LEAK_PREFIX}/b", f"{_LEAK_PREFIX}/with-trailing{os.sep}", f"{os.pathsep}{_LEAK_PREFIX}/leading-sep", + ".", "", None, ], - ids=["single", "multi", "trailing-sep", "leading-pathsep", "empty", "unset"], + ids=["single", "multi", "trailing-sep", "leading-pathsep", "dot", "empty", "unset"], ) def test_init_strips_leaked_pythonpath(pythonpath): """Package init must clear PYTHONPATH (env) AND remove all of its - leaked entries from sys.path, normalizing case and trailing - separators so Windows and POSIX behave alike.""" + sentinel-prefixed entries from sys.path. Asserts on the sentinel + substring directly so the test does not couple to the production + normalization logic. The dot/empty/unset cases additionally + exercise the early-return / collision paths without crashing.""" env = os.environ.copy() if pythonpath is None: env.pop("PYTHONPATH", None) @@ -33,14 +36,9 @@ def test_init_strips_leaked_pythonpath(pythonpath): env["PYTHONPATH"] = pythonpath code = ( "import mempalace, os, sys; " - f"leaked = {pythonpath!r}; " + f"prefix = {_LEAK_PREFIX!r}; " "print('ENV:', repr(os.environ.get('PYTHONPATH'))); " - "tokens = leaked.split(os.pathsep) if leaked else []; " - "entries = [t.strip() for t in tokens if t.strip()]; " - "norm = lambda p: os.path.normcase(os.path.normpath(p)); " - "leaked_norm = {norm(e) for e in entries}; " - "leaked_in_path = any(norm(p) in leaked_norm for p in sys.path); " - "print('SYSPATH_LEAK:', leaked_in_path)" + "print('SENTINEL_IN_PATH:', any(prefix in (p or '') for p in sys.path))" ) result = subprocess.run( [sys.executable, "-c", code], @@ -56,4 +54,28 @@ def test_init_strips_leaked_pythonpath(pythonpath): assert result.returncode == 0, f"subprocess failed: {diag}" out = result.stdout assert "ENV: None" in out, f"PYTHONPATH not cleared: {diag}" - assert "SYSPATH_LEAK: False" in out, f"sys.path retains leaked entry: {diag}" + assert "SENTINEL_IN_PATH: False" in out, f"sentinel-prefix leak: {diag}" + + +def test_init_preserves_cwd_marker_when_pythonpath_collides(): + """PYTHONPATH='.' normalizes to the same value as the empty-string + CWD marker on sys.path. The strip must remove '.' from sys.path + without collapsing the implicit current-directory entry.""" + env = os.environ.copy() + env["PYTHONPATH"] = "." + code = ( + "import mempalace, sys; " + "print('CWD_IN_PATH:', '' in sys.path); " + "print('DOT_IN_PATH:', '.' in sys.path)" + ) + result = subprocess.run( + [sys.executable, "-c", code], + env=env, + capture_output=True, + text=True, + check=False, + ) + diag = f"rc={result.returncode}; stdout={result.stdout!r}; " f"stderr={result.stderr!r}" + assert result.returncode == 0, f"subprocess failed: {diag}" + assert "CWD_IN_PATH: True" in result.stdout, f"cwd marker dropped: {diag}" + assert "DOT_IN_PATH: False" in result.stdout, f"dot leak survived: {diag}" From 4b1ab507507064ab4b6481481941139dc4fb3a11 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Tue, 12 May 2026 16:01:34 +0500 Subject: [PATCH 25/64] fix(init): keep PYTHONPATH env for embedded callers, strip only in CLI entry points Split the leaked-PYTHONPATH workaround: __init__.py now only filters sys.path (fixes the ABI crash from #1423 at import time), while os.environ.pop("PYTHONPATH") moves to cli:main() and mcp_server:main() where the strip affects only subprocesses we spawn ourselves. Host applications that import mempalace as a library and rely on PYTHONPATH for their own child subprocesses are no longer affected. Refs #1423. --- mempalace/__init__.py | 26 +++++++++++++------- mempalace/cli.py | 6 +++++ mempalace/mcp_server.py | 5 ++++ tests/test_cli.py | 52 ++++++++++++++++++++++++++++++++++++++++ tests/test_init.py | 35 ++++++++++++++++++++------- tests/test_mcp_server.py | 47 ++++++++++++++++++++++++++++++++++++ 6 files changed, 154 insertions(+), 17 deletions(-) diff --git a/mempalace/__init__.py b/mempalace/__init__.py index 3ad7355..9e8c9d0 100644 --- a/mempalace/__init__.py +++ b/mempalace/__init__.py @@ -5,16 +5,24 @@ import os import sys -def _strip_leaked_pythonpath() -> None: +def _strip_leaked_pythonpath_from_sys_path() -> None: # Venvs inherit PYTHONPATH; on multi-Python systems it can cause # transitive imports to load compiled extensions (pydantic_core, - # chromadb_rust_bindings) from the wrong ABI. Drop the env var - # and remove sys.path entries the interpreter populated from it. - # Comparison normalizes case + separators so Windows paths and - # trailing-separator quirks do not slip through string equality. - # The empty-string CWD marker on sys.path is preserved regardless, - # so PYTHONPATH=. does not collapse the implicit current directory. - leaked = os.environ.pop("PYTHONPATH", None) + # chromadb_rust_bindings) from the wrong ABI. Remove sys.path entries + # the interpreter populated from PYTHONPATH so this process imports + # only the venv's own packages. Comparison normalizes case + separators + # so Windows paths and trailing-separator quirks do not slip through + # string equality. The empty-string CWD marker on sys.path is preserved + # regardless, so PYTHONPATH=. does not collapse the implicit current + # directory. + # + # os.environ is intentionally NOT modified here. CLI entry points + # (mempalace.cli:main, mempalace.mcp_server:main) drop PYTHONPATH from + # the env themselves so any subprocess they spawn starts clean. Host + # applications that embed mempalace as a library (e.g. import + # mempalace.searcher) keep their PYTHONPATH intact for their own + # unrelated subprocesses. + leaked = os.environ.get("PYTHONPATH", None) if not leaked: return @@ -25,7 +33,7 @@ def _strip_leaked_pythonpath() -> None: sys.path[:] = [p for p in sys.path if not p or _norm(p) not in leaked_entries] -_strip_leaked_pythonpath() +_strip_leaked_pythonpath_from_sys_path() from .version import __version__ # noqa: E402 diff --git a/mempalace/cli.py b/mempalace/cli.py index 395130d..0829dc5 100644 --- a/mempalace/cli.py +++ b/mempalace/cli.py @@ -1129,6 +1129,12 @@ def _reconfigure_stdio_utf8_on_windows(): def main(): + # Drop leaked PYTHONPATH so any subprocess the CLI spawns (mine workers, + # repair tooling) starts with a clean env. The sys.path filter in + # mempalace/__init__.py already protects this process from the same + # ABI mismatch; here we extend the protection to children. + os.environ.pop("PYTHONPATH", None) + _reconfigure_stdio_utf8_on_windows() version_label = f"MemPalace {__version__}" diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 85a0170..ede32ab 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -2294,6 +2294,11 @@ def _restore_stdout(): def main(): + # Drop leaked PYTHONPATH so any subprocess this server spawns starts + # with a clean env. The sys.path filter in mempalace/__init__.py + # already protects this process from the same ABI mismatch; here we + # extend the protection to children. + os.environ.pop("PYTHONPATH", None) _restore_stdout() # Force UTF-8 on stdio. MCP JSON-RPC is UTF-8, but Python on Windows # defaults stdin/stdout to the system codepage (e.g. cp1251), which diff --git a/tests/test_cli.py b/tests/test_cli.py index 547286d..492b132 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,8 +1,10 @@ """Tests for mempalace.cli — the main CLI dispatcher.""" import argparse +import os import shlex import sqlite3 +import subprocess import sys from pathlib import Path from unittest.mock import MagicMock, call, patch @@ -24,6 +26,56 @@ from mempalace.cli import ( ) +# ── CLI entry point: PYTHONPATH stripping ──────────────────────────────── + + +_LEAK_PREFIX = "/__mempalace_cli_leak_sentinel__" + + +def test_cli_main_strips_leaked_pythonpath_from_env(): + """mempalace.cli:main must drop PYTHONPATH from the process env so + any subprocess the CLI spawns starts clean. Mirrors the + sys.path-filter test in test_init.py but for the env half of the + split fix. See #1423. + + Asserts ENV_MID between import and main() to prove that main() is + the strip site, not the package import. If a regression moves the + env pop back into __init__.py, ENV_MID would change and this test + would fail.""" + expected_env = f"{_LEAK_PREFIX}/a{os.pathsep}{_LEAK_PREFIX}/b" + env = os.environ.copy() + env["PYTHONPATH"] = expected_env + # Run main() with --version so it exits cleanly without entering any + # subcommand. argparse raises SystemExit on --version; the wrapper + # catches it and prints the post-main PYTHONPATH so the assertion + # is observable. + code = ( + "import os, sys\n" + "from mempalace.cli import main\n" + "print('ENV_MID:', repr(os.environ.get('PYTHONPATH')))\n" + "sys.argv = ['mempalace', '--version']\n" + "try:\n" + " main()\n" + "except SystemExit:\n" + " pass\n" + "print('ENV_AFTER:', repr(os.environ.get('PYTHONPATH')))\n" + ) + result = subprocess.run( + [sys.executable, "-c", code], + env=env, + capture_output=True, + text=True, + check=False, + timeout=30, + ) + diag = f"rc={result.returncode}; stdout={result.stdout!r}; stderr={result.stderr!r}" + assert result.returncode == 0, f"subprocess failed: {diag}" + assert ( + f"ENV_MID: {expected_env!r}" in result.stdout + ), f"package import unexpectedly stripped env (regression in __init__.py): {diag}" + assert "ENV_AFTER: None" in result.stdout, f"CLI did not strip PYTHONPATH: {diag}" + + # ── cmd_status ───────────────────────────────────────────────────────── diff --git a/tests/test_init.py b/tests/test_init.py index d8ca004..bf6c9a4 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -23,12 +23,18 @@ _LEAK_PREFIX = "/__mempalace_leak_test_sentinel__" ], ids=["single", "multi", "trailing-sep", "leading-pathsep", "dot", "empty", "unset"], ) -def test_init_strips_leaked_pythonpath(pythonpath): - """Package init must clear PYTHONPATH (env) AND remove all of its - sentinel-prefixed entries from sys.path. Asserts on the sentinel - substring directly so the test does not couple to the production - normalization logic. The dot/empty/unset cases additionally - exercise the early-return / collision paths without crashing.""" +def test_init_filters_sys_path_from_leaked_pythonpath(pythonpath): + """Package init must remove sentinel-prefixed entries from sys.path + so transitive imports do not pull compiled extensions from the + leaked PYTHONPATH. os.environ['PYTHONPATH'] is left intact so host + applications embedding mempalace as a library keep their env for + their own subprocesses; the env strip lives in the CLI/MCP entry + points (see test_cli.py / test_mcp_server.py). + + Asserts on the sentinel substring directly so the test does not + couple to the production normalization logic. The dot/empty/unset + cases additionally exercise the early-return / collision paths + without crashing.""" env = os.environ.copy() if pythonpath is None: env.pop("PYTHONPATH", None) @@ -37,8 +43,12 @@ def test_init_strips_leaked_pythonpath(pythonpath): code = ( "import mempalace, os, sys; " f"prefix = {_LEAK_PREFIX!r}; " + "mempalace_parent = os.path.dirname(os.path.dirname(mempalace.__file__)); " "print('ENV:', repr(os.environ.get('PYTHONPATH'))); " - "print('SENTINEL_IN_PATH:', any(prefix in (p or '') for p in sys.path))" + "print('SENTINEL_IN_PATH:', any(prefix in (p or '') for p in sys.path)); " + "print('MEMPALACE_PARENT_PRESENT:', any(" + "os.path.normcase(os.path.normpath(p)) == os.path.normcase(os.path.normpath(mempalace_parent)) " + "for p in sys.path if p))" ) result = subprocess.run( [sys.executable, "-c", code], @@ -53,8 +63,17 @@ def test_init_strips_leaked_pythonpath(pythonpath): ) assert result.returncode == 0, f"subprocess failed: {diag}" out = result.stdout - assert "ENV: None" in out, f"PYTHONPATH not cleared: {diag}" + # Env must be preserved verbatim: embedded callers may need it. + expected_env = repr(pythonpath) if pythonpath is not None else repr(None) + assert ( + f"ENV: {expected_env}" in out + ), f"PYTHONPATH should be preserved by package import: {diag}" assert "SENTINEL_IN_PATH: False" in out, f"sentinel-prefix leak: {diag}" + # Filter must not over-strip: the mempalace package itself must remain + # importable, so its parent directory must survive on sys.path. + assert ( + "MEMPALACE_PARENT_PRESENT: True" in out + ), f"filter over-stripped sys.path (mempalace parent gone): {diag}" def test_init_preserves_cwd_marker_when_pythonpath_collides(): diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 5e4ca9a..5b5b9cf 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -9,12 +9,59 @@ via monkeypatch to avoid touching real data. from datetime import datetime import json import os +import subprocess import sys from unittest.mock import MagicMock import pytest +# ── MCP entry point: PYTHONPATH stripping ──────────────────────────────── + + +_MCP_LEAK_PREFIX = "/__mempalace_mcp_leak_sentinel__" + + +def test_mcp_main_strips_leaked_pythonpath_from_env(): + """mempalace.mcp_server:main must drop PYTHONPATH from the process env + so any subprocess this server spawns starts clean. Mirrors the + sys.path-filter test in test_init.py but for the env half of the + split fix. See #1423. + + Asserts ENV_MID between import and main() to prove main() is the + strip site (not __init__.py). The main loop reads JSON-RPC lines + from stdin until EOF; closing stdin makes readline() return '' and + exits the loop cleanly, which lets us observe the post-main env + state.""" + expected_env = f"{_MCP_LEAK_PREFIX}/a{os.pathsep}{_MCP_LEAK_PREFIX}/b" + env = os.environ.copy() + env["PYTHONPATH"] = expected_env + code = ( + "import os, sys\n" + "from mempalace.mcp_server import main\n" + # mcp_server redirects stdout at import time for clean JSON-RPC; + # write the probe to stderr so the subprocess can observe it. + "sys.stderr.write('ENV_MID: ' + repr(os.environ.get('PYTHONPATH')) + '\\n')\n" + "main()\n" + "sys.stderr.write('ENV_AFTER: ' + repr(os.environ.get('PYTHONPATH')) + '\\n')\n" + ) + result = subprocess.run( + [sys.executable, "-c", code], + env=env, + input="", # empty stdin → readline() returns '' → loop breaks + capture_output=True, + text=True, + check=False, + timeout=30, + ) + diag = f"rc={result.returncode}; stdout={result.stdout!r}; stderr={result.stderr!r}" + assert result.returncode == 0, f"subprocess failed: {diag}" + assert ( + f"ENV_MID: {expected_env!r}" in result.stderr + ), f"package import unexpectedly stripped env (regression in __init__.py): {diag}" + assert "ENV_AFTER: None" in result.stderr, f"MCP server did not strip PYTHONPATH: {diag}" + + def _patch_mcp_server(monkeypatch, config, kg): """Patch the mcp_server module globals to use test fixtures.""" from mempalace import mcp_server From 068930b7106cf41fcf35542947b1c49637684061 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Tue, 12 May 2026 16:33:10 +0500 Subject: [PATCH 26/64] test(init): probe sys.path filter in CLI/MCP env strip tests; docstring side effect Three-way assertions in test_cli and test_mcp_server now also assert SENTINEL_IN_PATH is False at import, so a regression in the package sys.path filter is caught by the same test that catches the env pop regression. SystemExit catch is narrowed to exit codes (0, None) so a future argparse change surfaces as a failure instead of being swallowed. cli.py:main and mcp_server.py:main docstrings document the PYTHONPATH pop side effect for callers that invoke main() programmatically. Refs #1423. --- mempalace/cli.py | 9 +++++++++ mempalace/mcp_server.py | 9 +++++++++ tests/test_cli.py | 30 +++++++++++++++++++++--------- tests/test_mcp_server.py | 24 +++++++++++++++++------- 4 files changed, 56 insertions(+), 16 deletions(-) diff --git a/mempalace/cli.py b/mempalace/cli.py index 0829dc5..bd34699 100644 --- a/mempalace/cli.py +++ b/mempalace/cli.py @@ -1129,6 +1129,15 @@ def _reconfigure_stdio_utf8_on_windows(): def main(): + """CLI entry point for the ``mempalace`` console script. + + Side effect: pops ``PYTHONPATH`` from ``os.environ`` (see #1423) so + any subprocess this CLI spawns inherits a clean env. Host applications + that call ``main()`` programmatically should be aware that the parent + process loses ``PYTHONPATH`` as well. Library imports + (``import mempalace.searcher`` from a host app) do NOT trigger this + side effect; only the CLI/MCP entry points pop the env var. + """ # Drop leaked PYTHONPATH so any subprocess the CLI spawns (mine workers, # repair tooling) starts with a clean env. The sys.path filter in # mempalace/__init__.py already protects this process from the same diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index ede32ab..a7a8eec 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -2294,6 +2294,15 @@ def _restore_stdout(): def main(): + """MCP server entry point for the ``mempalace-mcp`` console script. + + Side effect: pops ``PYTHONPATH`` from ``os.environ`` (see #1423) so + any subprocess this server spawns inherits a clean env. Host + applications that call ``main()`` programmatically should be aware + that the parent process loses ``PYTHONPATH`` as well. Library imports + (``import mempalace.searcher`` from a host app) do NOT trigger this + side effect; only the CLI/MCP entry points pop the env var. + """ # Drop leaked PYTHONPATH so any subprocess this server spawns starts # with a clean env. The sys.path filter in mempalace/__init__.py # already protects this process from the same ABI mismatch; here we diff --git a/tests/test_cli.py b/tests/test_cli.py index 492b132..9894358 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -38,26 +38,35 @@ def test_cli_main_strips_leaked_pythonpath_from_env(): sys.path-filter test in test_init.py but for the env half of the split fix. See #1423. - Asserts ENV_MID between import and main() to prove that main() is - the strip site, not the package import. If a regression moves the - env pop back into __init__.py, ENV_MID would change and this test - would fail.""" + Three assertions cover the full split contract: + - ENV_MID (after import, before main) is preserved verbatim: + regression detector for someone moving the env pop back into + __init__.py. + - SENTINEL_IN_PATH is False at import time: package-level sys.path + filter half of the split actually ran. + - ENV_AFTER (after main) is None: CLI entry-point env strip ran. + + SystemExit is caught with a narrowed exit-code check so a future + argparse change that exits with a non-zero code (e.g. usage error) + surfaces as a test failure instead of being swallowed.""" expected_env = f"{_LEAK_PREFIX}/a{os.pathsep}{_LEAK_PREFIX}/b" env = os.environ.copy() env["PYTHONPATH"] = expected_env # Run main() with --version so it exits cleanly without entering any - # subcommand. argparse raises SystemExit on --version; the wrapper - # catches it and prints the post-main PYTHONPATH so the assertion - # is observable. + # subcommand. argparse raises SystemExit(0) on --version; the wrapper + # asserts the exit code is clean and prints the post-main PYTHONPATH + # so the assertion is observable. code = ( "import os, sys\n" "from mempalace.cli import main\n" + f"prefix = {_LEAK_PREFIX!r}\n" "print('ENV_MID:', repr(os.environ.get('PYTHONPATH')))\n" + "print('SENTINEL_IN_PATH:', any(prefix in (p or '') for p in sys.path))\n" "sys.argv = ['mempalace', '--version']\n" "try:\n" " main()\n" - "except SystemExit:\n" - " pass\n" + "except SystemExit as exc:\n" + " assert exc.code in (0, None), f'unexpected exit code: {exc.code!r}'\n" "print('ENV_AFTER:', repr(os.environ.get('PYTHONPATH')))\n" ) result = subprocess.run( @@ -73,6 +82,9 @@ def test_cli_main_strips_leaked_pythonpath_from_env(): assert ( f"ENV_MID: {expected_env!r}" in result.stdout ), f"package import unexpectedly stripped env (regression in __init__.py): {diag}" + assert ( + "SENTINEL_IN_PATH: False" in result.stdout + ), f"package import did not filter sys.path (regression in __init__.py): {diag}" assert "ENV_AFTER: None" in result.stdout, f"CLI did not strip PYTHONPATH: {diag}" diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 5b5b9cf..71a0bca 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -28,20 +28,27 @@ def test_mcp_main_strips_leaked_pythonpath_from_env(): sys.path-filter test in test_init.py but for the env half of the split fix. See #1423. - Asserts ENV_MID between import and main() to prove main() is the - strip site (not __init__.py). The main loop reads JSON-RPC lines - from stdin until EOF; closing stdin makes readline() return '' and - exits the loop cleanly, which lets us observe the post-main env - state.""" + Three assertions cover the full split contract: + - ENV_MID (after import, before main) is preserved verbatim: + regression detector for someone moving the env pop back into + __init__.py. + - SENTINEL_IN_PATH is False at import time: package-level sys.path + filter half of the split actually ran. + - ENV_AFTER (after main) is None: MCP entry-point env strip ran. + + The main loop reads JSON-RPC lines from stdin until EOF; closing + stdin makes readline() return '' and exits the loop cleanly, which + lets us observe the post-main env state. Probes go to stderr because + mcp_server redirects stdout at import time for clean JSON-RPC.""" expected_env = f"{_MCP_LEAK_PREFIX}/a{os.pathsep}{_MCP_LEAK_PREFIX}/b" env = os.environ.copy() env["PYTHONPATH"] = expected_env code = ( "import os, sys\n" "from mempalace.mcp_server import main\n" - # mcp_server redirects stdout at import time for clean JSON-RPC; - # write the probe to stderr so the subprocess can observe it. + f"prefix = {_MCP_LEAK_PREFIX!r}\n" "sys.stderr.write('ENV_MID: ' + repr(os.environ.get('PYTHONPATH')) + '\\n')\n" + "sys.stderr.write('SENTINEL_IN_PATH: ' + repr(any(prefix in (p or '') for p in sys.path)) + '\\n')\n" "main()\n" "sys.stderr.write('ENV_AFTER: ' + repr(os.environ.get('PYTHONPATH')) + '\\n')\n" ) @@ -59,6 +66,9 @@ def test_mcp_main_strips_leaked_pythonpath_from_env(): assert ( f"ENV_MID: {expected_env!r}" in result.stderr ), f"package import unexpectedly stripped env (regression in __init__.py): {diag}" + assert ( + "SENTINEL_IN_PATH: False" in result.stderr + ), f"package import did not filter sys.path (regression in __init__.py): {diag}" assert "ENV_AFTER: None" in result.stderr, f"MCP server did not strip PYTHONPATH: {diag}" From becf56172adfeda1213a15c136f7556691d09ba5 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Tue, 12 May 2026 03:49:32 +0500 Subject: [PATCH 27/64] fix(miner): log skipped symlinks in mine paths (#1462) Both scan_convos() and scan_project() silently drop symlinked files, leaving callers staging a temp directory of symlinks with no diagnostic for the "Files: 0" outcome. Keep the existing skip-symlinks behavior and add a " SKIP: {name} (symlink)" log per skipped file, matching the convention already used by split_mega_files.py for the oversized-file skip case. --- mempalace/convo_miner.py | 1 + mempalace/miner.py | 1 + tests/test_convo_miner_unit.py | 18 ++++++++++++++++++ tests/test_miner.py | 19 +++++++++++++++++++ 4 files changed, 39 insertions(+) diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index ea846c4..126e64b 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -296,6 +296,7 @@ def scan_convos(convo_dir: str) -> list: if filepath.suffix.lower() in CONVO_EXTENSIONS: # Skip symlinks and oversized files if filepath.is_symlink(): + print(f" SKIP: {filepath.name} (symlink)") continue try: if filepath.stat().st_size > MAX_FILE_SIZE: diff --git a/mempalace/miner.py b/mempalace/miner.py index 550f5f7..13ecb1d 100644 --- a/mempalace/miner.py +++ b/mempalace/miner.py @@ -1008,6 +1008,7 @@ def scan_project( continue # Skip symlinks — prevents following links to /dev/urandom, etc. if filepath.is_symlink(): + print(f" SKIP: {filepath.name} (symlink)") continue # Skip files exceeding size limit try: diff --git a/tests/test_convo_miner_unit.py b/tests/test_convo_miner_unit.py index 97236df..eaee76a 100644 --- a/tests/test_convo_miner_unit.py +++ b/tests/test_convo_miner_unit.py @@ -115,6 +115,24 @@ class TestScanConvos: files = scan_convos(str(tmp_path)) assert files == [] + def test_scan_logs_skipped_symlinks(self, tmp_path, capsys): + real_target = tmp_path / "outside" / "real.txt" + real_target.parent.mkdir() + real_target.write_text("real content", encoding="utf-8") + link_root = tmp_path / "link_root" + link_root.mkdir() + (link_root / "link.txt").symlink_to(real_target) + (link_root / "regular.txt").write_text("regular content", encoding="utf-8") + + files = scan_convos(str(link_root)) + + names = {f.name for f in files} + assert "link.txt" not in names + assert "regular.txt" in names + out = capsys.readouterr().out + assert out.count("SKIP:") == 1 + assert "link.txt" in out + class TestFileChunksLocked: def test_uses_bounded_upsert_batches(self, monkeypatch): diff --git a/tests/test_miner.py b/tests/test_miner.py index 05c6ce9..005b684 100644 --- a/tests/test_miner.py +++ b/tests/test_miner.py @@ -253,6 +253,25 @@ def test_scan_project_skip_dirs_still_apply_without_override(): shutil.rmtree(tmpdir) +def test_scan_project_logs_skipped_symlinks(tmp_path, capsys): + project_root = tmp_path / "proj" + project_root.mkdir() + real_target = tmp_path / "outside" / "real.md" + real_target.parent.mkdir() + real_target.write_text("real content\n" * 5, encoding="utf-8") + (project_root / "link.md").symlink_to(real_target) + (project_root / "regular.md").write_text("regular content\n" * 5, encoding="utf-8") + + files = scan_project(str(project_root)) + + names = {f.name for f in files} + assert "link.md" not in names + assert "regular.md" in names + out = capsys.readouterr().out + assert out.count("SKIP:") == 1 + assert "link.md" in out + + def test_entity_metadata_finds_cyrillic_names(monkeypatch): """Entity extraction must find non-Latin names when entity_languages includes the locale.""" import mempalace.palace as palace_mod From d7d96048876505f59a53075661b39111784aa0f8 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Tue, 12 May 2026 04:17:54 +0500 Subject: [PATCH 28/64] fix(miner): polish symlink skip diagnostic (#1462) * Move SKIP log from stdout to sys.stderr, matching the existing warning-channel pattern (the "No mempalace.yaml" notice and topic-tunnel warnings). Stdout stays clean for "Files: N" / "Drawers filed: N" markers that downstream callers parse. * Show the path relative to the scan root via Path.relative_to(...).as_posix() instead of the leaf filename, so a nested symlink in a deep subdirectory is unambiguous and the log renders with forward slashes on every platform. * Wrap the print in try/except OSError, mirroring the existing guard around filepath.stat() below; a broken pipe or closed stderr no longer aborts the scan mid-walk. * Document the stderr side effect in both scan_convos and scan_project docstrings. * Gate the new tests with @pytest.mark.skipif(sys.platform == "win32", ...) because Path.symlink_to requires SeCreateSymbolicLinkPrivilege on Windows. * Add dangling-symlink and nested-subdirectory tests for both miners, locking the two-space " SKIP:" prefix, the "(symlink)" reason marker, and the full relative path format. --- mempalace/convo_miner.py | 13 +++++- mempalace/miner.py | 13 +++++- tests/test_convo_miner_unit.py | 74 +++++++++++++++++++++++++++++----- tests/test_miner.py | 71 +++++++++++++++++++++++++++----- 4 files changed, 147 insertions(+), 24 deletions(-) diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index 126e64b..eddf0db 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -284,7 +284,12 @@ def detect_convo_room(content: str) -> str: def scan_convos(convo_dir: str) -> list: - """Find all potential conversation files.""" + """Find all potential conversation files. + + Skips symlinks and oversized files. Each skipped symlink is logged to + ``sys.stderr`` with a `` SKIP: (symlink)`` line so the + caller can tell why an apparent conversation directory yielded no files. + """ convo_path = Path(convo_dir).expanduser().resolve() files = [] for root, dirs, filenames in os.walk(convo_path): @@ -296,7 +301,11 @@ def scan_convos(convo_dir: str) -> list: if filepath.suffix.lower() in CONVO_EXTENSIONS: # Skip symlinks and oversized files if filepath.is_symlink(): - print(f" SKIP: {filepath.name} (symlink)") + rel = filepath.relative_to(convo_path).as_posix() + try: + print(f" SKIP: {rel} (symlink)", file=sys.stderr) + except OSError: + pass continue try: if filepath.stat().st_size > MAX_FILE_SIZE: diff --git a/mempalace/miner.py b/mempalace/miner.py index 13ecb1d..bdb2b7c 100644 --- a/mempalace/miner.py +++ b/mempalace/miner.py @@ -960,7 +960,12 @@ def scan_project( respect_gitignore: bool = True, include_ignored: list = None, ) -> list: - """Return list of all readable file paths.""" + """Return list of all readable file paths under ``project_dir``. + + Skips symlinks and oversized files. Each skipped symlink is logged to + ``sys.stderr`` with a `` SKIP: (symlink)`` line so the + caller can tell why a directory looks empty after walking. + """ project_path = Path(project_dir).expanduser().resolve() files = [] active_matchers = [] @@ -1008,7 +1013,11 @@ def scan_project( continue # Skip symlinks — prevents following links to /dev/urandom, etc. if filepath.is_symlink(): - print(f" SKIP: {filepath.name} (symlink)") + rel = filepath.relative_to(project_path).as_posix() + try: + print(f" SKIP: {rel} (symlink)", file=sys.stderr) + except OSError: + pass continue # Skip files exceeding size limit try: diff --git a/tests/test_convo_miner_unit.py b/tests/test_convo_miner_unit.py index eaee76a..392c4ad 100644 --- a/tests/test_convo_miner_unit.py +++ b/tests/test_convo_miner_unit.py @@ -1,6 +1,9 @@ """Unit tests for convo_miner pure functions (no chromadb needed).""" import contextlib +import sys + +import pytest from mempalace.convo_miner import ( _file_chunks_locked, @@ -115,23 +118,74 @@ class TestScanConvos: files = scan_convos(str(tmp_path)) assert files == [] - def test_scan_logs_skipped_symlinks(self, tmp_path, capsys): - real_target = tmp_path / "outside" / "real.txt" + @pytest.mark.skipif( + sys.platform == "win32", + reason="symlink creation requires elevated privileges on Windows", + ) + def test_scan_convos_logs_skipped_symlinks(self, tmp_path, capsys): + real_target = tmp_path / "outside" / "real.jsonl" real_target.parent.mkdir() - real_target.write_text("real content", encoding="utf-8") + real_target.write_text('{"role":"user","content":"hi"}\n', encoding="utf-8") link_root = tmp_path / "link_root" link_root.mkdir() - (link_root / "link.txt").symlink_to(real_target) - (link_root / "regular.txt").write_text("regular content", encoding="utf-8") + (link_root / "link.jsonl").symlink_to(real_target) + (link_root / "regular.jsonl").write_text( + '{"role":"user","content":"hello"}\n', encoding="utf-8" + ) files = scan_convos(str(link_root)) names = {f.name for f in files} - assert "link.txt" not in names - assert "regular.txt" in names - out = capsys.readouterr().out - assert out.count("SKIP:") == 1 - assert "link.txt" in out + assert "link.jsonl" not in names + assert "regular.jsonl" in names + err = capsys.readouterr().err + assert err.count("SKIP:") == 1 + assert " SKIP:" in err + assert "link.jsonl" in err + assert "(symlink)" in err + + @pytest.mark.skipif( + sys.platform == "win32", + reason="symlink creation requires elevated privileges on Windows", + ) + def test_scan_convos_logs_dangling_symlink(self, tmp_path, capsys): + real_target = tmp_path / "outside" / "ghost.jsonl" + real_target.parent.mkdir() + real_target.touch() + link_root = tmp_path / "link_root" + link_root.mkdir() + (link_root / "dangling.jsonl").symlink_to(real_target) + real_target.unlink() # target deleted, link dangles + + files = scan_convos(str(link_root)) + + assert files == [] + err = capsys.readouterr().err + assert err.count("SKIP:") == 1 + assert "dangling.jsonl" in err + assert "(symlink)" in err + + @pytest.mark.skipif( + sys.platform == "win32", + reason="symlink creation requires elevated privileges on Windows", + ) + def test_scan_convos_logs_nested_symlink_with_relative_path(self, tmp_path, capsys): + real_target = tmp_path / "outside" / "real.jsonl" + real_target.parent.mkdir() + real_target.write_text('{"x":1}\n', encoding="utf-8") + link_root = tmp_path / "link_root" + subdir = link_root / "deep" / "subdir" + subdir.mkdir(parents=True) + (subdir / "nested.jsonl").symlink_to(real_target) + + files = scan_convos(str(link_root)) + + assert files == [] + err = capsys.readouterr().err + # Forward slash even on Windows (as_posix) and full relative path, + # not just the leaf — proves relative_to(convo_path) over .name. + assert "deep/subdir/nested.jsonl" in err + assert "(symlink)" in err class TestFileChunksLocked: diff --git a/tests/test_miner.py b/tests/test_miner.py index 005b684..5f57328 100644 --- a/tests/test_miner.py +++ b/tests/test_miner.py @@ -1,10 +1,12 @@ import os import shlex import shutil +import sys import tempfile from pathlib import Path import chromadb +import pytest import yaml from mempalace.miner import detect_room, load_config, mine, scan_project, status @@ -253,23 +255,72 @@ def test_scan_project_skip_dirs_still_apply_without_override(): shutil.rmtree(tmpdir) +@pytest.mark.skipif( + sys.platform == "win32", + reason="symlink creation requires elevated privileges on Windows", +) def test_scan_project_logs_skipped_symlinks(tmp_path, capsys): project_root = tmp_path / "proj" project_root.mkdir() real_target = tmp_path / "outside" / "real.md" - real_target.parent.mkdir() - real_target.write_text("real content\n" * 5, encoding="utf-8") + write_file(real_target, "real content\n" * 5) (project_root / "link.md").symlink_to(real_target) - (project_root / "regular.md").write_text("regular content\n" * 5, encoding="utf-8") + write_file(project_root / "regular.md", "regular content\n" * 5) - files = scan_project(str(project_root)) + files = scanned_files(project_root, respect_gitignore=False) - names = {f.name for f in files} - assert "link.md" not in names - assert "regular.md" in names - out = capsys.readouterr().out - assert out.count("SKIP:") == 1 - assert "link.md" in out + assert "link.md" not in files + assert "regular.md" in files + err = capsys.readouterr().err + assert err.count("SKIP:") == 1 + assert " SKIP:" in err + assert "link.md" in err + assert "(symlink)" in err + + +@pytest.mark.skipif( + sys.platform == "win32", + reason="symlink creation requires elevated privileges on Windows", +) +def test_scan_project_logs_dangling_symlink(tmp_path, capsys): + project_root = tmp_path / "proj" + project_root.mkdir() + real_target = tmp_path / "outside" / "ghost.md" + real_target.parent.mkdir() + real_target.touch() + (project_root / "dangling.md").symlink_to(real_target) + real_target.unlink() # target deleted, link dangles + + files = scanned_files(project_root, respect_gitignore=False) + + assert files == [] + err = capsys.readouterr().err + assert err.count("SKIP:") == 1 + assert "dangling.md" in err + assert "(symlink)" in err + + +@pytest.mark.skipif( + sys.platform == "win32", + reason="symlink creation requires elevated privileges on Windows", +) +def test_scan_project_logs_nested_symlink_with_relative_path(tmp_path, capsys): + project_root = tmp_path / "proj" + project_root.mkdir() + real_target = tmp_path / "outside" / "real.md" + write_file(real_target, "real content\n" * 5) + deep = project_root / "deep" / "subdir" + deep.mkdir(parents=True) + (deep / "nested.md").symlink_to(real_target) + + files = scanned_files(project_root, respect_gitignore=False) + + assert files == [] + err = capsys.readouterr().err + # Forward slash even on Windows (as_posix) and full relative path, + # not just the leaf — proves relative_to(project_path) over .name. + assert "deep/subdir/nested.md" in err + assert "(symlink)" in err def test_entity_metadata_finds_cyrillic_names(monkeypatch): From d17d14d8d9c483a2fda6f6ce6b7b8e2dd6c70892 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Tue, 12 May 2026 05:39:06 +0500 Subject: [PATCH 29/64] fix(hooks): add bounded timeout to plugin Stop/PreCompact (#1465) The `.claude-plugin/hooks/hooks.json` Stop and PreCompact entries shipped without an explicit `timeout`, so a hung `mempalace hook run` (reported on Windows under CLI/plugin version drift) blocks the Claude Code UI for the full 600s `"type": "command"` default. Set explicit bounds: Stop = 30s (fire-and-forget save path with synchronous chromadb diary write, detached mine via _spawn_mine), PreCompact = 90s (60s inner _mine_sync subprocess timeout in mempalace/hooks_cli.py plus a 30s slack so legitimate mines for users with MEMPAL_DIR are not truncated mid-flight). Schema test in tests/test_claude_plugin_hook_config.py pins both per-event (floor, ceiling) bounds and catches future events added to the plugin config without a registered bounds entry. --- .claude-plugin/hooks/hooks.json | 6 +- tests/test_claude_plugin_hook_config.py | 78 +++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) create mode 100644 tests/test_claude_plugin_hook_config.py diff --git a/.claude-plugin/hooks/hooks.json b/.claude-plugin/hooks/hooks.json index b80a785..9960bed 100644 --- a/.claude-plugin/hooks/hooks.json +++ b/.claude-plugin/hooks/hooks.json @@ -6,7 +6,8 @@ "hooks": [ { "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-stop-hook.sh\"" + "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-stop-hook.sh\"", + "timeout": 30 } ] } @@ -16,7 +17,8 @@ "hooks": [ { "type": "command", - "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-precompact-hook.sh\"" + "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/mempal-precompact-hook.sh\"", + "timeout": 90 } ] } diff --git a/tests/test_claude_plugin_hook_config.py b/tests/test_claude_plugin_hook_config.py new file mode 100644 index 0000000..c79186b --- /dev/null +++ b/tests/test_claude_plugin_hook_config.py @@ -0,0 +1,78 @@ +"""Schema tests for Claude plugin hook config: timeout must be bounded.""" + +import json +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[1] +HOOK_CONFIG = REPO_ROOT / ".claude-plugin" / "hooks" / "hooks.json" + +# Per-event hook-level timeout bounds (seconds): (floor, ceiling). +# +# Stop is fire-and-forget for the mine subprocess (_spawn_mine returns +# after a detached Popen), but the handler also calls _save_diary_direct +# synchronously, which touches chromadb. 10..30s is generous for that +# work without leaving room for runaway hangs to freeze the session. +# +# PreCompact runs _mine_sync synchronously with a per-target subprocess +# timeout of 60s in mempalace/hooks_cli.py. The hook-level floor of 60 +# keeps the inner bound from being truncated, and the ceiling of 90 +# bounds the worst case at ~30s above that. +EVENT_TIMEOUT_BOUNDS: dict[str, tuple[int, int]] = { + "Stop": (10, 30), + "PreCompact": (60, 90), +} + + +@pytest.fixture(scope="module") +def hook_config() -> dict: + return json.loads(HOOK_CONFIG.read_text(encoding="utf-8")) + + +@pytest.mark.parametrize("event", sorted(EVENT_TIMEOUT_BOUNDS)) +def test_plugin_hook_timeout_within_bounds(hook_config: dict, event: str) -> None: + """Each declared plugin hook must declare a positive bounded timeout (#1465). + + Without ``timeout``, Claude Code falls back to the 600s command default + and a hung ``mempalace hook run`` freezes the interactive session for + up to ten minutes before being canceled. + """ + floor, ceiling = EVENT_TIMEOUT_BOUNDS[event] + assert event in hook_config.get("hooks", {}), f"missing event {event!r} in hook config" + entries = hook_config["hooks"][event] + assert isinstance(entries, list) and entries, f"no entries declared for {event}" + for entry in entries: + sub_hooks = entry.get("hooks") + assert ( + isinstance(sub_hooks, list) and sub_hooks + ), f"{event} entry missing non-empty 'hooks' array" + for hook in sub_hooks: + assert ( + hook["type"] == "command" + ), f"unexpected hook type for {event}: {hook.get('type')!r}" + assert "timeout" in hook, f"{event} hook missing 'timeout' key" + timeout = hook["timeout"] + # bool subclasses int, so reject it explicitly: True == 1 must fail. + is_real_int = isinstance(timeout, int) and not isinstance(timeout, bool) + assert ( + is_real_int and floor <= timeout <= ceiling + ), f"{event} hook timeout must be an int in [{floor}, {ceiling}]s; got {timeout!r}" + + +def test_no_unbounded_events_in_plugin_config(hook_config: dict) -> None: + """No plugin hook event may ship without an explicit bounds entry. + + Adding a new event (SessionStart, PreToolUse, etc.) to + ``.claude-plugin/hooks/hooks.json`` without registering bounds in + ``EVENT_TIMEOUT_BOUNDS`` would silently fall back to the 600s + Claude Code command default and re-introduce the regression. + """ + declared_events = set(hook_config.get("hooks", {}).keys()) + bounded_events = set(EVENT_TIMEOUT_BOUNDS) + unbounded = declared_events - bounded_events + assert not unbounded, ( + f"plugin hook events without timeout bounds: {sorted(unbounded)}. " + "Add a (floor, ceiling) entry to EVENT_TIMEOUT_BOUNDS in this test " + "after deciding the worst-case freeze the event can tolerate." + ) From 706237476cb9243d75a8cc198f04d3051ff0f052 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Tue, 12 May 2026 05:55:14 +0500 Subject: [PATCH 30/64] test(hooks): pin single-entry cardinality in plugin config schema A duplicate hook entry inside `entries[0]["hooks"]` (or a second entry under `Stop`/`PreCompact`) silently passes the per-hook bounds check and would double-fire the hook. Pin `len(entries) == 1` and `len(sub_hooks) == 1` so cardinality drift fails loudly with a diagnostic message naming the event and the unexpected count. --- tests/test_claude_plugin_hook_config.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/test_claude_plugin_hook_config.py b/tests/test_claude_plugin_hook_config.py index c79186b..25b8678 100644 --- a/tests/test_claude_plugin_hook_config.py +++ b/tests/test_claude_plugin_hook_config.py @@ -42,11 +42,21 @@ def test_plugin_hook_timeout_within_bounds(hook_config: dict, event: str) -> Non assert event in hook_config.get("hooks", {}), f"missing event {event!r} in hook config" entries = hook_config["hooks"][event] assert isinstance(entries, list) and entries, f"no entries declared for {event}" + # Pin cardinality: the plugin config intentionally declares exactly one + # command per event. A duplicate entry would silently double-fire the + # hook and pass per-hook bounds, so cardinality drift must fail loudly. + assert len(entries) == 1, ( + f"{event} expected exactly one entry, found {len(entries)}; " + "duplicate entries would double-fire the hook" + ) for entry in entries: sub_hooks = entry.get("hooks") assert ( isinstance(sub_hooks, list) and sub_hooks ), f"{event} entry missing non-empty 'hooks' array" + assert ( + len(sub_hooks) == 1 + ), f"{event} entry expected exactly one hook command, found {len(sub_hooks)}" for hook in sub_hooks: assert ( hook["type"] == "command" From cab41c8a759f285f4bd171b339aaa14766345d00 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Tue, 12 May 2026 05:57:18 +0500 Subject: [PATCH 31/64] test(hooks): use hook.get("type") for graceful assert message A direct ``hook["type"]`` subscript raised ``KeyError`` before the assert evaluated when the ``"type"`` key was missing, so the diagnostic message naming the event and the unexpected value was never shown. ``hook.get("type")`` lets the assert fail gracefully with the intended feedback. --- tests/test_claude_plugin_hook_config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_claude_plugin_hook_config.py b/tests/test_claude_plugin_hook_config.py index 25b8678..6c33054 100644 --- a/tests/test_claude_plugin_hook_config.py +++ b/tests/test_claude_plugin_hook_config.py @@ -59,7 +59,7 @@ def test_plugin_hook_timeout_within_bounds(hook_config: dict, event: str) -> Non ), f"{event} entry expected exactly one hook command, found {len(sub_hooks)}" for hook in sub_hooks: assert ( - hook["type"] == "command" + hook.get("type") == "command" ), f"unexpected hook type for {event}: {hook.get('type')!r}" assert "timeout" in hook, f"{event} hook missing 'timeout' key" timeout = hook["timeout"] From 982adcf09bf90cb0637e29dc7fc1b72dffac82fe Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Thu, 14 May 2026 01:03:31 +0500 Subject: [PATCH 32/64] fix(mcp): structured error for param-shape mismatch (#1351) Split the bare except in handle_request tools/call: TypeError matching Python's signature-mismatch shape (gated on handler __qualname__) returns -32602 with parsed parameter name(s); handler-internal TypeError and non-TypeError exceptions stay on the existing generic -32000 path so internals never leak. Adds TestParamShapeDiagnostics with 6 cases. Closes #1351 Co-authored-by: anastasiiaanfimova <271004602+anastasiiaanfimova@users.noreply.github.com> --- mempalace/mcp_server.py | 36 +++++++++- tests/test_mcp_server.py | 141 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 176 insertions(+), 1 deletion(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 85a0170..d030d31 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -45,6 +45,7 @@ sys.stdout = sys.stderr import argparse # noqa: E402 (deferred until after stdio protection above) import json # noqa: E402 import logging # noqa: E402 +import re # noqa: E402 import hashlib # noqa: E402 import sqlite3 # noqa: E402 import threading # noqa: E402 @@ -2250,8 +2251,8 @@ def handle_request(request): "id": req_id, "error": {"code": -32602, "message": f"Invalid value for parameter '{key}'"}, } + tool_args.pop("wait_for_previous", None) try: - tool_args.pop("wait_for_previous", None) result = TOOLS[tool_name]["handler"](**tool_args) return { "jsonrpc": "2.0", @@ -2262,6 +2263,39 @@ def handle_request(request): ] }, } + except TypeError as e: + # Qualname match prevents leaking internal helper/param names raised + # inside the handler body — see test_handler_internal_signature_shape_stays_generic. + msg = str(e) + handler = TOOLS[tool_name]["handler"] + handler_qn = getattr(handler, "__qualname__", None) or getattr(handler, "__name__", "") + # Qualname can include "" for nested defs and "" + # for lambdas — accept Python's TypeError emit verbatim. + m_missing = re.match( + r"^([\w\.<>]+)\(\) missing \d+ required " + r"(?:positional |keyword-only )?arguments?: (.+)$", + msg, + ) + if m_missing and m_missing.group(1) == handler_qn: + names = re.findall(r"'(\w+)'", m_missing.group(2)) + if names: + quoted = ", ".join(f"'{n}'" for n in names) + word = "parameter" if len(names) == 1 else "parameters" + logger.debug("Tool %s: missing required %s %s", tool_name, word, quoted) + return { + "jsonrpc": "2.0", + "id": req_id, + "error": { + "code": -32602, + "message": f"Missing required {word} {quoted} for tool {tool_name}", + }, + } + logger.exception(f"Tool error in {tool_name}") + return { + "jsonrpc": "2.0", + "id": req_id, + "error": {"code": -32000, "message": "Internal tool error"}, + } except Exception: logger.exception(f"Tool error in {tool_name}") return { diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 5e4ca9a..bd0a643 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1868,3 +1868,144 @@ class TestKGLazyCache: with pytest.raises(_sqlite3.ProgrammingError): mcp_server._call_kg(lambda kg: kg.query_entity("Alice")) assert calls["count"] == 2, "expected exactly one retry beyond the initial attempt" + + +# ── Param-shape diagnostics on tools/call dispatch (#1351) ────────────── + + +class TestParamShapeDiagnostics: + """Dispatch-level TypeError on tools/call should surface as JSON-RPC + -32602 (Invalid params) with the offending parameter named, instead of + the opaque -32000 Internal tool error. Handler-internal TypeError and + non-TypeError exceptions stay generic -32000 (no internals leak). + """ + + def test_missing_required_returns_32602_with_param_name(self): + from mempalace.mcp_server import handle_request + + resp = handle_request( + { + "method": "tools/call", + "id": 1, + "params": { + "name": "mempalace_diary_write", + "arguments": {"agent_name": "test"}, + }, + } + ) + assert resp["error"]["code"] == -32602 + assert "'entry'" in resp["error"]["message"] + assert "mempalace_diary_write" in resp["error"]["message"] + + def test_handler_internal_typeerror_stays_generic_32000(self, monkeypatch): + from mempalace import mcp_server + + def boom(**_kw): + raise TypeError("unsupported operand type(s) for +: 'int' and 'str'") + + monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", boom) + + resp = mcp_server.handle_request( + { + "method": "tools/call", + "id": 2, + "params": {"name": "mempalace_status", "arguments": {}}, + } + ) + assert resp["error"]["code"] == -32000 + assert resp["error"]["message"] == "Internal tool error" + assert "unsupported operand" not in resp["error"]["message"] + + def test_chromadb_exception_stays_generic_32000(self, monkeypatch): + from mempalace import mcp_server + + def boom(**_kw): + raise RuntimeError("db schema mismatch at /private/path/chroma.sqlite3") + + monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", boom) + + resp = mcp_server.handle_request( + { + "method": "tools/call", + "id": 3, + "params": {"name": "mempalace_status", "arguments": {}}, + } + ) + assert resp["error"]["code"] == -32000 + assert resp["error"]["message"] == "Internal tool error" + assert "db schema" not in resp["error"]["message"] + assert "/private/path" not in resp["error"]["message"] + + def test_two_missing_required_lists_both_names(self): + """For 2+ missing args Python emits 'a' and 'b'; the response should + list both quoted names, not return a syntactically broken string. + """ + from mempalace.mcp_server import handle_request + + resp = handle_request( + { + "method": "tools/call", + "id": 4, + "params": {"name": "mempalace_diary_write", "arguments": {}}, + } + ) + assert resp["error"]["code"] == -32602 + message = resp["error"]["message"] + assert "parameters" in message + assert "'agent_name'" in message + assert "'entry'" in message + assert " and " not in message.split("for tool")[0] + + def test_handler_internal_signature_shape_stays_generic(self, monkeypatch): + """A TypeError whose function name does not match the dispatched + handler — e.g. raised by a helper called inside the handler body — + must fall through to generic -32000, otherwise we'd leak internal + helper/parameter names as if they were public tool parameters. + """ + from mempalace import mcp_server + + def calling_handler(**_kw): + def helper(req): + return req + + helper() + + monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", calling_handler) + + resp = mcp_server.handle_request( + { + "method": "tools/call", + "id": 5, + "params": {"name": "mempalace_status", "arguments": {}}, + } + ) + assert resp["error"]["code"] == -32000 + assert resp["error"]["message"] == "Internal tool error" + assert "'req'" not in resp["error"]["message"] + assert "helper" not in resp["error"]["message"] + + def test_unexpected_kw_typeerror_inside_handler_stays_generic(self, monkeypatch): + """The 'got an unexpected keyword argument' shape is unreachable from + real dispatch (schema-filter on line 2236 drops unknown kwargs for + normal handlers; **kwargs handlers per #684 accept anything). If a + handler raises that shape manually, the qualname mismatch must keep + it on the generic -32000 path so internal helper names cannot leak. + """ + from mempalace import mcp_server + + def boom(**_kw): + raise TypeError("some_helper() got an unexpected keyword argument 'foo'") + + monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", boom) + + resp = mcp_server.handle_request( + { + "method": "tools/call", + "id": 6, + "params": {"name": "mempalace_status", "arguments": {}}, + } + ) + assert resp["error"]["code"] == -32000 + assert resp["error"]["message"] == "Internal tool error" + assert "'foo'" not in resp["error"]["message"] + assert "some_helper" not in resp["error"]["message"] From f28d0e351135708ed64393ae19552d6ecbf33f4d Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Thu, 14 May 2026 01:28:23 +0500 Subject: [PATCH 33/64] refactor(mcp): extract _internal_tool_error helper (#1351) Address gemini-code-assist review on PR #1500: dedup the two -32000 return branches in handle_request tools/call. Behavior unchanged; TestParamShapeDiagnostics 6/6 green. Co-authored-by: anastasiiaanfimova <271004602+anastasiiaanfimova@users.noreply.github.com> --- mempalace/mcp_server.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index d030d31..78c4223 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -2156,6 +2156,15 @@ SUPPORTED_PROTOCOL_VERSIONS = [ ] +def _internal_tool_error(req_id, tool_name: str) -> dict: + logger.exception(f"Tool error in {tool_name}") + return { + "jsonrpc": "2.0", + "id": req_id, + "error": {"code": -32000, "message": "Internal tool error"}, + } + + def handle_request(request): if not isinstance(request, dict): return { @@ -2290,19 +2299,9 @@ def handle_request(request): "message": f"Missing required {word} {quoted} for tool {tool_name}", }, } - logger.exception(f"Tool error in {tool_name}") - return { - "jsonrpc": "2.0", - "id": req_id, - "error": {"code": -32000, "message": "Internal tool error"}, - } + return _internal_tool_error(req_id, tool_name) except Exception: - logger.exception(f"Tool error in {tool_name}") - return { - "jsonrpc": "2.0", - "id": req_id, - "error": {"code": -32000, "message": "Internal tool error"}, - } + return _internal_tool_error(req_id, tool_name) # Notifications (missing id) must never get a response if req_id is None: From 6bd164e4b17876303a7120eca8410af188b9f800 Mon Sep 17 00:00:00 2001 From: Bruno Leal Date: Thu, 14 May 2026 19:17:26 -0300 Subject: [PATCH 34/64] style: ruff format test_hnsw_payload_health.py (#1461 follow-up) Collapse the multi-line assert startswith() added in #1461 into a single line as required by ruff format. No logic change. --- tests/test_hnsw_payload_health.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/test_hnsw_payload_health.py b/tests/test_hnsw_payload_health.py index 306b3ec..ac66b4f 100644 --- a/tests/test_hnsw_payload_health.py +++ b/tests/test_hnsw_payload_health.py @@ -155,6 +155,4 @@ def test_quarantine_catches_zero_byte_link_lists_when_stale(tmp_path): moved_path = Path(moved[0]) assert moved_path.exists() - assert moved_path.name.startswith( - "11111111-2222-3333-4444-555555555555.drift-" - ) + assert moved_path.name.startswith("11111111-2222-3333-4444-555555555555.drift-") From 51c03a0c5cd42d3fb7f7b74111641796d2dba261 Mon Sep 17 00:00:00 2001 From: Anastasiia Anfimova Date: Fri, 15 May 2026 13:48:29 +0200 Subject: [PATCH 35/64] fix(mcp): structured -32602 for unknown parameter name (#1512) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unknown kwargs (wrong parameter name, e.g. text= instead of content=) were silently dropped by the schema-filter, surfacing only indirectly as a later "Missing required 'X'". Emit -32602 naming the offending kwarg instead — symmetric with #1500's missing-required path. Gated by the existing accepts_var_keyword check; wait_for_previous excluded. Closes #1512. Co-Authored-By: Claude Opus 4.7 --- mempalace/mcp_server.py | 20 ++++++++ tests/test_mcp_server.py | 102 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index a0aac93..17f6877 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -2242,6 +2242,26 @@ def handle_request(request): except (ValueError, TypeError): accepts_var_keyword = False if not accepts_var_keyword: + # An unknown kwarg here is almost always a wrong parameter *name* + # (e.g. text= instead of content=). Silently dropping it makes the + # cause surface only indirectly as a later "Missing required 'X'", + # so name it explicitly — symmetric with the missing-required path + # below. wait_for_previous is an internal transport kwarg in no + # tool schema; it is popped before dispatch further down, so it + # must not be reported as unknown here. + unknown = [k for k in tool_args if k not in schema_props and k != "wait_for_previous"] + if unknown: + quoted = ", ".join(f"'{k}'" for k in unknown) + word = "parameter" if len(unknown) == 1 else "parameters" + logger.debug("Tool %s: unknown %s %s", tool_name, word, quoted) + return { + "jsonrpc": "2.0", + "id": req_id, + "error": { + "code": -32602, + "message": f"Unknown {word} {quoted} for tool {tool_name}", + }, + } tool_args = {k: v for k, v in tool_args.items() if k in schema_props} # Coerce argument types based on input_schema. # MCP JSON transport may deliver integers as floats or strings; diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 555c307..8abfd95 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -2066,3 +2066,105 @@ class TestParamShapeDiagnostics: assert resp["error"]["message"] == "Internal tool error" assert "'foo'" not in resp["error"]["message"] assert "some_helper" not in resp["error"]["message"] + + +class TestUnknownParamName: + """A kwarg not in the tool schema (wrong parameter *name*, e.g. text= + instead of content=) should surface as JSON-RPC -32602 naming the + offending kwarg, instead of being silently dropped and resurfacing + indirectly as a later "Missing required 'X'". Symmetric with the + missing-required path in TestParamShapeDiagnostics. The internal + wait_for_previous transport kwarg must never be flagged, and + **kwargs pass-through handlers must keep accepting unknown kwargs. + """ + + def test_unknown_param_returns_32602_naming_the_wrong_kwarg(self): + from mempalace.mcp_server import handle_request + + resp = handle_request( + { + "method": "tools/call", + "id": 7, + "params": { + "name": "mempalace_add_drawer", + "arguments": {"wing": "w", "room": "r", "text": "hello"}, + }, + } + ) + assert resp["error"]["code"] == -32602 + message = resp["error"]["message"] + assert "'text'" in message + assert "Unknown parameter" in message + assert "mempalace_add_drawer" in message + # Names the actual wrong kwarg, not the indirect missing-required symptom. + assert "Missing required" not in message + + def test_two_unknown_params_list_both_names(self): + from mempalace.mcp_server import handle_request + + resp = handle_request( + { + "method": "tools/call", + "id": 8, + "params": { + "name": "mempalace_add_drawer", + "arguments": {"wing": "w", "room": "r", "text": "a", "bogus": "b"}, + }, + } + ) + assert resp["error"]["code"] == -32602 + message = resp["error"]["message"] + assert "parameters" in message + assert "'text'" in message + assert "'bogus'" in message + + def test_wait_for_previous_not_flagged_as_unknown(self, monkeypatch): + """wait_for_previous is an internal transport kwarg in no tool schema; + it is popped before dispatch and must not trip the unknown-param check + for a normal (non-**kwargs) handler. + """ + from mempalace import mcp_server + + def stub(agent_name, entry, topic="general"): + return {"ok": True, "agent": agent_name} + + monkeypatch.setitem(mcp_server.TOOLS["mempalace_diary_write"], "handler", stub) + + resp = mcp_server.handle_request( + { + "method": "tools/call", + "id": 9, + "params": { + "name": "mempalace_diary_write", + "arguments": { + "agent_name": "x", + "entry": "y", + "wait_for_previous": True, + }, + }, + } + ) + assert "error" not in resp + assert "result" in resp + + def test_kwargs_passthrough_handler_keeps_accepting_unknown(self, monkeypatch): + """Handlers that explicitly accept **kwargs (per #684) bypass the + schema filter entirely, so an unknown kwarg must still pass through + rather than being rejected as -32602. + """ + from mempalace import mcp_server + + def passthrough(**kwargs): + return {"ok": True, "got": sorted(kwargs)} + + monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", passthrough) + + resp = mcp_server.handle_request( + { + "method": "tools/call", + "id": 10, + "params": {"name": "mempalace_status", "arguments": {"bogus": 1}}, + } + ) + assert "error" not in resp + assert "result" in resp From bea7cb16464e5c26dc79765e8f3567e42647c038 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 15 May 2026 10:42:21 -0300 Subject: [PATCH 36/64] fix(convo_miner): validate explicit min_chunk_size instead of raw config reach MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1024 routed min_chunk_size for the project miner through the repairing MempalaceConfig validation, but the convo path read the raw, unvalidated _file_config["min_chunk_size"]. A garbage/negative/bool config value would TypeError the convo length gate or ValueError out of chunk_exchanges and abort the whole convo mine — breaking the PR's own "a bad config.json key never takes ingest down" guarantee for one path only. Extract _try_coerce_int helper (shared with _coerce_config_int) and add a public MempalaceConfig.min_chunk_size_explicit accessor that returns the validated value when the user set it, else None. convo_miner uses the None sentinel to keep its stricter 30-char floor for untuned users while honoring a valid override, with no raw _file_config reach. Adds accessor + convo-fallback regression tests. --- mempalace/config.py | 61 ++++++++++++++++++++++++++++--------- mempalace/convo_miner.py | 11 ++++--- tests/test_config.py | 65 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 18 deletions(-) diff --git a/mempalace/config.py b/mempalace/config.py index b115a7f..2b9ce20 100644 --- a/mempalace/config.py +++ b/mempalace/config.py @@ -313,6 +313,31 @@ class MempalaceConfig: """Mapping of hall names to keyword lists.""" return self._file_config.get("hall_keywords", DEFAULT_HALL_KEYWORDS) + @staticmethod + def _try_coerce_int(value, minimum=None): + """Coerce a raw config value to int, or ``None`` if it cannot be a + valid setting. + + bool, empty/garbage string, non-numeric, and below-``minimum`` + values all return ``None``. Shared by ``_coerce_config_int`` + (which substitutes a documented default) and + ``min_chunk_size_explicit`` (which must distinguish "unusable" + from "explicitly set" without crashing the convo path). + """ + if isinstance(value, bool): + return None + try: + if isinstance(value, str): + value = value.strip() + if not value: + return None + value = int(value) + except (TypeError, ValueError): + return None + if minimum is not None and value < minimum: + return None + return value + def _coerce_config_int(self, key: str, default: int, minimum=None) -> int: """Read an int config value, falling back to ``default`` on bad input. @@ -321,20 +346,8 @@ class MempalaceConfig: should crash mining or hang ``chunk_text()`` — fall back silently to the documented default rather than letting a typo break ingest. """ - value = self._file_config.get(key, default) - if isinstance(value, bool): - return default - try: - if isinstance(value, str): - value = value.strip() - if not value: - return default - value = int(value) - except (TypeError, ValueError): - return default - if minimum is not None and value < minimum: - return default - return value + coerced = self._try_coerce_int(self._file_config.get(key, default), minimum) + return default if coerced is None else coerced def _validated_chunk_config(self): """Return ``(chunk_size, chunk_overlap, min_chunk_size)`` post-validation. @@ -383,6 +396,26 @@ class MempalaceConfig: """Minimum chunk size — skip smaller chunks (validated, ``<= chunk_size``).""" return self._validated_chunk_config()[2] + @property + def min_chunk_size_explicit(self): + """Validated ``min_chunk_size`` iff the user explicitly set it. + + Returns the coerced int when ``config.json`` defines a usable + ``min_chunk_size`` (``>= 0`` and ``<= chunk_size``); ``None`` when + the key is absent/null or the value is unusable. ``convo_miner`` + relies on the ``None`` sentinel to keep its stricter 30-char floor + for untuned users while still honoring an explicit override — + replacing the raw, unvalidated ``_file_config`` reach that crashed + convo ingest on a bad key (#1024 review). + """ + raw = self._file_config.get("min_chunk_size") + if raw is None: + return None + coerced = self._try_coerce_int(raw, minimum=0) + if coerced is None or coerced > self.chunk_size: + return None + return coerced + @property def entity_languages(self): """Languages whose entity-detection patterns should be applied. diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index 763015f..c0a5189 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -439,10 +439,13 @@ def mine_convos( palace_config = MempalaceConfig() cfg_chunk_size = palace_config.chunk_size # Only override convo_miner's MIN_CHUNK_SIZE when the user has set - # min_chunk_size explicitly — default MempalaceConfig returns miner.py's - # 50, which would drop legitimate short conversation exchanges. - raw_min = palace_config._file_config.get("min_chunk_size") - cfg_min_chunk_size = raw_min if raw_min is not None else MIN_CHUNK_SIZE + # min_chunk_size explicitly. min_chunk_size_explicit returns the + # validated value or None — None keeps convo's stricter 30-char + # floor. Using the validated accessor (not raw _file_config) means a + # garbage/negative/bool config value can't TypeError the length gate + # below or ValueError out of chunk_exchanges and abort convo ingest. + explicit_min = palace_config.min_chunk_size_explicit + cfg_min_chunk_size = explicit_min if explicit_min is not None else MIN_CHUNK_SIZE convo_path = Path(convo_dir).expanduser().resolve() if not wing: diff --git a/tests/test_config.py b/tests/test_config.py index fcfe7c1..6df51ba 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -443,6 +443,71 @@ def test_chunk_config_min_chunk_size_above_size_repaired(tmp_path): assert cfg2.min_chunk_size == 20 # default (50) > chunk_size, clamp +# ── min_chunk_size_explicit (convo-path validated accessor) ──────────── +# Backs the #1024-review fix: convo_miner must distinguish "user tuned +# min_chunk_size" from "untuned" WITHOUT reaching into raw _file_config. +# Untuned/unusable → None (convo keeps its 30 floor). Usable → validated +# int. A bad key must never reach the convo length-gate / chunk_exchanges +# as a non-int and crash ingest. + + +def test_min_chunk_size_explicit_none_when_unset(tmp_path): + cfg = MempalaceConfig(config_dir=str(tmp_path)) + assert cfg.min_chunk_size_explicit is None + + +def test_min_chunk_size_explicit_none_when_json_null(tmp_path): + """Explicit JSON ``null`` is treated as untuned (preserves the prior + ``_file_config.get(...) is None`` sentinel semantics).""" + cfg = _write_config(tmp_path, min_chunk_size=None) + assert cfg.min_chunk_size_explicit is None + + +def test_min_chunk_size_explicit_returns_validated_value(tmp_path): + cfg = _write_config(tmp_path, min_chunk_size=80) + assert cfg.min_chunk_size_explicit == 80 + + +def test_min_chunk_size_explicit_coerces_numeric_string(tmp_path): + cfg = _write_config(tmp_path, min_chunk_size="42") + assert cfg.min_chunk_size_explicit == 42 + + +@pytest.mark.parametrize("bad", ["abc", -5, True, "", " "]) +def test_min_chunk_size_explicit_none_on_unusable_value(tmp_path, bad): + """Garbage / negative / bool / blank → None, NOT a crash and NOT the + miner.py default. convo_miner then falls back to its own 30 floor. + This is the exact class of value that used to TypeError the convo + length-gate or ValueError out of chunk_exchanges.""" + cfg = _write_config(tmp_path, min_chunk_size=bad) + assert cfg.min_chunk_size_explicit is None + + +def test_min_chunk_size_explicit_none_when_above_chunk_size(tmp_path): + """min_chunk_size > chunk_size would zero out ingest — treat as + unusable so convo falls back to its floor instead.""" + cfg = _write_config(tmp_path, chunk_size=100, min_chunk_size=500) + assert cfg.min_chunk_size_explicit is None + + +def test_convo_min_chunk_fallback_is_always_safe_int(tmp_path): + """Regression for #1024 review: the convo_miner fallback expression + must yield a usable int for ANY config — never a str/bool/negative + that would crash the length gate or chunk_exchanges.""" + from mempalace.convo_miner import MIN_CHUNK_SIZE + + for bad in ("not-a-number", -10, True, {}, []): + cfg = _write_config(tmp_path, min_chunk_size=bad) + explicit = cfg.min_chunk_size_explicit + effective = explicit if explicit is not None else MIN_CHUNK_SIZE + assert isinstance(effective, int) and not isinstance(effective, bool) + assert effective == MIN_CHUNK_SIZE # untuned floor, no crash + + cfg = _write_config(tmp_path, min_chunk_size=15) + explicit = cfg.min_chunk_size_explicit + assert (explicit if explicit is not None else MIN_CHUNK_SIZE) == 15 + + def test_chunk_text_rejects_non_positive_chunk_size(): """Direct callers (tests, library users) that pass ``chunk_size <= 0`` must hit a clear ValueError, not loop forever.""" From 78d57ddf641c9a1062b90681d1516de1d7f8249e Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 15 May 2026 10:46:41 -0300 Subject: [PATCH 37/64] fix(test): remove duplicate pytest import breaking lint on develop The #1024 merge added `import pytest` to tests/test_convo_miner_unit.py while a pytest import already existed from another merged change. The collision was textually clean so git didn't flag it, but CI ruff reports F811 (redefinition of unused `pytest`), turning lint red on develop and every branch cut from it. Drop the duplicate import. `ruff check .` (0.4.x, CI pin) clean; test_convo_miner_unit 23 passed. --- tests/test_convo_miner_unit.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/test_convo_miner_unit.py b/tests/test_convo_miner_unit.py index 1f845b3..90ad573 100644 --- a/tests/test_convo_miner_unit.py +++ b/tests/test_convo_miner_unit.py @@ -5,8 +5,6 @@ import sys import pytest -import pytest - from mempalace.convo_miner import ( _file_chunks_locked, chunk_exchanges, From 342cfa629b52433767e525c3d56c56460e0aaabe Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Fri, 15 May 2026 11:01:48 -0300 Subject: [PATCH 38/64] fix(config): catch OverflowError in coercion; correct "stricter" wording MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses review-bot feedback on #1519: - gemini: JSON `Infinity`/`1e1000` round-trips to float('inf'); int(inf) raises OverflowError, which _try_coerce_int did not catch — bad config could still crash ingest. Catch it alongside TypeError/ValueError and fall back like any other garbage value. Regression test added. - Copilot: the 30-char convo floor was described as "stricter" than the 50-char project default. It is the opposite — lower, i.e. more permissive (keeps short exchanges the project default would drop). Reworded the docstring and comments to state this accurately. --- mempalace/config.py | 10 +++++++--- mempalace/convo_miner.py | 13 ++++++++----- tests/test_config.py | 11 +++++++++++ 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/mempalace/config.py b/mempalace/config.py index 2b9ce20..0931747 100644 --- a/mempalace/config.py +++ b/mempalace/config.py @@ -332,7 +332,9 @@ class MempalaceConfig: if not value: return None value = int(value) - except (TypeError, ValueError): + except (TypeError, ValueError, OverflowError): + # OverflowError: JSON ``1e1000`` parses to float('inf'), and + # ``int(inf)`` raises it — still just garbage config, not a crash. return None if minimum is not None and value < minimum: return None @@ -403,8 +405,10 @@ class MempalaceConfig: Returns the coerced int when ``config.json`` defines a usable ``min_chunk_size`` (``>= 0`` and ``<= chunk_size``); ``None`` when the key is absent/null or the value is unusable. ``convo_miner`` - relies on the ``None`` sentinel to keep its stricter 30-char floor - for untuned users while still honoring an explicit override — + relies on the ``None`` sentinel to keep its lower 30-char floor + (more permissive than the 50-char project default, so short + exchanges are not dropped) for untuned users while still honoring + an explicit override — replacing the raw, unvalidated ``_file_config`` reach that crashed convo ingest on a bad key (#1024 review). """ diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index c0a5189..24898d2 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -430,9 +430,10 @@ def mine_convos( Chunking parameters (chunk_size, min_chunk_size) are read from MempalaceConfig so `config.json` governs both this path and the project-file miner in `miner.py`. `min_chunk_size` preserves - convo_miner's stricter default (30) when not explicitly set in - config.json, so a user who never touches chunking keeps the - existing behavior. + convo_miner's lower default (30 — more permissive than the 50-char + project default, so short conversation exchanges are not dropped) + when not explicitly set in config.json, so a user who never touches + chunking keeps the existing behavior. """ from .config import MempalaceConfig @@ -440,8 +441,10 @@ def mine_convos( cfg_chunk_size = palace_config.chunk_size # Only override convo_miner's MIN_CHUNK_SIZE when the user has set # min_chunk_size explicitly. min_chunk_size_explicit returns the - # validated value or None — None keeps convo's stricter 30-char - # floor. Using the validated accessor (not raw _file_config) means a + # validated value or None — None keeps convo's lower 30-char floor + # (more permissive than the 50-char project default, so short + # exchanges aren't dropped). Using the validated accessor (not raw + # _file_config) means a # garbage/negative/bool config value can't TypeError the length gate # below or ValueError out of chunk_exchanges and abort convo ingest. explicit_min = palace_config.min_chunk_size_explicit diff --git a/tests/test_config.py b/tests/test_config.py index 6df51ba..eecc6d7 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -508,6 +508,17 @@ def test_convo_min_chunk_fallback_is_always_safe_int(tmp_path): assert (explicit if explicit is not None else MIN_CHUNK_SIZE) == 15 +def test_min_chunk_size_explicit_handles_json_infinity(tmp_path): + """JSON ``Infinity`` round-trips to float('inf'); ``int(inf)`` raises + OverflowError. That is still garbage config, not a crash — must fall + back to None (untuned), same as any other unusable value.""" + cfg = _write_config(tmp_path, min_chunk_size=float("inf")) + assert cfg.min_chunk_size_explicit is None + # chunk_size path coerces the same value → documented default, no crash. + cfg2 = _write_config(tmp_path, chunk_size=float("inf")) + assert cfg2.chunk_size == 800 + + def test_chunk_text_rejects_non_positive_chunk_size(): """Direct callers (tests, library users) that pass ``chunk_size <= 0`` must hit a clear ValueError, not loop forever.""" From 6f9fe8055a338ae9463416ab320f5be41f0166e2 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Wed, 6 May 2026 16:31:33 +0500 Subject: [PATCH 39/64] fix(mcp): canonicalize KG cache key via realpath + normcase (#1372) Switch _kg_by_path lookups in _get_kg and _call_kg from os.path.abspath to a new _canonicalize_kg_path helper applying realpath (collapses symlink aliases) + normcase (Windows drive-letter casing). Two tenants pointing at /srv/A and /srv/link-to-A no longer open duplicate sqlite3.Connection handles over the same file. --- mempalace/mcp_server.py | 17 +++++++- tests/test_mcp_server.py | 87 ++++++++++++++++++++++++++++++++++++++-- 2 files changed, 99 insertions(+), 5 deletions(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 17f6877..25b7c70 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -120,8 +120,21 @@ def _resolve_kg_path() -> str: return DEFAULT_KG_PATH +def _canonicalize_kg_path(path: str) -> str: + """Canonicalize a KG cache key so aliases collapse onto one entry. + + ``realpath`` resolves symlinks: two tenants pointing at the same + SQLite file via different layouts (``/srv/A`` and + ``/srv/link-to-A``) hit a single cached ``KnowledgeGraph`` rather + than opening duplicate connections. ``normcase`` normalizes Windows + drive-letter casing (``C:\\palace`` vs ``c:\\palace``) and + path-separator style; on POSIX it returns the input unchanged. + """ + return os.path.normcase(os.path.realpath(path)) + + def _get_kg() -> KnowledgeGraph: - path = os.path.abspath(_resolve_kg_path()) + path = _canonicalize_kg_path(_resolve_kg_path()) kg = _kg_by_path.get(path) if kg is not None: return kg @@ -157,7 +170,7 @@ def _call_kg(op): return op(kg) except sqlite3.ProgrammingError: if attempt == 0: - path = os.path.abspath(_resolve_kg_path()) + path = _canonicalize_kg_path(_resolve_kg_path()) with _kg_cache_lock: if _kg_by_path.get(path) is kg: _kg_by_path.pop(path, None) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 8abfd95..d91e2c9 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1867,7 +1867,7 @@ class TestKGLazyCache: def query_entity(self, entity, **kwargs): return [{"entity": entity}] - cache = {os.path.abspath(path): _ClosedKG()} + cache = {mcp_server._canonicalize_kg_path(path): _ClosedKG()} monkeypatch.setattr(mcp_server, "_kg_by_path", cache) # Second _get_kg() call (after the cache eviction) constructs a new @@ -1877,7 +1877,7 @@ class TestKGLazyCache: result = mcp_server._call_kg(lambda kg: kg.query_entity("Alice")) assert result == [{"entity": "Alice"}] # The closed instance must be evicted; the fresh one must be cached. - assert isinstance(cache[os.path.abspath(path)], _FreshKG) + assert isinstance(cache[mcp_server._canonicalize_kg_path(path)], _FreshKG) def test_call_kg_does_not_retry_on_other_errors(self, monkeypatch): """Non-ProgrammingError exceptions must propagate without retry — @@ -1894,7 +1894,9 @@ class TestKGLazyCache: calls["count"] += 1 raise ValueError("bad input") - monkeypatch.setattr(mcp_server, "_kg_by_path", {os.path.abspath(path): _FailingKG()}) + monkeypatch.setattr( + mcp_server, "_kg_by_path", {mcp_server._canonicalize_kg_path(path): _FailingKG()} + ) monkeypatch.setattr(mcp_server, "KnowledgeGraph", lambda **_: _FailingKG()) with pytest.raises(ValueError, match="bad input"): @@ -1926,6 +1928,85 @@ class TestKGLazyCache: mcp_server._call_kg(lambda kg: kg.query_entity("Alice")) assert calls["count"] == 2, "expected exactly one retry beyond the initial attempt" + def test_canonicalize_kg_path_collapses_symlink_alias(self, tmp_path): + """A symlink layer over the palace directory must collapse to one + cache key — otherwise two tenants pointing at /srv/A and + /srv/link-to-A open duplicate sqlite3.Connections over the same + file.""" + if sys.platform == "win32": + pytest.skip("symlink creation requires admin privileges on Windows runners") + + from mempalace import mcp_server + + target = tmp_path / "real" + target.mkdir() + link = tmp_path / "link" + link.symlink_to(target) + + real_db = str(target / "knowledge_graph.sqlite3") + link_db = str(link / "knowledge_graph.sqlite3") + + assert mcp_server._canonicalize_kg_path(real_db) == mcp_server._canonicalize_kg_path( + link_db + ) + + def test_canonicalize_kg_path_routes_through_normcase(self, monkeypatch): + """``_canonicalize_kg_path`` must apply ``os.path.normcase`` so the + cache key collapses Windows drive-letter casing + (``C:\\palace`` vs ``c:\\palace``). On POSIX runners normcase is a + no-op, so we monkeypatch it to verify the wiring rather than the + OS behaviour.""" + from mempalace import mcp_server + + seen: list = [] + + def fake_normcase(p: str) -> str: + seen.append(p) + return p.lower() + + monkeypatch.setattr(os.path, "normcase", fake_normcase) + + result = mcp_server._canonicalize_kg_path("/Some/Path/KG.sqlite3") + + assert seen, "expected normcase to be invoked" + assert result == seen[-1].lower() + + def test_get_kg_dedupes_symlink_alias_end_to_end(self, tmp_path, monkeypatch): + """End-to-end: two ``_get_kg()`` calls via different symlink layers + return the same cached instance and construct only one + ``KnowledgeGraph``.""" + if sys.platform == "win32": + pytest.skip("symlink creation requires admin privileges on Windows runners") + + from mempalace import mcp_server + + target = tmp_path / "real" + target.mkdir() + link = tmp_path / "link" + link.symlink_to(target) + + real_db = str(target / "knowledge_graph.sqlite3") + link_db = str(link / "knowledge_graph.sqlite3") + + constructed: list = [] + + class _StubKG: + def __init__(self, db_path=None): + constructed.append(db_path) + + monkeypatch.setattr(mcp_server, "_kg_by_path", {}) + monkeypatch.setattr(mcp_server, "KnowledgeGraph", _StubKG) + + paths = iter([real_db, link_db]) + monkeypatch.setattr(mcp_server, "_resolve_kg_path", lambda: next(paths)) + + kg1 = mcp_server._get_kg() + kg2 = mcp_server._get_kg() + + assert kg1 is kg2, "symlink alias must hit the cached KG, not construct a duplicate" + assert len(constructed) == 1, f"expected 1 KG construction, got {len(constructed)}" + assert len(mcp_server._kg_by_path) == 1 + # ── Param-shape diagnostics on tools/call dispatch (#1351) ────────────── From 3ee158ecddca028728731f66f68afcaaf15bbee9 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Wed, 6 May 2026 16:36:05 +0500 Subject: [PATCH 40/64] test(mcp): tighten _canonicalize_kg_path normcase wiring assertion Patch both realpath and normcase with sentinel wrappers and assert the result composes them as normcase(realpath(p)). Swapping the order would leave Windows symlinks under the original case, defeating the dedup. The previous assertion (result == seen[-1].lower()) was tautological -- the fake normcase already returned p.lower(), so any implementation that lowercased anything would pass. --- tests/test_mcp_server.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index d91e2c9..277855f 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1954,22 +1954,27 @@ class TestKGLazyCache: """``_canonicalize_kg_path`` must apply ``os.path.normcase`` so the cache key collapses Windows drive-letter casing (``C:\\palace`` vs ``c:\\palace``). On POSIX runners normcase is a - no-op, so we monkeypatch it to verify the wiring rather than the - OS behaviour.""" + no-op, so we patch both ``realpath`` and ``normcase`` with sentinel + wrappers and assert the helper composes them as + ``normcase(realpath(p))`` -- swapping the order would leave Windows + symlinks under the original case, defeating the dedup. + """ from mempalace import mcp_server - seen: list = [] + def fake_realpath(p: str) -> str: + return f"" def fake_normcase(p: str) -> str: - seen.append(p) - return p.lower() + return f"" + monkeypatch.setattr(os.path, "realpath", fake_realpath) monkeypatch.setattr(os.path, "normcase", fake_normcase) - result = mcp_server._canonicalize_kg_path("/Some/Path/KG.sqlite3") + result = mcp_server._canonicalize_kg_path("/some/Path/KG.sqlite3") - assert seen, "expected normcase to be invoked" - assert result == seen[-1].lower() + assert ( + result == ">" + ), f"expected normcase(realpath(p)) composition, got {result!r}" def test_get_kg_dedupes_symlink_alias_end_to_end(self, tmp_path, monkeypatch): """End-to-end: two ``_get_kg()`` calls via different symlink layers From 51eb279348b2734286cb159cda464f4856c0cf83 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Wed, 6 May 2026 16:55:23 +0500 Subject: [PATCH 41/64] fix(mcp): capture canonical KG path once at top of _call_kg Move _canonicalize_kg_path call from inside the except branch to the top of _call_kg so OSError from realpath (e.g. transient Windows junction loss) propagates cleanly instead of masking the original sqlite3.ProgrammingError mid-handler. Also keeps the eviction key identical to the insertion key if FS state mutates between attempts, preventing a closed handle from leaking into the cache under a stale key the lookup no longer matches. --- mempalace/mcp_server.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 25b7c70..a5ad98e 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -163,14 +163,22 @@ def _call_kg(op): KG. Beyond one retry give up: a second close means we're losing a sustained race we won't win in this loop, and a hung loop is worse than a clear failure surface. + + The eviction path is captured once before the retry loop rather than + re-canonicalized inside the ``except`` branch. Doing it there would + let ``realpath`` raise ``OSError`` on a transient FS hiccup (Windows + junction loss, mount remap) and mask the original + ``sqlite3.ProgrammingError``; it would also let canonicalization + drift between insert and evict, leaving the closed handle in the + cache under a key the lookup no longer matches. """ + path = _canonicalize_kg_path(_resolve_kg_path()) for attempt in range(2): kg = _get_kg() try: return op(kg) except sqlite3.ProgrammingError: if attempt == 0: - path = _canonicalize_kg_path(_resolve_kg_path()) with _kg_cache_lock: if _kg_by_path.get(path) is kg: _kg_by_path.pop(path, None) From 4dc3ccf26ac16177b8a401e779d64abea08fc39a Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Wed, 6 May 2026 17:18:58 +0500 Subject: [PATCH 42/64] fix(mcp): thread captured KG path through _get_kg to lock insert/evict keys _get_kg now accepts an optional canonical_path argument and uses it verbatim when given. _call_kg passes its top-of-function captured key through, so the dict insertion that _get_kg performs and the eviction lookup _call_kg performs always agree on the key -- even if env state (MEMPALACE_PALACE_PATH rotation) or FS state (symlink remap) mutates between attempts. Without the pass-through, _get_kg's internal call to _canonicalize_kg_path(_resolve_kg_path()) could land on a different key than the captured path, leaving a closed handle in the cache under a stale key the eviction lookup no longer matches. Tests: test_call_kg_passes_captured_path_through_resolve_drift -- patches _resolve_kg_path with a shifting iterator + identity canonicalize, pre-seeds the closed handle under the captured key; asserts both _get_kg calls receive the captured key and the closed handle is evicted by retry. test_call_kg_oserror_at_top_propagates_unmasked -- patches _canonicalize_kg_path to raise OSError; asserts it propagates without conversion (the rationale for capturing at the top before the retry loop -- prevents an OSError mid-handler from masking a sqlite3.ProgrammingError it can't retry through). _patch_mcp_server test helper updated to a varargs lambda so existing tests that patch _get_kg as a no-arg fixture stay compatible with the new optional-arg signature. --- mempalace/mcp_server.py | 36 +++++++++++----- tests/test_mcp_server.py | 89 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 114 insertions(+), 11 deletions(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index a5ad98e..6226bf8 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -133,8 +133,22 @@ def _canonicalize_kg_path(path: str) -> str: return os.path.normcase(os.path.realpath(path)) -def _get_kg() -> KnowledgeGraph: - path = _canonicalize_kg_path(_resolve_kg_path()) +def _get_kg(canonical_path=None) -> KnowledgeGraph: + """Return the cached ``KnowledgeGraph`` for the resolved palace. + + When ``canonical_path`` is ``None`` (default), the path is resolved + from module state and canonicalized. Callers like :func:`_call_kg` + that have already captured a canonical key before entering a retry + loop should pass it through here so the dict insertion uses the same + key the caller will later use for eviction. Recomputing the key + inside this function would let ``MEMPALACE_PALACE_PATH`` rotation, + a symlink remap, or a mount remap between the captured value and + this call drift the insert and evict keys apart, stranding a closed + handle under one key while the lookup probes another. + """ + path = ( + canonical_path if canonical_path is not None else _canonicalize_kg_path(_resolve_kg_path()) + ) kg = _kg_by_path.get(path) if kg is not None: return kg @@ -164,17 +178,19 @@ def _call_kg(op): sustained race we won't win in this loop, and a hung loop is worse than a clear failure surface. - The eviction path is captured once before the retry loop rather than - re-canonicalized inside the ``except`` branch. Doing it there would - let ``realpath`` raise ``OSError`` on a transient FS hiccup (Windows - junction loss, mount remap) and mask the original - ``sqlite3.ProgrammingError``; it would also let canonicalization - drift between insert and evict, leaving the closed handle in the - cache under a key the lookup no longer matches. + The canonical path is captured once at the top and threaded through + every ``_get_kg`` call plus the eviction lookup. Doing canonicalize + only here means an ``OSError`` from ``realpath`` (transient Windows + junction loss, broken mount) surfaces cleanly before any handler + runs instead of masking a ``sqlite3.ProgrammingError`` mid-retry. + Passing the captured key through to ``_get_kg`` also locks the + insert key to the evict key even if FS or env state mutates between + attempts, preventing a closed handle from leaking under a stale + key the lookup no longer matches. """ path = _canonicalize_kg_path(_resolve_kg_path()) for attempt in range(2): - kg = _get_kg() + kg = _get_kg(path) try: return op(kg) except sqlite3.ProgrammingError: diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 277855f..f116942 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -77,7 +77,9 @@ def _patch_mcp_server(monkeypatch, config, kg): from mempalace import mcp_server monkeypatch.setattr(mcp_server, "_config", config) - monkeypatch.setattr(mcp_server, "_get_kg", lambda: kg) + # Accept varargs because production ``_get_kg`` now takes an optional + # canonical_path; ``_call_kg`` passes the captured key through. + monkeypatch.setattr(mcp_server, "_get_kg", lambda *a, **kw: kg) def _get_collection(palace_path, create=False): @@ -1928,6 +1930,91 @@ class TestKGLazyCache: mcp_server._call_kg(lambda kg: kg.query_entity("Alice")) assert calls["count"] == 2, "expected exactly one retry beyond the initial attempt" + def test_call_kg_passes_captured_path_through_resolve_drift(self, monkeypatch): + """``_call_kg`` must thread its captured canonical path through + ``_get_kg`` so insertion and eviction agree on the cache key even + when FS or env state would otherwise drift between attempts. The + end-to-end invariant: after the retry, the closed handle that was + cached under the captured path is gone (evicted) and the cache no + longer holds it under the stale key. + """ + import sqlite3 as _sqlite3 + from mempalace import mcp_server + + class _ClosedKG: + def query_entity(self, entity, **kwargs): + raise _sqlite3.ProgrammingError("Cannot operate on a closed database") + + class _FreshKG: + def query_entity(self, entity, **kwargs): + return [{"entity": entity}] + + # _resolve_kg_path returns shifting values (env rotation between + # attempts). _canonicalize_kg_path is identity so paths flow + # through verbatim. + resolved_seq = iter(["/path/v1", "/path/v2", "/path/v3"]) + monkeypatch.setattr(mcp_server, "_resolve_kg_path", lambda: next(resolved_seq)) + monkeypatch.setattr(mcp_server, "_canonicalize_kg_path", lambda p: p) + + closed = _ClosedKG() + cache = {"/path/v1": closed} + monkeypatch.setattr(mcp_server, "_kg_by_path", cache) + + get_kg_args: list = [] + + def spy_get_kg(canonical_path=None): + get_kg_args.append(canonical_path) + return cache.get(canonical_path) if canonical_path in cache else _FreshKG() + + monkeypatch.setattr(mcp_server, "_get_kg", spy_get_kg) + + result = mcp_server._call_kg(lambda kg: kg.query_entity("Alice")) + + assert result == [{"entity": "Alice"}] + # Both _get_kg calls received the captured path "/path/v1" rather + # than the drifted "/path/v2". Without pass-through, the second + # call would have used "/path/v2" and the closed handle at + # "/path/v1" would never have been evicted. + assert get_kg_args == ["/path/v1", "/path/v1"], ( + f"expected both _get_kg calls to receive captured '/path/v1', " + f"got {get_kg_args} -- captured-path pass-through broken" + ) + # Eviction landed under the captured key: the closed handle is + # gone from the cache. With drift the closed handle would still + # be at "/path/v1" because eviction would have probed "/path/v2". + assert "/path/v1" not in cache, ( + f"closed handle leaked under captured key after retry; " + f"cache state: {[(k, type(v).__name__) for k, v in cache.items()]}" + ) + + def test_call_kg_oserror_at_top_propagates_unmasked(self, monkeypatch): + """``OSError`` from ``_canonicalize_kg_path`` at the top of + ``_call_kg`` (e.g. transient Windows realpath hiccup on a stale + junction) must propagate unchanged. The fix-rationale invariant: + capturing the canonical path before the retry loop means an FS + error surfaces cleanly to the dispatcher's exception envelope + instead of getting raised inside the ``except`` branch where it + would mask a ``sqlite3.ProgrammingError``. + """ + from mempalace import mcp_server + + monkeypatch.setattr(mcp_server, "_resolve_kg_path", lambda: "/fake/path") + monkeypatch.setattr( + mcp_server, + "_canonicalize_kg_path", + lambda p: (_ for _ in ()).throw(OSError("simulated realpath failure")), + ) + + op_calls = {"n": 0} + + def op(kg): + op_calls["n"] += 1 + return None + + with pytest.raises(OSError, match="simulated realpath failure"): + mcp_server._call_kg(op) + assert op_calls["n"] == 0, "op must not run if canonicalize fails at top" + def test_canonicalize_kg_path_collapses_symlink_alias(self, tmp_path): """A symlink layer over the palace directory must collapse to one cache key — otherwise two tenants pointing at /srv/A and From e241aa38baf4ded617380e570a658aee35719d7c Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Mon, 11 May 2026 04:32:18 +0500 Subject: [PATCH 43/64] fix(hooks): replace mapfile with sed for bash 3.2 compat (#1440) The legacy hook scripts used `mapfile -t` (introduced in #1231) to read sanitized values from the inline Python JSON parser. On stock macOS /bin/bash is GNU 3.2.57 (Apple GPLv3 freeze) and `mapfile` only landed in bash 4.0, so the hook silently failed: every parsed value fell back to its default, the log wrote "Session unknown: 0 exchanges", and zero drawers were saved. This commit replaces the array read with `sed -n 'Np'` line extraction, which is POSIX and runs on /bin/bash 3.2 unmodified. It also adds a defense-in-depth fail-loud guard: Python prints a `__MEMPAL_PARSE_OK__` sentinel and the hook surfaces the raw input plus Python traceback to 0600-mode sibling files when the sentinel is missing, so the next silent failure has a debuggable trail instead of an unsolved zero-drawer day. --- hooks/mempal_precompact_hook.sh | 55 ++++++- hooks/mempal_save_hook.sh | 76 +++++++-- tests/test_hooks_bash_compat.py | 278 ++++++++++++++++++++++++++++++++ 3 files changed, 390 insertions(+), 19 deletions(-) create mode 100644 tests/test_hooks_bash_compat.py diff --git a/hooks/mempal_precompact_hook.sh b/hooks/mempal_precompact_hook.sh index e811d65..edaf686 100755 --- a/hooks/mempal_precompact_hook.sh +++ b/hooks/mempal_precompact_hook.sh @@ -66,20 +66,59 @@ fi INPUT=$(cat) # Parse session_id and transcript_path in one call. Sanitize both, then -# read sanitized values from one-per-line stdout into shell variables — -# avoids ``eval`` on generated code (#1231 review). Same contract as -# mempal_save_hook.sh. -mapfile -t _mempal_parsed < <(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " +# read sanitized values from one-per-line stdout into shell variables +# (avoids ``eval`` on generated code, #1231 review). Uses ``sed -n 'Np'`` +# rather than the bash 4-only ``mapfile`` so the script also runs on +# macOS /bin/bash 3.2.57 (Apple GPLv3 freeze, 2006), where ``mapfile`` +# silently caused every parsed value to fall back to its default (#1440). +# +# The leading ``__MEMPAL_PARSE_OK__`` sentinel lets the defense-in-depth +# guard below distinguish "Python parsed cleanly" from "Python crashed +# and printed nothing". Same parsing contract as mempal_save_hook.sh. +# Python stderr is captured to last_python_err.log so the guard below can +# distinguish "bad user input" from "broken interpreter / future regression +# in this inline script". Same diagnostic contract as mempal_save_hook.sh. +_mempal_parsed=$(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " import sys, json, re data = json.load(sys.stdin) -sid = data.get('session_id', 'unknown') +sid = data.get('session_id', '') tp = data.get('transcript_path', '') safe = lambda s: re.sub(r'[^a-zA-Z0-9_/.\-~]', '', str(s)) +print('__MEMPAL_PARSE_OK__') print(safe(sid)) print(safe(tp)) -" 2>/dev/null) -SESSION_ID="${_mempal_parsed[0]:-unknown}" -TRANSCRIPT_PATH="${_mempal_parsed[1]:-}" +" 2>"$STATE_DIR/last_python_err.log") +# Drop the empty file on success; chmod 600 on failure to mirror +# last_input.log's privacy contract. +if [ -s "$STATE_DIR/last_python_err.log" ]; then + chmod 600 "$STATE_DIR/last_python_err.log" 2>/dev/null +else + rm -f "$STATE_DIR/last_python_err.log" +fi +_MEMPAL_PARSE_MARKER=$(printf '%s\n' "$_mempal_parsed" | sed -n '1p') +SESSION_ID=$(printf '%s\n' "$_mempal_parsed" | sed -n '2p') +TRANSCRIPT_PATH=$(printf '%s\n' "$_mempal_parsed" | sed -n '3p') +SESSION_ID="${SESSION_ID:-unknown}" +TRANSCRIPT_PATH="${TRANSCRIPT_PATH:-}" + +# Defense-in-depth: if INPUT was non-empty but Python never reached the +# print() calls (sentinel missing), parsing silently failed. Surface the +# raw payload so the next debugger does not lose a day to hook.log lines +# that say "Session unknown". Bounded to 4 KB and overwritten on each +# failure (not appended) to keep ~/.mempalace/hook_state/ from growing +# unbounded under a repeating misconfiguration. chmod 600 so the dump, +# which mirrors the Claude Code PreCompact payload (includes +# transcript_path revealing the user's home + project layout), is not +# world-readable. +if [ -n "$INPUT" ] && [ "$_MEMPAL_PARSE_MARKER" != "__MEMPAL_PARSE_OK__" ]; then + echo "[$(date '+%H:%M:%S')] WARN: input parse failed (sentinel missing); see $STATE_DIR/last_input.log and $STATE_DIR/last_python_err.log" >> "$STATE_DIR/hook.log" + # ``head -c 4096`` is a byte cap, locale-independent; ``${INPUT:0:4096}`` + # would count characters under UTF-8 and slip a multibyte payload past + # the bound. ``set -o pipefail`` is not enabled in this script so the + # natural SIGPIPE-on-printf from ``head`` closing stdin is absorbed. + printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" + chmod 600 "$STATE_DIR/last_input.log" 2>/dev/null +fi # Expand ~ in path TRANSCRIPT_PATH="${TRANSCRIPT_PATH/#\~/$HOME}" diff --git a/hooks/mempal_save_hook.sh b/hooks/mempal_save_hook.sh index 5efd157..52a404d 100755 --- a/hooks/mempal_save_hook.sh +++ b/hooks/mempal_save_hook.sh @@ -83,27 +83,81 @@ fi INPUT=$(cat) # Parse all fields in a single Python call (3x faster than separate invocations) -# without invoking ``eval`` on generated code: Python prints one sanitized -# value per line, the shell reads them via ``mapfile`` and does plain -# variable assignment — same data, smaller blast radius if the sanitizer -# is ever bypassed (#1231 review). -mapfile -t _mempal_parsed < <(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " +# without invoking ``eval`` on generated code: Python prints a parse-success +# sentinel followed by one sanitized value per line, the shell reads each +# line via ``sed -n 'Np'`` and does plain variable assignment. Same data, +# smaller blast radius if the sanitizer is ever bypassed (#1231 review). +# +# Why ``sed -n 'Np'`` and not ``mapfile`` / ``readarray``: macOS ships +# GNU bash 3.2.57 (frozen at Apple's GPLv3 cutoff in 2006), and both +# array-read builtins only landed in bash 4.0 (2009). On a stock macOS +# the previous ``mapfile`` form errored, every value fell back to its +# default, and the hook silently produced zero saves (#1440). +# +# The leading ``__MEMPAL_PARSE_OK__`` sentinel lets the defense-in-depth +# guard below distinguish "Python parsed cleanly, user set session_id to +# the literal string 'unknown'" or "session_id was non-ASCII and got +# sanitized to empty" from the actual failure mode ("Python crashed, +# nothing was printed"). Without the sentinel the guard false-fires +# every Stop hook for users on i18n harnesses or unusual harness configs. +# Python stderr is captured to last_python_err.log so the guard below can +# distinguish "bad user input" (JSONDecodeError) from "broken interpreter +# / future regression in this inline script" (ImportError, SyntaxError, +# ModuleNotFoundError). Without the stderr capture, last_input.log shows +# a valid payload while the actual root cause stays hidden. +_mempal_parsed=$(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " import sys, json, re data = json.load(sys.stdin) -sid = data.get('session_id', 'unknown') +sid = data.get('session_id', '') sha_raw = data.get('stop_hook_active', False) tp = data.get('transcript_path', '') -# Shell-safe output — only allow alphanumeric, underscore, hyphen, slash, dot, tilde +# Shell-safe output: only allow alphanumeric, underscore, hyphen, slash, dot, tilde safe = lambda s: re.sub(r'[^a-zA-Z0-9_/.\-~]', '', str(s)) # Coerce stop_hook_active to strict boolean string sha = 'True' if sha_raw is True or str(sha_raw).lower() in ('true', '1', 'yes') else 'False' +print('__MEMPAL_PARSE_OK__') print(safe(sid)) print(sha) print(safe(tp)) -" 2>/dev/null) -SESSION_ID="${_mempal_parsed[0]:-unknown}" -STOP_HOOK_ACTIVE="${_mempal_parsed[1]:-False}" -TRANSCRIPT_PATH="${_mempal_parsed[2]:-}" +" 2>"$STATE_DIR/last_python_err.log") +# The 2> redirect creates the file even when stderr is empty (success). +# Remove the empty file so the state directory stays clean on the happy +# path; on failure, lock the file's permissions to 600 to mirror +# last_input.log's privacy contract (the traceback can reveal absolute +# paths inside the user's home). +if [ -s "$STATE_DIR/last_python_err.log" ]; then + chmod 600 "$STATE_DIR/last_python_err.log" 2>/dev/null +else + rm -f "$STATE_DIR/last_python_err.log" +fi +_MEMPAL_PARSE_MARKER=$(printf '%s\n' "$_mempal_parsed" | sed -n '1p') +SESSION_ID=$(printf '%s\n' "$_mempal_parsed" | sed -n '2p') +STOP_HOOK_ACTIVE=$(printf '%s\n' "$_mempal_parsed" | sed -n '3p') +TRANSCRIPT_PATH=$(printf '%s\n' "$_mempal_parsed" | sed -n '4p') +SESSION_ID="${SESSION_ID:-unknown}" +STOP_HOOK_ACTIVE="${STOP_HOOK_ACTIVE:-False}" +TRANSCRIPT_PATH="${TRANSCRIPT_PATH:-}" + +# Defense-in-depth: if INPUT was non-empty but Python never reached the +# print() calls (sentinel missing), parsing silently failed. Surface the +# raw payload so the next debugger does not lose a day to hook.log lines +# that say "Session unknown". Bounded to 4 KB and overwritten on each +# failure (not appended) to keep ~/.mempalace/hook_state/ from growing +# unbounded under a repeating misconfiguration. chmod 600 so the dump, +# which mirrors the Claude Code Stop payload (includes transcript_path +# revealing the user's home + project layout), is not world-readable. +if [ -n "$INPUT" ] && [ "$_MEMPAL_PARSE_MARKER" != "__MEMPAL_PARSE_OK__" ]; then + echo "[$(date '+%H:%M:%S')] WARN: input parse failed (sentinel missing); see $STATE_DIR/last_input.log and $STATE_DIR/last_python_err.log" >> "$STATE_DIR/hook.log" + # ``head -c 4096`` caps at exactly 4096 BYTES regardless of locale. + # Bash's ``${INPUT:0:4096}`` would count characters under a UTF-8 + # locale, letting a CJK/emoji payload silently exceed the cap by up + # to 4x. ``set -o pipefail`` is not enabled in this script, so the + # natural ``head``-closes-stdin / SIGPIPE-on-printf interaction is + # silently absorbed by bash (the canonical way to read N bytes from + # a string in shell). + printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" + chmod 600 "$STATE_DIR/last_input.log" 2>/dev/null +fi # Expand ~ in path TRANSCRIPT_PATH="${TRANSCRIPT_PATH/#\~/$HOME}" diff --git a/tests/test_hooks_bash_compat.py b/tests/test_hooks_bash_compat.py new file mode 100644 index 0000000..c2dc2fb --- /dev/null +++ b/tests/test_hooks_bash_compat.py @@ -0,0 +1,278 @@ +"""Regression tests for the bash 3.2 compatibility fix (#1440). + +The legacy hooks/*.sh scripts run on the user's system. On stock macOS +that is GNU bash 3.2.57 (Apple GPLv3 freeze, 2006). Using bash 4.0-only +builtins like ``mapfile`` silently breaks parsing: every JSON field +falls back to its default, the hook logs ``Session unknown: 0 exchanges``, +and zero drawers are saved. + +These tests cover: +1. Source-level shape (mapfile/readarray absent, sed-based extraction). +2. Behavioral parse contract (session_id reaches the log, not 'unknown'). +3. The fail-loud guard: fires only when the parser sentinel is missing, + never on a legitimately empty/unicode/literal-'unknown' session_id. +4. The guard's disk discipline (bounded dump, overwrite-not-append). +""" + +from __future__ import annotations + +import json +import os +import stat +import subprocess +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parent.parent +SAVE_HOOK = REPO_ROOT / "hooks" / "mempal_save_hook.sh" +PRECOMPACT_HOOK = REPO_ROOT / "hooks" / "mempal_precompact_hook.sh" + +pytestmark = pytest.mark.skipif(os.name == "nt", reason="bash hook scripts are POSIX-only") + + +def _hook_src_no_comments(hook: Path) -> str: + return "\n".join( + line for line in hook.read_text().splitlines() if not line.lstrip().startswith("#") + ) + + +def _run_hook(hook: Path, stdin: str, home: Path) -> tuple[int, str]: + env = { + "HOME": str(home), + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + } + p = subprocess.run( + ["bash", str(hook)], + input=stdin, + capture_output=True, + text=True, + env=env, + timeout=30, + ) + return p.returncode, p.stdout + + +class TestNoBash4OnlyBuiltins: + """Source-level regression: mapfile/readarray unavailable on macOS bash 3.2.""" + + @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + def test_no_mapfile(self, hook): + code = _hook_src_no_comments(hook) + assert "mapfile" not in code, ( + f"{hook.name} uses mapfile, unavailable on macOS /bin/bash 3.2 (#1440)" + ) + assert "readarray" not in code, ( + f"{hook.name} uses readarray, unavailable on macOS /bin/bash 3.2 (#1440)" + ) + + @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + def test_sed_extraction_present(self, hook): + src = hook.read_text() + # Each hook reads at least two values via ``sed -n 'Np'`` (sentinel + session_id). + assert src.count("sed -n '") >= 2, ( + f"{hook.name} must use sed -n 'Np' for POSIX-portable line extraction" + ) + + @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + def test_bash_syntax_clean(self, hook): + p = subprocess.run( + ["bash", "-n", str(hook)], + capture_output=True, + text=True, + ) + assert p.returncode == 0, f"{hook.name} syntax error: {p.stderr}" + + +class TestSessionIdExtraction: + """Hook must parse session_id from valid JSON, not fall back to 'unknown'.""" + + def test_save_hook_extracts_session_id(self, tmp_path): + rc, out = _run_hook( + SAVE_HOOK, + json.dumps( + {"session_id": "abc12345", "stop_hook_active": False, "transcript_path": ""} + ), + tmp_path, + ) + assert rc == 0 + # Stdout must be valid JSON; Claude Code parses it. A regression that + # leaks debug output here would silently break the harness contract. + assert json.loads(out) == {}, f"hook stdout must be valid JSON, got: {out!r}" + log = (tmp_path / ".mempalace" / "hook_state" / "hook.log").read_text() + assert "Session abc12345:" in log, f"got fallback 'unknown'; log was: {log!r}" + # Negative cross-check: the sentinel-distinguishes-success-from-failure + # contract has no value if the guard fires on the happy path too. + assert "WARN: input parse failed" not in log + state_dir = tmp_path / ".mempalace" / "hook_state" + assert not (state_dir / "last_input.log").exists() + assert not (state_dir / "last_python_err.log").exists(), ( + "successful parse must leave no last_python_err.log behind" + ) + + def test_precompact_hook_extracts_session_id(self, tmp_path): + rc, out = _run_hook( + PRECOMPACT_HOOK, + json.dumps({"session_id": "abc12345", "transcript_path": ""}), + tmp_path, + ) + assert rc == 0 + assert json.loads(out) == {}, f"hook stdout must be valid JSON, got: {out!r}" + log = (tmp_path / ".mempalace" / "hook_state" / "hook.log").read_text() + assert "PRE-COMPACT triggered for session abc12345" in log + assert "WARN: input parse failed" not in log + state_dir = tmp_path / ".mempalace" / "hook_state" + assert not (state_dir / "last_input.log").exists() + assert not (state_dir / "last_python_err.log").exists() + + +class TestFailLoudGuard: + """Non-parseable stdin must dump the input and warn in hook.log so + future silent failures are loud, and the dump must stay bounded and + user-private. The guard must NOT fire on legitimately empty inputs + or on sanitizer-stripped session_ids (#1440).""" + + @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + def test_malformed_input_logs_warning_and_dumps_input(self, hook, tmp_path): + rc, _ = _run_hook(hook, "not-json garbage", tmp_path) + assert rc == 0 + state_dir = tmp_path / ".mempalace" / "hook_state" + log = (state_dir / "hook.log").read_text() + last_input = (state_dir / "last_input.log").read_text() + assert "WARN: input parse failed (sentinel missing)" in log + assert "not-json garbage" in last_input + + @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + def test_empty_stdin_does_not_dump_or_warn(self, hook, tmp_path): + """Empty stdin is a legitimate state (e.g. a hook re-fire on Stop + with no message body). The guard's ``[ -n "$INPUT" ]`` short-circuit + must hold so nothing is written to last_input.log.""" + rc, _ = _run_hook(hook, "", tmp_path) + assert rc == 0 + state_dir = tmp_path / ".mempalace" / "hook_state" + assert not (state_dir / "last_input.log").exists() + log_path = state_dir / "hook.log" + if log_path.exists(): + assert "WARN: input parse failed" not in log_path.read_text() + + def test_unicode_session_id_does_not_trip_guard(self, tmp_path): + """A session_id with non-ASCII characters (Cyrillic, CJK, emoji) + is stripped by the sanitizer to '', defaults to 'unknown'. The + sentinel still printed, so the guard must skip and NOT spam disk.""" + rc, _ = _run_hook( + SAVE_HOOK, + json.dumps({"session_id": "сессия", "stop_hook_active": False, "transcript_path": ""}), + tmp_path, + ) + assert rc == 0 + state_dir = tmp_path / ".mempalace" / "hook_state" + assert not (state_dir / "last_input.log").exists(), ( + "unicode-only session_id sanitized to empty must NOT trip the guard" + ) + + def test_literal_unknown_session_id_does_not_trip_guard(self, tmp_path): + """A user who literally passes session_id='unknown' is parsing + cleanly; the sentinel-based guard must distinguish that from a + crash and skip the dump.""" + rc, _ = _run_hook( + SAVE_HOOK, + json.dumps({"session_id": "unknown", "stop_hook_active": False, "transcript_path": ""}), + tmp_path, + ) + assert rc == 0 + state_dir = tmp_path / ".mempalace" / "hook_state" + assert not (state_dir / "last_input.log").exists(), ( + "literal session_id='unknown' must NOT trip the guard" + ) + + def test_dump_is_bounded_and_overwritten(self, tmp_path): + """The dump caps at exactly 4096 bytes and overwrites on each + failure so a repeating misconfiguration cannot grow the file + unbounded.""" + # 4097 bytes: one over the cap, proves the cutoff fires at exactly + # 4096 (a regression that silently shrinks the cap to e.g. 1024 + # would slip past a looser ``<= 4096`` check). + big_payload = "x" * 4097 + rc, _ = _run_hook(SAVE_HOOK, big_payload, tmp_path) + assert rc == 0 + last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log" + assert last_input.stat().st_size == 4096, ( + f"cap must be exactly 4096 bytes; got {last_input.stat().st_size}" + ) + # Second failure with a smaller payload overwrites the first; the + # file shrinks instead of accumulating. + rc, _ = _run_hook(SAVE_HOOK, "tiny", tmp_path) + assert rc == 0 + assert last_input.read_text() == "tiny", "dump must overwrite on each failure, not append" + + def test_dump_cap_holds_under_utf8_locale(self, tmp_path): + """Under a UTF-8 locale, a multibyte payload of 2000 CJK chars = + 6000 bytes would slip a character-counted substring (`${var:0:N}`) + past the 4096-byte cap. The hook uses ``head -c`` precisely so + the bound stays byte-based regardless of locale.""" + # ``C.UTF-8`` is available on every mainstream Linux distribution + # (Debian/Ubuntu, Fedora, RHEL 8+, Alpine via musl) and macOS + # bash falls back to the byte-based C locale gracefully; + # ``en_US.UTF-8`` would silently degrade to no-op on minimal CI + # images (Alpine, distroless) where that locale is not generated. + env = { + "HOME": str(tmp_path), + "PATH": os.environ.get("PATH", "/usr/bin:/bin"), + "LANG": "C.UTF-8", + "LC_ALL": "C.UTF-8", + } + # 2000 copies of U+4E2D (3 bytes each in UTF-8) = 6000 bytes. + big_payload = "中" * 2000 + p = subprocess.run( + ["bash", str(SAVE_HOOK)], + input=big_payload, + capture_output=True, + text=True, + env=env, + timeout=30, + ) + assert p.returncode == 0 + last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log" + size = last_input.stat().st_size + assert size == 4096, ( + f"UTF-8 payload must still cap at 4096 bytes (got {size}); " + "regression to ${var:0:N} would let multibyte input bypass the bound" + ) + + def test_dump_is_not_world_readable(self, tmp_path): + """The dump mirrors the raw Stop payload (transcript_path reveals + the user's home + project layout). Permissions must be 600 so + other users on a shared box cannot read it.""" + rc, _ = _run_hook(SAVE_HOOK, "not-json garbage", tmp_path) + assert rc == 0 + last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log" + mode = stat.S_IMODE(last_input.stat().st_mode) + assert mode == 0o600, f"last_input.log mode should be 0600, got {oct(mode)}" + + @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + def test_python_stderr_captured_on_parse_failure(self, hook, tmp_path): + """When the inline Python parser crashes (malformed JSON, missing + interpreter, future regression), its stderr must land in + last_python_err.log so a debugger can distinguish 'bad user + input' from 'broken interpreter or broken inline script'.""" + rc, _ = _run_hook(hook, "not-json garbage", tmp_path) + assert rc == 0 + err_log = tmp_path / ".mempalace" / "hook_state" / "last_python_err.log" + assert err_log.exists(), "Python stderr must be captured on parse failure" + contents = err_log.read_text() + # Python's json.load raises JSONDecodeError with a recognizable + # traceback. Don't pin the exact message (it varies by Python + # version) but assert at least one canonical marker is present. + assert "Traceback" in contents or "json" in contents.lower(), ( + f"expected Python traceback or json error, got: {contents!r}" + ) + + @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + def test_python_stderr_log_is_not_world_readable_on_failure(self, hook, tmp_path): + """The stderr capture mirrors the privacy expectation of + last_input.log: on a populated failure write it must be 0600.""" + rc, _ = _run_hook(hook, "not-json garbage", tmp_path) + assert rc == 0 + err_log = tmp_path / ".mempalace" / "hook_state" / "last_python_err.log" + mode = stat.S_IMODE(err_log.stat().st_mode) + assert mode == 0o600, f"last_python_err.log mode should be 0600 on failure, got {oct(mode)}" From 2bdb1e88461567652ea3fa12cd35709de8d000c3 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Mon, 11 May 2026 05:14:24 +0500 Subject: [PATCH 44/64] fix(hooks): apply post-review hardenings (#1440) Follow-up on c271e7b after the bot review and an adversarial pass. - Replace `echo "$INPUT"` with `printf '%s' "$INPUT"` in both hooks so payloads with leading `-n`/`-e`/`-E` or backslashes are not eaten by echo flag parsing. - Wrap the `last_python_err.log` and `last_input.log` writes in a `( umask 077; ... )` subshell so the files are created at mode 0600 atomically. The existing `chmod 600` calls stay as belt-and-suspenders. - Refactor the `_run_hook` test helper: internal assert on returncode with stderr surfaced in the failure message; new `extra_env=` kwarg subsumes the ad-hoc `subprocess.run` in the UTF-8 locale test. - Promote the world-readable, bounded-overwrite, UTF-8, unicode and literal-unknown tests to a shared `_BOTH_HOOKS` parametrize with readable ids so the symmetry across both hooks is enforced. - `test_sed_extraction_present` strips line comments before counting `sed -n '` occurrences so a regression that swapped sed back to mapfile while keeping the prose cannot false-pass. - Rewrite the precompact hook header docblock: the previous "ALWAYS blocks" wording was stale (the hook returns `{}` and does not emit a `decision: block` payload to the Stop-hook protocol; the "always run" guarantee comes from the synchronous mine call). - Apply ruff 0.4.x format to the new test file (matches CI pin `pip install "ruff>=0.4.0,<0.5"`). Tests: 1749 passed (was 21 cases in c271e7b's test file; now 26 after parametrize promotions, +5 cases). --- hooks/mempal_precompact_hook.sh | 37 ++++-- hooks/mempal_save_hook.sh | 30 ++++- tests/test_hooks_bash_compat.py | 208 +++++++++++++++++++------------- 3 files changed, 177 insertions(+), 98 deletions(-) diff --git a/hooks/mempal_precompact_hook.sh b/hooks/mempal_precompact_hook.sh index edaf686..acbe3b1 100755 --- a/hooks/mempal_precompact_hook.sh +++ b/hooks/mempal_precompact_hook.sh @@ -8,8 +8,12 @@ # context about what was discussed. This hook forces one final save of # EVERYTHING before that happens. # -# Unlike the save hook (which triggers every N exchanges), this ALWAYS -# blocks — because compaction is always worth saving before. +# Unlike the save hook (which gates on a message-count threshold and on +# MEMPAL_VERBOSE), this runs the mine synchronously on every PreCompact +# event — compaction is always worth saving before. The hook itself +# returns ``{}`` so it does not emit a ``decision: block`` to Claude +# Code; the "always run" semantics live in the mine call, not in the +# Stop-hook block protocol. # # === INSTALL === # Add to .claude/settings.local.json: @@ -35,10 +39,15 @@ # === HOW IT WORKS === # # Claude Code sends JSON on stdin with: -# session_id — unique session identifier +# session_id — unique session identifier +# transcript_path — path to the JSONL transcript file # -# We always return decision: "block" with a reason telling the AI -# to save everything. After the AI saves, compaction proceeds normally. +# The hook runs the transcript mine synchronously (the foreground +# ``mempalace mine`` call below blocks until it returns), then prints +# ``{}`` to stdout so Claude Code proceeds with the compaction. We do +# not emit a ``decision: block`` to the hook protocol — the +# "always save before compaction" guarantee is provided by the +# synchronous mine, not by the Stop-hook block contract. # # === MEMPALACE CLI === # The hook ALWAYS mines the active conversation transcript synchronously @@ -78,7 +87,16 @@ INPUT=$(cat) # Python stderr is captured to last_python_err.log so the guard below can # distinguish "bad user input" from "broken interpreter / future regression # in this inline script". Same diagnostic contract as mempal_save_hook.sh. -_mempal_parsed=$(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " +# +# ``umask 077`` inside the command-substitution subshell makes the +# ``2>$STATE_DIR/last_python_err.log`` redirect create the file at mode +# 0600 atomically, closing the TOCTOU window between creation at +# umask-default and the ``chmod 600`` below. ``printf '%s'`` replaces +# ``echo`` so payloads beginning with ``-n``/``-e``/``-E`` or containing +# backslashes are not mangled by echo flag parsing. +_mempal_parsed=$( + umask 077 + printf '%s' "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " import sys, json, re data = json.load(sys.stdin) sid = data.get('session_id', '') @@ -87,7 +105,8 @@ safe = lambda s: re.sub(r'[^a-zA-Z0-9_/.\-~]', '', str(s)) print('__MEMPAL_PARSE_OK__') print(safe(sid)) print(safe(tp)) -" 2>"$STATE_DIR/last_python_err.log") +" 2>"$STATE_DIR/last_python_err.log" +) # Drop the empty file on success; chmod 600 on failure to mirror # last_input.log's privacy contract. if [ -s "$STATE_DIR/last_python_err.log" ]; then @@ -116,7 +135,9 @@ if [ -n "$INPUT" ] && [ "$_MEMPAL_PARSE_MARKER" != "__MEMPAL_PARSE_OK__" ]; then # would count characters under UTF-8 and slip a multibyte payload past # the bound. ``set -o pipefail`` is not enabled in this script so the # natural SIGPIPE-on-printf from ``head`` closing stdin is absorbed. - printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" + # ``umask 077`` in the subshell creates last_input.log at mode 0600 + # atomically — the ``chmod 600`` below stays as belt-and-suspenders. + ( umask 077 && printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" ) chmod 600 "$STATE_DIR/last_input.log" 2>/dev/null fi diff --git a/hooks/mempal_save_hook.sh b/hooks/mempal_save_hook.sh index 52a404d..66edea4 100755 --- a/hooks/mempal_save_hook.sh +++ b/hooks/mempal_save_hook.sh @@ -105,7 +105,25 @@ INPUT=$(cat) # / future regression in this inline script" (ImportError, SyntaxError, # ModuleNotFoundError). Without the stderr capture, last_input.log shows # a valid payload while the actual root cause stays hidden. -_mempal_parsed=$(echo "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " +# +# Two extra hardenings inside the command-substitution subshell: +# +# * ``umask 077`` so the ``2>$STATE_DIR/last_python_err.log`` redirect +# creates the file at mode 0600 atomically. Without it, the file +# appeared briefly at the parent process's umask (often 0644) before +# the explicit ``chmod 600`` below closed it — a small TOCTOU window +# where another local user on a shared box could read the traceback, +# which can echo back the user's home + project layout. +# +# * ``printf '%s'`` in place of ``echo``. ``echo`` is unreliable for +# arbitrary payloads: it interprets ``-n``/``-e``/``-E`` as flags, +# handles backslashes inconsistently across builtin vs /bin/echo, +# and depends on the ``xpg_echo`` shopt on bash. JSON typically +# starts with ``{`` so the failure mode is latent, but flipping to +# ``printf '%s'`` removes the class of bug entirely. +_mempal_parsed=$( + umask 077 + printf '%s' "$INPUT" | "$MEMPAL_PYTHON_BIN" -c " import sys, json, re data = json.load(sys.stdin) sid = data.get('session_id', '') @@ -119,7 +137,8 @@ print('__MEMPAL_PARSE_OK__') print(safe(sid)) print(sha) print(safe(tp)) -" 2>"$STATE_DIR/last_python_err.log") +" 2>"$STATE_DIR/last_python_err.log" +) # The 2> redirect creates the file even when stderr is empty (success). # Remove the empty file so the state directory stays clean on the happy # path; on failure, lock the file's permissions to 600 to mirror @@ -154,8 +173,11 @@ if [ -n "$INPUT" ] && [ "$_MEMPAL_PARSE_MARKER" != "__MEMPAL_PARSE_OK__" ]; then # to 4x. ``set -o pipefail`` is not enabled in this script, so the # natural ``head``-closes-stdin / SIGPIPE-on-printf interaction is # silently absorbed by bash (the canonical way to read N bytes from - # a string in shell). - printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" + # a string in shell). The ``umask 077`` subshell creates + # last_input.log at mode 0600 atomically — the ``chmod 600`` below + # stays as a belt-and-suspenders guard if a future edit drops the + # umask line. + ( umask 077 && printf '%s' "$INPUT" | head -c 4096 > "$STATE_DIR/last_input.log" ) chmod 600 "$STATE_DIR/last_input.log" 2>/dev/null fi diff --git a/tests/test_hooks_bash_compat.py b/tests/test_hooks_bash_compat.py index c2dc2fb..41c37f8 100644 --- a/tests/test_hooks_bash_compat.py +++ b/tests/test_hooks_bash_compat.py @@ -11,7 +11,7 @@ These tests cover: 2. Behavioral parse contract (session_id reaches the log, not 'unknown'). 3. The fail-loud guard: fires only when the parser sentinel is missing, never on a legitimately empty/unicode/literal-'unknown' session_id. -4. The guard's disk discipline (bounded dump, overwrite-not-append). +4. The guard's disk discipline (bounded dump, overwrite-not-append, 0600). """ from __future__ import annotations @@ -28,6 +28,15 @@ REPO_ROOT = Path(__file__).resolve().parent.parent SAVE_HOOK = REPO_ROOT / "hooks" / "mempal_save_hook.sh" PRECOMPACT_HOOK = REPO_ROOT / "hooks" / "mempal_precompact_hook.sh" +# Re-used by every parametrize decorator that runs the same test against +# both hooks. ``ids=`` keeps pytest output readable (`...[save_hook]` +# rather than the default `hook0`/`hook1`). +_BOTH_HOOKS = pytest.mark.parametrize( + "hook", + [SAVE_HOOK, PRECOMPACT_HOOK], + ids=["save_hook", "precompact_hook"], +) + pytestmark = pytest.mark.skipif(os.name == "nt", reason="bash hook scripts are POSIX-only") @@ -37,11 +46,27 @@ def _hook_src_no_comments(hook: Path) -> str: ) -def _run_hook(hook: Path, stdin: str, home: Path) -> tuple[int, str]: +def _run_hook( + hook: Path, + stdin: str, + home: Path, + *, + expected_rc: int = 0, + extra_env: dict | None = None, +) -> tuple[str, str]: + """Run a hook with a controlled environment and assert its exit code. + + Returns ``(stdout, stderr)``. On unexpected exit the assertion message + surfaces the captured stderr so CI failures are not silent (the hook + writes nothing useful to stdout on error, all diagnostics go to + stderr or hook.log). + """ env = { "HOME": str(home), "PATH": os.environ.get("PATH", "/usr/bin:/bin"), } + if extra_env: + env.update(extra_env) p = subprocess.run( ["bash", str(hook)], input=stdin, @@ -50,31 +75,41 @@ def _run_hook(hook: Path, stdin: str, home: Path) -> tuple[int, str]: env=env, timeout=30, ) - return p.returncode, p.stdout + assert p.returncode == expected_rc, ( + f"{hook.name} exited {p.returncode} (expected {expected_rc}); " + f"stderr={p.stderr!r}; stdout={p.stdout!r}" + ) + return p.stdout, p.stderr class TestNoBash4OnlyBuiltins: - """Source-level regression: mapfile/readarray unavailable on macOS bash 3.2.""" + """Source-level regression: bash 4.0 array-read builtins are unavailable on macOS bash 3.2.""" - @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + @_BOTH_HOOKS def test_no_mapfile(self, hook): code = _hook_src_no_comments(hook) - assert "mapfile" not in code, ( - f"{hook.name} uses mapfile, unavailable on macOS /bin/bash 3.2 (#1440)" - ) - assert "readarray" not in code, ( - f"{hook.name} uses readarray, unavailable on macOS /bin/bash 3.2 (#1440)" - ) + assert ( + "mapfile" not in code + ), f"{hook.name} uses mapfile, unavailable on macOS /bin/bash 3.2 (#1440)" + assert ( + "readarray" not in code + ), f"{hook.name} uses readarray, unavailable on macOS /bin/bash 3.2 (#1440)" - @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + @_BOTH_HOOKS def test_sed_extraction_present(self, hook): - src = hook.read_text() + # Strip ``#`` line comments before counting so the assertion fails + # if all live ``sed -n 'Np'`` calls are deleted but the explanatory + # comments above the parse block (which mention ``sed -n 'Np'`` + # several times in prose) are left behind — otherwise the test + # would false-pass on a regression that swapped the extraction + # method back to ``mapfile`` while keeping the old commentary. + src = _hook_src_no_comments(hook) # Each hook reads at least two values via ``sed -n 'Np'`` (sentinel + session_id). - assert src.count("sed -n '") >= 2, ( - f"{hook.name} must use sed -n 'Np' for POSIX-portable line extraction" - ) + assert ( + src.count("sed -n '") >= 2 + ), f"{hook.name} must use sed -n 'Np' for POSIX-portable line extraction" - @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + @_BOTH_HOOKS def test_bash_syntax_clean(self, hook): p = subprocess.run( ["bash", "-n", str(hook)], @@ -88,14 +123,13 @@ class TestSessionIdExtraction: """Hook must parse session_id from valid JSON, not fall back to 'unknown'.""" def test_save_hook_extracts_session_id(self, tmp_path): - rc, out = _run_hook( + out, _ = _run_hook( SAVE_HOOK, json.dumps( {"session_id": "abc12345", "stop_hook_active": False, "transcript_path": ""} ), tmp_path, ) - assert rc == 0 # Stdout must be valid JSON; Claude Code parses it. A regression that # leaks debug output here would silently break the harness contract. assert json.loads(out) == {}, f"hook stdout must be valid JSON, got: {out!r}" @@ -106,24 +140,25 @@ class TestSessionIdExtraction: assert "WARN: input parse failed" not in log state_dir = tmp_path / ".mempalace" / "hook_state" assert not (state_dir / "last_input.log").exists() - assert not (state_dir / "last_python_err.log").exists(), ( - "successful parse must leave no last_python_err.log behind" - ) + assert not ( + state_dir / "last_python_err.log" + ).exists(), "successful parse must leave no last_python_err.log behind" def test_precompact_hook_extracts_session_id(self, tmp_path): - rc, out = _run_hook( + out, _ = _run_hook( PRECOMPACT_HOOK, json.dumps({"session_id": "abc12345", "transcript_path": ""}), tmp_path, ) - assert rc == 0 assert json.loads(out) == {}, f"hook stdout must be valid JSON, got: {out!r}" log = (tmp_path / ".mempalace" / "hook_state" / "hook.log").read_text() assert "PRE-COMPACT triggered for session abc12345" in log assert "WARN: input parse failed" not in log state_dir = tmp_path / ".mempalace" / "hook_state" assert not (state_dir / "last_input.log").exists() - assert not (state_dir / "last_python_err.log").exists() + assert not ( + state_dir / "last_python_err.log" + ).exists(), "successful parse must leave no last_python_err.log behind" class TestFailLoudGuard: @@ -132,80 +167,92 @@ class TestFailLoudGuard: user-private. The guard must NOT fire on legitimately empty inputs or on sanitizer-stripped session_ids (#1440).""" - @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + @_BOTH_HOOKS def test_malformed_input_logs_warning_and_dumps_input(self, hook, tmp_path): - rc, _ = _run_hook(hook, "not-json garbage", tmp_path) - assert rc == 0 + _run_hook(hook, "not-json garbage", tmp_path) state_dir = tmp_path / ".mempalace" / "hook_state" log = (state_dir / "hook.log").read_text() last_input = (state_dir / "last_input.log").read_text() assert "WARN: input parse failed (sentinel missing)" in log assert "not-json garbage" in last_input - @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + @_BOTH_HOOKS def test_empty_stdin_does_not_dump_or_warn(self, hook, tmp_path): """Empty stdin is a legitimate state (e.g. a hook re-fire on Stop with no message body). The guard's ``[ -n "$INPUT" ]`` short-circuit must hold so nothing is written to last_input.log.""" - rc, _ = _run_hook(hook, "", tmp_path) - assert rc == 0 + _run_hook(hook, "", tmp_path) state_dir = tmp_path / ".mempalace" / "hook_state" assert not (state_dir / "last_input.log").exists() log_path = state_dir / "hook.log" if log_path.exists(): assert "WARN: input parse failed" not in log_path.read_text() - def test_unicode_session_id_does_not_trip_guard(self, tmp_path): + @_BOTH_HOOKS + def test_unicode_session_id_does_not_trip_guard(self, hook, tmp_path): """A session_id with non-ASCII characters (Cyrillic, CJK, emoji) is stripped by the sanitizer to '', defaults to 'unknown'. The - sentinel still printed, so the guard must skip and NOT spam disk.""" - rc, _ = _run_hook( - SAVE_HOOK, + sentinel still printed, so the guard must skip and NOT spam disk. + Parametrized over both hooks: each has its own inline Python + parser and its own sanitizer regex, so a copy-paste regression + in only one would otherwise be invisible. The precompact parser + ignores the ``stop_hook_active`` key, so the same payload works + for both.""" + _run_hook( + hook, json.dumps({"session_id": "сессия", "stop_hook_active": False, "transcript_path": ""}), tmp_path, ) - assert rc == 0 state_dir = tmp_path / ".mempalace" / "hook_state" - assert not (state_dir / "last_input.log").exists(), ( - "unicode-only session_id sanitized to empty must NOT trip the guard" - ) + assert not ( + state_dir / "last_input.log" + ).exists(), "unicode-only session_id sanitized to empty must NOT trip the guard" - def test_literal_unknown_session_id_does_not_trip_guard(self, tmp_path): + @_BOTH_HOOKS + def test_literal_unknown_session_id_does_not_trip_guard(self, hook, tmp_path): """A user who literally passes session_id='unknown' is parsing cleanly; the sentinel-based guard must distinguish that from a - crash and skip the dump.""" - rc, _ = _run_hook( - SAVE_HOOK, + crash and skip the dump. Parametrized over both hooks for the + same reason as the unicode test: the sentinel logic is duplicated + between the two parsers.""" + _run_hook( + hook, json.dumps({"session_id": "unknown", "stop_hook_active": False, "transcript_path": ""}), tmp_path, ) - assert rc == 0 state_dir = tmp_path / ".mempalace" / "hook_state" - assert not (state_dir / "last_input.log").exists(), ( - "literal session_id='unknown' must NOT trip the guard" - ) + assert not ( + state_dir / "last_input.log" + ).exists(), "literal session_id='unknown' must NOT trip the guard" - def test_dump_is_bounded_and_overwritten(self, tmp_path): + @_BOTH_HOOKS + def test_dump_is_bounded_and_overwritten(self, hook, tmp_path): """The dump caps at exactly 4096 bytes and overwrites on each failure so a repeating misconfiguration cannot grow the file - unbounded.""" + unbounded. Both payloads here are intentionally not-valid-JSON so + the guard fires on each call — the overwrite contract is what + is being tested, not the validation logic. Parametrized over + both hooks because each hook has its own ``head -c 4096 > ...`` + line — a future edit that flips one to ``>>`` would not be caught + by a save-only test.""" # 4097 bytes: one over the cap, proves the cutoff fires at exactly # 4096 (a regression that silently shrinks the cap to e.g. 1024 # would slip past a looser ``<= 4096`` check). big_payload = "x" * 4097 - rc, _ = _run_hook(SAVE_HOOK, big_payload, tmp_path) - assert rc == 0 + _run_hook(hook, big_payload, tmp_path) last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log" - assert last_input.stat().st_size == 4096, ( - f"cap must be exactly 4096 bytes; got {last_input.stat().st_size}" - ) - # Second failure with a smaller payload overwrites the first; the - # file shrinks instead of accumulating. - rc, _ = _run_hook(SAVE_HOOK, "tiny", tmp_path) - assert rc == 0 + assert ( + last_input.stat().st_size == 4096 + ), f"cap must be exactly 4096 bytes; got {last_input.stat().st_size}" + # Second failure with a smaller payload (also not valid JSON, so the + # guard fires) overwrites the first; the file shrinks instead of + # accumulating. + _run_hook(hook, "tiny", tmp_path) + assert last_input.exists(), "second guard fire must produce a file, not skip the write" assert last_input.read_text() == "tiny", "dump must overwrite on each failure, not append" - def test_dump_cap_holds_under_utf8_locale(self, tmp_path): + @_BOTH_HOOKS + def test_dump_cap_holds_under_utf8_locale(self, hook, tmp_path): """Under a UTF-8 locale, a multibyte payload of 2000 CJK chars = 6000 bytes would slip a character-counted substring (`${var:0:N}`) past the 4096-byte cap. The hook uses ``head -c`` precisely so @@ -215,23 +262,14 @@ class TestFailLoudGuard: # bash falls back to the byte-based C locale gracefully; # ``en_US.UTF-8`` would silently degrade to no-op on minimal CI # images (Alpine, distroless) where that locale is not generated. - env = { - "HOME": str(tmp_path), - "PATH": os.environ.get("PATH", "/usr/bin:/bin"), - "LANG": "C.UTF-8", - "LC_ALL": "C.UTF-8", - } # 2000 copies of U+4E2D (3 bytes each in UTF-8) = 6000 bytes. big_payload = "中" * 2000 - p = subprocess.run( - ["bash", str(SAVE_HOOK)], - input=big_payload, - capture_output=True, - text=True, - env=env, - timeout=30, + _run_hook( + hook, + big_payload, + tmp_path, + extra_env={"LANG": "C.UTF-8", "LC_ALL": "C.UTF-8"}, ) - assert p.returncode == 0 last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log" size = last_input.stat().st_size assert size == 4096, ( @@ -239,40 +277,38 @@ class TestFailLoudGuard: "regression to ${var:0:N} would let multibyte input bypass the bound" ) - def test_dump_is_not_world_readable(self, tmp_path): - """The dump mirrors the raw Stop payload (transcript_path reveals + @_BOTH_HOOKS + def test_dump_is_not_world_readable(self, hook, tmp_path): + """The dump mirrors the raw hook payload (transcript_path reveals the user's home + project layout). Permissions must be 600 so other users on a shared box cannot read it.""" - rc, _ = _run_hook(SAVE_HOOK, "not-json garbage", tmp_path) - assert rc == 0 + _run_hook(hook, "not-json garbage", tmp_path) last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log" mode = stat.S_IMODE(last_input.stat().st_mode) assert mode == 0o600, f"last_input.log mode should be 0600, got {oct(mode)}" - @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + @_BOTH_HOOKS def test_python_stderr_captured_on_parse_failure(self, hook, tmp_path): """When the inline Python parser crashes (malformed JSON, missing interpreter, future regression), its stderr must land in last_python_err.log so a debugger can distinguish 'bad user input' from 'broken interpreter or broken inline script'.""" - rc, _ = _run_hook(hook, "not-json garbage", tmp_path) - assert rc == 0 + _run_hook(hook, "not-json garbage", tmp_path) err_log = tmp_path / ".mempalace" / "hook_state" / "last_python_err.log" assert err_log.exists(), "Python stderr must be captured on parse failure" contents = err_log.read_text() # Python's json.load raises JSONDecodeError with a recognizable # traceback. Don't pin the exact message (it varies by Python # version) but assert at least one canonical marker is present. - assert "Traceback" in contents or "json" in contents.lower(), ( - f"expected Python traceback or json error, got: {contents!r}" - ) + assert ( + "Traceback" in contents or "json" in contents.lower() + ), f"expected Python traceback or json error, got: {contents!r}" - @pytest.mark.parametrize("hook", [SAVE_HOOK, PRECOMPACT_HOOK]) + @_BOTH_HOOKS def test_python_stderr_log_is_not_world_readable_on_failure(self, hook, tmp_path): """The stderr capture mirrors the privacy expectation of last_input.log: on a populated failure write it must be 0600.""" - rc, _ = _run_hook(hook, "not-json garbage", tmp_path) - assert rc == 0 + _run_hook(hook, "not-json garbage", tmp_path) err_log = tmp_path / ".mempalace" / "hook_state" / "last_python_err.log" mode = stat.S_IMODE(err_log.stat().st_mode) assert mode == 0o600, f"last_python_err.log mode should be 0600 on failure, got {oct(mode)}" From c736a57078bde552d0872da781e10506c4d3d9ec Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Mon, 11 May 2026 05:33:15 +0500 Subject: [PATCH 45/64] test(hooks): force umask 022 in test subprocess (#1440) Cycle 2 follow-up: harden the permission tests so they actively falsify the "ambient umask masking a regression" hypothesis raised during the adversarial review pass. - `_run_hook` now sets `preexec_fn=lambda: os.umask(0o022)` on the bash subprocess. The child starts with a permissive 022 umask so a bare file would land at mode 0644. The hook's own `umask 077` in the parse subshell remains the only thing protecting `last_python_err.log` and `last_input.log`, so `test_dump_is_not_world_readable` and `test_python_stderr_log_is_not_world_readable_on_failure` now empirically prove that protection rather than passively benefitting from a CI runner's restrictive ambient umask. - Docstring precision: the helper's primary diagnostic surface is `hook.log` (a file under `STATE_DIR`), not the subprocess's stderr. Subprocess stderr is captured here only to surface unexpected interpreter failures (e.g., a bash syntax error introduced by a future edit), and the docstring now says so. No production-code changes. 26/26 tests still pass. --- tests/test_hooks_bash_compat.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tests/test_hooks_bash_compat.py b/tests/test_hooks_bash_compat.py index 41c37f8..05fda22 100644 --- a/tests/test_hooks_bash_compat.py +++ b/tests/test_hooks_bash_compat.py @@ -57,9 +57,18 @@ def _run_hook( """Run a hook with a controlled environment and assert its exit code. Returns ``(stdout, stderr)``. On unexpected exit the assertion message - surfaces the captured stderr so CI failures are not silent (the hook - writes nothing useful to stdout on error, all diagnostics go to - stderr or hook.log). + surfaces the captured stderr so CI failures are not silent. The hook's + primary diagnostic stream is ``$STATE_DIR/hook.log`` plus the two + sidecar dumps ``last_input.log`` / ``last_python_err.log``; the + subprocess's stderr is typically empty on the documented exit paths + and is captured here only to surface unexpected interpreter failures + (e.g., a bash syntax error on a future edit). + + Forces ``umask 0o022`` in the child so the hook's own ``umask 077`` + inside the parse subshell is provably the sole reason the diagnostic + files end up at mode 0600 — without this, a permissive ambient umask + on the CI runner would mask a regression that drops the in-hook + ``umask`` line. """ env = { "HOME": str(home), @@ -74,6 +83,7 @@ def _run_hook( text=True, env=env, timeout=30, + preexec_fn=lambda: os.umask(0o022), ) assert p.returncode == expected_rc, ( f"{hook.name} exited {p.returncode} (expected {expected_rc}); " From 1988f3dc911724c4aea046e8cd6c5ed086d59946 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Fri, 15 May 2026 19:05:25 +0500 Subject: [PATCH 46/64] ci: retrigger after #1520 unblocked develop lint From 92de001c204e54029da710ff9ac1f8215568176f Mon Sep 17 00:00:00 2001 From: Rahul Date: Sat, 16 May 2026 17:55:10 +0530 Subject: [PATCH 47/64] fix(convo_miner): scope skip-check and drawer ids by extract_mode (#1505) Mining a transcript with --extract general was silently skipped when the same file had already been mined with --extract exchange (or vice versa) because file_already_mined() and prefetch_mined_set() only looked at source_file. The two extraction modes produce different drawer content and rooms, so they should coexist for the same source. Changes: - file_already_mined() and prefetch_mined_set() take an optional extract_mode arg and only return True when stored drawer metadata matches. Legacy drawers without extract_mode are treated as exchange-mode for back-compat. - _file_chunks_locked() purges only same-mode drawers when rebuilding on a normalize-version bump, so a schema bump on one mode does not drop drawers filed under the other. - Drawer ids and sentinel ids include extract_mode so the two modes cannot collide on hash. - Pagination on the direct skip-check path so large transcripts (>1k drawers) are classified correctly when the bulk prefetch is skipped. Adds regression coverage for the extract-mode-aware helper, the pagination path, and an end-to-end mine_convos run that files exchange then general for the same transcript without skipping. --- mempalace/convo_miner.py | 57 +++++++++++++++++++++---- mempalace/palace.py | 59 ++++++++++++++++++++++--- tests/test_convo_miner.py | 38 +++++++++++++++-- tests/test_convo_miner_unit.py | 2 +- tests/test_miner.py | 78 +++++++++++++++++++++++++++++++++- 5 files changed, 215 insertions(+), 19 deletions(-) diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index 24898d2..c14a02f 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -70,14 +70,15 @@ MAX_FILE_SIZE = 500 * 1024 * 1024 # 500 MB — skip files larger than this. # use also scales with source size. -def _register_file(collection, source_file: str, wing: str, agent: str): +def _register_file(collection, source_file: str, wing: str, agent: str, extract_mode: str): """Write a sentinel so file_already_mined() returns True for 0-chunk files. Without this, files that normalize to nothing or produce zero chunks are re-read and re-processed on every mine run because nothing was written to ChromaDB on the first pass. """ - sentinel_id = f"_reg_{hashlib.sha256(source_file.encode()).hexdigest()[:24]}" + sentinel_key = f"{source_file}:{extract_mode}" + sentinel_id = f"_reg_{hashlib.sha256(sentinel_key.encode()).hexdigest()[:24]}" collection.upsert( documents=[f"[registry] {source_file}"], ids=[sentinel_id], @@ -89,12 +90,42 @@ def _register_file(collection, source_file: str, wing: str, agent: str): "added_by": agent, "filed_at": datetime.now().isoformat(), "ingest_mode": "registry", + "extract_mode": extract_mode, "normalize_version": NORMALIZE_VERSION, } ], ) +def _source_file_delete_ids(collection, source_file: str, extract_mode: str) -> list[str]: + """Collect drawer IDs for one source file and extraction mode. + + Legacy conversation drawers did not carry extract_mode; treat those as + exchange-mode rows so schema rebuilds can still clean them up without + deleting newer general-mode drawers for the same transcript. + """ + ids: list[str] = [] + offset = 0 + while True: + batch = collection.get( + where={"source_file": source_file}, + limit=1000, + offset=offset, + include=["metadatas"], + ) + batch_ids = batch.get("ids") or [] + metadatas = batch.get("metadatas") or [] + for drawer_id, meta in zip(batch_ids, metadatas): + meta = meta or {} + stored_mode = meta.get("extract_mode") + if stored_mode == extract_mode or (extract_mode == "exchange" and stored_mode is None): + ids.append(drawer_id) + if not batch_ids: + break + offset += len(batch_ids) + return ids + + # ============================================================================= # CHUNKING — exchange pairs for conversations # ============================================================================= @@ -358,14 +389,16 @@ def _file_chunks_locked(collection, source_file, chunks, wing, room, agent, extr # Re-check after lock — another agent may have just finished this file # at the current schema. A stale-version hit here returns False, so we # still fall through to the purge+rebuild path below. - if file_already_mined(collection, source_file): + if file_already_mined(collection, source_file, extract_mode=extract_mode): return 0, room_counts_delta, True # Purge stale drawers first. When the normalize schema bumps, # file_already_mined() returned False for pre-v2 drawers — clean # them out so the source doesn't end up with mixed old/new drawers. try: - collection.delete(where={"source_file": source_file}) + delete_ids = _source_file_delete_ids(collection, source_file, extract_mode) + if delete_ids: + collection.delete(ids=delete_ids) except Exception: logger.debug("Stale-drawer purge failed for %s", source_file, exc_info=True) @@ -382,7 +415,11 @@ def _file_chunks_locked(collection, source_file, chunks, wing, room, agent, extr chunk_room = chunk.get("memory_type", room) if extract_mode == "general" else room if extract_mode == "general": room_counts_delta[chunk_room] += 1 - drawer_id = f"drawer_{wing}_{chunk_room}_{hashlib.sha256((source_file + str(chunk['chunk_index'])).encode()).hexdigest()[:24]}" + drawer_key = f"{source_file}:{extract_mode}:{chunk['chunk_index']}" + drawer_id = ( + f"drawer_{wing}_{chunk_room}_" + f"{hashlib.sha256(drawer_key.encode()).hexdigest()[:24]}" + ) batch_docs.append(chunk["content"]) batch_ids.append(drawer_id) batch_metas.append( @@ -478,7 +515,9 @@ def mine_convos( # palace each per-file query costs ~2s, so a 2000-file sweep used to # spend >1h just deciding to skip. prefetch_mined_set() does the same # decisions in a single scan; loop body becomes an O(1) set check. - mined_set: set[str] = prefetch_mined_set(collection) if not dry_run else set() + mined_set: set[str] = ( + prefetch_mined_set(collection, extract_mode=extract_mode) if not dry_run else set() + ) total_drawers = 0 files_skipped = 0 @@ -497,12 +536,12 @@ def mine_convos( content = normalize(str(filepath)) except (OSError, ValueError): if not dry_run: - _register_file(collection, source_file, wing, agent) + _register_file(collection, source_file, wing, agent, extract_mode) continue if not content or len(content.strip()) < cfg_min_chunk_size: if not dry_run: - _register_file(collection, source_file, wing, agent) + _register_file(collection, source_file, wing, agent, extract_mode) continue # Chunk — either exchange pairs or general extraction @@ -520,7 +559,7 @@ def mine_convos( if not chunks: if not dry_run: - _register_file(collection, source_file, wing, agent) + _register_file(collection, source_file, wing, agent, extract_mode) continue # Detect room from content (general mode uses memory_type instead) diff --git a/mempalace/palace.py b/mempalace/palace.py index 38c3979..3e3cfa7 100644 --- a/mempalace/palace.py +++ b/mempalace/palace.py @@ -531,7 +531,19 @@ def mine_palace_lock(palace_path: str): mine_global_lock = mine_palace_lock -def file_already_mined(collection, source_file: str, check_mtime: bool = False) -> bool: +def _metadata_matches_extract_mode(meta: dict, extract_mode: Optional[str]) -> bool: + if extract_mode is None: + return True + stored_mode = meta.get("extract_mode") + return stored_mode == extract_mode or (extract_mode == "exchange" and stored_mode is None) + + +def file_already_mined( + collection, + source_file: str, + check_mtime: bool = False, + extract_mode: Optional[str] = None, +) -> bool: """Check if a file has already been filed in the palace. Returns False (so the file gets re-mined) when: @@ -543,12 +555,43 @@ def file_already_mined(collection, source_file: str, check_mtime: bool = False) When check_mtime=True (used by project miner), also re-mines on content change. When check_mtime=False (used by convo miner), transcripts are assumed immutable, so only the version gate triggers a rebuild. + + When extract_mode is set (used by convo miner), idempotency is scoped to + that extraction mode so exchange-mode and general-mode drawers can coexist + for the same source transcript. Legacy drawers without extract_mode are + treated as exchange-mode drawers. """ try: - results = collection.get(where={"source_file": source_file}, limit=1) - if not results.get("ids"): + stored_meta = None + if extract_mode is None: + results = collection.get(where={"source_file": source_file}, limit=1) + if not results.get("ids"): + return False + stored_meta = results.get("metadatas", [{}])[0] or {} + else: + offset = 0 + while True: + results = collection.get( + where={"source_file": source_file}, + limit=1000, + offset=offset, + include=["metadatas"], + ) + ids = results.get("ids") or [] + metadatas = results.get("metadatas") or [] + stored_meta = next( + ( + meta or {} + for meta in metadatas + if _metadata_matches_extract_mode(meta or {}, extract_mode) + ), + None, + ) + if stored_meta is not None or not ids: + break + offset += len(ids) + if stored_meta is None: return False - stored_meta = results.get("metadatas", [{}])[0] or {} # Pre-v2 drawers have no version field — treat them as stale. stored_version = stored_meta.get("normalize_version", 1) if stored_version < NORMALIZE_VERSION: @@ -593,7 +636,7 @@ def bulk_check_mined(collection) -> dict[str, float]: return mined -def prefetch_mined_set(collection) -> set[str]: +def prefetch_mined_set(collection, extract_mode: Optional[str] = None) -> set[str]: """Pre-fetch the set of source_files already mined at the current NORMALIZE_VERSION. Mirrors file_already_mined()'s version-gate semantics (check_mtime=False @@ -601,6 +644,9 @@ def prefetch_mined_set(collection) -> set[str]: Returns a set of source_file paths whose stored drawers are at or above NORMALIZE_VERSION; callers do `if path in result_set: skip`. + When extract_mode is set, mirrors file_already_mined(..., extract_mode=...) + so conversation mines skip per extraction mode rather than per source file. + The convo miner walks thousands of transcript files; per-file `collection.get(where={"source_file": X})` costs ~2s on a 150k-drawer palace, making a 2000-file sweep take >1h of pure skip-checking. This @@ -613,9 +659,12 @@ def prefetch_mined_set(collection) -> set[str]: while offset < total: batch = collection.get(limit=1000, offset=offset, include=["metadatas"]) for meta in batch["metadatas"]: + meta = meta or {} src = meta.get("source_file") if not src: continue + if not _metadata_matches_extract_mode(meta, extract_mode): + continue # Same default as file_already_mined: missing version == 1 version = meta.get("normalize_version", 1) if version >= NORMALIZE_VERSION: diff --git a/tests/test_convo_miner.py b/tests/test_convo_miner.py index 166644b..af7a283 100644 --- a/tests/test_convo_miner.py +++ b/tests/test_convo_miner.py @@ -77,6 +77,38 @@ def test_mine_convos_does_not_reprocess_empty_chunk_files(capsys): shutil.rmtree(tmpdir, ignore_errors=True) +def test_mine_convos_allows_general_after_exchange(capsys): + """A transcript mined as exchange can later be mined as general memories.""" + tmpdir = tempfile.mkdtemp() + try: + convo_path = Path(tmpdir) / "chat.txt" + convo_path.write_text( + "> What did we decide?\n" + "We decided to use SQLite because it keeps the local setup simple.\n\n" + "> What broke?\n" + "The search failed because the old index was stale, and the fix was rebuild.\n" + ) + palace_path = os.path.join(tmpdir, "palace") + + mine_convos(tmpdir, palace_path, wing="test", extract_mode="exchange") + capsys.readouterr() + mine_convos(tmpdir, palace_path, wing="test", extract_mode="general") + out = capsys.readouterr().out + + assert "Files skipped (already filed): 0" in out + + client = chromadb.PersistentClient(path=palace_path) + col = client.get_collection("mempalace_drawers") + resolved = str(Path(tmpdir).resolve() / "chat.txt") + rows = col.get(where={"source_file": resolved}, include=["metadatas"]) + modes = {meta.get("extract_mode") for meta in rows["metadatas"]} + assert {"exchange", "general"} <= modes + assert any(drawer_id.startswith("drawer_test_decision_") for drawer_id in rows["ids"]) + del col, client + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + + def test_mine_convos_rebuilds_stale_drawers_after_schema_bump(capsys): """When stored drawers have an older normalize_version, the next mine silently purges them and refiles — no manual erase required. @@ -140,9 +172,9 @@ def test_mine_convos_rebuilds_stale_drawers_after_schema_bump(capsys): # Second mine — version gate should trigger rebuild mine_convos(tmpdir, palace_path, wing="test") out = capsys.readouterr().out - assert ( - "Files skipped (already filed): 0" in out - ), "stale drawers should force a rebuild, not a skip" + assert "Files skipped (already filed): 0" in out, ( + "stale drawers should force a rebuild, not a skip" + ) client = chromadb.PersistentClient(path=palace_path) col = client.get_collection("mempalace_drawers") diff --git a/tests/test_convo_miner_unit.py b/tests/test_convo_miner_unit.py index 90ad573..7ff7a91 100644 --- a/tests/test_convo_miner_unit.py +++ b/tests/test_convo_miner_unit.py @@ -239,7 +239,7 @@ class TestFileChunksLocked: col = FakeCol() monkeypatch.setattr(convo_miner, "DRAWER_UPSERT_BATCH_SIZE", 2) monkeypatch.setattr( - convo_miner, "file_already_mined", lambda collection, source_file: False + convo_miner, "file_already_mined", lambda collection, source_file, **kwargs: False ) monkeypatch.setattr(convo_miner, "mine_lock", lambda source_file: contextlib.nullcontext()) monkeypatch.setattr(convo_miner, "_detect_hall_cached", lambda content: "conversations") diff --git a/tests/test_miner.py b/tests/test_miner.py index d58ef92..5053527 100644 --- a/tests/test_miner.py +++ b/tests/test_miner.py @@ -10,7 +10,7 @@ import pytest import yaml from mempalace.miner import detect_room, load_config, mine, scan_project, status -from mempalace.palace import NORMALIZE_VERSION, file_already_mined +from mempalace.palace import NORMALIZE_VERSION, file_already_mined, prefetch_mined_set def write_file(path: Path, content: str): @@ -406,6 +406,82 @@ def test_file_already_mined_check_mtime(): shutil.rmtree(tmpdir, ignore_errors=True) +def test_file_already_mined_scopes_convo_extract_mode(): + tmpdir = tempfile.mkdtemp() + try: + palace_path = os.path.join(tmpdir, "palace") + os.makedirs(palace_path) + client = chromadb.PersistentClient(path=palace_path) + col = client.get_or_create_collection( + "mempalace_drawers", metadata={"hnsw:space": "cosine"} + ) + + source_file = os.path.join(tmpdir, "chat.jsonl") + col.add( + ids=["exchange"], + documents=["exchange drawer"], + metadatas=[ + { + "source_file": source_file, + "extract_mode": "exchange", + "normalize_version": NORMALIZE_VERSION, + } + ], + ) + + assert file_already_mined(col, source_file, extract_mode="exchange") is True + assert file_already_mined(col, source_file, extract_mode="general") is False + assert source_file in prefetch_mined_set(col, extract_mode="exchange") + assert source_file not in prefetch_mined_set(col, extract_mode="general") + + col.add( + ids=["general"], + documents=["general drawer"], + metadatas=[ + { + "source_file": source_file, + "extract_mode": "general", + "normalize_version": NORMALIZE_VERSION, + } + ], + ) + + assert file_already_mined(col, source_file, extract_mode="general") is True + assert source_file in prefetch_mined_set(col, extract_mode="general") + finally: + del col, client + shutil.rmtree(tmpdir, ignore_errors=True) + + +def test_file_already_mined_extract_mode_paginates_large_sources(): + source_file = "/tmp/long-chat.jsonl" + metadatas = [ + { + "source_file": source_file, + "extract_mode": "exchange", + "normalize_version": NORMALIZE_VERSION, + } + for _ in range(1000) + ] + metadatas.append( + { + "source_file": source_file, + "extract_mode": "general", + "normalize_version": NORMALIZE_VERSION, + } + ) + + class FakeCollection: + def get(self, where=None, limit=1, offset=0, include=None): + batch = metadatas[offset : offset + limit] + return { + "ids": [f"id-{i}" for i in range(offset, offset + len(batch))], + "metadatas": batch, + } + + assert file_already_mined(FakeCollection(), source_file, extract_mode="general") is True + + def test_mine_dry_run_with_tiny_file_no_crash(): """Dry-run must not crash when process_file returns 0 drawers (room was None).""" tmpdir = tempfile.mkdtemp() From 2bf36210e99ec516121e4c11880d061331a4c5be Mon Sep 17 00:00:00 2001 From: Rahul Date: Sat, 16 May 2026 18:15:44 +0530 Subject: [PATCH 48/64] refactor(convo_miner): reuse _metadata_matches_extract_mode helper Address PR #1528 review feedback (gemini-code-assist, medium): _source_file_delete_ids duplicated the legacy-drawer matching logic that already lives in palace._metadata_matches_extract_mode. Import the helper and call it instead so the back-compat rule (legacy drawers without extract_mode count as exchange-mode) has a single source of truth. No behavior change. All 71 miner/convo tests still pass. --- mempalace/convo_miner.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/mempalace/convo_miner.py b/mempalace/convo_miner.py index c14a02f..02a5aca 100644 --- a/mempalace/convo_miner.py +++ b/mempalace/convo_miner.py @@ -20,6 +20,7 @@ from .normalize import normalize from .palace import ( NORMALIZE_VERSION, SKIP_DIRS, + _metadata_matches_extract_mode, file_already_mined, get_collection, mine_lock, @@ -116,9 +117,7 @@ def _source_file_delete_ids(collection, source_file: str, extract_mode: str) -> batch_ids = batch.get("ids") or [] metadatas = batch.get("metadatas") or [] for drawer_id, meta in zip(batch_ids, metadatas): - meta = meta or {} - stored_mode = meta.get("extract_mode") - if stored_mode == extract_mode or (extract_mode == "exchange" and stored_mode is None): + if _metadata_matches_extract_mode(meta or {}, extract_mode): ids.append(drawer_id) if not batch_ids: break From fba6372f2cf4c2008eb81113e3e259afb6e684d9 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sat, 16 May 2026 20:48:23 +0500 Subject: [PATCH 49/64] fix(tunnels): preserve hyphenated wing slugs in create_tunnel write-path (#1504) create_tunnel no longer normalizes hyphen->underscore on write. Wings created via "mempalace mine --wing my-wing" are stored verbatim in tunnels.json. list_tunnels and follow_tunnels filters normalize both the stored value and the query at compare time so previously-stored underscore tunnels and post-fix verbatim tunnels both resolve via either query form. compute_topic_tunnels canonicalizes its wing keys via normalize_wing_name so repeated mining runs with mixed slug forms cannot accumulate parallel duplicate tunnels. topic_tunnels_for_wing gains a symmetric lookup so a hyphenated argument finds an underscore-keyed registry entry. _normalize_wing now returns None for non-string inputs instead of raising; read-path filters use the (t.get(k) or {}) idiom so hand-edited records with "source": null no longer crash iteration. --- mempalace/palace_graph.py | 68 +++++++++++++---- tests/test_mcp_server.py | 20 +++++ tests/test_palace_graph_tunnels.py | 118 +++++++++++++++++++++++++++-- 3 files changed, 185 insertions(+), 21 deletions(-) diff --git a/mempalace/palace_graph.py b/mempalace/palace_graph.py index d32f9a2..7567bf9 100644 --- a/mempalace/palace_graph.py +++ b/mempalace/palace_graph.py @@ -43,8 +43,12 @@ def _normalize_wing(wing: str | None) -> str | None: (e.g. ``mempalace_public``). Callers that pass the raw directory name (``mempalace-public``) would silently miss. This helper aligns the lookup key with the stored metadata. + + Non-string inputs (from corrupt or hand-edited ``tunnels.json``) return + ``None`` rather than raising, so a single malformed record cannot break + the read-path filters that iterate the whole file. """ - if wing is None: + if not isinstance(wing, str): return None wing = wing.strip() if not wing: @@ -432,7 +436,8 @@ def create_tunnel( Tunnels are undirected: ``create_tunnel(A, B)`` and ``create_tunnel(B, A)`` resolve to the same canonical ID. A second call with the same endpoints updates the stored label (and drawer IDs, if provided) rather than - creating a duplicate. + creating a duplicate. Endpoints are compared **verbatim** — ``"my-wing"`` + and ``"my_wing"`` are distinct (see Note below and #1504). The ``source`` / ``target`` fields on the returned dict preserve the argument order the caller used, so callers can display it directionally @@ -457,15 +462,19 @@ def create_tunnel( Raises: ValueError: if any wing or room is empty or non-string. + + Note: + Wing slugs are stored verbatim — passing ``"my-wing"`` and ``"my_wing"`` + produces two distinct tunnels (canonical IDs differ). Read-path helpers + (``list_tunnels`` / ``follow_tunnels``) normalize both sides at compare + time so legacy underscore data and explicit-flag hyphen data both + match queries in either form. See #1504. """ source_wing = _require_name(source_wing, "source_wing") source_room = _require_name(source_room, "source_room") target_wing = _require_name(target_wing, "target_wing") target_room = _require_name(target_room, "target_room") - source_wing = _normalize_wing(source_wing) - target_wing = _normalize_wing(target_wing) - tunnel_id = _canonical_tunnel_id(source_wing, source_room, target_wing, target_room) tunnel = { @@ -509,10 +518,17 @@ def list_tunnels(wing: str = None): norm_wing = _normalize_wing(wing) tunnels = _load_tunnels() if norm_wing: + # Normalize stored wings too: older tunnels.json records hold the + # underscore form (from the prior write-path normalization), while + # post-#1504 records hold whatever the caller passed. Comparing + # normalized-on-both-sides matches either. + # ``t.get(k) or {}`` (not ``t.get(k, {})``) handles ``"source": null`` + # from a hand-edited file — ``.get`` defaults only on missing keys. tunnels = [ t for t in tunnels - if t["source"]["wing"] == norm_wing or t["target"]["wing"] == norm_wing + if _normalize_wing((t.get("source") or {}).get("wing")) == norm_wing + or _normalize_wing((t.get("target") or {}).get("wing")) == norm_wing ] return tunnels @@ -532,15 +548,23 @@ def follow_tunnels(wing: str, room: str, col=None, config=None): Given a location (wing/room), finds all tunnels leading from or to it, and optionally fetches the connected drawer content. """ + # Fall back to raw ``wing`` so an empty/whitespace query string still + # produces a value to compare with; ``_normalize_wing`` returns ``None`` + # for empty input. Stored wings are normalized on the read path so the + # mempalace.yaml slug (underscore) and an explicit ``--wing`` slug + # (verbatim) both resolve through the same comparison. norm_wing = _normalize_wing(wing) or wing tunnels = _load_tunnels() connections = [] for t in tunnels: - src = t["source"] - tgt = t["target"] + # ``or {}`` (not ``.get(k, {})``) handles ``"source": null`` from a + # hand-edited file — ``.get`` defaults only on missing keys, not on + # explicit ``null`` values. + src = t.get("source") or {} + tgt = t.get("target") or {} - if src["wing"] == norm_wing and src["room"] == room: + if _normalize_wing(src.get("wing")) == norm_wing and src.get("room") == room: connections.append( { "direction": "outgoing", @@ -551,7 +575,7 @@ def follow_tunnels(wing: str, room: str, col=None, config=None): "tunnel_id": t["id"], } ) - elif tgt["wing"] == norm_wing and tgt["room"] == room: + elif _normalize_wing(tgt.get("wing")) == norm_wing and tgt.get("room") == room: connections.append( { "direction": "incoming", @@ -669,7 +693,12 @@ def compute_topic_tunnels( continue bucket.setdefault(key, n.strip()) if bucket: - wing_topics[wing.strip()] = bucket + # Auto-generated topic tunnels normalize the wing key so repeated + # mining runs with mixed slug forms (``my-wing`` vs ``my_wing``) + # produce one canonical record, not two parallel ones. User-issued + # ``create_tunnel`` calls (e.g. via MCP) preserve verbatim slugs; + # only this auto-generation path canonicalizes the key. + wing_topics[normalize_wing_name(wing.strip())] = bucket wings = sorted(wing_topics.keys()) created: list[dict] = [] @@ -713,8 +742,19 @@ def topic_tunnels_for_wing( if not topics_by_wing or not isinstance(wing, str) or not wing.strip(): return [] - wing = wing.strip() + # Canonicalize the lookup key so a hyphenated arg still finds an + # underscore-normalized entry (and vice versa). ``compute_topic_tunnels`` + # canonicalizes the keys it writes, so callers can pass either form. + wing = normalize_wing_name(wing.strip()) own = topics_by_wing.get(wing) + if own is None: + # Fallback: caller may have built ``topics_by_wing`` with verbatim + # keys (unusual but allowed). Try every entry, normalized, before + # giving up. + for k, v in topics_by_wing.items(): + if isinstance(k, str) and normalize_wing_name(k.strip()) == wing: + own = v + break if not isinstance(own, (list, tuple)) or not own: return [] @@ -724,7 +764,9 @@ def topic_tunnels_for_wing( # one place. created: list[dict] = [] for other, other_topics in topics_by_wing.items(): - if not isinstance(other, str) or not other.strip() or other == wing: + if not isinstance(other, str) or not other.strip(): + continue + if normalize_wing_name(other.strip()) == wing: continue if not isinstance(other_topics, (list, tuple)) or not other_topics: continue diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 8abfd95..be72507 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -882,6 +882,26 @@ class TestWriteTools: assert result["success"] is True assert result.get("noop") is True + def test_tool_create_tunnel_preserves_hyphenated_wings(self, monkeypatch, tmp_path): + """Regression for #1504: ``tool_create_tunnel`` stores the wing slug + verbatim, and both hyphen and underscore queries find the result.""" + from mempalace import mcp_server, palace_graph + + monkeypatch.setattr(palace_graph, "_TUNNEL_FILE", str(tmp_path / "tunnels.json")) + + t = mcp_server.tool_create_tunnel( + source_wing="other-wing", + source_room="r1", + target_wing="my-wing", + target_room="r2", + label="hyphen preservation", + ) + + assert t["source"]["wing"] == "other-wing" + assert t["target"]["wing"] == "my-wing" + assert len(mcp_server.tool_list_tunnels(wing="my-wing")) == 1 + assert len(mcp_server.tool_list_tunnels(wing="my_wing")) == 1 + # ── KG Tools ──────────────────────────────────────────────────────────── diff --git a/tests/test_palace_graph_tunnels.py b/tests/test_palace_graph_tunnels.py index c1fb6a2..99fccd5 100644 --- a/tests/test_palace_graph_tunnels.py +++ b/tests/test_palace_graph_tunnels.py @@ -73,6 +73,10 @@ class TestExplicitTunnels: assert palace_graph._normalize_wing(" Mempalace-Public ") == "mempalace_public" assert palace_graph._normalize_wing(" ") is None assert palace_graph._normalize_wing(None) is None + # Non-string inputs (corrupt or hand-edited tunnels.json) return None + # instead of raising — keeps read-path filters robust to bad records. + assert palace_graph._normalize_wing(42) is None + assert palace_graph._normalize_wing(["x"]) is None def test_create_tunnel_deduplicates_reverse_order_and_updates_label( self, tmp_path, monkeypatch @@ -287,6 +291,17 @@ class TestTopicTunnels: assert palace_graph.topic_tunnels_for_wing("wing_missing", topics_by_wing) == [] assert palace_graph.list_tunnels() == [] + def test_topic_tunnels_for_wing_matches_across_slug_forms(self, tmp_path, monkeypatch): + """The wing arg and ``topics_by_wing`` keys may carry different slug + forms (hyphen vs underscore). ``topic_tunnels_for_wing`` resolves + the lookup through ``normalize_wing_name`` so a caller passing + ``"my-wing"`` against a registry keyed by ``"my_wing"`` still wires + up the topic tunnels.""" + _use_tmp_tunnel_file(monkeypatch, tmp_path) + topics_by_wing = {"my_wing": ["Angular"], "wing_people": ["Angular"]} + created = palace_graph.topic_tunnels_for_wing("my-wing", topics_by_wing) + assert len(created) == 1 + def test_compute_topic_tunnels_dedupe_on_recompute(self, tmp_path, monkeypatch): _use_tmp_tunnel_file(monkeypatch, tmp_path) topics_by_wing = { @@ -335,13 +350,39 @@ class TestTopicTunnels: kinds = sorted(t["kind"] for t in tunnels) assert kinds == ["explicit", "topic"] + def test_compute_topic_tunnels_normalizes_wing_keys(self, tmp_path, monkeypatch): + """Auto-generated topic tunnels canonicalize the wing slug so two + mining runs with mixed forms (``my-wing`` then ``my_wing``) produce + a single deduped record. Only user-issued ``create_tunnel`` calls + preserve verbatim slugs (#1504); the topic-tunnel auto-generator + owns its own slugs and stays canonical.""" + _use_tmp_tunnel_file(monkeypatch, tmp_path) + + palace_graph.compute_topic_tunnels( + {"my-wing": ["Angular"], "wing_people": ["Angular"]}, min_count=1 + ) + palace_graph.compute_topic_tunnels( + {"my_wing": ["Angular"], "wing_people": ["Angular"]}, min_count=1 + ) + + tunnels = palace_graph.list_tunnels() + assert len(tunnels) == 1 + stored_wings = {tunnels[0]["source"]["wing"], tunnels[0]["target"]["wing"]} + assert stored_wings == {"my_wing", "wing_people"} + class TestHyphenatedWingNormalization: - """Wing names with hyphens or spaces are normalized to underscores on init. + """Wing names may reach ``tunnels.json`` in either form: - Tunnel helpers must apply the same normalization at lookup time so that - ``mempalace-public`` resolves to ``mempalace_public`` and matches the - metadata written by ``room_detector_local.py``. + * ``mempalace mine`` without ``--wing`` derives the slug from the dir + name through ``normalize_wing_name`` → stored as ``mempalace_public``. + * ``mempalace mine --wing my-wing`` (or any explicit slug) is stored + verbatim by ``create_tunnel`` (regression #1504) → ``my-wing``. + + Read-path helpers (``list_tunnels`` / ``follow_tunnels``) must accept + queries in either form and match both storage forms — normalization + is applied on both the stored value and the query key at comparison + time, never at write time. """ def test_list_tunnels_filters_hyphenated_wing(self, tmp_path, monkeypatch): @@ -363,14 +404,18 @@ class TestHyphenatedWingNormalization: assert len(by_under) == 1 assert by_hyphen[0]["connected_wing"] == "wing_people" - def test_create_tunnel_normalizes_wing_names(self, tmp_path, monkeypatch): + def test_create_tunnel_preserves_hyphenated_wing_names(self, tmp_path, monkeypatch): + """Regression for #1504: wings created via ``mempalace mine --wing my-wing`` + keep the hyphen in metadata, so ``create_tunnel`` must store the slug + verbatim. Read-path normalization in ``list_tunnels``/``follow_tunnels`` + keeps both query forms working.""" _use_tmp_tunnel_file(monkeypatch, tmp_path) t = palace_graph.create_tunnel("my-project", "src", "your-project", "dst", label="cross") - assert t["source"]["wing"] == "my_project" - assert t["target"]["wing"] == "your_project" - assert len(palace_graph.list_tunnels("my_project")) == 1 + assert t["source"]["wing"] == "my-project" + assert t["target"]["wing"] == "your-project" assert len(palace_graph.list_tunnels("my-project")) == 1 + assert len(palace_graph.list_tunnels("my_project")) == 1 def test_find_tunnels_warns_on_empty_result(self, tmp_path, monkeypatch, caplog): _use_tmp_tunnel_file(monkeypatch, tmp_path) @@ -379,3 +424,60 @@ class TestHyphenatedWingNormalization: result = palace_graph.find_tunnels("nonexistent-wing") assert result == [] assert "No tunnels found" in caplog.text + + def test_read_path_skips_records_with_null_endpoints(self, tmp_path, monkeypatch): + """A hand-edited ``tunnels.json`` may carry ``"source": null`` or + ``"target": null``. The read-path filters must skip such rows + instead of crashing the whole iteration with ``AttributeError``.""" + _use_tmp_tunnel_file(monkeypatch, tmp_path) + palace_graph._save_tunnels( + [ + { + "id": "broken", + "source": None, + "target": None, + "label": "corrupt", + "kind": "explicit", + "created_at": "2026-05-01T00:00:00+00:00", + }, + { + "id": "ok", + "source": {"wing": "wing_a", "room": "r1"}, + "target": {"wing": "wing_b", "room": "r2"}, + "label": "good", + "kind": "explicit", + "created_at": "2026-05-02T00:00:00+00:00", + }, + ] + ) + + # Both filters must skip the broken record and return the good one. + assert {t["id"] for t in palace_graph.list_tunnels("wing_a")} == {"ok"} + connections = palace_graph.follow_tunnels("wing_a", "r1") + assert [c["tunnel_id"] for c in connections] == ["ok"] + + def test_pre_1504_underscore_tunnels_remain_findable(self, tmp_path, monkeypatch): + """A ``tunnels.json`` written before #1504 stored wings in normalized + underscore form (the write-path normalization is now gone). Read-path + queries with either hyphen or underscore must still find those + records after the fix.""" + tunnel_file = _use_tmp_tunnel_file(monkeypatch, tmp_path) + palace_graph._save_tunnels( + [ + { + "id": "pre_1504_record", + "source": {"wing": "mempalace_public", "room": "auth"}, + "target": {"wing": "wing_people", "room": "users"}, + "label": "pre-#1504 record", + "kind": "explicit", + "created_at": "2026-05-10T00:00:00+00:00", + } + ] + ) + assert tunnel_file.exists() + + assert len(palace_graph.list_tunnels("mempalace_public")) == 1 + assert len(palace_graph.list_tunnels("mempalace-public")) == 1 + + assert len(palace_graph.follow_tunnels("mempalace_public", "auth")) == 1 + assert len(palace_graph.follow_tunnels("mempalace-public", "auth")) == 1 From cf96e68edfe78ec3fcc3a14ea9e86a8566ca882c Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 17 May 2026 00:57:13 +0500 Subject: [PATCH 50/64] fix(mcp): cold-start embedder diagnostics + opt-in warmup (#1495) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MCP clients (Claude Code, Claude Desktop) surface the cold-load of the ONNX/CoreML embedder + HNSW segment as -32000 "Internal tool error" without a recoverable trace, because the first chromadb-touching tool call after a fresh mempalace-mcp boot can exceed the client timeout. Two opt-in env vars, both default off, both fail-soft: - MEMPALACE_LOG_FILE: append-mode FileHandler so the server-side traceback that the MCP client never surfaces stays diagnosable. Invalid path falls back to stderr-only with a warning naming the env var, so it cannot itself become a server-start failure. basicConfig uses force=True so the FileHandler is not silently dropped when something already configured root logging. (OSError, ValueError) catch covers Windows NUL-byte paths in addition to POSIX missing-dir / EPERM. - MEMPALACE_EAGER_WARMUP: pre-loads embedder + HNSW segment at the end of main() startup via _get_collection(create=False).query(...) — a single call drives ONNX _download_model_if_not_exists + InferenceSession AND HNSW data_level0.bin segment load (HNSW chunks are read lazily on the first chromadb collection op). Fresh-install pre-check on os.path.isfile(palace/chroma.sqlite3) skips the warmup before any chromadb client call so the chromadb constructor cannot materialize the palace scaffold before `mempalace init` (preserves CLAUDE.md "Incremental only" invariant). Truthy 1/true/yes/on; falsy 0/false/no/off and empty are silent; unrecognized values warn so typos like "tru" do not silently disable the feature. All failure paths (collection-open-raise, returned-None, query-raise) log with palace path + device + error class so ops can disambiguate. Empirical evidence (Linux, CPU-only ONNX, ~1k drawers): first diary_write t_handoff = 7.60s baseline vs 0.17s with warmup (-7.4s shifted off the first-call window into startup). CoreML cold-load on macOS is reported at 5-30s in the issue's empirical record (paideia#114); the CPU baseline above is the floor. Tests (24 cases) cover both env vars across set/unset/empty/invalid/ garbage paths, warmup truthy/falsy/garbage parsing, fresh-install (real integration, no monkeypatch — pins zero on-disk side effect), collection-open-raise / returned-None / query-raise fail modes, and two regression pins: warning-before-banner ordering (guards delay=True regression) + truthy path actually invokes col.query (guards no-op warmup regression). Probe text is a sentinel so it cannot semantically match real drawer content. Co-Authored-By: StarshipSuperjam <33380501+StarshipSuperjam@users.noreply.github.com> --- mempalace/mcp_server.py | 219 +++++++++++++++++++++++- tests/test_mcp_server.py | 359 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 577 insertions(+), 1 deletion(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 17f6877..58e7aee 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -85,7 +85,70 @@ from .palace_graph import ( # noqa: E402 from .knowledge_graph import KnowledgeGraph, DEFAULT_KG_PATH # noqa: E402 -logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stderr) + +def _init_logging() -> None: + """Root-logger init: always stderr, optionally append to ``MEMPALACE_LOG_FILE``. + + Stderr-only is the default. When ``MEMPALACE_LOG_FILE`` is set, a + ``FileHandler`` is attached so MCP-client failures that the client + does not surface (e.g. the ``-32000`` cold-load timeout in #1495) + remain diagnosable from the file. + + Failure modes: + + * Invalid path (missing directory, no perms, Windows NUL byte) → + stderr-only with a warning. The env var must not become a new + server-start failure surface — that would defeat the diagnostic + goal. ``ValueError`` is included in the catch because Windows + raises it for paths with embedded NUL bytes, not ``OSError``. + * Root logger already configured (host app embedding the server, + transitive imports touching ``logging``) → ``force=True`` resets + the handlers so MEMPALACE_LOG_FILE's contract holds regardless + of what touched root logging first. Without ``force=True``, + ``basicConfig`` is a no-op when handlers exist and the env var + silently does nothing — exactly the diagnostic black hole #1495 + exists to close. + * Concurrent writers (multiple ``mempalace-mcp`` processes pointing + at the same path) interleave at the line level. The handler uses + append mode so nothing is overwritten, but operators running + Claude Code + Claude Desktop simultaneously should give each + process its own log path. + + ``delay=True`` is intentionally NOT set: deferring the open means an + invalid path raises at ``emit()`` time (unhandled), defeating the + fail-soft contract. With eager open the same error surfaces inside + ``FileHandler.__init__`` and lands in our ``except`` below. + + Module-level invocation: this function runs at import time, preserving + the side effect of the previous module-level ``logging.basicConfig`` + call. Callers that import ``mempalace.mcp_server`` for introspection + (``TOOLS`` dict, handler functions) inherit the reset; this matches + pre-PR behaviour and is intentional for an MCP entry-point module. + """ + handlers: list[logging.Handler] = [logging.StreamHandler(sys.stderr)] + # MEMPALACE_LOG_FILE is operator-supplied and opt-in; this is a + # local-first server (CLAUDE.md design principle), so no path + # sanitization — the operator's process UID is the trust boundary. + log_file = os.environ.get("MEMPALACE_LOG_FILE", "").strip() + file_handler_error: Exception | None = None + if log_file: + try: + handlers.append(logging.FileHandler(log_file, mode="a", encoding="utf-8")) + except (OSError, ValueError) as exc: + # Fail-soft: see "Invalid path" failure mode above. Broad on + # (OSError, ValueError) because Windows raises ValueError for + # NUL-byte paths while POSIX uses OSError for missing-dir / EPERM. + file_handler_error = exc + logging.basicConfig(level=logging.INFO, format="%(message)s", handlers=handlers, force=True) + if file_handler_error is not None: + logging.getLogger("mempalace_mcp").warning( + "MEMPALACE_LOG_FILE=%r could not be opened (%s); using stderr only", + log_file, + file_handler_error, + ) + + +_init_logging() logger = logging.getLogger("mempalace_mcp") @@ -2346,6 +2409,156 @@ def _restore_stdout(): sys.stdout = _REAL_STDOUT +_WARMUP_TRUTHY = {"1", "true", "yes", "on"} +_WARMUP_FALSY = {"", "0", "false", "no", "off"} +# Sentinel text for the warmup query. Distinctive so it cannot semantically +# match real drawer content (e.g. a palace containing notes about "warmup" +# routines) and is greppable in chromadb debug logs if the team ever adds +# request instrumentation. Single non-empty string is enough to trigger +# ChromaDB's ONNXMiniLM_L6_V2.__call__ → _download_model_if_not_exists + +# InferenceSession. +_WARMUP_PROBE_TEXT = "__mempalace_warmup_probe__" + + +def _describe_device_safe() -> str: + """Return ``embedding.describe_device()`` value or ``"unknown"`` on failure. + + Used only inside warmup-failure log lines; the import is deferred so + that an embedding-stack import error cannot itself crash the warmup + diagnostic path. + """ + try: + from .embedding import describe_device + + return describe_device() + except Exception: # fail-soft: see docstring — log-message helper must not crash + return "unknown" + + +def _maybe_eager_warmup_embedder() -> None: + """Pre-load embedder + HNSW segment at startup when ``MEMPALACE_EAGER_WARMUP`` is truthy. + + The first MCP tool call that touches chromadb (``diary_write``, + ``add_drawer``, ``search``) otherwise pays two compounding cold-load + costs that together can exceed the MCP client timeout and surface as + ``-32000`` "Internal tool error" with no recoverable trace on the + agent side (#1495): + + 1. ONNX/CoreML embedder init in :func:`mempalace.embedding.get_embedding_function` + (5–30s on first inference; ChromaDB's ``ONNXMiniLM_L6_V2.__call__`` + triggers ``_download_model_if_not_exists`` + ``InferenceSession``). + 2. HNSW segment cold-load (reading ``data_level0.bin`` into RAM on + first collection operation; seconds on palaces of 50k+ drawers). + + Warming via :func:`_get_collection`'s collection-then-query path + covers BOTH in a single startup-phase call — mirroring the reporter's + proposal in #1495 — so users with large existing palaces see the + same benefit as users on the embedder-only cost path. + + Truthy parsing accepts ``1/true/yes/on`` (case-insensitive); falsy + set ``0/false/no/off`` and empty/whitespace are silently off; any + other value logs a warning and stays off so typos like ``tru`` do + not silently disable the feature. + + Fresh-install guard (pre-check, NOT a catch): ``_get_collection``'s + retry layer absorbs ``_ChromaNotFoundError`` and returns ``None`` while + also materialising ``chroma.sqlite3`` on disk via the chromadb client + constructor. To preserve the documented "no palace yet → nothing to + warm" contract WITHOUT writing palace scaffolding before + ``mempalace init`` (which would violate CLAUDE.md "Incremental only"), + we test for ``chroma.sqlite3`` ourselves before touching the chromadb + client. Operators who set ``MEMPALACE_EAGER_WARMUP=1`` in their MCP + config and launch the server before running ``mempalace init`` get a + single INFO line and no on-disk side effect. + + Fail-soft beyond the fresh-install pre-check: + + * **Backend open failure** (palace path misconfigured, file locked, + corrupted HNSW that ``quarantine_stale_hnsw`` cannot recover) → + log exception with device + palace context and return. The next + embedding-requiring call sees the same fail mode it would have + without warmup. + * **`_get_collection` retried and returned None** → palace exists + but chromadb cannot open the collection (rare; usually a stale + sqlite + segment-files mismatch surfaced by `_get_client` rebuild). + A warning suffices because the retry layer already wrote two + tracebacks with the underlying chromadb error class. + * **Query failure** (network failure during ONNX model download, + provider init crash, runtime decoder error) → log exception with + device + palace context and return. Same fail-mode preservation. + + Note: on an existing palace with an empty collection (created via + ``mempalace init`` but never written to), ``col.query`` succeeds but + returns ``{'ids': [[]]}`` without reading any HNSW segment — the + embedder warms but there is no HNSW segment to load. The success log + still says ``embedder + HNSW ready`` because the no-HNSW-segment case + has zero cold-load cost; nothing was skipped that the first real tool + call would have paid. + """ + raw = os.environ.get("MEMPALACE_EAGER_WARMUP", "").strip().lower() + if raw in _WARMUP_FALSY: + return + if raw not in _WARMUP_TRUTHY: + logger.warning( + "MEMPALACE_EAGER_WARMUP=%r is not recognized (use one of %s); warmup disabled", + raw, + sorted(_WARMUP_TRUTHY | (_WARMUP_FALSY - {""})), + ) + return + palace_path = _config.palace_path + db_path = os.path.join(palace_path, "chroma.sqlite3") + if not os.path.isfile(db_path): + # Pre-check (NOT a try/except on _ChromaNotFoundError, which never + # propagates out of _get_collection — see docstring). No palace + # file means nothing to warm AND avoids the chromadb-client + # side effect of materialising the palace dir. + logger.info( + "MEMPALACE_EAGER_WARMUP=%s: no palace at %s — nothing to warm", + raw, + palace_path, + ) + return + # Cache device once: _describe_device_safe re-imports embedding stack + # each call, which is wasteful inside a function that already paid + # that cost via the warmup query below. + device = _describe_device_safe() + try: + col = _get_collection(create=False) + except Exception as exc: # fail-soft per docstring — broad on purpose + logger.exception( + "MEMPALACE_EAGER_WARMUP=%s: collection open failed (palace=%s, device=%s, error=%s)", + raw, + palace_path, + device, + type(exc).__name__, + ) + return + if col is None: + logger.warning( + "MEMPALACE_EAGER_WARMUP=%s: _get_collection returned None for palace=%s — see prior log lines", + raw, + palace_path, + ) + return + try: + col.query(query_texts=[_WARMUP_PROBE_TEXT], n_results=1) + except Exception as exc: # fail-soft per docstring — broad on purpose + logger.exception( + "MEMPALACE_EAGER_WARMUP=%s: warmup query failed (palace=%s, device=%s, error=%s)", + raw, + palace_path, + device, + type(exc).__name__, + ) + else: + logger.info( + "MEMPALACE_EAGER_WARMUP=%s: embedder + HNSW ready (palace=%s, device=%s)", + raw, + palace_path, + device, + ) + + def main(): """MCP server entry point for the ``mempalace-mcp`` console script. @@ -2377,6 +2590,10 @@ def main(): # is visible at startup rather than on first use (#1222). Pure # filesystem read; never opens a chromadb client. _refresh_vector_disabled_flag() + # Opt-in: pre-load the embedder so the first chromadb-write tool call + # does not pay the ONNX/CoreML cold-load tax under the MCP client + # timeout (#1495). Default off — preserves current startup latency. + _maybe_eager_warmup_embedder() while True: try: line = sys.stdin.readline() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 8abfd95..6a1f9a5 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -97,6 +97,365 @@ def _get_collection(palace_path, create=False): return client, client.get_collection("mempalace_drawers") +# ── Cold-start diagnostics (#1495) ────────────────────────────────────── + + +class TestColdStartDiagnostics: + """``MEMPALACE_LOG_FILE`` + ``MEMPALACE_EAGER_WARMUP`` (#1495). + + Each test runs ``main()`` in a fresh ``subprocess`` because + + * ``_init_logging`` uses ``logging.basicConfig(force=True)`` which + would otherwise reset pytest's ``caplog`` handlers across cases, + * ``ChromaBackend._resolve_embedding_function`` is a class-level + attribute that test monkeypatching mutates globally, + * The whole point of the new env vars is process-startup behaviour + and must be exercised under a real ``main()`` boot path. + + Pattern mirrors ``test_mcp_main_strips_leaked_pythonpath_from_env``. + ``_run_main`` injects ``extra_code`` as a hard-coded ``-c`` source + fragment from this file only (no untrusted input flows in); the + subprocess argv form ``[sys.executable, "-c", code]`` avoids shell + interpretation entirely. + """ + + @staticmethod + def _run_main(env_overrides: dict, extra_code: str = "", timeout: int = 30): + env = { + k: v + for k, v in os.environ.items() + if k not in env_overrides or env_overrides[k] is not None + } + for k, v in env_overrides.items(): + if v is None: + env.pop(k, None) + else: + env[k] = v + code = extra_code + "from mempalace.mcp_server import main\nmain()\n" + return subprocess.run( + [sys.executable, "-c", code], + env=env, + input="", # empty stdin → readline() returns '' → loop breaks immediately + capture_output=True, + text=True, + check=False, + timeout=timeout, + ) + + def test_log_file_unset_attaches_only_stream_handler(self, tmp_path): + marker = tmp_path / "handlers.txt" + env_overrides = {"MEMPALACE_LOG_FILE": None} + extra = ( + "import logging, pathlib\n" + "from mempalace import mcp_server # noqa: F401 — triggers _init_logging()\n" + f"pathlib.Path({str(marker)!r}).write_text(" + "','.join(type(h).__name__ for h in logging.getLogger().handlers)" + ")\n" + "raise SystemExit(0)\n" + ) + result = self._run_main(env_overrides, extra_code=extra) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert marker.read_text().split(",") == ["StreamHandler"], marker.read_text() + + def test_log_file_empty_string_attaches_only_stream_handler(self, tmp_path): + marker = tmp_path / "handlers.txt" + env_overrides = {"MEMPALACE_LOG_FILE": " "} # whitespace counts as unset after .strip() + extra = ( + "import logging, pathlib\n" + "from mempalace import mcp_server # noqa: F401\n" + f"pathlib.Path({str(marker)!r}).write_text(" + "','.join(type(h).__name__ for h in logging.getLogger().handlers)" + ")\n" + "raise SystemExit(0)\n" + ) + result = self._run_main(env_overrides, extra_code=extra) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert marker.read_text().split(",") == ["StreamHandler"], marker.read_text() + + def test_log_file_set_attaches_file_handler_and_persists_startup_line(self, tmp_path): + log_path = tmp_path / "mcp.log" + result = self._run_main({"MEMPALACE_LOG_FILE": str(log_path)}) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert log_path.exists(), f"log file missing; stderr={result.stderr!r}" + body = log_path.read_text(encoding="utf-8") + assert "MemPalace MCP Server starting" in body, body + + def test_log_file_invalid_path_falls_back_to_stderr_with_warning(self, tmp_path): + # Unique directory name we can grep for cross-platform without + # depending on path-separator formatting in the %r warning value. + missing_dir = "missing_dir_for_1495" + bad_path = tmp_path / missing_dir / "mcp.log" + result = self._run_main({"MEMPALACE_LOG_FILE": str(bad_path)}) + assert result.returncode == 0, f"stderr={result.stderr!r}" + # Invalid path must NOT crash the server, must surface a warning, must + # NOT create the file (the missing-directory ancestor is the failure). + # Warning must name MEMPALACE_LOG_FILE so the operator knows the source. + assert "could not be opened" in result.stderr, result.stderr + assert "MEMPALACE_LOG_FILE" in result.stderr, result.stderr + assert missing_dir in result.stderr, result.stderr + assert not bad_path.exists() + + @staticmethod + def _make_fake_palace(tmp_path): + """Create just enough on disk for ``_maybe_eager_warmup_embedder``'s + fresh-install pre-check to pass (``chroma.sqlite3`` exists). + + Returns the palace dir as a string. The file is empty — production + code must not read its bytes during pre-check; only its existence + gates whether warmup proceeds to the chromadb client open. + """ + palace = tmp_path / "palace" + palace.mkdir() + (palace / "chroma.sqlite3").touch() + return str(palace) + + @staticmethod + def _spy_get_collection_extra(marker_path, return_expr="None"): + """Render an ``extra_code`` fragment that monkeypatches ``_get_collection``. + + ``marker_path`` records that the spy fired; ``return_expr`` is a Python + expression evaluated inside the subprocess for the call's return value + (e.g. ``"None"`` or ``"_FakeCol()"``). + """ + return ( + "import pathlib\n" + "from mempalace import mcp_server\n" + "def _spy_get_collection(create=False):\n" + f" pathlib.Path({str(marker_path)!r}).write_text('called')\n" + f" return {return_expr}\n" + "mcp_server._get_collection = _spy_get_collection\n" + ) + + def test_eager_warmup_off_by_default_does_not_open_collection(self, tmp_path): + marker = tmp_path / "called.txt" + palace = self._make_fake_palace(tmp_path) + result = self._run_main( + {"MEMPALACE_EAGER_WARMUP": None, "MEMPALACE_PALACE_PATH": palace}, + extra_code=self._spy_get_collection_extra(marker), + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert not marker.exists(), "warmup ran despite env var being unset" + + @pytest.mark.parametrize("value", ["0", "false", "no", "off", "FALSE"]) + def test_eager_warmup_explicit_falsy_skips_collection_open_without_warning( + self, tmp_path, value + ): + marker = tmp_path / "called.txt" + palace = self._make_fake_palace(tmp_path) + result = self._run_main( + {"MEMPALACE_EAGER_WARMUP": value, "MEMPALACE_PALACE_PATH": palace}, + extra_code=self._spy_get_collection_extra(marker), + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert not marker.exists(), f"warmup ran for explicit-falsy value {value!r}" + assert ( + "not recognized" not in result.stderr + ), f"explicit-falsy {value!r} should not log a warning; stderr={result.stderr!r}" + + @pytest.mark.parametrize("value", ["tru", "maybe", "ENABLED", "2"]) + def test_eager_warmup_unrecognized_value_warns_and_skips_collection_open(self, tmp_path, value): + marker = tmp_path / "called.txt" + palace = self._make_fake_palace(tmp_path) + result = self._run_main( + {"MEMPALACE_EAGER_WARMUP": value, "MEMPALACE_PALACE_PATH": palace}, + extra_code=self._spy_get_collection_extra(marker), + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert not marker.exists(), f"warmup ran despite unrecognized value {value!r}" + assert "not recognized" in result.stderr, result.stderr + + @pytest.mark.parametrize("value", ["1", "true", "YES", "On"]) + def test_eager_warmup_truthy_opens_collection_and_invokes_query(self, tmp_path, value): + """C1 (#1495): warmup must call ``col.query(...)`` — not just open the collection. + + ChromaDB's ``ONNXMiniLM_L6_V2.__init__`` only imports ``onnxruntime``; + ``InferenceSession`` and model download happen inside ``__call__``, + which the chromadb query path drives. Pinning both call sites here + prevents a regression to a no-op resolver-only warmup (the same + failure mode silent-failure-hunter flagged in initial review). + Reporter's #1495 proposal: same path covers HNSW cold-load too. + """ + open_marker = tmp_path / "open_called.txt" + query_marker = tmp_path / "query_called.txt" + palace = self._make_fake_palace(tmp_path) + extra = ( + "import pathlib\n" + "from mempalace import mcp_server\n" + "class _FakeCol:\n" + " def query(self, **kwargs):\n" + f" pathlib.Path({str(query_marker)!r}).write_text(repr(kwargs))\n" + " return {'ids': [[]], 'distances': [[]], 'documents': [[]]}\n" + "_fake_col = _FakeCol()\n" + "def _spy_get_collection(create=False):\n" + f" pathlib.Path({str(open_marker)!r}).write_text('open')\n" + " return _fake_col\n" + "mcp_server._get_collection = _spy_get_collection\n" + ) + result = self._run_main( + {"MEMPALACE_EAGER_WARMUP": value, "MEMPALACE_PALACE_PATH": palace}, + extra_code=extra, + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert ( + open_marker.exists() + ), f"_get_collection not called for {value!r}; stderr={result.stderr!r}" + assert query_marker.exists(), ( + f"col.query not invoked for {value!r} — warmup is a no-op " + f"(would let cold-load hit first MCP call); stderr={result.stderr!r}" + ) + # query was called with the sentinel probe text and n_results=1. + kwargs_repr = query_marker.read_text() + assert "__mempalace_warmup_probe__" in kwargs_repr, kwargs_repr + assert "n_results" in kwargs_repr and "1" in kwargs_repr, kwargs_repr + # Success path logs embedder + HNSW readiness + palace + device for ops. + assert "embedder + HNSW ready" in result.stderr, result.stderr + assert f"palace={palace}" in result.stderr, result.stderr + + def test_eager_warmup_fresh_install_skips_without_creating_palace(self, tmp_path): + """Real integration test (no monkeypatch): an empty palace dir with no + ``chroma.sqlite3`` must trigger the pre-check skip path BEFORE any + chromadb call materializes the palace scaffold on disk. + + This pins three behaviours simultaneously: + + 1. ``returncode == 0`` — fresh install does not crash the server. + 2. ``chroma.sqlite3`` is NOT created — warmup respects the + "no on-disk state before ``mempalace init``" contract from + CLAUDE.md ("Incremental only"). A regression that drops the + pre-check would let chromadb's ``PersistentClient(path=...)`` + materialize the palace dir. + 3. ``"nothing to warm"`` lands in stderr — the documented INFO + message actually fires (the previous test that asserted this + via a monkeypatched ``_get_collection`` was tautological because + the real ``_get_collection`` swallows ``NotFoundError`` into + ``return None`` and silently materializes the palace). + 4. No chromadb retry tracebacks ("attempt N/2 failed") leak into + stderr — those are the noise this PR exists to reduce. + """ + palace = tmp_path / "fresh_palace" + palace.mkdir() + # Confirm precondition: no chroma.sqlite3 exists before main(). + db_path = palace / "chroma.sqlite3" + assert not db_path.exists() + result = self._run_main( + {"MEMPALACE_EAGER_WARMUP": "1", "MEMPALACE_PALACE_PATH": str(palace)}, + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert "nothing to warm" in result.stderr, result.stderr + assert "collection open failed" not in result.stderr, result.stderr + assert "warmup query failed" not in result.stderr, result.stderr + assert "embedder + HNSW ready" not in result.stderr, result.stderr + assert "attempt 1/2 failed" not in result.stderr, result.stderr + assert "attempt 2/2 failed" not in result.stderr, result.stderr + # Pin the no-side-effect contract: the warmup MUST NOT create the + # palace scaffold on disk before the user runs ``mempalace init``. + assert not db_path.exists(), ( + f"warmup materialized chroma.sqlite3 in a fresh palace dir " + f"(violates 'Incremental only' from CLAUDE.md); stderr={result.stderr!r}" + ) + + def test_eager_warmup_collection_returning_none_surfaces_warning(self, tmp_path): + """_get_collection retries internally and returns None on persistent + failure (mcp_server.py:373). Warmup must not log a misleading + success line in that case.""" + palace = self._make_fake_palace(tmp_path) + extra = self._spy_get_collection_extra(tmp_path / "called.txt", return_expr="None") + result = self._run_main( + {"MEMPALACE_EAGER_WARMUP": "1", "MEMPALACE_PALACE_PATH": palace}, + extra_code=extra, + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert "_get_collection returned None" in result.stderr, result.stderr + assert "embedder + HNSW ready" not in result.stderr, result.stderr + + def test_eager_warmup_collection_open_failure_logs_and_does_not_block_server(self, tmp_path): + palace = self._make_fake_palace(tmp_path) + extra = ( + "from mempalace import mcp_server\n" + "def _boom(create=False):\n" + " raise RuntimeError('synthetic-collection-open-fail-1495')\n" + "mcp_server._get_collection = _boom\n" + ) + result = self._run_main( + {"MEMPALACE_EAGER_WARMUP": "1", "MEMPALACE_PALACE_PATH": palace}, + extra_code=extra, + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert "collection open failed" in result.stderr, result.stderr + assert "synthetic-collection-open-fail-1495" in result.stderr, result.stderr + # palace + error class included in the diagnostic + assert f"palace={palace}" in result.stderr, result.stderr + assert "error=RuntimeError" in result.stderr, result.stderr + + def test_eager_warmup_query_failure_logs_and_persists_to_log_file(self, tmp_path): + """Query may raise (broken HNSW, network failure during ONNX download, + runtime decoder error). Server stays up and the diagnostic lands in + both stderr AND ``MEMPALACE_LOG_FILE`` — the latter is the whole + point of #1495 for ops debugging the original -32000.""" + palace = self._make_fake_palace(tmp_path) + log_path = tmp_path / "mcp.log" + extra = ( + "from mempalace import mcp_server\n" + "class _BadCol:\n" + " def query(self, **kwargs):\n" + " raise RuntimeError('synthetic-query-fail-1495')\n" + "mcp_server._get_collection = lambda create=False: _BadCol()\n" + ) + result = self._run_main( + { + "MEMPALACE_EAGER_WARMUP": "1", + "MEMPALACE_PALACE_PATH": palace, + "MEMPALACE_LOG_FILE": str(log_path), + }, + extra_code=extra, + ) + assert result.returncode == 0, f"stderr={result.stderr!r}" + assert "warmup query failed" in result.stderr, result.stderr + assert "synthetic-query-fail-1495" in result.stderr, result.stderr + assert f"palace={palace}" in result.stderr, result.stderr + assert "error=RuntimeError" in result.stderr, result.stderr + assert log_path.exists(), f"log file not created; stderr={result.stderr!r}" + body = log_path.read_text(encoding="utf-8") + assert "warmup query failed" in body, body + assert "synthetic-query-fail-1495" in body, body + + def test_log_file_path_with_embedded_newline_does_not_crash(self, tmp_path): + """``MEMPALACE_LOG_FILE`` containing a newline (rare misconfig from + a YAML/env file copy-paste) must fall through the (OSError, ValueError) + catch rather than escape as an unhandled exception at import time.""" + # Embedding \n inside a path component triggers ValueError on POSIX + # ("embedded null byte" raises on OS-level open) or OSError depending + # on platform — both should land in the fail-soft branch. + bad_path = str(tmp_path / "with\nnewline" / "mcp.log") + result = self._run_main({"MEMPALACE_LOG_FILE": bad_path}) + assert result.returncode == 0, f"stderr={result.stderr!r}" + # Server proceeds with stderr-only and surfaces the env-var-named + # warning so ops can correlate the misconfig. + assert "could not be opened" in result.stderr, result.stderr + assert "MEMPALACE_LOG_FILE" in result.stderr, result.stderr + + def test_log_file_invalid_path_failure_surfaces_before_first_log_record(self, tmp_path): + """Behavioural pin: ``delay=True`` MUST NOT be used on the FileHandler. + + With ``delay=True`` an invalid path raises inside ``emit()`` at runtime, + unhandled, defeating the fail-soft contract documented in ``_init_logging``. + This test pins the eager-open semantics by checking that the warning lands + BEFORE the ``MemPalace MCP Server starting...`` banner — proving that + ``FileHandler.__init__`` raised and was caught at module import.""" + bad_path = tmp_path / "regression_pin_dir" / "mcp.log" + result = self._run_main({"MEMPALACE_LOG_FILE": str(bad_path)}) + assert result.returncode == 0, f"stderr={result.stderr!r}" + warning_pos = result.stderr.find("could not be opened") + banner_pos = result.stderr.find("MemPalace MCP Server starting") + assert warning_pos != -1, f"warning missing; stderr={result.stderr!r}" + assert banner_pos != -1, f"banner missing; stderr={result.stderr!r}" + assert warning_pos < banner_pos, ( + f"warning at {warning_pos} must precede banner at {banner_pos} — " + f"if banner is first, FileHandler was opened lazily (delay=True regression). " + f"stderr={result.stderr!r}" + ) + + # ── Protocol Layer ────────────────────────────────────────────────────── From c933095a2fa4f1323a7980415427e876734bc8cf Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 17 May 2026 03:56:50 +0500 Subject: [PATCH 51/64] fix(palace): stratify state messages for empty/missing palace (#1498) `mempalace status`, `search`, and `compress` printed the same misleading "No palace found / Run: mempalace init" output for three distinct palace states (no dir / no DB / no collection). Most user-visible on the first-run state where `init` had run but `mine` had not: the hint to re-run `init` is a no-op and wastes the user's time. Backend gets a new typed exception `CollectionNotInitializedError` (subclass of `PalaceNotFoundError`, transitively `FileNotFoundError`, so legacy callers keep working). `ChromaBackend.get_collection( create=False)` wraps chromadb's bare `NotFoundError` as the new typed exception instead of leaking the chromadb-specific class to callers. A new internal helper `_open_collection_or_explain` in `palace.py` runs filesystem-first state checks before the backend call to avoid chromadb's lazy `chroma.sqlite3` creation as a side-effect of a read-only inspection, then catches the typed exceptions and prints a state-specific actionable message. `BackendClosedError` is explicitly re-raised so a programmer error is not masked as a UX hint. Two CLI bug sites route through the helper: `miner.status` and `cli.cmd_compress`. `searcher.search` catches the typed exceptions directly so it can preserve the cause chain in `SearchError(...) from e` for programmatic search-API consumers. `cli.cmd_sync` gained an inline filesystem distinction (no helper needed: it does not use the collection handle). `repair.status` (capacity check, which by design must work on corrupted palaces without opening a chromadb client) got the same distinction via `sqlite_drawer_count`-based empty detection. The MCP `tool_status` is intentionally left alone: PR #831 already fixed it there with a `create=True` bootstrap strategy appropriate for programmatic clients. --- mempalace/backends/__init__.py | 2 + mempalace/backends/base.py | 12 +++ mempalace/backends/chroma.py | 6 +- mempalace/cli.py | 23 +++-- mempalace/miner.py | 8 +- mempalace/palace.py | 67 +++++++++++++ mempalace/repair.py | 15 +++ mempalace/searcher.py | 9 +- tests/test_backends.py | 39 ++++++++ tests/test_cli.py | 53 ++++++++-- tests/test_miner.py | 37 ++++++- tests/test_palace.py | 170 +++++++++++++++++++++++++++++++++ tests/test_repair.py | 95 ++++++++++++++++++ 13 files changed, 512 insertions(+), 24 deletions(-) create mode 100644 tests/test_palace.py diff --git a/mempalace/backends/__init__.py b/mempalace/backends/__init__.py index ab22ec6..4e8fdce 100644 --- a/mempalace/backends/__init__.py +++ b/mempalace/backends/__init__.py @@ -19,6 +19,7 @@ from .base import ( BackendError, BaseBackend, BaseCollection, + CollectionNotInitializedError, DimensionMismatchError, EmbedderIdentityMismatchError, GetResult, @@ -46,6 +47,7 @@ __all__ = [ "BaseCollection", "ChromaBackend", "ChromaCollection", + "CollectionNotInitializedError", "DimensionMismatchError", "EmbedderIdentityMismatchError", "GetResult", diff --git a/mempalace/backends/base.py b/mempalace/backends/base.py index 2ff9b87..a32f0a8 100644 --- a/mempalace/backends/base.py +++ b/mempalace/backends/base.py @@ -35,6 +35,18 @@ class PalaceNotFoundError(BackendError, FileNotFoundError): """ +class CollectionNotInitializedError(PalaceNotFoundError): + """Raised when the palace exists on disk but the requested collection has + never been created (e.g. ``init`` ran but ``mine`` has not). + + Distinct from :class:`PalaceNotFoundError`: the palace dir and DB are + present and valid, only the collection has not been bootstrapped yet. + Subclass of :class:`PalaceNotFoundError` (and therefore + :class:`FileNotFoundError`) so legacy callers catching either parent + keep working unchanged. + """ + + class BackendClosedError(BackendError): """Raised when a backend method is called after ``close()``.""" diff --git a/mempalace/backends/chroma.py b/mempalace/backends/chroma.py index 581a313..387a2b9 100644 --- a/mempalace/backends/chroma.py +++ b/mempalace/backends/chroma.py @@ -16,6 +16,7 @@ from chromadb.errors import NotFoundError as _ChromaNotFoundError from .base import ( BaseBackend, BaseCollection, + CollectionNotInitializedError, GetResult, HealthStatus, PalaceNotFoundError, @@ -1380,7 +1381,10 @@ class ChromaBackend(BaseBackend): **ef_kwargs, ) else: - collection = client.get_collection(collection_name, **ef_kwargs) + try: + collection = client.get_collection(collection_name, **ef_kwargs) + except _ChromaNotFoundError as e: + raise CollectionNotInitializedError(palace_path) from e _pin_hnsw_threads(collection) return ChromaCollection(collection, palace_path=palace_path) diff --git a/mempalace/cli.py b/mempalace/cli.py index bd34699..48b6af4 100644 --- a/mempalace/cli.py +++ b/mempalace/cli.py @@ -590,6 +590,10 @@ def cmd_sync(args): if not os.path.isdir(palace_path): print(f"\n No palace found at {palace_path}") return + if not os.path.isfile(os.path.join(palace_path, "chroma.sqlite3")): + print(f"\n Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.") + print(" Run: mempalace mine ") + return project_dirs = [] if args.dir: @@ -1007,15 +1011,20 @@ def cmd_compress(args): else: dialect = Dialect() - # Connect to palace - backend = ChromaBackend() - try: - col = backend.get_collection(palace_path, "mempalace_drawers") - except Exception: - print(f"\n No palace found at {palace_path}") - print(" Run: mempalace init then mempalace mine ") + # State-aware open: distinguish "no palace" from "initialized but empty" + # from "corrupt" via the shared helper (#1498). MCP and library callers + # catch the backend exceptions directly; CLI gets the friendly print. + from .palace import _open_collection_or_explain + + col = _open_collection_or_explain(palace_path, collection_name="mempalace_drawers") + if col is None: sys.exit(1) + # Backend instance for the closets write below. chromadb's + # PersistentClient is cached per palace path internally, so this second + # ChromaBackend instance shares the underlying client with the helper. + backend = ChromaBackend() + # Query drawers in batches to avoid SQLite variable limit (~999) where = {"wing": args.wing} if args.wing else None _BATCH = 500 diff --git a/mempalace/miner.py b/mempalace/miner.py index 0b55b7b..0eab9dc 100644 --- a/mempalace/miner.py +++ b/mempalace/miner.py @@ -22,6 +22,7 @@ from typing import Optional from .palace import ( NORMALIZE_VERSION, SKIP_DIRS, + _open_collection_or_explain, build_closet_lines, file_already_mined, get_closets_collection, @@ -1355,11 +1356,8 @@ def _compute_topic_tunnels_for_wing(wing: str) -> int: def status(palace_path: str): """Show what's been filed in the palace.""" - try: - col = get_collection(palace_path, create=False) - except Exception: - print(f"\n No palace found at {palace_path}") - print(" Run: mempalace init then mempalace mine ") + col = _open_collection_or_explain(palace_path) + if col is None: return # Count by wing and room — paginate to avoid SQLite "too many SQL diff --git a/mempalace/palace.py b/mempalace/palace.py index 38c3979..8df68e5 100644 --- a/mempalace/palace.py +++ b/mempalace/palace.py @@ -13,6 +13,7 @@ import sys import threading from typing import Optional +from .backends import BackendClosedError, CollectionNotInitializedError, PalaceNotFoundError from .backends.chroma import ChromaBackend logger = logging.getLogger("mempalace_mcp") @@ -78,6 +79,72 @@ def get_closets_collection(palace_path: str, create: bool = True): return get_collection(palace_path, collection_name="mempalace_closets", create=create) +def _open_collection_or_explain( + palace_path: str, + *, + collection_name: Optional[str] = None, + out=None, +): + """Open the palace collection or print a state-specific message and return ``None``. + + For CLI and repair commands that want consistent, actionable user-facing + messages distinguishing four "not-healthy" states from one another. MCP + and library callers should catch + :class:`mempalace.backends.PalaceNotFoundError` / + :class:`mempalace.backends.CollectionNotInitializedError` directly. + + The MCP server (``mcp_server.tool_status``) deliberately does NOT use + this helper: it uses ``_get_collection(create=db_exists)`` so a valid + palace whose collection was never bootstrapped lazily gets one on the + first status call, and a corruption-detection sqlite-only probe fires + first when the vector path is disabled (see PR #831 / issue #830). + + State A: palace dir is absent. + State B: dir is present but ``chroma.sqlite3`` is absent. The helper + short-circuits to a message before reaching the backend, because + ``chromadb.PersistentClient`` lazily creates the DB file on first + open — calling the backend on this state would silently mutate + the filesystem for what should be a read-only inspection. + State C: DB is present but the ``mempalace_drawers`` collection has + never been bootstrapped (``init`` ran, ``mine`` has not). + State D: healthy — returns the opened collection. + State E: an unexpected error opens the backend — message points the + user at ``repair-status`` for further diagnosis. + + ``out`` is the message sink; defaults to the builtin ``print``. Pass a + callable (e.g. a repair progress emitter) to route messages through it. + """ + emit = out if out is not None else print + + if not os.path.isdir(palace_path): + emit(f"\n No palace found at {palace_path}") + emit(" Run: mempalace init then mempalace mine ") + return None + if not os.path.isfile(os.path.join(palace_path, "chroma.sqlite3")): + emit(f"\n Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.") + emit(" Run: mempalace mine ") + return None + try: + return get_collection(palace_path, collection_name=collection_name, create=False) + except CollectionNotInitializedError: + emit(f"\n Palace at {palace_path} is initialized but empty (no drawers yet).") + emit(" Run: mempalace mine ") + return None + except PalaceNotFoundError: + emit(f"\n No palace found at {palace_path}") + emit(" Run: mempalace init then mempalace mine ") + return None + except BackendClosedError: + # Surface this as a programmer error, not a palace-state UX message: + # a closed backend means the caller violated the backend lifecycle, + # not that the palace on disk is in a recoverable state. + raise + except Exception as e: # noqa: BLE001 — backend exceptions vary (chromadb, OSError, lock errors) + emit(f"\n Error opening palace at {palace_path}: {e!r}") + emit(" Try: mempalace repair-status --palace ") + return None + + CLOSET_CHAR_LIMIT = 1500 # fill closet until ~1500 chars, then start a new one CLOSET_EXTRACT_WINDOW = 5000 # how many chars of source content to scan for entities/topics diff --git a/mempalace/repair.py b/mempalace/repair.py index c5ad068..778a354 100644 --- a/mempalace/repair.py +++ b/mempalace/repair.py @@ -1222,6 +1222,21 @@ def status(palace_path=None, collection_name: Optional[str] = None) -> dict: print(" No palace found.\n") return {"status": "unknown", "message": "no palace at path"} + db_path = os.path.join(palace_path, "chroma.sqlite3") + if not os.path.isfile(db_path): + print(f" Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.\n") + return {"status": "uninitialized", "message": "palace has no chroma.sqlite3 yet"} + + # Cheap collection-existence check via sqlite. By design this function + # never opens a chromadb client (see the docstring); sqlite_drawer_count + # reads chroma.sqlite3 directly and returns None on any schema/lock error + # (chromadb version drift, missing tables, locked file). None means fall + # through and let hnsw_capacity_status report "unknown". + drawer_row_count = sqlite_drawer_count(palace_path, collection_name) + if isinstance(drawer_row_count, int) and drawer_row_count == 0: + print(" Palace is initialized but empty (no drawers yet).\n") + return {"status": "empty", "message": "palace has no drawers yet"} + drawers = hnsw_capacity_status(palace_path, collection_name) closets = hnsw_capacity_status(palace_path, CLOSETS_COLLECTION_NAME) diff --git a/mempalace/searcher.py b/mempalace/searcher.py index f644fda..7f7e2e2 100644 --- a/mempalace/searcher.py +++ b/mempalace/searcher.py @@ -16,6 +16,7 @@ import re import sqlite3 from pathlib import Path +from .backends import CollectionNotInitializedError, PalaceNotFoundError from .palace import get_closets_collection, get_collection # Closet pointer line format: "topic|entities|→drawer_id_a,drawer_id_b" @@ -297,7 +298,13 @@ def search(query: str, palace_path: str, wing: str = None, room: str = None, n_r """ try: col = get_collection(palace_path, create=False) - except Exception as e: + except CollectionNotInitializedError as e: + # State C from #1498: palace initialized but never mined. + print(f"\n Palace at {palace_path} is initialized but empty (no drawers yet).") + print(" Run: mempalace mine ") + raise SearchError(f"Palace at {palace_path} is initialized but empty") from e + except PalaceNotFoundError as e: + # State A from #1498: palace dir missing. print(f"\n No palace found at {palace_path}") print(" Run: mempalace init then mempalace mine ") raise SearchError(f"No palace found at {palace_path}") from e diff --git a/tests/test_backends.py b/tests/test_backends.py index 90cf128..8f36126 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -9,7 +9,9 @@ import chromadb import pytest from mempalace.backends import ( + CollectionNotInitializedError, GetResult, + PalaceNotFoundError, PalaceRef, QueryResult, UnsupportedFilterError, @@ -993,6 +995,43 @@ def test_get_collection_applies_retrofit_on_existing_palace(tmp_path): assert wrapper._collection.configuration_json["hnsw"]["num_threads"] == 1 +def test_get_collection_raises_palace_not_found_when_dir_missing(tmp_path): + """create=False on a missing dir raises PalaceNotFoundError, not the + new CollectionNotInitializedError. The two states must be distinguishable + so callers can render state-specific messages (#1498).""" + missing = tmp_path / "no-such-dir" + with pytest.raises(PalaceNotFoundError) as excinfo: + ChromaBackend().get_collection( + str(missing), + collection_name="mempalace_drawers", + create=False, + ) + # Must be the parent class, not the new subclass: dir is genuinely absent. + assert not isinstance(excinfo.value, CollectionNotInitializedError) + + +def test_get_collection_raises_collection_not_initialized_on_empty_palace(tmp_path): + """When the palace dir + DB exist but the collection has never been + created, ChromaBackend.get_collection(create=False) raises the new + CollectionNotInitializedError instead of leaking chromadb.NotFoundError + (#1498).""" + palace_path = tmp_path / "palace" + palace_path.mkdir() + # PersistentClient lazily creates chroma.sqlite3 — no collection yet. + chromadb.PersistentClient(path=str(palace_path)) + assert (palace_path / "chroma.sqlite3").is_file() + + with pytest.raises(CollectionNotInitializedError) as excinfo: + ChromaBackend().get_collection( + str(palace_path), + collection_name="mempalace_drawers", + create=False, + ) + # Backward-compat: subclass of PalaceNotFoundError (and FileNotFoundError). + assert isinstance(excinfo.value, PalaceNotFoundError) + assert isinstance(excinfo.value, FileNotFoundError) + + def test_quarantine_invalid_hnsw_metadata_renames_missing_dimensionality(tmp_path): palace = tmp_path / "palace" palace.mkdir() diff --git a/tests/test_cli.py b/tests/test_cli.py index 9894358..788d295 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1041,16 +1041,45 @@ def test_cmd_repair_aborts_without_confirmation(mock_config_cls, tmp_path, capsy @patch("mempalace.cli.MempalaceConfig") -def test_cmd_compress_no_palace(mock_config_cls, capsys): - mock_config_cls.return_value.palace_path = "/fake/palace" +def test_cmd_sync_no_palace_dir(mock_config_cls, tmp_path, capsys): + """cmd_sync on a missing palace dir prints the State A message (#1498).""" + from mempalace.cli import cmd_sync + + palace_path = tmp_path / "nonexistent" + mock_config_cls.return_value.palace_path = str(palace_path) + args = argparse.Namespace(palace=None, dir=None, root=[], wing=None, dry_run=False) + cmd_sync(args) + captured = capsys.readouterr() + assert "No palace found" in captured.out + captured.err + + +@patch("mempalace.cli.MempalaceConfig") +def test_cmd_sync_palace_dir_no_db(mock_config_cls, tmp_path, capsys): + """cmd_sync on a palace dir without chroma.sqlite3 prints the State B + message and does NOT trigger chromadb's lazy DB creation (#1498).""" + from mempalace.cli import cmd_sync + + mock_config_cls.return_value.palace_path = str(tmp_path) + args = argparse.Namespace(palace=None, dir=None, root=[], wing=None, dry_run=False) + cmd_sync(args) + captured = capsys.readouterr() + assert "has no chroma.sqlite3 yet" in captured.out + captured.err + # Side-effect-free: backend not invoked. + assert list(tmp_path.iterdir()) == [] + + +@patch("mempalace.cli.MempalaceConfig") +def test_cmd_compress_no_palace(mock_config_cls, tmp_path, capsys): + """cmd_compress exits non-zero with a 'No palace found' message on a missing dir. + + Uses a real non-existent tmp_path so the stratified state helper (#1498) + walks the State A branch instead of hitting the chromadb backend. + """ + mock_config_cls.return_value.palace_path = str(tmp_path / "nonexistent") args = argparse.Namespace(palace=None, wing=None, dry_run=False, config=None) - mock_backend = MagicMock() - mock_backend.get_collection.side_effect = Exception("no palace") - with ( - patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend), - pytest.raises(SystemExit), - ): + with pytest.raises(SystemExit): cmd_compress(args) + assert "No palace found" in capsys.readouterr().out @patch("mempalace.cli.MempalaceConfig") @@ -1060,7 +1089,10 @@ def test_cmd_compress_no_drawers(mock_config_cls, capsys): mock_col = MagicMock() mock_col.get.return_value = {"documents": [], "metadatas": [], "ids": []} mock_backend = _mock_backend_for(col=mock_col) - with patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend): + with ( + patch("mempalace.palace._open_collection_or_explain", return_value=mock_col), + patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend), + ): cmd_compress(args) out = capsys.readouterr().out assert "No drawers found" in out @@ -1103,6 +1135,7 @@ def test_cmd_compress_dry_run(mock_config_cls, capsys): mock_dialect_mod = _make_mock_dialect_module(mock_dialect) with ( + patch("mempalace.palace._open_collection_or_explain", return_value=mock_col), patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend), patch.dict("sys.modules", {"mempalace.dialect": mock_dialect_mod}), ): @@ -1127,6 +1160,7 @@ def test_cmd_compress_with_config(mock_config_cls, tmp_path, capsys): mock_dialect_mod = _make_mock_dialect_module(mock_dialect) with ( + patch("mempalace.palace._open_collection_or_explain", return_value=mock_col), patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend), patch.dict("sys.modules", {"mempalace.dialect": mock_dialect_mod}), ): @@ -1167,6 +1201,7 @@ def test_cmd_compress_stores_results(mock_config_cls, capsys): mock_dialect_mod = _make_mock_dialect_module(mock_dialect) with ( + patch("mempalace.palace._open_collection_or_explain", return_value=mock_col), patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend), patch.dict("sys.modules", {"mempalace.dialect": mock_dialect_mod}), ): diff --git a/tests/test_miner.py b/tests/test_miner.py index d58ef92..2c62de3 100644 --- a/tests/test_miner.py +++ b/tests/test_miner.py @@ -442,6 +442,41 @@ def test_status_missing_palace_does_not_create_empty_collection(tmp_path, capsys assert not palace_path.exists() +def test_status_initialized_but_empty_palace_reports_empty(tmp_path, capsys): + """State C from #1498: palace dir + chroma.sqlite3 exist but no drawers + have been mined yet. status() must print the 'initialized but empty' + message and suggest `mempalace mine`, not the misleading 'No palace + found' / 'Run init' message.""" + import chromadb + + palace_path = tmp_path / "empty-palace" + palace_path.mkdir() + chromadb.PersistentClient(path=str(palace_path)) # creates chroma.sqlite3 + assert (palace_path / "chroma.sqlite3").is_file() + + status(str(palace_path)) + + out = capsys.readouterr().out + assert "initialized but empty" in out + assert "mempalace mine" in out + assert "No palace found" not in out + + +def test_status_palace_dir_without_db_reports_uninitialized(tmp_path, capsys): + """State B from #1498: palace dir exists but chroma.sqlite3 is absent. + Helper must short-circuit before invoking chromadb (which would lazily + create the DB file as a side effect of a read-only inspection).""" + palace_path = tmp_path / "no-db-palace" + palace_path.mkdir() + + status(str(palace_path)) + + out = capsys.readouterr().out + assert "has no chroma.sqlite3 yet" in out + # Side-effect check: chromadb was never touched. + assert list(palace_path.iterdir()) == [] + + def test_status_handles_none_metadata_without_crash(tmp_path, capsys): """status must not crash when col.get returns a None entry in metadatas. @@ -462,7 +497,7 @@ def test_status_handles_none_metadata_without_crash(tmp_path, capsys): "metadatas": [{"wing": "proj", "room": "r"}, None], } - with patch("mempalace.miner.get_collection", return_value=FakeCol()): + with patch("mempalace.miner._open_collection_or_explain", return_value=FakeCol()): status(str(tmp_path)) out = capsys.readouterr().out diff --git a/tests/test_palace.py b/tests/test_palace.py new file mode 100644 index 0000000..1e2325f --- /dev/null +++ b/tests/test_palace.py @@ -0,0 +1,170 @@ +"""Tests for mempalace.palace shared helpers.""" + +import chromadb + +from mempalace.backends import CollectionNotInitializedError, PalaceNotFoundError +from mempalace.palace import _open_collection_or_explain, get_collection + + +def _capture(): + """Return (emit, lines) — emit appends to lines for inspection.""" + lines: list[str] = [] + return lines.append, lines + + +def test_open_collection_or_explain_state_a_missing_dir(tmp_path): + """State A: palace dir does not exist.""" + emit, lines = _capture() + missing = tmp_path / "no-such-palace" + + result = _open_collection_or_explain(str(missing), out=emit) + + assert result is None + assert any("No palace found" in line for line in lines) + assert any("mempalace init" in line for line in lines) + # Helper must not create the directory. + assert not missing.exists() + + +def test_open_collection_or_explain_state_b_no_db(tmp_path): + """State B: dir exists but chroma.sqlite3 does not. + + Critical invariant: the helper must NOT trigger chromadb's lazy DB + creation by reaching the backend. The dir must remain empty after + the call so a read-only inspection stays read-only. + """ + emit, lines = _capture() + palace = tmp_path / "palace" + palace.mkdir() + assert not (palace / "chroma.sqlite3").exists() + + result = _open_collection_or_explain(str(palace), out=emit) + + assert result is None + assert any("has no chroma.sqlite3 yet" in line for line in lines) + # No side-effect: backend was not invoked. + assert list(palace.iterdir()) == [] + + +def test_open_collection_or_explain_state_c_no_collection(tmp_path): + """State C: DB file exists but the collection has never been created.""" + emit, lines = _capture() + palace = tmp_path / "palace" + palace.mkdir() + chromadb.PersistentClient(path=str(palace)) # creates DB, no collection + assert (palace / "chroma.sqlite3").is_file() + + result = _open_collection_or_explain(str(palace), out=emit) + + assert result is None + assert any("initialized but empty" in line for line in lines) + assert any("mempalace mine" in line for line in lines) + + +def test_open_collection_or_explain_state_d_healthy(tmp_path): + """State D: healthy palace — returns the opened collection silently.""" + emit, lines = _capture() + palace = tmp_path / "palace" + palace.mkdir() + get_collection(str(palace), create=True) # bootstrap collection + + result = _open_collection_or_explain(str(palace), out=emit) + + assert result is not None + assert lines == [] # healthy path is silent + + +def test_open_collection_or_explain_state_e_unexpected_error(tmp_path, monkeypatch): + """State E: unexpected error opening the backend routes to repair hint.""" + emit, lines = _capture() + palace = tmp_path / "palace" + palace.mkdir() + (palace / "chroma.sqlite3").touch() # pass the isfile guard + + def boom(*args, **kwargs): + raise RuntimeError("disk on fire") + + monkeypatch.setattr("mempalace.palace.get_collection", boom) + + result = _open_collection_or_explain(str(palace), out=emit) + + assert result is None + assert any("Error opening palace" in line for line in lines) + assert any("repair-status" in line for line in lines) + + +def test_open_collection_or_explain_default_sink_is_print(tmp_path, capsys): + """When out is None, messages go through builtin print → stdout.""" + missing = tmp_path / "no-such-palace" + + result = _open_collection_or_explain(str(missing)) + + assert result is None + assert "No palace found" in capsys.readouterr().out + + +def test_open_collection_or_explain_propagates_palace_not_found_from_backend(tmp_path, monkeypatch): + """If the backend raises bare PalaceNotFoundError after our filesystem + guards (rare race or backend-internal "not found"), the helper still + prints the State A message and returns None.""" + emit, lines = _capture() + palace = tmp_path / "palace" + palace.mkdir() + (palace / "chroma.sqlite3").touch() + + def raise_pnf(*args, **kwargs): + raise PalaceNotFoundError(str(palace)) + + monkeypatch.setattr("mempalace.palace.get_collection", raise_pnf) + + result = _open_collection_or_explain(str(palace), out=emit) + + assert result is None + assert any("No palace found" in line for line in lines) + + +def test_open_collection_or_explain_reraises_backend_closed_error(tmp_path, monkeypatch): + """BackendClosedError is a programmer error (caller violated the backend + lifecycle), not a palace-state UX condition. The helper must propagate + it instead of swallowing it into the State E "repair-status" hint. + + Without this re-raise, a closed default backend would silently mask + every call site as "Error opening palace ... Try: repair-status" + even when the actual fix is to stop using a closed backend handle. + """ + from mempalace.backends import BackendClosedError + + palace = tmp_path / "palace" + palace.mkdir() + (palace / "chroma.sqlite3").touch() + + def raise_closed(*args, **kwargs): + raise BackendClosedError("ChromaBackend has been closed") + + monkeypatch.setattr("mempalace.palace.get_collection", raise_closed) + + import pytest + + with pytest.raises(BackendClosedError): + _open_collection_or_explain(str(palace)) + + +def test_open_collection_or_explain_distinguishes_collection_subclass(tmp_path, monkeypatch): + """The helper must surface CollectionNotInitializedError as the + 'empty' message rather than the broader 'No palace found' message, + even though the former subclasses the latter.""" + emit, lines = _capture() + palace = tmp_path / "palace" + palace.mkdir() + (palace / "chroma.sqlite3").touch() + + def raise_cnie(*args, **kwargs): + raise CollectionNotInitializedError(str(palace)) + + monkeypatch.setattr("mempalace.palace.get_collection", raise_cnie) + + result = _open_collection_or_explain(str(palace), out=emit) + + assert result is None + assert any("initialized but empty" in line for line in lines) + assert not any("No palace found" in line for line in lines) diff --git a/tests/test_repair.py b/tests/test_repair.py index 144d907..d8dfa94 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -538,9 +538,104 @@ def test_rebuild_index_default_uses_configured_collection(mock_backend_cls, mock ] +def test_status_returns_uninitialized_when_db_missing(tmp_path, capsys): + """repair.status on a palace dir without chroma.sqlite3 returns a + structured status (no chromadb client opened, per the design that + repair-status must work even on corrupted palaces — #1498).""" + # tmp_path exists, no chroma.sqlite3 + result = repair.status(palace_path=str(tmp_path)) + + assert result["status"] == "uninitialized" + assert "no chroma.sqlite3" in result["message"] + captured = capsys.readouterr() + assert "has no chroma.sqlite3 yet" in captured.out + captured.err + + +def test_status_returns_empty_when_db_present_no_drawers(tmp_path, capsys): + """repair.status on a palace with chroma.sqlite3 but zero drawer rows + returns a structured 'empty' status, distinguishable from 'unknown' / + 'uninitialized' (#1498). Mocks sqlite_drawer_count to assert the + return-shape contract; see the real-disk sibling below for the + no-chromadb-client invariant.""" + (tmp_path / "chroma.sqlite3").touch() + with patch("mempalace.repair.sqlite_drawer_count", return_value=0): + result = repair.status(palace_path=str(tmp_path)) + + assert result["status"] == "empty" + assert "no drawers yet" in result["message"] + captured = capsys.readouterr() + assert "initialized but empty" in captured.out + captured.err + + +def test_status_empty_palace_never_opens_chromadb_client(tmp_path): + """Design invariant from #1498: repair.status on an initialized-but-empty + palace must NOT open a chromadb client. Opening would materialize HNSW + segment state files on disk, breaking the promise that repair-status is + safe to run on corrupted palaces. + + Real-disk sibling of test_status_returns_empty_when_db_present_no_drawers: + bootstrap a real chroma.sqlite3 via PersistentClient (creates the DB + file but no collection), then assert repair.status returns 'empty' and + no chromadb segment artifacts appeared in the dir.""" + import chromadb + + chromadb.PersistentClient(path=str(tmp_path)) + before = sorted(p.name for p in tmp_path.iterdir()) + + result = repair.status(palace_path=str(tmp_path)) + + after = sorted(p.name for p in tmp_path.iterdir()) + assert result["status"] == "empty", result + # repair.status must not create new files; chromadb writes HNSW segment + # state and *.bin payloads on collection open — none of those should + # appear here. + assert before == after, f"repair.status mutated palace on disk: before={before} after={after}" + + +def test_status_falls_through_to_capacity_when_sqlite_count_unreadable(tmp_path): + """When sqlite_drawer_count returns None (schema drift / locked file), + repair.status must fall through to hnsw_capacity_status instead of + short-circuiting on 'empty' (#1498).""" + (tmp_path / "chroma.sqlite3").touch() + with ( + patch("mempalace.repair.sqlite_drawer_count", return_value=None), + patch("mempalace.repair.hnsw_capacity_status") as capacity_status, + ): + capacity_status.side_effect = [ + { + "sqlite_count": None, + "hnsw_count": None, + "divergence": None, + "diverged": False, + "status": "unknown", + "message": "", + }, + { + "sqlite_count": None, + "hnsw_count": None, + "divergence": None, + "diverged": False, + "status": "unknown", + "message": "", + }, + ] + result = repair.status(palace_path=str(tmp_path)) + + # Did not short-circuit on 'empty': fell through to capacity check. + # The healthy/fall-through path returns {drawers, closets} dicts, no top-level "status" key. + assert "status" not in result or result["status"] != "empty" + assert "drawers" in result and "closets" in result + assert capacity_status.called + + def test_status_default_uses_configured_drawer_collection(tmp_path): + # Provide the on-disk preconditions the stratified state helper (#1498) + # checks before reaching the capacity probe: chroma.sqlite3 file exists + # and sqlite_drawer_count returns a positive number (palace not empty). + (tmp_path / "chroma.sqlite3").touch() with ( patch("mempalace.repair._drawers_collection_name", return_value="custom_drawers"), + patch("mempalace.repair.sqlite_drawer_count", return_value=1), patch("mempalace.repair.hnsw_capacity_status") as capacity_status, ): capacity_status.side_effect = [ From 990b155515a5e61bad2cc65b0c1bd2f0f8deb969 Mon Sep 17 00:00:00 2001 From: mvalentsev Date: Sun, 17 May 2026 04:13:42 +0500 Subject: [PATCH 52/64] fix(palace): address Gemini review on #1532 - searcher.search: add filesystem-first isdir/isfile checks before get_collection so State B (palace dir exists, chroma.sqlite3 absent) is distinguished from State C ("initialized but empty") instead of triggering chromadb's lazy DB creation as a side effect of a read-only search call. Preserves the SearchError(...) from e chain via the typed exception catches that follow. - cli.cmd_compress: replace the redundant `ChromaBackend()` instance used for the mempalace_closets write with `palace.get_closets_collection(create=True)`. The closets write now reuses the module-level _DEFAULT_BACKEND, avoiding the WAL-lock contention risk on Windows that Gemini flagged. - tests: new `fake_palace_path` fixture for searcher CLI unit tests so the filesystem-first state checks pass through to mocked backends instead of raising on State A / B; cmd_compress stores-results test patches `palace.get_closets_collection` to mirror the new write path. --- mempalace/cli.py | 12 +++++------- mempalace/searcher.py | 16 +++++++++++++++- tests/test_cli.py | 8 +------- tests/test_searcher.py | 37 +++++++++++++++++++++++++------------ 4 files changed, 46 insertions(+), 27 deletions(-) diff --git a/mempalace/cli.py b/mempalace/cli.py index 48b6af4..527c96d 100644 --- a/mempalace/cli.py +++ b/mempalace/cli.py @@ -992,8 +992,8 @@ def cmd_mcp(args): def cmd_compress(args): """Compress drawers in a wing using AAAK Dialect.""" - from .backends.chroma import ChromaBackend from .dialect import Dialect + from .palace import get_closets_collection palace_path = os.path.expanduser(args.palace) if args.palace else MempalaceConfig().palace_path @@ -1020,11 +1020,6 @@ def cmd_compress(args): if col is None: sys.exit(1) - # Backend instance for the closets write below. chromadb's - # PersistentClient is cached per palace path internally, so this second - # ChromaBackend instance shares the underlying client with the helper. - backend = ChromaBackend() - # Query drawers in batches to avoid SQLite variable limit (~999) where = {"wing": args.wing} if args.wing else None _BATCH = 500 @@ -1094,7 +1089,10 @@ def cmd_compress(args): # Store compressed versions (unless dry-run) if not args.dry_run: try: - comp_col = backend.get_or_create_collection(palace_path, "mempalace_closets") + # Route through palace.get_closets_collection so the shared + # _DEFAULT_BACKEND is reused (avoids a redundant ChromaBackend + # instance and its potential WAL-lock contention on Windows). + comp_col = get_closets_collection(palace_path, create=True) for doc_id, compressed, meta, stats in compressed_entries: comp_meta = dict(meta) comp_meta["compression_ratio"] = round(stats["size_ratio"], 1) diff --git a/mempalace/searcher.py b/mempalace/searcher.py index 7f7e2e2..9e8a358 100644 --- a/mempalace/searcher.py +++ b/mempalace/searcher.py @@ -296,6 +296,19 @@ def search(query: str, palace_path: str, wing: str = None, room: str = None, n_r Search the palace. Returns verbatim drawer content. Optionally filter by wing (project) or room (aspect). """ + # Filesystem-first checks distinguish State A / State B before reaching + # chromadb. PersistentClient lazily creates chroma.sqlite3 on first open + # of an empty palace dir, so without these checks State B collapses into + # the "initialized but empty" State C message and mutates the dir as a + # side effect of a read-only search call (#1498). + if not os.path.isdir(palace_path): + print(f"\n No palace found at {palace_path}") + print(" Run: mempalace init then mempalace mine ") + raise SearchError(f"No palace found at {palace_path}") + if not os.path.isfile(os.path.join(palace_path, "chroma.sqlite3")): + print(f"\n Palace dir at {palace_path} exists but has no chroma.sqlite3 yet.") + print(" Run: mempalace mine ") + raise SearchError(f"No palace database at {palace_path}") try: col = get_collection(palace_path, create=False) except CollectionNotInitializedError as e: @@ -304,7 +317,8 @@ def search(query: str, palace_path: str, wing: str = None, room: str = None, n_r print(" Run: mempalace mine ") raise SearchError(f"Palace at {palace_path} is initialized but empty") from e except PalaceNotFoundError as e: - # State A from #1498: palace dir missing. + # Backend filesystem-race fallback: dir was deleted between our + # check above and the backend call. Same message as State A. print(f"\n No palace found at {palace_path}") print(" Run: mempalace init then mempalace mine ") raise SearchError(f"No palace found at {palace_path}") from e diff --git a/tests/test_cli.py b/tests/test_cli.py index 788d295..ee0a7dc 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1202,7 +1202,7 @@ def test_cmd_compress_stores_results(mock_config_cls, capsys): with ( patch("mempalace.palace._open_collection_or_explain", return_value=mock_col), - patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend), + patch("mempalace.palace.get_closets_collection", return_value=mock_comp_col), patch.dict("sys.modules", {"mempalace.dialect": mock_dialect_mod}), ): cmd_compress(args) @@ -1210,12 +1210,6 @@ def test_cmd_compress_stores_results(mock_config_cls, capsys): assert "Stored" in out assert "Total:" in out mock_comp_col.upsert.assert_called_once() - # Verify the compress output goes to the closets collection so that - # palace.get_closets_collection() / searcher can read it back (#1244). - (call_args, _kwargs) = mock_backend.get_or_create_collection.call_args - assert ( - call_args[1] == "mempalace_closets" - ), f"compress should write to mempalace_closets, got {call_args[1]!r}" assert "mempalace_closets" in out diff --git a/tests/test_searcher.py b/tests/test_searcher.py index 76b1e5c..ccea063 100644 --- a/tests/test_searcher.py +++ b/tests/test_searcher.py @@ -239,6 +239,17 @@ class TestBM25NoneSafety: # ── search() (CLI print function) ───────────────────────────────────── +@pytest.fixture +def fake_palace_path(tmp_path): + """tmp_path with chroma.sqlite3 touched so searcher.search's + filesystem-first state checks (#1498) pass through to the mocked + backend instead of raising on State A / State B.""" + p = tmp_path / "palace" + p.mkdir() + (p / "chroma.sqlite3").touch() + return str(p) + + class TestSearchCLI: def test_search_prints_results(self, palace_path, seeded_collection, capsys): search("JWT authentication", palace_path) @@ -273,14 +284,14 @@ class TestSearchCLI: # Either prints "No results" or returns None assert result is None or "No results" in captured.out - def test_search_query_error_raises(self): + def test_search_query_error_raises(self, fake_palace_path): """search raises SearchError when query fails.""" mock_col = MagicMock() mock_col.query.side_effect = RuntimeError("boom") with patch("mempalace.searcher.get_collection", return_value=mock_col): with pytest.raises(SearchError, match="Search error"): - search("test", "/fake/path") + search("test", fake_palace_path) def test_search_n_results(self, palace_path, seeded_collection, capsys): search("code", palace_path, n_results=1) @@ -288,7 +299,7 @@ class TestSearchCLI: # Should have output with at least one result block assert "[1]" in captured.out - def test_search_applies_bm25_hybrid_rerank(self, capsys): + def test_search_applies_bm25_hybrid_rerank(self, fake_palace_path, capsys): """CLI search must call the same hybrid rerank that the MCP path uses. Regression for a bug where the CLI only consulted ChromaDB cosine @@ -323,7 +334,7 @@ class TestSearchCLI: "distances": [[1.5, 1.5, 1.5]], } with patch("mempalace.searcher.get_collection", return_value=mock_col): - search("foo bar baz", "/fake/path") + search("foo bar baz", fake_palace_path) captured = capsys.readouterr() first_block, _, _ = captured.out.partition("[2]") # Lexical match must rank first @@ -336,7 +347,7 @@ class TestSearchCLI: # Cosine still reported for transparency assert "cosine=" in first_block - def test_search_warns_when_palace_uses_wrong_distance_metric(self, capsys): + def test_search_warns_when_palace_uses_wrong_distance_metric(self, fake_palace_path, capsys): """Legacy palaces created without `hnsw:space=cosine` silently use L2, which breaks similarity interpretation. CLI must warn the user and point them at `mempalace repair` rather than @@ -349,12 +360,14 @@ class TestSearchCLI: "distances": [[1.2]], } with patch("mempalace.searcher.get_collection", return_value=mock_col): - search("anything", "/fake/path") + search("anything", fake_palace_path) captured = capsys.readouterr() assert "mempalace repair" in captured.err assert "cosine" in captured.err.lower() - def test_search_does_not_warn_when_palace_is_correctly_configured(self, capsys): + def test_search_does_not_warn_when_palace_is_correctly_configured( + self, fake_palace_path, capsys + ): mock_col = MagicMock() mock_col.metadata = {"hnsw:space": "cosine"} mock_col.query.return_value = { @@ -363,11 +376,11 @@ class TestSearchCLI: "distances": [[0.3]], } with patch("mempalace.searcher.get_collection", return_value=mock_col): - search("anything", "/fake/path") + search("anything", fake_palace_path) captured = capsys.readouterr() assert "mempalace repair" not in captured.err - def test_search_handles_none_metadata_without_crash(self, palace_path, capsys): + def test_search_handles_none_metadata_without_crash(self, fake_palace_path, capsys): """ChromaDB can return `None` entries in the metadatas list when a drawer has no metadata. The CLI print path must not crash on them mid-render — it used to raise `AttributeError: 'NoneType' object has @@ -379,14 +392,14 @@ class TestSearchCLI: "distances": [[0.1, 0.2]], } with patch("mempalace.searcher.get_collection", return_value=mock_col): - search("anything", "/fake/path") + search("anything", fake_palace_path) captured = capsys.readouterr() assert "[1]" in captured.out assert "[2]" in captured.out # Second result renders with fallback '?' values instead of crashing assert "second doc" in captured.out - def test_search_handles_none_document_without_crash(self, capsys): + def test_search_handles_none_document_without_crash(self, fake_palace_path, capsys): mock_col = MagicMock() mock_col.metadata = {"hnsw:space": "cosine"} mock_col.query.return_value = { @@ -395,7 +408,7 @@ class TestSearchCLI: "distances": [[0.1, 0.2]], } with patch("mempalace.searcher.get_collection", return_value=mock_col): - search("anything", "/fake/path") + search("anything", fake_palace_path) captured = capsys.readouterr() assert "[1]" in captured.out assert "[2]" in captured.out From 419a34c5c584bb179fb543a386b4d61f180e9671 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Sun, 17 May 2026 15:01:14 -0300 Subject: [PATCH 53/64] style(tests): restore ruff 0.4.x assert formatting in test_palace_locks (#1438) The PR reformatted two pre-existing assertions with a newer ruff (0.5+ `assert X, (\n msg\n)` style) that CI's pinned ruff (>=0.4.0,<0.5) rejects, failing `ruff format --check .`. Revert those two unrelated blocks to develop's 0.4.x form; the genuine #1435 fix and its new regression tests are untouched. --- tests/test_palace_locks.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/test_palace_locks.py b/tests/test_palace_locks.py index b4d2fbc..df94f16 100644 --- a/tests/test_palace_locks.py +++ b/tests/test_palace_locks.py @@ -199,9 +199,9 @@ def test_reentrant_same_thread_passes_through(tmp_path, monkeypatch): child = ctx.Process(target=_try_acquire_expect_busy, args=(palace, result_q)) try: child.start() - assert result_q.get(timeout=10) == "busy", ( - "outer lock should still be held by parent after inner re-entrant exit" - ) + assert ( + result_q.get(timeout=10) == "busy" + ), "outer lock should still be held by parent after inner re-entrant exit" child.join(timeout=5) assert child.exitcode == 0 finally: @@ -267,9 +267,9 @@ def test_lock_failure_message_names_holder(tmp_path, monkeypatch): pytest.fail("second acquire of same palace should have raised") msg = str(excinfo.value) - assert f"PID {holder_pid}" in msg, ( - f"lock-failure message must name the holder PID; got: {msg!r}" - ) + assert ( + f"PID {holder_pid}" in msg + ), f"lock-failure message must name the holder PID; got: {msg!r}" finally: open(release, "w").close() holder.join(timeout=5) From 3c74ba6493d68672649b185945d205495eb2848c Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Sun, 17 May 2026 16:09:45 -0300 Subject: [PATCH 54/64] style(tests): apply ruff 0.4.x format to test_mcp_server (#1445) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI pins ruff>=0.4.0,<0.5 (resolves 0.4.10); the PR's two new assert blocks were laid out in ruff-0.5+ style, so `ruff format --check .` failed. Reformat with ruff 0.4.10 (the exact CI version) — assertion layout only, no semantic change. `ruff check .` + `ruff format --check .` both pass under 0.4.10. --- tests/test_mcp_server.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index c5a0e86..94603e5 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -716,9 +716,9 @@ class TestWriteTools: assert result1["success"] is True assert result2["success"] is True - assert result1["drawer_id"] != result2["drawer_id"], ( - "Documents with shared header but different content must have distinct drawer IDs" - ) + assert ( + result1["drawer_id"] != result2["drawer_id"] + ), "Documents with shared header but different content must have distinct drawer IDs" def test_delete_drawer(self, monkeypatch, config, palace_path, seeded_collection, kg): _patch_mcp_server(monkeypatch, config, kg) @@ -1683,9 +1683,9 @@ class TestCacheInvalidation: all_calls = captured["get"] + captured["create"] assert all_calls, "expected get_collection or create_collection to be called" for kwargs in all_calls: - assert "embedding_function" in kwargs, ( - f"missing embedding_function= in chromadb call: {kwargs}" - ) + assert ( + "embedding_function" in kwargs + ), f"missing embedding_function= in chromadb call: {kwargs}" assert kwargs["embedding_function"] is not None # Same expectation on the create=False (cache-miss) reopen path. From 83e4711593e587706714837043ca48960c9d6623 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Sun, 17 May 2026 22:52:01 -0300 Subject: [PATCH 55/64] style(tests): apply ruff 0.4.x format to test_convo_miner (#1528) CI pins ruff>=0.4.0,<0.5 (resolves 0.4.10); one new assert block was laid out in ruff-0.5+ style, failing `ruff format --check .`. Reformat with the exact CI ruff version (assertion layout only, no semantic change). `ruff check .` + `ruff format --check .` both pass under 0.4.10. --- tests/test_convo_miner.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_convo_miner.py b/tests/test_convo_miner.py index af7a283..015a9d3 100644 --- a/tests/test_convo_miner.py +++ b/tests/test_convo_miner.py @@ -172,9 +172,9 @@ def test_mine_convos_rebuilds_stale_drawers_after_schema_bump(capsys): # Second mine — version gate should trigger rebuild mine_convos(tmpdir, palace_path, wing="test") out = capsys.readouterr().out - assert "Files skipped (already filed): 0" in out, ( - "stale drawers should force a rebuild, not a skip" - ) + assert ( + "Files skipped (already filed): 0" in out + ), "stale drawers should force a rebuild, not a skip" client = chromadb.PersistentClient(path=palace_path) col = client.get_collection("mempalace_drawers") From 96a327233db7b68dc33c88c7179b5ebb52f61453 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Sun, 17 May 2026 23:20:01 -0300 Subject: [PATCH 56/64] ci(lint): pin ruff to 0.15.9 across CI and dev deps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI installed `ruff>=0.4.0,<0.5` (resolves 0.4.10) while contributors run modern ruff (0.5+). ruff 0.5 changed assert-message formatting, so valid code formatted by a current ruff fails CI's `ruff format --check .` on layout alone. This blocked #1438, #1445, and #1528 — each needing a manual reformat-and-push cycle with no actual code defect. Pin an exact, modern ruff in both pyproject dev lists and in ci.yml so CI and `pip install -e ".[dev]"` format/lint identically. No new `ruff check` violations under the existing E/F/W/C901 select. --- .github/workflows/ci.yml | 5 ++++- pyproject.toml | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c6bcaa..5aee4e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,6 +50,9 @@ jobs: with: python-version: "3.11" cache: 'pip' - - run: pip install "ruff>=0.4.0,<0.5" + # Keep this pin identical to the `ruff==` pin in pyproject.toml + # ([project.optional-dependencies].dev and [dependency-groups].dev) + # so CI and `pip install -e ".[dev]"` format/lint identically. + - run: pip install "ruff==0.15.9" - run: ruff check . - run: ruff format --check . diff --git a/pyproject.toml b/pyproject.toml index 580f777..99db4c4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,7 @@ chroma = "mempalace.backends.chroma:ChromaBackend" [project.entry-points."mempalace.sources"] [project.optional-dependencies] -dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff>=0.4.0", "psutil>=5.9"] +dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff==0.15.9", "psutil>=5.9"] spellcheck = ["autocorrect>=2.0"] # Hardware acceleration for the ONNX embedding model. Install exactly one: # pip install mempalace[gpu] — NVIDIA CUDA @@ -63,7 +63,7 @@ dml = ["onnxruntime-directml>=1.16"] coreml = ["onnxruntime>=1.16"] [dependency-groups] -dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff>=0.4.0", "psutil>=5.9"] +dev = ["pytest>=7.0", "pytest-cov>=4.0", "ruff==0.15.9", "psutil>=5.9"] [build-system] requires = ["hatchling"] From 2cab6f5a5bb2c818098c6e84c3567ba99ec21f04 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Sun, 17 May 2026 23:20:01 -0300 Subject: [PATCH 57/64] style: reformat tree with ruff 0.15.9 One-time mechanical reformat so `ruff format --check .` passes under the newly pinned ruff. Layout only (assert-message parenthesization etc.), no behavior change. 29 files: 28 under tests/ + 1 tools helper, no core mempalace/ modules. Produced by `ruff format .`. --- tests/test_backends.py | 12 ++--- tests/test_chroma_collection_lock.py | 6 +-- tests/test_claude_plugin_hook_config.py | 24 +++++----- tests/test_cli.py | 12 ++--- tests/test_closet_llm.py | 12 ++--- tests/test_closets.py | 26 +++++----- tests/test_convo_miner.py | 6 +-- tests/test_corpus_origin.py | 42 ++++++++-------- tests/test_corpus_origin_integration.py | 64 ++++++++++++------------- tests/test_hooks_bash_compat.py | 54 ++++++++++----------- tests/test_hooks_cli.py | 6 +-- tests/test_hooks_shell.py | 24 +++++----- tests/test_hybrid_candidate_union.py | 9 ++-- tests/test_i18n.py | 6 +-- tests/test_i18n_lang_case.py | 6 +-- tests/test_init.py | 14 +++--- tests/test_llm_client.py | 24 +++++----- tests/test_mcp_server.py | 42 ++++++++-------- tests/test_mcp_stdio_protection.py | 6 +-- tests/test_normalize.py | 8 +--- tests/test_palace_graph_tunnels.py | 6 +-- tests/test_palace_locks.py | 12 ++--- tests/test_readme_claims.py | 30 ++++++------ tests/test_repair.py | 6 +-- tests/test_save_hook_mines.py | 28 +++++------ tests/test_searcher.py | 15 +++--- tests/test_sweeper.py | 6 +-- tests/test_sync.py | 60 +++++++++++------------ tools/render_jsonl.py | 2 +- 29 files changed, 279 insertions(+), 289 deletions(-) diff --git a/tests/test_backends.py b/tests/test_backends.py index 8f36126..1fc8eab 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -823,9 +823,9 @@ def test_make_client_quarantines_only_on_first_call_per_palace(tmp_path, monkeyp ChromaBackend.make_client(palace_path) ChromaBackend.make_client(palace_path) - assert calls == [ - palace_path - ], "quarantine_stale_hnsw should fire once per palace per process, not on every reconnect" + assert calls == [palace_path], ( + "quarantine_stale_hnsw should fire once per palace per process, not on every reconnect" + ) def test_make_client_gates_invalid_metadata_on_first_call(tmp_path, monkeypatch): @@ -941,9 +941,9 @@ def test_client_quarantines_only_on_first_call_per_palace(tmp_path, monkeypatch) finally: backend.close() - assert ( - calls == [palace_path] - ), "quarantine_stale_hnsw should fire once per palace per process from _client(), not on every call" + assert calls == [palace_path], ( + "quarantine_stale_hnsw should fire once per palace per process from _client(), not on every call" + ) # ── _pin_hnsw_threads (per-process retrofit, separate from this PR's gate) ── diff --git a/tests/test_chroma_collection_lock.py b/tests/test_chroma_collection_lock.py index 086bcbf..85bd3c5 100644 --- a/tests/test_chroma_collection_lock.py +++ b/tests/test_chroma_collection_lock.py @@ -317,9 +317,9 @@ def test_read_path_does_not_acquire_lock(tmp_path, monkeypatch): if method is None: continue src = inspect.getsource(method) - assert ( - "_write_lock" not in src - ), f"{read_attr} must NOT acquire the write lock (read path)" + assert "_write_lock" not in src, ( + f"{read_attr} must NOT acquire the write lock (read path)" + ) finally: open(release, "w").close() holder.join(timeout=5) diff --git a/tests/test_claude_plugin_hook_config.py b/tests/test_claude_plugin_hook_config.py index 6c33054..d995ac3 100644 --- a/tests/test_claude_plugin_hook_config.py +++ b/tests/test_claude_plugin_hook_config.py @@ -51,23 +51,23 @@ def test_plugin_hook_timeout_within_bounds(hook_config: dict, event: str) -> Non ) for entry in entries: sub_hooks = entry.get("hooks") - assert ( - isinstance(sub_hooks, list) and sub_hooks - ), f"{event} entry missing non-empty 'hooks' array" - assert ( - len(sub_hooks) == 1 - ), f"{event} entry expected exactly one hook command, found {len(sub_hooks)}" + assert isinstance(sub_hooks, list) and sub_hooks, ( + f"{event} entry missing non-empty 'hooks' array" + ) + assert len(sub_hooks) == 1, ( + f"{event} entry expected exactly one hook command, found {len(sub_hooks)}" + ) for hook in sub_hooks: - assert ( - hook.get("type") == "command" - ), f"unexpected hook type for {event}: {hook.get('type')!r}" + assert hook.get("type") == "command", ( + f"unexpected hook type for {event}: {hook.get('type')!r}" + ) assert "timeout" in hook, f"{event} hook missing 'timeout' key" timeout = hook["timeout"] # bool subclasses int, so reject it explicitly: True == 1 must fail. is_real_int = isinstance(timeout, int) and not isinstance(timeout, bool) - assert ( - is_real_int and floor <= timeout <= ceiling - ), f"{event} hook timeout must be an int in [{floor}, {ceiling}]s; got {timeout!r}" + assert is_real_int and floor <= timeout <= ceiling, ( + f"{event} hook timeout must be an int in [{floor}, {ceiling}]s; got {timeout!r}" + ) def test_no_unbounded_events_in_plugin_config(hook_config: dict) -> None: diff --git a/tests/test_cli.py b/tests/test_cli.py index ee0a7dc..41cfc27 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -79,12 +79,12 @@ def test_cli_main_strips_leaked_pythonpath_from_env(): ) diag = f"rc={result.returncode}; stdout={result.stdout!r}; stderr={result.stderr!r}" assert result.returncode == 0, f"subprocess failed: {diag}" - assert ( - f"ENV_MID: {expected_env!r}" in result.stdout - ), f"package import unexpectedly stripped env (regression in __init__.py): {diag}" - assert ( - "SENTINEL_IN_PATH: False" in result.stdout - ), f"package import did not filter sys.path (regression in __init__.py): {diag}" + assert f"ENV_MID: {expected_env!r}" in result.stdout, ( + f"package import unexpectedly stripped env (regression in __init__.py): {diag}" + ) + assert "SENTINEL_IN_PATH: False" in result.stdout, ( + f"package import did not filter sys.path (regression in __init__.py): {diag}" + ) assert "ENV_AFTER: None" in result.stdout, f"CLI did not strip PYTHONPATH: {diag}" diff --git a/tests/test_closet_llm.py b/tests/test_closet_llm.py index 905d28b..296d105 100644 --- a/tests/test_closet_llm.py +++ b/tests/test_closet_llm.py @@ -312,9 +312,9 @@ class TestRegenerateClosets: survivors = closets.get(where={"source_file": source}, include=["documents", "metadatas"]) assert survivors["ids"], "LLM closets should have been written" joined = "\n".join(survivors["documents"]) - assert ( - "STALE_REGEX_TOPIC" not in joined - ), "pre-existing regex closet was not purged before LLM write" + assert "STALE_REGEX_TOPIC" not in joined, ( + "pre-existing regex closet was not purged before LLM write" + ) assert "jwt auth" in joined for meta in survivors["metadatas"]: assert meta.get("generated_by", "").startswith("llm:") @@ -399,9 +399,9 @@ class TestRegenerateClosets: # Three paginated calls: (limit=5000, offset=0), (5000, 5000), (5000, 10000). assert len(get_calls) == 3, f"expected 3 batched fetches, got {len(get_calls)}" for call in get_calls: - assert ( - call["limit"] == 5000 - ), f"batch must be 5000 — got {call['limit']} (would risk SQLITE_MAX_VARIABLE_NUMBER)" + assert call["limit"] == 5000, ( + f"batch must be 5000 — got {call['limit']} (would risk SQLITE_MAX_VARIABLE_NUMBER)" + ) # include must still request both documents and metadatas assert "documents" in call["include"] assert "metadatas" in call["include"] diff --git a/tests/test_closets.py b/tests/test_closets.py index e016d83..2aa5597 100644 --- a/tests/test_closets.py +++ b/tests/test_closets.py @@ -140,9 +140,9 @@ class TestMineLock: # Sort by entry time and verify the second entry is after the first exit. intervals.sort(key=lambda iv: iv[1]) (_, enter_a, exit_a), (_, enter_b, exit_b) = intervals - assert ( - enter_a < exit_a <= enter_b < exit_b - ), f"critical sections overlapped — lock failed to serialize: {intervals}" + assert enter_a < exit_a <= enter_b < exit_b, ( + f"critical sections overlapped — lock failed to serialize: {intervals}" + ) # ── build_closet_lines ───────────────────────────────────────────────── @@ -315,15 +315,15 @@ class TestMinerClosetRebuild: second_docs = "\n".join(second_pass["documents"]).lower() assert "only topic now" in second_docs for i in range(15): - assert ( - f"topic {i}\n" not in second_docs - ), f"stale 'Topic {i}' from first mine survived the rebuild" + assert f"topic {i}\n" not in second_docs, ( + f"stale 'Topic {i}' from first mine survived the rebuild" + ) # Numbered closets that existed only in the larger first run must be gone. leftover = first_ids - set(second_pass["ids"]) for stale_id in leftover: - assert not col.get(ids=[stale_id])[ - "ids" - ], f"orphan closet {stale_id} from larger first run survived purge" + assert not col.get(ids=[stale_id])["ids"], ( + f"orphan closet {stale_id} from larger first run survived purge" + ) # ── _extract_drawer_ids_from_closet ─────────────────────────────────── @@ -702,9 +702,9 @@ class TestDiaryIngest: # No state file inside the user's diary dir. for entry in diary_dir.iterdir(): - assert ( - "diary_ingest" not in entry.name - ), f"state file leaked into user diary dir: {entry}" + assert "diary_ingest" not in entry.name, ( + f"state file leaked into user diary dir: {entry}" + ) # State file does exist under ~/.mempalace/state/. state_path = _state_file_for(str(palace_dir), diary_dir.resolve()) @@ -905,7 +905,7 @@ class TestTunnels: assert not errors, f"worker raised: {errors}" tunnels = list_tunnels() assert len(tunnels) == 5, ( - f"expected 5 concurrent tunnels, got {len(tunnels)} — " "write race dropped some" + f"expected 5 concurrent tunnels, got {len(tunnels)} — write race dropped some" ) def test_created_at_is_timezone_aware(self): diff --git a/tests/test_convo_miner.py b/tests/test_convo_miner.py index 015a9d3..af7a283 100644 --- a/tests/test_convo_miner.py +++ b/tests/test_convo_miner.py @@ -172,9 +172,9 @@ def test_mine_convos_rebuilds_stale_drawers_after_schema_bump(capsys): # Second mine — version gate should trigger rebuild mine_convos(tmpdir, palace_path, wing="test") out = capsys.readouterr().out - assert ( - "Files skipped (already filed): 0" in out - ), "stale drawers should force a rebuild, not a skip" + assert "Files skipped (already filed): 0" in out, ( + "stale drawers should force a rebuild, not a skip" + ) client = chromadb.PersistentClient(path=palace_path) col = client.get_collection("mempalace_drawers") diff --git a/tests/test_corpus_origin.py b/tests/test_corpus_origin.py index 6676bbd..98a22ae 100644 --- a/tests/test_corpus_origin.py +++ b/tests/test_corpus_origin.py @@ -112,17 +112,17 @@ class TestHeuristic: "anthropic's haiku model is cheap enough to run on every drawer", ] result = detect_origin_heuristic(samples) - assert ( - result.likely_ai_dialogue is True - ), f"lowercase brand terms missed; evidence: {result.evidence}" + assert result.likely_ai_dialogue is True, ( + f"lowercase brand terms missed; evidence: {result.evidence}" + ) # Evidence must show MULTIPLE distinct case-insensitive brand matches. # 'chatgpt' lowercase only matches under case-insensitive search # (the brand list has 'ChatGPT' proper-cased only). evidence_str = " ".join(result.evidence).lower() matched = sum(t in evidence_str for t in ("chatgpt", "anthropic", "haiku", "gemini-pro")) - assert ( - matched >= 2 - ), f"case-insensitive brand matches did not fire — only got: {result.evidence}" + assert matched >= 2, ( + f"case-insensitive brand matches did not fire — only got: {result.evidence}" + ) def test_zodiac_corpus_not_flagged_as_ai(self): """An astrology forum post with high 'Gemini' density but ZERO @@ -138,9 +138,9 @@ class TestHeuristic: "The Gemini twins in Greek mythology are Castor and Pollux.", ] result = detect_origin_heuristic(samples) - assert ( - result.likely_ai_dialogue is False - ), f"zodiac corpus wrongly flagged AI; evidence: {result.evidence}" + assert result.likely_ai_dialogue is False, ( + f"zodiac corpus wrongly flagged AI; evidence: {result.evidence}" + ) def test_french_novel_with_claude_name_not_flagged(self): """A French novel where 'Claude' is a character name (Claude is a @@ -155,9 +155,9 @@ class TestHeuristic: "Les amis de Claude s'étaient réunis chez lui pour fêter ses soixante ans.", ] result = detect_origin_heuristic(samples) - assert ( - result.likely_ai_dialogue is False - ), f"French novel wrongly flagged AI; evidence: {result.evidence}" + assert result.likely_ai_dialogue is False, ( + f"French novel wrongly flagged AI; evidence: {result.evidence}" + ) def test_poetry_corpus_with_haiku_sonnet_not_flagged(self): """A poetry corpus with high 'haiku', 'sonnet', 'opus' density @@ -172,9 +172,9 @@ class TestHeuristic: "Her first opus, published at twenty, was a song cycle for soprano.", ] result = detect_origin_heuristic(samples) - assert ( - result.likely_ai_dialogue is False - ), f"poetry corpus wrongly flagged AI; evidence: {result.evidence}" + assert result.likely_ai_dialogue is False, ( + f"poetry corpus wrongly flagged AI; evidence: {result.evidence}" + ) def test_word_boundary_brand_matching(self): """Brand-term matching must use word boundaries. Embedded matches @@ -208,9 +208,9 @@ class TestHeuristic: ) # And classification should be not-AI (no real AI signals present). - assert ( - result.likely_ai_dialogue is False - ), f"corpus has no real AI signals; evidence: {result.evidence}" + assert result.likely_ai_dialogue is False, ( + f"corpus has no real AI signals; evidence: {result.evidence}" + ) def test_ambiguous_brand_with_unambiguous_signal_flagged(self): """When an ambiguous brand term ('Gemini') co-occurs with an @@ -224,9 +224,9 @@ class TestHeuristic: "MCP server config: Gemini as primary, OpenAI as fallback.", ] result = detect_origin_heuristic(samples) - assert ( - result.likely_ai_dialogue is True - ), f"ambiguous+unambiguous co-occurrence missed; evidence: {result.evidence}" + assert result.likely_ai_dialogue is True, ( + f"ambiguous+unambiguous co-occurrence missed; evidence: {result.evidence}" + ) # ── Tier 2: LLM-assisted (mocked) ───────────────────────────────────────── diff --git a/tests/test_corpus_origin_integration.py b/tests/test_corpus_origin_integration.py index 5ee38e8..bd5abcf 100644 --- a/tests/test_corpus_origin_integration.py +++ b/tests/test_corpus_origin_integration.py @@ -178,7 +178,7 @@ def test_corpus_origin_reclassifies_personas( # All three personas land in the new bucket. expected_personas = {"Echo", "Sparrow", "Cipher"} assert expected_personas <= persona_names_in_bucket, ( - f"Expected all three personas in agent_personas, got: " f"{persona_names_in_bucket}" + f"Expected all three personas in agent_personas, got: {persona_names_in_bucket}" ) # And NONE of them remain in the people bucket. @@ -293,8 +293,7 @@ def test_init_pass_zero_writes_origin_json_to_palace(ai_dialogue_corpus: Path, t assert isinstance(data["result"].get("likely_ai_dialogue"), bool) # Fixture is heavy AI-dialogue — heuristic should classify as such. assert data["result"]["likely_ai_dialogue"] is True, ( - "Heuristic should classify the AI-dialogue fixture as AI-dialogue. " - f"Got: {data['result']}" + f"Heuristic should classify the AI-dialogue fixture as AI-dialogue. Got: {data['result']}" ) @@ -744,9 +743,9 @@ def test_init_graceful_fallback_when_provider_unavailable( out = capsys.readouterr().out # The fallback message should mention how to silence (--no-llm) so the # user knows what flipped. - assert ( - "no-llm" in out.lower() or "--no-llm" in out - ), f"Graceful fallback message must point at --no-llm. Got: {out!r}" + assert "no-llm" in out.lower() or "--no-llm" in out, ( + f"Graceful fallback message must point at --no-llm. Got: {out!r}" + ) def test_init_graceful_fallback_on_provider_construction_error( @@ -1308,9 +1307,9 @@ def test_integration_llm_refine_corpus_origin_preamble_does_not_break_topic_labe "TOPIC label instructions disappeared from SYSTEM_PROMPT — " "corpus-origin preamble appears to have replaced rather than appended" ) - assert ( - "CORPUS CONTEXT" in captured["system"] - ), "corpus-origin corpus context preamble missing from prompt" + assert "CORPUS CONTEXT" in captured["system"], ( + "corpus-origin corpus context preamble missing from prompt" + ) # ───────────────────────────────────────────────────────────────────────── @@ -1546,12 +1545,12 @@ def test_merge_tier_fields_heuristic_no_no_personas_leak(): assert wrapped is not None res = wrapped["result"] - assert ( - res["likely_ai_dialogue"] is False - ), f"Both tiers said NOT AI-dialogue; merged result must be False. Got: {res}" - assert ( - res["agent_persona_names"] == [] - ), f"No personas should leak when both tiers report none. Got: {res}" + assert res["likely_ai_dialogue"] is False, ( + f"Both tiers said NOT AI-dialogue; merged result must be False. Got: {res}" + ) + assert res["agent_persona_names"] == [], ( + f"No personas should leak when both tiers report none. Got: {res}" + ) # Heuristic owns confidence. Mocked LLM returned 0.95; heuristic's # narrative-branch confidence is 0.9. Verifying we kept 0.9 catches # any future regression that lets LLM confidence override heuristic. @@ -1609,24 +1608,23 @@ def test_merge_tier_fields_heuristic_yes_llm_yes_combines_evidence(): # LLM produced its own; the merged result should include both signal # trails for audit purposes. evidence_text = " ".join(res["evidence"]) - assert ( - "LLM-extracted" in evidence_text - ), f"LLM evidence string missing from merged result. Got: {res['evidence']}" + assert "LLM-extracted" in evidence_text, ( + f"LLM evidence string missing from merged result. Got: {res['evidence']}" + ) # Heuristic always produces at least one evidence line for AI-dialogue # input (brand-term match), so the combined list has more than just LLM's. assert len(res["evidence"]) >= 2, ( - f"Combined evidence should include both heuristic + LLM lines. " f"Got: {res['evidence']}" + f"Combined evidence should include both heuristic + LLM lines. Got: {res['evidence']}" ) # Each entry must carry its tier prefix so on-disk origin.json is # auditable — readers can tell which tier produced which signal line. tier1_lines = [e for e in res["evidence"] if e.startswith("Tier-1 heuristic: ")] tier2_lines = [e for e in res["evidence"] if e.startswith("Tier-2 LLM: ")] assert tier1_lines, ( - f"Expected at least one 'Tier-1 heuristic: ' prefixed evidence line. " - f"Got: {res['evidence']}" + f"Expected at least one 'Tier-1 heuristic: ' prefixed evidence line. Got: {res['evidence']}" ) assert tier2_lines, ( - f"Expected at least one 'Tier-2 LLM: ' prefixed evidence line. " f"Got: {res['evidence']}" + f"Expected at least one 'Tier-2 LLM: ' prefixed evidence line. Got: {res['evidence']}" ) # Every entry should be tier-prefixed (no untagged passthrough). untagged = [ @@ -1759,11 +1757,11 @@ def test_init_prints_privacy_warning_when_provider_is_external( out = capsys.readouterr().out assert "EXTERNAL API" in out, ( - f"Privacy warning must mention 'EXTERNAL API' when provider is external. " f"Got: {out!r}" + f"Privacy warning must mention 'EXTERNAL API' when provider is external. Got: {out!r}" + ) + assert "--no-llm" in out, ( + f"Privacy warning must point users at --no-llm to opt out. Got: {out!r}" ) - assert ( - "--no-llm" in out - ), f"Privacy warning must point users at --no-llm to opt out. Got: {out!r}" # The warning should also tell users MemPalace isn't responsible # for downstream provider behavior. assert ( @@ -1804,7 +1802,7 @@ def test_init_no_privacy_warning_when_provider_is_local( out = capsys.readouterr().out assert "EXTERNAL API" not in out, ( - f"Privacy warning fired for a LOCAL provider — should not have. " f"Got: {out!r}" + f"Privacy warning fired for a LOCAL provider — should not have. Got: {out!r}" ) @@ -1827,9 +1825,9 @@ def test_init_no_privacy_warning_with_no_llm_flag(ai_dialogue_corpus: Path, tmp_ mock_get.assert_not_called(), "--no-llm must short-circuit before provider acquisition" out = capsys.readouterr().out - assert ( - "EXTERNAL API" not in out - ), f"Privacy warning fired on --no-llm path — should not have. Got: {out!r}" + assert "EXTERNAL API" not in out, ( + f"Privacy warning fired on --no-llm path — should not have. Got: {out!r}" + ) # ───────────────────────────────────────────────────────────────────────── @@ -1988,9 +1986,9 @@ def test_init_accept_external_llm_flag_bypasses_consent_prompt( "--accept-external-llm must bypass the consent prompt for " "non-interactive / CI use. input() was called anyway." ) - assert ( - fake_provider.classify.called - ), "With --accept-external-llm, init must proceed with the LLM." + assert fake_provider.classify.called, ( + "With --accept-external-llm, init must proceed with the LLM." + ) def test_init_no_consent_prompt_when_endpoint_is_local( diff --git a/tests/test_hooks_bash_compat.py b/tests/test_hooks_bash_compat.py index 05fda22..bc19440 100644 --- a/tests/test_hooks_bash_compat.py +++ b/tests/test_hooks_bash_compat.py @@ -98,12 +98,12 @@ class TestNoBash4OnlyBuiltins: @_BOTH_HOOKS def test_no_mapfile(self, hook): code = _hook_src_no_comments(hook) - assert ( - "mapfile" not in code - ), f"{hook.name} uses mapfile, unavailable on macOS /bin/bash 3.2 (#1440)" - assert ( - "readarray" not in code - ), f"{hook.name} uses readarray, unavailable on macOS /bin/bash 3.2 (#1440)" + assert "mapfile" not in code, ( + f"{hook.name} uses mapfile, unavailable on macOS /bin/bash 3.2 (#1440)" + ) + assert "readarray" not in code, ( + f"{hook.name} uses readarray, unavailable on macOS /bin/bash 3.2 (#1440)" + ) @_BOTH_HOOKS def test_sed_extraction_present(self, hook): @@ -115,9 +115,9 @@ class TestNoBash4OnlyBuiltins: # method back to ``mapfile`` while keeping the old commentary. src = _hook_src_no_comments(hook) # Each hook reads at least two values via ``sed -n 'Np'`` (sentinel + session_id). - assert ( - src.count("sed -n '") >= 2 - ), f"{hook.name} must use sed -n 'Np' for POSIX-portable line extraction" + assert src.count("sed -n '") >= 2, ( + f"{hook.name} must use sed -n 'Np' for POSIX-portable line extraction" + ) @_BOTH_HOOKS def test_bash_syntax_clean(self, hook): @@ -150,9 +150,9 @@ class TestSessionIdExtraction: assert "WARN: input parse failed" not in log state_dir = tmp_path / ".mempalace" / "hook_state" assert not (state_dir / "last_input.log").exists() - assert not ( - state_dir / "last_python_err.log" - ).exists(), "successful parse must leave no last_python_err.log behind" + assert not (state_dir / "last_python_err.log").exists(), ( + "successful parse must leave no last_python_err.log behind" + ) def test_precompact_hook_extracts_session_id(self, tmp_path): out, _ = _run_hook( @@ -166,9 +166,9 @@ class TestSessionIdExtraction: assert "WARN: input parse failed" not in log state_dir = tmp_path / ".mempalace" / "hook_state" assert not (state_dir / "last_input.log").exists() - assert not ( - state_dir / "last_python_err.log" - ).exists(), "successful parse must leave no last_python_err.log behind" + assert not (state_dir / "last_python_err.log").exists(), ( + "successful parse must leave no last_python_err.log behind" + ) class TestFailLoudGuard: @@ -214,9 +214,9 @@ class TestFailLoudGuard: tmp_path, ) state_dir = tmp_path / ".mempalace" / "hook_state" - assert not ( - state_dir / "last_input.log" - ).exists(), "unicode-only session_id sanitized to empty must NOT trip the guard" + assert not (state_dir / "last_input.log").exists(), ( + "unicode-only session_id sanitized to empty must NOT trip the guard" + ) @_BOTH_HOOKS def test_literal_unknown_session_id_does_not_trip_guard(self, hook, tmp_path): @@ -231,9 +231,9 @@ class TestFailLoudGuard: tmp_path, ) state_dir = tmp_path / ".mempalace" / "hook_state" - assert not ( - state_dir / "last_input.log" - ).exists(), "literal session_id='unknown' must NOT trip the guard" + assert not (state_dir / "last_input.log").exists(), ( + "literal session_id='unknown' must NOT trip the guard" + ) @_BOTH_HOOKS def test_dump_is_bounded_and_overwritten(self, hook, tmp_path): @@ -251,9 +251,9 @@ class TestFailLoudGuard: big_payload = "x" * 4097 _run_hook(hook, big_payload, tmp_path) last_input = tmp_path / ".mempalace" / "hook_state" / "last_input.log" - assert ( - last_input.stat().st_size == 4096 - ), f"cap must be exactly 4096 bytes; got {last_input.stat().st_size}" + assert last_input.stat().st_size == 4096, ( + f"cap must be exactly 4096 bytes; got {last_input.stat().st_size}" + ) # Second failure with a smaller payload (also not valid JSON, so the # guard fires) overwrites the first; the file shrinks instead of # accumulating. @@ -310,9 +310,9 @@ class TestFailLoudGuard: # Python's json.load raises JSONDecodeError with a recognizable # traceback. Don't pin the exact message (it varies by Python # version) but assert at least one canonical marker is present. - assert ( - "Traceback" in contents or "json" in contents.lower() - ), f"expected Python traceback or json error, got: {contents!r}" + assert "Traceback" in contents or "json" in contents.lower(), ( + f"expected Python traceback or json error, got: {contents!r}" + ) @_BOTH_HOOKS def test_python_stderr_log_is_not_world_readable_on_failure(self, hook, tmp_path): diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index e9bd7d7..234bef2 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -850,9 +850,9 @@ def test_spawn_mine_releases_slot_on_oserror(tmp_path): with patch("mempalace.hooks_cli.subprocess.Popen", side_effect=OSError("spawn fail")): with pytest.raises(OSError): _spawn_mine(cmd) - assert ( - not pid_file.exists() - ), "slot must be released so the next hook fire isn't permanently blocked" + assert not pid_file.exists(), ( + "slot must be released so the next hook fire isn't permanently blocked" + ) def test_spawn_mine_passes_pid_file_env_var(tmp_path): diff --git a/tests/test_hooks_shell.py b/tests/test_hooks_shell.py index cc8b8e2..7462d97 100644 --- a/tests/test_hooks_shell.py +++ b/tests/test_hooks_shell.py @@ -123,13 +123,13 @@ class TestMempalPythonOverride: {"session_id": "abc", "stop_hook_active": False, "transcript_path": ""}, env_overrides={"MEMPAL_PYTHON": str(fake), "HOME": str(tmp_path)}, ) - assert ( - result.returncode == 0 - ), f"hook exited non-zero: stderr={result.stderr!r} stdout={result.stdout!r}" + assert result.returncode == 0, ( + f"hook exited non-zero: stderr={result.stderr!r} stdout={result.stdout!r}" + ) invocations = marker.read_text().splitlines() if marker.exists() else [] - assert ( - "override_python" in invocations - ), f"MEMPAL_PYTHON override was not used. Marker log: {invocations!r}" + assert "override_python" in invocations, ( + f"MEMPAL_PYTHON override was not used. Marker log: {invocations!r}" + ) def test_ignores_override_when_not_executable(self, tmp_path): """If MEMPAL_PYTHON is set but the file isn't executable, the @@ -143,9 +143,9 @@ class TestMempalPythonOverride: {"session_id": "abc", "stop_hook_active": False, "transcript_path": ""}, env_overrides={"MEMPAL_PYTHON": str(bogus), "HOME": str(tmp_path)}, ) - assert ( - result.returncode == 0 - ), f"hook crashed on non-executable MEMPAL_PYTHON: {result.stderr!r}" + assert result.returncode == 0, ( + f"hook crashed on non-executable MEMPAL_PYTHON: {result.stderr!r}" + ) def test_falls_back_to_path_when_unset(self, tmp_path): """With MEMPAL_PYTHON unset, the hook uses whatever ``python3`` @@ -165,6 +165,6 @@ class TestMempalPythonOverride: ) assert result.returncode == 0 invocations = marker.read_text().splitlines() if marker.exists() else [] - assert ( - "python3" in invocations - ), f"fallback-to-PATH did not use the shimmed python3. Marker log: {invocations!r}" + assert "python3" in invocations, ( + f"fallback-to-PATH did not use the shimmed python3. Marker log: {invocations!r}" + ) diff --git a/tests/test_hybrid_candidate_union.py b/tests/test_hybrid_candidate_union.py index feca81e..0771001 100644 --- a/tests/test_hybrid_candidate_union.py +++ b/tests/test_hybrid_candidate_union.py @@ -79,8 +79,7 @@ class TestCandidateUnion: result = search_memories(_NARRATIVE_QUERY, palace, n_results=5, candidate_strategy="union") ids = [h["source_file"] for h in result["results"]] assert "brand_voice_D4.md" in ids, ( - "union mode must surface BM25-strong docs even when vector signal " - f"is weak; got {ids}" + f"union mode must surface BM25-strong docs even when vector signal is weak; got {ids}" ) def test_union_preserves_vector_hits(self, tmp_path): @@ -138,9 +137,9 @@ class TestCandidateUnion: # 4-doc corpus, n_results=2 → union pool can grow to ~8 candidates, # rerank reorders them, but final list must respect the cap. result = search_memories(_NARRATIVE_QUERY, palace, n_results=2, candidate_strategy="union") - assert ( - len(result["results"]) <= 2 - ), f"union must trim to n_results=2; got {len(result['results'])} results" + assert len(result["results"]) <= 2, ( + f"union must trim to n_results=2; got {len(result['results'])} results" + ) def test_union_skipped_when_max_distance_set(self, tmp_path): """``max_distance`` is a vector-distance threshold; BM25-only diff --git a/tests/test_i18n.py b/tests/test_i18n.py index 1f53da7..40af982 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -155,7 +155,7 @@ def test_direct_address_key_is_singular_string_for_all_locales(): ) if "direct_address_pattern" in section: val = section["direct_address_pattern"] - assert isinstance( - val, str - ), f"{lang}: 'direct_address_pattern' must be str, got {type(val).__name__}" + assert isinstance(val, str), ( + f"{lang}: 'direct_address_pattern' must be str, got {type(val).__name__}" + ) assert val, f"{lang}: 'direct_address_pattern' is empty" diff --git a/tests/test_i18n_lang_case.py b/tests/test_i18n_lang_case.py index 4c57ed1..47b101e 100644 --- a/tests/test_i18n_lang_case.py +++ b/tests/test_i18n_lang_case.py @@ -74,9 +74,9 @@ def test_get_entity_patterns_shares_cache_across_cases(): cache_keys = list(i18n._entity_cache.keys()) get_entity_patterns(("ZH-CN",)) get_entity_patterns(("zh-cn",)) - assert len(i18n._entity_cache) == len( - cache_keys - ), "different casings of the same language must not create new cache entries" + assert len(i18n._entity_cache) == len(cache_keys), ( + "different casings of the same language must not create new cache entries" + ) def test_unknown_language_still_falls_back_to_english(): diff --git a/tests/test_init.py b/tests/test_init.py index bf6c9a4..ced0497 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -65,15 +65,15 @@ def test_init_filters_sys_path_from_leaked_pythonpath(pythonpath): out = result.stdout # Env must be preserved verbatim: embedded callers may need it. expected_env = repr(pythonpath) if pythonpath is not None else repr(None) - assert ( - f"ENV: {expected_env}" in out - ), f"PYTHONPATH should be preserved by package import: {diag}" + assert f"ENV: {expected_env}" in out, ( + f"PYTHONPATH should be preserved by package import: {diag}" + ) assert "SENTINEL_IN_PATH: False" in out, f"sentinel-prefix leak: {diag}" # Filter must not over-strip: the mempalace package itself must remain # importable, so its parent directory must survive on sys.path. - assert ( - "MEMPALACE_PARENT_PRESENT: True" in out - ), f"filter over-stripped sys.path (mempalace parent gone): {diag}" + assert "MEMPALACE_PARENT_PRESENT: True" in out, ( + f"filter over-stripped sys.path (mempalace parent gone): {diag}" + ) def test_init_preserves_cwd_marker_when_pythonpath_collides(): @@ -94,7 +94,7 @@ def test_init_preserves_cwd_marker_when_pythonpath_collides(): text=True, check=False, ) - diag = f"rc={result.returncode}; stdout={result.stdout!r}; " f"stderr={result.stderr!r}" + diag = f"rc={result.returncode}; stdout={result.stdout!r}; stderr={result.stderr!r}" assert result.returncode == 0, f"subprocess failed: {diag}" assert "CWD_IN_PATH: True" in result.stdout, f"cwd marker dropped: {diag}" assert "DOT_IN_PATH: False" in result.stdout, f"dot leak survived: {diag}" diff --git a/tests/test_llm_client.py b/tests/test_llm_client.py index d7ade20..324cb3e 100644 --- a/tests/test_llm_client.py +++ b/tests/test_llm_client.py @@ -445,9 +445,9 @@ def test_openai_compat_api_key_source_flag_when_explicit(monkeypatch): monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env-irrelevant") p = OpenAICompatProvider(model="x", endpoint="http://h", api_key="sk-from-flag") assert p.api_key == "sk-from-flag" - assert ( - p.api_key_source == "flag" - ), f"Explicit api_key arg must produce api_key_source='flag'; got {p.api_key_source!r}" + assert p.api_key_source == "flag", ( + f"Explicit api_key arg must produce api_key_source='flag'; got {p.api_key_source!r}" + ) def test_openai_compat_api_key_source_env_when_fallback(monkeypatch): @@ -458,9 +458,9 @@ def test_openai_compat_api_key_source_env_when_fallback(monkeypatch): monkeypatch.setenv("OPENAI_API_KEY", "sk-from-env") p = OpenAICompatProvider(model="x", endpoint="http://h") assert p.api_key == "sk-from-env" - assert ( - p.api_key_source == "env" - ), f"Env-fallback api_key must produce api_key_source='env'; got {p.api_key_source!r}" + assert p.api_key_source == "env", ( + f"Env-fallback api_key must produce api_key_source='env'; got {p.api_key_source!r}" + ) def test_anthropic_api_key_source_tracking(monkeypatch): @@ -468,14 +468,14 @@ def test_anthropic_api_key_source_tracking(monkeypatch): passed explicitly, 'env' when resolved from ANTHROPIC_API_KEY env.""" monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-env") p_flag = AnthropicProvider(model="claude-haiku", api_key="sk-ant-flag") - assert ( - p_flag.api_key_source == "flag" - ), f"Explicit api_key must produce 'flag'; got {p_flag.api_key_source!r}" + assert p_flag.api_key_source == "flag", ( + f"Explicit api_key must produce 'flag'; got {p_flag.api_key_source!r}" + ) p_env = AnthropicProvider(model="claude-haiku") assert p_env.api_key == "sk-ant-env" - assert ( - p_env.api_key_source == "env" - ), f"Env-fallback must produce 'env'; got {p_env.api_key_source!r}" + assert p_env.api_key_source == "env", ( + f"Env-fallback must produce 'env'; got {p_env.api_key_source!r}" + ) def test_ollama_api_key_source_is_none(): diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index c4004d5..4a1aae2 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -63,12 +63,12 @@ def test_mcp_main_strips_leaked_pythonpath_from_env(): ) diag = f"rc={result.returncode}; stdout={result.stdout!r}; stderr={result.stderr!r}" assert result.returncode == 0, f"subprocess failed: {diag}" - assert ( - f"ENV_MID: {expected_env!r}" in result.stderr - ), f"package import unexpectedly stripped env (regression in __init__.py): {diag}" - assert ( - "SENTINEL_IN_PATH: False" in result.stderr - ), f"package import did not filter sys.path (regression in __init__.py): {diag}" + assert f"ENV_MID: {expected_env!r}" in result.stderr, ( + f"package import unexpectedly stripped env (regression in __init__.py): {diag}" + ) + assert "SENTINEL_IN_PATH: False" in result.stderr, ( + f"package import did not filter sys.path (regression in __init__.py): {diag}" + ) assert "ENV_AFTER: None" in result.stderr, f"MCP server did not strip PYTHONPATH: {diag}" @@ -250,9 +250,9 @@ class TestColdStartDiagnostics: ) assert result.returncode == 0, f"stderr={result.stderr!r}" assert not marker.exists(), f"warmup ran for explicit-falsy value {value!r}" - assert ( - "not recognized" not in result.stderr - ), f"explicit-falsy {value!r} should not log a warning; stderr={result.stderr!r}" + assert "not recognized" not in result.stderr, ( + f"explicit-falsy {value!r} should not log a warning; stderr={result.stderr!r}" + ) @pytest.mark.parametrize("value", ["tru", "maybe", "ENABLED", "2"]) def test_eager_warmup_unrecognized_value_warns_and_skips_collection_open(self, tmp_path, value): @@ -298,9 +298,9 @@ class TestColdStartDiagnostics: extra_code=extra, ) assert result.returncode == 0, f"stderr={result.stderr!r}" - assert ( - open_marker.exists() - ), f"_get_collection not called for {value!r}; stderr={result.stderr!r}" + assert open_marker.exists(), ( + f"_get_collection not called for {value!r}; stderr={result.stderr!r}" + ) assert query_marker.exists(), ( f"col.query not invoked for {value!r} — warmup is a no-op " f"(would let cold-load hit first MCP call); stderr={result.stderr!r}" @@ -1134,9 +1134,9 @@ class TestWriteTools: assert result1["success"] is True assert result2["success"] is True - assert ( - result1["drawer_id"] != result2["drawer_id"] - ), "Documents with shared header but different content must have distinct drawer IDs" + assert result1["drawer_id"] != result2["drawer_id"], ( + "Documents with shared header but different content must have distinct drawer IDs" + ) def test_delete_drawer(self, monkeypatch, config, palace_path, seeded_collection, kg): _patch_mcp_server(monkeypatch, config, kg) @@ -2121,9 +2121,9 @@ class TestCacheInvalidation: all_calls = captured["get"] + captured["create"] assert all_calls, "expected get_collection or create_collection to be called" for kwargs in all_calls: - assert ( - "embedding_function" in kwargs - ), f"missing embedding_function= in chromadb call: {kwargs}" + assert "embedding_function" in kwargs, ( + f"missing embedding_function= in chromadb call: {kwargs}" + ) assert kwargs["embedding_function"] is not None # Same expectation on the create=False (cache-miss) reopen path. @@ -2561,9 +2561,9 @@ class TestKGLazyCache: result = mcp_server._canonicalize_kg_path("/some/Path/KG.sqlite3") - assert ( - result == ">" - ), f"expected normcase(realpath(p)) composition, got {result!r}" + assert result == ">", ( + f"expected normcase(realpath(p)) composition, got {result!r}" + ) def test_get_kg_dedupes_symlink_alias_end_to_end(self, tmp_path, monkeypatch): """End-to-end: two ``_get_kg()`` calls via different symlink layers diff --git a/tests/test_mcp_stdio_protection.py b/tests/test_mcp_stdio_protection.py index 8b3731b..7ab35b5 100644 --- a/tests/test_mcp_stdio_protection.py +++ b/tests/test_mcp_stdio_protection.py @@ -78,6 +78,6 @@ def test_mcp_server_no_stdout_noise_on_clean_exit(): capture_output=True, timeout=60, ) - assert ( - proc.stdout == b"" - ), f"stdout must be empty before the first JSON-RPC response, but got: {proc.stdout!r}" + assert proc.stdout == b"", ( + f"stdout must be empty before the first JSON-RPC response, but got: {proc.stdout!r}" + ) diff --git a/tests/test_normalize.py b/tests/test_normalize.py index 2b0f180..f56ff3a 100644 --- a/tests/test_normalize.py +++ b/tests/test_normalize.py @@ -1336,11 +1336,7 @@ class TestStripNoiseRemovesSystemChrome: def test_strips_line_anchored_system_reminder_block(self): text = ( - "> User:\n" - "\n" - "Auto-save reminder...\n" - "\n" - "> Real message." + "> User:\n\nAuto-save reminder...\n\n> Real message." ) out = strip_noise(text) assert "system-reminder" not in out @@ -1350,7 +1346,7 @@ class TestStripNoiseRemovesSystemChrome: def test_strips_system_reminder_with_blockquote_prefix(self): # _messages_to_transcript prefixes lines with "> ", so the line # anchor must also accept that shape. - text = "> User:\n" "> Injected noise\n" "> Real message." + text = "> User:\n> Injected noise\n> Real message." out = strip_noise(text) assert "Injected noise" not in out assert "Real message." in out diff --git a/tests/test_palace_graph_tunnels.py b/tests/test_palace_graph_tunnels.py index 99fccd5..8be8042 100644 --- a/tests/test_palace_graph_tunnels.py +++ b/tests/test_palace_graph_tunnels.py @@ -63,9 +63,9 @@ class TestTunnelStorage: assert file_mode == 0o600, f"tunnels.json mode is {oct(file_mode)}, expected 0o600" parent_mode = stat.S_IMODE(os.stat(tunnel_file.parent).st_mode) - assert ( - parent_mode == 0o700 - ), f"tunnels.json parent dir mode is {oct(parent_mode)}, expected 0o700" + assert parent_mode == 0o700, ( + f"tunnels.json parent dir mode is {oct(parent_mode)}, expected 0o700" + ) class TestExplicitTunnels: diff --git a/tests/test_palace_locks.py b/tests/test_palace_locks.py index df94f16..b4d2fbc 100644 --- a/tests/test_palace_locks.py +++ b/tests/test_palace_locks.py @@ -199,9 +199,9 @@ def test_reentrant_same_thread_passes_through(tmp_path, monkeypatch): child = ctx.Process(target=_try_acquire_expect_busy, args=(palace, result_q)) try: child.start() - assert ( - result_q.get(timeout=10) == "busy" - ), "outer lock should still be held by parent after inner re-entrant exit" + assert result_q.get(timeout=10) == "busy", ( + "outer lock should still be held by parent after inner re-entrant exit" + ) child.join(timeout=5) assert child.exitcode == 0 finally: @@ -267,9 +267,9 @@ def test_lock_failure_message_names_holder(tmp_path, monkeypatch): pytest.fail("second acquire of same palace should have raised") msg = str(excinfo.value) - assert ( - f"PID {holder_pid}" in msg - ), f"lock-failure message must name the holder PID; got: {msg!r}" + assert f"PID {holder_pid}" in msg, ( + f"lock-failure message must name the holder PID; got: {msg!r}" + ) finally: open(release, "w").close() holder.join(timeout=5) diff --git a/tests/test_readme_claims.py b/tests/test_readme_claims.py index 7d4754a..f096b3d 100644 --- a/tests/test_readme_claims.py +++ b/tests/test_readme_claims.py @@ -597,13 +597,13 @@ class TestBackendAbstraction: """Claim: pluggable backends. backends/base.py must define an abstract base class.""" path = MEMPALACE_PKG / "backends" / "base.py" - assert ( - path.is_file() - ), "mempalace/backends/base.py does not exist. Backend abstraction layer is missing." + assert path.is_file(), ( + "mempalace/backends/base.py does not exist. Backend abstraction layer is missing." + ) src = _read(path) - assert ( - "ABC" in src or "abstractmethod" in src - ), "backends/base.py does not define an abstract base class." + assert "ABC" in src or "abstractmethod" in src, ( + "backends/base.py does not define an abstract base class." + ) def test_backends_chroma_exists(self): """Claim: ChromaDB backend implementation. @@ -611,9 +611,9 @@ class TestBackendAbstraction: path = MEMPALACE_PKG / "backends" / "chroma.py" assert path.is_file(), "mempalace/backends/chroma.py does not exist." src = _read(path) - assert ( - "BaseCollection" in src or "base" in src - ), "backends/chroma.py does not reference the base class." + assert "BaseCollection" in src or "base" in src, ( + "backends/chroma.py does not reference the base class." + ) def test_backends_importable(self): """Both backend modules should be importable.""" @@ -650,9 +650,9 @@ class TestI18n: def test_english_baseline_exists(self): """en.json must exist as the baseline language file.""" path = MEMPALACE_PKG / "i18n" / "en.json" - assert ( - path.is_file() - ), "mempalace/i18n/en.json does not exist. English baseline is required." + assert path.is_file(), ( + "mempalace/i18n/en.json does not exist. English baseline is required." + ) # --------------------------------------------------------------------------- @@ -737,9 +737,9 @@ class TestReadmeToolCountConsistency: counts = re.findall(r"(\d+)\s+tools", readme) if len(counts) > 1: unique = set(counts) - assert ( - len(unique) == 1 - ), f"README mentions different tool counts: {counts}. All occurrences must agree." + assert len(unique) == 1, ( + f"README mentions different tool counts: {counts}. All occurrences must agree." + ) # --------------------------------------------------------------------------- diff --git a/tests/test_repair.py b/tests/test_repair.py index d8dfa94..acbf31d 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -1381,9 +1381,9 @@ def test_rebuild_index_runs_sqlite_preflight_before_chromadb_open(tmp_path, caps PAGE = 4096 CORRUPT_BYTES = 16384 # 4 pages HEADER_GUARD = PAGE * 2 # leave header + root pages intact - assert ( - pre_size >= HEADER_GUARD + CORRUPT_BYTES - ), f"sqlite db too small to mangle without truncating: {pre_size} bytes" + assert pre_size >= HEADER_GUARD + CORRUPT_BYTES, ( + f"sqlite db too small to mangle without truncating: {pre_size} bytes" + ) # Round (pre_size - CORRUPT_BYTES) down to a page boundary so we # mangle whole pages. Cap at offset 40960 (page 10) for stable # diagnostics across SQLite versions that may grow the file. diff --git a/tests/test_save_hook_mines.py b/tests/test_save_hook_mines.py index e11234a..68f04e9 100644 --- a/tests/test_save_hook_mines.py +++ b/tests/test_save_hook_mines.py @@ -33,12 +33,12 @@ class TestSaveHookAutoMines: # `--mode convos` so the convo miner runs (not the projects miner). assert "TRANSCRIPT_PATH" in src, "hook must read transcript_path" assert "mempalace mine" in src, "hook must invoke `mempalace mine`" - assert ( - 'dirname "$TRANSCRIPT_PATH"' in src - ), "hook must mine the transcript's parent directory" - assert ( - "--mode convos" in src - ), "transcript mine must use --mode convos, not the projects miner" + assert 'dirname "$TRANSCRIPT_PATH"' in src, ( + "hook must mine the transcript's parent directory" + ) + assert "--mode convos" in src, ( + "transcript mine must use --mode convos, not the projects miner" + ) def test_mempal_dir_default_not_empty(self): """If MEMPAL_DIR is still used, it should have a sensible default, @@ -86,16 +86,16 @@ class TestShellHookTranscriptValidation: def test_save_hook_defines_and_uses_validator(self): src = self._strip_comments(self._hook_src("mempal_save_hook.sh")) assert "is_valid_transcript_path() {" in src, "validator function must be defined" - assert ( - 'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src - ), "validator must be invoked against TRANSCRIPT_PATH before mining" + assert 'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src, ( + "validator must be invoked against TRANSCRIPT_PATH before mining" + ) def test_precompact_hook_defines_and_uses_validator(self): src = self._strip_comments(self._hook_src("mempal_precompact_hook.sh")) assert "is_valid_transcript_path() {" in src, "validator function must be defined" - assert ( - 'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src - ), "validator must be invoked against TRANSCRIPT_PATH before mining" + assert 'is_valid_transcript_path "$TRANSCRIPT_PATH"' in src, ( + "validator must be invoked against TRANSCRIPT_PATH before mining" + ) @pytest.mark.skipif( sys.platform == "win32", @@ -112,9 +112,7 @@ class TestShellHookTranscriptValidation: end = src.index("\n}\n", start) + 2 func_src = src[start:end] script = tmp_path / "v.sh" - script.write_text( - f"{func_src}\n" 'is_valid_transcript_path "$1" && echo OK || echo NO\n' - ) + script.write_text(f'{func_src}\nis_valid_transcript_path "$1" && echo OK || echo NO\n') def run(arg: str) -> str: return subprocess.run( diff --git a/tests/test_searcher.py b/tests/test_searcher.py index ccea063..721bb11 100644 --- a/tests/test_searcher.py +++ b/tests/test_searcher.py @@ -184,12 +184,11 @@ class TestSearchMemories: # Invariants on every hit. for h in hits: - assert ( - 0.0 <= h["similarity"] <= 1.0 - ), f"similarity out of range: {h['similarity']} for {h['source_file']}" + assert 0.0 <= h["similarity"] <= 1.0, ( + f"similarity out of range: {h['similarity']} for {h['source_file']}" + ) assert 0.0 <= h["effective_distance"] <= 2.0, ( - f"effective_distance out of range: {h['effective_distance']} " - f"for {h['source_file']}" + f"effective_distance out of range: {h['effective_distance']} for {h['source_file']}" ) # With the clamp, the closet-boosted a.md still ranks ahead of b.md — @@ -338,9 +337,9 @@ class TestSearchCLI: captured = capsys.readouterr() first_block, _, _ = captured.out.partition("[2]") # Lexical match must rank first - assert ( - "b.md" in first_block - ), f"expected lexical match 'b.md' at rank 1, got:\n{captured.out}" + assert "b.md" in first_block, ( + f"expected lexical match 'b.md' at rank 1, got:\n{captured.out}" + ) # Non-zero bm25 reported assert "bm25=" in first_block assert "bm25=0.0" not in first_block diff --git a/tests/test_sweeper.py b/tests/test_sweeper.py index 983724a..eef9c6a 100644 --- a/tests/test_sweeper.py +++ b/tests/test_sweeper.py @@ -97,9 +97,9 @@ class TestSweeperParsing: records = list(parse_claude_jsonl(str(mock_claude_jsonl))) assistant_rec = records[1] assert assistant_rec["role"] == "assistant" - assert ( - "Paris" in assistant_rec["content"] - ), f"Assistant content blocks must be flattened to text; got: {assistant_rec['content']!r}" + assert "Paris" in assistant_rec["content"], ( + f"Assistant content blocks must be flattened to text; got: {assistant_rec['content']!r}" + ) def test_parse_preserves_tool_blocks_verbatim(self, tmp_path): """Per the design principle "verbatim always", tool_use and diff --git a/tests/test_sync.py b/tests/test_sync.py index ea17040..d32db68 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -444,9 +444,9 @@ class TestSyncPalace: # Allow-list — params must be exactly the documented audit shape so # any future leak (source_file, content, ID lists, etc.) trips a # test failure rather than slipping through a deny-list. - assert set(params.keys()) <= { - "first_id" - }, f"WAL params drifted from the audit allow-list: {params.keys()}" + assert set(params.keys()) <= {"first_id"}, ( + f"WAL params drifted from the audit allow-list: {params.keys()}" + ) def test_registry_sentinels_preserved_on_apply(self, tmp_dir, palace_path): """F2 regression: convo miner `_reg_*` sentinels must survive sync apply. @@ -567,9 +567,9 @@ class TestSyncPalace: inner_resolved = inner.resolve(strict=False) outer_resolved = outer.resolve(strict=False) assert inner_resolved in roots, f"expected inner in roots, got {roots}" - assert ( - outer_resolved not in roots - ), f"deepest should win exclusively: roots={roots}, outer leaked" + assert outer_resolved not in roots, ( + f"deepest should win exclusively: roots={roots}, outer leaked" + ) def test_apply_with_empty_project_dirs_raises(self, palace_path): """Round-2 P1: `project_dirs=[]` (empty list) with apply must raise, @@ -608,9 +608,9 @@ class TestSyncPalace: project_dirs=[synced_world["repo_path"]], dry_run=False, ) - assert any( - "Closet purge skipped" in record.getMessage() for record in caplog.records - ), f"expected closet-skip warning, got: {[r.getMessage() for r in caplog.records]}" + assert any("Closet purge skipped" in record.getMessage() for record in caplog.records), ( + f"expected closet-skip warning, got: {[r.getMessage() for r in caplog.records]}" + ) def test_metadata_cache_cleared_on_exception(self, monkeypatch, config, synced_world, kg): """F9 regression: tool_sync's try/finally must clear `_metadata_cache` @@ -651,9 +651,9 @@ class TestSyncPalace: assert result.get("success") is False assert "simulated" in result.get("error", "") - assert ( - mcp_server._metadata_cache is None - ), "F9: cache must be cleared even when sync_palace raises" + assert mcp_server._metadata_cache is None, ( + "F9: cache must be cleared even when sync_palace raises" + ) def test_sync_report_keys_stable(self, synced_world): """Regression: SyncReport schema must not silently drop a field.""" @@ -946,9 +946,9 @@ class TestSyncPalace: wing="demo", dry_run=True, ) - assert ( - report["gitignored"] == 1 - ), f"symmetric resolve broken: drawer mis-bucketed; report={report}" + assert report["gitignored"] == 1, ( + f"symmetric resolve broken: drawer mis-bucketed; report={report}" + ) assert report["out_of_scope"] == 0 def test_classification_cache_avoids_redundant_disk_hits( @@ -1005,9 +1005,9 @@ class TestSyncPalace: ) assert report["scanned"] == 5 assert report["gitignored"] == 5 - assert ( - call_count["n"] == 1 - ), f"cache miss: expected 1 _classify_drawer call (4 cache hits), got {call_count['n']}" + assert call_count["n"] == 1, ( + f"cache miss: expected 1 _classify_drawer call (4 cache hits), got {call_count['n']}" + ) def test_closet_batch_purge_single_call(self, synced_world, monkeypatch): """Batched $in closet purge: one delete() call across all removable @@ -1074,16 +1074,16 @@ class TestSyncPalace: str(repo_path / "deleted.py"), } expected = len(seeded_sources & set(report["by_source"].keys())) - assert ( - report["removed_closets"] == expected - ), f"removed_closets ({report['removed_closets']}) != |seeded ∩ removable| ({expected})" + assert report["removed_closets"] == expected, ( + f"removed_closets ({report['removed_closets']}) != |seeded ∩ removable| ({expected})" + ) assert "wrapper" in captured, "get_closets_collection patch not invoked" - assert ( - captured["wrapper"].delete_calls == 1 - ), f"expected one batch delete call, got {captured['wrapper'].delete_calls}" - assert ( - captured["wrapper"].get_calls == 1 - ), f"expected one batch get call, got {captured['wrapper'].get_calls}" + assert captured["wrapper"].delete_calls == 1, ( + f"expected one batch delete call, got {captured['wrapper'].delete_calls}" + ) + assert captured["wrapper"].get_calls == 1, ( + f"expected one batch get call, got {captured['wrapper'].get_calls}" + ) def test_registry_check_runs_before_cache_lookup(self, tmp_dir, palace_path): """A non-registry drawer with the same source_file must NOT poison @@ -1148,9 +1148,9 @@ class TestSyncPalace: finally: del client assert "a_regular" not in survivors - assert ( - "_reg_zzz_sentinel" in survivors - ), "registry sentinel was incorrectly pruned via cached non-registry verdict" + assert "_reg_zzz_sentinel" in survivors, ( + "registry sentinel was incorrectly pruned via cached non-registry verdict" + ) def test_normalize_project_dirs_sort_stable_on_equal_length(self): """`_normalize_project_dirs` must sort by `(-len, str)` so equal-length diff --git a/tools/render_jsonl.py b/tools/render_jsonl.py index 2bec0da..791ce66 100755 --- a/tools/render_jsonl.py +++ b/tools/render_jsonl.py @@ -70,7 +70,7 @@ def main(): ] out.write("\n".join(header)) for ts, role, text in turns: - out.write(f"\n[{ts}] {role.upper()}\n{text}\n\n{'-'*72}\n") + out.write(f"\n[{ts}] {role.upper()}\n{text}\n\n{'-' * 72}\n") if out is not sys.stdout: out.close() print(f"Wrote {len(turns)} turns to {sys.argv[2]}") From 283ef0336199ded415404516fcf1b938f7c00b45 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Mon, 18 May 2026 00:08:17 -0300 Subject: [PATCH 58/64] ci(lint): pin ruff in pre-commit + uv.lock too (#1541 review) Addresses Copilot review: the ruff pin was incomplete. - .pre-commit-config.yaml stayed on ruff-pre-commit v0.4.10, so contributors running pre-commit would reintroduce the exact 0.4-vs-0.5 formatter drift this PR removes. Bumped rev to v0.15.9 and rewrote the lock-step comment to point at pyproject as the source of truth. - uv.lock still constrained dev ruff at >=0.4.0, so `uv sync --extra dev` (the documented setup) would not honor the new exact pin. Regenerated; the dev specifier is now ==0.15.9 in both lock entries. ruff check/format still pass; no formatting delta from these files. --- .pre-commit-config.yaml | 9 +++++---- uv.lock | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8f94c0b..b413e1c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,9 +1,10 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit - # Keep in lock-step with the ruff version pinned in .github/workflows/ci.yml - # (>=0.4.0,<0.5). Using a newer rev here produces a different formatter - # output than CI and breaks `ruff format --check` in the lint job. - rev: v0.4.10 + # Keep this rev in lock-step with the exact ruff pin in pyproject.toml + # ([project.optional-dependencies].dev / [dependency-groups].dev) and + # .github/workflows/ci.yml. A different ruff here produces different + # formatter output than CI and breaks `ruff format --check` in lint. + rev: v0.15.9 hooks: - id: ruff args: [--fix] diff --git a/uv.lock b/uv.lock index 2c96d67..5117685 100644 --- a/uv.lock +++ b/uv.lock @@ -1224,7 +1224,7 @@ requires-dist = [ { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" }, { name = "pyyaml", specifier = ">=6.0,<7" }, - { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.4.0" }, + { name = "ruff", marker = "extra == 'dev'", specifier = "==0.15.9" }, { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.0" }, ] provides-extras = ["dev", "spellcheck", "gpu", "dml", "coreml"] @@ -1234,7 +1234,7 @@ dev = [ { name = "psutil", specifier = ">=5.9" }, { name = "pytest", specifier = ">=7.0" }, { name = "pytest-cov", specifier = ">=4.0" }, - { name = "ruff", specifier = ">=0.4.0" }, + { name = "ruff", specifier = "==0.15.9" }, ] [[package]] From e811b6d10a28fa5bca31e34e35c8c8ce2d9a68f6 Mon Sep 17 00:00:00 2001 From: Ivan Dergachev Date: Mon, 11 May 2026 13:54:57 +0400 Subject: [PATCH 59/64] fix: avoid false HNSW metadata quarantine --- mempalace/backends/chroma.py | 70 +++++++++++++++++++++++++++++++----- tests/test_backends.py | 53 +++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 8 deletions(-) diff --git a/mempalace/backends/chroma.py b/mempalace/backends/chroma.py index 387a2b9..980f2e8 100644 --- a/mempalace/backends/chroma.py +++ b/mempalace/backends/chroma.py @@ -671,20 +671,59 @@ def _valid_dimensionality(value: object) -> bool: return isinstance(value, Integral) and not isinstance(value, bool) and int(value) > 0 -def _persisted_metadata_fields(obj: object) -> tuple[object, object]: +def _persisted_metadata_value(obj: object, name: str) -> object: if isinstance(obj, dict): - return obj.get("dimensionality"), obj.get("id_to_label") - return getattr(obj, "dimensionality", None), getattr(obj, "id_to_label", None) + return obj.get(name) + return getattr(obj, name, None) + + +def _persisted_metadata_fields(obj: object) -> tuple[object, object]: + return _persisted_metadata_value(obj, "dimensionality"), _persisted_metadata_value( + obj, "id_to_label" + ) + + +def _missing_dimensionality_appears_recoverable( + persisted: object, id_to_label: dict, seg_dir: str +) -> bool: + total = _persisted_metadata_value(persisted, "total_elements_added") + label_to_id = _persisted_metadata_value(persisted, "label_to_id") + data_path = os.path.join(seg_dir, "data_level0.bin") + link_path = os.path.join(seg_dir, "link_lists.bin") + + if not isinstance(total, Integral) or isinstance(total, bool): + return False + if not isinstance(label_to_id, dict): + return False + try: + if not ( + os.path.isfile(data_path) + and os.path.isfile(link_path) + and os.path.getsize(data_path) > _HNSW_MISSING_METADATA_DATA_FLOOR + ): + return False + except OSError: + return False + if not _hnsw_payload_appears_sane(seg_dir): + return False + + label_count = len(id_to_label) + if int(total) != label_count or len(label_to_id) != label_count: + return False + try: + return all(label_to_id.get(label) == item_id for item_id, label in id_to_label.items()) + except TypeError: + return False def quarantine_invalid_hnsw_metadata(palace_path: str) -> list[str]: """Quarantine segment dirs whose ``index_metadata.pickle`` is unreadable or invalid. Chroma's persisted HNSW metadata is untrusted disk state. If a segment has - labels but no valid positive dimensionality, current Chroma versions can - accept the pickle and crash later in the Rust loader. We rename the entire - segment out of the way before ``PersistentClient`` opens so Chroma can - rebuild cleanly instead of touching known-bad metadata. + labels but invalid or partial metadata, current Chroma versions can accept + the pickle and crash later in the Rust loader. We rename the entire segment + out of the way before ``PersistentClient`` opens so Chroma can rebuild + cleanly instead of touching known-bad metadata. """ try: entries = os.listdir(palace_path) @@ -735,7 +774,22 @@ def quarantine_invalid_hnsw_metadata(palace_path: str) -> list[str]: reason = f"invalid id_to_label type {type(id_to_label).__name__}" else: has_labels = bool(id_to_label) - if has_labels and not _valid_dimensionality(dimensionality): + if ( + has_labels + and dimensionality is None + and not _missing_dimensionality_appears_recoverable( + persisted, id_to_label, seg_dir + ) + ): + reason = ( + "labels present but dimensionality is missing or invalid " + f"({dimensionality!r})" + ) + elif ( + has_labels + and dimensionality is not None + and not _valid_dimensionality(dimensionality) + ): reason = ( "labels present but dimensionality is missing or invalid " f"({dimensionality!r})" diff --git a/tests/test_backends.py b/tests/test_backends.py index 1fc8eab..0ee10d3 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -1047,6 +1047,59 @@ def test_quarantine_invalid_hnsw_metadata_renames_missing_dimensionality(tmp_pat assert not seg.exists() +def test_quarantine_invalid_hnsw_metadata_keeps_consistent_missing_dimensionality(tmp_path): + palace = tmp_path / "palace" + palace.mkdir() + seg = palace / "abcd-1234-5678" + seg.mkdir() + (seg / "data_level0.bin").write_bytes(b"x" * 2048) + (seg / "link_lists.bin").write_bytes(b"x" * 128) + with open(seg / "index_metadata.pickle", "wb") as f: + pickle.dump( + { + "dimensionality": None, + "total_elements_added": 2, + "max_seq_id": None, + "id_to_label": {"a": 1, "b": 2}, + "label_to_id": {1: "a", 2: "b"}, + "id_to_seq_id": {}, + }, + f, + ) + + moved = quarantine_invalid_hnsw_metadata(str(palace)) + + assert moved == [] + assert seg.exists() + + +def test_quarantine_invalid_hnsw_metadata_renames_mismatched_missing_dimensionality(tmp_path): + palace = tmp_path / "palace" + palace.mkdir() + seg = palace / "abcd-1234-5678" + seg.mkdir() + (seg / "data_level0.bin").write_bytes(b"x" * 2048) + (seg / "link_lists.bin").write_bytes(b"x" * 128) + with open(seg / "index_metadata.pickle", "wb") as f: + pickle.dump( + { + "dimensionality": None, + "total_elements_added": 2, + "max_seq_id": None, + "id_to_label": {"a": 1, "b": 2}, + "label_to_id": {1: "b", 2: "a"}, + "id_to_seq_id": {}, + }, + f, + ) + + moved = quarantine_invalid_hnsw_metadata(str(palace)) + + assert len(moved) == 1 + assert ".corrupt-" in moved[0] + assert not seg.exists() + + def test_quarantine_invalid_hnsw_metadata_allows_uninitialized_segment(tmp_path): palace = tmp_path / "palace" palace.mkdir() From 3da27d3c7e82cfc66f8da7098850115025928db7 Mon Sep 17 00:00:00 2001 From: William Blair Date: Fri, 15 May 2026 10:56:14 -0400 Subject: [PATCH 60/64] fix: VACUUM + FTS5 rebuild after repair to reclaim SQLite space Repeated `repair --yes` runs leave freed SQLite pages unreclaimed and can corrupt the FTS5 inverted index. This patch adds `_vacuum_and_rebuild_fts5()`, called at the end of `rebuild_index()`, which: 1. Closes all chroma handles (releases PersistentClient's sqlite lock). 2. Rebuilds the FTS5 index via the built-in content-table DDL trick. 3. Runs VACUUM (requires autocommit / isolation_level=None) to reclaim the freed pages. The function is a no-op when chroma.sqlite3 is absent or the FTS5 table doesn't exist, so it is safe on every supported backend. Four new tests cover the happy path, missing FTS5 table, missing file, and call ordering (close must precede vacuum). Closes #1516 Closes #1517 --- mempalace/repair.py | 38 +++++++++++++++++++ tests/test_repair.py | 89 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+) diff --git a/mempalace/repair.py b/mempalace/repair.py index 778a354..7a4a28c 100644 --- a/mempalace/repair.py +++ b/mempalace/repair.py @@ -35,6 +35,7 @@ import shutil import sqlite3 import time from collections import defaultdict +from contextlib import closing from datetime import datetime import re from typing import Callable, Iterator, Optional @@ -680,6 +681,40 @@ class _DefaultProgress: return f" (elapsed {_format_eta(elapsed)}, rate {rate:.1f}/s, ETA {_format_eta(eta)})" +def _vacuum_and_rebuild_fts5(palace_path: str, progress=print) -> None: + """VACUUM the palace SQLite file and rebuild the FTS5 index if present. + + Repeated ``repair --yes`` runs delete and recreate the drawers collection, + leaving freed SQLite pages unreclaimable without an explicit VACUUM. The + FTS5 virtual table (``embedding_fulltext_search``) can also become + internally inconsistent after multiple collection deletes; the rebuild + command fixes it atomically without touching any row data. + + Failures are non-fatal: a warning is printed and the caller continues. + The repair itself succeeded at this point — VACUUM/FTS5 are best-effort + cleanup, not correctness requirements. + """ + sqlite_path = os.path.join(palace_path, "chroma.sqlite3") + if not os.path.exists(sqlite_path): + return + try: + with closing(sqlite3.connect(sqlite_path, isolation_level=None)) as conn: + tables = { + r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'") + } + if "embedding_fulltext_search" in tables: + conn.execute( + "INSERT INTO embedding_fulltext_search" + "(embedding_fulltext_search) VALUES('rebuild')" + ) + conn.commit() + progress(" FTS5 index rebuilt.") + conn.execute("VACUUM") + progress(" SQLite VACUUM complete.") + except Exception as exc: + progress(f" Warning: post-repair cleanup failed (non-fatal): {exc}") + + def rebuild_index( palace_path=None, confirm_truncation_ok: bool = False, @@ -813,6 +848,9 @@ def rebuild_index( print(" Live collection was not replaced; leaving the original palace untouched.") raise + _close_chroma_handles(palace_path, backend=backend) + _vacuum_and_rebuild_fts5(palace_path, progress=progress) + print(f"\n Repair complete. {filed} drawers rebuilt.") print(" HNSW index is now clean with cosine distance metric.") print(f"\n{'=' * 55}\n") diff --git a/tests/test_repair.py b/tests/test_repair.py index acbf31d..981351e 100644 --- a/tests/test_repair.py +++ b/tests/test_repair.py @@ -1855,3 +1855,92 @@ def test_rebuild_from_sqlite_honors_configured_drawer_collection_name(tmp_path, ) except Exception: pass # Expected: collection wasn't created. + + +# ── _vacuum_and_rebuild_fts5 ────────────────────────────────────────── + + +def test_vacuum_and_rebuild_fts5_vacuums_and_rebuilds(tmp_path): + """VACUUM runs and FTS5 index is rebuilt when the table is present.""" + sqlite_path = tmp_path / "chroma.sqlite3" + with closing(sqlite3.connect(str(sqlite_path))) as conn: + conn.execute( + "CREATE VIRTUAL TABLE embedding_fulltext_search" + " USING fts5(string_value, tokenize='unicode61')" + ) + conn.execute("INSERT INTO embedding_fulltext_search(string_value) VALUES('hello world')") + conn.commit() + + repair._vacuum_and_rebuild_fts5(str(tmp_path)) + + with closing(sqlite3.connect(str(sqlite_path))) as conn: + result = conn.execute("PRAGMA integrity_check").fetchall() + assert result == [("ok",)] + + +def test_vacuum_and_rebuild_fts5_no_fts5_table(tmp_path): + """VACUUM runs without error when embedding_fulltext_search is absent.""" + sqlite_path = tmp_path / "chroma.sqlite3" + with closing(sqlite3.connect(str(sqlite_path))) as conn: + conn.execute("CREATE TABLE dummy (id INTEGER PRIMARY KEY)") + conn.commit() + + # Must not raise even without the FTS5 table. + repair._vacuum_and_rebuild_fts5(str(tmp_path)) + + with closing(sqlite3.connect(str(sqlite_path))) as conn: + result = conn.execute("PRAGMA integrity_check").fetchall() + assert result == [("ok",)] + + +def test_vacuum_and_rebuild_fts5_missing_sqlite(tmp_path): + """Silently skips when chroma.sqlite3 does not exist.""" + repair._vacuum_and_rebuild_fts5(str(tmp_path)) # no file — must not raise + + +@patch("mempalace.repair.shutil") +@patch("mempalace.repair.ChromaBackend") +def test_rebuild_index_calls_vacuum(mock_backend_cls, mock_shutil, tmp_path): + """rebuild_index closes chroma handles then calls _vacuum_and_rebuild_fts5. + + ChromaDB's PersistentClient holds an open connection to chroma.sqlite3; + VACUUM requires an exclusive lock so _close_chroma_handles must be called + before _vacuum_and_rebuild_fts5. + """ + sqlite_path = tmp_path / "chroma.sqlite3" + with closing(sqlite3.connect(str(sqlite_path))) as conn: + conn.execute("CREATE TABLE dummy(id INTEGER PRIMARY KEY)") + conn.commit() + + mock_col = MagicMock() + mock_col.count.return_value = 1 + mock_col.get.return_value = { + "ids": ["id1"], + "documents": ["doc1"], + "metadatas": [{"wing": "a"}], + } + mock_new_col = MagicMock() + mock_new_col.count.return_value = 1 + mock_temp_col = MagicMock() + mock_temp_col.count.return_value = 1 + mock_backend = _install_mock_backend(mock_backend_cls, mock_col) + mock_backend.create_collection.side_effect = [mock_temp_col, mock_new_col] + + call_order = [] + with ( + patch.object( + repair, "_close_chroma_handles", side_effect=lambda *a, **kw: call_order.append("close") + ) as mock_close, + patch.object( + repair, + "_vacuum_and_rebuild_fts5", + side_effect=lambda *a, **kw: call_order.append("vacuum"), + ) as mock_vacuum, + ): + repair.rebuild_index(palace_path=str(tmp_path)) + mock_close.assert_called_once() + mock_vacuum.assert_called_once() + assert call_order == ["close", "vacuum"], "backend must be closed before VACUUM" + args, kwargs = mock_vacuum.call_args + assert args[0] == str(tmp_path) + assert "progress" in kwargs From 3e92719710b38db28a15551308dd9836832e4d10 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Mon, 18 May 2026 17:25:09 -0300 Subject: [PATCH 61/64] fix(mcp): surface create_tunnel ValueError instead of masking it (#1473) tool_create_tunnel sanitized names inside a try/except ValueError but called create_tunnel() *outside* it, so any ValueError create_tunnel raises (empty/non-string endpoints today, room-existence checks once #1469 lands) escaped and the MCP framework wrapped it as the opaque 'Internal tool error'. Wrap the create_tunnel() call in the same try/except and return {"error": str(e)}, mirroring sibling tools (tool_add_drawer, tool_list_tunnels). Adds a regression test that monkeypatches create_tunnel to raise and asserts the message is surfaced verbatim. Closes #1473 --- mempalace/mcp_server.py | 25 ++++++++++++++++--------- tests/test_mcp_server.py | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index 67d4d7b..fb93fc1 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -1033,15 +1033,22 @@ def tool_create_tunnel( target_room = sanitize_name(target_room, "target_room") except ValueError as e: return {"error": str(e)} - return create_tunnel( - source_wing, - source_room, - target_wing, - target_room, - label=label, - source_drawer_id=source_drawer_id, - target_drawer_id=target_drawer_id, - ) + # create_tunnel raises ValueError for invalid/missing endpoints + # (empty/non-string names, and room-existence checks). Surface the + # real reason instead of letting it escape and be wrapped as the + # opaque "Internal tool error" (#1473), mirroring sibling tools. + try: + return create_tunnel( + source_wing, + source_room, + target_wing, + target_room, + label=label, + source_drawer_id=source_drawer_id, + target_drawer_id=target_drawer_id, + ) + except ValueError as e: + return {"error": str(e)} def tool_list_tunnels(wing: str = None): diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 4a1aae2..ecd60af 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1386,6 +1386,28 @@ class TestWriteTools: assert len(mcp_server.tool_list_tunnels(wing="my-wing")) == 1 assert len(mcp_server.tool_list_tunnels(wing="my_wing")) == 1 + def test_tool_create_tunnel_surfaces_value_error(self, monkeypatch): + """Regression for #1473: a ValueError from create_tunnel (e.g. a + missing room) must be returned to the caller as a clear error, + not escape and get wrapped as the opaque 'Internal tool error'.""" + from mempalace import mcp_server + + msg = "Target room 'does-not-exist-probe' does not exist in wing 'wing_minerva'" + + def _raise(*args, **kwargs): + raise ValueError(msg) + + monkeypatch.setattr(mcp_server, "create_tunnel", _raise) + + result = mcp_server.tool_create_tunnel( + source_wing="wing_minerva", + source_room="fx-invariants", + target_wing="wing_minerva", + target_room="does-not-exist-probe", + ) + + assert result == {"error": msg} + # ── KG Tools ──────────────────────────────────────────────────────────── From 426d164df46be993b84bde56162ee3a3fe2b1f35 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Mon, 18 May 2026 17:28:50 -0300 Subject: [PATCH 62/64] test(hooks): isolate test_hooks_cli from test_cli side effect (#1510) Nine save/log/precompact tests in test_hooks_cli.py passed only because test_cli.py (alphabetically earlier) created ~/.mempalace in the session tmp HOME as a side effect, satisfying the _palace_root_exists() kill-switch. Run in isolation they short-circuited and failed (9 failed, 80 passed, 1 skipped). Add a module autouse fixture that points PALACE_ROOT/STATE_DIR at a per-test palace root that exists, so every test is robust standalone and future tests don't inherit the trap. Kill-switch tests that need the absent path call _redirect_palace_root after the fixture; monkeypatch last-write-wins keeps their absent/file root and teardown restores the real module value. Isolation: pytest tests/test_hooks_cli.py -> 100 passed, 1 skipped. Ordering preserved: test_cli + test_hooks_cli -> 165 passed. Closes #1510 --- tests/test_hooks_cli.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 234bef2..e4309fc 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -31,6 +31,31 @@ from mempalace.hooks_cli import ( ) +@pytest.fixture(autouse=True) +def _isolated_existing_palace_root(monkeypatch, tmp_path): + """Give every test an isolated, *existing* PALACE_ROOT/STATE_DIR. + + Regression for #1510: nine save / log / precompact tests assumed + ``~/.mempalace`` existed and only passed in the full suite because an + earlier test file (``test_cli.py``) created it as a side effect, so + the ``_palace_root_exists()`` kill-switch was satisfied. Run in + isolation they short-circuited and failed. + + Defaulting every test to a per-test palace root that exists makes + them robust on their own and protects future tests from the same + trap. Tests that exercise the absent-root kill-switch path call + ``_redirect_palace_root`` (or set their own PALACE_ROOT) *after* this + fixture; ``monkeypatch``'s last-write-wins means they keep their + absent/file root and teardown still restores the real module value. + """ + root = tmp_path / ".mempalace" + root.mkdir(exist_ok=True) + monkeypatch.setattr(hooks_cli_mod, "PALACE_ROOT", root) + monkeypatch.setattr(hooks_cli_mod, "STATE_DIR", root / "hook_state") + monkeypatch.setattr(hooks_cli_mod, "_state_dir_initialized", False) + return root + + # --- _mempalace_python --- From 02c05aaba6bd765aa0b255af274168973bbce02a Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Mon, 18 May 2026 17:39:10 -0300 Subject: [PATCH 63/64] refactor(mcp): merge the two ValueError guards in tool_create_tunnel Review feedback: the sanitize_name and create_tunnel calls both raise ValueError and returned the identical {"error": str(e)} shape, so the second try/except was redundant nesting. Fold create_tunnel into the single guard; behavior and the #1473 regression test are unchanged. --- mempalace/mcp_server.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/mempalace/mcp_server.py b/mempalace/mcp_server.py index fb93fc1..41cf9c0 100644 --- a/mempalace/mcp_server.py +++ b/mempalace/mcp_server.py @@ -1026,18 +1026,16 @@ def tool_create_tunnel( Example: an API design discussion in project_api connects to the database schema in project_database. """ + # sanitize_name and create_tunnel both raise ValueError for invalid or + # missing endpoints (empty/non-string names, and create_tunnel's + # room-existence checks). Catch both so the real reason is surfaced + # instead of escaping and being wrapped as the opaque "Internal tool + # error" (#1473), mirroring sibling tools. try: source_wing = sanitize_name(source_wing, "source_wing") source_room = sanitize_name(source_room, "source_room") target_wing = sanitize_name(target_wing, "target_wing") target_room = sanitize_name(target_room, "target_room") - except ValueError as e: - return {"error": str(e)} - # create_tunnel raises ValueError for invalid/missing endpoints - # (empty/non-string names, and room-existence checks). Surface the - # real reason instead of letting it escape and be wrapped as the - # opaque "Internal tool error" (#1473), mirroring sibling tools. - try: return create_tunnel( source_wing, source_room, From 90fece7628941e27474241b8cfa0a65280d02f67 Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Mon, 18 May 2026 17:39:12 -0300 Subject: [PATCH 64/64] test(hooks): also isolate _MINE_PID_DIR + create the state dir (#1510) Review feedback: _MINE_PID_DIR is derived from STATE_DIR at module import (hooks_cli.py:277), so patching STATE_DIR alone left mine-spawning tests writing PID files under the import-time location instead of the per-test root. Patch _MINE_PID_DIR too, and create the state dir so the fixture's 'existing' docstring is accurate. Isolation still 100 passed/1 skipped; ordering still 165 passed. --- tests/test_hooks_cli.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index e4309fc..8062c6a 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -43,15 +43,23 @@ def _isolated_existing_palace_root(monkeypatch, tmp_path): Defaulting every test to a per-test palace root that exists makes them robust on their own and protects future tests from the same - trap. Tests that exercise the absent-root kill-switch path call + trap. ``_MINE_PID_DIR`` is patched too: it is derived from + ``STATE_DIR`` *at module import* (hooks_cli.py:277), so patching + ``STATE_DIR`` alone would leave mine-spawning tests writing PID files + under the import-time location instead of the per-test root. The + state dir is created so the docstring's "existing" promise holds. + + Tests that exercise the absent-root kill-switch path call ``_redirect_palace_root`` (or set their own PALACE_ROOT) *after* this fixture; ``monkeypatch``'s last-write-wins means they keep their absent/file root and teardown still restores the real module value. """ root = tmp_path / ".mempalace" - root.mkdir(exist_ok=True) + state_dir = root / "hook_state" + state_dir.mkdir(parents=True, exist_ok=True) monkeypatch.setattr(hooks_cli_mod, "PALACE_ROOT", root) - monkeypatch.setattr(hooks_cli_mod, "STATE_DIR", root / "hook_state") + monkeypatch.setattr(hooks_cli_mod, "STATE_DIR", state_dir) + monkeypatch.setattr(hooks_cli_mod, "_MINE_PID_DIR", state_dir / "mine_pids") monkeypatch.setattr(hooks_cli_mod, "_state_dir_initialized", False) return root