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
18 changes: 18 additions & 0 deletions docs/architecture/code-index-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,24 @@ an entry (`code/app/index/retire.py`) deactivates its rows, runs an erasure saga
every `code_*` table for the namespace, and removes the mirror when no other entry uses
it on the host that served the call; every other host's sweep removes its own copy.

### A repository's branches

The entries of one org whose `repo` spells the same repository, whatever remote each
fetches it from, are the repository's members, and `repo_members(org, repo)` in
`code/domain/index/repos.py` is the one place that lists them. They come in the
Repositories page's branch order: `master` or `main` first, then release branches newest
first, then the rest by name. The first is the repository's trunk, and its namespace is
the repository's documents namespace, so every branch reads one set of documents under
the repository's own access rules.

A request names a branch as `<repository or namespace>@<branch>` in `namespace`
(`namespace_resolve.resolve_branch`, run by the HTTP and MCP admission sequences alike).
`@` is not a namespace character (`server/core/naming.py`), so the form never collides
with a namespace name. The gate then authorizes the namespace the name resolves to,
exactly as it authorizes a namespace named directly, and a branch the repository does not
index, or the caller cannot read, answers `UNKNOWN_BRANCH` naming the branches the caller
can read.

## Git mirrors on every replica

Every serving process can answer a history read (blame, bisect, citations, PR
Expand Down
6 changes: 6 additions & 0 deletions docs/features/code-index/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ name, or an indexed namespace's name with a longer or shorter commit hash, when
caller can read exactly one match. The result says so in `namespace_resolved`
([MCP reference](../../reference/mcp.md#sessions-and-identity)).

On every surface, a code call's `namespace` may name a branch as
`<repository or namespace>@<branch>` (`ClickHouse/ClickHouse@26.4`). It runs on the
namespace that indexes that branch of the repository, and authorization runs on that
namespace as on any other. A branch the repository does not index, or the caller cannot
read, answers `UNKNOWN_BRANCH` and lists the branches the caller can read.

Several ops also take `namespaces=[…]` (up to 8) to ask across branch indexes at once.
Every answer that returns results carries a `trace_run_id`; report what you did with the
hits through `code.outcome` so ranking learns from it.
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,10 @@ Raised in `server/identity/app/me_service_accounts.py`.

Raised in `server/transport/arg_check.py`. What to do: [common errors](#common-errors-and-what-to-do).

#### `UNKNOWN_BRANCH`

HTTP 404, raised as `server.core.errors.UnknownBranchError`. 404 — a code call named `<repository>@<branch>` and the repository indexes no such branch the caller can read. Category `input`, retryable: no.

#### `UNKNOWN_FIELD`

Raised in `server/memory/domain/record_values.py`.
Expand Down
4 changes: 3 additions & 1 deletion docs/reference/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,9 @@ What a client gets with and without a plugin is in
is refused with `UNKNOWN_NAMESPACE` and the nearest namespaces the caller may be
told of (`did_you_mean`). A token whose claim covers every namespace is not
refused on the name it gives, so its call runs on that name and nothing is
resolved. Over HTTP a namespace is taken as given.
resolved. Over HTTP a namespace is taken as given, but for a branch spelled
`<repository or namespace>@<branch>`, which a code call resolves on both transports
(`UNKNOWN_BRANCH` for a branch the caller cannot read, with the branches it can).
- **Implicit run.** One run per (org, token subject, session), begun in the
run ledger by the session's first run-scoped tool call and filed in the
caller's default namespace; writes carry its `run_id` (except `run.*`, which
Expand Down
8 changes: 7 additions & 1 deletion sdk/ruby/lib/clickhouse/loom/generated/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,11 @@ class UnknownArgument < Error
CODE = "UNKNOWN_ARGUMENT"
end

# `UNKNOWN_BRANCH`: HTTP 404. 404 — a code call named `<repository>@<branch>` and the repository indexes no such branch the caller can read.
class UnknownBranch < Error
CODE = "UNKNOWN_BRANCH"
end

# `UNKNOWN_FIELD`: Server code
class UnknownField < Error
CODE = "UNKNOWN_FIELD"
Expand Down Expand Up @@ -980,7 +985,7 @@ class WrongCell < Error
CODE = "WRONG_CELL"
end

# The Error subclass for each server code (195 codes); a code not
# The Error subclass for each server code (196 codes); a code not
# listed raises Error itself.
ERROR_CLASSES = {
"ACTIVITY_UNAVAILABLE" => ActivityUnavailable,
Expand Down Expand Up @@ -1170,6 +1175,7 @@ class WrongCell < Error
"TIMELINE_REQUIRES_FILTER" => TimelineRequiresFilter,
"TOKEN_NAME_TAKEN" => TokenNameTaken,
"UNKNOWN_ARGUMENT" => UnknownArgument,
"UNKNOWN_BRANCH" => UnknownBranch,
"UNKNOWN_FIELD" => UnknownField,
"VALIDATION" => Validation,
"VALIDATION_FAILED" => ValidationFailed,
Expand Down
42 changes: 15 additions & 27 deletions server/code/app/backport.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,33 +95,23 @@ async def _settle(tasks: Any, wall_ms: int) -> set[asyncio.Future[Any]]:
# ---- branches ----------------------------------------------------------------------


def release_namespaces(org: str, code_ns: str) -> list[tuple[str, str]]:
"""[(namespace, version)] of the release-branch namespaces configured
for the repository `code_ns` indexes, newest first; the trunk itself
never. Operator configuration, not a guess from names."""
from server.code.domain.index.repos import configured_repos, repo_for_namespace

me = repo_for_namespace(org, code_ns)
if me is None:
return []
out: list[tuple[str, str]] = []
for r in configured_repos():
if r.org != org or r.namespace == code_ns or r.repo != me.repo:
continue
v = bp.version_key(r.git_branch)
if v is None:
continue
out.append((r.namespace, f"{v[0]}.{v[1]}"))
out.sort(key=lambda x: bp.version_key(x[1]) or (0, 0), reverse=True)
return out


def resolve_branches(org: str, code_ns: str, wanted: list[str]) -> list[tuple[str, str]]:
"""The caller's `branches` — a namespace (`code-clickhouse-26-4`) or a
release (`26.4`) each — against the configuration; an entry the
configuration does not know keeps its name and, when it parses as a
release, that version. Empty → every configured release branch."""
configured = release_namespaces(org, code_ns)
release, that version. Empty → every configured release branch, newest
first: the other namespaces of the repository `code_ns` indexes whose
branch is a release, never the trunk. Operator configuration, not a guess
from names."""
from server.code.domain.index.repos import repo_for_namespace, repo_members

me = repo_for_namespace(org, code_ns)
configured: list[tuple[str, str]] = []
for r in repo_members(org, me.repo) if me else []:
v = bp.version_key(r.git_branch)
if r.namespace != code_ns and v is not None:
configured.append((r.namespace, f"{v[0]}.{v[1]}"))
configured.sort(key=lambda x: bp.version_key(x[1]) or (0, 0), reverse=True)
if not wanted:
return configured[:MAX_BRANCHES]
by_ns = dict(configured)
Expand Down Expand Up @@ -535,15 +525,13 @@ async def _ledger_fix() -> PrFacts | None:
def branch_refs(org: str, code_ns: str) -> tuple[str, dict[str, str]]:
"""(the repository's bare mirror, branch namespace → its git ref) from the
configuration: what the history leg reads the release branches with."""
from server.code.domain.index.repos import configured_repos, repo_for_namespace
from server.code.domain.index.repos import repo_for_namespace, repo_members

me = repo_for_namespace(org, code_ns)
if me is None:
return "", {}
return me.git_dir, {
r.namespace: r.git_branch
for r in configured_repos()
if r.org == org and r.repo == me.repo and r.namespace != code_ns
r.namespace: r.git_branch for r in repo_members(org, me.repo) if r.namespace != code_ns
}


Expand Down
5 changes: 3 additions & 2 deletions server/code/app/memory_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
from server.code.domain.index.repos import (
RepoConfig,
configured_repos,
docs_namespaces,
repo_for_namespace,
repo_members,
)
from server.code.store.index import CodeRepo
from server.settings import settings
Expand All @@ -49,7 +49,8 @@ def trunk_namespace(org: str, namespace: str) -> str:
cfg = repo_for_namespace(org, namespace)
if cfg is None:
return ""
return docs_namespaces().get((org, cfg.repo), namespace)
members = repo_members(org, cfg.repo)
return members[0].namespace if members else namespace


def namespace_for_tags(org: str, tags: list[str]) -> str:
Expand Down
11 changes: 6 additions & 5 deletions server/code/app/repo_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

A repository keeps what agents read about it beyond its code (its documents
and its decision memories) in one place: its trunk branch's code namespace
(`repos.docs_namespaces`). Every branch of the repository reads that one
(the first of `repos.repo_members`). Every branch of the repository reads that one
namespace, and it carries the repository's own access, so a restricted
repository's documents and decisions are as restricted as its code.
"""
Expand All @@ -15,8 +15,8 @@
from server.code.domain.index.repos import (
RegistryUnread,
configured_repos,
docs_namespaces,
repo_for_namespace,
repo_members,
)
from server.code.domain.scope import current_code_scope
from server.operations.base import Role
Expand All @@ -30,7 +30,8 @@ def trunk_namespace_of(org: str, code_namespace: str) -> str:
cfg = repo_for_namespace(org, code_namespace)
if cfg is None:
return ""
return docs_namespaces().get((org, str(cfg.repo)), "")
members = repo_members(org, cfg.repo)
return members[0].namespace if members else ""


async def readable_repo_namespace(org: str, code_namespace: str) -> str:
Expand Down Expand Up @@ -62,8 +63,8 @@ def repo_trunk(org: str, repo: str) -> tuple[str, str]:
entries = [c for c in configured_repos() if slug and c.org == org and repo_slug(c.repo) == slug]
if not entries:
return "", ""
# The entries the trunk is chosen from (`docs_namespaces` keys on the spelling of
# `repo`); any of them may be the one that names the remote.
# The entries that spell the repository as the first does; any of them may be the one
# that names the remote.
same = [c for c in entries if c.repo == entries[0].repo]
tag = next((t for c in same if (t := repo_tag(c.git_remote or c.repo))), "")
return trunk_namespace_of(org, entries[0].namespace), tag
Expand Down
10 changes: 6 additions & 4 deletions server/code/app/repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis
# Repositories added from the page appear here as soon as
# the snapshot refreshes (TTL-bounded; forced by the add itself).
from server.code.app.index.repo_registry import refresh_db_repos
from server.code.domain.index.repos import configured_repos, docs_namespaces
from server.code.domain.index.repos import configured_repos, repo_members

await refresh_db_repos()
auth = current_auth()
Expand Down Expand Up @@ -171,7 +171,7 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis
),
return_exceptions=True,
)
docs_ns = docs_namespaces() # every entry, not only the listed ones
every = list(configured_repos()) # every entry, not only the listed ones
bound = await _bound_trackers()
for cfg, readable in gated:
key = (cfg.org, cfg.namespace)
Expand All @@ -184,6 +184,8 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis
if readable:
st = await _repo_status_cached(cfg)
stage = st.state.get(STAGE_KEY) or {}
members = repo_members(cfg.org, cfg.repo, every)
trunk_ns = members[0].namespace if members else ""
out.append(
CodeRepoSummary(
org=st.org,
Expand Down Expand Up @@ -215,8 +217,8 @@ async def _code_repo_rows(input: CodeReposInput, wanted: set[str] | None) -> lis
embedding_coverage=st.embedding_coverage,
searchable=is_searchable(st.embedding_coverage),
has_maintainer=has_maintainer,
docs_namespace=docs_ns.get((cfg.org, cfg.repo), ""),
primary_namespace=docs_ns.get((cfg.org, cfg.repo), ""),
docs_namespace=trunk_ns,
primary_namespace=trunk_ns,
# The links as they are, said only to the maintainer
bound_trackers=(
bound(cfg.org, cfg.namespace) if roles.get(key, "") == "admin" else None
Expand Down
29 changes: 17 additions & 12 deletions server/code/domain/index/repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,15 +778,20 @@ def _trunk_rank(branch: str) -> tuple[int, Any]:
return (2, branch)


def docs_namespaces(entries: list[RepoConfig] | None = None) -> dict[tuple[str, str], str]:
"""(org, repo) → the one namespace the repository's documents live in — its trunk
branch's (the first in the page's branch order), so every branch of the repository
reads the same docs and they carry the repository's own access rules."""
best: dict[tuple[str, str], RepoConfig] = {}
for c in configured_repos() if entries is None else entries:
key = (c.org, c.repo)
rank = (_trunk_rank(str(c.git_branch or "")), c.namespace)
cur = best.get(key)
if cur is None or rank < (_trunk_rank(str(cur.git_branch or "")), cur.namespace):
best[key] = c
return {k: c.namespace for k, c in best.items()}
def repo_members(
org: str, repo: str, entries: Iterable[RepoConfig] | None = None
) -> list[RepoConfig]:
"""Every configured entry of `org` whose `repo` is `repo` as written, in the
Repositories page's branch order: the trunk first, then the release branches newest
first, then the rest by name. The first is the repository's trunk, whose namespace
holds its documents, so every branch reads the same docs under the repository's own
access rules. An entry that fetches the repository from another remote (a fork) is
one of them. `entries` is one snapshot to read, default the configured entries."""
return sorted(
(
c
for c in (configured_repos() if entries is None else entries)
if c.org == org and c.repo == repo
),
key=lambda c: (_trunk_rank(str(c.git_branch or "")), c.namespace),
)
19 changes: 19 additions & 0 deletions server/core/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,25 @@ class NotFoundError(LoomServerError):
status_code = 404


class UnknownBranchError(LoomServerError):
"""404 — a code call named `<repository>@<branch>` and the repository indexes no such
branch the caller can read. `branches` lists the ones the caller can read; retry
with one of them."""

code = "UNKNOWN_BRANCH"
status_code = 404

def __init__(
self,
message: str = "",
*,
repository: str = "",
branch: str = "",
branches: list[str] | None = None,
) -> None:
super().__init__(message, repository=repository, branch=branch, branches=branches or [])


class PreconditionFailedError(LoomServerError):
"""409 — `if_match_sha256` mismatch, an `approved_sha256` that no longer matches
the definition's text, or an erasure that landed while a `namespace.restore` ran. A
Expand Down
7 changes: 5 additions & 2 deletions server/knowledge/app/source_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
from server.code.domain.index.remote import repo_tag
from server.code.domain.index.repos import (
configured_repos,
docs_namespaces,
repo_members,
require_registry_read,
)
from server.core import leases
Expand Down Expand Up @@ -1303,7 +1303,10 @@ def _repo_tag(src: KnowledgeSource) -> str:
"""`repo:<id>` for a source on a repository's trunk code namespace, else ""."""
entries = configured_repos() # one snapshot for both lookups
cfg = next((c for c in entries if (c.org, c.namespace) == (src.org, src.namespace)), None)
if cfg is None or docs_namespaces(entries).get((cfg.org, cfg.repo)) != src.namespace:
if cfg is None:
return ""
members = repo_members(cfg.org, cfg.repo, entries)
if members[0].namespace != src.namespace:
return ""
return repo_tag(cfg.git_remote or cfg.repo)

Expand Down
Loading
Loading