diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index d43ef63ce3b..b9f0aacf60b 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -651,6 +651,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 @@ -670,15 +676,22 @@ 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 -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 -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/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 205e16b6976..9d5ac9f1f05 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -514,9 +514,11 @@ 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, 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 @@ -547,18 +549,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 @@ -751,13 +752,16 @@ 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 -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`. +`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`. 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 @@ -780,10 +784,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 @@ -815,16 +821,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 diff --git a/docs/features/memory/extraction.md b/docs/features/memory/extraction.md index 62cc406f491..bf5473cc0f7 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. A session that made a tested change is sent about 1,200 characters more (the +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. A +session that made a tested change is sent about 1,200 characters more (the [fix record](#the-fix-record) rules). 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 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` diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index 8990ea9eaf1..d1114ec5639 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/cli/code_backfill.py b/server/cli/code_backfill.py index be5ed94cd72..e0295906150 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 "" @@ -722,7 +723,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", @@ -852,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 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]]] = {} 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. diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index ecdfaed1cf9..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.""" @@ -401,7 +406,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", @@ -424,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/index/round_reads.py b/server/code/app/index/round_reads.py index d3b9f8be9a4..510eab24209 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 @@ -41,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 @@ -196,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 ( @@ -374,17 +378,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 @@ -396,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/server/code/app/memory_links.py b/server/code/app/memory_links.py index d742156e8f5..b60e50fad1f 100644 --- a/server/code/app/memory_links.py +++ b/server/code/app/memory_links.py @@ -38,6 +38,10 @@ log = logging.getLogger(__name__) +# what `grep_lines` raises, for its caller to catch +GrepTimedOut = gitrepo.GrepTimedOut +PathsTooLong = gitrepo.PathsTooLong + def trunk_namespace(org: str, namespace: str) -> str: """The repository's trunk code namespace for any of its branch namespaces; '' when @@ -181,8 +185,10 @@ 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`, 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) @@ -216,6 +222,8 @@ async def _grep( scope.cfg.namespace, type(e).__name__, ) + if not word and isinstance(e, (GrepTimedOut, PathsTooLong)): + raise return [] if word else None except gitrepo.GitError: return None diff --git a/server/code/app/search/calibrate.py b/server/code/app/search/calibrate.py index 766ada7787b..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 "") @@ -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/code/app/search/priors.py b/server/code/app/search/priors.py index 311252fb442..25a0c972c08 100644 --- a/server/code/app/search/priors.py +++ b/server/code/app/search/priors.py @@ -205,14 +205,18 @@ 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 -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.""" - 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] @@ -221,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( @@ -245,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) 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/server/code/domain/successor.py b/server/code/domain/successor.py index ce328782c49..4d8e6acc3f9 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,13 +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.""" + """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 not name.search(line)] - return sorted(told, key=lambda line: (-len(line), line))[:_LINES] + told = [ + line + for line in lines + 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))[:_OWN_LINES] def _scope_of(d: Definition) -> str: @@ -235,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) diff --git a/server/code/store/index/search.py b/server/code/store/index/search.py index 440e079f837..22a454c3a18 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): @@ -77,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, @@ -104,7 +111,6 @@ async def lexical_search_chunks( **scope_params, }, ) - return rows async def definition_chunks( self, diff --git a/server/memory/app/code_link_pass.py b/server/memory/app/code_link_pass.py index 663b574aa9d..0192e92210c 100644 --- a/server/memory/app/code_link_pass.py +++ b/server/memory/app/code_link_pass.py @@ -387,11 +387,18 @@ 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), 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.""" + 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, 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 @@ -405,19 +412,23 @@ 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)) # 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, code.PathsTooLong): # the paths are the same for every definition of the range: the next - # one's search would wait as long + # 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" break 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 diff --git a/server/memory/app/code_renames.py b/server/memory/app/code_renames.py index 24a3f669571..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 @@ -38,6 +39,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 +48,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. @@ -91,10 +94,12 @@ 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, 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)) @@ -121,8 +126,10 @@ 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 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/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 "" 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/server/memory/store/key_write_lock.py b/server/memory/store/key_write_lock.py index e0fb4054043..d4af13eba78 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() @@ -177,6 +181,7 @@ async def key_lock_for( __all__ = [ + "KeyBusy", "KeyWriteLocks", "LeaseBusy", "LeaseLost", 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 af79175a881..f08e510bdc1 100644 --- a/server/transport/mcp_primer.py +++ b/server/transport/mcp_primer.py @@ -562,7 +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. + 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 @@ -572,7 +573,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) @@ -602,6 +604,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 at `initialize`.""" + 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/server/transport/mcp_schemas.py b/server/transport/mcp_schemas.py index f678c71de82..ed14a492590 100644 --- a/server/transport/mcp_schemas.py +++ b/server/transport/mcp_schemas.py @@ -421,11 +421,16 @@ 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.""" - if str(requested or "").lower() != PLUGIN_SCHEMA_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. 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 "").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_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" 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)) diff --git a/tests/unit/test_code_round_reads_backfill_statements.py b/tests/unit/test_code_round_reads_backfill_statements.py index ef7c11279ba..8b5ca13a9d7 100644 --- a/tests/unit/test_code_round_reads_backfill_statements.py +++ b/tests/unit/test_code_round_reads_backfill_statements.py @@ -214,6 +214,96 @@ 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 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 + + +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} 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" 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 diff --git a/tests/unit/test_code_search_determinism.py b/tests/unit/test_code_search_determinism.py index 68c1eab8f6b..2ea69b64610 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 = [ @@ -272,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"}, 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 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)", + ] 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."}] 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_listing_budget.py b/tests/unit/test_mcp_listing_budget.py index bf5cbd9f016..413f9326da3 100644 --- a/tests/unit/test_mcp_listing_budget.py +++ b/tests/unit/test_mcp_listing_budget.py @@ -687,11 +687,19 @@ 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 + # 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") diff --git a/tests/unit/test_mcp_primer_order.py b/tests/unit/test_mcp_primer_order.py index 3ea82d1b69f..0cfcdc5e374 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( @@ -201,6 +201,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 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( + mcp_primer._initialize_instructions(object(), toolset, schema_profile=profile) + ) + + code = text("coding", "plugin-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 ( + ("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") diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index 5bda149bbc7..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,21 @@ 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",)) + assert "s3cret" not in str(raised.value) and "2 literals" in str(raised.value) @pytest.mark.asyncio @@ -5456,21 +5470,31 @@ 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 - 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', 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 @pytest.mark.asyncio @@ -5768,7 +5792,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: @@ -5785,9 +5811,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) @@ -5815,19 +5843,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" - ) - 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 + "its lines are in too many" if why == "too-many-hold-them" else "git cannot search them" ) + # 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-finish" else 2) @pytest.mark.asyncio @@ -5904,7 +5930,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"): @@ -5912,6 +5938,110 @@ 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_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 + # 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 = ( diff --git a/tests/unit/test_memory_code_rename_plan.py b/tests/unit/test_memory_code_rename_plan.py index 9950cb624b5..95e568f66b4 100644 --- a/tests/unit/test_memory_code_rename_plan.py +++ b/tests/unit/test_memory_code_rename_plan.py @@ -15,11 +15,13 @@ 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 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 +865,26 @@ 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_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, +) -> 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"] == [] 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)" 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)