From 09c4bf61dcaf97d8412c48f279d879a8af1e4df0 Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sat, 21 Nov 2026 21:03:59 -0500 Subject: [PATCH 1/8] fix(readiness): serve the published generation during a staged rebuild (#145) A staged build set index_publication_pending for its whole run, which readiness reported as missing_provenance, so every update - even a quick incremental - made search_code/symbol_lookup fail closed. The build now records its owner next to the repository writer.lock (.mcp-index/rebuild-owner.json: pid, process start time, host, registration and published generation, target commit) before the fence goes up, and clears it in finally (publish, failure or abort). The owner is alive only while that process exists with the same start time on this host and still holds the writer lock. While the owner is alive, readiness classifies the published generation (ready for a same-commit rebuild, stale_commit while a newer commit is indexed) and adds an additive `rebuild` object. search_code and symbol_lookup serve the published generation; stale responses carry the stale readiness and a note. A dead or unprovable owner keeps missing_provenance and fails closed; every other non-ready state is unchanged, and mutating tools still require ready. The live store's handles are now released after the publish swap rather than before it, so a query admitted during the build finishes on its open connection and is then refused by the existing generation recheck. Refs Consiliency/Code-Index-MCP#145 Co-Authored-By: Claude Opus 5.5 --- README.md | 6 + docs/SUPPORT_MATRIX.md | 28 ++ docs/operations/deployment-runbook.md | 4 + mcp_server/cli/tool_handlers.py | 52 ++- mcp_server/client.py | 6 +- mcp_server/core/repo_resolver.py | 18 +- mcp_server/health/repo_status.py | 21 +- mcp_server/health/repository_readiness.py | 45 +++ mcp_server/indexing/lock_registry.py | 153 ++++++++ mcp_server/storage/git_index_manager.py | 54 ++- mcp_server/storage/store_registry.py | 16 +- tests/test_health_surface.py | 1 + tests/test_issue_145_serve_during_rebuild.py | 368 +++++++++++++++++++ tests/test_repository_readiness.py | 3 + tests/test_v13_state.py | 10 +- 15 files changed, 758 insertions(+), 27 deletions(-) create mode 100644 tests/test_issue_145_serve_during_rebuild.py diff --git a/README.md b/README.md index 6c9d0760..5c28a5d8 100644 --- a/README.md +++ b/README.md @@ -666,6 +666,12 @@ MRREADY freezes the rollout-facing interpretation of those commands: `ready`, MCP search returns `index_unavailable` with `safe_fallback: "native_search"` instead of treating a status row as a query success. +- While a staged rebuild runs and its owner process is alive, queries keep + serving the published generation: readiness stays `ready` for a same-commit + rebuild, or reports `stale_commit` with an additive `rebuild` object while a + newer commit is indexed, and those responses carry that readiness. A crashed + build stays `missing_provenance` and fail-closed (see + [`docs/SUPPORT_MATRIX.md`](docs/SUPPORT_MATRIX.md)). - The current multi-repo verdict remains `controlled rollout only` while the multi-repo and STDIO surfaces are still beta. diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 83056170..4733c828 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -21,6 +21,34 @@ readiness is `ready`. Lexical repository readiness does not imply semantic readiness: `semantic: true` queries additionally require summaries, vector linkage, and profile-compatible semantic metadata. +During a staged rebuild or incremental update (Consiliency/Code-Index-MCP#145) +the published generation is never modified, so queries keep serving it while +the build's owner is alive. The owner is recorded next to the repository's +`writer.lock` (`.mcp-index/rebuild-owner.json`: pid, process start time, host, +registration and published generation); it counts as alive only while that +process still exists with the same start time on this host and holds the +writer lock. Readiness then classifies the published generation and adds a +`rebuild` object, `{"in_progress": true, "target_commit": "...", +"started_at": "..."}` (`null` when no live build runs; also on `get_status` +repository rows): + +| Situation during a staged build | Readiness before | Readiness now | `search_code` / `symbol_lookup` | +|---|---|---|---| +| Live owner, rebuild of the published commit (forced or repair) | `missing_provenance` | `ready` + `rebuild` | Served from the published generation, unchanged response shape | +| Live owner, indexing a newer commit | `missing_provenance` | `stale_commit` + `rebuild` | Served from the published generation; the response carries `readiness` (`state: "stale_commit"`, `last_indexed_commit`, `current_commit`, `rebuild`) and a `note`, and `search_code` returns its envelope instead of the bare list | +| Owner dead (crash mid-build) or unprovable (no record, other host, lock not held) | `missing_provenance` | `missing_provenance` | `index_unavailable`, `safe_fallback: "native_search"` until recovery rebuilds | +| Build failed (`partial_index_failure`) | `missing_provenance` | `missing_provenance` | `index_unavailable` | + +`stale_commit` without a live rebuild, and every other non-ready state, stay +fail-closed as before. `get_status` reports `query_status: "serving_stale"` +and lexical `available` while results come from the older published +generation. The HTTP gateway endpoints, whose bodies are bare result lists, +serve during a same-commit rebuild but keep refusing `stale_commit`. A query +whose generation is published mid-flight finishes on its open connection to +the old file (retention keeps that file) and is then refused by the generation +recheck, so the caller retries against the new generation. Mutating tools +(`reindex`, `write_summaries`, `summarize_sample`) still require `ready`. + Runtime facts are grounded in `mcp_server/plugins/language_registry.py`, `mcp_server/plugins/plugin_factory.py`, `mcp_server/plugins/plugin_set_registry.py`, `mcp_server/plugins/sandboxed_plugin.py`, `mcp_server/cli/tool_handlers.py`, diff --git a/docs/operations/deployment-runbook.md b/docs/operations/deployment-runbook.md index 6c8f7cc6..dfc561b9 100644 --- a/docs/operations/deployment-runbook.md +++ b/docs/operations/deployment-runbook.md @@ -40,6 +40,10 @@ workspace. Status surfaces are not query results. Query tools still return `index_unavailable` with `safe_fallback: "native_search"` for non-ready cases. +The one exception is a staged rebuild whose owner is alive: queries keep +serving the published generation, labelled `stale_commit` with a `rebuild` +object while a newer commit is indexed; see the readiness notes in +[`../SUPPORT_MATRIX.md`](../SUPPORT_MATRIX.md) (#145). Because multi-repo and STDIO remain beta, the current MRREADY verdict is `controlled rollout only`. diff --git a/mcp_server/cli/tool_handlers.py b/mcp_server/cli/tool_handlers.py index f6457ce1..ee71e022 100644 --- a/mcp_server/cli/tool_handlers.py +++ b/mcp_server/cli/tool_handlers.py @@ -170,9 +170,13 @@ def _resolve_ctx( repo_resolver: RepoResolver, path_arg: Optional[str], ) -> Optional[RepoContext]: - """Resolve a RepoContext from path_arg or MCP_WORKSPACE_ROOT fallback.""" + """Resolve a RepoContext from path_arg or MCP_WORKSPACE_ROOT fallback. + + Mutating callers gate on ``readiness.ready`` before calling this; query + callers also accept a published generation served during a rebuild (#145). + """ readiness = _classify_ctx(repo_resolver, path_arg) - if readiness is not None and not readiness.ready: + if readiness is not None and not readiness.queryable: return None if path_arg: @@ -369,7 +373,7 @@ async def handle_symbol_lookup( } ) - if readiness is not None and not readiness.ready: + if readiness is not None and not readiness.queryable: return _index_unavailable_response(readiness, "symbol_lookup", symbol=symbol) ctx = _resolve_ctx(repo_resolver, repository) @@ -429,6 +433,9 @@ async def handle_symbol_lookup( response_data["_usage_hint"] = ( f"To view definition: Read(file_path='{translated_path}', offset={offset}, limit=20)" ) + if readiness is not None and readiness.serving_stale: + response_data["readiness"] = readiness.to_dict() + response_data["note"] = _stale_note(readiness.to_dict()) return [types.TextContent(type="text", text=_ensure_response(response_data))] else: response_data = { @@ -438,6 +445,8 @@ async def handle_symbol_lookup( } if readiness is not None: response_data["readiness"] = readiness.to_dict() + if readiness.serving_stale: + response_data["note"] = _stale_note(readiness.to_dict()) if readiness.coverage_degraded: # The symbol may live in a language this generation left out # because its grammar was unavailable (#117). @@ -451,6 +460,16 @@ async def handle_symbol_lookup( return [types.TextContent(type="text", text=_ensure_response(response_data))] +def _stale_note(readiness: dict) -> str: + """Explain results served from an older published generation (#145).""" + indexed = str(readiness.get("last_indexed_commit") or "unknown")[:12] + target = str((readiness.get("rebuild") or {}).get("target_commit") or "a newer commit")[:12] + return ( + f"Results reflect the published index at commit {indexed}; a rebuild for " + f"{target} is in progress (readiness stale_commit)." + ) + + def _coverage_note(coverage: dict) -> str: languages = ", ".join(coverage.get("unavailable_languages") or []) or "unknown" return ( @@ -573,6 +592,13 @@ async def handle_search_code( history_repos = list(result.history_repos) include_source_metadata = result.include_source_metadata readiness = result.readiness + # Served from the published generation while a live rebuild indexes a + # newer commit: label it with the stale readiness (#145). + stale_readiness = ( + readiness + if isinstance(readiness, dict) and readiness.get("state") == "stale_commit" + else None + ) coverage = getattr(result, "coverage", None) if not (isinstance(coverage, dict) and coverage.get("state") == "degraded"): coverage = None @@ -725,12 +751,19 @@ async def handle_search_code( "indexing_in_progress": True, "note": "Initial index is still building — results may be incomplete", } - elif coverage is not None: - # Like indexing-in-progress, degraded coverage switches the bare - # list to the envelope so the caller sees what is missing (#117). + elif coverage is not None or stale_readiness is not None: + # Like indexing-in-progress, degraded coverage or stale results + # switch the bare list to the envelope so the caller sees what is + # missing or how old the results are (#117, #145). search_response = {"results": results_data, "query": query} else: search_response = results_data + if stale_readiness is not None and isinstance(search_response, dict): + search_response["readiness"] = stale_readiness + note = _stale_note(stale_readiness) + search_response["note"] = ( + f"{search_response['note']}; {note}" if search_response.get("note") else note + ) if coverage is not None and isinstance(search_response, dict): search_response["coverage"] = coverage note = _coverage_note(coverage) @@ -770,9 +803,14 @@ async def handle_search_code( ) if _indexing_active: response_data["indexing_in_progress"] = True + if stale_readiness is not None: + response_data["note"] = _stale_note(stale_readiness) if coverage is not None: response_data["coverage"] = coverage - response_data["note"] = _coverage_note(coverage) + note = _coverage_note(coverage) + response_data["note"] = ( + f"{response_data['note']}; {note}" if response_data.get("note") else note + ) return [types.TextContent(type="text", text=_ensure_response(response_data))] diff --git a/mcp_server/client.py b/mcp_server/client.py index ed16c3e0..7349a96c 100644 --- a/mcp_server/client.py +++ b/mcp_server/client.py @@ -235,7 +235,9 @@ def execute_search_service( if repo_resolver is not None else None ) - if readiness is not None and not readiness.ready: + # ``queryable`` also admits stale_commit while a live rebuild indexes a + # newer commit; the result then carries that stale readiness (#145). + if readiness is not None and not readiness.queryable: unavailable: IndexUnavailable | None = _index_unavailable(readiness) return _unavailable_search(options, unavailable) @@ -430,7 +432,7 @@ def symbol_lookup( str(repository) if repository is not None else None, workspace_root=self.workspace_root, ) - if readiness is not None and not readiness.ready: + if readiness is not None and not readiness.queryable: return ClientSymbolResult( symbol=symbol, found=False, diff --git a/mcp_server/core/repo_resolver.py b/mcp_server/core/repo_resolver.py index 39600f44..f830a6ab 100644 --- a/mcp_server/core/repo_resolver.py +++ b/mcp_server/core/repo_resolver.py @@ -80,9 +80,14 @@ def resolve(self, selector: str | Path) -> Optional[RepoContext]: return self._context_from_readiness(readiness) def resolve_ready(self, selector: str | Path) -> Optional[RepoContext]: - """Resolve only when this operation's own classification is ready.""" + """Resolve only when this operation's own classification is queryable. + + That is ``ready``, or ``stale_commit`` while a live rebuild indexes a + newer commit and the published generation keeps serving (#145). + Mutations still hold the writer lock, so no live rebuild can run then. + """ readiness = self.classify(selector) - if not readiness.ready: + if not readiness.queryable: return None ctx = self._context_from_readiness(readiness) return ctx if ctx is not None and self.is_current(ctx) else None @@ -100,7 +105,7 @@ def is_current(self, ctx: RepoContext) -> bool: != self._store_registry.binding(ctx.registry_entry) ): return False - return ReadinessClassifier.classify_registered(info).ready + return ReadinessClassifier.classify_registered(info).queryable except Exception: return False @@ -112,7 +117,12 @@ def mutate( if not self.is_current(ctx): raise RuntimeError("Repository generation changed before mutation") current = self.resolve_ready(ctx.workspace_root) - if current is None or current.generation_key != ctx.generation_key: + if ( + current is None + or current.generation_key != ctx.generation_key + # Mutations need a ready index, not one served stale (#145). + or not self.classify(ctx.workspace_root).ready + ): raise RuntimeError("Repository became unavailable before mutation") if self._index_manager is None: raise RuntimeError("Staged repository mutation owner is unavailable") diff --git a/mcp_server/health/repo_status.py b/mcp_server/health/repo_status.py index 7f857203..d3bd6f74 100644 --- a/mcp_server/health/repo_status.py +++ b/mcp_server/health/repo_status.py @@ -113,9 +113,15 @@ def build_health_row( ) rollout_status = _classify_rollout_status(readiness, artifact_health, staleness) rollout_remediation = _rollout_remediation(rollout_status, readiness) - query_status = "ready" if readiness.ready else "index_unavailable" + # While a live rebuild indexes a newer commit, query tools serve the + # published generation and label results stale_commit (#145). + query_status = ( + "ready" + if readiness.ready + else ("serving_stale" if readiness.serving_stale else "index_unavailable") + ) base_features = features or { - "lexical": {"status": "available" if readiness.ready else "unavailable"}, + "lexical": {"status": "available" if readiness.queryable else "unavailable"}, "semantic": {"status": "unavailable", "reason": "runtime_status_unavailable"}, "graph": {"status": "unavailable", "reason": "runtime_status_unavailable"}, "plugins": {"status": "unavailable", "reason": "runtime_status_unavailable"}, @@ -171,11 +177,20 @@ def build_health_row( "query_remediation": ( None if readiness.ready - else 'Use native search or follow the readiness remediation; query tools stay fail-closed with safe_fallback: "native_search".' + else ( + ( + "Results come from the published index at last_indexed_commit until the " + "in-progress rebuild publishes; re-check readiness for current results." + ) + if readiness.serving_stale + else 'Use native search or follow the readiness remediation; query tools stay fail-closed with safe_fallback: "native_search".' + ) ), "features": base_features, # Language coverage of the published generation (#117): additive, the # readiness state above stays ``ready`` while coverage is degraded. "coverage": readiness.coverage, "coverage_status": (readiness.coverage or {}).get("state"), + # A live staged rebuild (#145): additive, null when none runs. + "rebuild": readiness.rebuild, } diff --git a/mcp_server/health/repository_readiness.py b/mcp_server/health/repository_readiness.py index 9fb2e2f6..ce4443b6 100644 --- a/mcp_server/health/repository_readiness.py +++ b/mcp_server/health/repository_readiness.py @@ -14,6 +14,7 @@ from pathlib import Path from typing import Any, Optional +from mcp_server.indexing.lock_registry import live_rebuild_owner from mcp_server.storage.repo_identity import compute_repo_id from mcp_server.storage.sqlite_store import evaluate_chunk_scheme, read_grammar_degradation from mcp_server.utils.subprocess_env import get_full_env @@ -70,11 +71,36 @@ class RepositoryReadiness: #: their grammars were unavailable. Additive: ``state`` stays ``ready``. #: None when no index could be inspected. coverage: Optional[dict[str, Any]] = None + #: A staged rebuild whose owner is alive (Consiliency/Code-Index-MCP#145): + #: ``{"in_progress": True, "target_commit": ..., "started_at": ...}``. The + #: state above then describes the published generation, which keeps + #: serving queries until the build publishes. None when no live build runs. + rebuild: Optional[dict[str, Any]] = None @property def ready(self) -> bool: return self.state == RepositoryReadinessState.READY + @property + def serving_stale(self) -> bool: + """True while a live rebuild indexes a newer commit than the published one. + + Query tools then serve the published generation and label the results + ``stale_commit``; every other non-ready state stays fail-closed (#145). + """ + return bool( + self.state == RepositoryReadinessState.STALE_COMMIT + and self.rebuild + and self.current_commit + and self.last_indexed_commit + and self.current_commit != self.last_indexed_commit + ) + + @property + def queryable(self) -> bool: + """True when indexed query tools may serve the published generation.""" + return self.ready or self.serving_stale + @property def code(self) -> Optional[str]: return None if self.ready else self.state.value @@ -99,6 +125,7 @@ def to_dict(self) -> dict[str, Any]: "index_path": self.index_path, "remediation": self.remediation, "coverage": self.coverage, + "rebuild": self.rebuild, } @@ -394,6 +421,23 @@ def classify_registered( state = RepositoryReadinessState.READY remediation = None coverage = None + rebuild = None + if staleness_reason == "index_publication_pending": + # The published generation is untouched until the publish swap, so + # it may keep serving while the build's owner is alive (#145). A + # dead owner leaves the fail-closed missing_provenance below. + owner = live_rebuild_owner( + registered_path, + registration_id=getattr(repo_info, "registration_id", None), + published_generation=getattr(repo_info, "index_generation", None), + ) + if owner is not None: + staleness_reason = None + rebuild = { + "in_progress": True, + "target_commit": owner.get("target_commit"), + "started_at": owner.get("started_at"), + } if live_git_required and (current_branch is None or current_commit is None): state = RepositoryReadinessState.UNREGISTERED_REPOSITORY @@ -474,6 +518,7 @@ def classify_registered( index_path=str(index_path) if index_path else None, remediation=remediation, coverage=coverage, + rebuild=rebuild, ) @classmethod diff --git a/mcp_server/indexing/lock_registry.py b/mcp_server/indexing/lock_registry.py index 05b7af1d..60ad923b 100644 --- a/mcp_server/indexing/lock_registry.py +++ b/mcp_server/indexing/lock_registry.py @@ -1,10 +1,14 @@ """Per-repo reentrant lock registry (IF-0-P12-2).""" import fcntl +import json import os +import socket +import tempfile import threading import time from contextlib import contextmanager +from datetime import datetime, timezone from pathlib import Path from typing import Dict, Optional @@ -73,3 +77,152 @@ def acquire(self, repo_id: str, *, repo_path: Optional[Path] = None, timeout: fl # Module-level singleton (IF-0-P12-2) lock_registry: IndexingLockRegistry = IndexingLockRegistry() + + +# --------------------------------------------------------------------------- +# Live staged-build owner (Consiliency/Code-Index-MCP#145) +# +# A staged build holds the cross-process ``writer.lock`` for its whole run and +# leaves the published generation untouched until the publish swap. Readers may +# keep serving that published generation while the build runs, but only while +# its owner is provably alive: a crash mid-build must stay fail-closed. The +# owner record lives next to the writer lock; the lock itself is the liveness +# signal (the kernel drops a flock when its process dies), and the recorded +# pid, process start time and host rule out a different process holding it. + +_OWNER_FILE = "rebuild-owner.json" + + +def _index_lock_dir(repo_path: Path) -> Path: + return Path(repo_path).resolve() / ".mcp-index" + + +def _process_start_time(pid: int) -> Optional[str]: + """Return the kernel start time of ``pid`` (Linux ``/proc``), else None.""" + try: + stat = Path(f"/proc/{pid}/stat").read_text() + except OSError: + return None + # The command name may contain spaces or parentheses; fields follow the last ")". + fields = stat.rsplit(")", 1)[-1].split() + # Field 22 (starttime) is the 20th field after "pid (comm)". + return fields[19] if len(fields) > 19 else None + + +def _pid_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + return True + + +def writer_lock_held(repo_path: Path) -> bool: + """Return True when some process currently holds the repository writer lock. + + Probes with a non-blocking shared lock on a fresh descriptor, so a holder in + this same process is detected too. Never creates the lock file. + """ + try: + fd = os.open(_index_lock_dir(repo_path) / "writer.lock", os.O_RDONLY) + except OSError: + return False + try: + try: + fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB) + except BlockingIOError: + return True + except OSError: + return False + fcntl.flock(fd, fcntl.LOCK_UN) + return False + finally: + os.close(fd) + + +def record_rebuild_owner( + repo_path: Path, + *, + registration_id: Optional[str], + published_generation: Optional[str], + target_commit: str, +) -> Optional[dict]: + """Record this process as the owner of a staged build; None if unwritable.""" + owner = { + "token": os.urandom(16).hex(), + "pid": os.getpid(), + "process_start": _process_start_time(os.getpid()), + "host": socket.gethostname(), + "registration_id": registration_id, + "published_generation": published_generation, + "target_commit": target_commit, + "started_at": datetime.now(timezone.utc).isoformat(), + } + directory = _index_lock_dir(repo_path) + temporary = None + try: + directory.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=f".{_OWNER_FILE}.", dir=directory) + temporary = Path(name) + with os.fdopen(fd, "w") as target: + json.dump(owner, target) + os.replace(temporary, directory / _OWNER_FILE) + temporary = None + except OSError: + return None + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + return owner + + +def clear_rebuild_owner(repo_path: Path, token: str) -> None: + """Remove the owner record if it is still ours. Never raises.""" + path = _index_lock_dir(repo_path) / _OWNER_FILE + try: + current = json.loads(path.read_text()) + if isinstance(current, dict) and current.get("token") == token: + path.unlink(missing_ok=True) + except OSError, ValueError: + pass + + +def live_rebuild_owner( + repo_path: Path, + *, + registration_id: Optional[str], + published_generation: Optional[str], +) -> Optional[dict]: + """Return the owner record of a staged build whose owner is alive, else None. + + Alive means: the record names this registration and the generation that is + still published, it was written on this host, its pid exists with the same + start time, and the writer lock is held. Any doubt returns None, which + keeps the caller fail-closed. + """ + try: + owner = json.loads((_index_lock_dir(repo_path) / _OWNER_FILE).read_text()) + except OSError, ValueError: + return None + if not isinstance(owner, dict): + return None + pid = owner.get("pid") + if ( + not isinstance(pid, int) + or pid <= 0 + or owner.get("registration_id") != registration_id + or owner.get("published_generation") != published_generation + or owner.get("host") != socket.gethostname() + or not _pid_alive(pid) + ): + return None + recorded_start = owner.get("process_start") + if recorded_start is not None and _process_start_time(pid) != recorded_start: + return None + if not writer_lock_held(repo_path): + return None + return owner diff --git a/mcp_server/storage/git_index_manager.py b/mcp_server/storage/git_index_manager.py index 287b4a0e..174c2c9d 100644 --- a/mcp_server/storage/git_index_manager.py +++ b/mcp_server/storage/git_index_manager.py @@ -52,7 +52,7 @@ published_grammar_degradation, ) from ..indexing.change_detector import ChangeDetector -from ..indexing.lock_registry import lock_registry +from ..indexing.lock_registry import clear_rebuild_owner, lock_registry, record_rebuild_owner from ..plugins.language_registry import get_language_by_extension from ..utils import grammar_cache from ..utils.memory_release import release_rebuild_memory @@ -1448,8 +1448,19 @@ def _rebuild_repository_index_locked( full_call_started = False full_call_completed = False mutation_admitted = False + build_owner = None try: + # Recorded before the fence goes up, so readers keep serving the + # published generation for the whole build while this owner is + # alive; cleared in ``finally`` (#145). If it cannot be written, + # readers stay fail-closed exactly as before. + build_owner = record_rebuild_owner( + repo_path, + registration_id=repo_info.registration_id, + published_generation=repo_info.index_generation, + target_commit=current_commit, + ) self.registry.begin_generation_mutation( repo_id, expected_registration_id=repo_info.registration_id, @@ -1722,10 +1733,15 @@ def deferred(path: str) -> bool: raise StagedRebuildError("Staged index has no durable rows") self._rebuild_checkpoint("before_replacement") - self._release_runtime_handles(repo_id, repo_info, stage_ctx) + quarantine = readiness.state in _QUARANTINE_REBUILD_STATES + # A served (ready or stale) live generation keeps its handles until + # the publish swap, so queries admitted during the build finish on + # it; a quarantined one is released before its bytes move (#145). + self._release_runtime_handles(repo_id, repo_info, stage_ctx, live=quarantine) stage_store = None + previous_owner = replace(repo_info) quarantine_path = None - if readiness.state in _QUARANTINE_REBUILD_STATES: + if quarantine: quarantine_path = self._quarantine_active_index(active_path, readiness.state) self._fsync_generation(generation_path) self._rebuild_checkpoint("after_replacement") @@ -1759,6 +1775,8 @@ def deferred(path: str) -> bool: repo_info.last_indexed_branch = current_branch repo_info.staleness_reason = None ReadinessClassifier.clear_index_inspection_cache() + if not quarantine: + self._release_superseded_live_handles(repo_id, previous_owner) self._prune_superseded_generations( generation_dir, live_generation=generation, @@ -1863,6 +1881,8 @@ def deferred(path: str) -> bool: stage_store.close() if stage_dir is not None: shutil.rmtree(stage_dir, ignore_errors=True) + if build_owner is not None: + clear_rebuild_owner(repo_path, build_owner["token"]) if mutation_admitted: release_rebuild_memory(repo_id) @@ -3350,21 +3370,41 @@ def _restore_zero_summary_runtime_if_needed( self._cleanup_runtime_snapshot(snapshot) return None + def _release_superseded_live_handles(self, repo_id: str, previous_owner: Any) -> None: + """Release the handles of the generation a publish just superseded. + + Runs after ``publish_generation``: a query still holding the old store + finishes on its open connection and is then refused by its generation + recheck. Never raises, because the publication already happened (#145). + """ + try: + if self.store_registry is not None: + self.store_registry.close(repo_id, expected_owner=previous_owner) + if self.dispatcher is not None and hasattr(self.dispatcher, "evict_repository_state"): + self.dispatcher.evict_repository_state( + repo_id, previous_owner.path, expected_owner=previous_owner + ) + except Exception as exc: + logger.warning("Superseded generation handles remain open: %s", type(exc).__name__) + def _release_runtime_handles( self, repo_id: str, repo_info: Any, ctx: Optional[RepoContext], + *, + live: bool = True, ) -> None: - if self.store_registry is not None: + if live and self.store_registry is not None: self.store_registry.close(repo_id, expected_owner=repo_info) sqlite_store = getattr(ctx, "sqlite_store", None) if ctx is not None else None if sqlite_store is not None: sqlite_store.close() if self.dispatcher is not None and hasattr(self.dispatcher, "evict_repository_state"): - self.dispatcher.evict_repository_state( - repo_id, repo_info.path, expected_owner=repo_info - ) + if live: + self.dispatcher.evict_repository_state( + repo_id, repo_info.path, expected_owner=repo_info + ) if ctx is not None and ctx.staging: self.dispatcher.evict_repository_state( repo_id, repo_info.path, expected_owner=ctx.registry_entry diff --git a/mcp_server/storage/store_registry.py b/mcp_server/storage/store_registry.py index 2940a71e..dc8ca66f 100644 --- a/mcp_server/storage/store_registry.py +++ b/mcp_server/storage/store_registry.py @@ -9,6 +9,7 @@ from typing import Dict from mcp_server.core.path_resolver import PathResolver +from mcp_server.indexing.lock_registry import live_rebuild_owner from mcp_server.storage.connection_pool import ConnectionPool from mcp_server.storage.repository_registry import RepositoryRegistry from mcp_server.storage.sqlite_store import SQLiteStore @@ -75,10 +76,23 @@ def is_current(self, repo_id: str, store: SQLiteStore) -> bool: info = self._registry.get(repo_id) return ( info is not None - and not info.staleness_reason + and (not info.staleness_reason or self._serving_during_rebuild(info)) and store.registry_binding == self.binding(info) ) + @staticmethod + def _serving_during_rebuild(info) -> bool: + """The published generation stays current while a live owner rebuilds it (#145).""" + return ( + info.staleness_reason == "index_publication_pending" + and live_rebuild_owner( + Path(info.path), + registration_id=getattr(info, "registration_id", None), + published_generation=getattr(info, "index_generation", None), + ) + is not None + ) + def get(self, repo_id: str) -> SQLiteStore: """Return a store bound to the current registration and physical generation.""" with self._get_build_lock(repo_id): diff --git a/tests/test_health_surface.py b/tests/test_health_surface.py index 3052e8de..cfa9ba60 100644 --- a/tests/test_health_surface.py +++ b/tests/test_health_surface.py @@ -36,6 +36,7 @@ # Additive language coverage of the published generation (#117). "coverage", "coverage_status", + "rebuild", } diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py new file mode 100644 index 00000000..10e1c47b --- /dev/null +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -0,0 +1,368 @@ +"""Queries keep serving the published generation during a staged rebuild (#145). + +Owner decision: while a staged build runs and its owner is alive, readiness +classifies against the published generation (``ready`` for a same-commit +rebuild, ``stale_commit`` while a newer commit is indexed) with an additive +``rebuild`` object, and ``search_code``/``symbol_lookup`` serve the published +generation. A dead owner keeps today's fail-closed ``missing_provenance``. +""" + +from __future__ import annotations + +import importlib +import json +import os +import socket +import subprocess +import sys +from pathlib import Path + +import pytest + +from mcp_server.core.repo_resolver import run_repository_mutation +from mcp_server.health.repository_readiness import ReadinessClassifier, RepositoryReadinessState +from tests.fixtures.multi_repo import boot_test_server, build_temp_repo, git, git_head + +# ``mcp_server.indexing`` re-exports the ``lock_registry`` singleton under the +# module's own name, so import the module explicitly. +locks = importlib.import_module("mcp_server.indexing.lock_registry") + +SEED = { + "alpha.py": "def alpha_token():\n return 1\n\n\nclass AlphaSymbol:\n pass\n", +} + + +def _owner_file(path: Path) -> Path: + return path / ".mcp-index" / "rebuild-owner.json" + + +def _dead_pid() -> int: + child = subprocess.Popen([sys.executable, "-c", "pass"]) + child.wait() + return child.pid + + +def _search(server, path: Path, query: str) -> dict | list: + return server.call_tool("search_code", {"query": query, "repository": str(path)}) + + +def _symbol(server, path: Path, symbol: str) -> dict: + return server.call_tool("symbol_lookup", {"symbol": symbol, "repository": str(path)}) + + +def _result_files(response) -> list[str]: + results = response["results"] if isinstance(response, dict) else response + return [Path(item["file"]).name for item in results] + + +# --------------------------------------------------------------------------- +# Owner record and liveness +# --------------------------------------------------------------------------- + + +def test_live_owner_requires_matching_identity_and_a_held_writer_lock(tmp_path): + repo = tmp_path / "repo" + repo.mkdir() + owner = locks.record_rebuild_owner( + repo, registration_id="reg", published_generation="gen", target_commit="c" * 40 + ) + assert owner is not None and owner["pid"] == os.getpid() + assert owner["host"] == socket.gethostname() + identity = {"registration_id": "reg", "published_generation": "gen"} + + # The pid is alive, but nobody holds the writer lock: not a live build. + assert locks.live_rebuild_owner(repo, **identity) is None + with locks.lock_registry.acquire("repo", repo_path=repo): + assert locks.writer_lock_held(repo) + live = locks.live_rebuild_owner(repo, **identity) + assert live is not None and live["target_commit"] == "c" * 40 + # A record for another registration or generation is not this build. + assert ( + locks.live_rebuild_owner(repo, registration_id="other", published_generation="gen") + is None + ) + assert ( + locks.live_rebuild_owner(repo, registration_id="reg", published_generation="old") + is None + ) + assert not locks.writer_lock_held(repo) + + # Someone else's token never clears the record; ours does. + locks.clear_rebuild_owner(repo, "not-the-token") + assert _owner_file(repo).exists() + locks.clear_rebuild_owner(repo, owner["token"]) + assert not _owner_file(repo).exists() + + +@pytest.mark.parametrize("tamper", ["dead_pid", "reused_pid", "other_host", "unreadable"]) +def test_owner_that_is_not_provably_alive_is_dead(tmp_path, tamper): + repo = tmp_path / "repo" + repo.mkdir() + locks.record_rebuild_owner( + repo, registration_id="reg", published_generation="gen", target_commit="c" * 40 + ) + record = json.loads(_owner_file(repo).read_text()) + if tamper == "dead_pid": + record["pid"] = _dead_pid() + elif tamper == "reused_pid": + record["process_start"] = "1" + elif tamper == "other_host": + record["host"] = record["host"] + "-elsewhere" + if tamper == "unreadable": + _owner_file(repo).write_text("{not json") + else: + _owner_file(repo).write_text(json.dumps(record)) + with locks.lock_registry.acquire("repo", repo_path=repo): + assert ( + locks.live_rebuild_owner(repo, registration_id="reg", published_generation="gen") + is None + ) + + +# --------------------------------------------------------------------------- +# Same-commit rebuild with a live owner +# --------------------------------------------------------------------------- + + +def test_same_commit_rebuild_stays_ready_and_serves_the_published_generation(tmp_path): + path, repo_id = build_temp_repo(tmp_path, "same", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + ctx = resolver.resolve_ready(path) + published = server.registry.get(repo_id) + head = git_head(path) + observed: dict = {} + + def operation(stage): + registry_entry = server.registry.get(repo_id) + assert registry_entry.staleness_reason == "index_publication_pending" + readiness = resolver.classify(path) + observed["readiness"] = readiness + # Readers resolve the published file, never the stage. + reader = resolver.resolve_ready(path) + assert reader is not None + assert Path(reader.sqlite_store.db_path) == Path(published.index_path) + assert Path(stage.sqlite_store.db_path) != Path(published.index_path) + assert resolver.is_current(ctx) + observed["search"] = _search(server, path, "alpha_token") + observed["symbol"] = _symbol(server, path, "AlphaSymbol") + observed["status"] = server.call_tool("get_status", {}) + return {"failed_files": 0} + + run_repository_mutation(resolver, ctx, operation) + + readiness = observed["readiness"] + assert readiness.state == RepositoryReadinessState.READY + assert readiness.rebuild["in_progress"] is True + assert readiness.rebuild["target_commit"] == head + assert readiness.rebuild["started_at"] + assert readiness.to_dict()["rebuild"] == readiness.rebuild + assert "alpha.py" in _result_files(observed["search"]) + assert observed["symbol"]["symbol"] == "AlphaSymbol" + assert "error" not in observed["symbol"] + + # Publication cleared the owner and the rebuild marker. + assert not _owner_file(path).exists() + after = resolver.classify(path) + assert after.ready and after.rebuild is None + assert server.registry.get(repo_id).index_generation != published.index_generation + + +# --------------------------------------------------------------------------- +# Newer-commit rebuild with a live owner +# --------------------------------------------------------------------------- + + +def test_newer_commit_rebuild_reports_stale_and_serves_with_stale_metadata(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "newer", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + manager = resolver._index_manager + indexed = git_head(path) + (path / "beta.py").write_text("def beta_token():\n return 2\n") + git(path, "add", "beta.py") + git(path, "commit", "-m", "add beta") + target = git_head(path) + observed: dict = {} + original = manager._rebuild_checkpoint + + def checkpoint(stage): + if stage == "before_publish" and "readiness" not in observed: + observed["readiness"] = resolver.classify(path) + observed["search"] = _search(server, path, "alpha_token") + observed["symbol"] = _symbol(server, path, "AlphaSymbol") + observed["missing"] = _symbol(server, path, "NoSuchSymbol") + return original(stage) + + monkeypatch.setattr(manager, "_rebuild_checkpoint", checkpoint) + result = manager.sync_repository_index(repo_id) + assert result.action in {"incremental_update", "full_index"}, result + + readiness = observed["readiness"] + assert readiness.state == RepositoryReadinessState.STALE_COMMIT + assert readiness.serving_stale and readiness.queryable + assert readiness.last_indexed_commit == indexed + assert readiness.current_commit == target + assert readiness.rebuild["target_commit"] == target + + search = observed["search"] + assert isinstance(search, dict), search + assert "alpha.py" in _result_files(search) + assert "beta.py" not in _result_files(search) + assert search["readiness"]["state"] == "stale_commit" + assert search["readiness"]["last_indexed_commit"] == indexed + assert search["readiness"]["current_commit"] == target + assert search["readiness"]["rebuild"]["in_progress"] is True + assert "stale_commit" in search["note"] + + symbol = observed["symbol"] + assert symbol["symbol"] == "AlphaSymbol" + assert symbol["readiness"]["state"] == "stale_commit" + assert observed["missing"]["result"] == "not_found" + assert observed["missing"]["readiness"]["state"] == "stale_commit" + + assert not _owner_file(path).exists() + after = resolver.classify(path) + assert after.ready and after.rebuild is None + assert after.last_indexed_commit == target + + +def test_stale_commit_without_a_rebuild_stays_fail_closed(tmp_path): + path, repo_id = build_temp_repo(tmp_path, "plainstale", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + (path / "beta.py").write_text("x = 1\n") + git(path, "add", "beta.py") + git(path, "commit", "-m", "advance") + readiness = server.repo_resolver.classify(path) + assert readiness.state == RepositoryReadinessState.STALE_COMMIT + assert readiness.rebuild is None and not readiness.queryable + assert _search(server, path, "alpha_token")["code"] == "index_unavailable" + assert _symbol(server, path, "AlphaSymbol")["code"] == "index_unavailable" + + +# --------------------------------------------------------------------------- +# Dead owner +# --------------------------------------------------------------------------- + + +def test_dead_owner_keeps_missing_provenance_and_fails_closed(tmp_path): + path, repo_id = build_temp_repo(tmp_path, "dead", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + info = server.registry.get(repo_id) + server.registry.begin_generation_mutation( + repo_id, + expected_registration_id=info.registration_id, + expected_generation=info.index_generation, + ) + # A crashed build: the record names it, but its process is gone and + # the kernel released its writer lock. + locks.record_rebuild_owner( + path, + registration_id=info.registration_id, + published_generation=info.index_generation, + target_commit=git_head(path), + ) + record = json.loads(_owner_file(path).read_text()) + record["pid"] = _dead_pid() + _owner_file(path).write_text(json.dumps(record)) + + readiness = server.repo_resolver.classify(path) + assert readiness.state == RepositoryReadinessState.MISSING_PROVENANCE + assert readiness.rebuild is None and not readiness.queryable + assert server.repo_resolver.resolve_ready(path) is None + assert _search(server, path, "alpha_token")["code"] == "index_unavailable" + assert _symbol(server, path, "AlphaSymbol")["code"] == "index_unavailable" + + # Even with the writer lock held by a live process, a dead recorded + # owner is not this build. + with locks.lock_registry.acquire(repo_id, repo_path=path): + again = ReadinessClassifier.classify_registered(server.registry.get(repo_id)) + assert again.state == RepositoryReadinessState.MISSING_PROVENANCE + + # And a pending generation with no owner record at all stays fenced. + _owner_file(path).unlink() + assert ( + server.repo_resolver.classify(path).state == RepositoryReadinessState.MISSING_PROVENANCE + ) + + +# --------------------------------------------------------------------------- +# Failure and abort clear the owner +# --------------------------------------------------------------------------- + + +class _Abort(BaseException): + """Stands in for KeyboardInterrupt/SystemExit escaping the build.""" + + +@pytest.mark.parametrize("outcome", ["error", "exception", "abort"]) +def test_failed_or_aborted_build_clears_the_owner_and_stays_fail_closed(tmp_path, outcome): + path, repo_id = build_temp_repo(tmp_path, f"fail-{outcome}", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + ctx = resolver.resolve_ready(path) + seen: dict = {} + + def operation(stage): + seen["owner"] = _owner_file(path).exists() + seen["ready"] = resolver.classify(path).ready + if outcome == "exception": + raise RuntimeError("injected") + if outcome == "abort": + raise _Abort() + return {"failed_files": 1} + + expected = _Abort if outcome == "abort" else (RuntimeError, ValueError) + with pytest.raises(expected): + run_repository_mutation(resolver, ctx, operation) + + assert seen == {"owner": True, "ready": True} + assert not _owner_file(path).exists() + after = resolver.classify(path) + assert after.state == RepositoryReadinessState.MISSING_PROVENANCE + assert after.rebuild is None + assert _search(server, path, "alpha_token")["code"] == "index_unavailable" + + +# --------------------------------------------------------------------------- +# Publish swap during a query +# --------------------------------------------------------------------------- + + +def test_publish_swap_mid_query_finishes_on_the_old_file_then_fails_closed(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "swap", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + manager = resolver._index_manager + before = server.registry.get(repo_id) + old_file = Path(before.index_path) + original_search = server.dispatcher.search + observed: dict = {} + + def search(ctx, query, **kwargs): + assert Path(ctx.sqlite_store.db_path) == old_file + with ctx.sqlite_store._get_connection() as connection: + observed["before"] = connection.execute("SELECT COUNT(*) FROM files").fetchone()[0] + # The rebuild publishes a new generation while this reader + # still holds its connection to the old file. + observed["rebuild"] = manager.rebuild_repository_index(repo_id) + observed["after"] = connection.execute("SELECT COUNT(*) FROM files").fetchone()[0] + observed["old_file_kept"] = old_file.exists() + return original_search(ctx, query, **kwargs) + + monkeypatch.setattr(server.dispatcher, "search", search) + response = _search(server, path, "alpha_token") + + assert observed["rebuild"].action == "full_index", observed["rebuild"] + assert observed["before"] == observed["after"] > 0 + # Retention keeps the superseded generation (live + at least one previous). + assert observed["old_file_kept"] + assert old_file.exists() + assert server.registry.get(repo_id).index_path != before.index_path + # The generation recheck refuses results that straddled the swap. + assert response["code"] == "index_unavailable" + assert response["safe_fallback"] == "native_search" + + monkeypatch.setattr(server.dispatcher, "search", original_search) + retry = _search(server, path, "alpha_token") + assert "alpha.py" in _result_files(retry) diff --git a/tests/test_repository_readiness.py b/tests/test_repository_readiness.py index 33aae0b0..08447ffb 100644 --- a/tests/test_repository_readiness.py +++ b/tests/test_repository_readiness.py @@ -162,8 +162,11 @@ def test_serialized_response_keys(tmp_path): "index_path", "remediation", "coverage", + "rebuild", } assert readiness.to_dict()["state"] == "ready" + # No staged build in progress (#145). + assert readiness.to_dict()["rebuild"] is None assert readiness.to_dict()["code"] is None # No degradation marker: complete coverage (#117). assert readiness.to_dict()["coverage"] == {"state": "complete"} diff --git a/tests/test_v13_state.py b/tests/test_v13_state.py index f2d68578..69675c66 100644 --- a/tests/test_v13_state.py +++ b/tests/test_v13_state.py @@ -196,7 +196,9 @@ def commit(path): @pytest.mark.parametrize("outcome", ["clean", "error", "cancelled", "exception", "unregister"]) -def test_scoped_mutation_fences_reads_and_publishes_only_clean_outcomes(tmp_path, outcome): +def test_scoped_mutation_serves_published_reads_and_publishes_only_clean_outcomes( + tmp_path, outcome +): from mcp_server.core.repo_resolver import run_repository_mutation from tests.fixtures.multi_repo import boot_test_server, build_temp_repo @@ -209,8 +211,10 @@ def test_scoped_mutation_fences_reads_and_publishes_only_clean_outcomes(tmp_path def mutate(current): assert current.staging assert current.sqlite_store.db_path != ctx.sqlite_store.db_path - assert not resolver.is_current(ctx) - assert not resolver.classify(path).ready + # The live owner keeps the published generation serving (#145). + assert resolver.is_current(ctx) + during = resolver.classify(path) + assert during.ready and during.rebuild["in_progress"] is True assert server.registry.get(repo_id).staleness_reason == "index_publication_pending" with current.sqlite_store._get_connection() as conn: conn.execute("UPDATE files SET language = 'synthetic'") From 7f340cf4cfa96fb18a96960078aa33ad8ce9ecd0 Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sat, 21 Nov 2026 21:20:45 -0500 Subject: [PATCH 2/8] fix(readiness): serve during a rebuild only for the current clean source (#145) Review follow-up for #162. - The rebuild overlay now applies only while the live owner's target_commit equals the freshly observed HEAD and the tracked tree is clean. A HEAD that moved away from the build's target, or tracked edits, fall back to the fail-closed missing_provenance. serving_stale also requires rebuild.target_commit == current_commit. - An owner whose process start time was not recorded, or cannot be read now, is not provably alive and counts as dead. The start time comes from Linux /proc, falling back to psutil create_time() (a core dependency) on hosts without /proc. Refs Consiliency/Code-Index-MCP#145 Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 14 +- mcp_server/health/repository_readiness.py | 15 +- mcp_server/indexing/lock_registry.py | 34 ++++- tests/test_issue_145_serve_during_rebuild.py | 140 +++++++++++++++++++ 4 files changed, 190 insertions(+), 13 deletions(-) diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 4733c828..2f61d9ae 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -27,16 +27,20 @@ the build's owner is alive. The owner is recorded next to the repository's `writer.lock` (`.mcp-index/rebuild-owner.json`: pid, process start time, host, registration and published generation); it counts as alive only while that process still exists with the same start time on this host and holds the -writer lock. Readiness then classifies the published generation and adds a -`rebuild` object, `{"in_progress": true, "target_commit": "...", -"started_at": "..."}` (`null` when no live build runs; also on `get_status` -repository rows): +writer lock. A start time that cannot be read (Linux `/proc`, otherwise +psutil) means the owner is not provably alive. While the live build targets +the checkout as it is now (HEAD equals the build's `target_commit` and the +tracked tree is clean), readiness classifies the published generation and adds +a `rebuild` object, `{"in_progress": true, "target_commit": "...", +"started_at": "..."}` (`null` otherwise; also on `get_status` repository +rows): | Situation during a staged build | Readiness before | Readiness now | `search_code` / `symbol_lookup` | |---|---|---|---| | Live owner, rebuild of the published commit (forced or repair) | `missing_provenance` | `ready` + `rebuild` | Served from the published generation, unchanged response shape | | Live owner, indexing a newer commit | `missing_provenance` | `stale_commit` + `rebuild` | Served from the published generation; the response carries `readiness` (`state: "stale_commit"`, `last_indexed_commit`, `current_commit`, `rebuild`) and a `note`, and `search_code` returns its envelope instead of the bare list | -| Owner dead (crash mid-build) or unprovable (no record, other host, lock not held) | `missing_provenance` | `missing_provenance` | `index_unavailable`, `safe_fallback: "native_search"` until recovery rebuilds | +| Owner dead (crash mid-build) or unprovable (no record, other host, lock not held, no readable start time) | `missing_provenance` | `missing_provenance` | `index_unavailable`, `safe_fallback: "native_search"` until recovery rebuilds | +| Live owner, but HEAD moved away from the build's target or tracked files are edited | `missing_provenance` | `missing_provenance` | `index_unavailable` | | Build failed (`partial_index_failure`) | `missing_provenance` | `missing_provenance` | `index_unavailable` | `stale_commit` without a live rebuild, and every other non-ready state, stay diff --git a/mcp_server/health/repository_readiness.py b/mcp_server/health/repository_readiness.py index ce4443b6..4d43d456 100644 --- a/mcp_server/health/repository_readiness.py +++ b/mcp_server/health/repository_readiness.py @@ -94,6 +94,7 @@ def serving_stale(self) -> bool: and self.current_commit and self.last_indexed_commit and self.current_commit != self.last_indexed_commit + and self.rebuild.get("target_commit") == self.current_commit ) @property @@ -424,14 +425,22 @@ def classify_registered( rebuild = None if staleness_reason == "index_publication_pending": # The published generation is untouched until the publish swap, so - # it may keep serving while the build's owner is alive (#145). A - # dead owner leaves the fail-closed missing_provenance below. + # it may keep serving while the build's owner is alive (#145) and + # that build targets the checkout as it is now: HEAD is the build's + # commit and the tracked tree is clean. A dead owner, a HEAD that + # moved away from the target, or tracked edits leave the + # fail-closed missing_provenance below. owner = live_rebuild_owner( registered_path, registration_id=getattr(repo_info, "registration_id", None), published_generation=getattr(repo_info, "index_generation", None), ) - if owner is not None: + if ( + owner is not None + and current_commit + and owner.get("target_commit") == current_commit + and tracked_tree_clean + ): staleness_reason = None rebuild = { "in_progress": True, diff --git a/mcp_server/indexing/lock_registry.py b/mcp_server/indexing/lock_registry.py index 60ad923b..52c0ff92 100644 --- a/mcp_server/indexing/lock_registry.py +++ b/mcp_server/indexing/lock_registry.py @@ -97,8 +97,8 @@ def _index_lock_dir(repo_path: Path) -> Path: return Path(repo_path).resolve() / ".mcp-index" -def _process_start_time(pid: int) -> Optional[str]: - """Return the kernel start time of ``pid`` (Linux ``/proc``), else None.""" +def _proc_start_time(pid: int) -> Optional[str]: + """Return the kernel start time of ``pid`` from Linux ``/proc``, else None.""" try: stat = Path(f"/proc/{pid}/stat").read_text() except OSError: @@ -106,7 +106,26 @@ def _process_start_time(pid: int) -> Optional[str]: # The command name may contain spaces or parentheses; fields follow the last ")". fields = stat.rsplit(")", 1)[-1].split() # Field 22 (starttime) is the 20th field after "pid (comm)". - return fields[19] if len(fields) > 19 else None + return f"proc:{fields[19]}" if len(fields) > 19 else None + + +def _psutil_start_time(pid: int) -> Optional[str]: + """Return the process creation time from psutil (macOS and others), else None.""" + try: + import psutil + + return f"psutil:{psutil.Process(pid).create_time()!r}" + except Exception: # noqa: BLE001 - no identity means not provably alive + return None + + +def _process_start_time(pid: int) -> Optional[str]: + """Return a stable start-time identity for ``pid``, or None when unavailable. + + None means the owner's identity cannot be proven, and callers treat that + as a dead owner (fail closed). + """ + return _proc_start_time(pid) or _psutil_start_time(pid) def _pid_alive(pid: int) -> bool: @@ -202,7 +221,8 @@ def live_rebuild_owner( Alive means: the record names this registration and the generation that is still published, it was written on this host, its pid exists with the same start time, and the writer lock is held. Any doubt returns None, which - keeps the caller fail-closed. + keeps the caller fail-closed; that includes a start time that was not + recorded or cannot be read now, since a reused pid would otherwise pass. """ try: owner = json.loads((_index_lock_dir(repo_path) / _OWNER_FILE).read_text()) @@ -221,7 +241,11 @@ def live_rebuild_owner( ): return None recorded_start = owner.get("process_start") - if recorded_start is not None and _process_start_time(pid) != recorded_start: + if ( + not isinstance(recorded_start, str) + or not recorded_start + or _process_start_time(pid) != recorded_start + ): return None if not writer_lock_held(repo_path): return None diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py index 10e1c47b..9d7da53b 100644 --- a/tests/test_issue_145_serve_during_rebuild.py +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -119,6 +119,45 @@ def test_owner_that_is_not_provably_alive_is_dead(tmp_path, tamper): ) +@pytest.mark.parametrize("unavailable", ["when_recorded", "when_checked"]) +def test_owner_without_a_provable_start_time_is_dead(tmp_path, monkeypatch, unavailable): + # A host without /proc (or a psutil failure) cannot rule out a reused pid, + # so the owner is not provably alive even while a writer holds the lock. + repo = tmp_path / "repo" + repo.mkdir() + if unavailable == "when_recorded": + monkeypatch.setattr(locks, "_process_start_time", lambda pid: None) + owner = locks.record_rebuild_owner( + repo, registration_id="reg", published_generation="gen", target_commit="c" * 40 + ) + assert owner is not None + if unavailable == "when_recorded": + assert owner["process_start"] is None + else: + monkeypatch.setattr(locks, "_process_start_time", lambda pid: None) + with locks.lock_registry.acquire("repo", repo_path=repo): + assert ( + locks.live_rebuild_owner(repo, registration_id="reg", published_generation="gen") + is None + ) + + +def test_start_time_falls_back_to_psutil_without_proc(tmp_path, monkeypatch): + repo = tmp_path / "repo" + repo.mkdir() + monkeypatch.setattr(locks, "_proc_start_time", lambda pid: None) + owner = locks.record_rebuild_owner( + repo, registration_id="reg", published_generation="gen", target_commit="c" * 40 + ) + assert owner["process_start"].startswith("psutil:") + identity = {"registration_id": "reg", "published_generation": "gen"} + with locks.lock_registry.acquire("repo", repo_path=repo): + assert locks.live_rebuild_owner(repo, **identity) is not None + # Without any start-time source the same record is no longer provable. + monkeypatch.setattr(locks, "_psutil_start_time", lambda pid: None) + assert locks.live_rebuild_owner(repo, **identity) is None + + # --------------------------------------------------------------------------- # Same-commit rebuild with a live owner # --------------------------------------------------------------------------- @@ -227,6 +266,107 @@ def checkpoint(stage): assert after.last_indexed_commit == target +def test_head_moving_away_from_the_rebuild_target_fails_closed(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "moved", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + manager = resolver._index_manager + (path / "beta.py").write_text("def beta_token():\n return 2\n") + git(path, "add", "beta.py") + git(path, "commit", "-m", "add beta") + target = git_head(path) + observed: dict = {} + original = manager._rebuild_checkpoint + + def checkpoint(stage): + if stage == "before_provenance" and "readiness" not in observed: + # HEAD moves past the commit the live build is indexing. + (path / "gamma.py").write_text("gamma = 3\n") + git(path, "add", "gamma.py") + git(path, "commit", "-m", "add gamma") + observed["readiness"] = resolver.classify(path) + observed["search"] = _search(server, path, "alpha_token") + observed["symbol"] = _symbol(server, path, "AlphaSymbol") + return original(stage) + + monkeypatch.setattr(manager, "_rebuild_checkpoint", checkpoint) + result = manager.sync_repository_index(repo_id) + + readiness = observed["readiness"] + assert readiness.current_commit != target + assert readiness.state == RepositoryReadinessState.MISSING_PROVENANCE + assert readiness.rebuild is None + assert not readiness.queryable and not readiness.serving_stale + assert observed["search"]["code"] == "index_unavailable" + assert observed["symbol"]["code"] == "index_unavailable" + # The build itself refuses to publish the moved source. + assert result.action == "failed" + assert "changed" in (result.error or "") + assert not _owner_file(path).exists() + + +@pytest.mark.parametrize("scenario", ["same_commit", "newer_commit"]) +def test_dirty_tracked_tree_during_a_rebuild_fails_closed(tmp_path, monkeypatch, scenario): + path, repo_id = build_temp_repo(tmp_path, f"dirty-{scenario}", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + manager = resolver._index_manager + if scenario == "newer_commit": + (path / "beta.py").write_text("def beta_token():\n return 2\n") + git(path, "add", "beta.py") + git(path, "commit", "-m", "add beta") + target = git_head(path) + observed: dict = {} + original = manager._rebuild_checkpoint + + def checkpoint(stage): + if stage == "stage_created" and "dirty" not in observed: + observed["clean"] = resolver.classify(path) + (path / "alpha.py").write_text("def alpha_token():\n return 99\n") + observed["dirty"] = resolver.classify(path) + observed["search"] = _search(server, path, "alpha_token") + observed["symbol"] = _symbol(server, path, "AlphaSymbol") + # Restore the tracked file so the build itself can publish. + git(path, "checkout", "--", "alpha.py") + return original(stage) + + monkeypatch.setattr(manager, "_rebuild_checkpoint", checkpoint) + if scenario == "same_commit": + result = manager.rebuild_repository_index(repo_id) + else: + result = manager.sync_repository_index(repo_id) + + clean = observed["clean"] + assert clean.rebuild is not None and clean.rebuild["target_commit"] == target + assert clean.queryable + dirty = observed["dirty"] + assert dirty.state == RepositoryReadinessState.MISSING_PROVENANCE + assert dirty.rebuild is None and not dirty.queryable + assert observed["search"]["code"] == "index_unavailable" + assert observed["symbol"]["code"] == "index_unavailable" + assert result.action in {"full_index", "incremental_update"}, result + assert resolver.classify(path).ready + + +def test_serving_stale_requires_the_rebuild_to_target_the_current_commit(): + from mcp_server.health.repository_readiness import RepositoryReadiness + + base = dict( + state=RepositoryReadinessState.STALE_COMMIT, + current_commit="b" * 40, + last_indexed_commit="a" * 40, + ) + targeted = RepositoryReadiness( + **base, rebuild={"in_progress": True, "target_commit": "b" * 40, "started_at": "t"} + ) + elsewhere = RepositoryReadiness( + **base, rebuild={"in_progress": True, "target_commit": "c" * 40, "started_at": "t"} + ) + assert targeted.serving_stale and targeted.queryable + assert not elsewhere.serving_stale and not elsewhere.queryable + assert not RepositoryReadiness(**base).queryable + + def test_stale_commit_without_a_rebuild_stays_fail_closed(tmp_path): path, repo_id = build_temp_repo(tmp_path, "plainstale", seed_files=SEED) with boot_test_server(tmp_path, [path]) as server: From da4ccbb93674c9d1f75509f19678b6788f642ba5 Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sat, 21 Nov 2026 21:45:57 -0500 Subject: [PATCH 3/8] fix(readiness): refuse summary writes during a rebuild; one git check per query (#145) Second review follow-up for #162. - Persistent index writes no longer reach a generation a staged rebuild is about to replace. While readiness carries `rebuild`, write_summaries (including task mode) and summarize_sample(persist=true) return code "rebuild_in_progress" with a retry remediation. Right before writing they recheck RepoResolver.accepts_writes(ctx) (registry fence and file identity, no git), and the same check is the writer's per-batch cancel_check, so a rebuild that starts mid-run stops it at the next batch and the response says what may be lost. Lazy summary enqueue from search_code is skipped during a rebuild. Read-only queries are still served. - A served query now observes `git status` once per checkout: readiness classification reuses a request-scoped snapshot (contextvar, carried into the search executor thread) through admission and context creation, and only the post-query recheck observes git again, fresh. A HEAD move or a newly dirty tree during the query returns index_unavailable. Refs Consiliency/Code-Index-MCP#145 Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 10 +- mcp_server/cli/task_write_summaries.py | 16 +- mcp_server/cli/tool_handlers.py | 113 +++++++- mcp_server/client.py | 54 +++- mcp_server/core/repo_resolver.py | 22 ++ mcp_server/health/repository_readiness.py | 63 ++++- tests/test_issue_145_serve_during_rebuild.py | 277 +++++++++++++++++++ tests/test_tool_handlers_readiness.py | 4 +- 8 files changed, 541 insertions(+), 18 deletions(-) diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 2f61d9ae..0de82ea7 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -51,7 +51,15 @@ serve during a same-commit rebuild but keep refusing `stale_commit`. A query whose generation is published mid-flight finishes on its open connection to the old file (retention keeps that file) and is then refused by the generation recheck, so the caller retries against the new generation. Mutating tools -(`reindex`, `write_summaries`, `summarize_sample`) still require `ready`. +(`reindex`, `write_summaries`, `summarize_sample`) still require `ready`, and +while `rebuild` is set the summary writers (`write_summaries`, including task +mode, and `summarize_sample` with `persist: true`) return `code: +"rebuild_in_progress"` instead of writing into the generation about to be +replaced (retry after it publishes); a rebuild that starts mid-run stops them +at the next batch. Lazy summary enqueue from `search_code` is skipped during a +rebuild. Each served query observes `git status` once for admission and once +more, fresh, after the query; a HEAD move or newly dirty tree during the query +returns `index_unavailable` so the caller retries. Runtime facts are grounded in `mcp_server/plugins/language_registry.py`, `mcp_server/plugins/plugin_factory.py`, `mcp_server/plugins/plugin_set_registry.py`, diff --git a/mcp_server/cli/task_write_summaries.py b/mcp_server/cli/task_write_summaries.py index aaa87131..266cc5a1 100644 --- a/mcp_server/cli/task_write_summaries.py +++ b/mcp_server/cli/task_write_summaries.py @@ -3,7 +3,7 @@ from __future__ import annotations import json -from typing import Any +from typing import Any, Callable import anyio import mcp.types as types @@ -31,6 +31,7 @@ async def run_write_summaries_task( client_name: str | None, limit_arg: int, model_used: str | None, + write_blocked: Callable[[], bool] | None = None, ) -> types.CallToolResult: if active_store is None: raise RuntimeError("Task-backed write_summaries requires an initialized sqlite store") @@ -77,7 +78,9 @@ async def cancel_observer() -> None: result = await writer.process_scope( limit=min(per_pass_limit, remaining_budget), max_batches=1, - cancel_check=lambda: task.is_cancelled, + # A staged rebuild that starts mid-task stops it too (#145). + cancel_check=lambda: task.is_cancelled + or (write_blocked is not None and write_blocked()), ) total_written += result.summaries_written total_attempted += result.chunks_attempted @@ -113,6 +116,15 @@ async def cancel_observer() -> None: "summary_chunks_attempted": total_attempted, "summary_missing_chunks": total_missing, } + if write_blocked is not None and write_blocked(): + payload.update( + code="rebuild_in_progress", + note=( + "A staged rebuild started during this task, which stopped at the next " + "batch. Summaries written before it may be lost when it publishes; " + "rerun afterwards (already summarized chunks are skipped)." + ), + ) if task.is_cancelled: payload["cancelled"] = True result = _call_tool_result(payload) diff --git a/mcp_server/cli/tool_handlers.py b/mcp_server/cli/tool_handlers.py index ee71e022..34ef2ee6 100644 --- a/mcp_server/cli/tool_handlers.py +++ b/mcp_server/cli/tool_handlers.py @@ -7,6 +7,7 @@ from __future__ import annotations import asyncio +import functools import json import logging import os @@ -33,6 +34,9 @@ ReadinessClassifier, RepositoryReadiness, RepositoryReadinessState, + fresh_readiness, + readiness_snapshot, + readiness_snapshot_context, ) from mcp_server.indexing.source_metadata import normalize_friction_category @@ -256,6 +260,36 @@ def _index_unavailable_response( return _json_text_response(response) +def _rebuild_in_progress_response( + tool: str, readiness: Optional[RepositoryReadiness] = None, **extra: Any +) -> list[types.TextContent]: + """Refuse a persistent index write while a staged rebuild runs (#145). + + Reads keep being served from the published generation, but anything + written to it now would vanish when the rebuild publishes. + """ + return _json_text_response( + { + "error": "Rebuild in progress", + "code": "rebuild_in_progress", + "tool": tool, + "mutation_performed": False, + "readiness": readiness.to_dict() if readiness is not None else None, + "message": ( + "A staged index rebuild is in progress; writes to the published " + "generation would be lost when it publishes." + ), + "remediation": "Retry after the rebuild publishes (readiness.rebuild becomes null).", + **extra, + } + ) + + +def _write_blocked(repo_resolver: Any, ctx: Optional[RepoContext]) -> bool: + """True when a staged build fenced, or replaced, ctx's published generation.""" + return isinstance(repo_resolver, RepoResolver) and not repo_resolver.accepts_writes(ctx) + + def _resolution_transition_response(tool: str) -> list[types.TextContent]: return _json_text_response( { @@ -339,6 +373,28 @@ def _semantic_failure_response( return _json_text_response(response) +def _with_readiness_snapshot(handler): + """Run a query handler inside one request readiness snapshot (#145). + + One git observation per checkout admits the query and builds its context; + only the post-query recheck (``_fresh_is_current``) observes git again. + """ + + @functools.wraps(handler) + async def wrapper(**kwargs): + with readiness_snapshot(): + return await handler(**kwargs) + + return wrapper + + +def _fresh_is_current(repo_resolver: RepoResolver, ctx: Optional[RepoContext]) -> bool: + """Post-query recheck outside the request snapshot (#145).""" + with fresh_readiness(): + return repo_resolver.is_current(ctx) + + +@_with_readiness_snapshot async def handle_symbol_lookup( *, arguments: dict, @@ -387,11 +443,11 @@ async def handle_symbol_lookup( # Fallback: call without ctx for pre-SL-1 compatibility result = dispatcher.lookup(symbol) # type: ignore[call-arg] except Exception: - if isinstance(repo_resolver, RepoResolver) and not repo_resolver.is_current(ctx): + if isinstance(repo_resolver, RepoResolver) and not _fresh_is_current(repo_resolver, ctx): return _resolution_transition_response("symbol_lookup") raise - if isinstance(repo_resolver, RepoResolver) and not repo_resolver.is_current(ctx): + if isinstance(repo_resolver, RepoResolver) and not _fresh_is_current(repo_resolver, ctx): return _resolution_transition_response("symbol_lookup") if result: @@ -499,7 +555,11 @@ async def handle_search_code( ] repository = (arguments or {}).get("repository") - selector_readiness = _classify_ctx(repo_resolver, repository) + # One git observation per checkout for admission and context creation, + # carried into the executor thread; the service rechecks once, fresh, + # after the query (#145). + request_context = readiness_snapshot_context() + selector_readiness = request_context.run(_classify_ctx, repo_resolver, repository) repository_path = _repository_selector_path(repository, selector_readiness) if repository_path is not None: @@ -545,7 +605,8 @@ async def handle_search_code( result = await asyncio.wait_for( asyncio.get_event_loop().run_in_executor( None, - lambda: execute_search_service( + lambda: request_context.run( + execute_search_service, dispatcher=dispatcher, repo_resolver=repo_resolver, options=options, @@ -687,8 +748,10 @@ async def handle_search_code( ) results_data.append(result_item) - # Lazy summarization enqueue - if lazy_summarizer and lazy_summarizer.can_summarize() and sqlite_store: + # Lazy summarization enqueue. Skipped while a staged rebuild runs: the + # summaries would land in the generation it is about to replace (#145). + rebuilding = isinstance(readiness, dict) and bool(readiness.get("rebuild")) + if lazy_summarizer and lazy_summarizer.can_summarize() and sqlite_store and not rebuilding: # CHUNKERSAFE Lane A: find_chunk_at_line is a scheme-dependent # code_chunks read; fail closed and skip summarization over an # incompatible/rebuilding index rather than enqueue stale-scheme rows. @@ -1470,6 +1533,8 @@ async def handle_write_summaries( if readiness is not None and not readiness.ready: return _secondary_readiness_refusal_response(readiness, "write_summaries") + if readiness is not None and readiness.rebuild: + return _rebuild_in_progress_response("write_summaries", readiness) ctx = _resolve_ctx(repo_resolver, repository) if ctx is None and isinstance(repo_resolver, RepoResolver): @@ -1505,6 +1570,16 @@ async def handle_write_summaries( limit_arg = int((arguments or {}).get("limit", 500)) model_used = lazy_summarizer._get_model_name() + # Recheck right before writing: a rebuild that started since admission + # refuses now, and one that starts mid-run stops it at the next batch. + if _write_blocked(repo_resolver, ctx): + return _rebuild_in_progress_response( + "write_summaries", _classify_ctx(repo_resolver, repository) + ) + + def write_blocked() -> bool: + return _write_blocked(repo_resolver, ctx) + if request_experimental is not None and request_experimental.is_task: return await request_experimental.run_task( lambda task: run_write_summaries_task( @@ -1515,6 +1590,7 @@ async def handle_write_summaries( client_name=client_name, limit_arg=limit_arg, model_used=model_used, + write_blocked=write_blocked, ), model_immediate_response=( "Summary task created; use tasks/get and tasks/result to observe bounded progress." @@ -1533,7 +1609,18 @@ async def handle_write_summaries( "profile_id": profile_id, }, ) - summary_result = await writer.process_scope(limit=limit_arg) + summary_result = await writer.process_scope(limit=limit_arg, cancel_check=write_blocked) + if write_blocked(): + return _rebuild_in_progress_response( + "write_summaries", + _classify_ctx(repo_resolver, repository), + chunks_summarized=summary_result.summaries_written, + note=( + "A rebuild started during this run, which stopped at the next batch. " + "Summaries written before it may be lost when it publishes; rerun " + "afterwards (already summarized chunks are skipped)." + ), + ) return [ types.TextContent( @@ -1638,6 +1725,8 @@ async def handle_summarize_sample( ] if not path_readiness.ready: return _secondary_readiness_refusal_response(path_readiness, "summarize_sample") + if persist_flag and path_readiness.rebuild: + return _rebuild_in_progress_response("summarize_sample", path_readiness) repo_key = path_readiness.repository_id or "" path_readiness_by_repo[repo_key] = path_readiness @@ -1658,6 +1747,8 @@ async def handle_summarize_sample( if repository_readiness is not None and not repository_readiness.ready: return _secondary_readiness_refusal_response(repository_readiness, "summarize_sample") + if persist_flag and repository_readiness is not None and repository_readiness.rebuild: + return _rebuild_in_progress_response("summarize_sample", repository_readiness) scope_arg = repository if not scope_arg and paths_arg: @@ -1708,6 +1799,14 @@ async def handle_summarize_sample( total_chunks = 0 for file_id, file_path, language in file_rows: + if persist_flag and _write_blocked(repo_resolver, ctx): + # Recheck right before each persisted file (#145). + return _rebuild_in_progress_response( + "summarize_sample", + _classify_ctx(repo_resolver, scope_arg), + files=file_results, + total_chunks=total_chunks, + ) try: with open(file_path, encoding="utf-8", errors="replace") as _fh: file_content = _fh.read() diff --git a/mcp_server/client.py b/mcp_server/client.py index 7349a96c..96bcc61d 100644 --- a/mcp_server/client.py +++ b/mcp_server/client.py @@ -9,7 +9,11 @@ from mcp_server.core.repo_context import RepoContext from mcp_server.core.repo_resolver import RepoResolver, run_repository_mutation from mcp_server.dispatcher.protocol import DispatcherProtocol -from mcp_server.health.repository_readiness import ReadinessClassifier +from mcp_server.health.repository_readiness import ( + ReadinessClassifier, + fresh_readiness, + readiness_snapshot, +) from mcp_server.storage.store_registry import StoreRegistry from .client_types import ( @@ -107,6 +111,16 @@ def _generation_unavailable(repo_resolver, ctx) -> IndexUnavailable | None: return None +def _fresh_generation_unavailable(repo_resolver, ctx) -> IndexUnavailable | None: + """The one post-query recheck: observe git again, outside the request snapshot. + + Catches a HEAD that moved or a tracked tree that became dirty while the + query ran, as well as a publish swap, so the caller retries (#145). + """ + with fresh_readiness(): + return _generation_unavailable(repo_resolver, ctx) + + def _unavailable_search( options: ClientSearchOptions, unavailable: IndexUnavailable ) -> ClientSearchResult: @@ -229,6 +243,26 @@ def execute_search_service( options: ClientSearchOptions, workspace_root: Path | None = None, ctx: RepoContext | None = None, +) -> ClientSearchResult: + # One git observation per checkout admits the query and builds its + # context; only the post-query recheck observes git again (#145). + with readiness_snapshot(): + return _execute_search_service( + dispatcher=dispatcher, + repo_resolver=repo_resolver, + options=options, + workspace_root=workspace_root, + ctx=ctx, + ) + + +def _execute_search_service( + *, + dispatcher: DispatcherProtocol, + repo_resolver: RepoResolver | None, + options: ClientSearchOptions, + workspace_root: Path | None, + ctx: RepoContext | None, ) -> ClientSearchResult: readiness = ( _resolve_readiness(repo_resolver, options.repository, workspace_root=workspace_root) @@ -277,7 +311,7 @@ def execute_search_service( try: raw_results = list(dispatcher.search(ctx, options.query, **_search_kwargs(options))) except Exception: - unavailable = _generation_unavailable(repo_resolver, ctx) + unavailable = _fresh_generation_unavailable(repo_resolver, ctx) if unavailable is not None: return _unavailable_search(options, unavailable) if options.semantic: @@ -302,7 +336,7 @@ def execute_search_service( ) raise - unavailable = _generation_unavailable(repo_resolver, ctx) + unavailable = _fresh_generation_unavailable(repo_resolver, ctx) if unavailable is not None: return _unavailable_search(options, unavailable) return ClientSearchResult( @@ -426,6 +460,16 @@ def symbol_lookup( symbol: str, *, repository: str | Path | None = None, + ) -> ClientSymbolResult: + # Same single-observation admission as search (#145). + with readiness_snapshot(): + return self._symbol_lookup(symbol, repository=repository) + + def _symbol_lookup( + self, + symbol: str, + *, + repository: str | Path | None = None, ) -> ClientSymbolResult: readiness = _resolve_readiness( self.repo_resolver, @@ -460,7 +504,7 @@ def symbol_lookup( try: result = self.dispatcher.lookup(ctx, symbol) except Exception: - unavailable = _generation_unavailable(self.repo_resolver, ctx) + unavailable = _fresh_generation_unavailable(self.repo_resolver, ctx) if unavailable is None: raise return ClientSymbolResult( @@ -469,7 +513,7 @@ def symbol_lookup( index_unavailable=unavailable, message=unavailable.message, ) - unavailable = _generation_unavailable(self.repo_resolver, ctx) + unavailable = _fresh_generation_unavailable(self.repo_resolver, ctx) if unavailable is not None: return ClientSymbolResult( symbol=symbol, diff --git a/mcp_server/core/repo_resolver.py b/mcp_server/core/repo_resolver.py index f830a6ab..f5b67faf 100644 --- a/mcp_server/core/repo_resolver.py +++ b/mcp_server/core/repo_resolver.py @@ -109,6 +109,28 @@ def is_current(self, ctx: RepoContext) -> bool: except Exception: return False + def accepts_writes(self, ctx: Optional[RepoContext]) -> bool: + """True while ``ctx`` may persist into its published generation (#145). + + A staged build fences the registry entry before it snapshots the live + file, so any write after that could vanish when it publishes. Reads keep + being served during a live rebuild, but persistent writers (summaries) + check this before they start and between batches. Registry and file + identity only; no git. + """ + if ctx is None: + return False + try: + info = self._registry.get(ctx.repo_id) + return ( + info is not None + and not info.staleness_reason + and self._store_registry.binding(info) + == self._store_registry.binding(ctx.registry_entry) + ) + except Exception: + return False + def mutate( self, ctx: RepoContext, operation: Callable[[RepoContext], _MutationResult] ) -> _MutationResult: diff --git a/mcp_server/health/repository_readiness.py b/mcp_server/health/repository_readiness.py index 4d43d456..15f8495f 100644 --- a/mcp_server/health/repository_readiness.py +++ b/mcp_server/health/repository_readiness.py @@ -8,7 +8,9 @@ import subprocess import threading from collections import OrderedDict -from contextlib import closing +import contextvars +from contextlib import closing, contextmanager +from contextvars import ContextVar from dataclasses import dataclass from enum import Enum from pathlib import Path @@ -848,7 +850,66 @@ def _find_git_root(start: Path) -> Optional[Path]: current = current.parent +#: Per-request git observations (Consiliency/Code-Index-MCP#145). A query +#: classifies readiness several times on its way through admission and context +#: creation; inside ``readiness_snapshot()`` each checkout's ``git status`` runs +#: once and is reused, and ``fresh_readiness()`` observes it again for the one +#: recheck after the query. +_GIT_STATE_SNAPSHOT: ContextVar[Optional[dict[str, tuple[Optional[str], Optional[str], bool]]]] = ( + ContextVar("mcp_readiness_git_snapshot", default=None) +) + + +@contextmanager +def readiness_snapshot(): + """Reuse one git observation per checkout for the rest of this request. + + Re-entering inside an active snapshot reuses it. Copy the context + (``contextvars.copy_context().run``) to carry it into an executor thread. + """ + if _GIT_STATE_SNAPSHOT.get() is not None: + yield + return + token = _GIT_STATE_SNAPSHOT.set({}) + try: + yield + finally: + _GIT_STATE_SNAPSHOT.reset(token) + + +@contextmanager +def fresh_readiness(): + """Observe git again, bypassing any active request snapshot.""" + token = _GIT_STATE_SNAPSHOT.set(None) + try: + yield + finally: + _GIT_STATE_SNAPSHOT.reset(token) + + +def readiness_snapshot_context() -> contextvars.Context: + """Return a copied context holding a new request snapshot. + + For request handlers that hop to an executor thread: run each step with + ``context.run(...)`` so every classification shares one observation. + """ + context = contextvars.copy_context() + context.run(_GIT_STATE_SNAPSHOT.set, {}) + return context + + def _git_state(path: Path) -> tuple[Optional[str], Optional[str], bool]: + """Return HEAD, branch and tracked state, reusing the request snapshot if any.""" + snapshot = _GIT_STATE_SNAPSHOT.get() + if snapshot is None: + return _observe_git_state(path) + key = str(path) + if key not in snapshot: + snapshot[key] = _observe_git_state(path) + return snapshot[key] + + +def _observe_git_state(path: Path) -> tuple[Optional[str], Optional[str], bool]: """Read fresh HEAD, branch and tracked state without refreshing Git's index.""" try: result = subprocess.run( diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py index 9d7da53b..7e851c04 100644 --- a/tests/test_issue_145_serve_during_rebuild.py +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -9,6 +9,7 @@ from __future__ import annotations +import asyncio import importlib import json import os @@ -23,6 +24,8 @@ from mcp_server.health.repository_readiness import ReadinessClassifier, RepositoryReadinessState from tests.fixtures.multi_repo import boot_test_server, build_temp_repo, git, git_head +readiness_module = importlib.import_module("mcp_server.health.repository_readiness") + # ``mcp_server.indexing`` re-exports the ``lock_registry`` singleton under the # module's own name, so import the module explicitly. locks = importlib.import_module("mcp_server.indexing.lock_registry") @@ -506,3 +509,277 @@ def search(ctx, query, **kwargs): monkeypatch.setattr(server.dispatcher, "search", original_search) retry = _search(server, path, "alpha_token") assert "alpha.py" in _result_files(retry) + + +# --------------------------------------------------------------------------- +# Persistent index writes refuse while a rebuild runs +# --------------------------------------------------------------------------- + + +class _FakeSummarizer: + """Stands in for the lazy summarizer: summarization available, enqueue recorded.""" + + def __init__(self): + self.enqueued: list = [] + + def can_summarize(self) -> bool: + return True + + def _get_model_name(self) -> str: + return "fake-model" + + def enqueue(self, chunk) -> None: + self.enqueued.append(chunk) + + +class _FakeStore: + """The handler's global store, only consulted for lazy enqueue.""" + + def get_chunk_scheme_status(self): + return ("compatible", None, None) + + def find_chunk_at_line(self, path, line): + return {"chunk_id": f"{path}:{line}"} + + +def _run_tool(handler, **kwargs) -> dict: + from mcp_server.cli import tool_handlers + + result = asyncio.run(getattr(tool_handlers, handler)(**kwargs)) + return json.loads(result[0].text) + + +def _install_fake_writer(monkeypatch, on_process=None): + from mcp_server.indexing import summarization + from mcp_server.indexing.summarization import SummaryGenerationResult + + calls: list = [] + + class FakeWriter: + def __init__(self, **kwargs): + self.kwargs = kwargs + + async def process_scope(self, limit=500, cancel_check=None, **kwargs): + calls.append(self.kwargs["db_path"]) + if on_process is not None: + on_process() + cancelled = bool(cancel_check and cancel_check()) + return SummaryGenerationResult( + chunks_attempted=1, summaries_written=1, cancelled=cancelled + ) + + monkeypatch.setattr(summarization, "ComprehensiveChunkWriter", FakeWriter) + return calls + + +def test_write_summaries_refuses_during_a_rebuild_and_writes_after(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "summaries", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + calls = _install_fake_writer(monkeypatch) + common = dict( + arguments={"repository": str(path)}, + dispatcher=server.dispatcher, + repo_resolver=resolver, + lazy_summarizer=_FakeSummarizer(), + ) + observed: dict = {} + + def operation(stage): + observed["readiness"] = resolver.classify(path) + observed["write"] = _run_tool("handle_write_summaries", **common) + return {"failed_files": 0} + + run_repository_mutation(resolver, resolver.resolve_ready(path), operation) + + assert observed["readiness"].ready and observed["readiness"].rebuild + refused = observed["write"] + assert refused["code"] == "rebuild_in_progress" + assert refused["mutation_performed"] is False + assert refused["readiness"]["rebuild"]["in_progress"] is True + assert calls == [] # nothing reached the published generation + + written = _run_tool("handle_write_summaries", **common) + assert written["persisted"] is True and written["chunks_summarized"] == 1 + assert len(calls) == 1 + + +def test_write_summaries_stops_when_a_rebuild_starts_mid_run(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "midrun", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + info = server.registry.get(repo_id) + + def rebuild_starts(): + server.registry.begin_generation_mutation( + repo_id, + expected_registration_id=info.registration_id, + expected_generation=info.index_generation, + ) + + calls = _install_fake_writer(monkeypatch, on_process=rebuild_starts) + response = _run_tool( + "handle_write_summaries", + arguments={"repository": str(path)}, + dispatcher=server.dispatcher, + repo_resolver=server.repo_resolver, + lazy_summarizer=_FakeSummarizer(), + ) + assert len(calls) == 1 + assert response["code"] == "rebuild_in_progress" + assert response["chunks_summarized"] == 1 + assert "rerun" in response["note"] + + +def test_summarize_sample_refuses_to_persist_during_a_rebuild(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "sample", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + observed: dict = {} + + def sample(persist: bool) -> dict: + return _run_tool( + "handle_summarize_sample", + arguments={"repository": str(path), "persist": persist, "n": 1}, + dispatcher=server.dispatcher, + repo_resolver=resolver, + lazy_summarizer=None, + ) + + def operation(stage): + observed["persist"] = sample(True) + observed["preview"] = sample(False) + return {"failed_files": 0} + + run_repository_mutation(resolver, resolver.resolve_ready(path), operation) + + assert observed["persist"]["code"] == "rebuild_in_progress" + assert observed["persist"]["mutation_performed"] is False + # A non-persisting sample only reads; it passes the rebuild gate and + # stops at the (absent) summarizer instead. + assert observed["preview"].get("code") != "rebuild_in_progress" + assert observed["preview"]["error"] == "Summarization not available" + + +def test_lazy_summary_enqueue_is_skipped_during_a_rebuild(tmp_path): + path, repo_id = build_temp_repo(tmp_path, "lazy", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + summarizer = _FakeSummarizer() + + def search() -> object: + return _run_tool( + "handle_search_code", + arguments={"query": "alpha_token", "repository": str(path)}, + dispatcher=server.dispatcher, + repo_resolver=resolver, + sqlite_store=_FakeStore(), + lazy_summarizer=summarizer, + ) + + observed: dict = {} + + def operation(stage): + observed["search"] = search() + return {"failed_files": 0} + + run_repository_mutation(resolver, resolver.resolve_ready(path), operation) + + assert "alpha.py" in _result_files(observed["search"]) + assert summarizer.enqueued == [] + # Control: once the rebuild published, the same search enqueues. + assert "alpha.py" in _result_files(search()) + assert summarizer.enqueued + + +# --------------------------------------------------------------------------- +# One readiness observation per served query +# --------------------------------------------------------------------------- + + +def _count_git_status(monkeypatch) -> list: + calls: list = [] + original = readiness_module._observe_git_state + + def counting(path): + calls.append(str(path)) + return original(path) + + monkeypatch.setattr(readiness_module, "_observe_git_state", counting) + return calls + + +def test_served_queries_observe_git_at_most_twice(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "count", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + manager = resolver._index_manager + (path / "beta.py").write_text("def beta_token():\n return 2\n") + git(path, "add", "beta.py") + git(path, "commit", "-m", "add beta") + calls = _count_git_status(monkeypatch) + observed: dict = {} + original = manager._rebuild_checkpoint + + def checkpoint(stage): + if stage == "before_publish" and "search" not in observed: + calls.clear() + observed["search"] = _search(server, path, "alpha_token") + observed["search_calls"] = len(calls) + calls.clear() + observed["symbol"] = _symbol(server, path, "AlphaSymbol") + observed["symbol_calls"] = len(calls) + return original(stage) + + monkeypatch.setattr(manager, "_rebuild_checkpoint", checkpoint) + manager.sync_repository_index(repo_id) + + # Served stale during the rebuild, with at most admission + recheck. + assert observed["search"]["readiness"]["state"] == "stale_commit" + assert observed["symbol"]["readiness"]["state"] == "stale_commit" + assert observed["search_calls"] <= 2, observed + assert observed["symbol_calls"] <= 2, observed + + calls.clear() + assert "alpha.py" in _result_files(_search(server, path, "alpha_token")) + assert len(calls) <= 2, calls + calls.clear() + assert _symbol(server, path, "AlphaSymbol")["symbol"] == "AlphaSymbol" + assert len(calls) <= 2, calls + + +@pytest.mark.parametrize("change", ["head_moved", "tree_dirtied"]) +def test_post_query_recheck_catches_source_changes_during_the_query(tmp_path, monkeypatch, change): + path, repo_id = build_temp_repo(tmp_path, f"recheck-{change}", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + original_search = server.dispatcher.search + original_lookup = server.dispatcher.lookup + + def change_source(): + if change == "head_moved": + (path / f"gamma{len(list(path.glob('gamma*.py')))}.py").write_text("g = 1\n") + git(path, "add", ".") + git(path, "commit", "-m", "move head") + else: + (path / "alpha.py").write_text("def alpha_token():\n return 7\n") + + def search(ctx, query, **kwargs): + results = list(original_search(ctx, query, **kwargs)) + change_source() + return results + + def lookup(ctx, symbol): + result = original_lookup(ctx, symbol) + change_source() + return result + + monkeypatch.setattr(server.dispatcher, "search", search) + response = _search(server, path, "alpha_token") + assert response["code"] == "index_unavailable", response + + if change == "tree_dirtied": + git(path, "checkout", "--", "alpha.py") + else: + server.seed_repo_index(repo_id, path) + monkeypatch.setattr(server.dispatcher, "lookup", lookup) + symbol = _symbol(server, path, "AlphaSymbol") + assert symbol["code"] == "index_unavailable", symbol diff --git a/tests/test_tool_handlers_readiness.py b/tests/test_tool_handlers_readiness.py index 13c3bce2..40c0e9b1 100644 --- a/tests/test_tool_handlers_readiness.py +++ b/tests/test_tool_handlers_readiness.py @@ -862,8 +862,8 @@ class FakeWriter: def __init__(self, *args, **kwargs): seen_config.update(kwargs["summarization_config"]) - async def process_scope(self, limit=500): - del limit + async def process_scope(self, limit=500, cancel_check=None): + del limit, cancel_check return SimpleNamespace( summaries_written=3, chunks_attempted=4, missing_chunk_ids=["c4"] ) From 4ae09f82b26bc290149e14e18c1b2d7a9112ad46 Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sat, 21 Nov 2026 22:07:09 -0500 Subject: [PATCH 4/8] fix(summaries): fence summary writes at the write itself; schema for rebuild_in_progress (#145) Third review follow-up for #162. - Summary writes are now checked at the persistence point, after the provider call returns. ChunkWriter takes an optional write_fence, a context manager entered around each batch transaction and each single chunk write. RepoResolver.generation_write_fence takes the repository writer lock without waiting and yields whether the registration and published generation still accept writes, so no staged build can begin between the check and the commit. A fenced batch stores nothing, and SummaryGenerationResult.write_fenced reports it; process_scope stops on it. - write_summaries (direct and task mode) and summarize_sample(persist=true) pass the fence and return rebuild_in_progress, with partial counts, when a write is fenced. Batches committed before the fence are kept, since they precede any rebuild's snapshot. - Lazy summary entries carry the fence of the generation the query read; they are dropped before the provider call when already fenced, and checked again at the write. - A shared rebuild_in_progress branch is added to the write_summaries and summarize_sample output schemas, with jsonschema validation tests. - The query gates fall back to `ready` for duck-typed readiness objects that lack `queryable`/`serving_stale`/`rebuild`. Refs Consiliency/Code-Index-MCP#145 Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 11 +- mcp_server/cli/stdio_runner.py | 22 ++ mcp_server/cli/task_write_summaries.py | 14 +- mcp_server/cli/tool_handlers.py | 95 +++++- mcp_server/client.py | 5 +- mcp_server/core/repo_resolver.py | 41 ++- mcp_server/health/repository_readiness.py | 10 + mcp_server/indexing/summarization.py | 198 +++++++++---- tests/test_issue_145_serve_during_rebuild.py | 289 ++++++++++++++++++- 9 files changed, 603 insertions(+), 82 deletions(-) diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 0de82ea7..421bc434 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -55,9 +55,14 @@ recheck, so the caller retries against the new generation. Mutating tools while `rebuild` is set the summary writers (`write_summaries`, including task mode, and `summarize_sample` with `persist: true`) return `code: "rebuild_in_progress"` instead of writing into the generation about to be -replaced (retry after it publishes); a rebuild that starts mid-run stops them -at the next batch. Lazy summary enqueue from `search_code` is skipped during a -rebuild. Each served query observes `git status` once for admission and once +replaced (retry after it publishes). Every summary write is also fenced at the +write itself, after the provider call: the writer takes the repository writer +lock without waiting and stores nothing if a build holds it or the generation +was fenced or replaced, so a rebuild that begins mid-call loses no committed +work and the caller gets `rebuild_in_progress` with partial counts. Lazy +summary entries from `search_code` carry the generation they were found in and +are dropped, before the provider call or at the write, once a rebuild fences +it; no new entries are enqueued during a rebuild. Each served query observes `git status` once for admission and once more, fresh, after the query; a HEAD move or newly dirty tree during the query returns `index_unavailable` so the caller retries. diff --git a/mcp_server/cli/stdio_runner.py b/mcp_server/cli/stdio_runner.py index b8645d32..b9f0f273 100644 --- a/mcp_server/cli/stdio_runner.py +++ b/mcp_server/cli/stdio_runner.py @@ -225,6 +225,26 @@ def resolve(self, path: Any) -> Any: "required": ["error", "details"], "additionalProperties": True, } +#: Persistent summary writers refuse while a staged rebuild runs, or report a +#: rebuild that began mid-run (Consiliency/Code-Index-MCP#145). +_REBUILD_IN_PROGRESS_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "error": {"const": "Rebuild in progress"}, + "code": {"const": "rebuild_in_progress"}, + "tool": {"type": "string"}, + "mutation_performed": {"type": "boolean"}, + "readiness": {"type": ["object", "null"]}, + "message": {"type": "string"}, + "remediation": {"type": ["string", "array", "object", "null"]}, + "chunks_summarized": {"type": "integer"}, + "files": {"type": "array"}, + "total_chunks": {"type": "integer"}, + "note": {"type": "string"}, + }, + "required": ["error", "code", "tool", "mutation_performed", "message"], + "additionalProperties": True, +} _SQLITE_NOT_INITIALIZED_SCHEMA: dict[str, Any] = { "type": "object", "properties": { @@ -777,6 +797,7 @@ def _build_tool_list() -> list[types.Tool]: _PATH_OUTSIDE_ALLOWED_ROOTS_SCHEMA, _INDEX_UNAVAILABLE_SCHEMA, _SECONDARY_READINESS_REFUSAL_SCHEMA, + _REBUILD_IN_PROGRESS_SCHEMA, _SUMMARIZATION_UNAVAILABLE_SCHEMA, _SQLITE_NOT_INITIALIZED_SCHEMA, _object_schema( @@ -848,6 +869,7 @@ def _build_tool_list() -> list[types.Tool]: _INDEX_UNAVAILABLE_SCHEMA, _SECONDARY_READINESS_REFUSAL_SCHEMA, _CONFLICTING_SCOPE_SCHEMA, + _REBUILD_IN_PROGRESS_SCHEMA, _SUMMARIZATION_UNAVAILABLE_SCHEMA, _SQLITE_NOT_INITIALIZED_SCHEMA, _object_schema( diff --git a/mcp_server/cli/task_write_summaries.py b/mcp_server/cli/task_write_summaries.py index 266cc5a1..c20392a4 100644 --- a/mcp_server/cli/task_write_summaries.py +++ b/mcp_server/cli/task_write_summaries.py @@ -32,6 +32,7 @@ async def run_write_summaries_task( limit_arg: int, model_used: str | None, write_blocked: Callable[[], bool] | None = None, + write_fence: Callable[[], Any] | None = None, ) -> types.CallToolResult: if active_store is None: raise RuntimeError("Task-backed write_summaries requires an initialized sqlite store") @@ -53,6 +54,7 @@ async def run_write_summaries_task( **settings.get_profile_summarization_config(profile_id), "profile_id": profile_id, }, + write_fence=write_fence, ) total_written = 0 @@ -60,6 +62,7 @@ async def run_write_summaries_task( total_missing = 0 remaining_budget = limit_arg persisted_any = False + write_fenced = False per_pass_limit = min(64, limit_arg) async def cancel_observer() -> None: @@ -82,6 +85,7 @@ async def cancel_observer() -> None: cancel_check=lambda: task.is_cancelled or (write_blocked is not None and write_blocked()), ) + write_fenced = write_fenced or bool(getattr(result, "write_fenced", False)) total_written += result.summaries_written total_attempted += result.chunks_attempted total_missing = result.remaining_chunks @@ -101,7 +105,7 @@ async def cancel_observer() -> None: "persisted": persisted_any, }, ) - if result.cancelled or task.is_cancelled: + if result.cancelled or task.is_cancelled or write_fenced: break if result.summaries_written == 0 or result.remaining_chunks == 0: break @@ -116,13 +120,13 @@ async def cancel_observer() -> None: "summary_chunks_attempted": total_attempted, "summary_missing_chunks": total_missing, } - if write_blocked is not None and write_blocked(): + if write_fenced or (write_blocked is not None and write_blocked()): payload.update( code="rebuild_in_progress", note=( - "A staged rebuild started during this task, which stopped at the next " - "batch. Summaries written before it may be lost when it publishes; " - "rerun afterwards (already summarized chunks are skipped)." + "A staged rebuild started during this task. Summaries already committed " + "were written before it began and are kept; the rest were not written. " + "Rerun after the rebuild publishes (already summarized chunks are skipped)." ), ) if task.is_cancelled: diff --git a/mcp_server/cli/tool_handlers.py b/mcp_server/cli/tool_handlers.py index 34ef2ee6..ef84cb75 100644 --- a/mcp_server/cli/tool_handlers.py +++ b/mcp_server/cli/tool_handlers.py @@ -35,6 +35,8 @@ RepositoryReadiness, RepositoryReadinessState, fresh_readiness, + readiness_queryable, + readiness_serving_stale, readiness_snapshot, readiness_snapshot_context, ) @@ -180,7 +182,7 @@ def _resolve_ctx( callers also accept a published generation served during a rebuild (#145). """ readiness = _classify_ctx(repo_resolver, path_arg) - if readiness is not None and not readiness.queryable: + if readiness is not None and not readiness_queryable(readiness): return None if path_arg: @@ -285,6 +287,40 @@ def _rebuild_in_progress_response( ) +_FENCED_WRITE_NOTE = ( + "A staged rebuild started during this run. Summaries already committed were " + "written before it began and are kept; the rest were not written. Rerun after " + "the rebuild publishes (already summarized chunks are skipped)." +) + + +def _write_fence(repo_resolver: Any, ctx: Optional[RepoContext]) -> Any: + """The persistence-point fence for ctx's published generation, if available (#145).""" + if isinstance(repo_resolver, RepoResolver) and ctx is not None: + return repo_resolver.write_fence(ctx) + return None + + +def _lazy_write_fence(repo_resolver: Any, readiness: Any) -> tuple[bool, Any]: + """Return ``(enqueue_allowed, fence)`` for lazy summaries of a served query. + + The fence binds each queued entry to the registration and generation the + query read, so a staged rebuild that begins before the summary is stored + drops it (#145). With a resolver but no resolvable generation, nothing is + enqueued. + """ + if not isinstance(repo_resolver, RepoResolver): + return True, None + repo_id = readiness.get("repository_id") if isinstance(readiness, dict) else None + try: + info = repo_resolver._registry.get(repo_id) if repo_id else None + except Exception: + info = None + if info is None: + return False, None + return True, repo_resolver.generation_write_fence(repo_id, info, Path(info.path)) + + def _write_blocked(repo_resolver: Any, ctx: Optional[RepoContext]) -> bool: """True when a staged build fenced, or replaced, ctx's published generation.""" return isinstance(repo_resolver, RepoResolver) and not repo_resolver.accepts_writes(ctx) @@ -429,7 +465,7 @@ async def handle_symbol_lookup( } ) - if readiness is not None and not readiness.queryable: + if readiness is not None and not readiness_queryable(readiness): return _index_unavailable_response(readiness, "symbol_lookup", symbol=symbol) ctx = _resolve_ctx(repo_resolver, repository) @@ -489,7 +525,7 @@ async def handle_symbol_lookup( response_data["_usage_hint"] = ( f"To view definition: Read(file_path='{translated_path}', offset={offset}, limit=20)" ) - if readiness is not None and readiness.serving_stale: + if readiness is not None and readiness_serving_stale(readiness): response_data["readiness"] = readiness.to_dict() response_data["note"] = _stale_note(readiness.to_dict()) return [types.TextContent(type="text", text=_ensure_response(response_data))] @@ -501,7 +537,7 @@ async def handle_symbol_lookup( } if readiness is not None: response_data["readiness"] = readiness.to_dict() - if readiness.serving_stale: + if readiness_serving_stale(readiness): response_data["note"] = _stale_note(readiness.to_dict()) if readiness.coverage_degraded: # The symbol may live in a language this generation left out @@ -751,7 +787,14 @@ async def handle_search_code( # Lazy summarization enqueue. Skipped while a staged rebuild runs: the # summaries would land in the generation it is about to replace (#145). rebuilding = isinstance(readiness, dict) and bool(readiness.get("rebuild")) - if lazy_summarizer and lazy_summarizer.can_summarize() and sqlite_store and not rebuilding: + lazy_allowed, lazy_fence = _lazy_write_fence(repo_resolver, readiness) + if ( + lazy_summarizer + and lazy_summarizer.can_summarize() + and sqlite_store + and not rebuilding + and lazy_allowed + ): # CHUNKERSAFE Lane A: find_chunk_at_line is a scheme-dependent # code_chunks read; fail closed and skip summarization over an # incompatible/rebuilding index rather than enqueue stale-scheme rows. @@ -772,7 +815,10 @@ async def handle_search_code( if raw_file and raw_line: chunk_info = sqlite_store.find_chunk_at_line(raw_file, int(raw_line)) if chunk_info: - lazy_summarizer.enqueue(chunk_info) + if lazy_fence is None: + lazy_summarizer.enqueue(chunk_info) + else: + lazy_summarizer.enqueue(chunk_info, write_fence=lazy_fence) filtered_or_enriched = bool( source_type @@ -1533,7 +1579,7 @@ async def handle_write_summaries( if readiness is not None and not readiness.ready: return _secondary_readiness_refusal_response(readiness, "write_summaries") - if readiness is not None and readiness.rebuild: + if readiness is not None and getattr(readiness, "rebuild", None): return _rebuild_in_progress_response("write_summaries", readiness) ctx = _resolve_ctx(repo_resolver, repository) @@ -1580,6 +1626,11 @@ async def handle_write_summaries( def write_blocked() -> bool: return _write_blocked(repo_resolver, ctx) + # Checked at each write transaction, after the provider call returns: a + # fenced batch stores nothing, and every committed batch precedes any + # rebuild's snapshot because the fence holds the writer lock (#145). + write_fence = _write_fence(repo_resolver, ctx) + if request_experimental is not None and request_experimental.is_task: return await request_experimental.run_task( lambda task: run_write_summaries_task( @@ -1591,6 +1642,7 @@ def write_blocked() -> bool: limit_arg=limit_arg, model_used=model_used, write_blocked=write_blocked, + write_fence=write_fence, ), model_immediate_response=( "Summary task created; use tasks/get and tasks/result to observe bounded progress." @@ -1608,18 +1660,15 @@ def write_blocked() -> bool: **_settings.get_profile_summarization_config(profile_id), "profile_id": profile_id, }, + write_fence=write_fence, ) summary_result = await writer.process_scope(limit=limit_arg, cancel_check=write_blocked) - if write_blocked(): + if getattr(summary_result, "write_fenced", False) or write_blocked(): return _rebuild_in_progress_response( "write_summaries", _classify_ctx(repo_resolver, repository), chunks_summarized=summary_result.summaries_written, - note=( - "A rebuild started during this run, which stopped at the next batch. " - "Summaries written before it may be lost when it publishes; rerun " - "afterwards (already summarized chunks are skipped)." - ), + note=_FENCED_WRITE_NOTE, ) return [ @@ -1725,7 +1774,7 @@ async def handle_summarize_sample( ] if not path_readiness.ready: return _secondary_readiness_refusal_response(path_readiness, "summarize_sample") - if persist_flag and path_readiness.rebuild: + if persist_flag and getattr(path_readiness, "rebuild", None): return _rebuild_in_progress_response("summarize_sample", path_readiness) repo_key = path_readiness.repository_id or "" path_readiness_by_repo[repo_key] = path_readiness @@ -1747,7 +1796,11 @@ async def handle_summarize_sample( if repository_readiness is not None and not repository_readiness.ready: return _secondary_readiness_refusal_response(repository_readiness, "summarize_sample") - if persist_flag and repository_readiness is not None and repository_readiness.rebuild: + if ( + persist_flag + and repository_readiness is not None + and getattr(repository_readiness, "rebuild", None) + ): return _rebuild_in_progress_response("summarize_sample", repository_readiness) scope_arg = repository @@ -1855,6 +1908,8 @@ async def handle_summarize_sample( **settings.get_profile_summarization_config(profile_id), "profile_id": profile_id, }, + # Checked at the write itself, after the provider call (#145). + write_fence=_write_fence(repo_resolver, ctx) if persist_flag else None, ) try: @@ -1899,6 +1954,16 @@ async def handle_summarize_sample( "summaries": summary_list, } ) + if persist_flag and getattr(summary_result, "write_fenced", False): + # A rebuild began during the provider call: this file's summaries + # were not stored (#145). + return _rebuild_in_progress_response( + "summarize_sample", + _classify_ctx(repo_resolver, scope_arg), + files=file_results, + total_chunks=total_chunks, + note=_FENCED_WRITE_NOTE, + ) return [ types.TextContent( diff --git a/mcp_server/client.py b/mcp_server/client.py index 96bcc61d..55b21014 100644 --- a/mcp_server/client.py +++ b/mcp_server/client.py @@ -12,6 +12,7 @@ from mcp_server.health.repository_readiness import ( ReadinessClassifier, fresh_readiness, + readiness_queryable, readiness_snapshot, ) from mcp_server.storage.store_registry import StoreRegistry @@ -271,7 +272,7 @@ def _execute_search_service( ) # ``queryable`` also admits stale_commit while a live rebuild indexes a # newer commit; the result then carries that stale readiness (#145). - if readiness is not None and not readiness.queryable: + if readiness is not None and not readiness_queryable(readiness): unavailable: IndexUnavailable | None = _index_unavailable(readiness) return _unavailable_search(options, unavailable) @@ -476,7 +477,7 @@ def _symbol_lookup( str(repository) if repository is not None else None, workspace_root=self.workspace_root, ) - if readiness is not None and not readiness.queryable: + if readiness is not None and not readiness_queryable(readiness): return ClientSymbolResult( symbol=symbol, found=False, diff --git a/mcp_server/core/repo_resolver.py b/mcp_server/core/repo_resolver.py index f5b67faf..73b2d4e7 100644 --- a/mcp_server/core/repo_resolver.py +++ b/mcp_server/core/repo_resolver.py @@ -3,8 +3,9 @@ from __future__ import annotations import logging +from contextlib import contextmanager from pathlib import Path -from typing import TYPE_CHECKING, Callable, Optional, TypeVar +from typing import TYPE_CHECKING, Any, Callable, ContextManager, Iterator, Optional, TypeVar from mcp_server.core.repo_context import RepoContext from mcp_server.health.repository_readiness import ( @@ -120,17 +121,49 @@ def accepts_writes(self, ctx: Optional[RepoContext]) -> bool: """ if ctx is None: return False + return self._accepts_writes_for(ctx.repo_id, ctx.registry_entry) + + def _accepts_writes_for(self, repo_id: str, expected: Any) -> bool: try: - info = self._registry.get(ctx.repo_id) + info = self._registry.get(repo_id) return ( info is not None and not info.staleness_reason - and self._store_registry.binding(info) - == self._store_registry.binding(ctx.registry_entry) + and self._store_registry.binding(info) == self._store_registry.binding(expected) ) except Exception: return False + def write_fence(self, ctx: RepoContext) -> Callable[[], ContextManager[bool]]: + """Return a write fence bound to ctx's registration and published generation.""" + return self.generation_write_fence(ctx.repo_id, ctx.registry_entry, ctx.workspace_root) + + def generation_write_fence( + self, repo_id: str, expected: Any, repo_path: Path + ) -> Callable[[], ContextManager[bool]]: + """Return a fence that persistent writers enter around each write (#145). + + Entering it takes the repository writer lock without waiting, so no + staged build can begin until the write commits; a build that already + holds the lock, a fenced registry entry, or a replaced generation + yields False and the writer stores nothing. + """ + + @contextmanager + def fence() -> Iterator[bool]: + held = lock_registry.acquire(repo_id, repo_path=repo_path, timeout=0) + try: + held.__enter__() + except TimeoutError: + yield False + return + try: + yield self._accepts_writes_for(repo_id, expected) + finally: + held.__exit__(None, None, None) + + return fence + def mutate( self, ctx: RepoContext, operation: Callable[[RepoContext], _MutationResult] ) -> _MutationResult: diff --git a/mcp_server/health/repository_readiness.py b/mcp_server/health/repository_readiness.py index 15f8495f..a1a266fe 100644 --- a/mcp_server/health/repository_readiness.py +++ b/mcp_server/health/repository_readiness.py @@ -132,6 +132,16 @@ def to_dict(self) -> dict[str, Any]: } +def readiness_queryable(readiness: Any) -> bool: + """``readiness.queryable``, falling back to ``ready`` for duck-typed readiness objects.""" + return bool(getattr(readiness, "queryable", getattr(readiness, "ready", False))) + + +def readiness_serving_stale(readiness: Any) -> bool: + """``readiness.serving_stale``, False for duck-typed readiness objects.""" + return bool(getattr(readiness, "serving_stale", False)) + + @dataclass(frozen=True) class SemanticReadiness: state: SemanticReadinessState diff --git a/mcp_server/indexing/summarization.py b/mcp_server/indexing/summarization.py index b14e5f4a..a842bbc4 100644 --- a/mcp_server/indexing/summarization.py +++ b/mcp_server/indexing/summarization.py @@ -6,10 +6,22 @@ import re import sqlite3 import warnings +from contextlib import contextmanager from dataclasses import dataclass, field from pathlib import Path from types import SimpleNamespace -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, cast +from typing import ( + Any, + Callable, + ContextManager, + Dict, + Iterator, + List, + Optional, + Sequence, + Tuple, + cast, +) import mcp.types as types from mcp.shared.exceptions import MCPDeprecationWarning @@ -118,6 +130,10 @@ class SummaryGenerationResult: blocked_call_timeout_seconds: Optional[float] = None cancelled: bool = False summaries: Tuple[GeneratedSummary, ...] = field(default_factory=tuple) + #: A write fence refused at least one write: the target generation was + #: fenced or replaced by a staged rebuild, so those summaries were not + #: stored (Consiliency/Code-Index-MCP#145). + write_fenced: bool = False def __post_init__(self) -> None: object.__setattr__(self, "missing_chunk_ids", tuple(self.missing_chunk_ids)) @@ -140,6 +156,7 @@ def to_dict(self) -> Dict[str, Any]: "blocked_call_chunk_ids": list(self.blocked_call_chunk_ids), "blocked_call_timeout_seconds": self.blocked_call_timeout_seconds, "cancelled": self.cancelled, + "write_fenced": self.write_fenced, "summaries": [ {"chunk_id": item.chunk_id, "summary": item.summary} for item in self.summaries ], @@ -198,6 +215,7 @@ def __init__( session: Any = None, client_name: Optional[str] = None, summarization_config: Optional[Dict[str, Any]] = None, + write_fence: Optional[Callable[[], ContextManager[bool]]] = None, ): self.db_path = db_path self.qdrant_client = qdrant_client @@ -206,6 +224,26 @@ def __init__( self.summarization_config = summarization_config or {} self._sqlite_store: Optional[SQLiteStore] = None self._profile_model_resolution: Optional[EnrichmentModelResolution] = None + #: Entered around every summary write, after the provider call + #: returns: it yields False when the target generation no longer + #: accepts writes (a staged rebuild fenced or replaced it), and the + #: write is then skipped (Consiliency/Code-Index-MCP#145). + self.write_fence = write_fence + self.fenced_writes = 0 + + @contextmanager + def _fenced_write( + self, fence: Optional[Callable[[], ContextManager[bool]]] = None + ) -> Iterator[bool]: + """Yield whether a write may proceed; counts refusals in ``fenced_writes``.""" + fence = fence if fence is not None else self.write_fence + if fence is None: + yield True + return + with fence() as allowed: + if not allowed: + self.fenced_writes += 1 + yield bool(allowed) def _get_sqlite_store(self) -> SQLiteStore: if self._sqlite_store is None: @@ -557,6 +595,7 @@ async def summarize_chunk( file_content: str = "", is_authoritative: bool = False, cancel_check: Optional[Callable[[], bool]] = None, + write_fence: Optional[Callable[[], ContextManager[bool]]] = None, ) -> Optional[str]: """Generate a summary for a code chunk and persist it to SQLite. @@ -704,17 +743,23 @@ async def summarize_chunk( if summary_text is None: return None - self._persist_summary( - chunk_hash=chunk_hash, - file_id=file_id, - chunk_start=chunk_start, - chunk_end=chunk_end, - symbol=symbol, - summary_text=summary_text, - model_name=model_name or "unknown", - is_authoritative=is_authoritative, - **_stop_kwargs(cancel_check), - ) + # The provider call may have taken long enough for a staged rebuild to + # begin; check at the write itself (#145). + with self._fenced_write(write_fence) as allowed: + if not allowed: + logger.info("Chunk summary dropped: its index generation is being rebuilt") + return None + self._persist_summary( + chunk_hash=chunk_hash, + file_id=file_id, + chunk_start=chunk_start, + chunk_end=chunk_end, + symbol=symbol, + summary_text=summary_text, + model_name=model_name or "unknown", + is_authoritative=is_authoritative, + **_stop_kwargs(cancel_check), + ) logger.info("Stored chunk summary via %s", model_name) return summary_text @@ -1073,6 +1118,7 @@ async def summarize_file_chunks( """ if symbol_map is None: symbol_map = {} + fenced_before = self.fenced_writes # Filter already-authoritative chunks. with sqlite3.connect(self.db_path) as conn: @@ -1180,6 +1226,7 @@ async def summarize_file_chunks( ) summaries = recovery + batch_fenced = False if persist and summaries: chunk_lookup = {c["chunk_id"]: c for c in active_chunks} # Resolve the model before the write transaction opens: the first @@ -1191,55 +1238,67 @@ async def summarize_file_chunks( ) persisted_count = 0 # One transaction per provider batch: a failure or interrupt while - # storing leaves none of the batch rather than part of it. - with self._get_sqlite_store()._get_connection() as conn: - conn.execute("BEGIN IMMEDIATE") - persisted_hashes = { - row[0] - for row in conn.execute( - "SELECT chunk_hash FROM chunk_summaries WHERE is_authoritative=1 " - "AND profile_id=? AND prompt_fingerprint=?", - (self.summarization_config.get("profile_id"), self._prompt_fingerprint()), - ).fetchall() - } - for s in summaries: - c = chunk_lookup.get(s.chunk_id) - if c is None or s.chunk_id in persisted_hashes: - continue - sym = _symbol_name(symbol_map, c) - self._persist_summary( - chunk_hash=s.chunk_id, - file_id=file_id, - chunk_start=c.get("line_start") or 1, - chunk_end=c.get("line_end") or 1, - symbol=sym, - summary_text=s.summary, - model_name=model_name or "unknown", - is_authoritative=True, - **_stop_kwargs(cancel_check), - ) - persisted_hashes.add(s.chunk_id) - persisted_count += 1 + # storing leaves none of the batch rather than part of it. The write + # fence wraps the whole transaction, so a staged rebuild cannot + # begin between its check and the commit; if the generation is + # already fenced, none of the batch is written (#145). + with self._fenced_write() as allowed: + if not allowed: + batch_fenced = True + else: + with self._get_sqlite_store()._get_connection() as conn: + conn.execute("BEGIN IMMEDIATE") + persisted_hashes = { + row[0] + for row in conn.execute( + "SELECT chunk_hash FROM chunk_summaries WHERE is_authoritative=1 " + "AND profile_id=? AND prompt_fingerprint=?", + ( + self.summarization_config.get("profile_id"), + self._prompt_fingerprint(), + ), + ).fetchall() + } + for s in summaries: + c = chunk_lookup.get(s.chunk_id) + if c is None or s.chunk_id in persisted_hashes: + continue + sym = _symbol_name(symbol_map, c) + self._persist_summary( + chunk_hash=s.chunk_id, + file_id=file_id, + chunk_start=c.get("line_start") or 1, + chunk_end=c.get("line_end") or 1, + symbol=sym, + summary_text=s.summary, + model_name=model_name or "unknown", + is_authoritative=True, + **_stop_kwargs(cancel_check), + ) + persisted_hashes.add(s.chunk_id) + persisted_count += 1 logger.info( "FileBatchSummarizer: persisted %d summaries for %s", persisted_count, file_path, ) - summarized_chunk_ids = {s.chunk_id for s in summaries} + written = () if batch_fenced else summaries + summarized_chunk_ids = {s.chunk_id for s in written} missing_chunk_ids = [ c["chunk_id"] for c in to_summarize if c["chunk_id"] not in summarized_chunk_ids ] return SummaryGenerationResult( chunks_attempted=len(active_chunks), - summaries_written=len(summaries), - authoritative_chunks=existing_authoritative + len(summaries), + summaries_written=len(written), + authoritative_chunks=existing_authoritative + len(written), missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=1, - files_summarized=1 if summaries else 0, + files_summarized=1 if written else 0, remaining_chunks=len(missing_chunk_ids), scope_drained=len(missing_chunk_ids) == 0, summaries=summaries, + write_fenced=self.fenced_writes > fenced_before, ) @@ -1504,6 +1563,22 @@ async def process_scope( total_authoritative_chunks += file_result.authoritative_chunks total_files_summarized += file_result.files_summarized missing_chunk_ids.extend(file_result.missing_chunk_ids) + if file_result.write_fenced: + # A staged rebuild fenced the target generation: stop + # rather than spend provider calls on unwritable work. + remaining_chunks = self._count_unsummarized_rows(target_paths=target_paths) + return SummaryGenerationResult( + chunks_attempted=total_attempted, + summaries_written=total_summaries_written, + authoritative_chunks=total_authoritative_chunks, + missing_chunk_ids=tuple(missing_chunk_ids), + files_attempted=total_files_attempted, + files_summarized=total_files_summarized, + batches_processed=batches_processed, + remaining_chunks=remaining_chunks, + scope_drained=False, + write_fenced=True, + ) if file_result.blocked_call_reason is not None: remaining_chunks = self._count_unsummarized_rows(target_paths=target_paths) return SummaryGenerationResult( @@ -1610,14 +1685,37 @@ def update_session(self, session: Any) -> None: async def _worker(self) -> None: while True: - chunk = await self.queue.get() + item = await self.queue.get() try: - await self.summarize_chunk(**chunk) + await self._summarize_queued(item) except Exception as exc: logger.error("Error summarizing chunk (%s)", type(exc).__name__) finally: self.queue.task_done() - def enqueue(self, chunk_data: Dict[str, Any]) -> None: - """Add a chunk to the background summarization queue (non-blocking).""" - self.queue.put_nowait(chunk_data) + async def _summarize_queued(self, item: Any) -> Optional[str]: + """Summarize one queued entry unless its index generation was fenced (#145). + + An entry carries the write fence of the generation it was enqueued + for. It is dropped before the provider call when that generation is + already fenced or replaced, and the fence is checked again at the write. + """ + chunk, fence = item if isinstance(item, tuple) else (item, None) + if fence is not None: + with self._fenced_write(fence) as allowed: + if not allowed: + logger.info("Queued chunk summary dropped: its generation is being rebuilt") + return None + return await self.summarize_chunk(**chunk, write_fence=fence) + + def enqueue( + self, + chunk_data: Dict[str, Any], + write_fence: Optional[Callable[[], ContextManager[bool]]] = None, + ) -> None: + """Add a chunk to the background summarization queue (non-blocking). + + ``write_fence`` binds the entry to the generation it was found in, so a + staged rebuild that begins before it is stored drops it (#145). + """ + self.queue.put_nowait((chunk_data, write_fence)) diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py index 7e851c04..358f3c65 100644 --- a/tests/test_issue_145_serve_during_rebuild.py +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -528,8 +528,8 @@ def can_summarize(self) -> bool: def _get_model_name(self) -> str: return "fake-model" - def enqueue(self, chunk) -> None: - self.enqueued.append(chunk) + def enqueue(self, chunk, write_fence=None) -> None: + self.enqueued.append((chunk, write_fence)) class _FakeStore: @@ -627,7 +627,8 @@ def rebuild_starts(): assert len(calls) == 1 assert response["code"] == "rebuild_in_progress" assert response["chunks_summarized"] == 1 - assert "rerun" in response["note"] + assert "Rerun" in response["note"] + _assert_matches_schema("write_summaries", response) def test_summarize_sample_refuses_to_persist_during_a_rebuild(tmp_path, monkeypatch): @@ -783,3 +784,285 @@ def lookup(ctx, symbol): monkeypatch.setattr(server.dispatcher, "lookup", lookup) symbol = _symbol(server, path, "AlphaSymbol") assert symbol["code"] == "index_unavailable", symbol + + +# --------------------------------------------------------------------------- +# Writes are fenced at the persistence point, after the provider call +# --------------------------------------------------------------------------- + + +import threading # noqa: E402 + +from mcp_server.indexing.summarization import ( # noqa: E402 + FileBatchSummarizer, + LazyChunkWriter, +) + + +def _assert_matches_schema(tool: str, response: dict) -> None: + import jsonschema + + from mcp_server.cli.stdio_runner import _build_tool_list + + schema = next(t.output_schema for t in _build_tool_list() if t.name == tool) + jsonschema.validate(response, schema) + + +class _RebuildStarter: + """Starts a staged rebuild the way a real one fences readers and writers.""" + + def __init__(self, server, repo_id: str, path: Path, how: str): + self.server, self.repo_id, self.path, self.how = server, repo_id, path, how + self._release = threading.Event() + self._thread: threading.Thread | None = None + + def start(self) -> None: + if self.how == "none": + return + if self.how == "fence_flag": + info = self.server.registry.get(self.repo_id) + self.server.registry.begin_generation_mutation( + self.repo_id, + expected_registration_id=info.registration_id, + expected_generation=info.index_generation, + ) + return + acquired = threading.Event() + + def hold(): + with locks.lock_registry.acquire(self.repo_id, repo_path=self.path): + acquired.set() + self._release.wait(10) + + self._thread = threading.Thread(target=hold, daemon=True) + self._thread.start() + assert acquired.wait(10) + + def stop(self) -> None: + self._release.set() + if self._thread is not None: + self._thread.join(10) + + +def _summary_rows(db_path: Path) -> int: + import sqlite3 + + with sqlite3.connect(db_path) as conn: + return conn.execute("SELECT COUNT(*) FROM chunk_summaries").fetchone()[0] + + +def _seed_chunk(db_path: Path) -> tuple[int, str]: + """Store one chunk through the store API, which stamps the chunk scheme.""" + from mcp_server.storage.sqlite_store import SQLiteStore + + store = SQLiteStore(str(db_path)) + try: + with store._get_connection() as conn: + file_id = conn.execute("SELECT id FROM files WHERE path LIKE '%alpha.py'").fetchone()[0] + store.store_chunk( + file_id=file_id, + content="def alpha_token():", + content_start=0, + content_end=18, + line_start=1, + line_end=2, + chunk_id="chunk-alpha", + node_id="n", + treesitter_file_id="t", + language="python", + ) + finally: + store.close() + ReadinessClassifier.clear_index_inspection_cache() + return file_id, "chunk-alpha" + + +@pytest.mark.parametrize("how", ["none", "fence_flag", "writer_lock"]) +def test_summarize_sample_write_is_fenced_after_the_provider_call(tmp_path, monkeypatch, how): + path, repo_id = build_temp_repo(tmp_path, f"fenced-sample-{how}", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + published = Path(server.registry.get(repo_id).index_path) + _seed_chunk(published) + starter = _RebuildStarter(server, repo_id, path, how) + provider_calls: list = [] + + async def provider(self, *args, **kwargs): + # The rebuild begins while the provider call is in flight. + provider_calls.append(1) + starter.start() + from types import SimpleNamespace + + return [SimpleNamespace(chunk_id="chunk-alpha", summary="Synthetic summary.")] + + monkeypatch.setattr(FileBatchSummarizer, "_call_batch_api", provider) + monkeypatch.setattr(FileBatchSummarizer, "_call_profile_batch_api", provider) + monkeypatch.setattr( + FileBatchSummarizer, "_get_model_name", lambda self, **kwargs: "fake-model" + ) + try: + response = _run_tool( + "handle_summarize_sample", + arguments={"repository": str(path), "persist": True, "n": 1}, + dispatcher=server.dispatcher, + repo_resolver=server.repo_resolver, + lazy_summarizer=_FakeSummarizer(), + ) + finally: + starter.stop() + + assert provider_calls == [1] + if how == "none": + # Control: with no rebuild the same call persists its summary. + assert response["persisted"] is True and response["total_chunks"] == 1, response + assert _summary_rows(published) == 1 + _assert_matches_schema("summarize_sample", response) + return + assert response["code"] == "rebuild_in_progress", response + assert response["files"][0]["summaries_written"] == 0 + assert response["total_chunks"] == 0 + assert _summary_rows(published) == 0 # nothing reached the old generation + _assert_matches_schema("summarize_sample", response) + + +@pytest.mark.parametrize("how", ["fence_flag", "writer_lock"]) +def test_lazy_queue_entry_is_dropped_when_a_rebuild_starts_mid_call(tmp_path, monkeypatch, how): + path, repo_id = build_temp_repo(tmp_path, f"fenced-lazy-{how}", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + info = server.registry.get(repo_id) + published = Path(info.index_path) + file_id, chunk_id = _seed_chunk(published) + fence = server.repo_resolver.generation_write_fence(repo_id, info, path) + starter = _RebuildStarter(server, repo_id, path, how) + monkeypatch.delenv("CEREBRAS_API_KEY", raising=False) + writer = LazyChunkWriter( + db_path=str(published), + qdrant_client=None, + summarization_config={"base_url": "http://synthetic.invalid/v1"}, + ) + provider_calls: list = [] + + async def direct(*args, **kwargs): + provider_calls.append(1) + starter.start() + return "Synthetic summary.", "fake-model" + + monkeypatch.setattr(writer, "_has_sampling_capability", lambda: False) + monkeypatch.setattr(writer, "_call_direct_api", direct) + chunk = dict( + chunk_hash=chunk_id, + file_id=file_id, + chunk_start=1, + chunk_end=2, + symbol="alpha_token", + content="def alpha_token():", + language="python", + is_authoritative=False, + ) + try: + stored = asyncio.run(writer._summarize_queued((chunk, fence))) + finally: + starter.stop() + assert provider_calls == [1] + assert stored is None + assert writer.fenced_writes == 1 + assert _summary_rows(published) == 0 + + # An entry whose generation is already fenced is dropped before any + # provider call; with no rebuild the same entry is stored. + if how == "fence_flag": + provider_calls.clear() + assert asyncio.run(writer._summarize_queued((chunk, fence))) is None + assert provider_calls == [] + + +def test_lazy_queue_entry_is_stored_without_a_rebuild(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "lazy-stored", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + info = server.registry.get(repo_id) + published = Path(info.index_path) + file_id, chunk_id = _seed_chunk(published) + fence = server.repo_resolver.generation_write_fence(repo_id, info, path) + monkeypatch.delenv("CEREBRAS_API_KEY", raising=False) + writer = LazyChunkWriter( + db_path=str(published), + qdrant_client=None, + summarization_config={"base_url": "http://synthetic.invalid/v1"}, + ) + + async def direct(*args, **kwargs): + return "Synthetic summary.", "fake-model" + + monkeypatch.setattr(writer, "_has_sampling_capability", lambda: False) + monkeypatch.setattr(writer, "_call_direct_api", direct) + chunk = dict( + chunk_hash=chunk_id, + file_id=file_id, + chunk_start=1, + chunk_end=2, + symbol="alpha_token", + content="def alpha_token():", + language="python", + ) + assert asyncio.run(writer._summarize_queued((chunk, fence))) == "Synthetic summary." + assert _summary_rows(published) == 1 + writer_store = writer._sqlite_store + if writer_store is not None: + writer_store.close() + + +def test_search_enqueues_lazy_entries_with_a_generation_fence(tmp_path): + path, repo_id = build_temp_repo(tmp_path, "lazy-fence", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + summarizer = _FakeSummarizer() + _run_tool( + "handle_search_code", + arguments={"query": "alpha_token", "repository": str(path)}, + dispatcher=server.dispatcher, + repo_resolver=server.repo_resolver, + sqlite_store=_FakeStore(), + lazy_summarizer=summarizer, + ) + assert summarizer.enqueued + _chunk, fence = summarizer.enqueued[0] + with fence() as allowed: + assert allowed is True + info = server.registry.get(repo_id) + server.registry.begin_generation_mutation( + repo_id, + expected_registration_id=info.registration_id, + expected_generation=info.index_generation, + ) + with fence() as allowed: + assert allowed is False + + +def test_rebuild_in_progress_responses_match_the_advertised_schemas(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "schemas", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + resolver = server.repo_resolver + _install_fake_writer(monkeypatch) + observed: dict = {} + + def operation(stage): + observed["write"] = _run_tool( + "handle_write_summaries", + arguments={"repository": str(path)}, + dispatcher=server.dispatcher, + repo_resolver=resolver, + lazy_summarizer=_FakeSummarizer(), + ) + observed["sample"] = _run_tool( + "handle_summarize_sample", + arguments={"repository": str(path), "persist": True, "n": 1}, + dispatcher=server.dispatcher, + repo_resolver=resolver, + lazy_summarizer=_FakeSummarizer(), + ) + return {"failed_files": 0} + + run_repository_mutation(resolver, resolver.resolve_ready(path), operation) + + assert observed["write"]["code"] == "rebuild_in_progress" + assert observed["sample"]["code"] == "rebuild_in_progress" + _assert_matches_schema("write_summaries", observed["write"]) + _assert_matches_schema("summarize_sample", observed["sample"]) From b574cacb2e1501c19069621a1da6278985540f4e Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sat, 21 Nov 2026 22:25:34 -0500 Subject: [PATCH 5/8] fix(summaries): tell a busy writer from a rebuild; shared refusal envelope for tasks (#145) Fourth review follow-up for #162. - The persistent-write fence now yields a WriteGate instead of a bool. FENCED means a staged rebuild owns the generation (the entry is fenced or replaced, or a live rebuild owner holds the writer lock), so the work is obsolete. BUSY means another writer (a sync, or `mcp-index repository summarize`) holds the lock while no rebuild runs and the generation is unchanged, so the write is retryable. - write_summaries and summarize_sample(persist=true) return a retryable `writer_busy` result with partial counts on BUSY, and keep `rebuild_in_progress` for FENCED. SummaryGenerationResult gains write_busy, and process_scope stops on either. - Lazy entries are dropped only on FENCED. On BUSY they are requeued with exponential backoff (2 s doubling, capped at 60 s), at most five times, with the generation rechecked when they are admitted again; dropping after the last retry is logged. - Task-backed write_summaries builds its refusal with the same shared envelope (summary_write_refusal) as the synchronous tool, keeping the task counters. writer_busy joins rebuild_in_progress in both tools' output schemas, and jsonschema tests cover the direct and task results. Refs Consiliency/Code-Index-MCP#145 Co-Authored-By: Claude Opus 5.5 --- docs/SUPPORT_MATRIX.md | 16 +- mcp_server/cli/stdio_runner.py | 13 + mcp_server/cli/task_write_summaries.py | 77 +++++- mcp_server/cli/tool_handlers.py | 74 ++++-- mcp_server/core/repo_resolver.py | 39 ++- mcp_server/indexing/lock_registry.py | 25 ++ mcp_server/indexing/summarization.py | 126 +++++++-- tests/test_issue_145_serve_during_rebuild.py | 264 ++++++++++++++++++- 8 files changed, 544 insertions(+), 90 deletions(-) diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 421bc434..0e669178 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -57,12 +57,16 @@ mode, and `summarize_sample` with `persist: true`) return `code: "rebuild_in_progress"` instead of writing into the generation about to be replaced (retry after it publishes). Every summary write is also fenced at the write itself, after the provider call: the writer takes the repository writer -lock without waiting and stores nothing if a build holds it or the generation -was fenced or replaced, so a rebuild that begins mid-call loses no committed -work and the caller gets `rebuild_in_progress` with partial counts. Lazy -summary entries from `search_code` carry the generation they were found in and -are dropped, before the provider call or at the write, once a rebuild fences -it; no new entries are enqueued during a rebuild. Each served query observes `git status` once for admission and once +lock without waiting and stores nothing for that batch unless it gets the lock +and the generation is unchanged. If a staged rebuild owns the generation (a +live owner holds the lock, or the entry is fenced or replaced) the caller gets +`rebuild_in_progress`; if another writer (a sync, or `mcp-index repository +summarize`) merely holds the lock, the caller gets a retryable `code: +"writer_busy"`. Both carry partial counts, and committed work is always kept. +Lazy summary entries from `search_code` carry the generation they were found +in: a rebuild drops them (before the provider call or at the write), while a +busy writer requeues them with backoff, at most five times; no new entries are +enqueued during a rebuild. Each served query observes `git status` once for admission and once more, fresh, after the query; a HEAD move or newly dirty tree during the query returns `index_unavailable` so the caller retries. diff --git a/mcp_server/cli/stdio_runner.py b/mcp_server/cli/stdio_runner.py index b9f0f273..a93eb238 100644 --- a/mcp_server/cli/stdio_runner.py +++ b/mcp_server/cli/stdio_runner.py @@ -237,6 +237,7 @@ def resolve(self, path: Any) -> Any: "readiness": {"type": ["object", "null"]}, "message": {"type": "string"}, "remediation": {"type": ["string", "array", "object", "null"]}, + "retryable": {"type": "boolean"}, "chunks_summarized": {"type": "integer"}, "files": {"type": "array"}, "total_chunks": {"type": "integer"}, @@ -245,6 +246,16 @@ def resolve(self, path: Any) -> Any: "required": ["error", "code", "tool", "mutation_performed", "message"], "additionalProperties": True, } +#: Another writer held the repository writer lock while no rebuild ran; the +#: summary write is retryable (#145). +_WRITER_BUSY_SCHEMA: dict[str, Any] = { + **_REBUILD_IN_PROGRESS_SCHEMA, + "properties": { + **_REBUILD_IN_PROGRESS_SCHEMA["properties"], + "error": {"const": "Index writer busy"}, + "code": {"const": "writer_busy"}, + }, +} _SQLITE_NOT_INITIALIZED_SCHEMA: dict[str, Any] = { "type": "object", "properties": { @@ -798,6 +809,7 @@ def _build_tool_list() -> list[types.Tool]: _INDEX_UNAVAILABLE_SCHEMA, _SECONDARY_READINESS_REFUSAL_SCHEMA, _REBUILD_IN_PROGRESS_SCHEMA, + _WRITER_BUSY_SCHEMA, _SUMMARIZATION_UNAVAILABLE_SCHEMA, _SQLITE_NOT_INITIALIZED_SCHEMA, _object_schema( @@ -870,6 +882,7 @@ def _build_tool_list() -> list[types.Tool]: _SECONDARY_READINESS_REFUSAL_SCHEMA, _CONFLICTING_SCOPE_SCHEMA, _REBUILD_IN_PROGRESS_SCHEMA, + _WRITER_BUSY_SCHEMA, _SUMMARIZATION_UNAVAILABLE_SCHEMA, _SQLITE_NOT_INITIALIZED_SCHEMA, _object_schema( diff --git a/mcp_server/cli/task_write_summaries.py b/mcp_server/cli/task_write_summaries.py index c20392a4..2c851086 100644 --- a/mcp_server/cli/task_write_summaries.py +++ b/mcp_server/cli/task_write_summaries.py @@ -13,6 +13,61 @@ from mcp_server.indexing.summarization import ComprehensiveChunkWriter from mcp_server.storage.mcp_task_registry import MCPTaskRegistry +REBUILD_IN_PROGRESS = "rebuild_in_progress" +WRITER_BUSY = "writer_busy" + +_REFUSALS: dict[str, tuple[str, str, str]] = { + REBUILD_IN_PROGRESS: ( + "Rebuild in progress", + "A staged index rebuild owns this repository's published generation; " + "summaries written to it now would be lost when the rebuild publishes.", + "Retry after the staged rebuild publishes (already summarized chunks are skipped).", + ), + WRITER_BUSY: ( + "Index writer busy", + "Another index writer (a sync, or `mcp-index repository summarize`) holds the " + "repository writer lock. No rebuild is running; summaries that could not be " + "stored were not written.", + "Retry shortly (already summarized chunks are skipped).", + ), +} + + +def summary_write_refusal( + code: str, + tool: str, + *, + readiness: dict[str, Any] | None = None, + **extra: Any, +) -> dict[str, Any]: + """The shared envelope for a summary write that could not be stored (#145). + + ``code`` is ``rebuild_in_progress`` (the generation is being replaced) or + ``writer_busy`` (another writer holds the lock; retry shortly). Partial + counters in ``extra`` (``chunks_summarized``, ``total_chunks``, ...) say + what was already committed; committed work always precedes any rebuild's + snapshot, so it is kept. + """ + error, message, remediation = _REFUSALS[code] + written = int(extra.get("chunks_summarized") or extra.get("total_chunks") or 0) + payload: dict[str, Any] = { + "error": error, + "code": code, + "tool": tool, + "mutation_performed": written > 0, + "retryable": True, + "readiness": readiness, + "message": message, + "remediation": remediation, + **extra, + } + if written and "note" not in payload: + payload["note"] = ( + f"{written} summaries were committed before the write was refused and are " + "kept; the rest were not written." + ) + return payload + def _call_tool_result(payload: dict[str, Any], *, is_error: bool = False) -> types.CallToolResult: return types.CallToolResult( @@ -63,6 +118,7 @@ async def run_write_summaries_task( remaining_budget = limit_arg persisted_any = False write_fenced = False + write_busy = False per_pass_limit = min(64, limit_arg) async def cancel_observer() -> None: @@ -86,6 +142,7 @@ async def cancel_observer() -> None: or (write_blocked is not None and write_blocked()), ) write_fenced = write_fenced or bool(getattr(result, "write_fenced", False)) + write_busy = write_busy or bool(getattr(result, "write_busy", False)) total_written += result.summaries_written total_attempted += result.chunks_attempted total_missing = result.remaining_chunks @@ -105,7 +162,7 @@ async def cancel_observer() -> None: "persisted": persisted_any, }, ) - if result.cancelled or task.is_cancelled or write_fenced: + if result.cancelled or task.is_cancelled or write_fenced or write_busy: break if result.summaries_written == 0 or result.remaining_chunks == 0: break @@ -120,15 +177,15 @@ async def cancel_observer() -> None: "summary_chunks_attempted": total_attempted, "summary_missing_chunks": total_missing, } - if write_fenced or (write_blocked is not None and write_blocked()): - payload.update( - code="rebuild_in_progress", - note=( - "A staged rebuild started during this task. Summaries already committed " - "were written before it began and are kept; the rest were not written. " - "Rerun after the rebuild publishes (already summarized chunks are skipped)." - ), - ) + refusal = ( + REBUILD_IN_PROGRESS + if write_fenced or (write_blocked is not None and write_blocked()) + else WRITER_BUSY if write_busy else None + ) + if refusal is not None and not task.is_cancelled: + # Same envelope as the synchronous tool, with the task's counters (#145). + counters = {key: value for key, value in payload.items() if key != "persisted"} + return _call_tool_result(summary_write_refusal(refusal, "write_summaries", **counters)) if task.is_cancelled: payload["cancelled"] = True result = _call_tool_result(payload) diff --git a/mcp_server/cli/tool_handlers.py b/mcp_server/cli/tool_handlers.py index ef84cb75..1789e831 100644 --- a/mcp_server/cli/tool_handlers.py +++ b/mcp_server/cli/tool_handlers.py @@ -24,7 +24,12 @@ _record_reindexed_files, run_reindex_task, ) -from mcp_server.cli.task_write_summaries import run_write_summaries_task +from mcp_server.cli.task_write_summaries import ( + REBUILD_IN_PROGRESS, + WRITER_BUSY, + run_write_summaries_task, + summary_write_refusal, +) from mcp_server.client import ClientValidationError, build_search_options, execute_search_service from mcp_server.core.repo_context import RepoContext from mcp_server.core.repo_resolver import RepoResolver, run_repository_mutation @@ -271,27 +276,27 @@ def _rebuild_in_progress_response( written to it now would vanish when the rebuild publishes. """ return _json_text_response( - { - "error": "Rebuild in progress", - "code": "rebuild_in_progress", - "tool": tool, - "mutation_performed": False, - "readiness": readiness.to_dict() if readiness is not None else None, - "message": ( - "A staged index rebuild is in progress; writes to the published " - "generation would be lost when it publishes." - ), - "remediation": "Retry after the rebuild publishes (readiness.rebuild becomes null).", + summary_write_refusal( + REBUILD_IN_PROGRESS, + tool, + readiness=readiness.to_dict() if readiness is not None else None, **extra, - } + ) ) -_FENCED_WRITE_NOTE = ( - "A staged rebuild started during this run. Summaries already committed were " - "written before it began and are kept; the rest were not written. Rerun after " - "the rebuild publishes (already summarized chunks are skipped)." -) +def _writer_busy_response( + tool: str, readiness: Optional[RepositoryReadiness] = None, **extra: Any +) -> list[types.TextContent]: + """Another writer held the lock at a write; no rebuild runs; retryable (#145).""" + return _json_text_response( + summary_write_refusal( + WRITER_BUSY, + tool, + readiness=readiness.to_dict() if readiness is not None else None, + **extra, + ) + ) def _write_fence(repo_resolver: Any, ctx: Optional[RepoContext]) -> Any: @@ -1663,12 +1668,20 @@ def write_blocked() -> bool: write_fence=write_fence, ) summary_result = await writer.process_scope(limit=limit_arg, cancel_check=write_blocked) + partial = dict( + chunks_summarized=summary_result.summaries_written, + limit=limit_arg, + model_used=model_used, + summary_chunks_attempted=summary_result.chunks_attempted, + summary_missing_chunks=len(summary_result.missing_chunk_ids), + ) if getattr(summary_result, "write_fenced", False) or write_blocked(): return _rebuild_in_progress_response( - "write_summaries", - _classify_ctx(repo_resolver, repository), - chunks_summarized=summary_result.summaries_written, - note=_FENCED_WRITE_NOTE, + "write_summaries", _classify_ctx(repo_resolver, repository), **partial + ) + if getattr(summary_result, "write_busy", False): + return _writer_busy_response( + "write_summaries", _classify_ctx(repo_resolver, repository), **partial ) return [ @@ -1954,15 +1967,22 @@ async def handle_summarize_sample( "summaries": summary_list, } ) - if persist_flag and getattr(summary_result, "write_fenced", False): - # A rebuild began during the provider call: this file's summaries - # were not stored (#145). - return _rebuild_in_progress_response( + if persist_flag and ( + getattr(summary_result, "write_fenced", False) + or getattr(summary_result, "write_busy", False) + ): + # A rebuild began, or another writer held the lock, during the + # provider call: this file's summaries were not stored (#145). + refuse = ( + _rebuild_in_progress_response + if getattr(summary_result, "write_fenced", False) + else _writer_busy_response + ) + return refuse( "summarize_sample", _classify_ctx(repo_resolver, scope_arg), files=file_results, total_chunks=total_chunks, - note=_FENCED_WRITE_NOTE, ) return [ diff --git a/mcp_server/core/repo_resolver.py b/mcp_server/core/repo_resolver.py index 73b2d4e7..fd4b4867 100644 --- a/mcp_server/core/repo_resolver.py +++ b/mcp_server/core/repo_resolver.py @@ -13,7 +13,7 @@ RepositoryReadiness, RepositoryReadinessState, ) -from mcp_server.indexing.lock_registry import lock_registry +from mcp_server.indexing.lock_registry import WriteGate, live_rebuild_owner, lock_registry from mcp_server.storage.repository_registry import RepositoryRegistry from mcp_server.storage.store_registry import StoreRegistry @@ -144,26 +144,51 @@ def generation_write_fence( """Return a fence that persistent writers enter around each write (#145). Entering it takes the repository writer lock without waiting, so no - staged build can begin until the write commits; a build that already - holds the lock, a fenced registry entry, or a replaced generation - yields False and the writer stores nothing. + staged build can begin until the write commits. It yields a + ``WriteGate`` (falsy unless ``ALLOWED``): + + - ``FENCED`` when a staged rebuild owns the generation (a live owner + holds the lock, or the registry entry is fenced) or the + registration or generation changed: the work is obsolete. + - ``BUSY`` when another writer holds the lock but the generation is + unchanged and no rebuild runs: the write is retryable. """ @contextmanager - def fence() -> Iterator[bool]: + def fence() -> Iterator[WriteGate]: held = lock_registry.acquire(repo_id, repo_path=repo_path, timeout=0) try: held.__enter__() except TimeoutError: - yield False + yield self._contended_gate(repo_id, expected, repo_path) return try: - yield self._accepts_writes_for(repo_id, expected) + yield ( + WriteGate.ALLOWED + if self._accepts_writes_for(repo_id, expected) + else WriteGate.FENCED + ) finally: held.__exit__(None, None, None) return fence + def _contended_gate(self, repo_id: str, expected: Any, repo_path: Path) -> WriteGate: + """Classify a held writer lock: a rebuild (or changed generation) vs. a busy writer.""" + if not self._accepts_writes_for(repo_id, expected): + return WriteGate.FENCED + if ( + live_rebuild_owner( + Path(repo_path), + registration_id=getattr(expected, "registration_id", None), + published_generation=getattr(expected, "index_generation", None), + ) + is not None + ): + # The build holds the lock and recorded itself before fencing. + return WriteGate.FENCED + return WriteGate.BUSY + def mutate( self, ctx: RepoContext, operation: Callable[[RepoContext], _MutationResult] ) -> _MutationResult: diff --git a/mcp_server/indexing/lock_registry.py b/mcp_server/indexing/lock_registry.py index 52c0ff92..20012aa2 100644 --- a/mcp_server/indexing/lock_registry.py +++ b/mcp_server/indexing/lock_registry.py @@ -9,6 +9,7 @@ import time from contextlib import contextmanager from datetime import datetime, timezone +from enum import Enum from pathlib import Path from typing import Dict, Optional @@ -93,6 +94,30 @@ def acquire(self, repo_id: str, *, repo_path: Optional[Path] = None, timeout: fl _OWNER_FILE = "rebuild-owner.json" +class WriteGate(str, Enum): + """What a persistent-write fence decided (Consiliency/Code-Index-MCP#145). + + ``FENCED``: a staged rebuild owns the target generation, or the + registration or generation changed; work for it is obsolete. ``BUSY``: + another writer (a sync, ``repository summarize``) holds the writer lock + while the generation is unchanged; the write is retryable. + """ + + ALLOWED = "allowed" + FENCED = "fenced" + BUSY = "busy" + + def __bool__(self) -> bool: + return self is WriteGate.ALLOWED + + @classmethod + def of(cls, value: object) -> "WriteGate": + """Normalize a fence's yield: True/False (legacy) or a WriteGate.""" + if isinstance(value, WriteGate): + return value + return cls.ALLOWED if value is True else cls.FENCED + + def _index_lock_dir(repo_path: Path) -> Path: return Path(repo_path).resolve() / ".mcp-index" diff --git a/mcp_server/indexing/summarization.py b/mcp_server/indexing/summarization.py index a842bbc4..2df25b81 100644 --- a/mcp_server/indexing/summarization.py +++ b/mcp_server/indexing/summarization.py @@ -5,6 +5,7 @@ import os import re import sqlite3 +import time import warnings from contextlib import contextmanager from dataclasses import dataclass, field @@ -28,6 +29,7 @@ from mcp.types.version import HANDSHAKE_PROTOCOL_VERSIONS from ..config.settings import commercial_egress_allowed, learned_models_allowed +from ..indexing.lock_registry import WriteGate from ..setup.semantic_preflight import EnrichmentModelResolution, resolve_enrichment_model from ..storage.sqlite_store import SQLiteStore, assert_chunk_scheme_readable @@ -134,6 +136,10 @@ class SummaryGenerationResult: #: fenced or replaced by a staged rebuild, so those summaries were not #: stored (Consiliency/Code-Index-MCP#145). write_fenced: bool = False + #: Another writer held the repository writer lock at a write while the + #: generation was unchanged; those summaries were not stored and the call + #: is retryable (#145). + write_busy: bool = False def __post_init__(self) -> None: object.__setattr__(self, "missing_chunk_ids", tuple(self.missing_chunk_ids)) @@ -157,6 +163,7 @@ def to_dict(self) -> Dict[str, Any]: "blocked_call_timeout_seconds": self.blocked_call_timeout_seconds, "cancelled": self.cancelled, "write_fenced": self.write_fenced, + "write_busy": self.write_busy, "summaries": [ {"chunk_id": item.chunk_id, "summary": item.summary} for item in self.summaries ], @@ -225,25 +232,30 @@ def __init__( self._sqlite_store: Optional[SQLiteStore] = None self._profile_model_resolution: Optional[EnrichmentModelResolution] = None #: Entered around every summary write, after the provider call - #: returns: it yields False when the target generation no longer - #: accepts writes (a staged rebuild fenced or replaced it), and the - #: write is then skipped (Consiliency/Code-Index-MCP#145). + #: returns: it yields a ``WriteGate`` (or a bool) and the write is + #: skipped unless it is allowed. ``fenced_writes`` counts writes a + #: staged rebuild made obsolete, ``busy_writes`` writes refused only + #: because another writer held the lock (Consiliency/Code-Index-MCP#145). self.write_fence = write_fence self.fenced_writes = 0 + self.busy_writes = 0 @contextmanager def _fenced_write( - self, fence: Optional[Callable[[], ContextManager[bool]]] = None - ) -> Iterator[bool]: - """Yield whether a write may proceed; counts refusals in ``fenced_writes``.""" + self, fence: Optional[Callable[[], ContextManager[Any]]] = None + ) -> Iterator[WriteGate]: + """Yield the fence's ``WriteGate`` for one write and count refusals.""" fence = fence if fence is not None else self.write_fence if fence is None: - yield True + yield WriteGate.ALLOWED return - with fence() as allowed: - if not allowed: + with fence() as decision: + gate = WriteGate.of(decision) + if gate is WriteGate.FENCED: self.fenced_writes += 1 - yield bool(allowed) + elif gate is WriteGate.BUSY: + self.busy_writes += 1 + yield gate def _get_sqlite_store(self) -> SQLiteStore: if self._sqlite_store is None: @@ -747,7 +759,7 @@ async def summarize_chunk( # begin; check at the write itself (#145). with self._fenced_write(write_fence) as allowed: if not allowed: - logger.info("Chunk summary dropped: its index generation is being rebuilt") + logger.info("Chunk summary not stored: index write %s", allowed.value) return None self._persist_summary( chunk_hash=chunk_hash, @@ -1119,6 +1131,7 @@ async def summarize_file_chunks( if symbol_map is None: symbol_map = {} fenced_before = self.fenced_writes + busy_before = self.busy_writes # Filter already-authoritative chunks. with sqlite3.connect(self.db_path) as conn: @@ -1299,6 +1312,7 @@ async def summarize_file_chunks( scope_drained=len(missing_chunk_ids) == 0, summaries=summaries, write_fenced=self.fenced_writes > fenced_before, + write_busy=self.busy_writes > busy_before, ) @@ -1563,9 +1577,10 @@ async def process_scope( total_authoritative_chunks += file_result.authoritative_chunks total_files_summarized += file_result.files_summarized missing_chunk_ids.extend(file_result.missing_chunk_ids) - if file_result.write_fenced: - # A staged rebuild fenced the target generation: stop - # rather than spend provider calls on unwritable work. + if file_result.write_fenced or file_result.write_busy: + # A staged rebuild fenced the target generation, or + # another writer holds the lock: stop rather than spend + # provider calls on work that cannot be stored now. remaining_chunks = self._count_unsummarized_rows(target_paths=target_paths) return SummaryGenerationResult( chunks_attempted=total_attempted, @@ -1577,7 +1592,8 @@ async def process_scope( batches_processed=batches_processed, remaining_chunks=remaining_chunks, scope_drained=False, - write_fenced=True, + write_fenced=file_result.write_fenced, + write_busy=file_result.write_busy, ) if file_result.blocked_call_reason is not None: remaining_chunks = self._count_unsummarized_rows(target_paths=target_paths) @@ -1687,6 +1703,10 @@ async def _worker(self) -> None: while True: item = await self.queue.get() try: + if isinstance(item, _QueuedSummary): + delay = item.not_before - time.monotonic() + if delay > 0: + await asyncio.sleep(delay) await self._summarize_queued(item) except Exception as exc: logger.error("Error summarizing chunk (%s)", type(exc).__name__) @@ -1694,28 +1714,76 @@ async def _worker(self) -> None: self.queue.task_done() async def _summarize_queued(self, item: Any) -> Optional[str]: - """Summarize one queued entry unless its index generation was fenced (#145). + """Summarize one queued entry against the generation it was found in (#145). - An entry carries the write fence of the generation it was enqueued - for. It is dropped before the provider call when that generation is - already fenced or replaced, and the fence is checked again at the write. + An entry carries the write fence of its generation. It is dropped when + a staged rebuild has fenced or replaced that generation (before the + provider call, or at the write). When another writer only holds the + lock, it is requeued with backoff, up to ``MAX_BUSY_RETRIES`` times. """ - chunk, fence = item if isinstance(item, tuple) else (item, None) - if fence is not None: - with self._fenced_write(fence) as allowed: - if not allowed: - logger.info("Queued chunk summary dropped: its generation is being rebuilt") - return None - return await self.summarize_chunk(**chunk, write_fence=fence) + if isinstance(item, _QueuedSummary): + entry = item + elif isinstance(item, tuple): + entry = _QueuedSummary(chunk=item[0], fence=item[1]) + else: + entry = _QueuedSummary(chunk=item, fence=None) + if entry.fence is not None: + with self._fenced_write(entry.fence) as gate: + pass + if gate is WriteGate.FENCED: + logger.info("Queued chunk summary dropped: its generation is being rebuilt") + return None + if gate is WriteGate.BUSY: + self._requeue_busy(entry) + return None + busy_before = self.busy_writes + summary = await self.summarize_chunk(**entry.chunk, write_fence=entry.fence) + if summary is None and self.busy_writes > busy_before: + self._requeue_busy(entry) + return summary + + #: Requeues of one lazy entry while another writer holds the lock. + MAX_BUSY_RETRIES = 5 + #: Backoff seconds for the first busy retry; doubles per retry, capped. + BUSY_RETRY_BASE_SECONDS = 2.0 + BUSY_RETRY_MAX_SECONDS = 60.0 + + def _requeue_busy(self, entry: "_QueuedSummary") -> None: + if entry.attempts >= self.MAX_BUSY_RETRIES: + logger.warning( + "Queued chunk summary dropped after %d retries: the index writer stayed busy", + entry.attempts, + ) + return + delay = min(self.BUSY_RETRY_MAX_SECONDS, self.BUSY_RETRY_BASE_SECONDS * (2**entry.attempts)) + self.queue.put_nowait( + _QueuedSummary( + chunk=entry.chunk, + fence=entry.fence, + attempts=entry.attempts + 1, + not_before=time.monotonic() + delay, + ) + ) def enqueue( self, chunk_data: Dict[str, Any], - write_fence: Optional[Callable[[], ContextManager[bool]]] = None, + write_fence: Optional[Callable[[], ContextManager[Any]]] = None, ) -> None: """Add a chunk to the background summarization queue (non-blocking). ``write_fence`` binds the entry to the generation it was found in, so a - staged rebuild that begins before it is stored drops it (#145). + staged rebuild that begins before it is stored drops it, and a busy + writer delays it (#145). """ - self.queue.put_nowait((chunk_data, write_fence)) + self.queue.put_nowait(_QueuedSummary(chunk=chunk_data, fence=write_fence)) + + +@dataclass(frozen=True) +class _QueuedSummary: + """One lazy summary entry and the generation fence it was enqueued with.""" + + chunk: Dict[str, Any] + fence: Optional[Callable[[], ContextManager[Any]]] + attempts: int = 0 + not_before: float = 0.0 diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py index 358f3c65..a3f99e56 100644 --- a/tests/test_issue_145_serve_during_rebuild.py +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -627,7 +627,9 @@ def rebuild_starts(): assert len(calls) == 1 assert response["code"] == "rebuild_in_progress" assert response["chunks_summarized"] == 1 - assert "Rerun" in response["note"] + assert response["mutation_performed"] is True + assert response["retryable"] is True + assert "kept" in response["note"] _assert_matches_schema("write_summaries", response) @@ -809,12 +811,19 @@ def _assert_matches_schema(tool: str, response: dict) -> None: class _RebuildStarter: - """Starts a staged rebuild the way a real one fences readers and writers.""" + """Starts a competing writer while a summary provider call is in flight. + + ``fence_flag``: a staged build fenced the registry entry. ``rebuild_lock``: + a staged build holds the writer lock and recorded itself as the live + owner, before fencing. ``busy_lock``: an ordinary writer (a sync, or + ``repository summarize``) holds the lock; no rebuild runs. + """ def __init__(self, server, repo_id: str, path: Path, how: str): self.server, self.repo_id, self.path, self.how = server, repo_id, path, how self._release = threading.Event() self._thread: threading.Thread | None = None + self._owner: dict | None = None def start(self) -> None: if self.how == "none": @@ -828,9 +837,17 @@ def start(self) -> None: ) return acquired = threading.Event() + info = self.server.registry.get(self.repo_id) def hold(): with locks.lock_registry.acquire(self.repo_id, repo_path=self.path): + if self.how == "rebuild_lock": + self._owner = locks.record_rebuild_owner( + self.path, + registration_id=info.registration_id, + published_generation=info.index_generation, + target_commit=git_head(self.path), + ) acquired.set() self._release.wait(10) @@ -842,6 +859,8 @@ def stop(self) -> None: self._release.set() if self._thread is not None: self._thread.join(10) + if self._owner is not None: + locks.clear_rebuild_owner(self.path, self._owner["token"]) def _summary_rows(db_path: Path) -> int: @@ -877,7 +896,7 @@ def _seed_chunk(db_path: Path) -> tuple[int, str]: return file_id, "chunk-alpha" -@pytest.mark.parametrize("how", ["none", "fence_flag", "writer_lock"]) +@pytest.mark.parametrize("how", ["none", "fence_flag", "rebuild_lock", "busy_lock"]) def test_summarize_sample_write_is_fenced_after_the_provider_call(tmp_path, monkeypatch, how): path, repo_id = build_temp_repo(tmp_path, f"fenced-sample-{how}", seed_files=SEED) with boot_test_server(tmp_path, [path]) as server: @@ -917,14 +936,17 @@ async def provider(self, *args, **kwargs): assert _summary_rows(published) == 1 _assert_matches_schema("summarize_sample", response) return - assert response["code"] == "rebuild_in_progress", response + expected = "writer_busy" if how == "busy_lock" else "rebuild_in_progress" + assert response["code"] == expected, response + assert response["retryable"] is True + assert response["mutation_performed"] is False assert response["files"][0]["summaries_written"] == 0 assert response["total_chunks"] == 0 - assert _summary_rows(published) == 0 # nothing reached the old generation + assert _summary_rows(published) == 0 # nothing reached the index _assert_matches_schema("summarize_sample", response) -@pytest.mark.parametrize("how", ["fence_flag", "writer_lock"]) +@pytest.mark.parametrize("how", ["fence_flag", "rebuild_lock"]) def test_lazy_queue_entry_is_dropped_when_a_rebuild_starts_mid_call(tmp_path, monkeypatch, how): path, repo_id = build_temp_repo(tmp_path, f"fenced-lazy-{how}", seed_files=SEED) with boot_test_server(tmp_path, [path]) as server: @@ -964,7 +986,8 @@ async def direct(*args, **kwargs): starter.stop() assert provider_calls == [1] assert stored is None - assert writer.fenced_writes == 1 + assert writer.fenced_writes == 1 and writer.busy_writes == 0 + assert writer.queue.qsize() == 0 # dropped, not requeued assert _summary_rows(published) == 0 # An entry whose generation is already fenced is dropped before any @@ -1024,16 +1047,16 @@ def test_search_enqueues_lazy_entries_with_a_generation_fence(tmp_path): ) assert summarizer.enqueued _chunk, fence = summarizer.enqueued[0] - with fence() as allowed: - assert allowed is True + with fence() as gate: + assert gate is locks.WriteGate.ALLOWED info = server.registry.get(repo_id) server.registry.begin_generation_mutation( repo_id, expected_registration_id=info.registration_id, expected_generation=info.index_generation, ) - with fence() as allowed: - assert allowed is False + with fence() as gate: + assert gate is locks.WriteGate.FENCED def test_rebuild_in_progress_responses_match_the_advertised_schemas(tmp_path, monkeypatch): @@ -1066,3 +1089,222 @@ def operation(stage): assert observed["sample"]["code"] == "rebuild_in_progress" _assert_matches_schema("write_summaries", observed["write"]) _assert_matches_schema("summarize_sample", observed["sample"]) + + +# --------------------------------------------------------------------------- +# A busy (non-rebuild) writer is retryable, never a silent drop +# --------------------------------------------------------------------------- + + +def _lazy_writer(published: Path, monkeypatch, on_call=None) -> tuple: + monkeypatch.delenv("CEREBRAS_API_KEY", raising=False) + writer = LazyChunkWriter( + db_path=str(published), + qdrant_client=None, + summarization_config={"base_url": "http://synthetic.invalid/v1"}, + ) + calls: list = [] + + async def direct(*args, **kwargs): + calls.append(1) + if on_call is not None: + on_call() + return "Synthetic summary.", "fake-model" + + monkeypatch.setattr(writer, "_has_sampling_capability", lambda: False) + monkeypatch.setattr(writer, "_call_direct_api", direct) + return writer, calls + + +def _lazy_chunk(file_id: int, chunk_id: str) -> dict: + return dict( + chunk_hash=chunk_id, + file_id=file_id, + chunk_start=1, + chunk_end=2, + symbol="alpha_token", + content="def alpha_token():", + language="python", + ) + + +def test_lazy_entry_is_requeued_while_a_non_rebuild_writer_holds_the_lock(tmp_path, monkeypatch): + path, repo_id = build_temp_repo(tmp_path, "lazy-busy", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + info = server.registry.get(repo_id) + published = Path(info.index_path) + file_id, chunk_id = _seed_chunk(published) + fence = server.repo_resolver.generation_write_fence(repo_id, info, path) + busy = _RebuildStarter(server, repo_id, path, "busy_lock") + writer, calls = _lazy_writer(published, monkeypatch, on_call=busy.start) + writer.enqueue(_lazy_chunk(file_id, chunk_id), write_fence=fence) + try: + # The busy writer took the lock during the provider call. + assert asyncio.run(writer._summarize_queued(writer.queue.get_nowait())) is None + assert writer.busy_writes == 1 and writer.fenced_writes == 0 + assert _summary_rows(published) == 0 + requeued = writer.queue.get_nowait() + assert requeued.attempts == 1 and requeued.not_before > 0 + # Still busy when it comes round again: requeued before any + # provider call. + calls.clear() + assert asyncio.run(writer._summarize_queued(requeued)) is None + assert calls == [] + requeued = writer.queue.get_nowait() + assert requeued.attempts == 2 + finally: + busy.stop() + # The other writer finished and no rebuild ran: the generation is + # rechecked and the entry is stored. + assert asyncio.run(writer._summarize_queued(requeued)) == "Synthetic summary." + assert _summary_rows(published) == 1 + assert writer.queue.qsize() == 0 + if writer._sqlite_store is not None: + writer._sqlite_store.close() + + +def test_lazy_busy_retries_are_bounded(tmp_path, monkeypatch, caplog): + from mcp_server.indexing.summarization import _QueuedSummary + + path, repo_id = build_temp_repo(tmp_path, "lazy-bounded", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + info = server.registry.get(repo_id) + published = Path(info.index_path) + file_id, chunk_id = _seed_chunk(published) + fence = server.repo_resolver.generation_write_fence(repo_id, info, path) + writer, calls = _lazy_writer(published, monkeypatch) + busy = _RebuildStarter(server, repo_id, path, "busy_lock") + busy.start() + try: + last = _QueuedSummary( + chunk=_lazy_chunk(file_id, chunk_id), + fence=fence, + attempts=writer.MAX_BUSY_RETRIES, + ) + with caplog.at_level("WARNING"): + assert asyncio.run(writer._summarize_queued(last)) is None + finally: + busy.stop() + assert writer.queue.qsize() == 0 + assert calls == [] + assert "stayed busy" in caplog.text + + +def test_write_summaries_reports_writer_busy_with_partial_counts(tmp_path, monkeypatch): + from types import SimpleNamespace + + from mcp_server.indexing.summarization import ComprehensiveChunkWriter + + path, repo_id = build_temp_repo(tmp_path, "busy-write", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + published = Path(server.registry.get(repo_id).index_path) + _seed_chunk(published) + busy = _RebuildStarter(server, repo_id, path, "busy_lock") + + async def provider(self, *args, **kwargs): + if not busy._release.is_set(): + busy.start() + return [SimpleNamespace(chunk_id="chunk-alpha", summary="Synthetic summary.")] + + monkeypatch.setattr(FileBatchSummarizer, "_call_batch_api", provider) + monkeypatch.setattr(FileBatchSummarizer, "_call_profile_batch_api", provider) + monkeypatch.setattr( + FileBatchSummarizer, "_get_model_name", lambda self, **kwargs: "fake-model" + ) + monkeypatch.setattr(ComprehensiveChunkWriter, "can_summarize", lambda self: True) + common = dict( + arguments={"repository": str(path)}, + dispatcher=server.dispatcher, + repo_resolver=server.repo_resolver, + lazy_summarizer=_FakeSummarizer(), + ) + try: + response = _run_tool("handle_write_summaries", **common) + finally: + busy.stop() + + assert response["code"] == "writer_busy", response + assert response["retryable"] is True + assert response["mutation_performed"] is False + assert response["chunks_summarized"] == 0 + assert response["summary_chunks_attempted"] == 1 + assert response["readiness"]["rebuild"] is None # no rebuild was running + assert _summary_rows(published) == 0 + _assert_matches_schema("write_summaries", response) + + # Once the other writer is done, the retry stores the summary. + retry = _run_tool("handle_write_summaries", **common) + assert retry["persisted"] is True and retry["chunks_summarized"] == 1, retry + assert _summary_rows(published) == 1 + _assert_matches_schema("write_summaries", retry) + + +class _FakeTask: + def __init__(self, task_id: str) -> None: + self.task_id = task_id + self.is_cancelled = False + + def request_cancellation(self) -> None: + self.is_cancelled = True + + async def update_status(self, message: str) -> None: + pass + + +@pytest.mark.parametrize( + ("outcome", "code"), + [("write_fenced", "rebuild_in_progress"), ("write_busy", "writer_busy")], +) +def test_task_write_summaries_refusal_matches_the_advertised_schema(monkeypatch, outcome, code): + from types import SimpleNamespace + + from mcp.types import TaskMetadata + + from mcp_server.cli import task_write_summaries + from mcp_server.indexing.summarization import SummaryGenerationResult + from mcp_server.storage.mcp_task_registry import MCPTaskRegistry + + class Writer: + def __init__(self, **kwargs): + pass + + async def process_scope(self, **kwargs): + # The very first batch is refused, so nothing was persisted. + return SummaryGenerationResult( + chunks_attempted=2, summaries_written=0, remaining_chunks=2, **{outcome: True} + ) + + monkeypatch.setattr(task_write_summaries, "ComprehensiveChunkWriter", Writer) + monkeypatch.setattr( + task_write_summaries.Settings, + "from_environment", + staticmethod( + lambda: SimpleNamespace( + get_semantic_default_profile=lambda: "oss_high", + get_profile_summarization_config=lambda _profile: {}, + ) + ), + ) + + async def run(): + registry = MCPTaskRegistry() + state = await registry.create_task(TaskMetadata()) + return await task_write_summaries.run_write_summaries_task( + task=_FakeTask(state.task_id), + registry=registry, + active_store=SimpleNamespace(db_path="/synthetic/index.db"), + current_session=None, + client_name=None, + limit_arg=10, + model_used="fake-model", + write_blocked=lambda: False, + ) + + payload = asyncio.run(run()).structured_content + assert payload["code"] == code + assert payload["tool"] == "write_summaries" + assert payload["mutation_performed"] is False + assert payload["chunks_summarized"] == 0 + assert payload["summary_chunks_attempted"] == 2 + assert payload["summary_missing_chunks"] == 2 + _assert_matches_schema("write_summaries", payload) From 05c1cc4e5a0341b4e7f49d05a228317c279ce81b Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sat, 21 Nov 2026 22:39:48 -0500 Subject: [PATCH 6/8] fix(summaries): refusals report only committed work; log dropped lazy entries at shutdown (#145) Fifth review follow-up for #162. - ChunkWriter counts the rows it actually stores (committed_writes, incremented only when _persist_summary stores a row), and SummaryGenerationResult gains summaries_committed (in summarize_file_chunks and every process_scope result). summaries_written still counts what a call generated or completed, which can include rows another writer stored during the provider call. - summary_write_refusal takes an explicit `committed` count, which alone decides mutation_performed, the note and `summaries_committed`. write_summaries (direct and task mode) and summarize_sample derive their refusal counters from it, and summarize_sample file entries report summaries_committed. The output schema lists the new field. - LazyChunkWriter.stop() logs one line with the number of pending entries it drops, queued or in flight (including one backing off), without their content. Refs Consiliency/Code-Index-MCP#145 Co-Authored-By: Claude Opus 5.5 --- mcp_server/cli/stdio_runner.py | 1 + mcp_server/cli/task_write_summaries.py | 21 ++- mcp_server/cli/tool_handlers.py | 15 +- mcp_server/indexing/summarization.py | 33 +++- tests/test_issue_145_serve_during_rebuild.py | 184 ++++++++++++++++++- 5 files changed, 238 insertions(+), 16 deletions(-) diff --git a/mcp_server/cli/stdio_runner.py b/mcp_server/cli/stdio_runner.py index a93eb238..45600b90 100644 --- a/mcp_server/cli/stdio_runner.py +++ b/mcp_server/cli/stdio_runner.py @@ -238,6 +238,7 @@ def resolve(self, path: Any) -> Any: "message": {"type": "string"}, "remediation": {"type": ["string", "array", "object", "null"]}, "retryable": {"type": "boolean"}, + "summaries_committed": {"type": "integer"}, "chunks_summarized": {"type": "integer"}, "files": {"type": "array"}, "total_chunks": {"type": "integer"}, diff --git a/mcp_server/cli/task_write_summaries.py b/mcp_server/cli/task_write_summaries.py index 2c851086..19e75ce0 100644 --- a/mcp_server/cli/task_write_summaries.py +++ b/mcp_server/cli/task_write_summaries.py @@ -38,23 +38,27 @@ def summary_write_refusal( tool: str, *, readiness: dict[str, Any] | None = None, + committed: int = 0, **extra: Any, ) -> dict[str, Any]: """The shared envelope for a summary write that could not be stored (#145). ``code`` is ``rebuild_in_progress`` (the generation is being replaced) or - ``writer_busy`` (another writer holds the lock; retry shortly). Partial - counters in ``extra`` (``chunks_summarized``, ``total_chunks``, ...) say - what was already committed; committed work always precedes any rebuild's - snapshot, so it is kept. + ``writer_busy`` (another writer holds the lock; retry shortly). + ``committed`` is the number of summaries this request itself stored before + the refusal (not those it generated, which another writer may have stored + meanwhile); it alone decides ``mutation_performed``. Committed work always + precedes any rebuild's snapshot, so it is kept. ``extra`` carries the + tool's partial counters. """ error, message, remediation = _REFUSALS[code] - written = int(extra.get("chunks_summarized") or extra.get("total_chunks") or 0) + written = int(committed) payload: dict[str, Any] = { "error": error, "code": code, "tool": tool, "mutation_performed": written > 0, + "summaries_committed": written, "retryable": True, "readiness": readiness, "message": message, @@ -113,6 +117,7 @@ async def run_write_summaries_task( ) total_written = 0 + total_committed = 0 total_attempted = 0 total_missing = 0 remaining_budget = limit_arg @@ -144,6 +149,7 @@ async def cancel_observer() -> None: write_fenced = write_fenced or bool(getattr(result, "write_fenced", False)) write_busy = write_busy or bool(getattr(result, "write_busy", False)) total_written += result.summaries_written + total_committed += int(getattr(result, "summaries_committed", 0) or 0) total_attempted += result.chunks_attempted total_missing = result.remaining_chunks persisted_any = persisted_any or result.summaries_written > 0 @@ -185,7 +191,10 @@ async def cancel_observer() -> None: if refusal is not None and not task.is_cancelled: # Same envelope as the synchronous tool, with the task's counters (#145). counters = {key: value for key, value in payload.items() if key != "persisted"} - return _call_tool_result(summary_write_refusal(refusal, "write_summaries", **counters)) + counters["chunks_summarized"] = total_committed + return _call_tool_result( + summary_write_refusal(refusal, "write_summaries", committed=total_committed, **counters) + ) if task.is_cancelled: payload["cancelled"] = True result = _call_tool_result(payload) diff --git a/mcp_server/cli/tool_handlers.py b/mcp_server/cli/tool_handlers.py index 1789e831..20e568c0 100644 --- a/mcp_server/cli/tool_handlers.py +++ b/mcp_server/cli/tool_handlers.py @@ -1668,8 +1668,10 @@ def write_blocked() -> bool: write_fence=write_fence, ) summary_result = await writer.process_scope(limit=limit_arg, cancel_check=write_blocked) + committed = int(getattr(summary_result, "summaries_committed", 0) or 0) partial = dict( - chunks_summarized=summary_result.summaries_written, + committed=committed, + chunks_summarized=committed, limit=limit_arg, model_used=model_used, summary_chunks_attempted=summary_result.chunks_attempted, @@ -1863,6 +1865,8 @@ async def handle_summarize_sample( file_results = [] total_chunks = 0 + # Rows this request itself stored, for refusal envelopes (#145). + total_committed = 0 for file_id, file_path, language in file_rows: if persist_flag and _write_blocked(repo_resolver, ctx): @@ -1871,7 +1875,8 @@ async def handle_summarize_sample( "summarize_sample", _classify_ctx(repo_resolver, scope_arg), files=file_results, - total_chunks=total_chunks, + total_chunks=total_committed, + committed=total_committed, ) try: with open(file_path, encoding="utf-8", errors="replace") as _fh: @@ -1953,12 +1958,15 @@ async def handle_summarize_sample( ) total_chunks += summary_result.summaries_written + committed = int(getattr(summary_result, "summaries_committed", 0) or 0) + total_committed += committed file_results.append( { "file_path": file_path, "chunk_count": len(summaries), "chunks_attempted": summary_result.chunks_attempted, "summaries_written": summary_result.summaries_written, + "summaries_committed": committed, "authoritative_chunks": summary_result.authoritative_chunks, "missing_chunk_ids": list(summary_result.missing_chunk_ids), "remaining_chunks": summary_result.remaining_chunks, @@ -1982,7 +1990,8 @@ async def handle_summarize_sample( "summarize_sample", _classify_ctx(repo_resolver, scope_arg), files=file_results, - total_chunks=total_chunks, + total_chunks=total_committed, + committed=total_committed, ) return [ diff --git a/mcp_server/indexing/summarization.py b/mcp_server/indexing/summarization.py index 2df25b81..62bc0a7e 100644 --- a/mcp_server/indexing/summarization.py +++ b/mcp_server/indexing/summarization.py @@ -140,6 +140,10 @@ class SummaryGenerationResult: #: generation was unchanged; those summaries were not stored and the call #: is retryable (#145). write_busy: bool = False + #: Summaries this call itself stored. ``summaries_written`` counts what it + #: generated or found complete; another writer may have stored the same + #: rows during the provider call (#145). + summaries_committed: int = 0 def __post_init__(self) -> None: object.__setattr__(self, "missing_chunk_ids", tuple(self.missing_chunk_ids)) @@ -164,6 +168,7 @@ def to_dict(self) -> Dict[str, Any]: "cancelled": self.cancelled, "write_fenced": self.write_fenced, "write_busy": self.write_busy, + "summaries_committed": self.summaries_committed, "summaries": [ {"chunk_id": item.chunk_id, "summary": item.summary} for item in self.summaries ], @@ -239,6 +244,8 @@ def __init__( self.write_fence = write_fence self.fenced_writes = 0 self.busy_writes = 0 + #: Rows this writer actually stored (``_persist_summary`` returned True). + self.committed_writes = 0 @contextmanager def _fenced_write( @@ -350,7 +357,7 @@ def _persist_summary( audit_metadata = self._build_summary_audit_metadata( model_name=model_name, **_stop_kwargs(cancel_check) ) - return bool( + stored = bool( self._get_sqlite_store().store_chunk_summary( chunk_hash=chunk_hash, file_id=file_id, @@ -368,6 +375,9 @@ def _persist_summary( audit_metadata=audit_metadata, ) ) + if stored: + self.committed_writes += 1 + return stored def _has_sampling_capability(self) -> bool: """Return True if the connected MCP client supports sampling/createMessage.""" @@ -1132,6 +1142,7 @@ async def summarize_file_chunks( symbol_map = {} fenced_before = self.fenced_writes busy_before = self.busy_writes + committed_before = self.committed_writes # Filter already-authoritative chunks. with sqlite3.connect(self.db_path) as conn: @@ -1313,6 +1324,7 @@ async def summarize_file_chunks( summaries=summaries, write_fenced=self.fenced_writes > fenced_before, write_busy=self.busy_writes > busy_before, + summaries_committed=self.committed_writes - committed_before, ) @@ -1444,6 +1456,7 @@ async def process_scope( ) return SummaryGenerationResult() + committed_before = self.committed_writes total_attempted = 0 total_summaries_written = 0 total_authoritative_chunks = 0 @@ -1461,6 +1474,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=self.committed_writes - committed_before, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1542,6 +1556,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=self.committed_writes - committed_before, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1585,6 +1600,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=self.committed_writes - committed_before, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1600,6 +1616,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=self.committed_writes - committed_before, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1638,6 +1655,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=self.committed_writes - committed_before, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1675,6 +1693,7 @@ def __init__( super().__init__(db_path, qdrant_client, session, client_name, summarization_config) self.queue: asyncio.Queue = asyncio.Queue() self._task: Optional[asyncio.Task] = None + self._in_flight: Any = None def start(self) -> None: """Start the background worker task (idempotent).""" @@ -1682,11 +1701,18 @@ def start(self) -> None: self._task = asyncio.create_task(self._worker()) async def stop(self) -> None: - """Cancel and await the owned background task before closing its storage.""" + """Cancel and await the owned background task before closing its storage. + + Queued and in-flight (including backing-off) entries are dropped; one + line records how many, so a shutdown that loses lazy work is visible. + """ if self._task is not None: task, self._task = self._task, None task.cancel() await asyncio.gather(task, return_exceptions=True) + dropped = self.queue.qsize() + (1 if self._in_flight is not None else 0) + self._in_flight = None + logger.info("Lazy summary writer stopped; %d pending entries dropped", dropped) if self._sqlite_store is not None: self._sqlite_store.close() self._sqlite_store = None @@ -1702,6 +1728,7 @@ def update_session(self, session: Any) -> None: async def _worker(self) -> None: while True: item = await self.queue.get() + self._in_flight = item try: if isinstance(item, _QueuedSummary): delay = item.not_before - time.monotonic() @@ -1712,6 +1739,8 @@ async def _worker(self) -> None: logger.error("Error summarizing chunk (%s)", type(exc).__name__) finally: self.queue.task_done() + # Not reached on cancellation, so stop() still counts the entry. + self._in_flight = None async def _summarize_queued(self, item: Any) -> Optional[str]: """Summarize one queued entry against the generation it was found in (#145). diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py index a3f99e56..700069e2 100644 --- a/tests/test_issue_145_serve_during_rebuild.py +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -565,7 +565,10 @@ async def process_scope(self, limit=500, cancel_check=None, **kwargs): on_process() cancelled = bool(cancel_check and cancel_check()) return SummaryGenerationResult( - chunks_attempted=1, summaries_written=1, cancelled=cancelled + chunks_attempted=1, + summaries_written=1, + summaries_committed=1, + cancelled=cancelled, ) monkeypatch.setattr(summarization, "ComprehensiveChunkWriter", FakeWriter) @@ -794,6 +797,7 @@ def lookup(ctx, symbol): import threading # noqa: E402 +import time # noqa: E402 from mcp_server.indexing.summarization import ( # noqa: E402 FileBatchSummarizer, @@ -870,14 +874,18 @@ def _summary_rows(db_path: Path) -> int: return conn.execute("SELECT COUNT(*) FROM chunk_summaries").fetchone()[0] -def _seed_chunk(db_path: Path) -> tuple[int, str]: +def _seed_chunk( + db_path: Path, filename: str = "alpha.py", chunk_id: str = "chunk-alpha" +) -> tuple[int, str]: """Store one chunk through the store API, which stamps the chunk scheme.""" from mcp_server.storage.sqlite_store import SQLiteStore store = SQLiteStore(str(db_path)) try: with store._get_connection() as conn: - file_id = conn.execute("SELECT id FROM files WHERE path LIKE '%alpha.py'").fetchone()[0] + file_id = conn.execute( + "SELECT id FROM files WHERE path LIKE ?", (f"%{filename}",) + ).fetchone()[0] store.store_chunk( file_id=file_id, content="def alpha_token():", @@ -885,7 +893,7 @@ def _seed_chunk(db_path: Path) -> tuple[int, str]: content_end=18, line_start=1, line_end=2, - chunk_id="chunk-alpha", + chunk_id=chunk_id, node_id="n", treesitter_file_id="t", language="python", @@ -893,7 +901,7 @@ def _seed_chunk(db_path: Path) -> tuple[int, str]: finally: store.close() ReadinessClassifier.clear_index_inspection_cache() - return file_id, "chunk-alpha" + return file_id, chunk_id @pytest.mark.parametrize("how", ["none", "fence_flag", "rebuild_lock", "busy_lock"]) @@ -1308,3 +1316,169 @@ async def run(): assert payload["summary_chunks_attempted"] == 2 assert payload["summary_missing_chunks"] == 2 _assert_matches_schema("write_summaries", payload) + + +# --------------------------------------------------------------------------- +# Refusals report only what this request itself committed +# --------------------------------------------------------------------------- + + +def test_refusal_after_another_writer_stored_this_requests_summaries(tmp_path, monkeypatch): + from types import SimpleNamespace + + from mcp_server.indexing.summarization import ComprehensiveChunkWriter + from mcp_server.storage.sqlite_store import SQLiteStore + + seed = {**SEED, "beta.py": "def beta_token():\n return 2\n"} + path, repo_id = build_temp_repo(tmp_path, "committed", seed_files=seed) + with boot_test_server(tmp_path, [path]) as server: + published = Path(server.registry.get(repo_id).index_path) + _seed_chunk(published) + _seed_chunk(published, filename="beta.py", chunk_id="chunk-beta") + busy = _RebuildStarter(server, repo_id, path, "busy_lock") + calls: list = [] + + async def provider(self, *args, **kwargs): + chunks = next( + value + for value in list(args) + list(kwargs.values()) + if isinstance(value, list) and value and isinstance(value[0], dict) + ) + calls.append([chunk["chunk_id"] for chunk in chunks]) + if len(calls) == 1: + # Another writer stores this call's summaries while the + # provider call is in flight. + other = SQLiteStore(str(published)) + try: + for chunk in chunks: + other.store_chunk_summary( + chunk_hash=chunk["chunk_id"], + file_id=chunk["file_id"], + chunk_start=1, + chunk_end=2, + summary_text="Synthetic summary.", + llm_model="other-writer", + is_authoritative=True, + profile_id=self.summarization_config.get("profile_id"), + prompt_fingerprint=self._prompt_fingerprint(), + ) + finally: + other.close() + else: + busy.start() + return [ + SimpleNamespace(chunk_id=chunk["chunk_id"], summary="Synthetic summary.") + for chunk in chunks + ] + + monkeypatch.setattr(FileBatchSummarizer, "_call_batch_api", provider) + monkeypatch.setattr(FileBatchSummarizer, "_call_profile_batch_api", provider) + monkeypatch.setattr( + FileBatchSummarizer, "_get_model_name", lambda self, **kwargs: "fake-model" + ) + monkeypatch.setattr(ComprehensiveChunkWriter, "can_summarize", lambda self: True) + try: + response = _run_tool( + "handle_write_summaries", + arguments={"repository": str(path)}, + dispatcher=server.dispatcher, + repo_resolver=server.repo_resolver, + lazy_summarizer=_FakeSummarizer(), + ) + finally: + busy.stop() + + assert len(calls) == 2, calls + assert response["code"] == "writer_busy", response + # The first file's summaries were completed by the other writer, not + # stored by this request, so nothing was mutated by it. + assert response["mutation_performed"] is False + assert response["summaries_committed"] == 0 + assert response["chunks_summarized"] == 0 + assert "note" not in response + assert _summary_rows(published) == 1 # only the other writer's row + _assert_matches_schema("write_summaries", response) + + +def test_task_refusal_counts_only_committed_summaries(monkeypatch): + from types import SimpleNamespace + + from mcp.types import TaskMetadata + + from mcp_server.cli import task_write_summaries + from mcp_server.indexing.summarization import SummaryGenerationResult + from mcp_server.storage.mcp_task_registry import MCPTaskRegistry + + passes = [ + # Pass 1 completed a summary another writer had stored meanwhile. + SummaryGenerationResult( + chunks_attempted=1, summaries_written=1, summaries_committed=0, remaining_chunks=1 + ), + # Pass 2 hit a busy writer. + SummaryGenerationResult( + chunks_attempted=1, summaries_written=0, remaining_chunks=1, write_busy=True + ), + ] + + class Writer: + def __init__(self, **kwargs): + pass + + async def process_scope(self, **kwargs): + return passes.pop(0) + + monkeypatch.setattr(task_write_summaries, "ComprehensiveChunkWriter", Writer) + monkeypatch.setattr( + task_write_summaries.Settings, + "from_environment", + staticmethod( + lambda: SimpleNamespace( + get_semantic_default_profile=lambda: "oss_high", + get_profile_summarization_config=lambda _profile: {}, + ) + ), + ) + + async def run(): + registry = MCPTaskRegistry() + state = await registry.create_task(TaskMetadata()) + return await task_write_summaries.run_write_summaries_task( + task=_FakeTask(state.task_id), + registry=registry, + active_store=SimpleNamespace(db_path="/synthetic/index.db"), + current_session=None, + client_name=None, + limit_arg=10, + model_used="fake-model", + write_blocked=lambda: False, + ) + + payload = asyncio.run(run()).structured_content + assert passes == [] + assert payload["code"] == "writer_busy" + assert payload["mutation_performed"] is False + assert payload["summaries_committed"] == 0 + assert payload["chunks_summarized"] == 0 + _assert_matches_schema("write_summaries", payload) + + +def test_lazy_writer_shutdown_logs_dropped_entries(tmp_path, caplog): + from mcp_server.indexing.summarization import _QueuedSummary + + writer = LazyChunkWriter(db_path=str(tmp_path / "unused.db"), qdrant_client=None) + + async def run(): + writer.start() + # One entry backing off in the worker, two still queued. + writer.queue.put_nowait( + _QueuedSummary(chunk={}, fence=None, attempts=1, not_before=time.monotonic() + 60) + ) + await asyncio.sleep(0.05) + writer.enqueue({"chunk_hash": "a"}) + writer.enqueue({"chunk_hash": "b"}) + with caplog.at_level("INFO", logger="mcp_server.indexing.summarization"): + await writer.stop() + + asyncio.run(run()) + assert "3 pending entries dropped" in caplog.text + assert "chunk_hash" not in caplog.text # counts only, no content From bc1ff4ea0eed4c1e876e41aae6480e0847253a7c Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sun, 22 Nov 2026 00:34:00 -0500 Subject: [PATCH 7/8] fix(summaries): per-call write tally instead of shared-counter deltas (#145) Sixth review follow-up for #162. - Each summarize_file_chunks call, and each lazy queued entry, opens its own write tally (a ContextVar, isolated per asyncio task). _persist_summary and the write fence record committed, fenced and busy writes into the active call's tally. write_fenced, write_busy and summaries_committed come from that tally, and process_scope sums summaries_committed from its file results. Concurrent calls sharing one writer no longer pick up each other's commits through a delta of the writer's cumulative counters, which remain only as diagnostics. - Successful summarize_sample responses are unchanged again: summaries_committed appears only in refusal envelopes. Refs Consiliency/Code-Index-MCP#145 Co-Authored-By: Claude Opus 5.5 --- mcp_server/cli/tool_handlers.py | 1 - mcp_server/indexing/summarization.py | 97 ++++++++++++++++---- tests/test_issue_145_serve_during_rebuild.py | 66 +++++++++++++ 3 files changed, 147 insertions(+), 17 deletions(-) diff --git a/mcp_server/cli/tool_handlers.py b/mcp_server/cli/tool_handlers.py index 20e568c0..5ec4f159 100644 --- a/mcp_server/cli/tool_handlers.py +++ b/mcp_server/cli/tool_handlers.py @@ -1966,7 +1966,6 @@ async def handle_summarize_sample( "chunk_count": len(summaries), "chunks_attempted": summary_result.chunks_attempted, "summaries_written": summary_result.summaries_written, - "summaries_committed": committed, "authoritative_chunks": summary_result.authoritative_chunks, "missing_chunk_ids": list(summary_result.missing_chunk_ids), "remaining_chunks": summary_result.remaining_chunks, diff --git a/mcp_server/indexing/summarization.py b/mcp_server/indexing/summarization.py index 62bc0a7e..fc30e37a 100644 --- a/mcp_server/indexing/summarization.py +++ b/mcp_server/indexing/summarization.py @@ -8,7 +8,8 @@ import time import warnings from contextlib import contextmanager -from dataclasses import dataclass, field +from contextvars import ContextVar +from dataclasses import dataclass, field, replace from pathlib import Path from types import SimpleNamespace from typing import ( @@ -209,6 +210,31 @@ def _topological_order(chunks: List[Dict]) -> List[str]: return order +@dataclass +class _WriteTally: + """Writes made by one summarization call (Consiliency/Code-Index-MCP#145).""" + + committed: int = 0 + fenced: int = 0 + busy: int = 0 + + +#: The innermost active call's tally. Each call opens its own, and asyncio +#: tasks copy the context, so concurrent calls on one writer never see each +#: other's writes (unlike a delta of the writer's cumulative counters). +_CALL_TALLY: ContextVar[Optional[_WriteTally]] = ContextVar("summary_write_tally", default=None) + + +@contextmanager +def _call_tally() -> Iterator[_WriteTally]: + tally = _WriteTally() + token = _CALL_TALLY.set(tally) + try: + yield tally + finally: + _CALL_TALLY.reset(token) + + class ChunkWriter: """Base interface for semantic chunk summarization. @@ -258,10 +284,15 @@ def _fenced_write( return with fence() as decision: gate = WriteGate.of(decision) + tally = _CALL_TALLY.get() if gate is WriteGate.FENCED: self.fenced_writes += 1 + if tally is not None: + tally.fenced += 1 elif gate is WriteGate.BUSY: self.busy_writes += 1 + if tally is not None: + tally.busy += 1 yield gate def _get_sqlite_store(self) -> SQLiteStore: @@ -377,6 +408,9 @@ def _persist_summary( ) if stored: self.committed_writes += 1 + tally = _CALL_TALLY.get() + if tally is not None: + tally.committed += 1 return stored def _has_sampling_capability(self) -> bool: @@ -1127,6 +1161,42 @@ async def summarize_file_chunks( max_chunks: Optional[int] = None, call_timeout_seconds: Optional[float] = None, cancel_check: Optional[Callable[[], bool]] = None, + ) -> SummaryGenerationResult: + """Summarize all chunks of a file; see ``_summarize_file_chunks``. + + The result's ``write_fenced``, ``write_busy`` and + ``summaries_committed`` come from this call's own write tally (#145). + """ + with _call_tally() as tally: + result = await self._summarize_file_chunks( + file_id=file_id, + file_path=file_path, + file_content=file_content, + chunks=chunks, + symbol_map=symbol_map, + persist=persist, + max_chunks=max_chunks, + call_timeout_seconds=call_timeout_seconds, + cancel_check=cancel_check, + ) + return replace( + result, + write_fenced=tally.fenced > 0, + write_busy=tally.busy > 0, + summaries_committed=tally.committed, + ) + + async def _summarize_file_chunks( + self, + file_id: int, + file_path: str, + file_content: str, + chunks: List[Dict], + symbol_map: Optional[Dict[int, str]] = None, + persist: bool = True, + max_chunks: Optional[int] = None, + call_timeout_seconds: Optional[float] = None, + cancel_check: Optional[Callable[[], bool]] = None, ) -> SummaryGenerationResult: """Summarize all chunks of a file, preferring the batch API path. @@ -1140,9 +1210,6 @@ async def summarize_file_chunks( """ if symbol_map is None: symbol_map = {} - fenced_before = self.fenced_writes - busy_before = self.busy_writes - committed_before = self.committed_writes # Filter already-authoritative chunks. with sqlite3.connect(self.db_path) as conn: @@ -1322,9 +1389,6 @@ async def summarize_file_chunks( remaining_chunks=len(missing_chunk_ids), scope_drained=len(missing_chunk_ids) == 0, summaries=summaries, - write_fenced=self.fenced_writes > fenced_before, - write_busy=self.busy_writes > busy_before, - summaries_committed=self.committed_writes - committed_before, ) @@ -1456,7 +1520,7 @@ async def process_scope( ) return SummaryGenerationResult() - committed_before = self.committed_writes + total_committed = 0 total_attempted = 0 total_summaries_written = 0 total_authoritative_chunks = 0 @@ -1474,7 +1538,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, - summaries_committed=self.committed_writes - committed_before, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1556,7 +1620,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, - summaries_committed=self.committed_writes - committed_before, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1589,6 +1653,7 @@ async def process_scope( ) pass_summaries_written += file_result.summaries_written total_summaries_written += file_result.summaries_written + total_committed += file_result.summaries_committed total_authoritative_chunks += file_result.authoritative_chunks total_files_summarized += file_result.files_summarized missing_chunk_ids.extend(file_result.missing_chunk_ids) @@ -1600,7 +1665,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, - summaries_committed=self.committed_writes - committed_before, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1616,7 +1681,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, - summaries_committed=self.committed_writes - committed_before, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1655,7 +1720,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, - summaries_committed=self.committed_writes - committed_before, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1765,9 +1830,9 @@ async def _summarize_queued(self, item: Any) -> Optional[str]: if gate is WriteGate.BUSY: self._requeue_busy(entry) return None - busy_before = self.busy_writes - summary = await self.summarize_chunk(**entry.chunk, write_fence=entry.fence) - if summary is None and self.busy_writes > busy_before: + with _call_tally() as tally: + summary = await self.summarize_chunk(**entry.chunk, write_fence=entry.fence) + if summary is None and tally.busy: self._requeue_busy(entry) return summary diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py index 700069e2..7bb44821 100644 --- a/tests/test_issue_145_serve_during_rebuild.py +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -941,6 +941,9 @@ async def provider(self, *args, **kwargs): if how == "none": # Control: with no rebuild the same call persists its summary. assert response["persisted"] is True and response["total_chunks"] == 1, response + # Success responses are unchanged: no refusal-only fields. + assert "summaries_committed" not in response + assert all("summaries_committed" not in entry for entry in response["files"]) assert _summary_rows(published) == 1 _assert_matches_schema("summarize_sample", response) return @@ -1482,3 +1485,66 @@ async def run(): asyncio.run(run()) assert "3 pending entries dropped" in caplog.text assert "chunk_hash" not in caplog.text # counts only, no content + + +def test_overlapping_calls_on_one_writer_count_only_their_own_commits(tmp_path, monkeypatch): + from types import SimpleNamespace + + seed = {**SEED, "beta.py": "def beta_token():\n return 2\n"} + path, repo_id = build_temp_repo(tmp_path, "overlap", seed_files=seed) + with boot_test_server(tmp_path, [path]) as server: + published = Path(server.registry.get(repo_id).index_path) + alpha_file, alpha_chunk = _seed_chunk(published) + beta_file, beta_chunk = _seed_chunk(published, filename="beta.py", chunk_id="chunk-beta") + writer = FileBatchSummarizer( + db_path=str(published), + qdrant_client=None, + summarization_config={"profile_id": "synthetic-profile"}, + ) + monkeypatch.setattr(writer, "_get_model_name", lambda **kwargs: "fake-model") + order: list = [] + + async def provider(file_id, file_path, file_content, chunks, symbol_map): + if chunks[0]["chunk_id"] == alpha_chunk: + # Let the other call start and enter its provider first. + await asyncio.sleep(0.02) + order.append("alpha-returns") + return [SimpleNamespace(chunk_id=alpha_chunk, summary="Alpha summary.")] + order.append("beta-waits") + # Stay in flight until the alpha call has committed its row. + while writer.committed_writes < 1: + await asyncio.sleep(0.005) + order.append("beta-returns") + return [] # nothing to store for this call + + monkeypatch.setattr(writer, "_call_batch_api", provider) + + def chunk(file_id: int, chunk_id: str) -> dict: + return { + "chunk_id": chunk_id, + "file_id": file_id, + "line_start": 1, + "line_end": 2, + "content": "def token():", + "language": "python", + } + + async def run(): + return await asyncio.gather( + writer.summarize_file_chunks( + alpha_file, "alpha.py", "def alpha_token():", [chunk(alpha_file, alpha_chunk)] + ), + writer.summarize_file_chunks( + beta_file, "beta.py", "def beta_token():", [chunk(beta_file, beta_chunk)] + ), + ) + + alpha_result, beta_result = asyncio.run(run()) + writer._get_sqlite_store().close() + + assert order == ["beta-waits", "alpha-returns", "beta-returns"], order + assert alpha_result.summaries_committed == 1 + # The beta call overlapped the alpha commit but stored nothing itself. + assert beta_result.summaries_committed == 0 + assert writer.committed_writes == 1 + assert _summary_rows(published) == 1 From e460193c29cbf816f6870f757056f5e9d9e1325e Mon Sep 17 00:00:00 2001 From: Jenner Torrence Date: Sun, 22 Nov 2026 00:45:17 -0500 Subject: [PATCH 8/8] fix(summarization): open a lazy entry's tally before its preflight fence (#145 re-review) The preflight fence of a queued lazy entry ran before the entry opened its own write tally, so a worker that inherited an active context (or a nested call) recorded the entry's BUSY/FENCED outcome into an unrelated caller's tally. The entry's tally now covers the preflight and every early return. Co-Authored-By: Claude Opus 5.5 --- mcp_server/indexing/summarization.py | 21 ++++++++------- tests/test_issue_145_serve_during_rebuild.py | 28 ++++++++++++++++++++ 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/mcp_server/indexing/summarization.py b/mcp_server/indexing/summarization.py index fc30e37a..70f178f5 100644 --- a/mcp_server/indexing/summarization.py +++ b/mcp_server/indexing/summarization.py @@ -1821,16 +1821,19 @@ async def _summarize_queued(self, item: Any) -> Optional[str]: entry = _QueuedSummary(chunk=item[0], fence=item[1]) else: entry = _QueuedSummary(chunk=item, fence=None) - if entry.fence is not None: - with self._fenced_write(entry.fence) as gate: - pass - if gate is WriteGate.FENCED: - logger.info("Queued chunk summary dropped: its generation is being rebuilt") - return None - if gate is WriteGate.BUSY: - self._requeue_busy(entry) - return None + # The entry's own tally covers its preflight fence too, so a worker that + # inherited an active context (or a nested call) never records this + # entry's BUSY/FENCED outcome into an unrelated caller's tally. with _call_tally() as tally: + if entry.fence is not None: + with self._fenced_write(entry.fence) as gate: + pass + if gate is WriteGate.FENCED: + logger.info("Queued chunk summary dropped: its generation is being rebuilt") + return None + if gate is WriteGate.BUSY: + self._requeue_busy(entry) + return None summary = await self.summarize_chunk(**entry.chunk, write_fence=entry.fence) if summary is None and tally.busy: self._requeue_busy(entry) diff --git a/tests/test_issue_145_serve_during_rebuild.py b/tests/test_issue_145_serve_during_rebuild.py index 7bb44821..0cb0a08e 100644 --- a/tests/test_issue_145_serve_during_rebuild.py +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -1139,6 +1139,34 @@ def _lazy_chunk(file_id: int, chunk_id: str) -> dict: ) +def test_lazy_entry_preflight_never_records_into_an_outer_tally(tmp_path, monkeypatch): + """A lazy entry's preflight BUSY outcome stays in the entry's own tally.""" + from mcp_server.indexing import summarization + + path, repo_id = build_temp_repo(tmp_path, "lazy-outer-tally", seed_files=SEED) + with boot_test_server(tmp_path, [path]) as server: + info = server.registry.get(repo_id) + published = Path(info.index_path) + file_id, chunk_id = _seed_chunk(published) + fence = server.repo_resolver.generation_write_fence(repo_id, info, path) + writer, calls = _lazy_writer(published, monkeypatch) + writer.enqueue(_lazy_chunk(file_id, chunk_id), write_fence=fence) + busy = _RebuildStarter(server, repo_id, path, "busy_lock") + busy.start() + try: + # The worker runs inside a context that already has an unrelated + # caller's tally active; the entry's preflight sees a busy writer. + with summarization._call_tally() as outer: + assert asyncio.run(writer._summarize_queued(writer.queue.get_nowait())) is None + assert calls == [] + assert outer.busy == 0 and outer.fenced == 0 + assert writer.queue.get_nowait().attempts == 1 + finally: + busy.stop() + if writer._sqlite_store is not None: + writer._sqlite_store.close() + + def test_lazy_entry_is_requeued_while_a_non_rebuild_writer_holds_the_lock(tmp_path, monkeypatch): path, repo_id = build_temp_repo(tmp_path, "lazy-busy", seed_files=SEED) with boot_test_server(tmp_path, [path]) as server: