Merge pull request #2145 from mvalentsev/fix/repair-legacy-dry-run

fix(repair): honor --dry-run in the default mode (#2144)
This commit is contained in:
Igor Lins e Silva
2026-08-07 09:22:57 -03:00
committed by GitHub
6 changed files with 592 additions and 16 deletions
+1
View File
@@ -27,6 +27,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
- **Chroma HNSW write defaults match chromadb** (`batch_size=100` / `sync_threshold=1000`) instead of the old 2/2 bloat guard that rewrote segments thousands of times on large mines. (#2107, #2106)
- **Repair and recovery are safer under contention.** `repair --mode from-sqlite` takes the mine-lock before archiving; rebuilds preserve a verified temp collection when the live swap fails; sparse drawers with zero `embedding_metadata` rows are no longer dropped; truncated ID pagination fails loud instead of pretending success. (#2109, #2086, #2087)
- **`repair --mode from-sqlite --dry-run` is a true preview.** It no longer archives or re-embeds; it prints per-collection would-be counts from SQLite ground truth and exits without touching the palace. Unreadable counts fail closed instead of inventing zeros. (#2133, #2095, #1654)
- **`repair --dry-run` is a true preview in the default (legacy) mode too.** That path ignored the flag entirely and ran the real rebuild — deleting any existing `<palace>.backup`, copying the palace over it, and re-filing the drawers collection. It now prints a read-only plan and exits without opening a chromadb client, which is itself a write to `chroma.sqlite3`. The plan names the live-collection delete the rebuild performs, warns when an existing backup would be destroyed, and reports the truncation guard as disabled when `--confirm-truncation-ok` is set. An isolated FTS5 inverted-index error is reported as auto-healable instead of raising the manual-recovery abort a real run never reaches, unreadable counts fail closed with a non-zero exit, and the `--dry-run` help no longer claims to be `--mode max-seq-id` only. (#2144)
- **HNSW divergence is preflighted before remaining `col.count()` crash sites** across mine, dedup, migrate, repair, and palace helpers. (#2093)
- **Re-mine and conversation ingest no longer lose or duplicate drawers.** Content-hash dedup prevents duplicate LLM conversation drawers; sweeper drawers are excluded from convo extract-mode purge scope and failed purges abort; search returns round-trippable `drawer_id` values for `get_drawer`. (#2050, #2125, #2089, #2090, #2044, #2080)
- **MCP and daemon lifecycle harden multi-agent use.** Read-only mode refuses config and checkpoint-ack tools that rewrite host state; stdio MCP exits on stdin EOF/broken pipe so orphaned sessions release locks; daemon jobs refused the palace lock are deferred instead of failed permanently. (#2126, #2103, #2101, #2072, #2029, #2014)
+29 -6
View File
@@ -1140,13 +1140,14 @@ def cmd_repair(args):
_close_chroma_handles,
_extract_drawers,
_post_rebuild_cleanup,
_preview_legacy_repair,
_promote_temp_collection,
_rebuild_collection_via_temp,
check_extraction_safety,
index_read_recovery_guidance,
maybe_autoheal_fts5_index,
maybe_repair_poisoned_max_seq_id_before_rebuild,
print_sqlite_integrity_abort,
resolve_repair_preflight_errors,
sqlite_integrity_errors,
)
@@ -1250,9 +1251,13 @@ def cmd_repair(args):
# stack trace instead of the friendly abort message. Run quick_check
# here so we can surface the clear recovery instructions and exit
# cleanly before chromadb's compactor touches the disk.
sqlite_errors = sqlite_integrity_errors(palace_path)
if sqlite_errors:
sqlite_errors = maybe_autoheal_fts5_index(palace_path, sqlite_errors)
dry_run = getattr(args, "dry_run", False)
# The FTS5 autoheal inside this call is a write, so a --dry-run predicts
# its outcome instead of performing it (#1596 is auto-healable and must
# not surface as an abort in a preview).
sqlite_errors = resolve_repair_preflight_errors(
palace_path, sqlite_integrity_errors(palace_path), dry_run=dry_run
)
if sqlite_errors:
print_sqlite_integrity_abort(palace_path, sqlite_errors)
sys.exit(1)
@@ -1260,7 +1265,7 @@ def cmd_repair(args):
preflight = maybe_repair_poisoned_max_seq_id_before_rebuild(
palace_path,
backup=getattr(args, "backup", True),
dry_run=getattr(args, "dry_run", False),
dry_run=dry_run,
assume_yes=getattr(args, "yes", False),
)
if preflight is not None:
@@ -1271,6 +1276,24 @@ def cmd_repair(args):
print(f"{'=' * 55}\n")
print(f" Palace: {palace_path}")
if dry_run:
# Return before the backend is used at all: the chromadb client this
# path opens is itself a write to chroma.sqlite3 (measured — the file
# hash changes on get_collection alone, before count()), so a preview
# that reached it could not be inert. Staying off the chromadb layer
# also keeps a dry run clear of the layer repair is separately reported
# to segfault in on a large palace (#2113). Exit non-zero on an
# unreadable count for parity with the from-sqlite preview above, so
# `--dry-run && repair --yes` cannot walk into the destructive run
# after a failed preview (#2095, #2133).
if not _preview_legacy_repair(
palace_path=palace_path,
collection_name=collection_name,
confirm_truncation_ok=getattr(args, "confirm_truncation_ok", False),
):
sys.exit(1)
return
backend = ChromaBackend()
# Try to read existing drawers
@@ -2135,7 +2158,7 @@ def main():
p_repair.add_argument(
"--dry-run",
action="store_true",
help="Print detected poisoned rows and exit without mutation (--mode max-seq-id only)",
help="Print what the repair would do and exit without modifying the palace",
)
# repair-status — read-only HNSW capacity health check (#1222)
+126 -9
View File
@@ -1715,6 +1715,21 @@ def rebuild_from_sqlite(
)
def _print_unreadable_count_refusal(*, collection_name: str, palace_path: str) -> None:
"""Refuse to preview a collection whose SQLite row count cannot be read.
Fail closed: inventing 0 would hide an unreadable source and make the
operator believe a real run would upsert nothing (review note on #1654 /
#2095). Shared by both previews so the wording cannot drift apart.
"""
print(
f"\n Cannot preview [{collection_name}]: SQLite row count is unreadable "
f"at {os.path.join(palace_path, 'chroma.sqlite3')}.\n"
" Fix source readability (schema, lock, permissions) and re-run "
"--dry-run; refusing to invent zero counts."
)
def _preview_rebuild_from_sqlite(
*,
source_palace: str,
@@ -1739,15 +1754,7 @@ def _preview_rebuild_from_sqlite(
for cname in _recoverable_collections():
n = sqlite_drawer_count(source_palace, cname)
if n is None:
# Fail closed: inventing 0 would hide an unreadable source and
# make the operator believe a real rebuild would upsert nothing
# (review note on #1654 / #2095).
print(
f"\n Cannot preview [{cname}]: SQLite row count is unreadable "
f"at {os.path.join(source_palace, 'chroma.sqlite3')}.\n"
" Fix source readability (schema, lock, permissions) and re-run "
"--dry-run; refusing to invent zero counts."
)
_print_unreadable_count_refusal(collection_name=cname, palace_path=source_palace)
return {}
counts[cname] = n
print(f" [{cname}] would re-embed and upsert {n} rows")
@@ -1758,6 +1765,116 @@ def _preview_rebuild_from_sqlite(
return counts
def _preview_legacy_repair(
*,
palace_path: str,
collection_name: str,
confirm_truncation_ok: bool = False,
) -> dict[str, int]:
"""Read-only preview for the default (legacy) ``repair`` path (``dry_run=True``).
Never opens a chromadb client, takes a lock, or writes. Opening a client is
itself a write to ``chroma.sqlite3``, so the row count comes from the
read-only SQLite ground truth :func:`check_extraction_safety` already
trusts. That is a different source than the real run rebuilds from (it
re-files what the chromadb collection layer returns), so the plan below
states the ``#1208`` contingency rather than promising the number.
``confirm_truncation_ok`` mirrors the real run's flag: it switches that
contingency off, so the preview has to say the guard is disabled rather
than promise an abort that would not happen.
Returns ``{}`` when the count is unreadable so a broken preview cannot look
like a valid plan (#1654, #2095, #2133).
"""
print("\n DRY RUN — no changes will be made.")
n = sqlite_drawer_count(palace_path, collection_name)
if n is None:
_print_unreadable_count_refusal(collection_name=collection_name, palace_path=palace_path)
print(f"{'=' * 55}\n")
return {}
if n == 0:
# The real run stops at ``total == 0`` with "Nothing to repair.", or —
# when the collection is absent altogether — at the index-read error
# that points to --mode from-sqlite. Neither backs up nor rebuilds, so
# promising a backup and a VACUUM here would describe a run that does
# not happen.
print(
f" [{collection_name}] chroma.sqlite3 holds no rows. A real run would report\n"
" nothing to repair, or an index read error, and change nothing."
)
print(f"{'=' * 55}\n")
return {collection_name: 0}
backup_path = os.path.normpath(palace_path) + ".backup"
if confirm_truncation_ok:
print(
f" [{collection_name}] chroma.sqlite3 holds {n} rows, and --confirm-truncation-ok\n"
" is set, so the #1208 truncation guard is DISABLED. A real run would re-file\n"
f" whatever the chromadb collection layer returns, even if that is fewer than {n}\n"
" rows, and the difference would be destroyed. It would, in order:"
)
else:
print(
f" [{collection_name}] chroma.sqlite3 holds {n} rows. A real run would extract them\n"
" through the chromadb collection layer first and abort without changes if that\n"
f" returns fewer than {n} (#1208 truncation guard). It would then, in order:"
)
if os.path.exists(backup_path):
print(f" 1. DELETE the existing backup at {backup_path} — or refuse outright")
print(" if it is not a palace — and copy the live palace in its place")
else:
print(f" 1. copy the palace directory to {backup_path}")
print(f" 2. DELETE the live '{collection_name}' collection and re-file the extracted rows")
print(" into a fresh one, staged and verified in a temp collection first")
print(" 3. rebuild the FTS5 index and VACUUM chroma.sqlite3")
print("\n Without --yes it would ask for confirmation before step 1.")
print(" Re-run without --dry-run to execute.")
print(f"{'=' * 55}\n")
return {collection_name: n}
def resolve_repair_preflight_errors(
palace_path: str,
errors: list[str],
*,
dry_run: bool,
progress=print,
) -> list[str]:
"""Return the quick_check errors that still block a repair.
A real run heals an isolated malformed FTS5 inverted index in place and
carries on (#1596). ``--dry-run`` must not perform that write, so it
classifies the errors with the same :func:`_errors_are_isolated_fts5`
predicate the real path gates on: an isolated FTS5 error is reported and
cleared, anything broader still aborts. Without this a preview would print
the ABORT banner — offline ``sqlite3 .recover``, recreate the FTS5 table —
for a palace the tool repairs by itself.
The prediction is deliberately the optimistic branch, and it is stated as
an attempt rather than a promise: the real heal still returns the errors
unchanged when another process holds the mine lock, when the rebuild
raises, or when ``quick_check`` is still dirty afterwards. A dry run cannot
tell those apart without taking the lock and writing, which is exactly what
it must not do, so the wording names them instead.
"""
if not errors:
return errors
if not dry_run:
return maybe_autoheal_fts5_index(palace_path, errors, progress=progress)
if _errors_are_isolated_fts5(errors):
progress(
"\n DRY RUN — quick_check reports an isolated FTS5 inverted-index error.\n"
" A real run would attempt an in-place rebuild of that index from the\n"
" intact content table and continue if it succeeds; it aborts instead if\n"
" another process holds the mine lock or the rebuild leaves quick_check\n"
" dirty. This preview leaves the index untouched."
)
return []
return errors
def _rebuild_from_sqlite_locked(
*,
source_palace: str,
+189
View File
@@ -1214,6 +1214,195 @@ def test_cmd_repair_uses_configured_collection(mock_config_cls, tmp_path, capsys
]
@patch("mempalace.cli.MempalaceConfig")
def test_cmd_repair_default_mode_dry_run_writes_nothing(mock_config_cls, tmp_path, capsys):
"""``repair --dry-run`` with no --mode must print a plan and leave the palace alone.
#2095 / #2133 fixed this for ``--mode from-sqlite``; the default (legacy)
path still ran the backup copy and the full rebuild.
"""
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
sqlite3.connect(str(palace_dir / "chroma.sqlite3")).close()
mock_config_cls.return_value.palace_path = str(palace_dir)
mock_config_cls.return_value.collection_name = "mempalace_drawers"
args = argparse.Namespace(palace=None, yes=True, dry_run=True)
mock_col = MagicMock()
mock_col.count.return_value = 2
# A concrete extract payload, so that if the dry-run guard ever regresses
# this test fails on its assertions instead of spinning in _extract_drawers.
mock_col.get.return_value = {
"ids": ["id1", "id2"],
"documents": ["doc1", "doc2"],
"metadatas": [{"wing": "a"}, {"wing": "b"}],
}
mock_backend = _mock_backend_for(col=mock_col)
with (
patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend),
patch("mempalace.repair.sqlite_drawer_count", return_value=2) as mock_count,
patch("mempalace.migrate.confirm_destructive_action") as mock_confirm,
):
cmd_repair(args)
out = capsys.readouterr().out
assert "DRY RUN — no changes will be made." in out
assert "holds 2 rows" in out
assert "Repair complete" not in out
# The count comes from read-only SQLite, never from a chromadb client:
# opening one is itself a write to chroma.sqlite3.
mock_count.assert_called_once_with(str(palace_dir), "mempalace_drawers")
mock_backend.get_collection.assert_not_called()
mock_col.get.assert_not_called()
mock_backend.create_collection.assert_not_called()
mock_backend.delete_collection.assert_not_called()
mock_confirm.assert_not_called()
assert not (tmp_path / "palace.backup").exists()
@patch("mempalace.cli.MempalaceConfig")
def test_cmd_repair_default_mode_dry_run_honours_custom_collection(
mock_config_cls, tmp_path, capsys
):
"""The preview must target the configured collection, not a hardcoded name."""
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
sqlite3.connect(str(palace_dir / "chroma.sqlite3")).close()
mock_config_cls.return_value.palace_path = str(palace_dir)
mock_config_cls.return_value.collection_name = "custom_drawers"
args = argparse.Namespace(palace=None, yes=True, dry_run=True)
with (
patch("mempalace.backends.chroma.ChromaBackend", return_value=_mock_backend_for()),
patch("mempalace.repair.sqlite_drawer_count", return_value=7) as mock_count,
):
cmd_repair(args)
assert "[custom_drawers]" in capsys.readouterr().out
mock_count.assert_called_once_with(str(palace_dir), "custom_drawers")
@patch("mempalace.cli.MempalaceConfig")
def test_cmd_repair_default_mode_dry_run_reports_healable_fts5_and_continues(
mock_config_cls, tmp_path, capsys
):
"""An isolated FTS5 error is auto-healed by a real run, so the preview must not abort.
Aborting here would hand the operator the manual ``sqlite3 .recover``
recipe for a palace ``maybe_autoheal_fts5_index`` repairs by itself (#1596).
"""
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
sqlite3.connect(str(palace_dir / "chroma.sqlite3")).close()
mock_config_cls.return_value.palace_path = str(palace_dir)
mock_config_cls.return_value.collection_name = "mempalace_drawers"
args = argparse.Namespace(palace=None, yes=True, dry_run=True)
with (
patch(
"mempalace.repair.sqlite_integrity_errors",
return_value=["malformed inverted index for FTS5 table x"],
),
patch("mempalace.repair.maybe_autoheal_fts5_index") as mock_autoheal,
patch("mempalace.repair.sqlite_drawer_count", return_value=4),
patch("mempalace.backends.chroma.ChromaBackend", return_value=_mock_backend_for()),
):
cmd_repair(args)
out = capsys.readouterr().out
mock_autoheal.assert_not_called()
assert "isolated FTS5 inverted-index error" in out
assert "ABORT" not in out
assert "holds 4 rows" in out
@patch("mempalace.cli.MempalaceConfig")
def test_cmd_repair_default_mode_dry_run_still_aborts_on_broad_corruption(
mock_config_cls, tmp_path, capsys
):
"""Corruption a real run cannot heal must still abort the preview with exit 1."""
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
sqlite3.connect(str(palace_dir / "chroma.sqlite3")).close()
mock_config_cls.return_value.palace_path = str(palace_dir)
mock_config_cls.return_value.collection_name = "mempalace_drawers"
args = argparse.Namespace(palace=None, yes=True, dry_run=True)
with (
patch(
"mempalace.repair.sqlite_integrity_errors",
return_value=["*** in database main *** Page 42 is never used"],
),
patch("mempalace.repair.maybe_autoheal_fts5_index") as mock_autoheal,
patch("mempalace.backends.chroma.ChromaBackend"),
pytest.raises(SystemExit) as excinfo,
):
cmd_repair(args)
assert excinfo.value.code == 1
mock_autoheal.assert_not_called()
assert "ABORT" in capsys.readouterr().out
@patch("mempalace.cli.MempalaceConfig")
def test_cmd_repair_non_dry_run_still_autoheals_fts5(mock_config_cls, tmp_path, capsys):
"""The real path must keep calling the autoheal — the patch restructured this branch."""
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
sqlite3.connect(str(palace_dir / "chroma.sqlite3")).close()
mock_config_cls.return_value.palace_path = str(palace_dir)
mock_config_cls.return_value.collection_name = "mempalace_drawers"
args = argparse.Namespace(palace=None, yes=True)
mock_col = MagicMock()
mock_col.count.return_value = 0
with (
patch(
"mempalace.repair.sqlite_integrity_errors",
return_value=["malformed inverted index for FTS5 table x"],
),
patch("mempalace.repair.maybe_autoheal_fts5_index", return_value=[]) as mock_autoheal,
patch(
"mempalace.backends.chroma.ChromaBackend",
return_value=_mock_backend_for(col=mock_col),
),
):
cmd_repair(args)
mock_autoheal.assert_called_once()
assert "Nothing to repair" in capsys.readouterr().out
@patch("mempalace.cli.MempalaceConfig")
def test_cmd_repair_default_mode_dry_run_refuses_to_invent_zero(mock_config_cls, tmp_path, capsys):
"""An unreadable count must refuse AND exit non-zero, like the from-sqlite preview.
Otherwise ``repair --dry-run && repair --yes`` walks into the destructive
run after a preview that could not be produced.
"""
palace_dir = tmp_path / "palace"
palace_dir.mkdir()
sqlite3.connect(str(palace_dir / "chroma.sqlite3")).close()
mock_config_cls.return_value.palace_path = str(palace_dir)
mock_config_cls.return_value.collection_name = "mempalace_drawers"
args = argparse.Namespace(palace=None, yes=True, dry_run=True)
mock_backend = _mock_backend_for(col=MagicMock())
with (
patch("mempalace.backends.chroma.ChromaBackend", return_value=mock_backend),
patch("mempalace.repair.sqlite_drawer_count", return_value=None),
pytest.raises(SystemExit) as excinfo,
):
cmd_repair(args)
out = capsys.readouterr().out
assert excinfo.value.code == 1
assert "Cannot preview [mempalace_drawers]" in out
assert "refusing to invent zero counts" in out
assert "would extract" not in out
mock_backend.get_collection.assert_not_called()
@patch("mempalace.cli.MempalaceConfig")
def test_cmd_repair_restores_backup_on_live_rebuild_failure(mock_config_cls, tmp_path, capsys):
"""When the live swap fails after the delete, recovery must PROMOTE the
+233
View File
@@ -2420,6 +2420,239 @@ def test_rebuild_from_sqlite_dry_run_fails_closed_when_count_unreadable(tmp_path
assert not dest.exists()
# ── _preview_legacy_repair — the default (legacy) repair --dry-run ─────
def test_preview_legacy_repair_leaves_the_palace_byte_identical(tmp_path, capsys):
"""The preview must not change a single byte of a real palace."""
import hashlib
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [(f"d{i}", f"b{i}", {"wing": "w"}) for i in range(6)])
db = palace / "chroma.sqlite3"
before = hashlib.sha256(db.read_bytes()).hexdigest()
tree_before = sorted((p.name, p.stat().st_size) for p in palace.iterdir())
counts = repair._preview_legacy_repair(
palace_path=str(palace), collection_name="mempalace_drawers"
)
assert counts == {"mempalace_drawers": 6}
assert hashlib.sha256(db.read_bytes()).hexdigest() == before
assert sorted((p.name, p.stat().st_size) for p in palace.iterdir()) == tree_before
assert [p for p in tmp_path.iterdir() if p.name.endswith(".backup")] == []
out = capsys.readouterr().out
assert "holds 6 rows" in out
assert "#1208 truncation guard" in out
def test_cmd_repair_dry_run_leaves_a_real_palace_byte_identical(tmp_path, capsys):
"""End-to-end: everything cmd_repair touches ahead of the preview is read-only.
The helper test above covers ``_preview_legacy_repair`` on its own. This one
covers the calls ``cmd_repair`` makes before reaching it — the quick_check
preflight and the poisoned-bookmark detector — against a palace that really
exists on disk, which is the only assertion that would catch a write
sneaking into any of them.
"""
import argparse
import hashlib
from mempalace.cli import cmd_repair
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [(f"d{i}", f"b{i}", {"wing": "w"}) for i in range(4)])
def snapshot():
return {
str(p.relative_to(palace)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted(palace.rglob("*"))
if p.is_file()
}
before = snapshot()
args = argparse.Namespace(palace=str(palace), yes=True, dry_run=True)
with patch("mempalace.cli.MempalaceConfig") as mock_config_cls:
mock_config_cls.return_value.palace_path = str(palace)
mock_config_cls.return_value.collection_name = "mempalace_drawers"
cmd_repair(args)
out = capsys.readouterr().out
assert snapshot() == before
assert not (tmp_path / "palace.backup").exists()
assert "DRY RUN — no changes will be made." in out
assert "holds 4 rows" in out
assert "Repair complete" not in out
def test_preview_legacy_repair_zero_rows_promises_no_backup(tmp_path, capsys):
"""A real run stops at "Nothing to repair." — the preview must not promise a rebuild.
``sqlite_drawer_count`` returns 0 (not None) for an absent collection, so
the fail-closed guard does not cover this case.
"""
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [("d1", "b1", {"wing": "w"})])
counts = repair._preview_legacy_repair(
palace_path=str(palace), collection_name="collection_that_does_not_exist"
)
out = capsys.readouterr().out
assert counts == {"collection_that_does_not_exist": 0}
assert "holds no rows" in out
assert "copy the palace directory" not in out
assert "VACUUM" not in out
def test_preview_legacy_repair_warns_it_would_delete_an_existing_backup(tmp_path, capsys):
"""Destroying the operator's previous backup is the step a preview must not hide."""
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [("d1", "b1", {"wing": "w"})])
backup = tmp_path / "palace.backup"
backup.mkdir()
repair._preview_legacy_repair(palace_path=str(palace), collection_name="mempalace_drawers")
out = capsys.readouterr().out
assert f"DELETE the existing backup at {backup}" in out
assert backup.exists()
def test_preview_legacy_repair_warns_when_the_backup_path_is_a_file(tmp_path, capsys):
"""The real run branches on exists(), not isdir().
A regular file at <palace>.backup makes a real run refuse at the backup
validation step, so a preview that promised a plain copy would describe a
run that never happens.
"""
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [("d1", "b1", {"wing": "w"})])
backup = tmp_path / "palace.backup"
backup.write_text("not a palace")
repair._preview_legacy_repair(palace_path=str(palace), collection_name="mempalace_drawers")
out = capsys.readouterr().out
assert f"DELETE the existing backup at {backup}" in out
assert "refuse outright" in out
assert "copy the palace directory" not in out
assert backup.read_text() == "not a palace"
def test_preview_legacy_repair_names_the_live_collection_delete(tmp_path, capsys):
"""The real run calls delete_collection on the live collection.
"re-file via a staged temp copy" alone reads as additive, which is the one
thing an operator must not misread about a destructive rebuild.
"""
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [("d1", "b1", {"wing": "w"})])
repair._preview_legacy_repair(palace_path=str(palace), collection_name="mempalace_drawers")
out = capsys.readouterr().out
assert "DELETE the live 'mempalace_drawers' collection" in out
def test_preview_legacy_repair_reports_the_truncation_guard_as_disabled(tmp_path, capsys):
"""--confirm-truncation-ok switches the #1208 abort off, so the preview must say so.
The abort message the guard prints tells operators to re-run with this
flag, so the flag plus --dry-run is a combination they are actively
steered into. Promising the guard there would be a false safety claim.
"""
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [(f"d{i}", f"b{i}", {"wing": "w"}) for i in range(3)])
counts = repair._preview_legacy_repair(
palace_path=str(palace),
collection_name="mempalace_drawers",
confirm_truncation_ok=True,
)
out = capsys.readouterr().out
assert counts == {"mempalace_drawers": 3}
assert "#1208 truncation guard is DISABLED" in out
assert "the difference would be destroyed" in out
assert "abort without changes" not in out
def test_preview_legacy_repair_fails_closed_when_count_unreadable(tmp_path, capsys, monkeypatch):
"""Unreadable count must return {} rather than render a zero-row plan."""
palace = tmp_path / "palace"
_seed_palace(palace, "mempalace_drawers", [("d1", "b1", {"wing": "w"})])
monkeypatch.setattr(repair, "sqlite_drawer_count", lambda *a, **k: None)
counts = repair._preview_legacy_repair(
palace_path=str(palace), collection_name="mempalace_drawers"
)
out = capsys.readouterr().out
assert counts == {}
assert "refusing to invent zero counts" in out
assert "holds" not in out
# ── resolve_repair_preflight_errors ───────────────────────────────────
def test_resolve_preflight_dry_run_clears_isolated_fts5_without_healing(tmp_path, capsys):
"""A dry run predicts the autoheal instead of performing its write."""
called = []
errs = ["malformed inverted index for FTS5 table x"]
out_errors = repair.resolve_repair_preflight_errors(
str(tmp_path),
errs,
dry_run=True,
progress=lambda *a, **k: called.append(a),
)
assert out_errors == []
assert called and "isolated FTS5 inverted-index error" in called[0][0]
def test_resolve_preflight_dry_run_keeps_broad_corruption(tmp_path):
"""Errors a real run cannot heal must survive so the caller still aborts."""
errs = ["*** in database main *** Page 42 is never used"]
assert repair.resolve_repair_preflight_errors(str(tmp_path), errs, dry_run=True) == errs
def test_resolve_preflight_real_run_delegates_to_autoheal(tmp_path, monkeypatch):
"""Outside a dry run the behaviour is unchanged: hand off to the autoheal."""
seen = {}
def fake_autoheal(path, errors, *, progress=print):
seen["args"] = (path, errors)
return []
monkeypatch.setattr(repair, "maybe_autoheal_fts5_index", fake_autoheal)
errs = ["malformed inverted index for FTS5 table x"]
assert repair.resolve_repair_preflight_errors(str(tmp_path), errs, dry_run=False) == []
assert seen["args"] == (str(tmp_path), errs)
def test_resolve_preflight_passes_empty_errors_through(tmp_path, monkeypatch):
"""A clean quick_check must not invoke the autoheal at all.
Asserting only on the return value would pass with the early-out deleted,
since the autoheal hands empty errors straight back.
"""
called = []
monkeypatch.setattr(
repair,
"maybe_autoheal_fts5_index",
lambda path, errors, **kw: called.append(path) or errors,
)
assert repair.resolve_repair_preflight_errors(str(tmp_path), [], dry_run=False) == []
assert called == []
def test_rebuild_from_sqlite_in_place_validates_source_before_archiving(tmp_path):
"""In-place + archive_existing_dest=True with a dir that lacks
chroma.sqlite3 must NOT rename the dir before bailing. An earlier
+14 -1
View File
@@ -134,7 +134,20 @@ Rebuild palace vector index from stored data. Fixes segfaults after database cor
mempalace repair
```
Creates a backup at `<palace_path>.backup` before rebuilding.
Creates a backup at `<palace_path>.backup` before rebuilding, replacing any backup already there.
| Flag | Description |
|------|-------------|
| `rebuild-index` | Positional alias for `--mode from-sqlite --archive-existing` |
| `--mode` | `legacy` (default), `max-seq-id`, or `from-sqlite` |
| `--dry-run` | Print what the repair would do and exit without modifying the palace |
| `--yes` | Skip confirmation for destructive changes |
| `--backup` | Back up SQLite before mutation (default: on) |
| `--source` | Source palace for `--mode from-sqlite` (defaults to `--palace`) |
| `--archive-existing` | Rename the existing palace to `<palace>.pre-rebuild-<timestamp>` first |
| `--segment` | Segment UUID filter for `--mode max-seq-id` |
| `--from-sidecar` | Pre-corruption `chroma.sqlite3` to copy clean `max_seq_id` values from |
| `--confirm-truncation-ok` | Override the truncation safety guard. Disables the abort that protects you when the collection layer returns fewer drawers than SQLite holds |
## `mempalace mcp`