Skip to content
Merged
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
49 changes: 49 additions & 0 deletions docs/SUPPORT_MATRIX.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
4 changes: 4 additions & 0 deletions docs/operations/deployment-runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
36 changes: 36 additions & 0 deletions mcp_server/cli/stdio_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
88 changes: 85 additions & 3 deletions mcp_server/cli/task_write_summaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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")
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down
Loading
Loading