diff --git a/.env.example b/.env.example index 28ed3b2efe5..721692e4b59 100644 --- a/.env.example +++ b/.env.example @@ -204,8 +204,6 @@ OPENAI_API_KEY= # LOOM_CODE_GITHUB_TOKEN= # private clones and PR history; empty = public clones, no PR sync # The stock single-node stack enables the non-LLM indexing workers so repositories # added in the dashboard make progress without a second setup step. -# Per-merge fast tier (tree-sitter + embeddings). -LOOM_CODE_INGEST_ENABLED=true # LOOM_CODE_PR_HISTORY_ENABLED=true # merged-PR sync (needs the GitHub token) # Re-embed code rows whose embedding failed. LOOM_CODE_EMBED_RECOVERY_ENABLED=true diff --git a/deploy/standalone/env.example b/deploy/standalone/env.example index 2fd1b812db0..4a2695cc32a 100644 --- a/deploy/standalone/env.example +++ b/deploy/standalone/env.example @@ -60,7 +60,6 @@ OPENAI_API_KEY= # C/C++ compiler indexing needs a project compilation database and scip-clang; # these are repository build prerequisites, not additional running services. # LOOM_CODE_REPOS_JSON=[{"org":"dev","namespace":"code-myrepo","repo":"acme/myrepo","git_branch":"main","public":true}] -LOOM_CODE_INGEST_ENABLED=true LOOM_CODE_EMBED_RECOVERY_ENABLED=true LOOM_CODE_GRAPH_STATS_ENABLED=true LOOM_CODE_SCIP_DELTA_ENABLED=true diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index d837ea3c252..205e16b6976 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -530,23 +530,22 @@ link comes back only when its own name does. A definition moved to another file own name with an edit is followed there when its text is close to the one the link last read. A new definition left where it was stops that search only when it may be the old one under a new name: an export list or an unrelated function added beside it does not. A -name gone from its file is -looked for in the files changed -since its last check as the mirror holds them, beside the index, so a definition moved by -a commit the index has not taken in whole (past `code_ingest_max_files_per_commit`) is -followed when the link is rechecked. When `memory_code_links_mirror_naming_files` or more -of those files name it, or more than `memory_code_links_mirror_changed_files` changed -under the entry's prefixes, or the diff cannot be read, or the paths are more than git -takes in one command or searches in its time, the mirror adds nothing and the index -decides. When git cannot run the search, or a definition it finds cannot be -fingerprinted, a live link the index's namesakes do not settle is `unresolved`. Files the -ingest would not index (outside the entry's `path_prefixes`, refused by its denylist, -over the byte cap, binary) add no definition; a generated file, which the ingest declares -without searching its text, does. A file the parser fails on keeps its links as they were -until it parses. When the fingerprint rules change, every link is re-hashed from the -commits its hashes were taken at. When its old text is gone from git, a link that matched -it takes the text the next check finds and a changed one stays `changed`; one whose old -text no longer parses keeps its last state, and the worker reports it. +name gone from its file is looked for in the files changed since its last check as the +mirror holds them, beside the index, so a definition moved by a commit the index has not +taken in whole (past `code_ingest_max_files_per_commit`) is followed when the link is +rechecked. When `memory_code_links_mirror_naming_files` or more of those files name it, +or more than `memory_code_links_mirror_changed_files` changed under the entry's prefixes, +or the diff cannot be read, or the paths are more than git takes in one command or +searches in its time, the mirror adds nothing and the index decides. When git cannot run +the search, or a definition it finds cannot be fingerprinted, a live link the index's +namesakes do not settle is `unresolved`. Files the ingest would not index (outside the +entry's `path_prefixes`, refused by its denylist, over the byte cap, binary) add no +definition; a generated file, which the ingest declares without searching its text, does. +A file the parser fails on keeps its links as they were until it parses. When the +fingerprint rules change, every link is re-hashed from the commits its hashes were taken +at. When its old text is gone from git, a link that matched it takes the text the next +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 @@ -643,10 +642,11 @@ The links are read where the code is: commit that put its code in a changed, unresolved or missing state) when one is known, and `supersedes_key` when it replaces an older row, and `code_moved` (its links to code in the file that is now at another path or symbol than it was written against) when there are - any; a row another row read for the answer supersedes is not served. `lessons_left_out` counts the rows the cap, a cut or that rule left - out. A decision or constraint is served whole or left out. The read runs after the answer, - never enters the search memo, and is skipped for `include_lessons: false`, with - `code_result_lessons` off, or for a token narrowed to its own user or session. + any; a row another row read for the answer supersedes is not served. `lessons_left_out` + counts the rows the cap, a cut or that rule left out. A decision or constraint is served + whole or left out. The read runs after the answer, never enters the search memo, and is + skipped for `include_lessons: false`, with `code_result_lessons` off, or for a token + narrowed to its own user or session. - `code.grep` in matches mode focuses inline lessons on the definitions its matches name in trunk files. When selecting files to read, grep prefers files with a current lesson linked to a matched definition at the returned @@ -721,9 +721,9 @@ counts the served memories that name code (a backticked or qualified name, a cal | `code_unlinked_name_unresolved` | lists no `files`, and each name is defined nowhere on trunk or more than once. | | `code_unlinked_pending` | waits for its link; each sample says what it `waits_for`: `link_pass` (the worker has not read this write), `index` (no index yet, or a file that does not parse) or `trunk` (a qualified name trunk does not define yet). | -The counts are of the 2,000 served memories last written (all under `keys` when given), -and only in an org that indexes a repository; a raw tool observation, which is never -linked, is not counted. How far each repository's links trail its +The counts are of the 2,000 served memories last written (of those under `keys` when +given), and only in an org that indexes a repository; a raw tool observation, which is +never linked, is not counted. How far each repository's links trail its index is a gauge, and a health warning when it lasts ([monitoring](../operations/monitoring.md#what-to-alert-on)). @@ -820,9 +820,9 @@ says. A sentence ends after `.`, `!` or `?` and a space (not after a one-letter 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 (all -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 +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. diff --git a/docs/features/memory/extraction.md b/docs/features/memory/extraction.md index 4508a92e5fe..90d828b132e 100644 --- a/docs/features/memory/extraction.md +++ b/docs/features/memory/extraction.md @@ -85,17 +85,20 @@ The rules in `server/memory/domain/durable_facts.py` match sentence shape, not t 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 about 2,700 tokens -where the conversation prompt is 20,000 to 34,000, 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 day. The extractor sets no `valid_at`, -`temporal_confidence`, occurrence record or `question_topic` on a session capture's fact; -the row takes its `valid_at` from the fact's `temporal_anchor` when that is not in the -future, else from the observation date. From the work, only knowledge about the codebase -that a later session in the repository can reuse without reading the code again is kept: +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 +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 +day. The prompt asks for no `valid_at`, `temporal_confidence`, occurrence record or +`question_topic` on a session capture's fact. The row takes its `valid_at` from the time +of the latest turn the fact cites, when the capture's messages carry a `timestamp` and the +fact's `temporal_anchor` names no other day or time of day; else from the call's own +`valid_at`; else from the fact's `temporal_anchor` when that is not in the future; else +from the observation date. From the work, only knowledge about the codebase that a later +session in the repository can reuse without reading the code again is kept: - how a behaviour is reached across definitions or files, as one claim for the whole path; - a relation between definitions that reading one of them does not show; diff --git a/server/code/domain/units.py b/server/code/domain/units.py index dd5ded7da95..a9bc359222d 100644 --- a/server/code/domain/units.py +++ b/server/code/domain/units.py @@ -113,22 +113,12 @@ def estimate_unit_tokens(unit: CodeUnit, *, body: str | None = None) -> int: } ) -# Every served unit says which leg found it. `via` is one of VIA_VALUES: a content leg -# or both, the symbol route, or the other leg that proposed a unit neither content leg -# found. The ranks are 1-based positions inside the leg's pool before fusion (0 = the -# leg did not return this chunk). Computed from the leg results BEFORE the fusion priors -# reorder anything, so they answer "what did each leg say", not "where did it end up". -VIA_VALUES: tuple[str, ...] = ( - "lexical", - "vector", - "both", - "symbol", - "definition", - "history", - "card", - "concept", - "hyde", -) +# Every served unit says which leg found it. `via` names a content leg or both +# (`lexical`, `vector`, `both`), the symbol route, or the other leg that proposed a unit +# neither content leg found. The ranks are 1-based positions inside the leg's pool before +# fusion (0 = the leg did not return this chunk). Computed from the leg results BEFORE the +# fusion priors reorder anything, so they answer "what did each leg say", not "where did +# it end up". _DEFAULT_GRANULARITY = "unit" diff --git a/server/identity/app/namespace_validate.py b/server/identity/app/namespace_validate.py index 5b39b54c557..a4d2bfe7c88 100644 --- a/server/identity/app/namespace_validate.py +++ b/server/identity/app/namespace_validate.py @@ -326,8 +326,8 @@ # What every `code_unlinked_*` check reads (`code_unlinked.unlinked`). _UNLINKED_READ = ( - f"Only the {code_unlinked.SCANNED} served memories last written are read (all under " - "`keys` when given), and only in an org that indexes a repository. A raw tool " + f"Only the {code_unlinked.SCANNED} served memories last written are read (of those " + "under `keys` when given), and only in an org that indexes a repository. A raw tool " "observation is never linked and is not read; a word of the prose counts as a name " "only beside `files`." ) @@ -409,7 +409,7 @@ 1, exceptions=( f"Only the {code_unlinked.SCANNED} memories whose `moved` link was last checked " - "are read (all under `keys` when given), only in repositories the caller may " + "are read (of those under `keys` when given), only in repositories the caller may " "read, and no high-sensitivity memory. A link whose code also changed is " "`code_links_stale`'s." ), @@ -448,7 +448,9 @@ exceptions=_UNLINKED_READ, uncertainty=( "While the link pass backfills earlier writes, a memory it has not reached is " - "counted here even when nothing of it will resolve." + "counted here even when nothing of it will resolve. A write queued after the " + "pass's position with an earlier write time (an insert in flight, a writer " + "clock behind ClickHouse's) is counted under its cause until the next pass." ), ), } diff --git a/server/memory/app/code_link_pass.py b/server/memory/app/code_link_pass.py index f2a9f96e8fc..663b574aa9d 100644 --- a/server/memory/app/code_link_pass.py +++ b/server/memory/app/code_link_pass.py @@ -276,8 +276,9 @@ async def touched(self, base: str, head: str) -> set[str] | None: async def turnover(self, base: str, head: str, *, limit: int) -> Turnover | None: """The definitions `base..head` brought in and took out of the files it changed, those the ingest would not index left out, a renamed file read as one. None when - the range cannot be read (a force-push, a diff git fails on), or changed more - than `limit` files under the entry's prefixes: counted in `wide_ranges`, and + the range cannot be read (a force-push, a diff git fails on), when no repository + indexes the namespace, or when the range changed more than `limit` files under + the entry's prefixes: only that last case is counted in `wide_ranges`, and it is read only where a definition's lines are (`turnover_holding`).""" async def read() -> Turnover | None: @@ -289,7 +290,7 @@ async def read() -> Turnover | None: return None return await self._read_turnover(paths[0], base, head, paths[1]) - return await self._once(("turnover", base, head), read) + return await self._once(("turnover", base, head, limit), read) async def turnover_holding( self, base: str, head: str, lines: Sequence[str], path: str, *, limit: int diff --git a/server/memory/app/code_link_rehash.py b/server/memory/app/code_link_rehash.py index fe738c49212..21cd8e25515 100644 --- a/server/memory/app/code_link_rehash.py +++ b/server/memory/app/code_link_rehash.py @@ -133,10 +133,10 @@ async def cited_at(commit: str, path: str) -> str | None: first = written or await cited_at(a["baseline_commit"], a["baseline_path"]) or "" read = await cited_at(a["checked_commit"], link.path) checked = read or "" - took = not first and link.matched_baseline() - baseline = first or (checked if took else NO_BASELINE) + adopts_checked = not first and link.matched_baseline() + baseline = first or (checked if adopts_checked else NO_BASELINE) out = {"anchored_hash": written, "body_hash": baseline, "checked_hash": checked} - if took and checked: + if adopts_checked and checked: # the next re-hash reads the baseline where this one took it out |= {"baseline_commit": a["checked_commit"], "baseline_path": link.path} # a file that is gone stays gone; lines that cannot be read show no change diff --git a/server/memory/app/code_unlinked.py b/server/memory/app/code_unlinked.py index 215671eb894..921016dd19f 100644 --- a/server/memory/app/code_unlinked.py +++ b/server/memory/app/code_unlinked.py @@ -9,6 +9,7 @@ from __future__ import annotations +import asyncio from collections import defaultdict from collections.abc import Sequence from typing import Any @@ -64,7 +65,9 @@ async def read(cls) -> _Pass: def has_read(self, org: str, memory: dict[str, Any]) -> bool: """The pass read `memory` as it is now: written before the queue position and, while the backfill runs, at or before the identity it has reached. A version is - the write's wall-clock time in ns.""" + the write's wall-clock time in ns, and the position is ClickHouse's time at the + queue insert: a write queued after the position with an earlier version (an + insert in flight, a writer clock behind) reads as read until the next pass.""" if not self.read_to or int(memory["version"]) // 1000 > self.read_to: return False ident = (org, *(str(memory[c]) for c in IDENTITY[1:])) @@ -79,18 +82,16 @@ async def unlinked( read), the last written first: each with its memory_key and memory_id and, under `pending`, what it `waits_for` (`index`: its repository's first index or a file that does not parse; `trunk`: a qualified name trunk does not define - yet; `link_pass`: the pass to read it). Read of the memories under `keys` when given, - of the `SCANNED` last written otherwise. A memory whose repository the caller may not + yet; `link_pass`: the pass to read it). Read of the `SCANNED` last written, among + those under `keys` when given. A memory whose repository the caller may not read counts as naming none: its cause must not tell what that repository holds. Nothing is read, and nothing counted, in an org that indexes no repository.""" out: dict[str, list[dict[str, str]]] = {cause: [] for cause in CAUSES} if not any(cfg.org == org for cfg in configured_repos()): return out # the org indexes no repository: no memory of it could be linked - heads = [ - h - for h in await store.linkable_of_namespace(org, namespace, keys, limit=SCANNED) - if _names_code(h) - ] + linkable = await store.linkable_of_namespace(org, namespace, keys, limit=SCANNED) + # reading names is CPU work: off the loop + heads = await asyncio.to_thread(lambda: [h for h in linkable if _names_code(h)]) if not heads: return out named = {h["mid"]: code_namespace_for(org, namespace, list(h.get("tags") or [])) for h in heads} diff --git a/server/memory/app/extract/prompts.py b/server/memory/app/extract/prompts.py index e1598558b45..49ae9f51a69 100644 --- a/server/memory/app/extract/prompts.py +++ b/server/memory/app/extract/prompts.py @@ -32,8 +32,9 @@ def _extraction_base_prompt( compact: bool, *, agent_learnings: bool = False, coding_session: bool = False ) -> str: """The extraction system prompt before the preamble: a coding session's own - prompt at every input size, else the full or the compact examples plus the - flag-gated blocks.""" + prompt at every input size, which takes no flag-gated block (`agent_learnings` + is not read for it), else the full or the compact examples plus the flag-gated + blocks.""" if coding_session: return _CODING_SESSION_SYSTEM_PROMPT base_prompt = ( diff --git a/server/memory/app/pipeline.py b/server/memory/app/pipeline.py index d2346dbad2b..2e67d11c255 100644 --- a/server/memory/app/pipeline.py +++ b/server/memory/app/pipeline.py @@ -704,9 +704,10 @@ async def _stored_neighbours(state: WorkflowState, facts: list[dict[str, Any]]) earlier session may already have stored of this capture's claims. One `embed_many` call for the capture, and the reads bounded like the conflict checks of the write that follows. None for a fact that carries `valid_at`, `valid_to` or `foresight`: - the verifier compares text and sees no validity. None under `append_only`, where - every write is its own event, or under a policy that could not be read. Fail-open: - with none, no fact is dropped as already stored.""" + the verifier compares text and sees no validity. The call's own `valid_at` default + is not read: a fact that takes its start from it is still compared. None under + `append_only`, where every write is its own event, or under a policy that could not + be read. Fail-open: with none, no fact is dropped as already stored.""" import server.memory.store as memory_repo from server.embedding import get_embedder from server.memory.app.handlers import nearest_existing_rows diff --git a/server/memory/domain/code_change.py b/server/memory/domain/code_change.py index 201d118928b..274afb447b2 100644 --- a/server/memory/domain/code_change.py +++ b/server/memory/domain/code_change.py @@ -110,9 +110,13 @@ def relocation(link: Mapping[str, Any]) -> tuple[str, str] | None: _NAME_CHARS = 120 +def _value(link: Any, name: str) -> Any: + return link.get(name) if isinstance(link, Mapping) else getattr(link, name, None) + + def _field(link: Any, name: str) -> str: - value = link.get(name) if isinstance(link, Mapping) else getattr(link, name, None) - text = " ".join(str(value or "").replace("`", "'").split()) + """A path or name of `link` as one line of a note.""" + text = " ".join(str(_value(link, name) or "").replace("`", "'").split()) return text if len(text) <= _NAME_CHARS else text[: _NAME_CHARS - 1] + "…" @@ -122,7 +126,7 @@ def _now(link: Any) -> str: path, symbol, was = _field(link, "path"), _field(link, "symbol"), _field(link, "was_symbol") if not symbol: return f"`{_field(link, 'was_path')}` is now `{path}`" - start, end = int(_field(link, "start_line") or 0), int(_field(link, "end_line") or 0) + start, end = int(_value(link, "start_line") or 0), int(_value(link, "end_line") or 0) lines = f":{start}-{end}" if 0 < start <= end else "" name = f"`{symbol}` " if symbol != was else "" return f"`{was}` is now {name}at {path}{lines}" diff --git a/server/observability/otel_probes.py b/server/observability/otel_probes.py index 61889bad4c3..996947a8d6c 100644 --- a/server/observability/otel_probes.py +++ b/server/observability/otel_probes.py @@ -780,9 +780,10 @@ def _probe_code_state() -> dict[str, list[tuple[float, dict[str, str]]]]: client = _probe_client() rows = list(client.query(_CODE_STATE_SQL).result_rows) # The FINAL counts over the four code tables read every live code row (GBs a call on - # a large deployment) for figures that move once an index run; the watermark rows - # above cost nothing. So the counts refresh on their own, slower clock: - # LOOM_OTEL_CODE_COUNTS_CACHE_S, default an hour, 0 = every call. + # a large deployment) for figures that move once an index run. The statement above + # reads the small state table and, of every link row, only its repository. So the + # counts refresh on their own, slower clock: LOOM_OTEL_CODE_COUNTS_CACHE_S, default + # an hour, 0 = every call. ttl = float(settings.otel_code_counts_cache_s) now_m = time.monotonic() never = float(_CODE_COUNTS_CACHE["at"]) <= 0.0 # monotonic() may be < ttl after boot diff --git a/tests/unit/test_coding_session_extraction.py b/tests/unit/test_coding_session_extraction.py index ed0db1b6cb8..82492b92d45 100644 --- a/tests/unit/test_coding_session_extraction.py +++ b/tests/unit/test_coding_session_extraction.py @@ -42,12 +42,12 @@ def system_prompt(existing: list[dict[str, str]] | None) -> str: existing_memories=existing, namespace_categories=None, custom_instructions="", - agent_learnings=True, + agent_learnings=True, # not read for a coding session coding_session=True, ) prompt = system_prompt(None) - # No conversation rule or example and no examples preamble. + # 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. diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index 6fc9e61c46c..5bda149bbc7 100644 --- a/tests/unit/test_memory_code_links.py +++ b/tests/unit/test_memory_code_links.py @@ -2920,7 +2920,7 @@ async def candidates(org, cns, *, names=None, qualified_names=None): "fresh", [("unresolved", "pkg/a.py", "pkg.a::fetch_rows")], ), - # deleted beside the export list, its name nowhere else: unsure, as before + # deleted beside an added export list, its name nowhere else: unsure, not removed (_EXPORTS, {}, "fresh", [("unresolved", "pkg/a.py", "pkg.a::fetch_rows")]), # its name is new in another module over an unrelated text: unsure ( diff --git a/tests/unit/test_memory_code_staleness.py b/tests/unit/test_memory_code_staleness.py index 8fabcc75e3b..7283c876126 100644 --- a/tests/unit/test_memory_code_staleness.py +++ b/tests/unit/test_memory_code_staleness.py @@ -108,6 +108,25 @@ async def test_a_rename_within_its_file_names_the_old_and_the_new_symbol(monkeyp ) +@pytest.mark.asyncio +async def test_a_module_prefix_that_follows_its_file_reads_as_a_rename(monkeypatch) -> None: + moved = _link( + "m1", + "moved", + qn="loader::fetch_rows", + path="loader.py", + prev="reader.py", + prev_qn="reader::fetch_rows", + ) + _links(monkeypatch, [_head("m1")], [moved]) + note = await ma._annotate_stale_code_memories([_mem("m1")], _IN) + assert note is not None + assert ( + "[m1]: `reader::fetch_rows` is now `loader::fetch_rows` at loader.py" + in note.content_excerpt + ) + + @pytest.mark.asyncio async def test_two_renames_name_what_the_memory_was_written_against(monkeypatch) -> None: renamed = _link("m1", "moved", qn="n::retrieve_rows", path="src/n.py", prev="src/m.py")