From cebbc45075f729db1e3746caa5aac01d0f78ff03 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sat, 28 Nov 2026 18:36:05 +0530 Subject: [PATCH 1/4] The embed phase copies vectors from embed_reuse_from before it embeds Only the inline ingest looked up reusable vectors, so a branch namespace indexed with --phase index and embedded with --phase embed (or by code_embed_recovery) embedded every chunk. _embed_rows now copies the vector of every code chunk stub whose path, content hash and stored context text match a live, embedded chunk in the namespace's embed_reuse_from, and embeds only the rest. A switched-off org still gets its copied vectors; its other stubs stay as they are. Signed-off-by: Vanshaj Poonia --- server/code/workers/embed_recovery.py | 104 ++++++++++++-- .../test_code_embed_recovery_republishes.py | 1 + tests/unit/test_code_embed_recovery_reuse.py | 132 ++++++++++++++++++ 3 files changed, 224 insertions(+), 13 deletions(-) create mode 100644 tests/unit/test_code_embed_recovery_reuse.py diff --git a/server/code/workers/embed_recovery.py b/server/code/workers/embed_recovery.py index 7983db1f46d..f55892a8c2b 100644 --- a/server/code/workers/embed_recovery.py +++ b/server/code/workers/embed_recovery.py @@ -92,6 +92,8 @@ class CodeEmbedRecoveryResult: poisoned: int = 0 # Stubs left as they are: their org was switched off during the pass. switched_off: int = 0 + # Vectors copied from the namespace's `embed_reuse_from` instead of embedded. + reused: int = 0 rows_written: int = 0 scans: int = 0 keys_seen: int = 0 @@ -377,23 +379,14 @@ async def _embed_rows( set_worker_identity("code_embed_recovery", org=org, namespace=ns) pass_context.set_namespace(ns) batch = _batch() + source = _reuse_source(table, org, ns) for start in range(0, len(whole), batch): group = whole[start : start + batch] texts = [clip_for_embedding(text_of(r), count_tokens=counter) for r in group] - vectors: dict[int, list[float]] - try: - with customer.for_org(org, namespace=ns): - if not customer.names_one(): - vectors = {} - failures = dict.fromkeys(range(len(group)), customer.NO_CUSTOMER) - else: - vectors, failures = await _vectors_for(embedder, texts) - except customer.GROUP_HOLDS: - # Switched off since the pass began, or the identity refused, asked to - # wait or unread: its stubs stay as they are, no attempt spent, and - # are embedded later; the other groups' vectors are written. - result.switched_off += len(group) + staged = await _group_vectors(repo, org, ns, source, group, texts, embedder, result) + if staged is None: continue + group, vectors, failures = staged embedded += _stage_replacements( repo, table, group, vectors, failures, max_attempts, result, replacements ) @@ -407,6 +400,91 @@ async def _embed_rows( return embedded +def _reuse_source(table: str, org: str, ns: str) -> str: + """The namespace a code namespace copies identical chunk vectors from + (`embed_reuse_from`), or "" when none applies.""" + if table != "code_chunks": + return "" + from server.code.domain.index.repos import repo_for_namespace + + try: + cfg = repo_for_namespace(org, ns) + except Exception: # noqa: BLE001 - no readable repo config means nothing to reuse + return "" + src = cfg.embed_reuse_from.strip() if cfg else "" + return src if src and src != ns else "" + + +async def _reused_vectors( + repo: Any, org: str, source: str, group: list[dict[str, Any]] +) -> dict[int, list[float]]: + """`{index -> vector}` for the group's stubs whose path, content hash and stored + context text match a live, embedded chunk in `source`, one lookup per path.""" + from server.code.app.index.embed_reuse import reusable_vectors + + by_path: dict[tuple[str, str], list[int]] = {} + for i, r in enumerate(group): + if ( + r.get("path") + and r.get("content_hash") + and r.get("context_text") + and r.get("embedding_model") + ): + by_path.setdefault((str(r["path"]), str(r["embedding_model"])), []).append(i) + out: dict[int, list[float]] = {} + for (path, model), idx in by_path.items(): + found = await reusable_vectors( + repo, + org, + source, + embedding_model=model, + path=path, + content_hashes=[str(group[i]["content_hash"]) for i in idx], + context_texts=[str(group[i]["context_text"]) for i in idx], + ) + out.update({idx[j]: vec for j, vec in found.items()}) + return out + + +async def _group_vectors( + repo: Any, + org: str, + ns: str, + source: str, + group: list[dict[str, Any]], + texts: list[str], + embedder: Any, + result: CodeEmbedRecoveryResult, +) -> tuple[list[dict[str, Any]], dict[int, list[float]], dict[int, str]] | None: + """The rows of one embed call to write, with their vectors and failures: vectors + copied from `source` first, the rest embedded. None when the org is switched off + and nothing was copied, so its stubs stay as they are.""" + reused = await _reused_vectors(repo, org, source, group) if source else {} + result.reused += len(reused) + todo = [i for i in range(len(group)) if i not in reused] + vectors: dict[int, list[float]] = dict(reused) + failures: dict[int, str] = {} + if not todo: + return group, vectors, failures + try: + with customer.for_org(org, namespace=ns): + if not customer.names_one(): + failures = dict.fromkeys(todo, customer.NO_CUSTOMER) + else: + got, bad = await _vectors_for(embedder, [texts[i] for i in todo]) + vectors.update({todo[j]: vec for j, vec in got.items()}) + failures = {todo[j]: err for j, err in bad.items()} + except customer.GROUP_HOLDS: + # Switched off since the pass began, or the identity refused, asked to wait or + # unread: the stubs it would embed stay as they are, no attempt spent. + result.switched_off += len(todo) + if not reused: + return None + kept = sorted(reused) + return [group[i] for i in kept], {j: reused[i] for j, i in enumerate(kept)}, {} + return group, vectors, failures + + def _stage_replacements( repo: Any, table: str, diff --git a/tests/unit/test_code_embed_recovery_republishes.py b/tests/unit/test_code_embed_recovery_republishes.py index 75d7a4e121c..7c4428f56c8 100644 --- a/tests/unit/test_code_embed_recovery_republishes.py +++ b/tests/unit/test_code_embed_recovery_republishes.py @@ -167,6 +167,7 @@ def configured(monkeypatch: pytest.MonkeyPatch) -> list[Any]: class _Cfg: org, namespace = ORG, NS + embed_reuse_from = "" out: list[Any] = [_Cfg()] monkeypatch.setattr(repos_mod, "configured_repos", lambda: list(out)) diff --git a/tests/unit/test_code_embed_recovery_reuse.py b/tests/unit/test_code_embed_recovery_reuse.py new file mode 100644 index 00000000000..72d040cd56f --- /dev/null +++ b/tests/unit/test_code_embed_recovery_reuse.py @@ -0,0 +1,132 @@ +"""The embed phase copies vectors from a namespace's `embed_reuse_from` before it +embeds. A branch namespace indexed with `--phase index` and then embedded with +`--phase embed` reuses every chunk whose path, content hash and stored context +text match a live, embedded chunk in the source, and sends only the rest to the +embedder, as an inline (`--embed`) ingest already does.""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.code.domain.index import repos +from server.code.workers import embed_recovery as w +from server.llm import customer + +MODEL = "test-model" +SOURCE = [ + {"path": "a.py", "content_hash": "h1", "context_text": "a.py def f", "embedding": [1.0, 0.0]}, + {"path": "a.py", "content_hash": "h2", "context_text": "a.py def g", "embedding": [0.0, 1.0]}, +] + + +class _Repo: + def __init__(self) -> None: + self.lookups: list[tuple[str, str, str, list[str]]] = [] + self.written: list[dict[str, Any]] = [] + + async def embeddings_for_texts( + self, org: str, ns: str, *, embedding_model: str, path: str, content_hashes: list[str] + ) -> list[dict[str, Any]]: + self.lookups.append((ns, embedding_model, path, sorted(content_hashes))) + if ns != "code-main" or embedding_model != MODEL: + return [] + return [r for r in SOURCE if r["path"] == path and r["content_hash"] in content_hashes] + + def tombstone_of(self, table: str, live: dict[str, Any]) -> dict[str, Any]: + return dict(live) + + async def insert_rows(self, table: str, rows: list[Any]) -> None: + self.written = rows + + +class _Embedder: + def __init__(self) -> None: + self.sent: list[str] = [] + + async def embed_many(self, texts: list[str]) -> list[list[float]]: + self.sent.extend(texts) + return [[0.5, 0.5] for _ in texts] + + +def _stub(ns: str, content_hash: str, context_text: str) -> dict[str, Any]: + return { + "org": "acme", + "namespace": ns, + "path": "a.py", + "content_hash": content_hash, + "context_text": context_text, + "embedding_model": MODEL, + "embed_attempts": 0, + } + + +@pytest.fixture +def branch_reuses_main(monkeypatch: pytest.MonkeyPatch) -> None: + def _config(org: str, ns: str) -> Any: + return SimpleNamespace(embed_reuse_from="code-main") if ns == "code-rel" else None + + monkeypatch.setattr(repos, "repo_for_namespace", _config) + + +def _run( + repo: _Repo, rows: list[dict[str, Any]], emb: _Embedder +) -> tuple[int, w.CodeEmbedRecoveryResult]: + result = w.CodeEmbedRecoveryResult() + embedded = asyncio.run( + w._embed_rows( + repo, + "code_chunks", + rows, + emb, + text_of=lambda r: str(r["context_text"]), + max_attempts=5, + result=result, + ) + ) + return embedded, result + + +def test_identical_chunks_copy_the_source_vector_and_only_the_rest_embed( + branch_reuses_main, +) -> None: + repo, emb = _Repo(), _Embedder() + rows = [ + _stub("code-rel", "h1", "a.py def f"), + _stub("code-rel", "h2", "a.py def g"), + # Same content, different context text: the source vector does not apply. + _stub("code-rel", "h1", "a.py def f (edited summary)"), + ] + embedded, result = _run(repo, rows, emb) + assert embedded == 3 and result.reused == 2 + assert emb.sent == ["a.py def f (edited summary)"] + assert repo.lookups == [("code-main", MODEL, "a.py", ["h1", "h1", "h2"])] + assert [r["embedding"] for r in repo.written] == [[1.0, 0.0], [0.0, 1.0], [0.5, 0.5]] + assert all(r["embedding_dim"] == 2 for r in repo.written) + + +def test_a_namespace_without_embed_reuse_from_embeds_everything(branch_reuses_main) -> None: + repo, emb = _Repo(), _Embedder() + embedded, result = _run(repo, [_stub("code-main", "h1", "a.py def f")], emb) + assert embedded == 1 and result.reused == 0 + assert emb.sent == ["a.py def f"] and repo.lookups == [] + + +def test_a_switched_off_org_still_lands_the_copied_vectors( + branch_reuses_main, monkeypatch: pytest.MonkeyPatch +) -> None: + repo, emb = _Repo(), _Embedder() + + def _off() -> bool: + raise customer.GROUP_HOLDS[0]("model calls are off for this org") + + monkeypatch.setattr(customer, "names_one", _off) + rows = [_stub("code-rel", "h1", "a.py def f"), _stub("code-rel", "h3", "a.py def h")] + embedded, result = _run(repo, rows, emb) + assert embedded == 1 and result.reused == 1 and result.switched_off == 1 + assert emb.sent == [] + # The stub that needed the embedder is left as it was: no attempt spent. + assert [r["content_hash"] for r in repo.written] == ["h1"] From aabdc27d1d149c939077e37dcda4b124397b0cc3 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sat, 28 Nov 2026 18:36:05 +0530 Subject: [PATCH 2/4] The backfill embed phase reports how many vectors it reused Signed-off-by: Vanshaj Poonia --- server/cli/code_backfill.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/server/cli/code_backfill.py b/server/cli/code_backfill.py index 83bbec99060..c74c6fc7067 100644 --- a/server/cli/code_backfill.py +++ b/server/cli/code_backfill.py @@ -867,7 +867,13 @@ async def _backfill_embed(repo: Any, org: str, ns: str, args: argparse.Namespace declared = False async def _finish(code: int) -> int: - _note(phase="embed", embedded=total, failed=result.failed, poisoned=result.poisoned) + _note( + phase="embed", + embedded=total, + reused=result.reused, + failed=result.failed, + poisoned=result.poisoned, + ) await _compact_after_bulk(total, embedder.model_name) if declared: await _republish_counts(repo, org, ns) @@ -879,7 +885,12 @@ async def _finish(code: int) -> int: done=total, rows_written=total, errors=result.failed, - counters={"embedded": total, "failed": result.failed, "poisoned": result.poisoned}, + counters={ + "embedded": total, + "embed_reused": result.reused, + "failed": result.failed, + "poisoned": result.poisoned, + }, phase="embed", ) return code @@ -918,7 +929,10 @@ async def _pending() -> list[Any]: result=result, ) total += n - print(f" embedded {total} (+{n}); failed={result.failed} poisoned={result.poisoned}") + print( + f" embedded {total} (+{n}); reused={result.reused} " + f"failed={result.failed} poisoned={result.poisoned}" + ) if result.switched_off: # Its rows stay as they are, so the next page would be the same one. print(f" {org}'s model calls are switched off — stopping", file=sys.stderr) From 0c6f24cf97e10c840896c9027b24270688293d47 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sat, 28 Nov 2026 18:36:05 +0530 Subject: [PATCH 3/4] The code index guide says the embed phase reuses vectors too Signed-off-by: Vanshaj Poonia --- docs/operations/code-index-operations.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 5edd518d2e8..027a16028b1 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -250,7 +250,9 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac on a persistent volume so a rollout does not re-clone every mirror on every pod. - `backfill` parses, chunks, extracts symbols and edges, and embeds each file. It is resumable: re-run it after an interruption. `--phase index` then `--phase embed` splits - the work, since the unembedded rows are the embed phase's queue. `--commit ` pins + the work, since the unembedded rows are the embed phase's queue. The embed phase copies + vectors from `embed_reuse_from` as an inline embed does, and reports them as `reused`. + `--commit ` pins the tree (and implies `--no-fetch`); `--concurrency N` parallelises files; `--limit N` indexes a sample. - One process parses and extracts at about one core. `--workers N` runs the index @@ -1103,7 +1105,8 @@ line evidence. The import retains historical evidence until a complete run repla A namespace follows one branch, and a branch is indexed only when an entry names it. Add an entry with the same `repo` and a different `namespace` and `git_branch`; it shares the bare clone. Set `embed_reuse_from` to the main branch's namespace so identical chunks -reuse embeddings. Then run `loom code init` and `loom code backfill` for the new +reuse embeddings, whether they are embedded during the index or later by `--phase embed` +and `code_embed_recovery`. Then run `loom code init` and `loom code backfill` for the new namespace, as for the first index. ## Repairs From dff24521489c23dd5f6d9e25346e9d65eb570ca5 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sat, 28 Nov 2026 20:24:03 +0530 Subject: [PATCH 4/4] The polling tests' config fixture sets embed_reuse_from The embed phase reads embed_reuse_from from the namespace's repo config, and the cer fixture's stand-in config had only org and namespace, so four polling tests raised AttributeError. Signed-off-by: Vanshaj Poonia --- tests/unit/test_workers_poll_the_work.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/test_workers_poll_the_work.py b/tests/unit/test_workers_poll_the_work.py index c4424ba52d0..6b86f70f166 100644 --- a/tests/unit/test_workers_poll_the_work.py +++ b/tests/unit/test_workers_poll_the_work.py @@ -251,6 +251,7 @@ def cer(monkeypatch: pytest.MonkeyPatch): class _Cfg: def __init__(self, ns: str) -> None: self.org, self.namespace = "o", ns + self.embed_reuse_from = "" monkeypatch.setattr(repos_mod, "configured_repos", lambda: [_Cfg("n1"), _Cfg("n2"), _Cfg("n3")]) from server.embedding import embedder as emb_mod