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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions docs/operations/code-index-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <sha>` 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 <sha>` 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
Expand Down Expand Up @@ -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
Expand Down
20 changes: 17 additions & 3 deletions server/cli/code_backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
104 changes: 91 additions & 13 deletions server/code/workers/embed_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
)
Expand All @@ -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 ""
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
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,
Expand Down
1 change: 1 addition & 0 deletions tests/unit/test_code_embed_recovery_republishes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
132 changes: 132 additions & 0 deletions tests/unit/test_code_embed_recovery_reuse.py
Original file line number Diff line number Diff line change
@@ -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"]
1 change: 1 addition & 0 deletions tests/unit/test_workers_poll_the_work.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading