From 7eb744b8d75abbdf28b4a1fffd587768fcab7bf0 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:14:59 +0530 Subject: [PATCH 01/49] A rename revision that lost its key's lock is tried again by a later pass Review nit on the rename revision (server/memory/app/code_renames.py): "`_REFUSED` treats every 409 as a final refusal, and the key write lock raises `PreconditionFailedError` (409) when the key is busy. A revision that only lost a lock race returns False, the policy step clears the mark, and the memory is never revised though nothing about it forbids it." The lock's refusal is its own class, `KeyBusy`, with the same wire code and status. `revise` raises it, so the policy step leaves every mark of the memory due, stamped behind the rest, as for any failed revision. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/concepts/memory.md | 3 ++- server/memory/app/code_renames.py | 9 ++++++--- server/memory/store/key_write_lock.py | 22 +++++++++++++--------- tests/unit/test_memory_code_rename_plan.py | 16 ++++++++++++++++ 4 files changed, 37 insertions(+), 13 deletions(-) diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 205e16b6976..71f928e793d 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -751,7 +751,8 @@ and applies them itself when all of these hold: The revision is one `memory.update_by_id` write on the hash of the text the edits were planned for, so a memory rewritten in the meantime is left alone. The write reads the memory again under its key's lock, and one pinned, verified, attested or no longer -`active` since the pass read it keeps its text. It runs that write's +`active` since the pass read it keeps its text. A revision that fails, or that another +conditional write kept from the key's lock, is tried again by a later pass. It runs that write's blacklist and conflict checks, embeds the new text and closes the facts the old value stated, as any revision does. Nobody asked for it, so it changes that memory alone. It is not written where a caller's revision would do more: the conflict check finds the revised diff --git a/server/memory/app/code_renames.py b/server/memory/app/code_renames.py index 24a3f669571..c6feb7a042f 100644 --- a/server/memory/app/code_renames.py +++ b/server/memory/app/code_renames.py @@ -38,6 +38,7 @@ from server.memory.domain.trust import attests, subject_of from server.memory.store import code_links as store from server.memory.store.code_links import LinkRow +from server.memory.store.key_write_lock import KeyBusy # What `planned` counts a memory under when it offers edits; else under its reason. OFFERED = "edits" @@ -46,6 +47,7 @@ # The statuses memory.update_by_id's write refuses a revision with: the memory moved # since it was planned, expired, is locked, was pinned, attested or retired since it was # read, or the new value is refused or is close to another memory's. Its text stays. +# A key another write holds (`KeyBusy`, a 409 too) refuses nothing of the memory. _REFUSED = (404, 409, 422, 423) # A memory to plan: its head and the links made from it as it is now. @@ -93,8 +95,9 @@ async def revise(org: str, head: dict[str, Any], links: Sequence[LinkRow]) -> bo write, on the hash of the text the edits were planned for. True when it was written. The write is the reviser's own in the audit log (`ACTOR`), and the model calls it makes (the embedding) are for the memory's writer. A revision the write - refuses (`_REFUSED`) leaves the text; any other failure raises, a model call held - for the writer (`customer.HOLDS`) among them.""" + refuses (`_REFUSED`) leaves the text; any other failure raises, among them a model + call held for the writer (`customer.HOLDS`) and a key whose lock another write kept + (`KeyBusy`).""" from server.memory.app import update current = code_link_reads.current(org, head, list(links)) @@ -122,7 +125,7 @@ async def revise(org: str, head: dict[str, Any], links: Sequence[LinkRow]) -> bo if_match_sha256=plan.sha256, ) except (HTTPException, LoomServerError) as e: - if e.status_code not in _REFUSED: + if isinstance(e, KeyBusy) or e.status_code not in _REFUSED: raise return False return written.updated diff --git a/server/memory/store/key_write_lock.py b/server/memory/store/key_write_lock.py index e0fb4054043..453e3af741f 100644 --- a/server/memory/store/key_write_lock.py +++ b/server/memory/store/key_write_lock.py @@ -30,6 +30,16 @@ def lock_name( return "memory_key/" + hashlib.sha256(ident.encode()).hexdigest()[:40] +class KeyBusy(PreconditionFailedError): + """409 — another conditional write held the key's lock past the wait. Nothing was + read of the row, so the same write may be made again.""" + + def __init__(self) -> None: + super().__init__( + "another conditional write to this key is still running; re-read and retry" + ) + + class KeyWriteLocks: def __init__( self, @@ -90,7 +100,7 @@ async def _take(self, name: str, until: float) -> leases.Lease: try: wait_s = until - time.monotonic() if wait_s <= 0: - raise _busy() + raise KeyBusy() lease = await leases.take( name, ttl_s=self._ttl_s, @@ -108,7 +118,7 @@ async def _take(self, name: str, until: float) -> leases.Lease: operation="memory_key_lock", ) from e if lease is None: - raise _busy() + raise KeyBusy() return lease @asynccontextmanager @@ -119,7 +129,7 @@ async def _process_lock(self, name: str, until: float) -> AsyncIterator[None]: try: await asyncio.wait_for(lock.acquire(), timeout=until - time.monotonic()) except TimeoutError: - raise _busy() from None + raise KeyBusy() from None try: yield finally: @@ -132,12 +142,6 @@ async def _process_lock(self, name: str, until: float) -> AsyncIterator[None]: self._local[name] = (lock, users - 1) -def _busy() -> PreconditionFailedError: - return PreconditionFailedError( - "another conditional write to this key is still running; re-read and retry" - ) - - key_write_locks = KeyWriteLocks() diff --git a/tests/unit/test_memory_code_rename_plan.py b/tests/unit/test_memory_code_rename_plan.py index 9950cb624b5..ebeba38cb66 100644 --- a/tests/unit/test_memory_code_rename_plan.py +++ b/tests/unit/test_memory_code_rename_plan.py @@ -20,6 +20,7 @@ from server.memory.app import code_link_reads, code_renames, update from server.memory.app import provenance as app_provenance from server.memory.domain.code_rename import REASONS, Plan, plan, revised, written_as +from server.memory.store import key_write_lock RULES = "rules-1" PATH = "src/io/reader.py" @@ -863,3 +864,18 @@ async def test_a_revision_that_fails_raises_so_the_memory_stays_due( writer["refusal"] = failure with pytest.raises(type(failure)): await _revise(writer) + + +@pytest.mark.asyncio +async def test_a_revision_that_lost_the_keys_lock_raises_so_the_memory_stays_due( + writer: dict, +) -> None: + """Another conditional write held the key past the lock's wait. That is the write's + 409 too, and nothing about the memory forbids the revision.""" + with pytest.raises(PreconditionFailedError) as busy: + async with key_write_lock.KeyWriteLocks(wait_s=0).hold("o", "code", "-", "-", "-", "k"): + pass + writer["refusal"] = busy.value + with pytest.raises(key_write_lock.KeyBusy): + await _revise(writer) + assert writer["written"] == [] From e57ba3a9fe14195c06ddd1d635e21ac41d8dcd77 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:16:21 +0530 Subject: [PATCH 02/49] A plugin connection's `?mode=` is trimmed, as the plugin's hooks read it Review nit on the plugin modes (server/transport/mcp_schemas.py): "The server and the hooks read a padded mode differently. `plugin_profile` lower-cases without trimming, so `?mode=memory ` lists both planes; `pluginMode` trims, so the hooks run memory only. [...] An install whose option has a stray space captures nothing while its listing shows every tool. Fix: `.strip()` in `plugin_profile`." Failing cases: `plugin_profile("plugin", "MEMORY ")` returned `plugin`, the listing of both planes, which the test asserted. Pattern: the server lower-cased the mode, the hooks trim and lower-case. Hypothesis: strip before the lookup; a padded `memory` or `code` then names its one-plane profile and every other value still changes nothing. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/transport/mcp_schemas.py | 7 ++++--- tests/unit/test_mcp_listing_budget.py | 5 ++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/server/transport/mcp_schemas.py b/server/transport/mcp_schemas.py index f678c71de82..466b9dc8706 100644 --- a/server/transport/mcp_schemas.py +++ b/server/transport/mcp_schemas.py @@ -421,11 +421,12 @@ def compact_descriptor(descriptor: dict[str, Any]) -> dict[str, Any]: def plugin_profile(requested: str | None, mode: str | None) -> str | None: """The URL's `?schema_profile=` with a plugin connection's `?mode=` folded in, so every reader of the profile sees one value: `memory` and `code` name the profile - that lists that plane alone. Any other mode (`both`, a typo, none) and any other - profile leave the value as the URL gave it.""" + that lists that plane alone, read as the plugin's hooks read the option: trimmed, + in any case. Any other mode (`both`, a typo, none) and any other profile leave the + value as the URL gave it.""" if str(requested or "").lower() != PLUGIN_SCHEMA_PROFILE: return requested - return PLUGIN_PLANE_PROFILES.get(str(mode or "").lower(), requested) + return PLUGIN_PLANE_PROFILES.get(str(mode or "").strip().lower(), requested) def plugin_plane(schema_profile: str | None) -> str: diff --git a/tests/unit/test_mcp_listing_budget.py b/tests/unit/test_mcp_listing_budget.py index 7f3ed946d9f..e3d94e112e7 100644 --- a/tests/unit/test_mcp_listing_budget.py +++ b/tests/unit/test_mcp_listing_budget.py @@ -674,9 +674,12 @@ def selectors(**query: str) -> dict: # each is strictly smaller than the listing of both planes assert _tok(list(listed["memory"].values())) < _tok(list(both.values())) assert _tok(list(listed["code"].values())) < _tok(list(both.values())) - for mode in ("both", "cod", "", "MEMORY "): + for mode in ("both", "cod", "", "memory code"): assert plugin_profile("plugin", mode) == "plugin", mode assert plugin_profile("Plugin", "Code") == "plugin-code" + # read as the plugin's hooks read the option: trimmed, in any case + assert plugin_profile("plugin", "MEMORY ") == "plugin-memory" + assert plugin_profile("plugin", " code\n") == "plugin-code" for profile in ("compact", "standard", ""): assert selectors(schema_profile=profile, mode="code")["schema_profile"] == profile # a toolset with no `coding` part keeps its whole listing, as it keeps its own rules From 6564c2df093f79154187a1014c8ac70ad3c48546 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:20:10 +0530 Subject: [PATCH 03/49] A plugin connection in code mode gets no authored profile at `initialize` Review nit on the plugin modes (server/transport/mcp_primer.py): "Code mode's startup instructions still end with the caller's authored profile. The plugin branch of `_initialize_instructions` appends `_profile_section` for every plugin profile, `plugin-code` included, and `initialize` records a profile read. [...] Fix: skip the profile when `plugin_plane(schema_profile) == 'code'`, or say in docs/reference/mcp.md and the Modes sections that the profile is still sent." Failing cases: `initialize` on `?schema_profile=plugin&mode=code` for a caller with an authored profile returned the code sentence followed by the whole profile, and wrote an `mcp.initialize` profile-read row. Pattern: the plugin branch rendered the profile for every plugin profile. Hypothesis: code mode reads no memory, so its sentence is the whole text; no profile is rendered and no profile read is recorded. The both-planes and memory-mode texts are unchanged. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/reference/mcp.md | 12 ++++---- server/transport/mcp.py | 6 ++-- server/transport/mcp_primer.py | 15 ++++++++-- tests/unit/test_mcp_initialize_surface.py | 10 +++++++ tests/unit/test_mcp_primer_order.py | 34 +++++++++++++++++++---- 5 files changed, 63 insertions(+), 14 deletions(-) diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index 3abd0584b61..5e56c636cd6 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -36,9 +36,11 @@ Query parameters on the URL select what `tools/list` shows for that connection: plane, for a plugin installed in that mode. `memory` lists the toolset without its `code.*` tools and loads none up front. `code` lists the `code.*` tools alone, with the repository header or without it, and no prompt and no - resource. The startup paragraph says that plane's sentence. `both`, any other - value, and a `mode` beside another profile change nothing. The lists follow - the URL alone, so a shared cache may keep them. + resource. The startup paragraph says that plane's sentence, and in `code` it is + the whole of the instructions: the caller's authored profile is not read. The + value is trimmed and read in any case. `both`, any other value, and a `mode` + beside another profile change nothing. The lists follow the URL alone, so a + shared cache may keep them. Compact coding connections describe the common source workflows in the startup instructions. Find the other tools through discovery. When the `coding` @@ -115,8 +117,8 @@ Coding connections describe implicit code and memory scopes as defaults in `initialize` and `server/discover`. The routing text can be reused across sessions with different default bindings. When a call needs a namespace argument, the instructions name the available namespaces. Authored profiles -remain in the instructions. Usage hints are available in tool results and -through `mentor.brief`. +remain in the instructions, except on a plugin connection in code mode. Usage +hints are available in tool results and through `mentor.brief`. Methods served: `initialize`, `notifications/initialized`, `notifications/cancelled`, `ping`, `tools/list`, `tools/call`, `prompts/list`, diff --git a/server/transport/mcp.py b/server/transport/mcp.py index b613bc7b12b..edbf582ff61 100644 --- a/server/transport/mcp.py +++ b/server/transport/mcp.py @@ -90,6 +90,7 @@ _prompts_descriptor, _read_resource, _resources_descriptor, + inlines_profile, ) from server.transport.mcp_refusals import classify_tool_errors from server.transport.mcp_schemas import plugin_profile @@ -204,8 +205,9 @@ async def _handle_request( # row like `loom_activate` does, and the Profile page's "read by" # chip stops saying "never read" to a client that reads it on # every connect. Anonymous probes carry no profile and no row, and neither - # does the assistant toolset's primer, which inlines no profile. - if auth is not None and not assistant_connection(toolset): + # does a primer that inlines none: the assistant toolset's, and a + # plugin's in code mode. + if auth is not None and inlines_profile(toolset, schema_profile): await _emit_initialize_event(auth, client_name) return _ok(req_id, result) diff --git a/server/transport/mcp_primer.py b/server/transport/mcp_primer.py index b908a045603..ea0e82438f7 100644 --- a/server/transport/mcp_primer.py +++ b/server/transport/mcp_primer.py @@ -561,7 +561,8 @@ async def _initialize_instructions( paragraph, since its hooks carry the routing. Clients control display and context limits. The profile comes only with a verified bearer: an anonymous probe (discovery_only / open modes) must not read - profile content. + profile content. A plugin's connection in code mode reads no memory, so its + paragraph is the whole text (`inlines_profile`). """ from server.settings import settings @@ -571,7 +572,8 @@ async def _initialize_instructions( defaults = await _caller_defaults(auth) coding = "coding" in toolset_parts(toolset) if coding and _plugin_connection(schema_profile): - profile = await _profile_section(auth, defaults) if auth is not None else "" + inlined = auth is not None and inlines_profile(toolset, schema_profile) + profile = await _profile_section(auth, defaults) if inlined else "" return _plugin_instructions(toolset, defaults, schema_profile) + profile rules = ( _coding_instructions(toolset, defaults, schema_profile=schema_profile) @@ -601,6 +603,15 @@ async def _initialize_instructions( return keep_first_marks(rules + scope_line + workspace + mentor) + profile +def inlines_profile(toolset: str | None, schema_profile: str | None) -> bool: + """Whether a verified caller's `initialize` ends with their authored profile: not + the assistant's, and not a coding-agent plugin's in code mode, which reads no + memory.""" + if assistant_connection(toolset): + return False + return not (_plugin_connection(schema_profile) and code_only_listing(toolset, schema_profile)) + + def _plugin_connection(schema_profile: str | None) -> bool: """Whether the URL names the plugin profile: a coding-agent plugin's connection.""" return str(schema_profile or "").lower() in PLUGIN_SCHEMA_PROFILES diff --git a/tests/unit/test_mcp_initialize_surface.py b/tests/unit/test_mcp_initialize_surface.py index 9c370a74f7b..5e7ef178e55 100644 --- a/tests/unit/test_mcp_initialize_surface.py +++ b/tests/unit/test_mcp_initialize_surface.py @@ -237,6 +237,16 @@ async def _defaults(auth: Any, client_name: str | None = None) -> dict[str, str] ) ) assert emitted == [] + # a plugin connection in code mode inlines no profile: no profile read + asyncio.run( + mcp._handle_request( + {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, + auth=object(), + toolset="coding", + schema_profile="plugin-code", + ) + ) + assert emitted == [] def test_initialize_survives_ledger_failure(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/tests/unit/test_mcp_primer_order.py b/tests/unit/test_mcp_primer_order.py index 8751f5e48dc..da0d0d1ef31 100644 --- a/tests/unit/test_mcp_primer_order.py +++ b/tests/unit/test_mcp_primer_order.py @@ -141,11 +141,10 @@ def test_a_plugin_connection_in_one_mode_gets_that_planes_sentence( """The paragraph names only tools the mode lists: the two sentences of the full paragraph, one each, so each mode's text is shorter than it.""" both, memory, code = ( - _split( - asyncio.run( - mcp_primer._initialize_instructions(object(), "coding", schema_profile=profile) - ) - )[0].strip() + # the profile follows the paragraph, in every mode but code + asyncio.run(mcp_primer._initialize_instructions(object(), "coding", schema_profile=profile)) + .partition("**My always-loaded context")[0] + .strip() for profile in ("plugin", "plugin-memory", "plugin-code") ) assert both == f"{code} {memory}" @@ -168,6 +167,31 @@ async def no_default(*_a: Any, **_k: Any) -> dict[str, Any]: assert "namespace" not in texts["plugin-code"] +def test_a_plugin_connection_in_code_mode_carries_no_profile(wired_caller: list[Any]) -> None: + """Code mode reads no memory: its sentence is the whole text and the caller's + profile is not rendered. Every other plugin connection ends with the profile, and + so does a toolset with no `coding` part, which keeps its own rules.""" + + def text(toolset: str, profile: str) -> str: + return asyncio.run( + mcp_primer._initialize_instructions(object(), toolset, schema_profile=profile) + ) + + code = text("coding", "plugin-code") + assert code.startswith("Use Loom first for unchanged indexed code") + assert "be terse." not in code and "always-loaded context" not in code + assert wired_caller == [] # no profile render, so no restricted-access check + assert not mcp_primer.inlines_profile("coding", "plugin-code") + for toolset, profile in ( + ("coding", "plugin"), + ("coding", "plugin-memory"), + ("core", "plugin-code"), + ): + assert "be terse." in _split(text(toolset, profile))[1], (toolset, profile) + assert mcp_primer.inlines_profile(toolset, profile), (toolset, profile) + assert not mcp_primer.inlines_profile("assistant", None) + + def test_compact_coding_primer_preserves_scope_and_profile() -> None: full = asyncio.run( mcp_primer._initialize_instructions(object(), "coding", schema_profile="standard") From 222594eaeec2f4e430bef35c7a8582aa3de5760d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:21:18 +0530 Subject: [PATCH 04/49] A plugin connection's plane has one spelling on the URL: `?mode=` Review nit on the plugin modes (server/transport/mcp_schemas.py): "`plugin-memory` and `plugin-code` are now accepted directly as `?schema_profile=` values: `resolve_schema_profile`, `_plugin_connection` and `listing_plane` all take them from the URL, with no `?mode=`. docs/reference/mcp.md documents only `?mode=`, so the same listing has a second, undocumented spelling. Fix: carry the plane as its own selector, or have `_listing_params` reduce a URL-given `plugin-*` value to the default." `plugin_profile` reads a URL-given one-plane name as no profile, so the connection gets the server's default profile, as for any value the server does not take from a URL. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/transport/mcp_schemas.py | 8 ++++++-- tests/unit/test_mcp_listing_budget.py | 5 +++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/server/transport/mcp_schemas.py b/server/transport/mcp_schemas.py index 466b9dc8706..ed14a492590 100644 --- a/server/transport/mcp_schemas.py +++ b/server/transport/mcp_schemas.py @@ -423,8 +423,12 @@ def plugin_profile(requested: str | None, mode: str | None) -> str | None: every reader of the profile sees one value: `memory` and `code` name the profile that lists that plane alone, read as the plugin's hooks read the option: trimmed, in any case. Any other mode (`both`, a typo, none) and any other profile leave the - value as the URL gave it.""" - if str(requested or "").lower() != PLUGIN_SCHEMA_PROFILE: + value as the URL gave it. The one-plane names are not the URL's to give, so a + plane has one spelling: a URL that gives one names no profile.""" + profile = str(requested or "").lower() + if profile in PLUGIN_PLANE_PROFILES.values(): + return None + if profile != PLUGIN_SCHEMA_PROFILE: return requested return PLUGIN_PLANE_PROFILES.get(str(mode or "").strip().lower(), requested) diff --git a/tests/unit/test_mcp_listing_budget.py b/tests/unit/test_mcp_listing_budget.py index e3d94e112e7..eeeb8791903 100644 --- a/tests/unit/test_mcp_listing_budget.py +++ b/tests/unit/test_mcp_listing_budget.py @@ -682,6 +682,11 @@ def selectors(**query: str) -> dict: assert plugin_profile("plugin", " code\n") == "plugin-code" for profile in ("compact", "standard", ""): assert selectors(schema_profile=profile, mode="code")["schema_profile"] == profile + # the one-plane names are the server's own: a URL that gives one names no profile + for profile in ("plugin-memory", "Plugin-Code"): + for mode in ({}, {"mode": "code"}): + named = selectors(toolset="coding", schema_profile=profile, **mode) + assert named["schema_profile"] is None, (profile, mode) # a toolset with no `coding` part keeps its whole listing, as it keeps its own rules assert _listing("core", False, "plugin-memory") == _listing("core", False, "plugin") From 8b4bf585cef7a2cce21cd74af896e502cf80f0a4 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:30:20 +0530 Subject: [PATCH 05/49] A code search that abstains on its fused list names the abstain score Review nit on the code-search confidence (server/code/app/search/calibrate.py): "A `low_calibrated_confidence` abstain keeps the shared `finalize_abstain` text 'calibrated retrieval confidence is too low for a grounded answer' while `retrieval_confidence` on the same reply can read 1.0. [...] only the wording now contradicts the field. Fix: have the code plane's reason say 'abstain score', as the settings comment already does." `finalize_abstain` takes the name of the score its verdict was taken on; the memory plane keeps its text. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/search/calibrate.py | 2 ++ server/memory/domain/retrieval_calibration.py | 6 +++++- tests/unit/test_code_search_provenance.py | 2 ++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/server/code/app/search/calibrate.py b/server/code/app/search/calibrate.py index 766ada7787b..d0f39eec01f 100644 --- a/server/code/app/search/calibrate.py +++ b/server/code/app/search/calibrate.py @@ -102,6 +102,8 @@ def _calibrate( no_match_reason=( "no strong match in the code index — use grep on the working tree instead" ), + # not `retrieval_confidence`, which reads the best cosine alone and can be 1.0 here + low_confidence_reason="the abstain score is too low", ) _apply_voting_leg_outcomes(result, card_stats, concept_stats, card_gate=card_gate) if result.abstain and result.abstain_reason and result.abstain_code != "off_domain": diff --git a/server/memory/domain/retrieval_calibration.py b/server/memory/domain/retrieval_calibration.py index 7eb077271d6..afa46130709 100644 --- a/server/memory/domain/retrieval_calibration.py +++ b/server/memory/domain/retrieval_calibration.py @@ -236,6 +236,7 @@ def finalize_abstain( abstain_threshold: float, no_match_reason: str = "nothing matched the query above the noise floor", grounding_reason: str | None = None, + low_confidence_reason: str = "calibrated retrieval confidence is too low", ) -> tuple[bool, str, str]: """Shared abstain envelope for any retrieval plane. @@ -254,6 +255,9 @@ def finalize_abstain( on-topic same-domain neighbour that names none of the identifiers the query asked about. It ranks below the empty/weak-hit gates (those already abstain for a stronger reason) and above the calibrator's verdict. + + `low_confidence_reason` names the score the calibrator's verdict was taken on, for + a plane that reports another number as its confidence. """ if top_similarity is None: return (True, "no_match", no_match_reason) @@ -271,7 +275,7 @@ def finalize_abstain( return ( True, "low_calibrated_confidence", - "calibrated retrieval confidence is too low for a grounded answer: " + f"{low_confidence_reason} for a grounded answer: " + str(getattr(calibration, "explanation", "")), ) return False, "", "" diff --git a/tests/unit/test_code_search_provenance.py b/tests/unit/test_code_search_provenance.py index 5784eaf2652..08fcad72612 100644 --- a/tests/unit/test_code_search_provenance.py +++ b/tests/unit/test_code_search_provenance.py @@ -333,6 +333,8 @@ def test_abstention_is_decided_on_the_fused_list_not_on_the_confidence() -> None assert weak.abstain and weak.abstain_code == "low_calibrated_confidence" assert (weak.retrieval_confidence, weak.retrieval_risk) == (1.0, "abstain") assert "top_similarity=0.40, margin=0.00, route_agreement=0.33" in weak.abstain_reason + # the reason names the score that decided, not the confidence that reads 1.0 beside it + assert weak.abstain_reason.startswith("the abstain score is too low for a grounded answer: ") # the legs agree on the best row: the same cosine is not an abstain agreed = _search(_agreeing(0.40), _Embedder(), **scale) assert not agreed.abstain From 9084949de724ee167d45cc155abb4d26b86d44a3 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:31:32 +0530 Subject: [PATCH 06/49] The `retrieval_confidence` field comment is one sentence Review nit on the code-search confidence (server/code/api/models_search.py): "The `retrieval_confidence` field comment runs eight lines, and the generated reference keeps only its first two sentences. The 0.5 cases (no vector row, no scale) and the 0.0 on an empty abstain are therefore missing from the op reference and the tool description. The wire-ops rule asks for one sentence per field; move the detail to the architecture page, which already has it." The comment keeps the sentence the reference renders. The architecture page gains the cases it did not have: 0.0 on an abstain with no result, the fixed values of the symbol and history routes, and a second vector model read on the served embedder's scale. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/architecture/code-index-architecture.md | 6 ++++++ server/code/api/models_search.py | 7 +------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index bf5ce27deb3..ed1cd7942b5 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -650,6 +650,12 @@ the rows (`code/domain/index/search_confidence.py`, `code/app/search/calibrate.p into its distractor range, or, with no calibration, `LOOM_MEMORY_SEARCH_ABSTAIN_THRESHOLD` set at or over `LOOM_LLM_RERANK_SKIP_ABOVE`. The search reads 0.5 then too, and `calibration_explanation` says so. +- **No results.** An abstain that returns no result reads 0.0. +- **A second vector model.** The scale is the served embedder's. A request's + `vector_model` with no shortlist ranks on its own cosines, which are read on that + scale all the same, as its abstention is. +- **No vector leg to read.** An exact symbol match reads a fixed 0.95 and the history + route 0.5. - **Not abstention.** Abstention is decided apart from the confidence, on the fused list: its top cosine under the abstain threshold (`below_threshold`), or a route-aware score (that cosine, its margin over the second hit, route agreement and diff --git a/server/code/api/models_search.py b/server/code/api/models_search.py index b196786e0d6..f4b86dba79c 100644 --- a/server/code/api/models_search.py +++ b/server/code/api/models_search.py @@ -259,12 +259,7 @@ def _drop_empty_fanout(self, handler: SerializerFunctionWrapHandler) -> dict[str retrieval_risk: Literal["low", "medium", "high", "abstain"] = "low" # Confidence 0-1 that the index holds an answer, not that the first result is the # right one: the vector leg's best cosine on the embedder's calibrated scale, or a - # fixed 0.95 on an exact symbol match and 0.5 on the history route. A question about - # other code usually scores lower, not always. 0.5 when the vector leg gave no row - # or the confident-hit cosine is not above the abstain threshold, 0.0 on an abstain - # with no results. The scale is the served embedder's: a second - # `vector_model` with no shortlist ranks on its own cosines, which are read on that - # scale all the same, as its abstention is. + # fixed 0.95 on an exact symbol match and 0.5 on the history route. retrieval_confidence: float = 0.0 # Share (0-1) of the retrieval routes that ran and agreed: the primary hit, lexical and # vector legs sharing a top-10 chunk, a fuzzy-symbol hit; 1.0 on an exact symbol hit. From 8a57f0294f6eca6e68adafd604f7eb2156a64302 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:31:49 +0530 Subject: [PATCH 07/49] The stand-in confidence is named for both of its uses Review nit on the code-search confidence (server/code/domain/index/search_confidence.py): "`NO_COSINE_CONFIDENCE` is also returned by `similarity_term` when a cosine exists but the scale has no range, so the name describes one of its two uses. [...] A neutral name such as `UNREAD_CONFIDENCE` would fit both uses." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/search/calibrate.py | 2 +- server/code/domain/index/search_confidence.py | 6 +++--- tests/unit/test_code_search_confidence.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/server/code/app/search/calibrate.py b/server/code/app/search/calibrate.py index d0f39eec01f..dd7e137a824 100644 --- a/server/code/app/search/calibrate.py +++ b/server/code/app/search/calibrate.py @@ -81,7 +81,7 @@ def _calibrate( # the request skipped the vector leg, no embedder is configured, the leg failed # or it ran and returned no row (a scope or path filter that admits no embedded # chunk, an embedding backlog) - confidence = search_confidence.NO_COSINE_CONFIDENCE + confidence = search_confidence.UNREAD_CONFIDENCE explanation = "no vector row, best cosine unknown" result.retrieval_confidence = round(confidence, 3) result.calibration_explanation = explanation + (", constrained=true" if constrained else "") diff --git a/server/code/domain/index/search_confidence.py b/server/code/domain/index/search_confidence.py index 36c75cfa2c2..ff65de8904d 100644 --- a/server/code/domain/index/search_confidence.py +++ b/server/code/domain/index/search_confidence.py @@ -23,7 +23,7 @@ RAMP_FROM = 0.5 # No cosine to read (no vector leg, or one that returned no row) or no scale to read it # on: the middle of the scale, a medium risk at the default bands, never low. -NO_COSINE_CONFIDENCE = 0.5 +UNREAD_CONFIDENCE = 0.5 def has_range(*, abstain_threshold: float, confident_similarity: float) -> bool: @@ -40,11 +40,11 @@ def similarity_term( best_cosine: float, *, abstain_threshold: float, confident_similarity: float ) -> float: """Where `best_cosine` sits between the two calibrated cosines, 0 to 1; - `NO_COSINE_CONFIDENCE` when they leave no range (`has_range`).""" + `UNREAD_CONFIDENCE` when they leave no range (`has_range`).""" if not has_range( abstain_threshold=abstain_threshold, confident_similarity=confident_similarity ): - return NO_COSINE_CONFIDENCE + return UNREAD_CONFIDENCE position = (best_cosine - abstain_threshold) / (confident_similarity - abstain_threshold) return max(0.0, min((position - RAMP_FROM) / (1.0 - RAMP_FROM), 1.0)) diff --git a/tests/unit/test_code_search_confidence.py b/tests/unit/test_code_search_confidence.py index 644f1be7432..99086498e75 100644 --- a/tests/unit/test_code_search_confidence.py +++ b/tests/unit/test_code_search_confidence.py @@ -33,7 +33,7 @@ def test_a_scale_with_no_range_reads_the_middle_at_every_cosine(confident: float scale = dict(abstain_threshold=0.5, confident_similarity=confident) assert not sc.has_range(**scale) for cosine in (0.2, 0.46, 0.5, 0.7, 1.0): - assert sc.similarity_term(cosine, **scale) == sc.NO_COSINE_CONFIDENCE + assert sc.similarity_term(cosine, **scale) == sc.UNREAD_CONFIDENCE def test_the_narrowest_scale_with_a_range_is_still_read() -> None: @@ -67,4 +67,4 @@ def band(confidence: float) -> str: # under it is high risk, and the band never abstains assert band(1.0) == "low" and band(0.0) == "high" # a search with no cosine is neither - assert band(sc.NO_COSINE_CONFIDENCE) == "medium" + assert band(sc.UNREAD_CONFIDENCE) == "medium" From 4979166d4b23dd34d5ce960247fcc502c6d66e3c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:33:12 +0530 Subject: [PATCH 08/49] The docs say a memory the rename pass left is taken up when its link is next rewritten Review nit on the rename revision (docs/concepts/memory.md): "The docs say the pass decides once and a memory it left is not revised later. `_write_moves` marks every rewritten link that reads `moved` as due, and `_recheck` emits a move whenever the link differs from the stored one, which by my reading includes a shift of its lines. So a memory left while pinned, then unpinned, is revised when its file is next touched [...]. Fix: mark due only when the link's path or name changed in this move, or correct the sentence." The sentence is corrected, here and in the rolling-upgrade rule that said a link `moved` before the upgrade is never marked. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/architecture/rolling-upgrades.md | 5 +++-- docs/concepts/memory.md | 10 ++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 2553a7c2643..a2ba7197c3e 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -984,8 +984,9 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline never marks a `moved` link, and its policy step clears a mark N wrote without revising, so a rename followed during the rollout can leave its memory's text as written: `namespace.validate` lists the edit, as before. A link that read `moved` - before N served is never marked, so its memory's text also stays as written and - listed: no backfill marks it. The revision is a `memory.update_by_id` write, which + before N served is marked only when a recheck next rewrites it (its file changed + and its lines shifted, for one): until then its memory's text stays as written and + listed, and no backfill marks it. The revision is a `memory.update_by_id` write, which N-1 reads as any other version. `renamed` is one more number in the pass outcome. No gate holds the rollout. diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 71f928e793d..352c2475990 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -781,10 +781,12 @@ counted in Unicode code points of the text, where the text reads `old`) and the the link pass left (held outside the repository's code namespace, held by a person, attested, flagged `conflicted`, in a repository indexed on more than one branch, or close to another memory once revised) or has not reached yet. The -pass decides once, when its link follows the rename: a memory it left then is not -revised later, and neither is one whose link already read `moved` under a build that -revises no text ([rule 67](../architecture/rolling-upgrades.md#the-rules)). Those stay -listed until a principal applies the edit. The report writes nothing: to apply an edit, +pass decides when a link follows the rename, and again each time a later recheck +rewrites that link while it reads `moved` (its file changed and its lines shifted, for +one). A memory it left, or one whose link already read `moved` under a build that +revises no text ([rule 67](../architecture/rolling-upgrades.md#the-rules)), is taken +up again then and revised if nothing holds it any more. Until then it stays listed, and +a principal may apply the edit. The report writes nothing: to apply an edit, read the sentence it changes, then call `memory.update` on the key with the revised text and `if_match_sha256` set to the listed hash. That is a revision by the caller, with its conflict check, and it is refused when the memory changed after the report read it. The From 44c52aa4af4f05c1e3914368a8fc68e645399bac Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:34:21 +0530 Subject: [PATCH 09/49] A rename revision committed with its publication pending counts as written Review nit on the rename revision (server/memory/app/code_link_policy.py): "Under the Postgres authority a revision that committed but whose publication failed raises `PublicationPending` (503). `revise` re-raises it, so the pass counts an error, does not count the memory in `renamed`, and stamps links of the replaced text as still due, although the text was written. The next pass tombstones those links, so only the outcome numbers are wrong." `revise` returns True for it: the pass counts the memory as renamed and leaves its links to the link pass, with no error. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/memory/app/code_renames.py | 6 +++++- tests/unit/test_memory_code_rename_plan.py | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/server/memory/app/code_renames.py b/server/memory/app/code_renames.py index c6feb7a042f..6c7456597ef 100644 --- a/server/memory/app/code_renames.py +++ b/server/memory/app/code_renames.py @@ -29,6 +29,7 @@ from server.code.domain.declaration import fingerprint_version from server.code.domain.index.repos import configured_repos, repo_for_namespace from server.core.errors import LoomServerError +from server.core.pg_lease import PublicationPending from server.llm import customer from server.memory.app import code_link_pass as link_pass from server.memory.app import code_link_reads @@ -93,7 +94,8 @@ async def revise(org: str, head: dict[str, Any], links: Sequence[LinkRow]) -> bo """Bring the text of memory `head` up to the renames its `links` followed, when its plan offers edits and it is `_revisable`: one revision through memory.update_by_id's write, on the hash of the text the edits were planned for. True when it was - written. The write is the reviser's own in the audit log (`ACTOR`), and the model + written, its publication still pending included (`PublicationPending`: the text + is committed). The write is the reviser's own in the audit log (`ACTOR`), and the model calls it makes (the embedding) are for the memory's writer. A revision the write refuses (`_REFUSED`) leaves the text; any other failure raises, among them a model call held for the writer (`customer.HOLDS`) and a key whose lock another write kept @@ -124,6 +126,8 @@ async def revise(org: str, head: dict[str, Any], links: Sequence[LinkRow]) -> bo code_rename.revised(text, plan.edits), if_match_sha256=plan.sha256, ) + except PublicationPending: + return True # committed: the delivery worker publishes its rows except (HTTPException, LoomServerError) as e: if isinstance(e, KeyBusy) or e.status_code not in _REFUSED: raise diff --git a/tests/unit/test_memory_code_rename_plan.py b/tests/unit/test_memory_code_rename_plan.py index ebeba38cb66..95e568f66b4 100644 --- a/tests/unit/test_memory_code_rename_plan.py +++ b/tests/unit/test_memory_code_rename_plan.py @@ -15,6 +15,7 @@ from server.code.domain.anchor import Definition from server.core.errors import BackendUnavailableError, ModelCallRefused, PreconditionFailedError from server.core.hashing import served_content_sha256 +from server.core.pg_lease import PublicationPending from server.llm import customer from server.memory.api.models_crud import MemoryUpdateByIdOutput from server.memory.app import code_link_reads, code_renames, update @@ -866,6 +867,14 @@ async def test_a_revision_that_fails_raises_so_the_memory_stays_due( await _revise(writer) +@pytest.mark.asyncio +async def test_a_revision_committed_with_its_publication_pending_is_written(writer: dict) -> None: + """Under the Postgres authority the text is committed and the delivery worker + publishes its rows: the memory is revised, not failed and not to be written again.""" + writer["refusal"] = PublicationPending() + assert await _revise(writer) + + @pytest.mark.asyncio async def test_a_revision_that_lost_the_keys_lock_raises_so_the_memory_stays_due( writer: dict, From d8ffa290bda6afe1c3fa6e8f1fdd09078c37436d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:34:57 +0530 Subject: [PATCH 10/49] Three paragraphs of the memory concepts page are wrapped at the page's width Review nits on docs/concepts/memory.md: "The rewritten paragraph leaves one line unwrapped (`apart) name where the code is now. A link that is ...`), far past the page's wrap width." "The edit leaves a line of about 103 characters ('high-sensitivity memory; a link whose code also changed is listed under `code_links_stale`. Neither the') in a paragraph wrapped near 90. [...] Rewrap the paragraph to its end." Each is rewrapped to its end, with the paragraph an earlier commit of this branch lengthened. No word changes. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/concepts/memory.md | 56 ++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 29 deletions(-) diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 352c2475990..0d8948a131c 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -547,18 +547,17 @@ at. When its old text is gone from git, a link that matched it takes the text th check finds and a changed one stays `changed`; one whose old text no longer parses keeps its last state, and the worker reports it. -After a rename a memory's text still says the old name until it is revised, by the -link pass where the swap is certain ([below](#a-memorys-text-after-a-rename)) or by a -person. Until then the reads that serve its links (listed below, `namespace.validate` -apart) name where the code is now. A link that is `fresh`, `moved` or `changed` at another path or symbol than -the memory was written against is served with both: the current `path`, `symbol`, -`start_line` and `end_line` (trunk's, at the link's last check), and `was_path` and -`was_symbol`, the oldest of the identities the link keeps (its last 16; a claim the -`revise` policy found to hold is re-anchored where the code is and still carries them). -A link to a file carries the path it was written against and no lines. A definition -renamed back to its first name carries neither, nor does an `unresolved` or `missing` -link, nor a link to a definition that replaced a link to its file. In text the line -reads +After a rename a memory's text still says the old name until it is revised, by the link +pass where the swap is certain ([below](#a-memorys-text-after-a-rename)) or by a person. +Until then the reads that serve its links (listed below, `namespace.validate` apart) name +where the code is now. A link that is `fresh`, `moved` or `changed` at another path or +symbol than the memory was written against is served with both: the current `path`, +`symbol`, `start_line` and `end_line` (trunk's, at the link's last check), and `was_path` +and `was_symbol`, the oldest of the identities the link keeps (its last 16; a claim the +`revise` policy found to hold is re-anchored where the code is and still carries them). A +link to a file carries the path it was written against and no lines. A definition renamed +back to its first name carries neither, nor does an `unresolved` or `missing` link, nor a +link to a definition that replaced a link to its file. In text the line reads ``(code moved: `reader::fetch_rows` is now `reader::load_rows` at src/reader.py:12-40)``; a line whose code also changed keeps its warning and adds the same clause. A line names two such links and counts the rest. Naming the place moves no result: a `moved` memory @@ -752,13 +751,13 @@ The revision is one `memory.update_by_id` write on the hash of the text the edit planned for, so a memory rewritten in the meantime is left alone. The write reads the memory again under its key's lock, and one pinned, verified, attested or no longer `active` since the pass read it keeps its text. A revision that fails, or that another -conditional write kept from the key's lock, is tried again by a later pass. It runs that write's -blacklist and conflict checks, embeds the new text and closes the facts the old value -stated, as any revision does. Nobody asked for it, so it changes that memory alone. It is -not written where a caller's revision would do more: the conflict check finds the revised -text a duplicate, a restatement, a refinement or a contradiction of another memory, or -the conflict resolver would judge it against one. It also retires no other row of the -same key. Such a memory keeps its text and is listed with its `edits`. +conditional write kept from the key's lock, is tried again by a later pass. It runs that +write's blacklist and conflict checks, embeds the new text and closes the facts the old +value stated, as any revision does. Nobody asked for it, so it changes that memory alone. +It is not written where a caller's revision would do more: the conflict check finds the +revised text a duplicate, a restatement, a refinement or a contradiction of another +memory, or the conflict resolver would judge it against one. It also retires no other row +of the same key. Such a memory keeps its text and is listed with its `edits`. The new version stays its writer's row (`actor` is kept) and leaves an audit row by `process:code_rename` and a `memory.revised` event; `memory.history` keeps the text it @@ -818,16 +817,15 @@ first of these reasons that applies: | `would_unlink` | would lose a link once revised: the new name is not one definition on the indexed trunk, or the revised text no longer names a definition or file it is linked to. | A memory whose text names no old name or path is not listed, whatever its links, key, tags -and `files` say: its bare name still holds after a move, or the link is back where the text -says. A sentence ends after `.`, `!` or `?` and a space (not after a one-letter abbreviation -such as `e.g.`), at a blank line and before a list item; a line break alone does not end -one. The words that mark a sentence as -being about the name are English, and `call` or `calls` is not one: it is read as calling -the code. The finding reads the 2,000 memories whose `moved` link was last checked (of -those under `keys` when given), in the repositories the caller may read, and no -high-sensitivity memory; a link whose code also changed is listed under `code_links_stale`. Neither the -memory's key, tags, `files`, entities and concepts nor a line number written in its text -is edited. +and `files` say: its bare name still holds after a move, or the link is back where the +text says. A sentence ends after `.`, `!` or `?` and a space (not after a one-letter +abbreviation such as `e.g.`), at a blank line and before a list item; a line break alone +does not end one. The words that mark a sentence as being about the name are English, and +`call` or `calls` is not one: it is read as calling the code. The finding reads the 2,000 +memories whose `moved` link was last checked (of those under `keys` when given), in the +repositories the caller may read, and no high-sensitivity memory; a link whose code also +changed is listed under `code_links_stale`. Neither the memory's key, tags, `files`, +entities and concepts nor a line number written in its text is edited. ## Time From 54925e05c29bd83265671ebc09bfadefb415f065 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:35:10 +0530 Subject: [PATCH 11/49] The docs say what a refused rename revision costs Review nit on the rename revision (server/memory/app/update.py): "`_refuse_unsettled` runs after the embedding call and the conflict check, so each refused revision spends one embedding for the memory's writer. With the conflict resolver on, any near peer sets `review` and refuses the revision, which in a code namespace of related rules may be most of them. Worth a line in the docs on how often the pass is expected to write." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/concepts/memory.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 0d8948a131c..3638629f084 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -757,7 +757,9 @@ value stated, as any revision does. Nobody asked for it, so it changes that memo It is not written where a caller's revision would do more: the conflict check finds the revised text a duplicate, a restatement, a refinement or a contradiction of another memory, or the conflict resolver would judge it against one. It also retires no other row -of the same key. Such a memory keeps its text and is listed with its `edits`. +of the same key. Such a memory keeps its text and is listed with its `edits`. The conflict +check runs on the new text's embedding, so a revision refused there has cost its writer +one embedding call, each time the pass takes the memory up. The new version stays its writer's row (`actor` is kept) and leaves an audit row by `process:code_rename` and a `memory.revised` event; `memory.history` keeps the text it From 8f175d0b03b4af8a451fa8fc842792c7b9af7f6f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:36:42 +0530 Subject: [PATCH 12/49] A git grep error for a list of lines names how many, not the first one Review nit on the line search (server/code/app/index/gitrepo.py): "`shown = literals[0][:40]` puts the first 40 characters of a source line into the `ArgumentsTooLong`, `GrepTimedOut` and `GitError` messages, while `memory_links._grep` takes care to log only a count because 'a line of source may hold a literal'. No caller logs these messages today [...]; for a list of lines the message should carry the count, so that a later `log.warning(..., e)` cannot print source text." A single literal, a name the caller searched for, is still shown. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/index/gitrepo.py | 3 ++- tests/unit/test_memory_code_links.py | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index ecdfaed1cf9..35d68f39415 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -401,7 +401,8 @@ async def grep_paths( written with `literal_paths`, else pathspecs with their magic) — `git grep -l -F`. Exit 1 with nothing on stderr is git's "no match", not an error.""" literals = [literal] if isinstance(literal, str) else list(literal) - shown = literals[0][:40] if literals else "" + # several are lines of source, which may hold a literal: an error names their count + shown = literal[:40] if isinstance(literal, str) else f"{len(literals)} literals" try: proc = await asyncio.create_subprocess_exec( "git", diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index 5bda149bbc7..274bd82087a 100644 --- a/tests/unit/test_memory_code_links.py +++ b/tests/unit/test_memory_code_links.py @@ -5442,6 +5442,10 @@ async def cannot_start(*a, **k): await gitrepo.grep_paths("/nowhere", "a" * 40, "f", ("x.py",)) # E2BIG is the paths being too many, which leaves the index's verdict assert isinstance(raised.value, gitrepo.ArgumentsTooLong) == (errno_ == errno.E2BIG) + # lines of source are counted, never quoted: one may hold a literal + with pytest.raises(gitrepo.GitError) as raised: + await gitrepo.grep_paths("/nowhere", "a" * 40, ['key = "s3cret"', "x = 1"], ("x.py",)) + assert "s3cret" not in str(raised.value) and "2 literals" in str(raised.value) @pytest.mark.asyncio From 845976ab96e2e6a7e3055a17ccafc3446f015121 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:38:43 +0530 Subject: [PATCH 13/49] A line with a NUL byte is not one a definition is searched for by Review nit on the line search (server/code/app/memory_links.py, server/code/domain/successor.py): "a line of the definition is passed to `create_subprocess_exec` as an argument. A line holding a NUL byte raises `ValueError` (embedded null byte), which is neither `OSError` nor `GitError`, so it would fail the recheck of that path instead of reading as 'git cannot search them'. [...] Dropping lines with `\x00` in `own_lines` closes it." A file's bytes are decoded with replacement and split into lines, so a NUL inside a parsed file reaches `own_lines` as written. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/domain/successor.py | 9 +++++++-- tests/unit/test_code_successor.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/server/code/domain/successor.py b/server/code/domain/successor.py index ce328782c49..c6c4f641b23 100644 --- a/server/code/domain/successor.py +++ b/server/code/domain/successor.py @@ -89,10 +89,15 @@ def text(self, d: Definition) -> str: def own_lines(was: Definition, before: Side) -> list[str]: """The lines that tell `was`'s text among the files of a range: its `_LINES` longest that do not hold its name (a rename rewrites those), without their indentation (a - move changes it). A definition moved whole takes them along.""" + move changes it). A definition moved whole takes them along. A line with a NUL byte + is none of them: git takes each as an argument, which cannot hold one.""" name = re.compile(r"(?= _MIN_LINE and not name.search(line)] + told = [ + line + for line in lines + if len(line) >= _MIN_LINE and "\x00" not in line and not name.search(line) + ] return sorted(told, key=lambda line: (-len(line), line))[:_LINES] diff --git a/tests/unit/test_code_successor.py b/tests/unit/test_code_successor.py index b1aa7e41130..a1d3bb6be97 100644 --- a/tests/unit/test_code_successor.py +++ b/tests/unit/test_code_successor.py @@ -1311,3 +1311,14 @@ def test_a_definitions_own_lines_are_its_longest_without_its_name() -> None: ] stub = _side("a.py", "def fetch_rows():\n pass\n") assert own_lines(stub.defs[0], stub) == [] + # a line with a NUL byte cannot be an argument to git: the next longest is taken + nul = _side( + "a.py", + "class Reader:\n" + + _METHOD.replace("sorted(self.rows)", '"\x00 is in the longest line of the method"'), + ) + assert own_lines(next(d for d in nul.defs if d.name == "fetch_rows"), nul) == [ + "for i in range(start, n):", + "self.rows.append(-i)", + "self.rows.append(i)", + ] From 3f2643d9ae0ab61faeebe2e1dd0388043a7985a6 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:39:44 +0530 Subject: [PATCH 14/49] The bounds of a definition's own lines are named for `own_lines` Review nit on the line search (server/code/domain/successor.py): "`_LINES` and `_MIN_LINE` name the mechanism; `_OWN_LINES` / `_MIN_OWN_LINE` (or similar) would say they bound `own_lines`. There is also an extra blank line between `_MAX_LINES` and the new comment that leaves the two constant groups three lines apart." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/domain/successor.py | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/server/code/domain/successor.py b/server/code/domain/successor.py index c6c4f641b23..55ffe68df9f 100644 --- a/server/code/domain/successor.py +++ b/server/code/domain/successor.py @@ -48,14 +48,10 @@ # line up to this many lines; past that the two are not compared and the answer is unsure _MAX_TOKENS = 600 _MAX_LINES = 400 - - -# the lines a definition is searched for by in a range too wide to read whole: this many -# of its longest, each of this many characters or more -_LINES = 3 -_MIN_LINE = 12 - - +# the lines a definition is searched for by in a range too wide to read whole +# (`own_lines`): this many of its longest, each of this many characters or more +_OWN_LINES = 3 +_MIN_OWN_LINE = 12 # the kinds that make a scope a class (a namespace or module is never renamed into one) _CLASS_KINDS = {"class", "struct", "interface", "trait", "record", "enum"} @@ -87,18 +83,19 @@ def text(self, d: Definition) -> str: def own_lines(was: Definition, before: Side) -> list[str]: - """The lines that tell `was`'s text among the files of a range: its `_LINES` longest - that do not hold its name (a rename rewrites those), without their indentation (a - move changes it). A definition moved whole takes them along. A line with a NUL byte - is none of them: git takes each as an argument, which cannot hold one.""" + """The lines that tell `was`'s text among the files of a range: its `_OWN_LINES` + longest that do not hold its name (a rename rewrites those), without their + indentation (a move changes it). A definition moved whole takes them along. A line + with a NUL byte is none of them: git takes each as an argument, which cannot hold + one.""" name = re.compile(r"(?= _MIN_LINE and "\x00" not in line and not name.search(line) + if len(line) >= _MIN_OWN_LINE and "\x00" not in line and not name.search(line) ] - return sorted(told, key=lambda line: (-len(line), line))[:_LINES] + return sorted(told, key=lambda line: (-len(line), line))[:_OWN_LINES] def _scope_of(d: Definition) -> str: From d4400e9fe8fa5e5185e3ba7a9b43e560eeb35d7c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:39:45 +0530 Subject: [PATCH 15/49] The `_may_be` docstring leaves each rule to the function that holds it Review nit on the line search (server/code/domain/successor.py): "the docstring is wrapped unevenly ('kinship among every changed file. A member's name is one any' / 'class may define ...') and runs to ten lines restating rules that `_grown` and `_with_its_class` already document. Rewrap it and leave the detail to those two." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/domain/successor.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/server/code/domain/successor.py b/server/code/domain/successor.py index 55ffe68df9f..4d8e6acc3f9 100644 --- a/server/code/domain/successor.py +++ b/server/code/domain/successor.py @@ -237,15 +237,13 @@ def _may_be( was: Definition, before: Side, d: Definition, now: Side, had: Side | None, left: Side | None ) -> bool: """Whether a small `was` may be `d` in another file or scope. Under `_SMALL` tokens - a text is mostly its signature, and two stubs have one shape (`class - ReadError(Exception): pass`, `RetryError`). From module level its name is its own: - it goes, into any scope, under a name of its own words (`_read_rows`, - `read_rows_v2`), and to the module level of another file under one that holds them - or that they hold, two words at least or a number apart (`_grown`; in its own file - `successor` decides, where a width alone is a sibling); one shared word is no - kinship among every changed file. A member's name is one any - class may define (`__iter__`, `close`): it goes only with its class - (`_with_its_class`), under a name the search of its own file would take (`_kin`).""" + a text is mostly its signature, and two stubs have one shape. From module level its + name is its own: it goes into any scope under a name of its own words + (`_read_rows`, `read_rows_v2`), and to the module level of another file under a + name grown from them (`_grown`; in its own file `successor` decides). A member's + name is one any class may define (`__iter__`, `close`): it goes only with its + class (`_with_its_class`), under a name the search of its own file would take + (`_kin`).""" a, b = _words(was.name), _words(d.name) same = bool(a) and _unversioned(a) == _unversioned(b) scope, target = _scope_of(was), _scope_of(d) From 6ac54a2ae4accf886c263d4309e2d3c92a2c38c5 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:40:16 +0530 Subject: [PATCH 16/49] The `_renamed_elsewhere` docstring says what is returned Review nit on the line search (server/memory/app/code_link_recheck.py): "'Nothing, as before this search, when ...' describes history rather than the behaviour [...]. Say what is returned: no successor." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/memory/app/code_link_recheck.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/memory/app/code_link_recheck.py b/server/memory/app/code_link_recheck.py index 5a454270d4e..e4c744acb5e 100644 --- a/server/memory/app/code_link_recheck.py +++ b/server/memory/app/code_link_recheck.py @@ -599,8 +599,8 @@ async def _renamed_elsewhere( files changed since: the one with its tokens, also under a name its file had for another text (`successor.retaken`), or with `edited` one with a close text. A range of more than `_MAX_ELSEWHERE` files is read only where a line of the definition is - held, in as many files at most. Nothing, as before this search, when the range - brought no definition in or cannot be read, or the link's last-read text cannot. A + held, in as many files at most. No successor when the range brought no definition + in or cannot be read, or the link's last-read text cannot. A link already unresolved is unsure over a range not read whole, unless that read names its successor: its range starts at its own commit and only grows, and the candidates that left it unresolved may still be there, in a file that holds none of From ea231c0d3ede0efb6b3df0952106f63bb9b47770 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:41:38 +0530 Subject: [PATCH 17/49] A range git cannot search is logged once, not for each lost definition Review nit on the line search (server/memory/app/code_link_pass.py): "the INFO line 'a definition not searched for across the N files' is written once per lost definition, also when the cause is range-wide (`git cannot search them`, already remembered under `("unsearchable", base, head)`). A range that lost many linked definitions repeats the same line for each; the past-the-setting warning is logged once a range, and this one could be too." A definition whose own lines are in too many files, or that has none, is still logged for itself. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/memory/app/code_link_pass.py | 7 ++++--- tests/unit/test_memory_code_links.py | 20 +++++++++----------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/server/memory/app/code_link_pass.py b/server/memory/app/code_link_pass.py index 663b574aa9d..409d665b32e 100644 --- a/server/memory/app/code_link_pass.py +++ b/server/memory/app/code_link_pass.py @@ -391,7 +391,8 @@ async def _holding( `memory_code_links_mirror_changed_files` paths (each is an argument to git), more than `limit` files holding one at either end (a line any file has), or a search git cannot run or finish, which is then not made again over this range. - Each is logged, the second as a warning once a range.""" + Each is logged: the second as a warning and the last once a range, the others + for each definition.""" if len(paths) > settings.memory_code_links_mirror_changed_files: if ("too wide", base, head) not in self._read: self._read["too wide", base, head] = True @@ -405,10 +406,10 @@ async def _holding( self.cns, ) return None + if ("unsearchable", base, head) in self._read: + return None # found out, and logged, for another definition: not again held: set[str] = set() why = "" if lines else "it has no line of its own" - if ("unsearchable", base, head) in self._read: - why = "git cannot search them" # found out for another definition: not again ends = ((head, set(paths.values()) - {""}), (base, set(paths))) if not why else () for commit, some in ends: takes = sorted(filter(scope.takes, some)) diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index 274bd82087a..b7f79044382 100644 --- a/tests/unit/test_memory_code_links.py +++ b/tests/unit/test_memory_code_links.py @@ -5821,17 +5821,15 @@ async def no_search(scope, commit, lines, paths, *, limit): reason = ( "git cannot search them" if why == "git-cannot-search" else "its lines are in too many" ) - assert ( - logged - == [ - ( - "INFO", - f"memory links: a definition not searched for across the {changed} files " - f"changed in c0..c1 of code-a: {reason}", - ) - ] - * 2 - ) + # what git cannot search is the range's, said once; whose lines are in too many + # files is each definition's + assert logged == [ + ( + "INFO", + f"memory links: a definition not searched for across the {changed} files " + f"changed in c0..c1 of code-a: {reason}", + ) + ] * (1 if why == "git-cannot-search" else 2) @pytest.mark.asyncio From 4d8ccf0c4b15dfd4a33dba332e34bcc37ee2a623 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:42:10 +0530 Subject: [PATCH 18/49] A test reads one range under two limits Review nit on the earlier follow-ups (server/memory/app/code_link_pass.py): "No test asserts that `limit` is part of the `_once` key; the before/after proof is a snippet only. [...] Add a test that reads one range under two limits, or leave the key alone and say the memo holds one limit per pass." The test fails when the limit is dropped from the key: the answer under the narrower limit would then be the answer under the wider one. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_memory_code_links.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index b7f79044382..db665f14909 100644 --- a/tests/unit/test_memory_code_links.py +++ b/tests/unit/test_memory_code_links.py @@ -5914,6 +5914,30 @@ async def no_search(scope, commit, lines, paths, *, limit): assert searched == [["a line of one definition"]] +@pytest.mark.asyncio +async def test_a_range_is_read_whole_or_not_by_the_limit_it_is_asked_with(monkeypatch) -> None: + # five files changed: too wide under a limit of two, read whole under a limit of + # five, and the first answer is not kept for the second + commits = _wide( + { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + ) + files, _ = _renaming_world(monkeypatch, commits) + assert await files.turnover("c0", "c1", limit=2) is None + whole = await files.turnover("c0", "c1", limit=5) + assert whole is not None + assert [d.name for side in whole.new for d in side.defs if side.path == "pkg/b.py"] == [ + "warm_up" + ] + # asked again under each limit, the range is neither read nor counted again + assert await files.turnover("c0", "c1", limit=2) is None + assert await files.turnover("c0", "c1", limit=5) is whole + assert files.wide_ranges == 1 + + # `_LONG_ROWS` under another name with each of its three longest lines edited: nearly # its text, and no line a search for them finds _REWRITTEN_ROWS = ( From ef744c5522d5bbe546c30761c7a455f2dd0faeed Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:43:06 +0530 Subject: [PATCH 19/49] The extraction page sizes the session prompt by what a test pins Review nit on the earlier follow-ups (docs/features/memory/extraction.md): "The conversation prompt sizes ('about 57,000 for a short input and 86,000 for a longer one') are pinned by no test. Only `len(prompt) < 9000` for the session prompt is asserted [...]. Assert them with a margin, or drop them and keep the pinned bound." The two figures had drifted: the conversation prompt measures 58,083 and 92,454 characters with every flag-gated block off. The page now gives the session prompt's bound and its ratio to the conversation prompt, and the test asserts both. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/features/memory/extraction.md | 6 +++--- tests/unit/test_coding_session_extraction.py | 10 ++++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/features/memory/extraction.md b/docs/features/memory/extraction.md index 90d828b132e..8c55815fceb 100644 --- a/docs/features/memory/extraction.md +++ b/docs/features/memory/extraction.md @@ -86,9 +86,9 @@ a release changed is kept; whether its CI was green at the time is dropped. A plugin's session capture (a `source:` tag) is extracted with a prompt of its own, at every capture size. It holds no conversation rule or example, and is under 9,000 -characters where the conversation prompt is about 57,000 for a short input and 86,000 for -a longer one, because most captures hold nothing to keep and the prompt is then what the -call costs. What the user states that holds beyond the session is kept: a standing rule, a +characters, less than a sixth of the conversation prompt for an input of either size, +because most captures hold nothing to keep and the prompt is then what the call costs. +What the user states that holds beyond the session is kept: a standing rule, a preference, a decision, a fact about their setup. What the user asks for the task alone is not. Its schema asks for the fields a coding fact uses and for the end of a state the user bounds (`valid_to`, `foresight`), so a freeze "until Friday" stops being served after that diff --git a/tests/unit/test_coding_session_extraction.py b/tests/unit/test_coding_session_extraction.py index 82492b92d45..547651472ce 100644 --- a/tests/unit/test_coding_session_extraction.py +++ b/tests/unit/test_coding_session_extraction.py @@ -36,22 +36,24 @@ def test_a_coding_session_is_extracted_with_its_own_prompt_at_every_size(compact: bool) -> None: assert CODING_SESSION_ANCHOR not in _extraction_base_prompt(compact) - def system_prompt(existing: list[dict[str, str]] | None) -> str: + def system_prompt(existing: list[dict[str, str]] | None, session: bool = True) -> str: return _extraction_system_prompt( compact, existing_memories=existing, namespace_categories=None, custom_instructions="", - agent_learnings=True, # not read for a coding session - coding_session=True, + agent_learnings=session, # not read for a coding session + coding_session=session, ) prompt = system_prompt(None) # No conversation rule or example, no examples preamble and no flag-gated block. assert prompt == _CODING_SESSION_SYSTEM_PROMPT assert "EXAMPLE 1" not in prompt - # Most captures hold nothing to keep, so this prompt is what their call costs. + # Most captures hold nothing to keep, so this prompt is what their call costs: the + # sizes the extraction page states, against the conversation prompt's shortest form. assert len(prompt) < 9000 + assert 6 * len(prompt) < len(system_prompt(None, session=False)) # Shown existing memories, which only a short capture is, it ends with the # fence note: the one other system text a session capture is sent. existing = [{"memory_key": "k0", "value": "User lives in Lyon."}] From 399f11198b30c487651cbfc4aa80f47017082788 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:48:17 +0530 Subject: [PATCH 20/49] Vector rows with no distance sort last and leave the rest nearest first Review nit on the tie order (server/code/store/index/search.py): "`_nearest_first` re-sorts the whole pool in Python on `r["distance"]`. A NaN distance (cosineDistance against a zero-norm stored vector) compares false both ways, so `sorted` can leave rows with real distances out of order around it, where ClickHouse's own sort put NaN last [...]. Reachable only if a row with `embedding_dim > 0` holds an all-zero vector; a read of the embed writers would settle it." It is reachable: the local embedder returns an all-zero vector for a blank text. The sort key puts such rows last, in the tie order among themselves. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/store/index/search.py | 11 +++++++++-- tests/unit/test_code_search_determinism.py | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/server/code/store/index/search.py b/server/code/store/index/search.py index 440e079f837..6954e8d0971 100644 --- a/server/code/store/index/search.py +++ b/server/code/store/index/search.py @@ -6,6 +6,7 @@ from __future__ import annotations import asyncio +import math from datetime import datetime from typing import Any @@ -18,8 +19,14 @@ def _nearest_first(rows: list[dict[str, Any]], *keys: str) -> list[dict[str, Any]]: """`rows` nearest first, rows at one distance in `keys` order: the statement that - read them may sort on the distance alone.""" - return sorted(rows, key=lambda r: (r["distance"], *(r[k] for k in keys))) + read them may sort on the distance alone. A distance that is not a number (to an + all-zero stored vector) comes last, as ClickHouse sorts it.""" + + def order(r: dict[str, Any]) -> tuple[Any, ...]: + unknown = math.isnan(r["distance"]) + return (unknown, 0.0 if unknown else r["distance"], *(r[k] for k in keys)) + + return sorted(rows, key=order) class SearchMixin(CodeRepoBase): diff --git a/tests/unit/test_code_search_determinism.py b/tests/unit/test_code_search_determinism.py index 68c1eab8f6b..239c55193d6 100644 --- a/tests/unit/test_code_search_determinism.py +++ b/tests/unit/test_code_search_determinism.py @@ -68,6 +68,25 @@ async def test_vector_rows_at_one_distance_come_in_file_order() -> None: assert "ORDER BY distance ASC LIMIT {pool:UInt32}" in _norm(ch.calls[0][0]) +@pytest.mark.asyncio +async def test_a_row_with_no_distance_comes_last_and_leaves_the_rest_in_order() -> None: + """The cosine distance to an all-zero stored vector (a blank text under the local + embedder) is NaN, which compares false both ways: it sorts last, as ClickHouse puts + it, and the rows around it stay nearest first.""" + rows = [ + _row("far", "src/a.py", 1, 0.40), + _row("none-b", "src/b.py", 1, float("nan")), + _row("near", "src/a.py", 2, 0.10), + _row("none-a", "src/a.py", 3, float("nan")), + _row("mid", "src/a.py", 4, 0.25), + ] + rng = random.Random(7) + for _ in range(20): + rng.shuffle(rows) + found = await CodeRepo(_CH(rows)).vector_search_chunks("o", "n", "m", [0.1, 0.2]) # type: ignore[arg-type] + assert [r["chunk_id"] for r in found] == ["near", "mid", "far", "none-a", "none-b"] + + @pytest.mark.asyncio async def test_card_rows_at_one_distance_come_in_path_order() -> None: rows = [ From e7c5babc3ec1548b5085ea30ed06ca4b36d81623 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:48:34 +0530 Subject: [PATCH 21/49] The symbol-lookup order test says why it asserts the bound keys Review nit on the tie order (tests/unit/test_code_search_determinism.py): "`test_symbol_lookup_reads_its_candidates_in_one_order` asserts the bound `keys` parameter of the second statement, the implementation rather than the rows read back. A behavioural case needs more than 4,000 candidate keys; if that is why it stays a stub, say so in its docstring in one clause." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_code_search_determinism.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_code_search_determinism.py b/tests/unit/test_code_search_determinism.py index 239c55193d6..2ea69b64610 100644 --- a/tests/unit/test_code_search_determinism.py +++ b/tests/unit/test_code_search_determinism.py @@ -291,7 +291,8 @@ async def test_overloads_of_one_name_and_span_come_in_file_order() -> None: @pytest.mark.asyncio async def test_symbol_lookup_reads_its_candidates_in_one_order() -> None: """The candidate keys come back in no order and the live read takes the first 4,000: - they are sorted, the compiler tier's before the parser tier's.""" + they are sorted, the compiler tier's before the parser tier's. Asserted on the keys + the read is given: the rows show the order only past 4,000 candidates.""" candidates = [ {"tier": "treesitter", "qualified_name": "m::f", "symbol_id": "s2"}, {"tier": "scip", "qualified_name": "m::f", "symbol_id": "s9"}, From f985d2fcda69c63e8bf1fc1c93d0adc9e8e9dbef Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:49:30 +0530 Subject: [PATCH 22/49] The architecture page states the path penalties of code-search ranking Review nit on the lexical pool (docs/architecture/code-index-architecture.md): "The revert removes the paragraph that describes the ranking's test-path and prose penalties and the test-word and doc-word exemptions. That behaviour still ships in `_apply_fusion_signals` [...]. The page now says nothing about the penalties." A later change put the exemptions back on the page. This adds the sentence they refer to: which paths are ranked lower, and by how much. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/architecture/code-index-architecture.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index ed1cd7942b5..efe4cd39b39 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -675,6 +675,11 @@ questions about a named identifier. An unmatched identifier does not disable saturation. Per-symbol deduplication still removes repeated chunks of one definition, and continuation pages retain the final served order. +For a question about the implementation, ranking multiplies the score of a test, +example, fuzzer or benchmark path by 0.35 and the score of a prose file by +`LOOM_CODE_SEARCH_PROSE_PENALTY`: such a file is ranked lower, never dropped. The prose +penalty is off for a search constrained to paths and for a symbol lookup. + A question asks for tests when it holds a test word (`test`, `pytest`, `fixture`, `ci`), and for documentation when it holds a documentation word (`docs`, `changelog`, `tutorial`). Test intent turns off the test-path penalty, the fan-in prior, the kind From 5f1b05eebd5d151e12264c0e48047e5ba53f51bf Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:49:41 +0530 Subject: [PATCH 23/49] The architecture page lists the definition leg among what test intent changes Review nit on the issue-length priors (docs/architecture/code-index-architecture.md): "The paragraph lists four things test intent turns off (test-path penalty, fan-in prior, kind prior, per-file saturation) and omits the fifth reader this PR rewires: the definition leg's exclusion of definitions on test paths (definitions.py named_definitions asks_tests)." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/architecture/code-index-architecture.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index efe4cd39b39..9fdeaeddf0b 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -683,7 +683,8 @@ penalty is off for a search constrained to paths and for a symbol lookup. A question asks for tests when it holds a test word (`test`, `pytest`, `fixture`, `ci`), and for documentation when it holds a documentation word (`docs`, `changelog`, `tutorial`). Test intent turns off the test-path penalty, the fan-in prior, the kind -prior and per-file saturation; documentation intent turns off the prose penalty. A +prior and per-file saturation, and lets the definition leg return a definition on a +test path; documentation intent turns off the prose penalty. A question with more lexemes than `LOOM_CODE_SEARCH_QUERY_MAX_TOKENS` is an issue body, where such a word names where a fault showed: a traceback path, a version listing, a link. Only its first 16 lexemes are read for intent, which hold the title of a report From 938ad72364dc6f28c6865717a0606a10ae36b82f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:50:59 +0530 Subject: [PATCH 24/49] The intent-length tests pin the issue-body cap they index by Review nit on the issue-length priors (tests/unit/test_code_fusion_signals.py): "`test_a_question_up_to_the_issue_body_length_is_read_whole` and the test after it build questions from settings.code_search_query_max_tokens with a 60-word list. A unit environment that sets the cap above 59 raises IndexError in `_question` instead of a readable failure, and a cap of 15 or less makes the second test index past the question. Pin the cap with monkeypatch as the third test does." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_code_fusion_signals.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_code_fusion_signals.py b/tests/unit/test_code_fusion_signals.py index c77f0ad5a11..4093816c972 100644 --- a/tests/unit/test_code_fusion_signals.py +++ b/tests/unit/test_code_fusion_signals.py @@ -175,15 +175,17 @@ def _question(lexemes: int, word: str, at: int) -> str: return " ".join(words) -def test_a_question_up_to_the_issue_body_length_is_read_whole() -> None: - cap = settings.code_search_query_max_tokens +def test_a_question_up_to_the_issue_body_length_is_read_whole(monkeypatch) -> None: + cap = 48 # within the word list, whatever the environment sets + monkeypatch.setattr(settings, "code_search_query_max_tokens", cap) assert asks_for_tests(_question(cap, "tests", cap - 1)) assert asks_for_docs(_question(cap, "docs", cap - 1)) assert not asks_for_tests(_question(cap, "docs", cap - 1)) -def test_an_issue_body_asks_for_tests_or_docs_only_in_its_opening() -> None: - longer = settings.code_search_query_max_tokens + 1 +def test_an_issue_body_asks_for_tests_or_docs_only_in_its_opening(monkeypatch) -> None: + monkeypatch.setattr(settings, "code_search_query_max_tokens", 48) + longer = 49 assert asks_for_tests(_question(longer, "tests", _INTENT_HEAD_LEXEMES - 1)) assert not asks_for_tests(_question(longer, "tests", _INTENT_HEAD_LEXEMES)) assert asks_for_docs(_question(longer, "changelog", 0)) From 9c24812aa45d6264fa190d1dd74c2ec21645e267 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:51:00 +0530 Subject: [PATCH 25/49] A test covers the definition leg on a long report that mentions a test Review nit on the issue-length priors (server/code/app/search/definitions.py): "Missing test for a promised behaviour: the body draft says the definition leg prefers a source definition for a long report that mentions a test, but no test covers the leg with such a query. [...] One named_definitions or _definition_leg case with a query over 48 lexemes and a test word past lexeme 16 would close it." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_code_search_definition_leg.py | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/unit/test_code_search_definition_leg.py b/tests/unit/test_code_search_definition_leg.py index c9eaab423e7..8b705ab46cd 100644 --- a/tests/unit/test_code_search_definition_leg.py +++ b/tests/unit/test_code_search_definition_leg.py @@ -162,6 +162,46 @@ def test_a_name_keeps_its_definitions_outside_tests_or_its_test_ones() -> None: ] +class _Named: + """The two keyed reads of the definition leg, over `_SYMBOLS`.""" + + async def symbols_named(self, org, ns, names, *, qualified, per_name): + return [row for row in _SYMBOLS if row["name"] in names] + + async def definition_chunks(self, org, ns, model, definitions, *, scope): + return [{"path": path, "scope": name} for path, name in definitions] + + +def test_a_report_that_mentions_a_test_gets_the_source_definition(monkeypatch) -> None: + """A test word past the opening of an issue-length question asks for no tests: the + name defined only on a test path is passed over for the next one. The same names in + a short question, read whole, give the test's definition.""" + from server.code.app.search.definitions import _definition_leg + + monkeypatch.setattr(settings, "code_search_query_max_tokens", 48) + + def leg(query: str) -> list[str]: + rows = asyncio.run( + _definition_leg( + _Named(), # type: ignore[arg-type] + "o", + "n", + "m", + query=query, + run=True, + work={}, + path_prefix="", + scope=None, + ) + ) + return [row["path"] for row in rows] + + names = "test_combine() fails and combine() drops the alias" + assert leg(names) == ["tests/q.py"] + report = " ".join(f"word{i}" for i in range(50)) # an issue body with no test word + assert leg(f"{report} {names}") == ["pkg/query.py", "pkg/tree.py"] + + def test_a_definition_on_a_demoted_path_is_no_candidate_unless_the_query_asks_for_tests() -> None: names = [_name("test_combine"), _name("combine")] # the search ranks a test down for this query, so the name defined only there is From cce8ea25bec6d34e58250edc2901edde6dca8264 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:51:28 +0530 Subject: [PATCH 26/49] The intent head is documented as the opening of the question as sent Review nit on the issue-length priors (server/code/app/search/priors.py): "`_intent_lexemes` takes the first 16 lexemes of the raw query, while the trim it borrows its length line from reads the query after strip_boilerplate. A flattened templated body that opens 'Company or project name _No response_ Describe what's wrong ...' spends 9 of the 16 lexemes on headings [...]. The failure direction is the safe default (ranked as a report). Fix: take the head from code_tokens(strip_boilerplate(query)[0]), or say in the comment that headings count." The comment and the architecture page say so. Reading the head after the headings are stripped would change which questions keep the path penalties, which needs the held-out measurement the rule was chosen on. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/architecture/code-index-architecture.md | 5 +++-- server/code/app/search/priors.py | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 9fdeaeddf0b..d873d21144a 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -688,8 +688,9 @@ test path; documentation intent turns off the prose penalty. A question with more lexemes than `LOOM_CODE_SEARCH_QUERY_MAX_TOKENS` is an issue body, where such a word names where a fault showed: a traceback path, a version listing, a link. Only its first 16 lexemes are read for intent, which hold the title of a report -or the request a long prompt opens with. A long prompt that states its request after -that opening is ranked as a report. +or the request a long prompt opens with. They are counted in the question as sent, so a +template's headings before the title are among them. A long prompt that states its +request after that opening is ranked as a report. ### Symbol bodies diff --git a/server/code/app/search/priors.py b/server/code/app/search/priors.py index 311252fb442..7d161938d8c 100644 --- a/server/code/app/search/priors.py +++ b/server/code/app/search/priors.py @@ -205,7 +205,10 @@ def _prose_penalty(*, eligible: bool) -> float: # application called `test1`, a traceback path, `pytest: 7.1` in a version listing, a # `docs.` host, "the following test fails"), so only its opening can ask for tests or # documentation: the title of a report, or the request a long prompt starts with. A -# title fits in 16 lexemes. +# title fits in 16 lexemes. The opening is of the question as sent: a template heading +# before the title (`Describe what's wrong`) spends lexemes of it, where the long +# question trim reads the text without its headings, so a templated body is more often +# ranked as a report. _INTENT_HEAD_LEXEMES = 16 From 535135b4b4b7e6245d622663aa281e2d2fe639e7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:51:36 +0530 Subject: [PATCH 27/49] `_intent_lexemes` says a request's extra terms do not count toward its length Review nit on the issue-length priors (server/code/app/search/priors.py): "The length test is code_tokens(query), but query_trim.plan() decides 'issue body' on code_tokens(query + extra_terms). A request with extra_terms can be trimmed as an issue body while intent is still read from the whole question. [...] Either state that extra_terms do not count for intent, or pass the same token count." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/search/priors.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/server/code/app/search/priors.py b/server/code/app/search/priors.py index 7d161938d8c..82f6920b198 100644 --- a/server/code/app/search/priors.py +++ b/server/code/app/search/priors.py @@ -214,7 +214,9 @@ def _prose_penalty(*, eligible: bool) -> float: def _intent_lexemes(query: str) -> frozenset[str]: """The lexemes that can say what `query` asks for: all of them, or the first - `_INTENT_HEAD_LEXEMES` when the question is long enough to be an issue body.""" + `_INTENT_HEAD_LEXEMES` when the question is long enough to be an issue body. The + length is the question's own: a request's `extra_terms`, which the long question + trim counts with it, say nothing of what is asked.""" tokens = code_tokens(query) cap = int(settings.code_search_query_max_tokens) if 0 < cap < len(tokens): From d2fa3b051cf4bfc30542260141c90166b876a635 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:53:05 +0530 Subject: [PATCH 28/49] The fusion signals tokenize the query once Review nit on the issue-length priors (server/code/app/search/priors.py): "`_apply_fusion_signals` now tokenizes the query three times in a row (q_tokens, asks_for_tests, asks_for_docs), each a full regex pass over up to 20,000 characters [...]. A single _intent_lexemes(query) call intersected with both word sets, or helpers that take the token list, would remove the repeat." `_intent_lexemes` takes the token list. The ranking of the same units is unchanged. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/search/priors.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/server/code/app/search/priors.py b/server/code/app/search/priors.py index 82f6920b198..25a0c972c08 100644 --- a/server/code/app/search/priors.py +++ b/server/code/app/search/priors.py @@ -212,12 +212,11 @@ def _prose_penalty(*, eligible: bool) -> float: _INTENT_HEAD_LEXEMES = 16 -def _intent_lexemes(query: str) -> frozenset[str]: - """The lexemes that can say what `query` asks for: all of them, or the first - `_INTENT_HEAD_LEXEMES` when the question is long enough to be an issue body. The - length is the question's own: a request's `extra_terms`, which the long question - trim counts with it, say nothing of what is asked.""" - tokens = code_tokens(query) +def _intent_lexemes(tokens: list[str]) -> frozenset[str]: + """Those of a question's lexemes (`tokens`) that can say what it asks for: all of + them, or the first `_INTENT_HEAD_LEXEMES` when the question is long enough to be an + issue body. The length is the question's own: a request's `extra_terms`, which the + long question trim counts with it, say nothing of what is asked.""" cap = int(settings.code_search_query_max_tokens) if 0 < cap < len(tokens): tokens = tokens[:_INTENT_HEAD_LEXEMES] @@ -226,12 +225,12 @@ def _intent_lexemes(query: str) -> frozenset[str]: def asks_for_tests(query: str) -> bool: """True when `query` asks for test or CI code (see `_TEST_INTENT_TOKENS`).""" - return bool(_intent_lexemes(query) & _TEST_INTENT_TOKENS) + return bool(_intent_lexemes(code_tokens(query)) & _TEST_INTENT_TOKENS) def asks_for_docs(query: str) -> bool: """True when `query` asks for documentation (see `_DOC_INTENT_TOKENS`).""" - return bool(_intent_lexemes(query) & _DOC_INTENT_TOKENS) + return bool(_intent_lexemes(code_tokens(query)) & _DOC_INTENT_TOKENS) def _apply_fusion_signals( @@ -250,9 +249,10 @@ def _apply_fusion_signals( unaffected. Default cap 0 = the prior is not computed.""" if not ranked: return ranked - q_tokens = frozenset(code_tokens(query)) - test_intent = asks_for_tests(query) - if asks_for_docs(query): + tokens = code_tokens(query) # read once, for the keywords and for both intents + q_tokens, intent = frozenset(tokens), _intent_lexemes(tokens) + test_intent = bool(intent & _TEST_INTENT_TOKENS) + if intent & _DOC_INTENT_TOKENS: prose_penalty = 1.0 keywords = frozenset(t for t in q_tokens if len(t) > 2 and t not in _QUERY_STOPWORDS) embedded = embedded_idents(query) From f9343ada69b7129b58c39b2ad7ca2f474390ab4a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:54:21 +0530 Subject: [PATCH 29/49] The lexical leg returns its read directly Review nit on the lexical pool (server/code/store/index/search.py): "The restored `rows = await self._ch.query_all(...)` followed by `return rows` is a local with one use. Returning the awaited call directly is the simpler form." The statement is unchanged. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/store/index/search.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/code/store/index/search.py b/server/code/store/index/search.py index 6954e8d0971..22a454c3a18 100644 --- a/server/code/store/index/search.py +++ b/server/code/store/index/search.py @@ -84,7 +84,7 @@ async def lexical_search_chunks( "{tokens:Array(String)}, {idfs:Array(Float32)}))" ) scope_sql, scope_params = _scope_sql(scope) - rows = await self._ch.query_all( + return await self._ch.query_all( f""" SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, @@ -111,7 +111,6 @@ async def lexical_search_chunks( **scope_params, }, ) - return rows async def definition_chunks( self, From 5a19d263e616f46064c3000a225087f72d4ac1de Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:55:37 +0530 Subject: [PATCH 30/49] The round prefetch says which paths it reads file rows for Review nit on the backfill round reads (server/code/app/index/round_reads.py): "`refused` is every path `parse_for_round` returned None for, which includes declared-only generated files and files over the byte cap. `ingest_file` tombstones neither, so their prefetched file rows are never read. The docstrings call these 'the paths `ingest_file` refuses', and the module docstring says the prefetch reads their 'chunk and file rows' where it reads the chunk index and the file rows." The paths are named for what the round knows of them: it did not parse them. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/index/round_reads.py | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/server/code/app/index/round_reads.py b/server/code/app/index/round_reads.py index d3b9f8be9a4..b8a6c200f94 100644 --- a/server/code/app/index/round_reads.py +++ b/server/code/app/index/round_reads.py @@ -19,10 +19,12 @@ (headers before sources); a `code_edges` insert drops its paths. Prefetch failures fail open to the per-file reads. -With `embedding_model` the prefetch also reads the round's chunk index, the chunk and -file rows of the paths `ingest_file` refuses (their tombstone reads), and with -`reuse_from` the vectors that namespace holds for the round's paths with no live chunk -yet, up to `code_ingest_round_write_rows` of them; a larger round reads them per file. +With `embedding_model` the prefetch also reads the round's chunk index, the chunk index +and file rows of the paths it did not parse (`parse_for_round` gives none for a file +the ingest stops at before parsing; `ingest_file` reads those rows for the ones it +tombstones), and with `reuse_from` the vectors that namespace holds for the round's +paths with no live chunk yet, up to `code_ingest_round_write_rows` of them; a larger +round reads them per file. The round's writes are buffered. A read keyed by name, qualified name, symbol or callee edge writes the buffer first only when an unwritten row carries one of its keys @@ -374,17 +376,18 @@ async def _prefetch_chunk_rows( self, paths: list[str], model: str, *, edges_only: bool, reuse_from: str ) -> None: """The chunk index each file's content-addressed reconcile compares on, the file - rows of the paths `ingest_file` refuses, and the vectors `reuse_from` holds for - the paths with no live chunk yet (every chunk of those is new, so each would - ask). An edges-only round reads no chunk but a refused path's, to tombstone it.""" - refused = [p for p in paths if p not in self.parsed] - indexed = refused if edges_only else paths + rows of the paths the round did not parse (`parse_for_round` gave none), and + the vectors `reuse_from` holds for the paths with no live chunk yet (every + chunk of those is new, so each would ask). An edges-only round reads no chunk + index but an unparsed path's, which `ingest_file` reads for one it tombstones.""" + unparsed = [p for p in paths if p not in self.parsed] + indexed = unparsed if edges_only else paths if indexed: index = await self._round_read("live_chunk_index_for_paths", indexed, model) for path, rows in index.items(): self._chunk_index.setdefault((path, model), rows) - if refused: - self._files = await self._round_read("live_files_for_paths", refused) + if unparsed: + self._files = await self._round_read("live_files_for_paths", unparsed) fresh = [p for p in self.parsed if self._chunk_index.get((p, model), None) == []] if edges_only or not fresh or not reuse_from or reuse_from == self._ns: return From c90983d49749dc56408ec09540b830db9215f9cf Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:58:03 +0530 Subject: [PATCH 31/49] The buffered-key selector is typed by the names it may take Review nit on the backfill round reads (server/code/app/index/round_reads.py): "`_buffers(keyed_by: str, ...)` picks the key set with `getattr(self._pending_keys, keyed_by)` from a string literal at each call site, so a misspelt name fails only at run time and mypy cannot check it." `keyed_by` is a `Literal` of the four key sets, so mypy refuses any other name. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/index/round_reads.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/server/code/app/index/round_reads.py b/server/code/app/index/round_reads.py index b8a6c200f94..de22ece806b 100644 --- a/server/code/app/index/round_reads.py +++ b/server/code/app/index/round_reads.py @@ -43,7 +43,7 @@ import logging from collections.abc import Iterable from dataclasses import dataclass, field -from typing import Any +from typing import Any, Literal from server.code.store.index.symbols import NameCandidates @@ -198,7 +198,9 @@ def _holds(self, path: str) -> bool: def _unsettled(self) -> bool: return bool(self._pending or self._inflight_paths) - def _buffers(self, keyed_by: str, keys: Iterable[Any]) -> bool: + def _buffers( + self, keyed_by: Literal["names", "qualified", "symbols", "callees"], keys: Iterable[Any] + ) -> bool: """Whether a row buffered or being written carries one of `keys`.""" wanted = keys if isinstance(keys, set) else set(keys) return not ( From 4353ff0e20dd308a98cace9533b42542d0809fed Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:59:24 +0530 Subject: [PATCH 32/49] A round's reuse read counts a statement for each hundred paths Review nit on the backfill round reads (server/code/app/index/round_reads.py): "the reuse read adds 1 to `statements` whatever the number of batches `embeddings_for_paths` sent; `_round_read` counts one per 100 paths. A round of more than 100 fresh paths under-counts." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/code/app/index/round_reads.py | 3 ++- .../test_code_round_reads_backfill_statements.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/server/code/app/index/round_reads.py b/server/code/app/index/round_reads.py index de22ece806b..510eab24209 100644 --- a/server/code/app/index/round_reads.py +++ b/server/code/app/index/round_reads.py @@ -401,7 +401,8 @@ async def _prefetch_chunk_rows( except Exception as exc: # noqa: BLE001 — a missed prefetch: each file reads its own vectors logger.debug("round reads: reuse prefetch skipped (%s)", exc) return - self.statements += 1 + # as `_round_read` counts: one per 100 paths (a read cut at the cap sent fewer) + self.statements += max(1, (len(fresh) + 99) // 100) if len(found) > cap: return # more vectors than a round holds at once: each file reads its own self._reuse_for = (reuse_from, model) diff --git a/tests/unit/test_code_round_reads_backfill_statements.py b/tests/unit/test_code_round_reads_backfill_statements.py index ef7c11279ba..7533fae4c10 100644 --- a/tests/unit/test_code_round_reads_backfill_statements.py +++ b/tests/unit/test_code_round_reads_backfill_statements.py @@ -214,6 +214,18 @@ async def go() -> tuple[_Repo, Any]: assert "embeddings_for_texts:a.py" in repo.calls +def test_the_reuse_read_counts_a_statement_for_each_hundred_paths() -> None: + sources = {f"f{i:03}.py": b"X = 1\n" for i in range(150)} + + async def statements(reuse_from: str) -> int: + reads = RoundReads(_Repo(), ORG, NS) + await reads.prefetch(sources, embedding_model=MODEL, reuse_from=reuse_from) + return reads.statements + + # the vectors of 150 paths with no live chunk are read in two statements + assert asyncio.run(statements(SOURCE_NS)) - asyncio.run(statements("")) == 2 + + def _symbol(name: str, qualified: str, symbol_id: str) -> dict[str, Any]: return {"path": "a.py", "name": name, "qualified_name": qualified, "symbol_id": symbol_id} From 1aa7ea07d2ef33a81529283ba6ffcd97e9ea9870 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 02:59:51 +0530 Subject: [PATCH 33/49] Tests cover a file-row write and the vectors of another org or model in a round Review nit on the backfill round reads (tests/unit/test_code_round_reads_backfill_statements.py): "a `code_chunks` insert ending the empty-chunk answer is tested, but a `code_files` insert dropping the cached `live_files_for_path` rows is not, nor that `embeddings_for_texts` reads per file for another org or model." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- ...st_code_round_reads_backfill_statements.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/unit/test_code_round_reads_backfill_statements.py b/tests/unit/test_code_round_reads_backfill_statements.py index 7533fae4c10..b84d4602898 100644 --- a/tests/unit/test_code_round_reads_backfill_statements.py +++ b/tests/unit/test_code_round_reads_backfill_statements.py @@ -226,6 +226,45 @@ async def statements(reuse_from: str) -> int: assert asyncio.run(statements(SOURCE_NS)) - asyncio.run(statements("")) == 2 +def test_a_file_write_ends_the_no_file_row_answer() -> None: + async def go() -> tuple[_Repo, list[Any]]: + repo = _Repo() + reads = RoundReads(repo, ORG, NS) + await reads.prefetch(SOURCES, embedding_model=MODEL) + before = await reads.live_files_for_path(ORG, NS, "logo.png") + await reads.insert_rows("code_files", [{"path": "logo.png"}]) + return repo, [before, await reads.live_files_for_path(ORG, NS, "logo.png")] + + repo, (before, after) = asyncio.run(go()) + assert before == [] and after == [] + # answered from the round's read, then read after the buffered row was written + assert [c for c in repo.calls if c.startswith("live_files_for_path:")] == [ + "live_files_for_path:logo.png" + ] + assert repo.inserted == ["code_files"] + + +@pytest.mark.parametrize("other", [{"org": "other"}, {"embedding_model": "m2"}]) +def test_the_vectors_of_another_org_or_model_are_read_per_file(other: dict[str, str]) -> None: + async def go() -> tuple[_Repo, Any]: + repo = _Repo(vectors={"a.py": [_vector("h1", "t1")]}) + reads = RoundReads(repo, ORG, NS) + await reads.prefetch(SOURCES, embedding_model=MODEL, reuse_from=SOURCE_NS) + asked = {"org": ORG, "embedding_model": MODEL} | other + return repo, await reads.embeddings_for_texts( + asked["org"], + SOURCE_NS, + embedding_model=asked["embedding_model"], + path="a.py", + content_hashes=["h1"], + ) + + repo, rows = asyncio.run(go()) + # the round read this org's vectors under its model: it answers for no other + assert [r["context_text"] for r in rows] == ["t1"] + assert "embeddings_for_texts:a.py" in repo.calls + + def _symbol(name: str, qualified: str, symbol_id: str) -> dict[str, Any]: return {"path": "a.py", "name": name, "qualified_name": qualified, "symbol_id": symbol_id} From 2092f536cc20c9b5bf82d087f35a3eec9cb38338 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:01:10 +0530 Subject: [PATCH 34/49] A test covers the vector read's limit across batches of paths Review nit on the backfill round reads (server/code/store/index/files.py): "nothing exercises `embeddings_for_paths`' limit carried across batches (more than 100 paths, `limit - len(rows)`, the early break). The unit fake reimplements it as `rows[:limit]` and the analyzer case only checks the statement's shape." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- ...st_code_round_reads_backfill_statements.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/unit/test_code_round_reads_backfill_statements.py b/tests/unit/test_code_round_reads_backfill_statements.py index b84d4602898..8b5ca13a9d7 100644 --- a/tests/unit/test_code_round_reads_backfill_statements.py +++ b/tests/unit/test_code_round_reads_backfill_statements.py @@ -265,6 +265,45 @@ async def go() -> tuple[_Repo, Any]: assert "embeddings_for_texts:a.py" in repo.calls +class _Batches: + """Answers each statement with the next scripted rows and keeps its parameters.""" + + def __init__(self, *answers: int) -> None: + self.answers = list(answers) + self.asked: list[dict[str, Any]] = [] + + async def query_all(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]]: + self.asked.append(params) + rows = min(self.answers.pop(0), params["limit"]) + return [{"path": params["paths"][0], "content_hash": b"0a\x00\x00"} for _ in range(rows)] + + +def test_the_vector_read_carries_its_limit_across_batches_of_paths() -> None: + from server.code.store.index import CodeRepo + + paths = [f"f{i:03}.py" for i in range(250)] # three statements of 100 paths at most + + def read(ch: _Batches, limit: int) -> list[dict[str, Any]]: + repo = CodeRepo(ch) # type: ignore[arg-type] + return asyncio.run( + repo.embeddings_for_paths( + ORG, SOURCE_NS, embedding_model=MODEL, paths=paths, limit=limit + ) + ) + + # each statement may return what is left of the limit, and the last batch is read + ch = _Batches(2, 2, 9) + rows = read(ch, 5) + assert [(len(a["paths"]), a["limit"]) for a in ch.asked] == [(100, 5), (100, 3), (50, 1)] + assert len(rows) == 5 and {r["content_hash"] for r in rows} == {"0a"} + # a batch that fills the limit ends the read: the paths after it are not asked for + ch = _Batches(9, 9, 9) + assert len(read(ch, 5)) == 5 and len(ch.asked) == 1 + # under the limit every path is asked for + ch = _Batches(1, 0, 1) + assert len(read(ch, 5)) == 2 and [a["limit"] for a in ch.asked] == [5, 4, 4] + + def _symbol(name: str, qualified: str, symbol_id: str) -> dict[str, Any]: return {"path": "a.py", "name": name, "qualified_name": qualified, "symbol_id": symbol_id} From 7ca3fc612af2b1f376bf648221ec85c576f33432 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:02:05 +0530 Subject: [PATCH 35/49] The worker docstrings say a batch stops the run, held or after a failed write Review nit on the backfill exit code (server/cli/code_backfill_workers.py): "`Workers.index_batches` ('why it was held', 'Once a batch is held nothing more is handed out', 'after a hold') and `Workers._run` ('none handed out once one comes back held') still describe only the org switch. The same channel now carries 'a write failed', and the `Done` comment was updated to 'why it stops the run'. Fix: use the same wording in both docstrings." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/cli/code_backfill_workers.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/server/cli/code_backfill_workers.py b/server/cli/code_backfill_workers.py index 12fd95ee1e7..16c8fb869db 100644 --- a/server/cli/code_backfill_workers.py +++ b/server/cli/code_backfill_workers.py @@ -95,10 +95,11 @@ def __init__(self, workers: list[_Worker]) -> None: async def index_batches( self, batches: list[tuple[int, list[str]]] ) -> AsyncGenerator[Done, None]: - """Each batch with its counters and why it was held, in batch order. The header - batches are all written before the first source batch is handed out. Once a batch - is held nothing more is handed out; the batches still running finish and are - yielded after the ones before them.""" + """Each batch with its counters and why it stops the run (held, or a write + failed), in batch order. The header batches are all written before the first + source batch is handed out. Once a batch stops the run nothing more is handed + out; the batches still running finish and are yielded after the ones before + them.""" held = False for group, part in _groups(batches): if held: @@ -111,7 +112,7 @@ async def index_batches( held = held or bool(done[3]) while order and order[0] in ready: yield ready.pop(order.popleft()) - for b in sorted(ready): # after a hold: those that ran beside it + for b in sorted(ready): # after a stop: those that ran beside it yield ready[b] async def edge_batches(self, batches: list[tuple[int, list[str]]]) -> list[dict[str, int]]: @@ -123,7 +124,7 @@ async def _run( self, kind: str, group: str, batches: list[tuple[int, list[str]]] ) -> AsyncGenerator[Done, None]: """`batches` across the workers as each one finishes its last, yielded as they - finish; none handed out once one comes back held.""" + finish; none handed out once one comes back with a reason to stop the run.""" todo = deque(batches) idle = list(self._workers) running: dict[asyncio.Future[Any], tuple[_Worker, int, list[str]]] = {} From 4418279c2b8174e808af317b254b209f85468e63 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:02:06 +0530 Subject: [PATCH 36/49] The recorded failure count of a backfill pass says what it adds Review nit on the backfill exit code (server/cli/code_backfill.py): "`_close_index` passes `errors=counters["errors"] + sum(unwritten(counters).values())`, so `loom.worker_status.partial_failures` adds failed files to dropped rows, beside `items_done`, which counts files. [...] Fix: say in the comment that the number is files plus rows, or pass `errors + 1` per failed pass so the column stays a count of items." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/cli/code_backfill.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/cli/code_backfill.py b/server/cli/code_backfill.py index be5ed94cd72..77a508b1269 100644 --- a/server/cli/code_backfill.py +++ b/server/cli/code_backfill.py @@ -722,7 +722,8 @@ async def _close_index( started=started, done=counters["files"], rows_written=counters["chunks"] + counters["symbols"] + counters["edges"], - # A row a failed write left out is a failure of the pass, as a file's error is. + # A row a failed write left out is a failure of the pass, as a file's error is: + # the number adds failed files and rows left out. errors=counters["errors"] + sum(unwritten(counters).values()), counters=counters, phase="index", From 1d3e93d694d2be24e9e5ea4d5f9bdc7b0d4f0715 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:02:06 +0530 Subject: [PATCH 37/49] The `write_failed` docstring reads in one pass Review nit on the backfill exit code (server/cli/code_backfill.py): "The `write_failed` docstring 'Why a batch a failed write left rows out of stops its run' is a garden-path sentence." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/cli/code_backfill.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/cli/code_backfill.py b/server/cli/code_backfill.py index 77a508b1269..4c03013ae23 100644 --- a/server/cli/code_backfill.py +++ b/server/cli/code_backfill.py @@ -100,7 +100,8 @@ def unwritten(counters: dict[str, int]) -> dict[str, int]: def write_failed(counters: dict[str, int]) -> str: - """Why a batch a failed write left rows out of stops its run, "" when none did.""" + """The reason a batch stops its run when a failed write left rows out of it, else + "".""" return "a write failed" if unwritten(counters) else "" From 23f19068b6c98c64688a23c73a1a36fc7a26a3ec Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:02:25 +0530 Subject: [PATCH 38/49] The operations page names the backfill's failed writes in plainer words Review nit on the backfill exit code (docs/operations/code-index-operations.md): "'A failed insert of the rows the index phase indexed' and 'the write that closes a round a held model call or a signal had already stopped' are hard to parse on a first read. The second is the only place an operator learns which failures still end in a traceback." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/operations/code-index-operations.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 73785cc9bd9..a32f550dd9a 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -283,7 +283,7 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac once the pass is done, so a resumed run, or a rerun after an interrupted pass, still runs it. `--dialect-folder-pass` lets SQL files of undecided dialect take the dialect their directory agrees on. -- A failed insert of the rows the index phase indexed, for example one that ran past +- A failed insert of rows the index phase buffered, for example one that ran past `LOOM_CH_TIMEOUT_WRITE_S`, stops the run. The round of files that write belongs to finishes, no later round or batch starts (under `--workers`, the batches already running beside it finish), no watermark is written, and the command exits 1. Its last @@ -296,8 +296,8 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac exits 0 with up to 1% of its files failing, a smaller run with none. The record of a file over `LOOM_CODE_INGEST_MAX_FILE_BYTES` is written on its own, and a failure there is that file's error. Any other failed write ends the command with the error itself - and no such lines: the write that closes a round a held model call or a signal had - already stopped, a cursor or watermark write, and the insert of + and no such lines: the closing write of a round that a held model call or a signal + had already stopped, a cursor or watermark write, and the insert of `--dialect-folder-pass`. - `backfill-prs` loads merged-PR history from GitHub, resumable by cursor and bounded by GitHub's rate limit (`LOOM_CODE_PR_BACKFILL_MONTHS`, default 12). `backfill-reviews` From 18d1b76193793c61000a40be7644aac67f12f4bd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:02:26 +0530 Subject: [PATCH 39/49] A comment says why a backfill round is written twice Review nit on the backfill exit code (server/cli/code_backfill.py): "The round is flushed twice: explicitly inside `async with reads:` so a failure is printed and counted, and again by `RoundReads.__aexit__`, which is a no-op on the normal path and the only flush on a hold or cancellation, where its failure propagates as a traceback. [...] Fix: one comment line on the explicit flush saying `__aexit__` then finds nothing buffered, and that it is the flush whose failure still ends the command." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/cli/code_backfill.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server/cli/code_backfill.py b/server/cli/code_backfill.py index 4c03013ae23..e0295906150 100644 --- a/server/cli/code_backfill.py +++ b/server/cli/code_backfill.py @@ -854,6 +854,9 @@ async def _backfill_batch_rounds( await gather_or_cancel( *(one(reads, p, sources[p]) for p in rnd if p in sources) ) + # Written here so a failure is printed and counted. `__aexit__` then + # finds nothing buffered; after a hold or a cancellation it is the + # only write, and its failure ends the command. try: await reads.flush() except Exception as e: # noqa: BLE001 — counted below; the run reports it From 455810b09b7affe7590f9f801ac747691d60ac38 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:03:15 +0530 Subject: [PATCH 40/49] The failed-write test asserts the status row the pass records Review nit on the backfill exit code (tests/unit/test_cli_backfill_second_pass.py): "`test_rows_a_failed_write_left_out_fail_the_recorded_pass` stubs `_record_manual_pass`, `_compact_after_bulk` and `_republish_counts`, then checks the kwargs `_close_index` passed. It would still pass if `_record_manual_pass` stopped mapping `errors` to `partial_failures`. Fix: stub only `status_store.record_manual_pass` and assert the `status` and `partial_failures` it receives." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_cli_backfill_second_pass.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_cli_backfill_second_pass.py b/tests/unit/test_cli_backfill_second_pass.py index 94780aab155..32e9209ce21 100644 --- a/tests/unit/test_cli_backfill_second_pass.py +++ b/tests/unit/test_cli_backfill_second_pass.py @@ -270,15 +270,17 @@ def test_rows_a_failed_write_left_out_fail_the_recorded_pass( monkeypatch: pytest.MonkeyPatch, ) -> None: """The run's `loom.worker_status` row when no file failed and a write did.""" + from server.workers import status_store + recorded: dict[str, Any] = {} - async def _record(*_a: object, **k: Any) -> None: - recorded.update(k) + async def _record(worker: str, **row: Any) -> None: + recorded.update(row, worker=worker) async def _noop(*_a: object, **_k: object) -> None: return None - monkeypatch.setattr(code_backfill, "_record_manual_pass", _record) + monkeypatch.setattr(status_store, "record_manual_pass", _record) monkeypatch.setattr(code_backfill, "_compact_after_bulk", _noop) monkeypatch.setattr(code_backfill, "_republish_counts", _noop) counters = code_backfill.index_counters() | {"files": 200} @@ -286,5 +288,7 @@ async def _noop(*_a: object, **_k: object) -> None: asyncio.run( code_backfill._close_index(None, counters, "acme", "code-x", "m", 0.0, "f" * 40, "backfill") ) - assert (recorded["done"], recorded["errors"]) == (200, 7) - assert code_backfill.manual_pass_status(recorded["done"], recorded["errors"]) == "partial" + # the row as it is written: 200 files done, 7 rows left out, so not `ok` + assert (recorded["worker"], recorded["namespace"]) == ("code_ingest", "code-x") + assert (recorded["items_done"], recorded["partial_failures"]) == (200, 7) + assert recorded["status"] == "partial" From 601d00e1aa47222f9dda81b684e9e406f9f9c49f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:04:36 +0530 Subject: [PATCH 41/49] The rewritten-row test builds its hit from the search document's day Post-merge review of the code-state lead (tests/unit/test_memory_code_state_lead.py): "test_a_rewritten_row_says_first_written_on_a_row_read_and_written_on_a_hit builds its hit from a hand-made date so its assertion is true by construction (build the hit from the document's created_at)." The document is built at a pinned clock and the hit carries its `created_at`, so the `written=` day asserted is the one the write produced. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_memory_code_state_lead.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_memory_code_state_lead.py b/tests/unit/test_memory_code_state_lead.py index 1200249f6e2..29317e8ccc1 100644 --- a/tests/unit/test_memory_code_state_lead.py +++ b/tests/unit/test_memory_code_state_lead.py @@ -190,7 +190,9 @@ def test_a_write_that_leaves_the_text_alone_does_not_move_the_printed_day( assert lesson is not None and lesson["first_written"] == "2026-03-02" -def test_a_rewritten_row_says_first_written_on_a_row_read_and_written_on_a_hit() -> None: +def test_a_rewritten_row_says_first_written_on_a_row_read_and_written_on_a_hit( + monkeypatch: pytest.MonkeyPatch, +) -> None: """A write of the text carries the row's `created_at` and stamps a new search document: a `memory.for_file` line and a lesson name the first day as `first_written`, a search hit names the day of the text it serves as `written`.""" @@ -219,7 +221,9 @@ def test_a_rewritten_row_says_first_written_on_a_row_read_and_written_on_a_hit() lesson = path_lessons._lesson(read, "src/a.cpp") assert lesson is not None and "written" not in lesson assert (lesson["first_written"], lesson["excerpt"]) == ("2026-03-02", said) - # the search document of the rewritten text is created at that write + # the search document of the rewritten text is created at that write, and a hit + # carries the document's day + monkeypatch.setattr(rows, "naive_utc_now", lambda: again) document = rows.search_document_row( row | {"run_id": "-", "source_class": "user"}, embedding_model="test", @@ -228,13 +232,13 @@ def test_a_rewritten_row_says_first_written_on_a_row_read_and_written_on_a_hit() key_text="", excerpt=said, ) - assert document["created_at"] != first + assert document["created_at"] == again hit = _hit( "rules/buckets", said, code_state="fresh", code_rev="ba5e" * 10, - created_at=again.isoformat(), + created_at=document["created_at"].isoformat(), ) assert code_change.hit_note(hit) == " (code_state=fresh rev=ba5eba5eba5e written=2026-04-01)" From fd40a12b0d9c692e8d011db8dac9a202a53dbd5e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:04:37 +0530 Subject: [PATCH 42/49] The `lead` docstring shows both forms of the day Post-merge review of the code-state lead (server/memory/domain/code_change.py): "`lead` docstring shows only the `written=` form." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/memory/domain/code_change.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server/memory/domain/code_change.py b/server/memory/domain/code_change.py index 274afb447b2..1689ce4c3a0 100644 --- a/server/memory/domain/code_change.py +++ b/server/memory/domain/code_change.py @@ -173,8 +173,9 @@ def lead(state: str, rev: str = "", written: str = "", *, first_written: str = " """` (code_state= rev= written=)` ahead of a line's `note` for a memory that names code: its state, the indexed commit its worst link was anchored at (`anchored_commit`) when it holds one, and the day the read knows (`written_on`): - never an `updated_at`, which an unpin, a lock or a restore stamps. '' for a memory - that names no code.""" + `written=` for the day of the text served, else `first_written=` for the + memory's first write, never an `updated_at`, which an unpin, a lock or a restore + stamps. '' for a memory that names no code.""" if not state: return "" at = f" rev={rev[:12]}" if rev else "" From c5eb5b37c58e0d4ee7a423d968df6c0a316eb6a1 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:21:42 +0530 Subject: [PATCH 43/49] The restore tests raise the key lock's own error The undo tests built the busy lock's error through the helper that the lock's error class replaced in this branch. They raise `KeyBusy`, which is what the lock raises. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_restore_lock_busy.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_restore_lock_busy.py b/tests/unit/test_restore_lock_busy.py index f750b048ded..3a7a2d15000 100644 --- a/tests/unit/test_restore_lock_busy.py +++ b/tests/unit/test_restore_lock_busy.py @@ -26,7 +26,7 @@ async def hold(*_args): async def test_an_undo_meeting_a_conditional_write_says_to_retry_the_undo(monkeypatch) -> None: - _lock_failing_with(monkeypatch, key_write_lock._busy()) + _lock_failing_with(monkeypatch, key_write_lock.KeyBusy()) with pytest.raises(PreconditionFailedError) as e: await restore._restore_superseded(_UNDO, ch=None) assert e.value.status_code == 409 @@ -73,7 +73,7 @@ async def query_one(self, sql: str, params: object = None) -> dict: } monkeypatch.setattr(restore, "get_client", lambda: CH()) - _lock_failing_with(monkeypatch, key_write_lock._busy()) + _lock_failing_with(monkeypatch, key_write_lock.KeyBusy()) undo = MemoryRestoreInput(org="o", namespace="ns", agent="a", memory_key="k") with pytest.raises(PreconditionFailedError) as e: await restore.handle_memory_restore(undo) From 4957742d41bcb5881fcedddf0876664e0e938cb8 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:24:52 +0530 Subject: [PATCH 44/49] The primer tests read a text with no profile after the merge of main Main's new first-call test split the code-mode text at the profile, which this branch no longer sends in code mode, and this branch's test asserted the code sentence main reworded. `_split` returns no profile for a text that carries none, and the code-mode test asserts the sentence by the part both wordings keep. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- tests/unit/test_mcp_primer_order.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/tests/unit/test_mcp_primer_order.py b/tests/unit/test_mcp_primer_order.py index fdbedab7f7e..d6a6e7ab149 100644 --- a/tests/unit/test_mcp_primer_order.py +++ b/tests/unit/test_mcp_primer_order.py @@ -51,9 +51,9 @@ async def workspace(*_a: Any, **_k: Any) -> str: def _split(text: str) -> tuple[str, str]: - """The text before the profile and the profile.""" - at = text.index("**My always-loaded context") - return text[:at], text[at:] + """The text before the profile and the profile, '' for a text that carries none.""" + before, mark, profile = text.partition("**My always-loaded context") + return before, mark + profile @pytest.mark.parametrize( @@ -171,10 +171,11 @@ def test_a_plugin_connection_in_one_mode_gets_that_planes_sentence( """The paragraph names only tools the mode lists: the two sentences of the full paragraph, one each, so each mode's text is shorter than it.""" both, memory, code = ( - # the profile follows the paragraph, in every mode but code - asyncio.run(mcp_primer._initialize_instructions(object(), "coding", schema_profile=profile)) - .partition("**My always-loaded context")[0] - .strip() + _split( + asyncio.run( + mcp_primer._initialize_instructions(object(), "coding", schema_profile=profile) + ) + )[0].strip() for profile in ("plugin", "plugin-memory", "plugin-code") ) assert both == f"{code} {memory}" @@ -208,8 +209,8 @@ def text(toolset: str, profile: str) -> str: ) code = text("coding", "plugin-code") - assert code.startswith("Use Loom first for unchanged indexed code") - assert "be terse." not in code and "always-loaded context" not in code + assert " first for unchanged indexed code" in code and "loom_search" not in code + assert _split(code) == (code, "") and "be terse." not in code assert wired_caller == [] # no profile render, so no restricted-access check assert not mcp_primer.inlines_profile("coding", "plugin-code") for toolset, profile in ( From 88321a8ea17f90a023d5bbc36bbcbc104a22c1e8 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:49:30 +0530 Subject: [PATCH 45/49] A line search git cannot run is still made for the next lost definition Review finding on the link pass (server/memory/app/code_link_pass.py): "One definition's failed line search now stops the line search for every other lost definition of the same range in the pass. `_holding` sets `self._read["unsearchable", base, head]` whenever `code.grep_lines` returns None [...] but `grep_lines` returns None for `ArgumentsTooLong` and any `GitError` too, and those depend on the lines." Failing cases: two definitions lost over one wide range, the first holding a line past what git takes as one argument. Its search raised `ArgumentsTooLong`, the range was marked, and the second, which git could search, read `missing` where it had moved. Pattern: the mark was set for every failed search, and only a timeout is the range's: the paths are the same for each definition, the lines are not. Hypothesis: `grep_lines` raises `GrepTimedOut` for a search git does not finish and keeps None for the rest; `_holding` marks the range only then. Predicted: the second definition is followed, and a timed-out search is still made once a range. Both held. The mark was there before this pull request, which had only moved its log line. A search git cannot run fails at once, so making it again for the next definition costs no wait. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/concepts/memory.md | 7 +-- server/code/app/memory_links.py | 10 +++- server/memory/app/code_link_pass.py | 21 +++++---- tests/unit/test_memory_code_links.py | 70 ++++++++++++++++++++++++---- 4 files changed, 85 insertions(+), 23 deletions(-) diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 3638629f084..5330029a10a 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -514,9 +514,10 @@ files and the link's own are parsed, so a removed or kept definition in a file t none of those lines contests nothing. That search is not made for a definition with no such line of 12 characters or more, when those files are more than 32 with the link's own, when more than `memory_code_links_mirror_changed_files` changed (a warning in the -server log names the range), or when git cannot run or finish it, which is then not tried -again for the other links of that range in the pass; nor is a range searched whose diff -cannot be read. Over a range not searched a live link is read as if nothing was renamed. +server log names the range), or when git cannot run it or finish it in its time; nor is a +range searched whose diff cannot be read. A search git did not finish in its time is not +tried again for the other links of that range in the pass: the files are the same for +each. Over a range not searched a live link is read as if nothing was renamed. An `unresolved` link is looked for from the commit its code was last read at, so its range grows with every commit. While that range is within 32 files, the link is followed once one definition that may be it is left. A wider range is read only where its lines diff --git a/server/code/app/memory_links.py b/server/code/app/memory_links.py index d742156e8f5..50d992d37ba 100644 --- a/server/code/app/memory_links.py +++ b/server/code/app/memory_links.py @@ -38,6 +38,9 @@ log = logging.getLogger(__name__) +# what `grep_lines` raises, for its caller to catch +GrepTimedOut = gitrepo.GrepTimedOut + def trunk_namespace(org: str, namespace: str) -> str: """The repository's trunk code namespace for any of its branch namespaces; '' when @@ -181,8 +184,9 @@ async def grep_lines( scope: IngestScope, commit: str, lines: Sequence[str], paths: list[str], *, limit: int ) -> list[str] | None: """Up to `limit` of `paths` whose text at `commit` holds one of `lines` as written. - None when git cannot tell, and for paths too many to pass to git or to search in its - time: no index answers for a line, so a search cut short found nothing out.""" + None when git cannot tell, and for arguments too long to pass to git: no index + answers for a line, so a search cut short found nothing out. One git does not finish + in its time raises `GrepTimedOut`: the same paths take as long for any lines.""" return await _grep(scope, commit, list(lines), paths, limit=limit, word=False) @@ -216,6 +220,8 @@ async def _grep( scope.cfg.namespace, type(e).__name__, ) + if not word and isinstance(e, GrepTimedOut): + raise return [] if word else None except gitrepo.GitError: return None diff --git a/server/memory/app/code_link_pass.py b/server/memory/app/code_link_pass.py index 409d665b32e..9f7b476259d 100644 --- a/server/memory/app/code_link_pass.py +++ b/server/memory/app/code_link_pass.py @@ -389,10 +389,10 @@ async def _holding( holds one of `lines`: at `head` under its path there, at `base` under its old one. None when that cannot be told: no line to look for, more than `memory_code_links_mirror_changed_files` paths (each is an argument to git), - more than `limit` files holding one at either end (a line any file has), or a - search git cannot run or finish, which is then not made again over this range. - Each is logged: the second as a warning and the last once a range, the others - for each definition.""" + more than `limit` files holding one at either end (a line any file has), a + search git cannot run, or one it does not finish in its time, which is then not + made again over this range. Each is logged: the second as a warning and the last + once a range, the others for each definition.""" if len(paths) > settings.memory_code_links_mirror_changed_files: if ("too wide", base, head) not in self._read: self._read["too wide", base, head] = True @@ -406,7 +406,7 @@ async def _holding( self.cns, ) return None - if ("unsearchable", base, head) in self._read: + if ("unfinished", base, head) in self._read: return None # found out, and logged, for another definition: not again held: set[str] = set() why = "" if lines else "it has no line of its own" @@ -414,11 +414,14 @@ async def _holding( for commit, some in ends: takes = sorted(filter(scope.takes, some)) # one past the bound: a cut list is never taken as whole - found = await code.grep_lines(scope, commit, lines, takes, limit=limit + 1) - if found is None: + try: + found = await code.grep_lines(scope, commit, lines, takes, limit=limit + 1) + except code.GrepTimedOut: # the paths are the same for every definition of the range: the next - # one's search would wait as long - self._read["unsearchable", base, head] = True + # one's search would wait as long. A search git cannot run may fail on + # these lines alone (each is an argument), so the next one's is made + self._read["unfinished", base, head] = True + found = None if found is None or len(found) > limit: why = "git cannot search them" if found is None else "its lines are in too many" break diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index db665f14909..27fefa94df5 100644 --- a/tests/unit/test_memory_code_links.py +++ b/tests/unit/test_memory_code_links.py @@ -5473,8 +5473,13 @@ async def too_many(*a, **k): monkeypatch.setattr(gitrepo, "grep_paths", too_many) scope = SimpleNamespace(cfg=SimpleNamespace(git_dir="/nowhere", namespace="code-a")) assert await memory_links.grep_words(scope, "c1", "f", ["a.py"], limit=5) == [] - # no index answers for a line: a search cut short found nothing out - assert await memory_links.grep_lines(scope, "c1", ["f(x)"], ["a.py"], limit=5) is None + # no index answers for a line: a search cut short found nothing out. A timeout is + # the paths', and is raised for the caller to stop searching them + if why == "timed-out": + with pytest.raises(memory_links.GrepTimedOut): + await memory_links.grep_lines(scope, "c1", ["f(x)"], ["a.py"], limit=5) + else: + assert await memory_links.grep_lines(scope, "c1", ["f(x)"], ["a.py"], limit=5) is None @pytest.mark.asyncio @@ -5772,7 +5777,9 @@ async def test_a_range_past_the_file_cap_is_read_where_the_definitions_lines_are @pytest.mark.asyncio -@pytest.mark.parametrize("why", ["too-many-hold-them", "git-cannot-search", "past-the-setting"]) +@pytest.mark.parametrize( + "why", ["too-many-hold-them", "git-cannot-search", "git-cannot-finish", "past-the-setting"] +) async def test_a_wide_range_whose_files_cannot_be_told_is_not_searched( monkeypatch, caplog, why: str ) -> None: @@ -5789,9 +5796,11 @@ async def test_a_wide_range_whose_files_cannot_be_told_is_not_searched( } files, row = _renaming_world(monkeypatch, commits) monkeypatch.setattr(code_link_recheck, "_MAX_ELSEWHERE", 2) - if why == "git-cannot-search": + if why in ("git-cannot-search", "git-cannot-finish"): async def no_search(scope, commit, lines, paths, *, limit): + if why == "git-cannot-finish": + raise code_links.code.GrepTimedOut("git grep 1 literals timed out") return None monkeypatch.setattr(code_links.code, "grep_lines", no_search) @@ -5819,17 +5828,17 @@ async def no_search(scope, commit, lines, paths, *, limit): ] else: reason = ( - "git cannot search them" if why == "git-cannot-search" else "its lines are in too many" + "its lines are in too many" if why == "too-many-hold-them" else "git cannot search them" ) - # what git cannot search is the range's, said once; whose lines are in too many - # files is each definition's + # what git cannot finish is the range's, said once; what it cannot run, or whose + # lines are in too many files, is each definition's assert logged == [ ( "INFO", f"memory links: a definition not searched for across the {changed} files " f"changed in c0..c1 of code-a: {reason}", ) - ] * (1 if why == "git-cannot-search" else 2) + ] * (1 if why == "git-cannot-finish" else 2) @pytest.mark.asyncio @@ -5906,7 +5915,7 @@ async def test_a_line_search_git_cannot_finish_is_not_made_again_over_the_range( async def no_search(scope, commit, lines, paths, *, limit): searched.append(list(lines)) - return None + raise code_links.code.GrepTimedOut("git grep 1 literals timed out") monkeypatch.setattr(code_links.code, "grep_lines", no_search) for line in ("a line of one definition", "a line of another"): @@ -5914,6 +5923,49 @@ async def no_search(scope, commit, lines, paths, *, limit): assert searched == [["a line of one definition"]] +@pytest.mark.asyncio +async def test_a_line_search_that_fails_on_one_definitions_lines_is_made_for_the_next( + monkeypatch, caplog +) -> None: + # git takes each line as an argument, and one definition lost over the range holds a + # line past what an argument may be: that search fails on its lines, not on the range + from server.code.app.index import gitrepo + + commits = _wide( + { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + ) + files, row = _renaming_world(monkeypatch, commits) + monkeypatch.setattr(code_link_recheck, "_MAX_ELSEWHERE", 2) # five changed + blob = "BLOB = '" + "9" * 131_072 + "'" + + async def grep_paths(git_dir, rev, literals, paths, **kw): + if any(len(one) >= 131_072 for one in literals): + raise gitrepo.ArgumentsTooLong("git grep 1 literals: 5 paths") + return [p for p in paths if any(one in commits.get((rev, p), "") for one in literals)] + + async def ingest_scope(org, cns, commit): + cfg = SimpleNamespace(git_dir="/nowhere", namespace="code-a") + return SimpleNamespace(under=lambda path: True, takes=lambda path: True, cfg=cfg) + + monkeypatch.setattr(gitrepo, "grep_paths", grep_paths) + monkeypatch.setattr(code_links.code, "ingest_scope", ingest_scope) + monkeypatch.setattr(code_links.code, "grep_lines", _REAL_GREP_LINES) + with caplog.at_level(logging.INFO, logger=code_link_pass.log.name): + assert await files.turnover_holding("c0", "c1", [blob], "pkg/z.py", limit=2) is None + assert await _followed(files, row) == [("moved", "pkg/b.py", "pkg.b::warm_up")] + # the failed search is said for its definition alone + assert [r.getMessage() for r in caplog.records] == [ + "memory links: mirror search for 1 of its lines over 5 paths of code-a cut short: " + "ArgumentsTooLong", + "memory links: a definition not searched for across the 5 files changed in " + "c0..c1 of code-a: git cannot search them", + ] + + @pytest.mark.asyncio async def test_a_range_is_read_whole_or_not_by_the_limit_it_is_asked_with(monkeypatch) -> None: # five files changed: too wide under a limit of two, read whole under a limit of From cd187fc49b781a44399d6fd859072ad5b9b03eca Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:49:30 +0530 Subject: [PATCH 46/49] `key_write_lock` lists `KeyBusy` among its names Review nit (server/memory/store/key_write_lock.py): "`__all__` does not list `KeyBusy`, which `code_renames.py` imports and two test files use as `key_write_lock.KeyBusy`." Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/memory/store/key_write_lock.py | 1 + 1 file changed, 1 insertion(+) diff --git a/server/memory/store/key_write_lock.py b/server/memory/store/key_write_lock.py index 453e3af741f..d4af13eba78 100644 --- a/server/memory/store/key_write_lock.py +++ b/server/memory/store/key_write_lock.py @@ -181,6 +181,7 @@ async def key_lock_for( __all__ = [ + "KeyBusy", "KeyWriteLocks", "LeaseBusy", "LeaseLost", From 7d85a4337529fd98accd47f1d98ca9d98269726b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 03:49:31 +0530 Subject: [PATCH 47/49] The primer docstrings say code mode reads no memory at `initialize` Review nit (server/transport/mcp_primer.py): "The docstrings say a plugin connection in code mode 'reads no memory'. That holds for `initialize` and `server/discover` only: `resources/read` of `loom://primer`, `prompts/get` of `loom` and `loom_activate` stay callable by name in code mode, and `_loom_primer_text` still appends the caller's profile there." The test docstring that repeated the sentence says the same. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/transport/mcp_primer.py | 6 +++--- tests/unit/test_mcp_primer_order.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/server/transport/mcp_primer.py b/server/transport/mcp_primer.py index 898b1ff6597..7a8a26429bc 100644 --- a/server/transport/mcp_primer.py +++ b/server/transport/mcp_primer.py @@ -562,8 +562,8 @@ async def _initialize_instructions( paragraph, since its hooks carry the routing. Clients control display and context limits. The profile comes only with a verified bearer: an anonymous probe (discovery_only / open modes) must not read - profile content. A plugin's connection in code mode reads no memory, so its - paragraph is the whole text (`inlines_profile`). + profile content. A plugin's connection in code mode reads no memory at + `initialize`, so its paragraph is the whole text (`inlines_profile`). """ from server.settings import settings @@ -607,7 +607,7 @@ async def _initialize_instructions( def inlines_profile(toolset: str | None, schema_profile: str | None) -> bool: """Whether a verified caller's `initialize` ends with their authored profile: not the assistant's, and not a coding-agent plugin's in code mode, which reads no - memory.""" + memory at `initialize`.""" if assistant_connection(toolset): return False return not (_plugin_connection(schema_profile) and code_only_listing(toolset, schema_profile)) diff --git a/tests/unit/test_mcp_primer_order.py b/tests/unit/test_mcp_primer_order.py index d6a6e7ab149..22dddfbeaaf 100644 --- a/tests/unit/test_mcp_primer_order.py +++ b/tests/unit/test_mcp_primer_order.py @@ -199,9 +199,9 @@ async def no_default(*_a: Any, **_k: Any) -> dict[str, Any]: def test_a_plugin_connection_in_code_mode_carries_no_profile(wired_caller: list[Any]) -> None: - """Code mode reads no memory: its sentence is the whole text and the caller's - profile is not rendered. Every other plugin connection ends with the profile, and - so does a toolset with no `coding` part, which keeps its own rules.""" + """Code mode reads no memory at `initialize`: its sentence is the whole text and the + caller's profile is not rendered. Every other plugin connection ends with the + profile, and so does a toolset with no `coding` part, which keeps its own rules.""" def text(toolset: str, profile: str) -> str: return asyncio.run( From a3ccebc46439e5be201c6e8d9af4c8f358a0054f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 04:03:40 +0530 Subject: [PATCH 48/49] The `_holding` docstring names each unsearched case with its log level Review finding on the link pass (server/memory/app/code_link_pass.py): "the `_holding` docstring's logging sentence ('Each is logged: the second as a warning and the last once a range, the others for each definition') makes the reader count back through a five-item list, and it leaves out that a search git cannot run for over-long arguments is also a warning (from `memory_links._grep`). Name each case with its log level instead of by position." The five cases are a list, each with its level and whether it is said for each definition or once a range. Docstring only. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- server/memory/app/code_link_pass.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/server/memory/app/code_link_pass.py b/server/memory/app/code_link_pass.py index 9f7b476259d..f20ec73c744 100644 --- a/server/memory/app/code_link_pass.py +++ b/server/memory/app/code_link_pass.py @@ -387,12 +387,17 @@ async def _holding( ) -> set[str] | None: """The paths of a wide range (`paths`: old -> its path at `head`) whose text holds one of `lines`: at `head` under its path there, at `base` under its old - one. None when that cannot be told: no line to look for, more than - `memory_code_links_mirror_changed_files` paths (each is an argument to git), - more than `limit` files holding one at either end (a line any file has), a - search git cannot run, or one it does not finish in its time, which is then not - made again over this range. Each is logged: the second as a warning and the last - once a range, the others for each definition.""" + one. None when that cannot be told, each case logged: + + - no line to look for: info, for each definition; + - more than `memory_code_links_mirror_changed_files` paths (each is an argument + to git): a warning, once a range; + - more than `limit` files holding a line at either end (a line any file has): + info, for each definition; + - a search git cannot run: info, for each definition, and a warning from + `memory_links._grep` when its arguments were too long; + - a search git does not finish in its time: that warning and the info line, once + a range, as the search is not made again over this range.""" if len(paths) > settings.memory_code_links_mirror_changed_files: if ("too wide", base, head) not in self._read: self._read["too wide", base, head] = True From 02da7790a5797294cdce469caa1132f31bb3ba10 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sun, 29 Nov 2026 04:03:54 +0530 Subject: [PATCH 49/49] A line search git cannot run for its paths alone is made once over a range Review finding on the link pass (server/memory/app/code_link_pass.py): "`ArgumentsTooLong` no longer marks the range, on the reasoning that it may come from one definition's lines. It can also come from the path list, which is the same for every lost definition of the range [...] In that case every lost definition repeats the failed exec, one warning from `_grep` and one info line from `_unsearched`, each pass [...] If the setting's ceiling keeps the paths well under the system's argument limit, this cannot happen and the nit drops; otherwise tell the two causes apart." The ceiling does not keep them under it: the setting allows 20,000 paths and a path may be 4,096 bytes, against a limit of 1 to 2 MiB. Measured here (limit 1,048,576, counting each argument's bytes, NUL and pointer): 9,708 paths of 100 bytes start, 9,709 do not. Failing cases: two definitions lost over one range whose paths alone are past the argument limit. git was started twice, and a warning and an info line were logged for each definition. Pattern: an argument list too long has two causes, the lines (the definition's) and the paths (the range's), and both were read as the definition's. Hypothesis: `grep_paths` raises `PathsTooLong`, a kind of `ArgumentsTooLong`, when the paths alone are past `SC_ARG_MAX`; `grep_lines` raises it on as it does `GrepTimedOut`; `_holding` marks the range for both. Predicted: one start of git, one warning and one info line for the two definitions, and a definition with one over-long line still leaves the next one searched. Both held. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/concepts/memory.md | 7 +-- server/code/app/index/gitrepo.py | 10 +++- server/code/app/memory_links.py | 6 ++- server/memory/app/code_link_pass.py | 16 ++++--- tests/unit/test_memory_code_links.py | 70 ++++++++++++++++++++++++---- 5 files changed, 87 insertions(+), 22 deletions(-) diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 5330029a10a..9d5ac9f1f05 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -515,9 +515,10 @@ none of those lines contests nothing. That search is not made for a definition w such line of 12 characters or more, when those files are more than 32 with the link's own, when more than `memory_code_links_mirror_changed_files` changed (a warning in the server log names the range), or when git cannot run it or finish it in its time; nor is a -range searched whose diff cannot be read. A search git did not finish in its time is not -tried again for the other links of that range in the pass: the files are the same for -each. Over a range not searched a live link is read as if nothing was renamed. +range searched whose diff cannot be read. A search git did not finish in its time, or +could not run because the paths of those files are more than it takes in one command, is +not tried again for the other links of that range in the pass: the files are the same +for each. Over a range not searched a live link is read as if nothing was renamed. An `unresolved` link is looked for from the commit its code was last read at, so its range grows with every commit. While that range is within 32 files, the link is followed once one definition that may be it is left. A wider range is read only where its lines diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index 35d68f39415..6c7b63255dc 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -17,6 +17,7 @@ import os import re import signal +import struct import tempfile from collections.abc import Sequence from dataclasses import dataclass @@ -39,6 +40,10 @@ class ArgumentsTooLong(GitError): """A git command whose arguments are past the system's limit (E2BIG).""" +class PathsTooLong(ArgumentsTooLong): + """One whose paths alone are past it, whatever else it is given.""" + + class GrepTimedOut(GitError): """A `git grep` that ran past its time.""" @@ -425,7 +430,10 @@ async def grep_paths( ) except OSError as e: # an argument list past the system's limit, or no git to run if e.errno == errno.E2BIG: - raise ArgumentsTooLong(f"git grep {shown}: {len(pathspecs)} paths") from None + # an argument counts its bytes, its NUL and its pointer + alone = sum(len(os.fsencode(p)) + 1 + struct.calcsize("P") for p in pathspecs) + kind = PathsTooLong if alone > os.sysconf("SC_ARG_MAX") else ArgumentsTooLong + raise kind(f"git grep {shown}: {len(pathspecs)} paths") from None logger.warning("git grep did not start: %s", e) # the cause, for the operator raise GitError(f"git grep {shown} did not start") from None try: diff --git a/server/code/app/memory_links.py b/server/code/app/memory_links.py index 50d992d37ba..b60e50fad1f 100644 --- a/server/code/app/memory_links.py +++ b/server/code/app/memory_links.py @@ -40,6 +40,7 @@ # what `grep_lines` raises, for its caller to catch GrepTimedOut = gitrepo.GrepTimedOut +PathsTooLong = gitrepo.PathsTooLong def trunk_namespace(org: str, namespace: str) -> str: @@ -186,7 +187,8 @@ async def grep_lines( """Up to `limit` of `paths` whose text at `commit` holds one of `lines` as written. None when git cannot tell, and for arguments too long to pass to git: no index answers for a line, so a search cut short found nothing out. One git does not finish - in its time raises `GrepTimedOut`: the same paths take as long for any lines.""" + in its time raises `GrepTimedOut`, and one whose `paths` alone are too long to pass + raises `PathsTooLong`: the same paths fail the same way for any lines.""" return await _grep(scope, commit, list(lines), paths, limit=limit, word=False) @@ -220,7 +222,7 @@ async def _grep( scope.cfg.namespace, type(e).__name__, ) - if not word and isinstance(e, GrepTimedOut): + if not word and isinstance(e, (GrepTimedOut, PathsTooLong)): raise return [] if word else None except gitrepo.GitError: diff --git a/server/memory/app/code_link_pass.py b/server/memory/app/code_link_pass.py index f20ec73c744..0192e92210c 100644 --- a/server/memory/app/code_link_pass.py +++ b/server/memory/app/code_link_pass.py @@ -396,8 +396,9 @@ async def _holding( info, for each definition; - a search git cannot run: info, for each definition, and a warning from `memory_links._grep` when its arguments were too long; - - a search git does not finish in its time: that warning and the info line, once - a range, as the search is not made again over this range.""" + - a search git does not finish in its time, or cannot run for the paths alone: + that warning and the info line, once a range, as the search is not made again + over this range.""" if len(paths) > settings.memory_code_links_mirror_changed_files: if ("too wide", base, head) not in self._read: self._read["too wide", base, head] = True @@ -411,7 +412,7 @@ async def _holding( self.cns, ) return None - if ("unfinished", base, head) in self._read: + if ("unsearchable", base, head) in self._read: return None # found out, and logged, for another definition: not again held: set[str] = set() why = "" if lines else "it has no line of its own" @@ -421,11 +422,12 @@ async def _holding( # one past the bound: a cut list is never taken as whole try: found = await code.grep_lines(scope, commit, lines, takes, limit=limit + 1) - except code.GrepTimedOut: + except (code.GrepTimedOut, code.PathsTooLong): # the paths are the same for every definition of the range: the next - # one's search would wait as long. A search git cannot run may fail on - # these lines alone (each is an argument), so the next one's is made - self._read["unfinished", base, head] = True + # one's search would wait as long, or fail as this one did. Any other + # search git cannot run may fail on these lines alone (each is an + # argument), so the next one's is made + self._read["unsearchable", base, head] = True found = None if found is None or len(found) > limit: why = "git cannot search them" if found is None else "its lines are in too many" diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index 27fefa94df5..bf47446a88c 100644 --- a/tests/unit/test_memory_code_links.py +++ b/tests/unit/test_memory_code_links.py @@ -9,6 +9,7 @@ import json import logging import re +import struct import subprocess from collections.abc import Callable from datetime import datetime @@ -5440,8 +5441,17 @@ async def cannot_start(*a, **k): monkeypatch.setattr(gitrepo.asyncio, "create_subprocess_exec", cannot_start) with pytest.raises(gitrepo.GitError) as raised: await gitrepo.grep_paths("/nowhere", "a" * 40, "f", ("x.py",)) - # E2BIG is the paths being too many, which leaves the index's verdict - assert isinstance(raised.value, gitrepo.ArgumentsTooLong) == (errno_ == errno.E2BIG) + # E2BIG is the arguments being too long, which leaves the index's verdict; one + # short path is not what made them so + assert (type(raised.value) is gitrepo.ArgumentsTooLong) == (errno_ == errno.E2BIG) + # paths that alone are past the system's limit are: each counts its four bytes, its + # NUL and its pointer + alone = 2 * (4 + 1 + struct.calcsize("P")) + for limit, kind in ((alone, gitrepo.ArgumentsTooLong), (alone - 1, gitrepo.PathsTooLong)): + monkeypatch.setattr(gitrepo.os, "sysconf", lambda name, n=limit: {"SC_ARG_MAX": n}[name]) + with pytest.raises(gitrepo.GitError) as raised: + await gitrepo.grep_paths("/nowhere", "a" * 40, "f", ("x.py", "y.py")) + assert (type(raised.value) is kind) == (errno_ == errno.E2BIG) # lines of source are counted, never quoted: one may hold a literal with pytest.raises(gitrepo.GitError) as raised: await gitrepo.grep_paths("/nowhere", "a" * 40, ['key = "s3cret"', "x = 1"], ("x.py",)) @@ -5460,23 +5470,28 @@ async def test_the_mirror_is_searched_for_a_name_without_its_ordinal(monkeypatch @pytest.mark.asyncio -@pytest.mark.parametrize("why", ["too-many-arguments", "timed-out"]) +@pytest.mark.parametrize("why", ["too-many-arguments", "paths-too-long", "timed-out"]) async def test_paths_too_many_for_git_leave_the_index_verdict(monkeypatch, why) -> None: from server.code.app import memory_links from server.code.app.index import gitrepo + cut = { + "too-many-arguments": gitrepo.ArgumentsTooLong, + "paths-too-long": gitrepo.PathsTooLong, + "timed-out": gitrepo.GrepTimedOut, + }[why] + async def too_many(*a, **k): - raise (gitrepo.ArgumentsTooLong if why == "too-many-arguments" else gitrepo.GrepTimedOut)( - "many paths" - ) + raise cut("many paths") monkeypatch.setattr(gitrepo, "grep_paths", too_many) scope = SimpleNamespace(cfg=SimpleNamespace(git_dir="/nowhere", namespace="code-a")) assert await memory_links.grep_words(scope, "c1", "f", ["a.py"], limit=5) == [] # no index answers for a line: a search cut short found nothing out. A timeout is - # the paths', and is raised for the caller to stop searching them - if why == "timed-out": - with pytest.raises(memory_links.GrepTimedOut): + # the paths', as are paths too long alone, and each is raised for the caller to stop + # searching them + if why != "too-many-arguments": + with pytest.raises(cut): await memory_links.grep_lines(scope, "c1", ["f(x)"], ["a.py"], limit=5) else: assert await memory_links.grep_lines(scope, "c1", ["f(x)"], ["a.py"], limit=5) is None @@ -5966,6 +5981,43 @@ async def ingest_scope(org, cns, commit): ] +@pytest.mark.asyncio +async def test_a_line_search_git_cannot_run_for_the_paths_alone_is_made_once_over_the_range( + monkeypatch, caplog +) -> None: + # the paths are the same for every lost definition of a range: where they alone are + # past what the system takes as arguments, the second one's search fails as the first + from server.code.app.index import gitrepo + + commits = _wide({("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, ("c1", "pkg/a.py"): _KEEP}) + files, _ = _renaming_world(monkeypatch, commits) + started = [] + + async def cannot_start(*argv, **kw): + started.append(argv[argv.index("-e") + 1]) + raise OSError(errno.E2BIG, "Argument list too long") + + async def ingest_scope(org, cns, commit): + cfg = SimpleNamespace(git_dir="/nowhere", namespace="code-a") + return SimpleNamespace(under=lambda path: True, takes=lambda path: True, cfg=cfg) + + monkeypatch.setattr(gitrepo.asyncio, "create_subprocess_exec", cannot_start) + monkeypatch.setattr(gitrepo.os, "sysconf", lambda name: {"SC_ARG_MAX": 64}[name]) + monkeypatch.setattr(code_links.code, "ingest_scope", ingest_scope) + monkeypatch.setattr(code_links.code, "grep_lines", _REAL_GREP_LINES) + with caplog.at_level(logging.INFO, logger=code_link_pass.log.name): + for line in ("a line of one definition", "a line of another"): + assert await files.turnover_holding("c0", "c1", [line], "pkg/a.py", limit=2) is None + assert started == ["a line of one definition"] + # said once for the range, not for each definition + assert [r.getMessage() for r in caplog.records] == [ + "memory links: mirror search for 1 of its lines over 4 paths of code-a cut short: " + "PathsTooLong", + "memory links: a definition not searched for across the 4 files changed in " + "c0..c1 of code-a: git cannot search them", + ] + + @pytest.mark.asyncio async def test_a_range_is_read_whole_or_not_by_the_limit_it_is_asked_with(monkeypatch) -> None: # five files changed: too wide under a limit of two, read whole under a limit of