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: 7 additions & 0 deletions docs/architecture/code-index-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,13 @@ is a model self-assessment rather than verified correctness. See
[repository questions](../guides/repository-questions.md) for calibration and mixed
source/documentation retrieval.

An operator entry with an `embed_reuse_from` source also reads that namespace's cached
answers when its own cache misses. The entry is served only when the caller may read the
source, both namespaces share one restriction and one visibility, and every cited and shown
file hashes the same in the branch; a copy is then stored in the branch. A branch added from
the Repositories page takes the namespace it was added from as its vector source
(`code_repos.base_namespace`) and never reads that namespace's cached answers.

Bulk passes leave extra copies per key until a merge. `code/app/index/compaction.py`
runs `OPTIMIZE … FINAL` on the twin tables after a bulk pass. `code_chunks` is compacted
only by `loom code compact --table code_chunks --apply`.
Expand Down
2 changes: 1 addition & 1 deletion docs/features/code-index/repositories.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ chunks carry a vector; until then `code.search` answers lexically
| --------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code.repo.remote_branches` | viewer | what the Git remote shows before anything is written: provider, branches and heads, default branch, release-shaped branches, quota and readiness warnings |
| `code.repo.add` | writer | add `repo@branch` (blank discovers the remote default), optionally more `branches`; access, filters, `scip_producer`, `access_token` |
| `code.repo.add_branch` | admin | index another branch of a repository you maintain; it inherits remote, token, prefixes and access |
| `code.repo.add_branch` | admin | index another branch of a repository you maintain; it inherits remote, token, prefixes and access, and reuses its source's embeddings |
| `code.repo.set_access` | admin | set `classification` (`standard` / `restricted`) and `join_policy` (`open` / `approval` / `closed`) |
| `code.repo.set_source` | admin | link the tracker namespaces this repository reads, primary first ([tracker overview](../tracker/overview.md#linking-a-tracker-to-a-repository)) |
| `code.repo.remove` | admin | retire a self-service index; `confirm` must equal the namespace |
Expand Down
4 changes: 4 additions & 0 deletions docs/operations/code-index-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -1279,6 +1279,10 @@ reuse embeddings, whether they are embedded during the index or later by `--phas
and `code_embed_recovery`. Then run `loom code init` and `loom code backfill` for the new
namespace, as for the first index.

A branch added from the Repositories page (`code.repo.add_branch`) needs none of this: its
registry row records the namespace it was added from (`base_namespace`), which is its
`embed_reuse_from`. A branch whose row records no base namespace embeds every chunk.

## Repairs

`loom code reconcile --namespace NS` lists indexed paths whose chunks predate their last
Expand Down
8 changes: 8 additions & 0 deletions schemas/migrations/121_code_repo_base_namespace.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- The namespace a loom.code_repos row's branch was added from on the Repositories page
-- (code.repo.add_branch); '' for a repository added whole, an operator entry's access
-- row and a row written before this file. The branch copies the vectors of identical
-- chunks from that namespace (RepoConfig.embed_reuse_from). Additive: a running pod of
-- the previous build reads the table by column name, writes a new row without the column
-- and copies an existing row whole, so it keeps working and keeps a value a newer pod wrote.
ALTER TABLE loom.code_repos
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
ADD COLUMN IF NOT EXISTS `base_namespace` LowCardinality(String) DEFAULT '';
3 changes: 2 additions & 1 deletion schemas/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,8 @@ CREATE TABLE IF NOT EXISTS loom.code_repos
`exclude_generated` Bool DEFAULT false,
`scip_producer` LowCardinality(String) DEFAULT '',
`row_kind` LowCardinality(String) DEFAULT '',
`git_proxy_identity` String DEFAULT ''
`git_proxy_identity` String DEFAULT '',
`base_namespace` LowCardinality(String) DEFAULT ''
)
ENGINE = ReplacingMergeTree(version)
ORDER BY (org, namespace)
Expand Down
6 changes: 5 additions & 1 deletion server/code/app/answers_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,13 +210,17 @@ async def _negative(ctx: _AskCtx) -> AskResult | None:


def _trunk_of(org: str, ns: str) -> str:
"""The namespace whose answers this one borrows: an operator entry's
`embed_reuse_from`. A branch added from the page takes only vectors from its
source: a borrowed answer is copied into the branch, and that copy's later hits
check the branch alone, not the source grant."""
try:
from server.code.domain.index.repos import repo_for_namespace

cfg = repo_for_namespace(org, ns)
except Exception: # noqa: BLE001 — no repo config: no trunk to reuse
return ""
src = cfg.embed_reuse_from.strip() if cfg else ""
src = cfg.embed_reuse_from.strip() if cfg and cfg.source == "config" else ""
return src if src and src != ns and cache_namespace_ok(src) else ""


Expand Down
1 change: 1 addition & 0 deletions server/code/app/index/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,7 @@ async def _one(reads: Any, path: str, source: bytes) -> None:
commit_sha=head,
embedding_model=model_name,
embedder=embedder,
embed_reuse_from=cfg.embed_reuse_from,
max_chunk_chars=settings.code_chunk_max_chars,
denylist=denylist,
parsed=reads.parsed.get(path),
Expand Down
4 changes: 4 additions & 0 deletions server/code/app/index/repo_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ def row_to_config(r: dict[str, Any]) -> RepoConfig:
exclude_generated=bool(r.get("exclude_generated", False)),
scip_producer=str(r.get("scip_producer") or ""),
row_kind=str(r.get("row_kind") or ""),
# A branch added from the page copies the vectors of the namespace it came from.
embed_reuse_from=str(r.get("base_namespace") or ""),
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
)


Expand Down Expand Up @@ -259,6 +261,7 @@ async def insert_entry(
exclude_generated: bool = True,
scip_producer: str = "",
git_proxy_identity: str = "",
base_namespace: str = "",
ch: Any | None = None,
) -> None:
from datetime import UTC, datetime
Expand All @@ -282,6 +285,7 @@ async def insert_entry(
"join_policy": join_policy,
"github_token_enc": encrypt_token(github_token),
"git_proxy_identity": git_proxy_identity,
"base_namespace": base_namespace,
"created_by": created_by,
"active": True,
"created_at": now,
Expand Down
3 changes: 3 additions & 0 deletions server/code/app/repo_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ async def _register(
exclude_generated: bool = True,
scip_producer: str = "",
git_proxy_identity: str = "",
base_namespace: str = "",
) -> CodeRepoAddOutput:
from server.auth.default_namespace import auth_off_subject
from server.code.app.index.bootstrap import set_stage
Expand Down Expand Up @@ -205,6 +206,7 @@ async def _register(
exclude_generated=exclude_generated,
scip_producer=scip_producer,
git_proxy_identity=git_proxy_identity,
base_namespace=base_namespace,
)
await reg.refresh_db_repos(force=True)
cfg = next(
Expand Down Expand Up @@ -677,6 +679,7 @@ async def handle_code_repo_add_branch(input: CodeRepoAddBranchInput) -> CodeRepo
exclude_generated=bool(getattr(src, "exclude_generated", True)),
scip_producer=str(getattr(src, "scip_producer", "") or ""),
git_proxy_identity=src.git_proxy_identity,
base_namespace=src.namespace,
)
await _inherit_tracker_links(input.org, input.namespace, namespace)
return out
Expand Down
5 changes: 3 additions & 2 deletions server/code/store/index/code_repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ async def registry_rows(self) -> list[dict[str, Any]]:
(`repos._with_registry`)."""
rows: list[dict[str, Any]] = await self._ch.query_all(
"""
-- A removed row's repository, remote, branch, paths, token and git proxy
-- identity read empty.
-- A removed row's repository, remote, branch, paths, token, git proxy
-- identity and base namespace read empty.
SELECT org, namespace, if(active, repo, '') AS repo,
if(active, git_remote, '') AS git_remote,
if(active, git_branch, '') AS git_branch,
Expand All @@ -32,6 +32,7 @@ async def registry_rows(self) -> list[dict[str, Any]]:
toString(join_policy) AS join_policy,
if(active, github_token_enc, '') AS github_token_enc,
if(active, git_proxy_identity, '') AS git_proxy_identity,
if(active, base_namespace, '') AS base_namespace,
exclude_generated, toString(scip_producer) AS scip_producer,
row_kind, active
FROM loom.code_repos FINAL
Expand Down
2 changes: 1 addition & 1 deletion tests/analyzer/shapes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,7 @@
39f9fbc2c519 SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND user_id = {uid:String}
3a315e2ef1be ALTER TABLE loom.entity_canonical_map UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String}
3a6169b72b54 SELECT count() AS n FROM loom.derived_facts WHERE org = {org:String} AND user_id = {uid:String}
3a662f80aca3 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou
3a8471ec9ffe SELECT pr_number, any(title) AS title, any(author) AS author, min(merged_at) AS merged_at, max(opened_at) AS opened_at, any(files) AS files, any(linked_issues) AS linked_issues FROM loom.code_pr_histo
3a88608e1703 SELECT count() AS n FROM loom.entity_triples WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ?
3a892047e93b SELECT scope_type, scope_path, summary, pagerank, in_degree, out_degree, key_symbols FROM loom.code_summaries FINAL WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:St
Expand Down Expand Up @@ -1325,7 +1326,6 @@
939f4aded6d7 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user
93b20af9b346 SELECT concat(?, c.session_id, ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, c.content AS content_excerpt, toString(ss.session_date) AS created_at, toString(ss.session_date) AS valid_at
93b6309f14f7 SELECT agent, count() AS rows, count() OVER () AS total, sum(count()) OVER () AS total_rows FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND st
93b8f43058b1 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou
93ec8d6c0770 SELECT run_id, toString(memory_id) AS mid, event_type, credited_at, actor, agent, consumer, sum(event_count) AS net, count() AS n FROM loom.memory_usage_events WHERE org = {org:String} AND namespace =
93fb8239f3f5 SELECT count() AS n FROM loom.memory_record_fields FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}
945db02b838d SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ?
Expand Down
56 changes: 56 additions & 0 deletions tests/integration/test_code_repo_row_kind.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import dataclasses
from collections.abc import AsyncIterator
from datetime import UTC, datetime
from typing import Any

import pytest
Expand Down Expand Up @@ -171,6 +172,7 @@ async def test_an_operator_entry_over_an_inactive_access_row_writes_a_fresh_one(
"scip_producer": "",
"row_kind": "access",
"git_proxy_identity": "",
"base_namespace": "",
}


Expand Down Expand Up @@ -212,3 +214,57 @@ async def test_a_page_branch_keeps_its_git_proxy_identity_until_it_is_removed(or
False,
"",
)


async def test_a_branch_keeps_the_namespace_it_was_added_from_until_it_is_removed(org: str) -> None:
"""The base an add stored is read back as the entry's vector source, survives an
access change (which copies the row whole, as the previous build does) and reads
empty once the branch is removed; a row written without the column has none."""
await reg.insert_entry(
org=org,
namespace="code-release",
repo="it/row-kind",
branch="release/1.2",
classification="standard",
join_policy="open",
github_token="",
path_prefixes=[],
exclude=[],
created_by="admin",
base_namespace="code-main",
)
await _add(org, "code-main")
now = datetime.now(UTC).replace(microsecond=0, tzinfo=None)
# What a build without the column writes: the key is absent from the row.
await CodeRepo().insert_code_repo_row(
{
"org": org,
"namespace": "code-old",
"repo": "it/row-kind",
"git_remote": "https://github.com/it/row-kind.git",
"git_branch": "old",
"row_kind": "page",
"created_by": "member",
"created_at": now,
"updated_at": now,
}
)
row = await CodeRepo().code_repo_row(org, "code-release")
assert row is not None and row["base_namespace"] == "code-main"
release = dataclasses.replace(_entry(org, "code-release"), source="registry")
await reg.upsert_access(
release,
classification="restricted",
join_policy="approval",
created_by="admin",
current=await reg.live_row(release),
)
assert await reg.read_registry()
read = {c.namespace: c for c in repos.registry_repos() if c.org == org}
assert read["code-release"].embed_reuse_from == "code-main"
assert read["code-release"].classification == "restricted"
assert read["code-main"].embed_reuse_from == ""
assert read["code-old"].embed_reuse_from == ""
assert await CodeRepo().deactivate_code_repo(org, "code-release")
rows = {r["namespace"]: r for r in await CodeRepo().registry_rows() if r["org"] == org}
assert (rows["code-release"]["active"], rows["code-release"]["base_namespace"]) == (False, "")
19 changes: 18 additions & 1 deletion tests/unit/test_code_ask_cache_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,7 @@ def branch(env: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> dict[str, An
import server.identity.app.namespace_classification as nc
import server.identity.app.namespace_visibility as nv

cfg = SimpleNamespace(embed_reuse_from=NS)
cfg = SimpleNamespace(embed_reuse_from=NS, source="config") # an operator release branch
monkeypatch.setattr(repos, "repo_for_namespace", lambda org, ns: cfg if ns == BRANCH else None)
env["restricted"] = set()
env["vis"] = {NS: "private", BRANCH: "private"}
Expand Down Expand Up @@ -1188,6 +1188,23 @@ def test_reuse_needs_the_same_visibility_and_a_readable_trunk(branch: dict[str,
)


def test_a_branch_added_from_the_page_never_serves_its_source_answers(
branch: dict[str, Any], monkeypatch: pytest.MonkeyPatch
) -> None:
import server.code.domain.index.repos as repos

page = SimpleNamespace(embed_reuse_from=NS, source="registry")
monkeypatch.setattr(repos, "repo_for_namespace", lambda org, ns: page if ns == BRANCH else None)
repo = branch["repo"]
# A viewer who may read the source asks first: the branch synthesizes its own answer.
assert _ask(repo, "how does TTL drop old parts?", ns=BRANCH).source == "synthesized"
# A second viewer without the source grant (or the first, once revoked) reads the
# branch's own entry, never a copy of the source's.
branch["readable"] = False
assert _ask(repo, "how does TTL drop old parts?", ns=BRANCH).cache == "hit"
assert not [r for r in repo.inserts if r.get("reused_from")]


# ---- 6. feedback invalidation ----------------------------------------------------


Expand Down
7 changes: 6 additions & 1 deletion tests/unit/test_code_ingest_pass_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,12 @@ async def set_state(
monkeypatch.setattr(bs, "bootstrap_embedder", lambda: None)
repo = _Repo()
cfg = SimpleNamespace(
org="o", namespace="n", git_dir="/nowhere.git", path_prefixes=(), label="o/n"
org="o",
namespace="n",
git_dir="/nowhere.git",
path_prefixes=(),
label="o/n",
embed_reuse_from="",
)
progress = asyncio.run(bs.index_slice(cfg, repo, "f" * 40, stop_after=clock.now + 15.0))
# round one at t=0 (→10), round two at t=10 < 15 (→20), round three not started
Expand Down
Loading
Loading