Skip to content

feat(v4.8.0 Fase 5): zero-downtime nuclear_rebuild via staging swap - #152

Merged
lyonzin merged 3 commits into
masterfrom
feat/v4.8.0-fase-5-swap
Aug 6, 2026
Merged

lyonzin merged 3 commits into
masterfrom
feat/v4.8.0-fase-5-swap

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 6, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Replace destructive nuclear_rebuild() with staging-collection + atomic swap workflow — eliminates the RAG downtime window (previously 4min-40h).
  • Backwards-compat preserved via nuclear_rebuild(swap=False) (legacy destructive path moved to _rebuild_destructive).
  • Startup cleanup auto-sweeps crash-orphaned staging collections (24h TTL).

Workflow (new default swap=True)

  1. Cleanup stale stagings (>24h)
  2. Snapshot orchestrator state (collection + bm25 + indexed_docs + source_lookup)
  3. Create {collection_name}__staging_{unix_ts} (timestamped to avoid collisions)
  4. Populate via temporary orchestrator rebind — throwaway BM25 so production BM25 keeps serving queries throughout
  5. Validate (3 gates, ALL must pass):
    • count >= baseline * 0.9 (10% loss threshold accommodates parser-skipped docs)
    • 4 of 5 canonical queries (readme/function/import/return/class) return hits (4/5 not 5/5 so genuinely small corpora legitimately lacking e.g. return still pass)
    • query() does not raise (catches dim mismatches)
  6. Atomic 2-step Collection.modify(name=):
    • prod → __old_{ts} (frees name)
    • staging → prod_name (assumes name)
    • delete __old_{ts} non-fatally (cleanup helper ages it out later)
    • Rollback rename on mid-swap failure so previous prod is still queryable
  7. Post-swap BM25 rebuild from swapped-in ChromaDB contents + query cache invalidation

Any failure in populate/validate/swap triggers _rollback_staging_state + staging cleanup. Production sees zero net change.

API research (ChromaDB)

Collection.modify(name=...) confirmed via context7 docs AND direct venv check (venv/Lib/site-packages/chromadb/api/models/Collection.py:281). Rename-based swap chosen over metadata-role plan B because it is atomic on the ChromaDB side (single SQLite UPDATE) and requires no application-layer routing logic.

Test plan

  • pytest tests/test_swap_zero_downtime.py -v — 15/15 green (1.66s)
  • pytest tests/test_backwards_compat.py -v — 5/5 green (no MCP tool signature change; nuclear_rebuild is internal)
  • pytest tests/test_reindex_resume.py -v — 22/22 green (F4 behavior intact)
  • pytest tests/test_batch_parallel.py tests/test_config.py -v — 37/37 green
  • CI full suite (may need --admin bypass if runners intermittent — same pattern as F1-F4 PRs)

Storage impact

  • During rebuild: ~2x storage temporarily (both collections on disk)
  • After swap: back to 1x (__old_{ts} deleted at end of swap)
  • Cleanup TTL: 24h — orphan sits at most one day before automatic reclaim

Docs

  • docs/reindex-operations.md: new section "Zero-downtime Rebuild (v4.8.0 Fase 5+)" with 7-step workflow, all 3 validation gates rationale, failure modes table, storage impact
  • README.md CHANGELOG Unreleased: v4.8.0 Fase 5 entry at top

Commits

  • 82f76ec feat(reindex): staging-based nuclear_rebuild for zero-downtime swap
  • 9de6d7d test(reindex): 15 tests for swap lifecycle + zero-downtime + cleanup
  • 978ff12 docs(reindex): zero-downtime swap workflow + v4.8.0 Fase 5 CHANGELOG

Summary by CodeRabbit

  • New Features

    • Rebuilding search data now uses a zero-downtime workflow by default, with staging, validation, atomic switching, rollback protection, and search index refresh.
    • Existing destructive rebuild behavior remains available as an optional compatibility mode.
    • Stale temporary rebuild data is automatically cleaned up after 24 hours.
  • Documentation

    • Added guidance covering rebuild workflows, validation, rollback, storage requirements, cleanup, and failure handling.
  • Tests

    • Added coverage for concurrent searches, staging isolation, swapping, cleanup, validation, and compatibility behavior.

Greptile Summary

The PR replaces destructive rebuilding with a staging-populate, validate, rename-swap, and post-swap BM25 reconstruction workflow, while retaining the legacy path. It also adds startup cleanup, lifecycle tests, and operational documentation, but the implementation currently exposes staging state to live queries and has unsafe recovery and ownership behavior.

  • Adds timestamped staging collection creation, validation gates, and rename-based promotion.
  • Rebuilds BM25 and invalidates query caches after promotion.
  • Adds stale-staging cleanup and preserves swap=False compatibility.
  • Documents and tests the intended zero-downtime lifecycle.

Confidence Score: 4/5

The PR should not merge until live queries remain isolated from staging, post-swap failures retain the promoted collection, rebuild staging names are exclusively owned, and failed old-collection deletion is recoverable.

The new default rebuild publishes partial staging state to concurrent queries, can restore a deleted production handle after a successful swap, allows concurrent rebuilds to share the same staging name, and permanently leaks old collections after transient deletion failures.

Files Needing Attention: mcp_server/server.py and tests/test_swap_zero_downtime.py

Important Files Changed

Filename Overview
mcp_server/server.py Implements the staging swap, but shared-state rebinding breaks query isolation, post-swap rollback restores an invalid handle, timestamp names can collide, and old collections are never swept.
tests/test_swap_zero_downtime.py Adds broad mocked lifecycle coverage, but its concurrency test queries a pre-captured production handle and therefore does not exercise the real self.query path affected by the shared rebind.
docs/reindex-operations.md Documents the intended workflow, including cleanup and availability guarantees that the current implementation does not fully satisfy.
README.md Records the feature and operational claims, including collision avoidance and zero downtime that are not currently guaranteed.

Sequence Diagram

sequenceDiagram
    participant Q as Concurrent query
    participant O as Orchestrator
    participant P as Production
    participant S as Staging
    O->>S: Create staging
    O->>O: Rebind shared collection/BM25 to staging
    par Populate staging
        O->>S: "index_all(force=True)"
    and Live query
        Q->>O: query()
        O->>S: Query partial staging state
        S-->>Q: Partial or empty results
    end
    O->>S: Validate
    O->>P: Rename production to old
    O->>S: Rename staging to production
    O->>P: Delete old
    O->>O: Reconnect and rebuild BM25
Loading

Fix All in Claude Code

Prompt To Fix All With AI
### Issue 1
mcp_server/server.py:1885-1889
**Staging state leaks into queries**

When a query executes during staging population, `_populate_staging` has rebound the shared collection and BM25 attributes to a partially populated staging collection and an empty index, causing incomplete semantic results and missing BM25 results throughout the rebuild window.

### Issue 2
mcp_server/server.py:2136-2137
**Rollback restores deleted collection**

When BM25 reconstruction or metadata persistence raises after a successful swap, this handler restores the pre-swap collection handle even though the old production collection has already been deleted, causing subsequent queries to fail or serve stale data until the orchestrator is reinitialized.

### Issue 3
mcp_server/server.py:2108-2111
**Concurrent rebuilds share staging**

If two processes sharing the ChromaDB directory begin rebuilding in the same second, both derive the same staging name and open it with get-or-create semantics, so their writes are mixed and either process can rename or delete the collection while the other is using it.

### Issue 4
mcp_server/server.py:1806-1819
**Old collections evade cleanup**

When deletion of the renamed old production collection fails after a successful swap, this cleanup path ignores its `__old_` name because it scans only the staging prefix, causing full-corpus copies to remain indefinitely and accumulate across repeated failures.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "docs(reindex): zero-downtime swap workfl..." | Re-trigger Greptile

Greptile also left 4 inline comments on this PR.

lyonzin added 3 commits August 6, 2026 20:15
Replaces the destructive nuclear_rebuild() with a staging-collection
workflow that eliminates the RAG downtime window (previously 4min-40h
depending on corpus size and hardware).

Workflow (new default nuclear_rebuild(swap=True)):
  1. _cleanup_stale_staging_collections — sweep >24h orphans
  2. _snapshot_pre_staging — save collection/bm25/indexed_docs
  3. _create_staging_collection — timestamped name for collision avoidance
  4. _populate_staging — temporary orchestrator rebind, throwaway BM25 so
     production BM25 keeps serving queries throughout
  5. _validate_staging — count >= baseline*0.9 + 4/5 canonical queries
     (readme/function/import/return/class) return hits + query() does
     not raise (catches dim mismatches)
  6. _swap_collections_atomic — two-step Collection.modify(name=): prod
     to __old_ts, staging to prod_name, delete __old_ts. Rollback on
     mid-swap failure so previous prod is still queryable.
  7. _rebuild_bm25_post_swap — reconnect self.collection, clear + rebuild
     BM25 from the swapped-in ChromaDB contents.

Failure semantics: any exception in populate/validate/swap triggers
_rollback_staging_state and staging cleanup. Production sees zero net
change. Startup cleanup handles crash-orphaned stagings via 24h TTL.

Backwards compat: nuclear_rebuild(swap=False) preserves the legacy
destructive behavior byte-for-byte (moved into _rebuild_destructive)
for cases that require a full disk cleanup.
Coverage groups:

TestStagingLifecycle (6):
  - Timestamped staging name format
  - Populate does NOT mutate production BM25 (identity preservation)
  - Validate rejects undersized staging (count < baseline * 0.9)
  - Validate rejects broken canonical queries (< 4/5 hits)
  - Validate passes healthy staging (count + 5/5 canonical hits)
  - Validate accepts fresh-install (baseline == 0 skips canonical gate)

TestSwap (3):
  - Post-swap self.collection resolves to the renamed object
  - BM25 rebuild NOT triggered when validate fails (via _rebuild_via_swap)
  - Chaos: 100 parallel queries against captured prod handle during
    populate return zero errors and non-empty results

TestCleanup (3):
  - Stale (>24h) staging deleted
  - Recent (<24h) staging preserved (may belong to rebuild in flight)
  - Non-staging collections with unrelated names left alone

TestBackwardsCompat (3):
  - Default kwarg is swap=True (v4.8.0+ default)
  - swap=False dispatches _rebuild_destructive
  - No-arg call dispatches _rebuild_via_swap

Runtime 1.66s. All mocks — no real ChromaDB / FastEmbed touched.
- docs/reindex-operations.md: new section 'Zero-downtime Rebuild
  (v4.8.0 Fase 5+)' documenting the 7-step swap workflow, all three
  validation gates with rationale for 4/5 canonical threshold, atomic
  2-step Collection.modify(name=) semantics with rollback behavior,
  failure modes table (validate fail / swap step 1 fail / swap step 2
  fail / crash mid-populate) and storage impact (2x during rebuild,
  back to 1x after swap, 24h TTL cleanup).

- README.md CHANGELOG: v4.8.0 Fase 5 entry at top of Unreleased with
  the full end-to-end description (workflow, failure semantics,
  storage impact, test coverage summary).
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Zero-downtime rebuild

Layer / File(s) Summary
Staging lifecycle
mcp_server/server.py, tests/test_swap_zero_downtime.py
The orchestrator creates isolated staging collections, snapshots state, restores state on failure, and removes stale staging collections. Tests cover staging isolation, validation, zero-baseline installs, and cleanup.
Validated collection swap
mcp_server/server.py, tests/test_swap_zero_downtime.py, docs/reindex-operations.md, README.md
The workflow validates staged data, swaps collections, rebuilds BM25 metadata, invalidates caches, and performs rollback handling. Documentation and tests cover the workflow and failure paths.
Rebuild mode dispatch
mcp_server/server.py, tests/test_swap_zero_downtime.py
nuclear_rebuild(swap=True) now selects the staged workflow by default. swap=False retains the destructive rebuild path. Tests verify both dispatch modes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant KnowledgeOrchestrator
  participant StagingCollection
  participant ProductionCollection
  participant BM25Index
  participant QueryCache
  KnowledgeOrchestrator->>StagingCollection: populate documents
  KnowledgeOrchestrator->>StagingCollection: validate count and sanity queries
  KnowledgeOrchestrator->>ProductionCollection: atomically swap collections
  KnowledgeOrchestrator->>BM25Index: rebuild BM25 metadata
  KnowledgeOrchestrator->>QueryCache: invalidate cached results
Loading

Suggested reviewers: hohlas

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: zero-downtime nuclear_rebuild using a staging swap.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/v4.8.0-fase-5-swap

Comment @coderabbitai help to get the list of available commands.

@lyonzin
lyonzin merged commit 2e02c1d into master Aug 6, 2026
4 of 5 checks passed
@lyonzin
lyonzin deleted the feat/v4.8.0-fase-5-swap branch August 6, 2026 23:21

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (5)
mcp_server/server.py (2)

1990-1994: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Pass embedding_function to get_collection for consistency.

Line 2025 passes embedding_function=self.embed_fn, but Line 1991 does not. The handle here is only renamed, so behavior is unaffected today. Aligning both calls prevents a future query on this handle from using a default embedding function.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 1990 - 1994, Update the collection lookup
in the rename flow around get_collection to pass
embedding_function=self.embed_fn, matching the later get_collection call while
preserving the existing rename behavior.

1878-1884: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse _snapshot_pre_staging inside _populate_staging.

The _saved literal at Lines 1878-1884 duplicates the dict that _snapshot_pre_staging returns. Two copies can drift when a new mutated field is added.

♻️ Proposed refactor
-        _saved = {
-            "collection": self.collection,
-            "bm25_index": self.bm25_index,
-            "_bm25_initialized": self._bm25_initialized,
-            "_indexed_docs": dict(self._indexed_docs),
-            "_source_to_docid": dict(self._source_to_docid),
-        }
+        _saved = self._snapshot_pre_staging()
         self.collection = staging

Also applies to: 1902-1914

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 1878 - 1884, Update _populate_staging to
obtain the pre-staging state by calling _snapshot_pre_staging() instead of
constructing the duplicate _saved dictionary literal, and reuse that snapshot at
the corresponding restore path around the additionally affected block. Keep the
existing staging and rollback behavior unchanged.
tests/test_swap_zero_downtime.py (3)

128-133: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

prod_collection_name is never used.

The parameter has no effect. Every caller relies on monkeypatch.setattr(srv.config, "collection_name", ...) instead. Remove the parameter or use it to set the config value.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_swap_zero_downtime.py` around lines 128 - 133, The _fresh_orch
function accepts the unused prod_collection_name parameter while callers
configure the collection through srv.config.collection_name. Remove this
parameter and update its callers, or use it to assign the orchestrator’s
collection configuration consistently; avoid retaining an argument with no
effect.

270-324: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the swap rollback path and the query-error gate.

Two behaviors that the PR description lists as features have no test:

  1. _swap_collections_atomic step-2 failure. No test makes staging.modify(name=...) raise, so the rollback rename of production is never exercised.
  2. Validation gate 3. _fake_collection already supports raise_on_query=True, but no test passes it, so the query_error branch in _validate_staging is never reached.

Do you want me to generate these two tests?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_swap_zero_downtime.py` around lines 270 - 324, The TestSwap
coverage is missing atomic-swap rollback and staging query-error validation
cases. Add a test that makes staging.modify during _swap_collections_atomic step
2 raise and asserts production is renamed back, plus a test using
_fake_collection(..., raise_on_query=True) that exercises _validate_staging’s
query_error gate and verifies validation fails with the expected error.

326-381: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

This test does not exercise the rebind it describes.

The query threads read captured_prod, which is a direct reference to the mock collection. _populate_staging never mutates that object. The assertion therefore proves only that a MagicMock is callable from several threads. It cannot fail because of a regression in the rebind logic.

To make the test meaningful, have the threads read orch.collection at each iteration and assert that every returned handle is either the production collection or the staging collection, never a partially updated state.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_swap_zero_downtime.py` around lines 326 - 381, Update
test_100_parallel_queries_during_populate_zero_errors so each query iteration
reads the collection through orch.collection instead of the captured_prod
reference, allowing the test to observe _populate_staging’s rebind. Assert each
handle is either the original production collection or the staging collection,
then query it and retain the existing zero-error assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/reindex-operations.md`:
- Around line 111-116: Update the “Validate fails” row in the failure table to
state that the staging collection is deleted during cleanup, while the snapshot
is restored and production remains untouched. Keep the other failure rows
unchanged and align the wording with _rebuild_via_swap’s exception behavior.

In `@mcp_server/server.py`:
- Around line 1795-1842: Extend _cleanup_stale_staging_collections to scan both
the existing __staging_ prefix and the swap-generated __old_ prefix so stale
post-swap collections are reclaimed by the TTL sweep; update the related
server.py comment to reflect this behavior. Also revise
docs/reindex-operations.md lines 102-106 so Step 3 accurately describes
automatic __old_{ts} cleanup and any manual removal needed when deletion fails.
- Around line 1878-1895: Update the rollback path in _rebuild_via_swap,
specifically _rollback_staging_state, to persist the restored metadata snapshot
after restoring the in-memory fields. Ensure the production index_metadata.json
is rewritten from the restored _indexed_docs and _source_to_docid state before
re-raising the original failure.
- Around line 2112-2113: In the workflow around _populate_staging, inspect the
returned stats for the index_all lock-skip marker before performing staging
validation or swapping. When stats["skipped_reason"] is
"reindex_already_running", return or abort the workflow immediately while
preserving the existing skip result, and leave normal validation unchanged for
completed indexing.
- Around line 2100-2106: Update the baseline-count handling before
_cleanup_stale_staging_collections so an exception from self.collection.count()
aborts the rebuild instead of retaining baseline_count = 0 and continuing
validation or swap. Propagate or explicitly signal the failure through the
surrounding rebuild flow, while preserving the normal fresh-install behavior
only when count succeeds and legitimately returns zero.

---

Nitpick comments:
In `@mcp_server/server.py`:
- Around line 1990-1994: Update the collection lookup in the rename flow around
get_collection to pass embedding_function=self.embed_fn, matching the later
get_collection call while preserving the existing rename behavior.
- Around line 1878-1884: Update _populate_staging to obtain the pre-staging
state by calling _snapshot_pre_staging() instead of constructing the duplicate
_saved dictionary literal, and reuse that snapshot at the corresponding restore
path around the additionally affected block. Keep the existing staging and
rollback behavior unchanged.

In `@tests/test_swap_zero_downtime.py`:
- Around line 128-133: The _fresh_orch function accepts the unused
prod_collection_name parameter while callers configure the collection through
srv.config.collection_name. Remove this parameter and update its callers, or use
it to assign the orchestrator’s collection configuration consistently; avoid
retaining an argument with no effect.
- Around line 270-324: The TestSwap coverage is missing atomic-swap rollback and
staging query-error validation cases. Add a test that makes staging.modify
during _swap_collections_atomic step 2 raise and asserts production is renamed
back, plus a test using _fake_collection(..., raise_on_query=True) that
exercises _validate_staging’s query_error gate and verifies validation fails
with the expected error.
- Around line 326-381: Update
test_100_parallel_queries_during_populate_zero_errors so each query iteration
reads the collection through orch.collection instead of the captured_prod
reference, allowing the test to observe _populate_staging’s rebind. Assert each
handle is either the original production collection or the staging collection,
then query it and retain the existing zero-error assertion.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 2fb13aa2-53f0-4c95-9c48-c965703aa41b

📥 Commits

Reviewing files that changed from the base of the PR and between 55c3bfc and 978ff12.

📒 Files selected for processing (4)
  • README.md
  • docs/reindex-operations.md
  • mcp_server/server.py
  • tests/test_swap_zero_downtime.py

Comment on lines +111 to +116
| Failure | Effect on production |
| ------------------------ | ---------------------------------------------------------------- |
| Validate fails | Staging kept for inspection; snapshot restored; prod untouched |
| Swap step 1 fails | Nothing renamed; snapshot restored; prod untouched |
| Swap step 2 fails | Rollback of step 1; snapshot restored; prod queryable at old name if inner rollback fails |
| Python crash mid-populate | Staging orphaned; next Orchestrator boot cleans it (24h TTL) |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

The "Validate fails" row contradicts the implementation.

The table states that staging is kept for inspection. _rebuild_via_swap deletes the staging collection in its except block (mcp_server/server.py Lines 2139-2144) for every failure, including validation failure. Operators who follow this table will look for a collection that no longer exists.

📝 Proposed doc fix
-| Validate fails           | Staging kept for inspection; snapshot restored; prod untouched   |
+| Validate fails           | Staging deleted; snapshot restored; prod untouched; failure detail in the `[SWAP] Validation FAILED` log line |
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
| Failure | Effect on production |
| ------------------------ | ---------------------------------------------------------------- |
| Validate fails | Staging kept for inspection; snapshot restored; prod untouched |
| Swap step 1 fails | Nothing renamed; snapshot restored; prod untouched |
| Swap step 2 fails | Rollback of step 1; snapshot restored; prod queryable at old name if inner rollback fails |
| Python crash mid-populate | Staging orphaned; next Orchestrator boot cleans it (24h TTL) |
| Failure | Effect on production |
| ------------------------ | --------------------------------------------------------------------------- |
| Validate fails | Staging deleted; snapshot restored; prod untouched; failure detail in the `[SWAP] Validation FAILED` log line |
| Swap step 1 fails | Nothing renamed; snapshot restored; prod untouched |
| Swap step 2 fails | Rollback of step 1; snapshot restored; prod queryable at old name if inner rollback fails |
| Python crash mid-populate | Staging orphaned; next Orchestrator boot cleans it (24h TTL) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/reindex-operations.md` around lines 111 - 116, Update the “Validate
fails” row in the failure table to state that the staging collection is deleted
during cleanup, while the snapshot is restored and production remains untouched.
Keep the other failure rows unchanged and align the wording with
_rebuild_via_swap’s exception behavior.

Comment thread mcp_server/server.py
Comment on lines +1795 to +1842
def _cleanup_stale_staging_collections(self) -> Dict[str, int]:
"""Remove staging collections older than ``_STAGING_TTL_SECONDS``.

Runs opportunistically at Orchestrator init and before each swap
rebuild. Idempotent — safe to call repeatedly. Stagings younger than
the TTL are preserved because they may belong to a rebuild in flight
(another process, another host mounting the same DB, or a very slow
embed backend). Structured logging reports counts so operators can
spot leaks.
"""
prefix = f"{config.collection_name}__staging_"
now = int(time.time())
stats = {"scanned": 0, "removed": 0, "preserved": 0}
try:
existing = self.chroma_client.list_collections()
except Exception as e:
print(f"[STAGING] list_collections failed (non-fatal): {e}")
return stats

for coll in existing:
name = getattr(coll, "name", "")
if not name.startswith(prefix):
continue
stats["scanned"] += 1
suffix = name[len(prefix):]
try:
ts = int(suffix)
except ValueError:
# Non-conforming name — leave it alone rather than delete
# something we didn't create.
stats["preserved"] += 1
continue
if (now - ts) < self._STAGING_TTL_SECONDS:
stats["preserved"] += 1
continue
try:
self.chroma_client.delete_collection(name)
stats["removed"] += 1
print(f"[STAGING] Cleaned up stale staging: {name}")
except Exception as e:
print(f"[STAGING] Failed to delete {name} (non-fatal): {e}")

if stats["removed"] > 0 or stats["scanned"] > 0:
print(
f"[STAGING] Cleanup: scanned={stats['scanned']} "
f"removed={stats['removed']} preserved={stats['preserved']}"
)
return stats

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

__old_{ts} collections have no reclaim path. _cleanup_stale_staging_collections filters on the {collection_name}__staging_ prefix only, so the __old_{ts} collection created during the swap is never aged out. Both the code comment and the documentation claim otherwise.

  • mcp_server/server.py#L1795-L1842: extend the prefix match to include {config.collection_name}__old_ so the TTL sweep also reclaims post-swap leftovers, and correct the comment at Lines 2010-2011.
  • docs/reindex-operations.md#L102-L106: update the Step 3 note so it matches the implemented behavior, either after the sweep covers __old_{ts} or by stating that a failed delete needs manual removal.
📍 Affects 2 files
  • mcp_server/server.py#L1795-L1842 (this comment)
  • docs/reindex-operations.md#L102-L106
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 1795 - 1842, Extend
_cleanup_stale_staging_collections to scan both the existing __staging_ prefix
and the swap-generated __old_ prefix so stale post-swap collections are
reclaimed by the TTL sweep; update the related server.py comment to reflect this
behavior. Also revise docs/reindex-operations.md lines 102-106 so Step 3
accurately describes automatic __old_{ts} cleanup and any manual removal needed
when deletion fails.

Comment thread mcp_server/server.py
Comment on lines +1878 to +1895
_saved = {
"collection": self.collection,
"bm25_index": self.bm25_index,
"_bm25_initialized": self._bm25_initialized,
"_indexed_docs": dict(self._indexed_docs),
"_source_to_docid": dict(self._source_to_docid),
}
self.collection = staging
self.bm25_index = BM25Index()
self._bm25_initialized = True # suppress lazy rebuild on staging
self._indexed_docs = {}
self._source_to_docid = {}
try:
return self.index_all(force=True)
except Exception:
for k, v in _saved.items():
setattr(self, k, v)
raise

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Rollback does not restore index_metadata.json on disk.

_populate_staging replaces self._indexed_docs with an empty dict, then calls index_all(force=True). _index_all_impl calls self._save_metadata() at Line 1544, so the staging metadata overwrites the production index_metadata.json during populate.

If validate or swap then fails, _rollback_staging_state restores only the in-memory fields. The on-disk file keeps the staging content. After the next process restart, _load_metadata and _build_source_lookup produce state that does not match the production collection. Adjacent-chunk expansion and orphan cleanup then operate on wrong doc ids.

Re-persist the restored snapshot in the rollback path at Lines 2136-2145.

🔧 Proposed fix in `_rebuild_via_swap` rollback
         except Exception:
             # Rollback: restore prod state + delete staging orphan.
             self._rollback_staging_state(_saved)
+            # index_all() already overwrote index_metadata.json with the
+            # staging-only dict; re-persist the restored production state so
+            # a later boot does not load staging metadata.
+            try:
+                self._save_metadata()
+            except Exception as e:
+                print(f"[SWAP] Failed to restore metadata file: {e}")
             try:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 1878 - 1895, Update the rollback path in
_rebuild_via_swap, specifically _rollback_staging_state, to persist the restored
metadata snapshot after restoring the in-memory fields. Ensure the production
index_metadata.json is rewritten from the restored _indexed_docs and
_source_to_docid state before re-raising the original failure.

Comment thread mcp_server/server.py
Comment on lines +2100 to +2106
baseline_count = 0
try:
baseline_count = self.collection.count()
except Exception as e:
print(f"[SWAP] Could not read baseline count (assume 0): {e}")

self._cleanup_stale_staging_collections()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

A failed baseline count disables every validation gate and can destroy production data.

If self.collection.count() raises, baseline_count stays 0. _validate_staging then sets min_expected = 0 and skips the canonical-query gate, so any staging collection passes, including an empty one. _swap_collections_atomic then renames the real production collection to __old_{ts} and deletes it at Line 2013. The result is total index loss with no validation signal.

A count failure is not the same condition as a fresh install. Abort the rebuild instead.

🛡️ Proposed fix
         prod_name = config.collection_name
-        baseline_count = 0
         try:
             baseline_count = self.collection.count()
         except Exception as e:
-            print(f"[SWAP] Could not read baseline count (assume 0): {e}")
+            raise RuntimeError(
+                f"Cannot read production baseline count; refusing swap "
+                f"rebuild because validation gates would be disabled: {e}"
+            )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 2100 - 2106, Update the baseline-count
handling before _cleanup_stale_staging_collections so an exception from
self.collection.count() aborts the rebuild instead of retaining baseline_count =
0 and continuing validation or swap. Propagate or explicitly signal the failure
through the surrounding rebuild flow, while preserving the normal fresh-install
behavior only when count succeeds and legitimately returns zero.

Comment thread mcp_server/server.py
Comment on lines +2112 to +2113
try:
stats = self._populate_staging(staging)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Detect the index_all lock-skip result before validating.

index_all returns early with "skipped_reason": "reindex_already_running" when _index_lock is held, and it indexes nothing. _populate_staging returns that dict unchanged, so the workflow proceeds to validate an empty staging collection. With a non-zero baseline the count gate aborts, but the log reports a validation failure instead of the real cause. With a zero baseline the swap promotes the empty staging.

Fail fast on that marker.

🔧 Proposed fix
             stats = self._populate_staging(staging)
+            if stats.get("skipped_reason"):
+                raise RuntimeError(
+                    f"Staging populate skipped: {stats['skipped_reason']}"
+                )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
stats = self._populate_staging(staging)
try:
stats = self._populate_staging(staging)
if stats.get("skipped_reason"):
raise RuntimeError(
f"Staging populate skipped: {stats['skipped_reason']}"
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 2112 - 2113, In the workflow around
_populate_staging, inspect the returned stats for the index_all lock-skip marker
before performing staging validation or swapping. When stats["skipped_reason"]
is "reindex_already_running", return or abort the workflow immediately while
preserving the existing skip result, and leave normal validation unchanged for
completed indexing.

Comment thread mcp_server/server.py
Comment on lines +1885 to +1889
self.collection = staging
self.bm25_index = BM25Index()
self._bm25_initialized = True # suppress lazy rebuild on staging
self._indexed_docs = {}
self._source_to_docid = {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Staging state leaks into queries

When a query executes during staging population, _populate_staging has rebound the shared collection and BM25 attributes to a partially populated staging collection and an empty index, causing incomplete semantic results and missing BM25 results throughout the rebuild window.

Prompt To Fix With AI
This is a comment left during a code review.
Path: mcp_server/server.py
Line: 1885-1889

Comment:
**Staging state leaks into queries**

When a query executes during staging population, `_populate_staging` has rebound the shared collection and BM25 attributes to a partially populated staging collection and an empty index, causing incomplete semantic results and missing BM25 results throughout the rebuild window.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Comment thread mcp_server/server.py
Comment on lines +2136 to +2137
except Exception:
# Rollback: restore prod state + delete staging orphan.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Rollback restores deleted collection

When BM25 reconstruction or metadata persistence raises after a successful swap, this handler restores the pre-swap collection handle even though the old production collection has already been deleted, causing subsequent queries to fail or serve stale data until the orchestrator is reinitialized.

Prompt To Fix With AI
This is a comment left during a code review.
Path: mcp_server/server.py
Line: 2136-2137

Comment:
**Rollback restores deleted collection**

When BM25 reconstruction or metadata persistence raises after a successful swap, this handler restores the pre-swap collection handle even though the old production collection has already been deleted, causing subsequent queries to fail or serve stale data until the orchestrator is reinitialized.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Comment thread mcp_server/server.py
Comment on lines +2108 to +2111
ts = int(time.time())
_saved = self._snapshot_pre_staging()
staging = self._create_staging_collection(ts)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Concurrent rebuilds share staging

If two processes sharing the ChromaDB directory begin rebuilding in the same second, both derive the same staging name and open it with get-or-create semantics, so their writes are mixed and either process can rename or delete the collection while the other is using it.

Prompt To Fix With AI
This is a comment left during a code review.
Path: mcp_server/server.py
Line: 2108-2111

Comment:
**Concurrent rebuilds share staging**

If two processes sharing the ChromaDB directory begin rebuilding in the same second, both derive the same staging name and open it with get-or-create semantics, so their writes are mixed and either process can rename or delete the collection while the other is using it.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Comment thread mcp_server/server.py
Comment on lines +1806 to +1819
now = int(time.time())
stats = {"scanned": 0, "removed": 0, "preserved": 0}
try:
existing = self.chroma_client.list_collections()
except Exception as e:
print(f"[STAGING] list_collections failed (non-fatal): {e}")
return stats

for coll in existing:
name = getattr(coll, "name", "")
if not name.startswith(prefix):
continue
stats["scanned"] += 1
suffix = name[len(prefix):]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Old collections evade cleanup

When deletion of the renamed old production collection fails after a successful swap, this cleanup path ignores its __old_ name because it scans only the staging prefix, causing full-corpus copies to remain indefinitely and accumulate across repeated failures.

Prompt To Fix With AI
This is a comment left during a code review.
Path: mcp_server/server.py
Line: 1806-1819

Comment:
**Old collections evade cleanup**

When deletion of the renamed old production collection fails after a successful swap, this cleanup path ignores its `__old_` name because it scans only the staging prefix, causing full-corpus copies to remain indefinitely and accumulate across repeated failures.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant