Repository navigation
feat(v4.8.0 Fase 5): zero-downtime nuclear_rebuild via staging swap - #152
Conversation
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).
📝 WalkthroughWalkthroughChangesZero-downtime rebuild
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
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (5)
mcp_server/server.py (2)
1990-1994: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePass
embedding_functiontoget_collectionfor 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 winReuse
_snapshot_pre_staginginside_populate_staging.The
_savedliteral at Lines 1878-1884 duplicates the dict that_snapshot_pre_stagingreturns. 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 = stagingAlso 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_nameis 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 winAdd coverage for the swap rollback path and the query-error gate.
Two behaviors that the PR description lists as features have no test:
_swap_collections_atomicstep-2 failure. No test makesstaging.modify(name=...)raise, so the rollback rename of production is never exercised.- Validation gate 3.
_fake_collectionalready supportsraise_on_query=True, but no test passes it, so thequery_errorbranch in_validate_stagingis 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 valueThis test does not exercise the rebind it describes.
The query threads read
captured_prod, which is a direct reference to the mock collection._populate_stagingnever mutates that object. The assertion therefore proves only that aMagicMockis 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.collectionat 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
📒 Files selected for processing (4)
README.mddocs/reindex-operations.mdmcp_server/server.pytests/test_swap_zero_downtime.py
| | 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) | |
There was a problem hiding this comment.
📐 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.
| | 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.
| 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 |
There was a problem hiding this comment.
🩺 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.
| _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 |
There was a problem hiding this comment.
🗄️ 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.
| 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() |
There was a problem hiding this comment.
🗄️ 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.
| try: | ||
| stats = self._populate_staging(staging) |
There was a problem hiding this comment.
🎯 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.
| 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.
| self.collection = staging | ||
| self.bm25_index = BM25Index() | ||
| self._bm25_initialized = True # suppress lazy rebuild on staging | ||
| self._indexed_docs = {} | ||
| self._source_to_docid = {} |
There was a problem hiding this 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.
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.| except Exception: | ||
| # Rollback: restore prod state + delete staging orphan. |
There was a problem hiding this 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.
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.| ts = int(time.time()) | ||
| _saved = self._snapshot_pre_staging() | ||
| staging = self._create_staging_collection(ts) | ||
|
|
There was a problem hiding this 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.
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.| 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):] |
There was a problem hiding this comment.
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.
Summary
nuclear_rebuild()with staging-collection + atomic swap workflow — eliminates the RAG downtime window (previously 4min-40h).nuclear_rebuild(swap=False)(legacy destructive path moved to_rebuild_destructive).Workflow (new default
swap=True){collection_name}__staging_{unix_ts}(timestamped to avoid collisions)count >= baseline * 0.9(10% loss threshold accommodates parser-skipped docs)readme/function/import/return/class) return hits (4/5 not 5/5 so genuinely small corpora legitimately lacking e.g.returnstill pass)query()does not raise (catches dim mismatches)Collection.modify(name=):__old_{ts}(frees name)prod_name(assumes name)__old_{ts}non-fatally (cleanup helper ages it out later)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_rebuildis 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--adminbypass if runners intermittent — same pattern as F1-F4 PRs)Storage impact
__old_{ts}deleted at end of swap)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 impactREADME.mdCHANGELOG Unreleased: v4.8.0 Fase 5 entry at topCommits
82f76ecfeat(reindex): staging-based nuclear_rebuild for zero-downtime swap9de6d7dtest(reindex): 15 tests for swap lifecycle + zero-downtime + cleanup978ff12docs(reindex): zero-downtime swap workflow + v4.8.0 Fase 5 CHANGELOGSummary by CodeRabbit
New Features
Documentation
Tests
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.
swap=Falsecompatibility.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
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 BM25Prompt To Fix All With AI
Reviews (1): Last reviewed commit: "docs(reindex): zero-downtime swap workfl..." | Re-trigger Greptile