Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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": <regex over the repo-relative test path>, "run": <template>}, tried before the built-ins. Templates may use {path} {dir} {stem} {name} {parent}. A path no recipe matches is reported run_unknown, never guessed. |
| `LOOM_CODE_TEST_NEIGHBOR_ROWS` | `int` | `200` | | Maximum neighboring test files examined for links to changed definitions. Between 1 and 4294967295; larger values consider more files before ranking. |
| `LOOM_CODE_ASK_TOKEN_BUDGET` | `int` | `0` | | Retrieval context (tokens) code.ask hands to synthesis when the caller passes no token_budget; 0 means unlimited. |
Expand Down
4 changes: 4 additions & 0 deletions loom.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,10 @@ settings:
# (code.repo.remove), which only deletes. [restart]
# code_intel_enabled: true

# Maximum render attempts for code.map and orientation context packs when the indexed
# head advances; at least 1. Exhaustion returns a retryable overload. [restart]
# code_map_render_attempts: 3

# code.test_gate run recipes (LOOM_CODE_TEST_GATE_RUN_TEMPLATES): JSON list of
# {"pattern": <regex over the repo-relative test path>, "run": <template>}, tried
# before the built-ins. Templates may use {path} {dir} {stem} {name} {parent}. A path
Expand Down
6 changes: 6 additions & 0 deletions schemas/loom-settings.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -1452,6 +1452,12 @@
"type": "string",
"description": "The code-link `revise` judge: does a memory's claim still hold for its code's new text."
},
"code_map_render_attempts": {
"default": 3,
"minimum": 1,
"type": "integer",
"description": "Maximum render attempts for code.map and orientation context packs when the indexed head advances; at least 1. Exhaustion returns a retryable overload."
},
"code_merge_shas_log_timeout_s": {
"default": 8.0,
"exclusiveMinimum": 0,
Expand Down
49 changes: 37 additions & 12 deletions server/code/app/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import time
from dataclasses import dataclass
from typing import Any

from server.code.api.models_context import (
Expand All @@ -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
from server.settings import settings

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)


async def handle_code_context_pack(input: CodeContextPackInput) -> CodeContextPackOutput:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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- `")
Expand Down Expand Up @@ -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(settings.code_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
Expand Down Expand Up @@ -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


Expand Down
4 changes: 4 additions & 0 deletions server/settings/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,10 @@ class CodeSettings(BaseModel):
# retirement (code.repo.remove), which only deletes.
code_intel_enabled: bool = True

# Maximum render attempts for code.map and orientation context packs when
# the indexed head advances; at least 1. Exhaustion returns a retryable overload.
code_map_render_attempts: int = Field(default=3, ge=1)

# code.test_gate run recipes (LOOM_CODE_TEST_GATE_RUN_TEMPLATES): JSON list of
# {"pattern": <regex over the repo-relative test path>, "run": <template>},
# tried before the built-ins. Templates may use {path} {dir} {stem} {name}
Expand Down
69 changes: 69 additions & 0 deletions tests/integration/test_code_map_cache.py
Original file line number Diff line number Diff line change
@@ -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()
1 change: 1 addition & 0 deletions tests/unit/snapshots/settings_defaults.json
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@
"code_jit_risk_refit_interval_s": 604800,
"code_jit_risk_window_months": 12,
"code_link_revise_model": "",
"code_map_render_attempts": 3,
"code_merge_shas_log_timeout_s": 8.0,
"code_merge_shas_max_log_commits": 5000,
"code_message_grep_error_codes_ttl_s": 600.0,
Expand Down
Loading
Loading