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..0e669178 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -21,6 +21,55 @@ 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. 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, 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 +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`, 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). 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 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. + 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/stdio_runner.py b/mcp_server/cli/stdio_runner.py index b8645d32..45600b90 100644 --- a/mcp_server/cli/stdio_runner.py +++ b/mcp_server/cli/stdio_runner.py @@ -225,6 +225,38 @@ 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"]}, + "retryable": {"type": "boolean"}, + "summaries_committed": {"type": "integer"}, + "chunks_summarized": {"type": "integer"}, + "files": {"type": "array"}, + "total_chunks": {"type": "integer"}, + "note": {"type": "string"}, + }, + "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": { @@ -777,6 +809,8 @@ def _build_tool_list() -> list[types.Tool]: _PATH_OUTSIDE_ALLOWED_ROOTS_SCHEMA, _INDEX_UNAVAILABLE_SCHEMA, _SECONDARY_READINESS_REFUSAL_SCHEMA, + _REBUILD_IN_PROGRESS_SCHEMA, + _WRITER_BUSY_SCHEMA, _SUMMARIZATION_UNAVAILABLE_SCHEMA, _SQLITE_NOT_INITIALIZED_SCHEMA, _object_schema( @@ -848,6 +882,8 @@ def _build_tool_list() -> list[types.Tool]: _INDEX_UNAVAILABLE_SCHEMA, _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 aaa87131..19e75ce0 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 @@ -13,6 +13,65 @@ 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, + 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). + ``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(committed) + payload: dict[str, Any] = { + "error": error, + "code": code, + "tool": tool, + "mutation_performed": written > 0, + "summaries_committed": written, + "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( @@ -31,6 +90,8 @@ async def run_write_summaries_task( client_name: str | None, 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") @@ -52,13 +113,17 @@ async def run_write_summaries_task( **settings.get_profile_summarization_config(profile_id), "profile_id": profile_id, }, + write_fence=write_fence, ) total_written = 0 + total_committed = 0 total_attempted = 0 total_missing = 0 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: @@ -77,9 +142,14 @@ 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()), ) + 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 @@ -98,7 +168,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 or write_busy: break if result.summaries_written == 0 or result.remaining_chunks == 0: break @@ -113,6 +183,18 @@ async def cancel_observer() -> None: "summary_chunks_attempted": total_attempted, "summary_missing_chunks": total_missing, } + 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"} + 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 f6457ce1..5ec4f159 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 @@ -23,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 @@ -33,6 +39,11 @@ ReadinessClassifier, RepositoryReadiness, RepositoryReadinessState, + fresh_readiness, + readiness_queryable, + readiness_serving_stale, + readiness_snapshot, + readiness_snapshot_context, ) from mcp_server.indexing.source_metadata import normalize_friction_category @@ -170,9 +181,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(readiness): return None if path_arg: @@ -252,6 +267,70 @@ 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( + summary_write_refusal( + REBUILD_IN_PROGRESS, + tool, + readiness=readiness.to_dict() if readiness is not None else None, + **extra, + ) + ) + + +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: + """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) + + def _resolution_transition_response(tool: str) -> list[types.TextContent]: return _json_text_response( { @@ -335,6 +414,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, @@ -369,7 +470,7 @@ async def handle_symbol_lookup( } ) - if readiness is not None and not readiness.ready: + 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) @@ -383,11 +484,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: @@ -429,6 +530,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(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))] else: response_data = { @@ -438,6 +542,8 @@ async def handle_symbol_lookup( } if readiness is not None: response_data["readiness"] = readiness.to_dict() + 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 # because its grammar was unavailable (#117). @@ -451,6 +557,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 ( @@ -480,7 +596,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: @@ -526,7 +646,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, @@ -573,6 +694,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 @@ -661,8 +789,17 @@ 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")) + 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. @@ -683,7 +820,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 @@ -725,12 +865,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 +917,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))] @@ -1432,6 +1584,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 getattr(readiness, "rebuild", None): + return _rebuild_in_progress_response("write_summaries", readiness) ctx = _resolve_ctx(repo_resolver, repository) if ctx is None and isinstance(repo_resolver, RepoResolver): @@ -1467,6 +1621,21 @@ 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) + + # 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( @@ -1477,6 +1646,8 @@ async def handle_write_summaries( client_name=client_name, 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." @@ -1494,8 +1665,26 @@ async def handle_write_summaries( **_settings.get_profile_summarization_config(profile_id), "profile_id": profile_id, }, + write_fence=write_fence, ) - summary_result = await writer.process_scope(limit=limit_arg) + 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( + committed=committed, + chunks_summarized=committed, + 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), **partial + ) + if getattr(summary_result, "write_busy", False): + return _writer_busy_response( + "write_summaries", _classify_ctx(repo_resolver, repository), **partial + ) return [ types.TextContent( @@ -1600,6 +1789,8 @@ async def handle_summarize_sample( ] if not path_readiness.ready: return _secondary_readiness_refusal_response(path_readiness, "summarize_sample") + 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 @@ -1620,6 +1811,12 @@ 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 getattr(repository_readiness, "rebuild", None) + ): + return _rebuild_in_progress_response("summarize_sample", repository_readiness) scope_arg = repository if not scope_arg and paths_arg: @@ -1668,8 +1865,19 @@ 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): + # 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_committed, + committed=total_committed, + ) try: with open(file_path, encoding="utf-8", errors="replace") as _fh: file_content = _fh.read() @@ -1718,6 +1926,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: @@ -1748,6 +1958,8 @@ 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, @@ -1762,6 +1974,24 @@ async def handle_summarize_sample( "summaries": summary_list, } ) + 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_committed, + committed=total_committed, + ) return [ types.TextContent( diff --git a/mcp_server/client.py b/mcp_server/client.py index ed16c3e0..55b21014 100644 --- a/mcp_server/client.py +++ b/mcp_server/client.py @@ -9,7 +9,12 @@ 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_queryable, + readiness_snapshot, +) from mcp_server.storage.store_registry import StoreRegistry from .client_types import ( @@ -107,6 +112,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,13 +244,35 @@ 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) 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(readiness): unavailable: IndexUnavailable | None = _index_unavailable(readiness) return _unavailable_search(options, unavailable) @@ -275,7 +312,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: @@ -300,7 +337,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( @@ -424,13 +461,23 @@ 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, 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(readiness): return ClientSymbolResult( symbol=symbol, found=False, @@ -458,7 +505,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( @@ -467,7 +514,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 39600f44..fd4b4867 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 ( @@ -12,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 @@ -80,9 +81,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,10 +106,89 @@ 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 + + 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 + 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(repo_id) + return ( + info is not None + and not info.staleness_reason + 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. 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[WriteGate]: + held = lock_registry.acquire(repo_id, repo_path=repo_path, timeout=0) + try: + held.__enter__() + except TimeoutError: + yield self._contended_gate(repo_id, expected, repo_path) + return + try: + 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: @@ -112,7 +197,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..a1a266fe 100644 --- a/mcp_server/health/repository_readiness.py +++ b/mcp_server/health/repository_readiness.py @@ -8,12 +8,15 @@ 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 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 +73,37 @@ 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 + and self.rebuild.get("target_commit") == self.current_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,9 +128,20 @@ def to_dict(self) -> dict[str, Any]: "index_path": self.index_path, "remediation": self.remediation, "coverage": self.coverage, + "rebuild": self.rebuild, } +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 @@ -394,6 +434,31 @@ 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) 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 + and current_commit + and owner.get("target_commit") == current_commit + and tracked_tree_clean + ): + 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 +539,7 @@ def classify_registered( index_path=str(index_path) if index_path else None, remediation=remediation, coverage=coverage, + rebuild=rebuild, ) @classmethod @@ -794,7 +860,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/mcp_server/indexing/lock_registry.py b/mcp_server/indexing/lock_registry.py index 05b7af1d..20012aa2 100644 --- a/mcp_server/indexing/lock_registry.py +++ b/mcp_server/indexing/lock_registry.py @@ -1,10 +1,15 @@ """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 enum import Enum from pathlib import Path from typing import Dict, Optional @@ -73,3 +78,200 @@ 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" + + +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" + + +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: + 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 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: + 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; 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()) + 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 ( + 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 + return owner diff --git a/mcp_server/indexing/summarization.py b/mcp_server/indexing/summarization.py index b14e5f4a..70f178f5 100644 --- a/mcp_server/indexing/summarization.py +++ b/mcp_server/indexing/summarization.py @@ -5,17 +5,32 @@ import os import re import sqlite3 +import time import warnings -from dataclasses import dataclass, field +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass, field, replace 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 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 @@ -118,6 +133,18 @@ 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 + #: 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 + #: 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)) @@ -140,6 +167,9 @@ 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, + "write_busy": self.write_busy, + "summaries_committed": self.summaries_committed, "summaries": [ {"chunk_id": item.chunk_id, "summary": item.summary} for item in self.summaries ], @@ -180,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. @@ -198,6 +253,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 +262,38 @@ 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 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 + #: Rows this writer actually stored (``_persist_summary`` returned True). + self.committed_writes = 0 + + @contextmanager + def _fenced_write( + 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 WriteGate.ALLOWED + 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: if self._sqlite_store is None: @@ -300,7 +388,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, @@ -318,6 +406,12 @@ def _persist_summary( audit_metadata=audit_metadata, ) ) + 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: """Return True if the connected MCP client supports sampling/createMessage.""" @@ -557,6 +651,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 +799,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 not stored: index write %s", allowed.value) + 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 @@ -1060,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. @@ -1180,6 +1317,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,52 +1329,63 @@ 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, @@ -1371,6 +1520,7 @@ async def process_scope( ) return SummaryGenerationResult() + total_committed = 0 total_attempted = 0 total_summaries_written = 0 total_authoritative_chunks = 0 @@ -1388,6 +1538,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1469,6 +1620,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1501,14 +1653,35 @@ 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) + 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, + summaries_written=total_summaries_written, + summaries_committed=total_committed, + 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=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) return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1547,6 +1720,7 @@ async def process_scope( return SummaryGenerationResult( chunks_attempted=total_attempted, summaries_written=total_summaries_written, + summaries_committed=total_committed, authoritative_chunks=total_authoritative_chunks, missing_chunk_ids=tuple(missing_chunk_ids), files_attempted=total_files_attempted, @@ -1584,6 +1758,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).""" @@ -1591,11 +1766,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 @@ -1610,14 +1792,95 @@ def update_session(self, session: Any) -> None: async def _worker(self) -> None: while True: - chunk = await self.queue.get() + item = await self.queue.get() + self._in_flight = item try: - await self.summarize_chunk(**chunk) + 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__) 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). + + 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. + """ + 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) + # 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) + 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[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, and a busy + writer delays it (#145). + """ + 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.""" - 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) + chunk: Dict[str, Any] + fence: Optional[Callable[[], ContextManager[Any]]] + attempts: int = 0 + not_before: float = 0.0 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..0cb0a08e --- /dev/null +++ b/tests/test_issue_145_serve_during_rebuild.py @@ -0,0 +1,1578 @@ +"""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 asyncio +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 + +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") + +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 + ) + + +@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 +# --------------------------------------------------------------------------- + + +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_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: + (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) + + +# --------------------------------------------------------------------------- +# 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, write_fence=None) -> None: + self.enqueued.append((chunk, write_fence)) + + +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, + summaries_committed=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 response["mutation_performed"] is True + assert response["retryable"] is True + assert "kept" in response["note"] + _assert_matches_schema("write_summaries", response) + + +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 + + +# --------------------------------------------------------------------------- +# Writes are fenced at the persistence point, after the provider call +# --------------------------------------------------------------------------- + + +import threading # noqa: E402 +import time # 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 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": + 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() + 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) + + 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) + if self._owner is not None: + locks.clear_rebuild_owner(self.path, self._owner["token"]) + + +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, 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 ?", (f"%{filename}",) + ).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_id, + node_id="n", + treesitter_file_id="t", + language="python", + ) + finally: + store.close() + ReadinessClassifier.clear_index_inspection_cache() + return file_id, chunk_id + + +@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: + 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 + # 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 + 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 index + _assert_matches_schema("summarize_sample", response) + + +@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: + 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 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 + # 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 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 gate: + assert gate is locks.WriteGate.FENCED + + +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"]) + + +# --------------------------------------------------------------------------- +# 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_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: + 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) + + +# --------------------------------------------------------------------------- +# 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 + + +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 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_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"] ) 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'")