Skip to content

feat(v4.8.0 Fase 4): reindex checkpoint + resume + granular progress - #151

Merged
lyonzin merged 11 commits into
masterfrom
feat/v4.8.0-fase-4-resume-checkpoint
Aug 6, 2026
Merged

lyonzin merged 11 commits into
masterfrom
feat/v4.8.0-fase-4-resume-checkpoint

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 6, 2026 •

Copy link
Copy Markdown
Owner

Summary

v4.8.0 Fase 4 — the "don't restart from zero" milestone.

  • reindex_documents(resume=True) recovers a crashed / killed smart reindex from data/reindex_checkpoint.json. Checkpoint is written every 500 docs OR 30 seconds (whichever first), and stores the completed doc_ids + chunks_processed + a config signature. Config drift (embedding model / dim / chunk size / overlap change) invalidates the checkpoint with a WARN — prevents a mixed collection.
  • get_reindex_status() returns 6 new fields — chunks_processed, chunks_total, throughput_cps (sliding window), eta_seconds, checkpoint_saved_at, resumed. Enables real-time progress dashboards.
  • docs/reindex-operations.md NEW — documents the sync-vs-async gotcha for reindex_documents(full_rebuild=True) (daemon thread dies with process), resume semantics, checkpoint lifecycle, and example recovery flow.

Behavior guarantees

  • Backwards compatible: reindex_documents(force, full_rebuild) 2-arg signature preserved — resume is an opt-in tail kwarg with default False.
  • Nonsensical combo rejected: resume=True + full_rebuild=True returns structured error, touches nothing on disk (nuclear rebuild has no meaningful checkpoint semantic — the whole collection is thrown away).
  • Mode upgrade: resume=True implicitly forces mode='smart_reindex' even when force=False — an interrupted smart run cannot silently fall back to incremental (which would ignore the checkpoint).
  • Graceful degradation: missing / corrupt / future-version / signature-mismatch checkpoints all print WARN and start fresh instead of raising.
  • Atomic writes: checkpoint written via .tmp + os.replace() (Windows-safe on NTFS). Metadata (index_metadata.json) flushed alongside every checkpoint write to keep _indexed_docs on disk in sync with the checkpoint's indexed_doc_ids.
  • Sliding window throughput: deque bounded to 100 samples AND pruned at 30s age — stays meaningful during transient stalls without diluting current speed with ancient samples.

Changes

File Change
mcp_server/server.py +237 / -18 LOC — checkpoint plumbing, resume path, status fields
tests/test_reindex_resume.py +482 LOC NEW — 22 tests, 4 groups
tests/test_backwards_compat.py +1 / -1 LOC — pin new signature with resume kwarg
docs/reindex-operations.md +92 LOC NEW — operational guide
README.md +3 LOC — CHANGELOG entries (resume + progress fields + docs)

Perf note

Checkpoint write cadence is 500 docs OR 30s. Per-write I/O cost is ~1-3ms on NTFS SSD for a few-thousand doc_id list — rounding error next to the ChromaDB add() calls that dominate the loop. If Pillar 5 (perf gate) lights up on the checkpoint file write, apply skip-perf-gate label with justification: the trade-off (crash-safe smart reindex vs. millisecond I/O per 500 docs) was the explicit goal of Fase 4.

Test plan

  • pytest tests/test_reindex_resume.py -v — 22 green
  • pytest tests/test_backwards_compat.py -v — 5 green (resume kwarg is additive)
  • pytest tests/test_tools.py -v — 19 green
  • pytest tests/test_batch_parallel.py -v — 20 green (Fase 3 sanity)
  • pytest tests/test_embedding_profile.py tests/test_gpu_auto.py -v — 21 green (Fase 1+2 sanity)
  • python -c 'from mcp_server import server' — import clean
  • Manual (optional local): kill Python at ~50% of a large corpus reindex, then reindex_documents(resume=True) should skip the completed docs and continue chunk counting from where it stopped.

Commits (10)

  1. feat(reindex) — extend _reindex_progress with new fields
  2. feat(reindex) — track chunks_processed and compute throughput+ETA
  3. feat(reindex) — checkpoint file schema with atomic write and config signature
  4. feat(reindex) — write checkpoint every 500 docs or 30s
  5. feat(reindex) — add resume=True kwarg for smart reindex checkpoint recovery
  6. test(compat) — pin reindex_documents signature with resume kwarg
  7. test(reindex) — coverage for checkpoint write/load + resume + status fields
  8. feat(status) — expose new progress fields in get_reindex_status
  9. docs(reindex) — guide on sync vs async APIs and resume behavior
  10. docs(changelog) — v4.8.0 Fase 4 progress + resume + async guide

Roadmap position

Fase 4 of v4.8.0 (F1 embedding profile + F2 gpu auto-detect + F3 batch/parallel + F4 resume checkpoint shipped). Remaining phases F5-F7 (dual-collection swap zero-downtime, etc.) unchanged in scope.

Summary by CodeRabbit

  • New Features

    • Added resumable smart reindexing with persistent checkpoints.
    • Added validation and recovery support for interrupted reindex operations.
    • Added progress metrics including completion status, throughput, estimated time remaining, and checkpoint timestamps.
    • Added a resume option for reindexing; incompatible combinations are rejected.
  • Documentation

    • Added guidance for synchronous and asynchronous reindexing, checkpoint recovery, progress monitoring, and troubleshooting.

Greptile Summary

The PR adds resumable smart reindexing backed by an atomic checkpoint and exposes granular chunk progress, throughput, ETA, checkpoint time, and resume state.

  • Persists and validates smart-reindex checkpoints using a configuration signature.
  • Restores completed document IDs and chunk counts after interruption.
  • Adds operational documentation and focused compatibility/resume tests.

Confidence Score: 4/5

The PR does not appear safe to merge until config-signature invalidation rebuilds unchanged documents instead of retaining stale chunks.

A signature mismatch discards only the checkpoint and starts smart reindexing with force=False; unchanged files are consequently skipped, so their existing chunks can remain encoded or partitioned under the previous configuration.

Files Needing Attention: mcp_server/server.py

Important Files Changed

Filename Overview
mcp_server/server.py Adds checkpoint persistence, resume plumbing, and granular progress calculations across the smart-reindex lifecycle.
tests/test_reindex_resume.py Adds isolated coverage for checkpoint schema, validation, cadence, resume dispatch, and progress fields.
docs/reindex-operations.md Documents asynchronous rebuild behavior, checkpoint lifecycle, recovery workflow, and progress semantics.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Tool as reindex_documents
    participant CP as Checkpoint
    participant Worker as Smart reindex
    Client->>Tool: "resume=True"
    Tool->>CP: Load and validate
    alt Valid checkpoint
        CP-->>Tool: completed IDs and chunk count
        Tool->>Worker: Start with resume state
        Worker->>Worker: Skip completed documents
    else Missing or invalid checkpoint
        CP-->>Tool: No resume state
        Tool->>Worker: Start fresh smart reindex
    end
    Worker->>CP: Save every 500 docs or 30 seconds
    Worker->>CP: Clear after completion
Loading

Reviews (2): Last reviewed commit: "ci: probe workflow re-fire on F4 branch" | Re-trigger Greptile

lyonzin added 10 commits August 6, 2026 19:43
…hput, eta

Add 5 new v4.8.0 Fase 4 fields to the background reindex progress dict:

- chunks_processed: chunks committed to ChromaDB so far
- chunks_total: rolling estimate (0 during warmup, then average from
  completed docs)
- throughput_cps: chunks per second, sliding window (last 30s or 100
  chunks, whichever smaller)
- eta_seconds: estimated seconds to completion, from throughput +
  remaining chunks
- checkpoint_saved_at: ISO timestamp of last checkpoint file write

Both initialization sites updated:

- __init__ default dict keeps only {active: False} — new fields become
  present only after start_reindex_background() runs
- start_reindex_background() adds the 5 fields with zero/None defaults
  when a real reindex kicks off

Downstream code in _index_all_impl (Step 2) will populate them per doc.
get_reindex_status (Step 8) will expose them. Backwards compatible —
older callers that only read known keys are unaffected.
Extend _index_all_impl to populate the v4.8.0 Fase 4 progress fields
introduced in the previous commit:

- chunks_processed: incremented from _index_document's chunks_added
  return value per successful doc. Kept out of the except branch (a
  parser error means no chunks were committed).

- throughput_cps: sliding window over (timestamp, chunks_processed)
  samples in a deque bounded by maxlen=100. Also prunes samples older
  than 30 seconds each iteration, so throughput stays meaningful when
  the loop stalls (e.g. one giant PDF with 5000 chunks). Sample count
  >= 2 required before emitting a non-zero value.

- chunks_total: warm-started from the average chunks/doc across the
  existing self._indexed_docs (0 for a fresh index). Refined every
  iteration using the running average of docs processed so far,
  extrapolated to total_files. Guaranteed >= chunks_processed to avoid
  a negative remaining count.

- eta_seconds: (chunks_total - chunks_processed) / throughput_cps.
  Emits 0 during warmup (throughput unset) and near completion (when
  chunks_processed catches up to the estimate).

Adds 'from collections import deque' to the existing OrderedDict
import — no new external deps. Zero perf overhead on the hot path
(deque append + up to 100 popleft() calls per iteration, dwarfed by
the ChromaDB add() call it wraps).

Backwards-compat test still green — 3-arg signatures untouched.
…gnature

Introduce the v4.8.0 Fase 4 resume checkpoint plumbing. Four new
private methods on KnowledgeOrchestrator:

- _compute_config_signature() -> str
  SHA256 of embedding_model|embedding_dim|chunk_size|chunk_overlap.
  Any drift between checkpoint write and resume read invalidates the
  file. A stale checkpoint written under a different embedding model
  would produce a mixed collection (partial old vectors + partial new)
  which is worse than a clean restart.

- _write_checkpoint(operation, indexed_doc_ids, chunks_processed, started_at)
  Atomic write via .tmp + os.replace(). Windows-safe on NTFS. Payload
  schema:
    {
      version: 1,
      started_at: ISO,
      checkpoint_at: ISO,
      operation: str,
      indexed_doc_ids: [hash1, hash2, ...],
      chunks_processed: int,
      config_signature: sha256_hex
    }
  Also updates self._reindex_progress['checkpoint_saved_at'] for
  status poll visibility.

- _load_checkpoint() -> Optional[Dict]
  Returns None with a printed WARN when the file is missing, corrupt
  (JSONDecodeError/OSError), not a dict, from a future schema
  version, OR when config_signature mismatches. All failure modes
  degrade gracefully into 'restart from scratch' instead of raising.

- _clear_checkpoint()
  Removes the file after a successful reindex completes; used by
  Step 4 to close the loop.

Checkpoint file location: config.data_dir / 'reindex_checkpoint.json'.
Stored on self._checkpoint_file at __init__ time to keep the path
handling consistent with self._metadata_file.

No behavior change yet — Step 4 wires _write_checkpoint into the
_index_all_impl loop, Step 5 wires _load_checkpoint into the
reindex_documents kwarg. Adding these in isolation keeps the diff
reviewable one concept at a time.
Wire _write_checkpoint into the smart_reindex hot path. Three guards:

1. Only active for operation == 'smart_reindex'. Nuclear rebuild
   throws the whole collection away — resuming from a partial state
   would be nonsense. Incremental runs without force typically skip
   most docs and complete fast; the overhead of a checkpoint file
   would not pay for itself.

2. Cadence = 500 docs OR 30 seconds (whichever first).
   - 500 gives coverage for fast runs (small markdown docs mostly
     cached by mtime skip, thousands per minute).
   - 30s gives coverage for slow runs (one PDF with 5000 chunks
     could take > 30s, leaving too long a gap between checkpoints).

3. Write failures are non-fatal — a printed WARN, then the reindex
   continues. Losing a single checkpoint just means slightly less to
   resume from.

Successful completion clears the checkpoint (via _clear_checkpoint())
right after _save_metadata(). This prevents the next
reindex(resume=True) from resuming into a stale doc_id list where
half the referenced docs no longer exist.

I/O cost per checkpoint write: ~1-3ms on NTFS SSD for a few-thousand
doc_id list. Rounding error next to the ChromaDB add() calls that
dominate the loop.
…overy

Wire the resume path end-to-end. Threading:

- reindex_documents(force, full_rebuild, resume=False) — new opt-in
  MCP tool kwarg. When resume=True: rejects the combination
  resume=True + full_rebuild=True with a structured error, forces
  mode='smart_reindex' (an interrupted smart run should not silently
  fall back to incremental which would ignore the checkpoint),
  loads the checkpoint via _load_checkpoint(), and if valid builds a
  resume_state dict with doc_ids + chunks_processed.

- start_reindex_background(mode, resume_state=None) — forwards
  resume_state to reindex_all via lambda closure. Also stamps
  'resumed': True/False in _reindex_progress so the status poll can
  distinguish a fresh run from a recovered one. Pre-populates
  chunks_processed from the checkpoint so status counters do not
  regress to zero on first poll.

- reindex_all(resume_state=None) — passes resume_state through to
  index_all. Adjusts the startup log so a resume is visible in stdout
  (docs already processed + chunks count).

- index_all(force, resume_state=None) — thin propagation to
  _index_all_impl (kept split for the _index_lock guarantee).

- _index_all_impl(force, resume_state=None) — where the work happens.
  Initializes chunks_processed from resume_state and builds a set of
  _resume_doc_ids. First check inside the loop: if doc.id is in that
  set, count as skipped and continue. Everything downstream (metadata
  write, category count, chunks_added tally) is bypassed for those
  docs since they were already committed in the previous run.

Also adds _save_metadata() call right before every _write_checkpoint()
in the loop. Without it, the metadata on disk would be stale when a
resume tried to skip docs — the skip would trust the checkpoint's
doc_id list, but the loop would re-index them anyway because
_indexed_docs (loaded from disk) would not know about them.

One breaking-signature test (test_backwards_compat) now fails as
expected — Step 6 updates the frozen contract dict to include the
new kwarg.
Update the frozen MCP tool signature contract to include the new
opt-in 'resume' kwarg added in Step 5. Adding a keyword-only
argument at the tail with a default value is safe — existing
callers that only pass 'force' and 'full_rebuild' by name (or by
position, which the MCP protocol does not use) keep working.

Test rationale: LLM clients call MCP tools by parameter name, so
renaming or removing a parameter breaks them silently. Adding a
parameter is safe only if it has a default — which resume does
(False). This test locks that guarantee going forward.
…ields

New file tests/test_reindex_resume.py. 22 tests across 4 groups:

1. TestCheckpointWrite (4 tests)
   - schema (version 1, timestamps, operation, doc_ids, chunks_processed,
     config_signature)
   - progress dict side effect (checkpoint_saved_at populated)
   - atomic write via .tmp + os.replace() — mocked replace verifies
     the two paths and that the .tmp file exists before the rename
   - parent directory creation matches _save_metadata behavior

2. TestCheckpointLoad (6 tests)
   - missing file returns None
   - valid JSON round-trip
   - corrupt JSON returns None + WARN (no crash)
   - future schema version returns None + WARN
   - config_signature mismatch invalidates + WARN
   - non-dict payload returns None + WARN

3. TestResumeKwarg (6 tests)
   - signature exposes resume kwarg with default False
   - resume=True + full_rebuild=True rejected with structured error
     (start_reindex_background never called, checkpoint never loaded)
   - resume=False (default) skips _load_checkpoint entirely
   - resume=True + valid checkpoint builds resume_state {doc_ids,
     chunks_processed} and forwards it
   - resume=True + missing checkpoint logs info + starts fresh (no
     resume_state passed downstream)
   - resume=True forces mode='smart_reindex' even when force=False
     (an interrupted smart run must not silently fall back to
     incremental which would ignore the checkpoint)

4. TestStatusReporting (6 tests)
   - start_reindex_background seeds all 5 new keys with defaults +
     resumed=False flag
   - start_reindex_background with resume_state pre-populates
     chunks_processed + resumed=True
   - get_reindex_status returns the new fields — MARKED XFAIL, Step 8
     wires them into the return dict (strict=True so Step 8 must
     unxfail it or the test suite fails)
   - throughput invariant: fewer than 2 samples in sliding window
     keeps throughput_cps at 0.0
   - _clear_checkpoint removes the file after successful run
   - _clear_checkpoint on missing file is a no-op (no raise)

All tests use object.__new__ to bypass __init__ — no ChromaDB, no
FastEmbed download, no config.yaml roundtrip. Same isolation pattern
as tests/test_batch_parallel.py and tests/test_search.py.

Result: 21 passed + 1 xfailed (Step 8 clears the xfail).
Wire the 6 v4.8.0 Fase 4 progress fields into the get_reindex_status
return dict when a reindex is active:

- chunks_processed: chunks committed to ChromaDB so far
- chunks_total: rolling estimate of total chunks in the corpus (0
  during warmup, then updated per iteration)
- throughput_cps: chunks/sec over the sliding window (30s or 100
  samples, whichever is smaller)
- eta_seconds: estimated seconds to completion, derived from
  throughput and remaining chunks
- checkpoint_saved_at: ISO timestamp of the last checkpoint write
  (None until the first checkpoint at 500 docs or 30s)
- resumed: True when this run recovered from a checkpoint via
  reindex_documents(resume=True), False otherwise

Docstring updated to enumerate the new fields per audience block
(active vs. idle) so status consumers know what to poll for.

Removes the pytest.mark.xfail(strict=True) marker from
test_get_reindex_status_returns_new_fields_via_progress — the
strict=True flag would fail the suite if the test passed with the
marker still in place, guaranteeing this commit unxfails it.

Idle path unchanged — active=False still returns just last_result or
last_error, matching v4.7.x callers.
New docs/reindex-operations.md covering the operational shape of the
reindex APIs added or extended in v4.8.0 Fase 4:

- Sync vs async gotcha for reindex_documents(full_rebuild=True). The
  MCP tool returns immediately after spawning a daemon thread — if
  the Python process dies mid-rebuild, the collection is deleted but
  never repopulated. Recommends orchestrator.nuclear_rebuild() sync
  for CLI scripts and reindex_documents(force=True) + resume=True
  for long unstable rebuilds.

- Resume kwarg rules: only valid with full_rebuild=False (rejected
  otherwise with structured error), implicitly forces smart_reindex
  even when force=False, silently starts fresh when checkpoint is
  missing / corrupt / version-mismatch / config_signature-mismatch.

- Checkpoint cadence (500 docs OR 30s), rationale for the AND
  condition, config_signature invalidation semantic, lifecycle
  (written on cadence, cleared on success, cleared on failed
  resume load).

- Progress fields table for get_reindex_status: chunks_processed,
  chunks_total, throughput_cps, eta_seconds, checkpoint_saved_at,
  resumed. Documents warmup behavior (throughput 0.0 until 2
  samples, ETA 0 during warmup and near completion).

- Example recovery flow showing the actual sequence: start →
  crash → ls checkpoint → resume=True → poll status with
  resumed:true marker.

- Escalation rules of thumb for the three most likely operator
  questions: reindex looks stuck, resume=True rejected, checkpoint
  keeps invalidating.
Add three Unreleased entries at the top of the changelog:

- NEW (reindex): reindex_documents(resume=True) full-featured entry
  covering checkpoint cadence (500 docs or 30s), schema (doc_ids +
  chunks_processed + config_signature), rejection of the invalid
  full_rebuild=True + resume=True combination, implicit
  smart_reindex mode upgrade, graceful degradation on missing/
  corrupt/version/signature-mismatch checkpoints, atomic .tmp +
  os.replace() write, metadata flush alongside every checkpoint
  write, and test coverage summary (22 tests in
  tests/test_reindex_resume.py, all object.__new__ isolated).

- NEW (reindex): get_reindex_status returns 6 new progress fields
  (chunks_processed, chunks_total, throughput_cps, eta_seconds,
  checkpoint_saved_at, resumed) with warmup + sliding window
  rationale. Idle path unchanged.

- DOCS (reindex): docs/reindex-operations.md new file summary,
  covering sync-vs-async gotcha, resume semantics, checkpoint
  lifecycle, progress fields table, example recovery flow, and
  escalation rules of thumb.
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The reindex flow now supports validated persistent checkpoints, smart-reindex recovery, atomic progress writes, expanded active-status metrics, and checkpoint cleanup after success. The MCP tool accepts resume and rejects incompatible full rebuild requests.

Changes

Resumable reindexing

Layer / File(s) Summary
Checkpoint management
mcp_server/server.py, tests/test_reindex_resume.py
Adds versioned checkpoint payloads, configuration validation, atomic writes, loading safeguards, directory creation, and cleanup.
Smart indexing progress
mcp_server/server.py, tests/test_reindex_resume.py
Restores committed documents and chunk counts. Tracks throughput, ETA, timestamps, and chunk progress. Persists progress periodically and removes completed checkpoints.
Reindex orchestration and MCP entry point
mcp_server/server.py, tests/test_reindex_resume.py, tests/test_backwards_compat.py
Propagates resume state through synchronous and background reindexing. Adds MCP resume handling and full-rebuild validation.
Operations documentation
README.md, docs/reindex-operations.md, mcp_server/server.py
Documents resume behavior, checkpoint lifecycle, recovery procedures, and expanded status fields.

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

Sequence Diagram(s)

sequenceDiagram
  participant MCPTool as reindex_documents
  participant KnowledgeOrchestrator
  participant CheckpointManagement
  participant SmartIndexer
  MCPTool->>CheckpointManagement: load and validate checkpoint
  CheckpointManagement-->>MCPTool: resume state
  MCPTool->>KnowledgeOrchestrator: start smart reindex
  KnowledgeOrchestrator->>SmartIndexer: pass resume state
  SmartIndexer->>CheckpointManagement: persist progress
  SmartIndexer-->>KnowledgeOrchestrator: report progress and completion
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: reindex checkpointing, resume support, and granular progress reporting.
✨ 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-4-resume-checkpoint

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

@lyonzin

lyonzin commented Aug 6, 2026

Copy link
Copy Markdown
Owner Author

Nota de CI (2026-08-06 23:05Z): o push da branch + abertura do PR não dispararam nenhum workflow do GitHub Actions (CI, Quality Gate, Security, Bench Dashboard). Só rodaram os bots externos (Socket, Greptile, CodeRabbit, Snyk). Isso não é regressão desta PR — parece o mesmo padrão dos commits recentes de ci: probe/trigger workflows after Actions kill-switch toggle que sugerem que o kill-switch pode estar oscilando na org/repo. Testes rodaram todos localmente green (87 passed no bundle Fase 1-4). Se precisar re-dispatch depois de destravar o Actions, um empty commit ou fechar/reabrir o PR normalmente força re-trigger.

Comment thread mcp_server/server.py
Comment on lines +2748 to +2753
if stored_sig != current_sig:
print(
"[WARN] Checkpoint config_signature mismatch "
"(embedding model or chunking changed) — starting fresh"
)
return None

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 Config drift retains stale chunks

When an interrupted reindex's checkpoint no longer matches chunk_size or chunk_overlap, this branch discards the checkpoint but starts a smart reindex with force=False, causing unchanged files to retain chunks generated under the old configuration while changed or new files use the new one.

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

Comment:
**Config drift retains stale chunks**

When an interrupted reindex's checkpoint no longer matches `chunk_size` or `chunk_overlap`, this branch discards the checkpoint but starts a smart reindex with `force=False`, causing unchanged files to retain chunks generated under the old configuration while changed or new files use the new one.

---

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

Fix in Claude Code

@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 (2)
tests/test_reindex_resume.py (1)

439-453: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert throughput through the production code path.

The test recreates the sliding-window formula locally. It never calls _index_all_impl, so it passes even if the throughput code in mcp_server/server.py changes or is removed. Drive _index_all_impl with a stubbed parser and a patched _index_document, then assert _reindex_progress["throughput_cps"] and eta_seconds.

🤖 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_reindex_resume.py` around lines 439 - 453, Rewrite
test_throughput_zero_when_no_samples to exercise _index_all_impl instead of
duplicating its sliding-window calculation. Stub the parser and patch
_index_document so the implementation produces fewer than two samples, then
assert _reindex_progress["throughput_cps"] is 0.0 and verify eta_seconds through
the production path.
mcp_server/server.py (1)

3003-3022: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move checkpoint decoding behind a public orchestrator method.

The tool function calls the private orchestrator._load_checkpoint() and then reshapes the payload into resume_state. That places checkpoint schema knowledge (indexed_doc_ids, chunks_processed) in the MCP layer. Add a public method on KnowledgeOrchestrator, for example load_resume_state() -> Optional[Dict[str, Any]], that loads, validates, and returns the {"doc_ids": ..., "chunks_processed": ...} shape. The tool then holds no schema details.

Note: the new tests assert on _load_checkpoint, so this refactor also updates tests/test_reindex_resume.py.

🤖 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 3003 - 3022, Move checkpoint loading and
payload transformation out of the tool’s resume block into a public
KnowledgeOrchestrator method such as load_resume_state(), which should call
_load_checkpoint(), validate the checkpoint, and return the normalized
doc_ids/chunks_processed structure or None. Update the tool to call only this
public method and remove its checkpoint schema knowledge; adjust tests in
test_reindex_resume.py to target the refactored _load_checkpoint interaction.
🤖 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 57-86: Add the text language identifier to the recovery example’s
opening Markdown code fence in the reindex operations documentation, keeping the
mixed terminal transcript content unchanged.
- Around line 11-13: Revise the CLI scripts / one-off jobs guidance around
get_orchestrator().nuclear_rebuild() to remove the claim that it prevents a
half-destroyed collection. State that nuclear_rebuild() deletes and recreates
the active collection non-atomically, so an interrupted process may leave it
empty or partially populated and recovery requires rerunning the full rebuild.

In `@mcp_server/server.py`:
- Around line 2716-2755: Update _load_checkpoint to validate checkpoint payload
types before returning: require indexed_doc_ids to be a list and
chunks_processed to be a valid integer value, rejecting malformed or missing
fields with the existing warning-and-None behavior. Ensure malformed checkpoints
are discarded so start_reindex_background and reindex_documents do not receive
invalid resume state or raise TypeError.
- Around line 1381-1388: Track document IDs processed during the current
indexing run, adding each ID only after successful indexing, and use that
run-local set when writing the resume checkpoint instead of
self._indexed_docs.keys(). Keep the existing _resume_doc_ids skip check so
documents changed on disk still reach the mtime/size comparison.

In `@README.md`:
- Line 1419: Remove the inaccurate “clear on failed resume load” behavior from
the checkpoint lifecycle documentation in README.md lines 1419-1419 and
docs/reindex-operations.md lines 36-36. Document that invalid resume checkpoints
are rejected and a fresh rebuild starts, without claiming the checkpoint is
deleted or quarantined; no implementation change is required unless
deletion/quarantine is intentionally added.

---

Nitpick comments:
In `@mcp_server/server.py`:
- Around line 3003-3022: Move checkpoint loading and payload transformation out
of the tool’s resume block into a public KnowledgeOrchestrator method such as
load_resume_state(), which should call _load_checkpoint(), validate the
checkpoint, and return the normalized doc_ids/chunks_processed structure or
None. Update the tool to call only this public method and remove its checkpoint
schema knowledge; adjust tests in test_reindex_resume.py to target the
refactored _load_checkpoint interaction.

In `@tests/test_reindex_resume.py`:
- Around line 439-453: Rewrite test_throughput_zero_when_no_samples to exercise
_index_all_impl instead of duplicating its sliding-window calculation. Stub the
parser and patch _index_document so the implementation produces fewer than two
samples, then assert _reindex_progress["throughput_cps"] is 0.0 and verify
eta_seconds through the production path.
🪄 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: 4d6b4816-09e7-4966-9018-91a5d4a44ae6

📥 Commits

Reviewing files that changed from the base of the PR and between 7a48d62 and 0ade3d5.

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

Comment on lines +11 to +13
- **MCP tool calls:** use `reindex_documents(...)` as documented — the async wrapper is correct. The whole point of MCP is that clients (Claude, Cursor, etc.) get a response inside the request budget.
- **CLI scripts / one-off jobs:** prefer `get_orchestrator().nuclear_rebuild()` (sync) directly. This guarantees the rebuild completes before Python exits. If the script gets killed, at least the collection is not in a half-destroyed state.
- **Long-running rebuilds on unstable connections:** use `reindex_documents(force=True)` (smart reindex, not full rebuild) and rely on the resume checkpoint (see below) to recover.

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline mcp_server/server.py --items all --type function --match 'nuclear_rebuild'
rg -n -C 35 '^\s*def nuclear_rebuild\b|nuclear_rebuild\(' mcp_server/server.py
rg -n -C 5 'delete_collection|create_collection|os\.replace|rename_collection' mcp_server/server.py

Repository: lyonzin/knowledge-rag

Length of output: 10157


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1772,1835p' mcp_server/server.py
sed -n '1,45p' docs/reindex-operations.md
sed -n '45,95p' docs/reindex-operations.md

python3 - <<'PY'
from pathlib import Path
import re

source = Path("mcp_server/server.py").read_text(encoding="utf-8")
match = re.search(
    r"(?ms)^    def nuclear_rebuild\(self\).*?(?=^    def |\Z)",
    source,
)
if not match:
    raise SystemExit("nuclear_rebuild() was not found")

body = match.group(0)
checks = {
    "deletes named collection": "delete_collection(config.collection_name)" in body,
    "recreates named collection": "get_or_create_collection(" in body,
    "uses temporary collection": bool(re.search(r"\btemp(?:orary)?\b", body, re.I)),
    "atomically swaps collection": "os.replace(" in body or "rename_collection(" in body,
}
for name, result in checks.items():
    print(f"{name}: {result}")
PY

Repository: lyonzin/knowledge-rag

Length of output: 9587


Weaken the synchronous rebuild safety claim

nuclear_rebuild() deletes and recreates the active collection before index_all(force=True). It does not use a temporary collection or an atomic swap. A killed process can leave the collection empty or partially populated. State that recovery requires rerunning the full rebuild.

🤖 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 11 - 13, Revise the CLI scripts /
one-off jobs guidance around get_orchestrator().nuclear_rebuild() to remove the
claim that it prevents a half-destroyed collection. State that nuclear_rebuild()
deletes and recreates the active collection non-atomically, so an interrupted
process may leave it empty or partially populated and recovery requires
rerunning the full rebuild.

Comment on lines +57 to +86
```
# Terminal 1: start a smart reindex (say, 5000 docs)
mcp> reindex_documents(force=True)
{"status": "started", "operation": "smart_reindex", ...}

# ... 3 minutes in, laptop crashes at doc 2100 / 5000 ...

# Terminal 1 restart: check if a checkpoint survived
$ ls data/reindex_checkpoint.json
data/reindex_checkpoint.json

# Resume from where it stopped
mcp> reindex_documents(resume=True)
{"status": "started", "operation": "smart_reindex", ...}
[REINDEX] Resuming smart reindex from checkpoint (2100 docs already processed, 12345 chunks)

# Poll status — resumed=True marker + chunks_processed continues from checkpoint
mcp> get_reindex_status()
{
"active": true,
"operation": "smart_reindex",
"progress": "2103/5000",
"chunks_processed": 12360,
"chunks_total": 29400,
"throughput_cps": 45.2,
"eta_seconds": 377,
"resumed": true,
...
}
```

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

Add a language identifier to the recovery example fence.

The fence starting at Line 57 has no language identifier. Use text for the mixed terminal transcript, or split it into shell, json, and text fences. This resolves the reported markdownlint MD040 warning.

🧰 Tools
🪛 markdownlint-cli2 (0.23.2)

[warning] 57-57: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 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 57 - 86, Add the text language
identifier to the recovery example’s opening Markdown code fence in the reindex
operations documentation, keeping the mixed terminal transcript content
unchanged.

Source: Linters/SAST tools

Comment thread mcp_server/server.py
Comment on lines 1381 to +1388
for idx, doc in enumerate(documents):
try:
# v4.8.0 Fase 4: resume skip — doc was already committed
# in the previous interrupted run.
if _resume_doc_ids and doc.id in _resume_doc_ids:
stats["skipped"] += 1
continue

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 | 🏗️ Heavy lift

Resume skips documents that changed on disk.

The checkpoint stores list(self._indexed_docs.keys()) (Line 1518). That set contains every document known to the index, not only the documents committed during the interrupted run. On resume, Line 1385 skips each of those documents before the mtime/size comparison at Lines 1392-1407 runs. A smart reindex started to pick up filesystem edits therefore misses those edits and reports the documents as skipped.

Track the ids processed by the current run and checkpoint only that set.

🐛 Proposed fix: checkpoint only the ids handled by this run
         _throughput_window: deque = deque(maxlen=100)
+        # Doc ids committed by THIS run — the resume list must not include
+        # docs carried over from previous runs, otherwise resume would skip
+        # change detection for files edited on disk.
+        _run_doc_ids: List[str] = list(_resume_doc_ids)

Then append after a successful index (near Line 1431):

                 chunks_processed += chunks_added
+                _run_doc_ids.append(doc.id)

And use it in the checkpoint write (Line 1518):

-                        indexed_doc_ids=list(self._indexed_docs.keys()),
+                        indexed_doc_ids=_run_doc_ids,
🤖 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 1381 - 1388, Track document IDs processed
during the current indexing run, adding each ID only after successful indexing,
and use that run-local set when writing the resume checkpoint instead of
self._indexed_docs.keys(). Keep the existing _resume_doc_ids skip check so
documents changed on disk still reach the mtime/size comparison.

Comment thread mcp_server/server.py
Comment on lines +2716 to +2755
def _load_checkpoint(self) -> Optional[Dict[str, Any]]:
"""Load and validate a checkpoint from disk.

Returns None (with a WARN) when the file is missing, corrupt,
from a future schema version, or when the config signature
differs from the current config — any of those means the
checkpoint cannot be trusted and the caller should restart from
scratch.
"""
if not self._checkpoint_file.exists():
return None

try:
data = json.loads(self._checkpoint_file.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as e:
print(f"[WARN] Corrupt checkpoint file, ignoring: {e}")
return None

if not isinstance(data, dict):
print("[WARN] Checkpoint payload is not a dict, ignoring")
return None

version = data.get("version")
if version != self.CHECKPOINT_VERSION:
print(
f"[WARN] Checkpoint version {version} != current "
f"{self.CHECKPOINT_VERSION}, ignoring"
)
return None

stored_sig = data.get("config_signature")
current_sig = self._compute_config_signature()
if stored_sig != current_sig:
print(
"[WARN] Checkpoint config_signature mismatch "
"(embedding model or chunking changed) — starting fresh"
)
return None

return data

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 | 🟡 Minor | ⚡ Quick win

Validate the payload field types before returning the checkpoint.

_load_checkpoint checks the version and the config signature only. It does not check indexed_doc_ids or chunks_processed. A checkpoint with "chunks_processed": null or a non-list indexed_doc_ids passes validation. start_reindex_background then evaluates int(resume_state.get("chunks_processed", 0)) at Line 1686 and raises TypeError on the caller thread, so reindex_documents raises instead of returning a JSON error. Line 1363 and Line 1366 have the same exposure.

🛡️ Proposed fix: reject malformed field types
         stored_sig = data.get("config_signature")
         current_sig = self._compute_config_signature()
         if stored_sig != current_sig:
             print(
                 "[WARN] Checkpoint config_signature mismatch "
                 "(embedding model or chunking changed) — starting fresh"
             )
             return None
 
+        doc_ids = data.get("indexed_doc_ids")
+        chunks = data.get("chunks_processed")
+        if not isinstance(doc_ids, list) or not isinstance(chunks, int) or isinstance(chunks, bool):
+            print("[WARN] Checkpoint fields have unexpected types, ignoring")
+            return None
+
         return data
📝 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
def _load_checkpoint(self) -> Optional[Dict[str, Any]]:
"""Load and validate a checkpoint from disk.
Returns None (with a WARN) when the file is missing, corrupt,
from a future schema version, or when the config signature
differs from the current config — any of those means the
checkpoint cannot be trusted and the caller should restart from
scratch.
"""
if not self._checkpoint_file.exists():
return None
try:
data = json.loads(self._checkpoint_file.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as e:
print(f"[WARN] Corrupt checkpoint file, ignoring: {e}")
return None
if not isinstance(data, dict):
print("[WARN] Checkpoint payload is not a dict, ignoring")
return None
version = data.get("version")
if version != self.CHECKPOINT_VERSION:
print(
f"[WARN] Checkpoint version {version} != current "
f"{self.CHECKPOINT_VERSION}, ignoring"
)
return None
stored_sig = data.get("config_signature")
current_sig = self._compute_config_signature()
if stored_sig != current_sig:
print(
"[WARN] Checkpoint config_signature mismatch "
"(embedding model or chunking changed) — starting fresh"
)
return None
return data
def _load_checkpoint(self) -> Optional[Dict[str, Any]]:
"""Load and validate a checkpoint from disk.
Returns None (with a WARN) when the file is missing, corrupt,
from a future schema version, or when the config signature
differs from the current config — any of those means the
checkpoint cannot be trusted and the caller should restart from
scratch.
"""
if not self._checkpoint_file.exists():
return None
try:
data = json.loads(self._checkpoint_file.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as e:
print(f"[WARN] Corrupt checkpoint file, ignoring: {e}")
return None
if not isinstance(data, dict):
print("[WARN] Checkpoint payload is not a dict, ignoring")
return None
version = data.get("version")
if version != self.CHECKPOINT_VERSION:
print(
f"[WARN] Checkpoint version {version} != current "
f"{self.CHECKPOINT_VERSION}, ignoring"
)
return None
stored_sig = data.get("config_signature")
current_sig = self._compute_config_signature()
if stored_sig != current_sig:
print(
"[WARN] Checkpoint config_signature mismatch "
"(embedding model or chunking changed) — starting fresh"
)
return None
doc_ids = data.get("indexed_doc_ids")
chunks = data.get("chunks_processed")
if not isinstance(doc_ids, list) or not isinstance(chunks, int) or isinstance(chunks, bool):
print("[WARN] Checkpoint fields have unexpected types, ignoring")
return None
return data
🤖 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 2716 - 2755, Update _load_checkpoint to
validate checkpoint payload types before returning: require indexed_doc_ids to
be a list and chunks_processed to be a valid integer value, rejecting malformed
or missing fields with the existing warning-and-None behavior. Ensure malformed
checkpoints are discarded so start_reindex_background and reindex_documents do
not receive invalid resume state or raise TypeError.

Comment thread README.md

- **NEW (reindex)**: `reindex_documents(resume=True)` recovers from `data/reindex_checkpoint.json` after an interrupted smart reindex. Checkpoint is written every 500 docs or 30s (whichever first), and stores `indexed_doc_ids` + `chunks_processed` + `config_signature` (SHA256 of `embedding_model | embedding_dim | chunk_size | chunk_overlap`). A config mismatch between checkpoint write and resume load invalidates the checkpoint with a WARN — this prevents a mixed collection (partial old-model vectors + partial new-model vectors) which would silently degrade retrieval. The combination `resume=True + full_rebuild=True` is rejected with a structured error because nuclear rebuild wipes the collection first — resuming into a partial state would leave no coherent index. The `resume=True` flag also implicitly forces `mode='smart_reindex'` even when `force=False` was passed, so an interrupted smart run cannot silently fall back to `incremental` (which would ignore the checkpoint entirely). Existing 2-arg `reindex_documents(force, full_rebuild)` signature preserved — `resume` is an opt-in tail kwarg. Missing / corrupt / future-version / non-dict checkpoints all degrade gracefully to "start fresh" instead of raising. Written to `data/reindex_checkpoint.json` via atomic `.tmp` + `os.replace()` — Windows-safe on NTFS in-directory. Cleared automatically on successful reindex completion. Metadata (`index_metadata.json`) is flushed alongside every checkpoint write so `_indexed_docs` on disk stays in sync with the checkpoint's `indexed_doc_ids` list. New `tests/test_reindex_resume.py` (22 tests, all `object.__new__` isolation — no ChromaDB, no FastEmbed download) covers write cadence + atomic write + schema + load validation (6 failure modes) + resume kwarg happy path + rejection combos + status field flow. v4.8.0 Fase 4.
- **NEW (reindex)**: `get_reindex_status()` now returns 6 new fields during active reindex — `chunks_processed` (chunks committed to ChromaDB so far), `chunks_total` (rolling estimate, 0 during warmup then running average from completed docs × `total_files`), `throughput_cps` (chunks/sec, sliding window bounded by the smaller of 100 samples or 30 seconds — deque `maxlen=100` combined with age-based pruning each iteration keeps the number stable during transient stalls without diluting current speed with ancient samples), `eta_seconds` (estimated seconds to completion, derived from throughput + remaining chunks, guarded against div-by-zero), `checkpoint_saved_at` (ISO timestamp of last checkpoint write, `null` until first checkpoint at 500 docs / 30s), `resumed` (bool — `true` when the current run was recovered from a checkpoint via `resume=True`, `false` otherwise). Enables real-time progress dashboards and the "should I keep waiting or restart" call. Idle path (`active: false`) unchanged — still returns just `last_result` or `last_error`. v4.8.0 Fase 4.
- **DOCS (reindex)**: `docs/reindex-operations.md` NEW — documents the sync-vs-async gotcha for `reindex_documents(full_rebuild=True)` (daemon thread dies with process → RAG offline until manual restart), recommends `orchestrator.nuclear_rebuild()` sync for CLI scripts and `reindex_documents(force=True) + resume=True` for long unstable smart rebuilds. Also covers resume semantics (only valid with `full_rebuild=False`, implicitly forces `smart_reindex` mode, graceful degrade to fresh start on missing/corrupt/version/signature mismatch), checkpoint cadence (500 docs OR 30s, whichever first, plus rationale for the OR condition), `config_signature` invalidation semantic, full lifecycle (write on cadence, clear on success, clear on failed resume load), progress fields table with warmup behavior, example recovery flow showing crash → `ls checkpoint` → `resume=True` → poll status with `resumed:true` marker, and escalation rules of thumb for the three most likely operator questions. v4.8.0 Fase 4.

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

Remove the false “clear on failed resume load” contract.

Both documentation sites claim that invalid resume checkpoints are deleted, but the implementation only rejects them and starts fresh. Align the implementation and documentation before release so stale checkpoint state cannot be silently reused.

  • README.md#L1419-L1419: remove “clear on failed resume load” or implement deletion/quarantine.
  • docs/reindex-operations.md#L36-L36: make the same correction to the checkpoint lifecycle.
📍 Affects 2 files
  • README.md#L1419-L1419 (this comment)
  • docs/reindex-operations.md#L36-L36
🤖 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 `@README.md` at line 1419, Remove the inaccurate “clear on failed resume load”
behavior from the checkpoint lifecycle documentation in README.md lines
1419-1419 and docs/reindex-operations.md lines 36-36. Document that invalid
resume checkpoints are rejected and a fresh rebuild starts, without claiming the
checkpoint is deleted or quarantined; no implementation change is required
unless deletion/quarantine is intentionally added.

@lyonzin
lyonzin merged commit 55c3bfc into master Aug 6, 2026
5 checks passed
@lyonzin
lyonzin deleted the feat/v4.8.0-fase-4-resume-checkpoint branch August 6, 2026 23:06
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