From 7b5cc0ca4e8fbd533d954480385622ed75fcdcc9 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Mon, 30 Nov 2026 20:05:33 +0800 Subject: [PATCH 1/4] Keep cached code maps paired with their index commit The handler read the current commit after retrieving cached map text, so an index advance could attach a new commit to an older map. Cache the map text and commit together, key entries by commit, and retry when the index head changes during rendering. After three unstable attempts, return a retryable error without caching the result. Cover warm-cache advances, render-time changes, retry exhaustion and orientation reuse. The HTTP regression checks the map and commit after a completed index advance. Signed-off-by: zhangxiaoyu.york --- server/code/app/context.py | 49 ++++++--- tests/integration/test_code_map_cache.py | 69 ++++++++++++ tests/unit/test_code_map.py | 128 ++++++++++++++++++++++- tests/unit/test_code_observability.py | 2 +- 4 files changed, 231 insertions(+), 17 deletions(-) create mode 100644 tests/integration/test_code_map_cache.py diff --git a/server/code/app/context.py b/server/code/app/context.py index 857ad256e1d..6fe0d3462bf 100644 --- a/server/code/app/context.py +++ b/server/code/app/context.py @@ -4,6 +4,7 @@ import logging import time +from dataclasses import dataclass from typing import Any from server.code.api.models_context import ( @@ -26,10 +27,20 @@ from server.code.app.spans import code_span, set_code_span_attributes, span_attrs from server.code.app.ttl_cache import TtlCache from server.code.store.index import CodeRepo +from server.core.ch import current_query_tag, set_query_tag +from server.core.errors import OverloadedError logger = logging.getLogger(__name__) -_MAP_CACHE: TtlCache[tuple[str, str, str, int], str] = TtlCache(900.0, maxsize=200) + +@dataclass(frozen=True) +class _MapArtifact: + text: str + commit_sha: str + + +_MAP_CACHE: TtlCache[tuple[str, str, str, int, str], _MapArtifact] = TtlCache(900.0, maxsize=200) +_MAP_RENDER_ATTEMPTS = 3 async def handle_code_context_pack(input: CodeContextPackInput) -> CodeContextPackOutput: @@ -135,8 +146,8 @@ def _trace(*, route: str, ids: list[str], tokens: int) -> str: # Orientation mode: repo map + top module cards. with code_span("context_pack.orientation"): - map_text = await _render_map(repo, org, ns, "", input.token_budget) - map_text = await _with_repo_docs(org, ns, map_text, input.token_budget) + artifact = await _render_map(repo, org, ns, "", input.token_budget) + map_text = await _with_repo_docs(org, ns, artifact.text, input.token_budget) map_text, _ = fit_pack_budget(map_text, input.token_budget) tokens = estimate_tokens(map_text) return CodeContextPackOutput( @@ -205,8 +216,8 @@ async def handle_code_map(input: CodeMapInput) -> CodeMapOutput: org, ns = resolve_code_identity(input.org, input.namespace) repo = CodeRepo() with code_span("map.render"): - text = await _render_map(repo, org, ns, input.module_prefix, input.token_budget) - head = await repo.get_state(org, ns, "git_head") + artifact = await _render_map(repo, org, ns, input.module_prefix, input.token_budget) + text = artifact.text tokens = estimate_tokens(text) # the header line alone means no module cards matched the prefix entries = max(0, text.count("\n- **")) + text.count("\n- `") @@ -241,24 +252,39 @@ async def handle_code_map(input: CodeMapInput) -> CodeMapOutput: return CodeMapOutput( map=text, tokens_used=tokens, - commit_sha=head, + commit_sha=artifact.commit_sha, trace_run_id=trace_run_id, ) async def _render_map( repo: CodeRepo, org: str, ns: str, module_prefix: str, token_budget: int +) -> _MapArtifact: + set_query_tag(current_query_tag() or "code.map") + for _ in range(_MAP_RENDER_ATTEMPTS): + head = await repo.get_state(org, ns, "git_head") + key = (org, ns, module_prefix, token_budget, head) + cached = _MAP_CACHE.get(key) + if cached is not None: + return cached + text = await _build_map_text(repo, org, ns, module_prefix, token_budget) + # Detect a completed index advance, not a snapshot of its progressive writes. + if await repo.get_state(org, ns, "git_head") != head: + continue + artifact = _MapArtifact(text=text, commit_sha=head) + _MAP_CACHE.put(key, artifact) + return artifact + raise OverloadedError("Repository index changed while rendering the map; retry shortly.") + + +async def _build_map_text( + repo: CodeRepo, org: str, ns: str, module_prefix: str, token_budget: int ) -> str: from server.code.app import fan_in as code_fan_in from server.code.app.index.packs import estimate_tokens, fit_pack_budget from server.embedding.embedder import get_embedder - key = (org, ns, module_prefix, token_budget) - cached = _MAP_CACHE.get(key) - if cached is not None: - return cached - model = "" try: model = get_embedder().model_name @@ -291,7 +317,6 @@ async def _render_map( lines.pop() break text, _ = fit_pack_budget("\n".join(lines), token_budget) - _MAP_CACHE.put(key, text) return text diff --git a/tests/integration/test_code_map_cache.py b/tests/integration/test_code_map_cache.py new file mode 100644 index 00000000000..1a0e346fe2a --- /dev/null +++ b/tests/integration/test_code_map_cache.py @@ -0,0 +1,69 @@ +"""A completed index advance replaces a cached map through the HTTP operation.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import httpx +import pytest + +from server.code.store.index import CodeRepo +from server.code.store.index.rows import build_row +from server.core.ch import CHClient, query_tag +from server.embedding.embedder import get_embedder +from tests.integration._resources import unique_org + +pytestmark = [pytest.mark.asyncio, pytest.mark.usefixtures("ch_target_required")] + + +async def test_a_warm_map_tracks_the_completed_index_commit( + control_plane_url: str, mint_test_token: Callable[..., str] +) -> None: + org, namespace = unique_org("map-cache"), "code-map" + token = mint_test_token(org=org, namespaces=[namespace], roles=["viewer"]) + body = {"org": org, "namespace": namespace, "token_budget": 2000} + client = CHClient() + with query_tag("integration.code_map_cache"): + try: + await client.connect() + repo = CodeRepo(client) + row = build_row( + "code_summaries", + org=org, + namespace=namespace, + embedding_model=get_embedder().model_name, + scope_path="src/module.py", + summary="revision-a-card", + pagerank=0.5, + in_degree=3, + ) + await repo.insert_rows("code_summaries", [row]) + await repo.set_state(org, namespace, "git_head", "a" * 40) + async with httpx.AsyncClient( + base_url=control_plane_url, + headers={"Authorization": f"Bearer {token}"}, + timeout=30, + ) as http: + first = await _map(http, body) + assert first["commit_sha"] == "a" * 40 + assert "revision-a-card" in first["map"] + + updated = CodeRepo.moved_of("code_summaries", row, summary="revision-b-card") + await repo.insert_rows("code_summaries", [updated]) + await repo.set_state(org, namespace, "git_head", "b" * 40) + second = await _map(http, body) + assert second["commit_sha"] == "b" * 40 + assert "revision-b-card" in second["map"] + assert "revision-a-card" not in second["map"] + repeated = await _map(http, body) + assert repeated["map"] == second["map"] + assert repeated["commit_sha"] == second["commit_sha"] + finally: + await client.disconnect() + + +async def _map(http: httpx.AsyncClient, body: dict[str, Any]) -> dict[str, Any]: + response = await http.post("/v1/code.map", json=body) + assert response.status_code == 200, response.text + return response.json() diff --git a/tests/unit/test_code_map.py b/tests/unit/test_code_map.py index 5170c3bfba4..8f9b0678993 100644 --- a/tests/unit/test_code_map.py +++ b/tests/unit/test_code_map.py @@ -1,5 +1,5 @@ """code.map: the rendered repo map stops at its token budget, is cached per -(org, namespace, prefix, budget) for its TTL, degrades to the include-graph +(org, namespace, prefix, budget, commit) for its TTL, degrades to the include-graph map when the call-graph read fails, and abstains when no card matches.""" from __future__ import annotations @@ -10,8 +10,9 @@ import pytest -from server.code.api.models_context import CodeMapInput +from server.code.api.models_context import CodeContextPackInput, CodeMapInput from server.code.app import context as hc +from server.core.errors import OverloadedError from server.settings import settings @@ -29,6 +30,8 @@ def __init__( ) -> None: self.summaries, self.callers, self.callers_fail = summaries, callers or [], callers_fail self.summary_reads: list[tuple[str, str, str]] = [] + self.head = "abc123" + self.head_reads = 0 async def top_summaries( self, org: str, ns: str, model: str, *, module_prefix: str, limit: int @@ -50,7 +53,8 @@ async def cards_for_paths( async def get_state(self, org: str, ns: str, key: str) -> str: assert key == "git_head" - return "abc123" + self.head_reads += 1 + return self.head @pytest.fixture(autouse=True) @@ -68,7 +72,7 @@ async def _no_hubs(*_a: Any, **_k: Any) -> list[dict[str, Any]]: def _render(repo: _Repo, prefix: str = "", budget: int = 2000, ns: str = "n") -> str: - return asyncio.run(hc._render_map(repo, "o", ns, prefix, budget)) # type: ignore[arg-type] + return asyncio.run(hc._render_map(repo, "o", ns, prefix, budget)).text # type: ignore[arg-type] def test_the_map_reads_with_the_embedder_model_and_lists_the_hubs() -> None: @@ -169,3 +173,119 @@ def test_a_prefix_no_card_matches_abstains(monkeypatch: pytest.MonkeyPatch) -> N "# Repo map (include-graph and call-graph hubs; per-merge fresh)" ] assert trace["abstain"] is True and trace["returned_ids"] == [] + + +@pytest.mark.parametrize("initial_head", ["abc123", ""]) +def test_an_index_advance_rebuilds_a_warm_map( + monkeypatch: pytest.MonkeyPatch, initial_head: str +) -> None: + repo = _Repo([_summary("src/a")]) + repo.head = initial_head + first, _ = _handle(monkeypatch, repo) + assert first.commit_sha == initial_head and "src/a" in first.map + + repo.head = "def456" + repo.summaries = [_summary("src/b")] + second, _ = _handle(monkeypatch, repo) + assert second.commit_sha == "def456" and "src/b" in second.map + assert "src/a" not in second.map + assert len(repo.summary_reads) == 2 + repeated, _ = _handle(monkeypatch, repo) + assert repeated.map == second.map and repeated.commit_sha == second.commit_sha + assert len(repo.summary_reads) == 2 + + +def test_a_cache_hit_keeps_its_commit_when_the_index_advances_after_lookup( + monkeypatch: pytest.MonkeyPatch, +) -> None: + repo = _Repo([_summary("src/a")]) + first, _ = _handle(monkeypatch, repo) + + async def _advance_after_head(org: str, ns: str, key: str) -> str: + head = await _Repo.get_state(repo, org, ns, key) + repo.head = "def456" + repo.summaries = [_summary("src/b")] + return head + + monkeypatch.setattr(repo, "get_state", _advance_after_head) + reads = repo.head_reads + cached, _ = _handle(monkeypatch, repo) + assert cached.map == first.map and cached.commit_sha == first.commit_sha + assert repo.head_reads == reads + 1 + assert len(repo.summary_reads) == 1 + + latest, _ = _handle(monkeypatch, repo) + assert latest.commit_sha == "def456" and "src/b" in latest.map + + +@pytest.mark.parametrize("advances", [1, 2]) +def test_a_head_change_during_render_discards_the_map_and_retries( + monkeypatch: pytest.MonkeyPatch, advances: int +) -> None: + repo = _Repo([_summary("src/a")]) + top_summaries = repo.top_summaries + + async def _advancing_summaries(*args: Any, **kwargs: Any) -> list[dict[str, Any]]: + rows = await top_summaries(*args, **kwargs) + if len(repo.summary_reads) <= advances: + repo.head = f"commit-{len(repo.summary_reads)}" + repo.summaries = [_summary(f"src/revision-{len(repo.summary_reads)}")] + return rows + + monkeypatch.setattr(repo, "top_summaries", _advancing_summaries) + out, _ = _handle(monkeypatch, repo) + assert out.commit_sha == f"commit-{advances}" + assert f"src/revision-{advances}" in out.map and "src/a" not in out.map + assert len(repo.summary_reads) == advances + 1 + assert len(hc._MAP_CACHE) == 1 + repeated, _ = _handle(monkeypatch, repo) + assert repeated.map == out.map and repeated.commit_sha == out.commit_sha + assert len(repo.summary_reads) == advances + 1 + + +def test_continuous_index_advances_fail_without_caching_an_unstable_map( + monkeypatch: pytest.MonkeyPatch, +) -> None: + repo = _Repo([_summary("src/a")]) + top_summaries = repo.top_summaries + + async def _always_advancing(*args: Any, **kwargs: Any) -> list[dict[str, Any]]: + rows = await top_summaries(*args, **kwargs) + repo.head = f"commit-{len(repo.summary_reads)}" + repo.summaries = [_summary(repo.head)] + return rows + + monkeypatch.setattr(repo, "top_summaries", _always_advancing) + with pytest.raises(OverloadedError, match="index changed") as caught: + _handle(monkeypatch, repo) + assert caught.value.status_code == 503 + assert len(repo.summary_reads) == 3 + assert len(hc._MAP_CACHE) == 0 + + monkeypatch.setattr(repo, "top_summaries", top_summaries) + recovered, _ = _handle(monkeypatch, repo) + assert recovered.commit_sha == repo.head and repo.head in recovered.map + assert len(hc._MAP_CACHE) == 1 + + +def test_orientation_uses_the_map_cache_and_rebuilds_after_an_index_advance( + monkeypatch: pytest.MonkeyPatch, +) -> None: + repo = _Repo([_summary("src/a")]) + _handle(monkeypatch, repo) + + async def _no_docs(org: str, ns: str, text: str, token_budget: int) -> str: + return text + + monkeypatch.setattr(hc, "_with_repo_docs", _no_docs) + request = CodeContextPackInput(org="o", namespace="n") + first = asyncio.run(hc.handle_code_context_pack(request)) + assert first.source == "orientation" and "src/a" in first.context + assert len(repo.summary_reads) == 1 + + repo.head = "def456" + repo.summaries = [_summary("src/b")] + second = asyncio.run(hc.handle_code_context_pack(request)) + assert second.source == "orientation" and "src/b" in second.context + assert "src/a" not in second.context + assert len(repo.summary_reads) == 2 diff --git a/tests/unit/test_code_observability.py b/tests/unit/test_code_observability.py index 2af945b971d..3c876d5f986 100644 --- a/tests/unit/test_code_observability.py +++ b/tests/unit/test_code_observability.py @@ -794,7 +794,7 @@ async def context_pack(self, org, ns, pr): return None async def _map(repo, org, ns, prefix, budget): - return "# Repo map\n- **src/** (included by 3)" + return hc._MapArtifact("# Repo map\n- **src/** (included by 3)", "abc") monkeypatch.setattr(hc, "_render_map", _map) with patch.object(hc, "CodeRepo", return_value=_Repo()): From 30b08eb34dae8e3ebb7c6535ba86bf5800d5a303 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Mon, 30 Nov 2026 23:31:35 +0800 Subject: [PATCH 2/4] Map token-budget tests read the cached artifact text The map helper returns text with its observed head. Preserve the token-budget assertions after merging the new tests from main. Signed-off-by: zhangxiaoyu.york --- tests/unit/test_unlimited_code_context.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_unlimited_code_context.py b/tests/unit/test_unlimited_code_context.py index c9829fac065..192bacf4d8f 100644 --- a/tests/unit/test_unlimited_code_context.py +++ b/tests/unit/test_unlimited_code_context.py @@ -103,9 +103,11 @@ async def test_map_header_obeys_a_tiny_explicit_cap(monkeypatch): monkeypatch.setattr(embedder, "get_embedder", lambda: SimpleNamespace(model_name="test")) monkeypatch.setattr(context, "_call_graph_hubs", AsyncMock(return_value=([], {}))) monkeypatch.setattr(fan_in, "top_under", AsyncMock(return_value=[])) - repo = SimpleNamespace(top_summaries=AsyncMock(return_value=[])) - assert await context._render_map(repo, "org", "code", "", 1) == "" - assert await context._render_map(repo, "org", "code", "", 0) + repo = SimpleNamespace( + top_summaries=AsyncMock(return_value=[]), get_state=AsyncMock(return_value="abc123") + ) + assert (await context._render_map(repo, "org", "code", "", 1)).text == "" + assert (await context._render_map(repo, "org", "code", "", 0)).text @pytest.mark.asyncio From f14d4c9209f544f4a1b31a941ae4a1e03459cf13 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Mon, 30 Nov 2026 23:37:20 +0800 Subject: [PATCH 3/4] Task fallback tests return the cached map artifact The orientation handler reads artifact.text. Keep the empty-search fallback test aligned with that helper contract. Signed-off-by: zhangxiaoyu.york --- tests/unit/test_task_context_pack.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_task_context_pack.py b/tests/unit/test_task_context_pack.py index b8c22caed51..65e671a4204 100644 --- a/tests/unit/test_task_context_pack.py +++ b/tests/unit/test_task_context_pack.py @@ -282,7 +282,7 @@ async def search(inp): return _Found([]) async def render_map(repo, org, ns, prefix, budget): - return "# Repo map" + return hc._MapArtifact(text="# Repo map", commit_sha="abc123") async def docs(org, ns, text, budget): return text From 749d3ae98468d4513c1849b0f333200becb71825 Mon Sep 17 00:00:00 2001 From: "zhangxiaoyu.york" Date: Tue, 1 Dec 2026 08:41:23 +0800 Subject: [PATCH 4/4] code.map render attempts are configurable Read the render bound from settings with a default of three and a minimum of one. Cover configured bounds, environment loading and invalid values, and regenerate the configuration contracts. Signed-off-by: zhangxiaoyu.york --- docs/reference/configuration.md | 1 + loom.example.yaml | 4 ++++ schemas/loom-settings.schema.json | 6 ++++++ server/code/app/context.py | 4 ++-- server/settings/catalog.py | 4 ++++ tests/unit/snapshots/settings_defaults.json | 1 + tests/unit/test_code_map.py | 24 +++++++++++++++++++-- 7 files changed, 40 insertions(+), 4 deletions(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index b3d0a5a0398..9fa0f2fdeec 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -255,6 +255,7 @@ The code plane: ingest, indexes, search, ask, review. | Variable | Type | Default | Live | Meaning | | --- | --- | --- | --- | --- | | `LOOM_CODE_INTEL_ENABLED` | `bool` | `True` | | Master kill switch, checked at the top of every code.* handler but the retirement (code.repo.remove), which only deletes. | +| `LOOM_CODE_MAP_RENDER_ATTEMPTS` | `int` | `3` | | Maximum render attempts for code.map and orientation context packs when the indexed head advances; at least 1. Exhaustion returns a retryable overload. | | `LOOM_CODE_TEST_GATE_RUN_TEMPLATES` | `str` | `''` | | code.test_gate run recipes (LOOM_CODE_TEST_GATE_RUN_TEMPLATES): JSON list of {"pattern": , "run":