From 0d030335597af1212298981903075f7c15c3be1d Mon Sep 17 00:00:00 2001 From: Kaloyan Date: Tue, 1 Dec 2026 23:02:44 +0000 Subject: [PATCH 01/10] A code read can name a branch as `repo@branch` A code call's `namespace` can be `@` on HTTP, MCP and the SDKs alike. The name resolves in the shared admission sequence, before validation and the gate, to the namespace that indexes that branch, and the gate authorizes that namespace exactly as it authorizes one named directly. A branch the repository does not index, or the caller cannot read, answers UNKNOWN_BRANCH (404) naming the readable branches. `@` is not a namespace character (`server/core/naming.py`), so the form never collides with a name. `repo_members(org, repo_key)` replaces `docs_namespaces`, `repo_siblings` and `release_namespaces`: one list of a repository's entries in the Repositories page's branch order, the trunk first. The architecture page states the trunk's role. Related: #1680 Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Sonnet 5.5 --- docs/architecture/code-index-architecture.md | 18 + docs/features/code-index/operations.md | 6 + docs/reference/errors.md | 4 + docs/reference/mcp.md | 4 +- .../lib/clickhouse/loom/generated/errors.rb | 8 +- server/code/app/backport.py | 42 +- server/code/app/bisect.py | 6 +- server/code/app/bisect_fix.py | 5 +- server/code/app/blame.py | 22 +- server/code/app/first_build.py | 6 +- server/code/app/memory_links.py | 6 +- server/code/app/repo_scope.py | 12 +- server/code/app/repos.py | 10 +- server/code/domain/index/repos.py | 39 +- server/core/errors.py | 19 + server/knowledge/app/source_sync.py | 8 +- server/transport/gates.py | 46 ++ server/transport/http.py | 24 +- server/transport/mcp_auth.py | 57 +- server/transport/mcp_call.py | 32 +- server/transport/namespace_resolve.py | 60 ++- .../test_backport_release_branch_names.py | 14 +- tests/unit/test_code_backport_gap.py | 3 +- tests/unit/test_code_backport_gap_exact.py | 1 + tests/unit/test_code_backport_gaps.py | 1 + tests/unit/test_code_bisect_deadline.py | 3 +- tests/unit/test_mcp_session_runs.py | 2 +- tests/unit/test_merge_shas.py | 4 +- tests/unit/test_mirrors.py | 7 +- .../test_platform_admin_repository_read.py | 1 - tests/unit/test_pr_post_image.py | 2 +- tests/unit/test_repo_at_branch.py | 485 ++++++++++++++++++ tests/unit/test_repo_docs.py | 17 +- tests/unit/test_sdk_errors_from_response.py | 1 + 34 files changed, 856 insertions(+), 119 deletions(-) create mode 100644 tests/unit/test_repo_at_branch.py diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 1573ed82c17..9b809ab8dbd 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -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 that name the same repository (`remote.repo_key`) are the +repository's members, and `repo_members(org, repo_key)` 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 `@` 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 diff --git a/docs/features/code-index/operations.md b/docs/features/code-index/operations.md index 8ad29e079e4..721f835595c 100644 --- a/docs/features/code-index/operations.md +++ b/docs/features/code-index/operations.md @@ -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 +`@` (`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. diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 54a6f0c7785..17a6d2ce0f5 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -956,6 +956,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 `@` 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`. diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index d71300b313c..9ca6ae45833 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -295,7 +295,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 + `@`, 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 diff --git a/sdk/ruby/lib/clickhouse/loom/generated/errors.rb b/sdk/ruby/lib/clickhouse/loom/generated/errors.rb index e3249bd01e0..0ea11e5f46f 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/errors.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/errors.rb @@ -930,6 +930,11 @@ class UnknownArgument < Error CODE = "UNKNOWN_ARGUMENT" end + # `UNKNOWN_BRANCH`: HTTP 404. 404 — a code call named `@` 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" @@ -970,7 +975,7 @@ class WrongCell < Error CODE = "WRONG_CELL" end - # The Error subclass for each server code (193 codes); a code not + # The Error subclass for each server code (194 codes); a code not # listed raises Error itself. ERROR_CLASSES = { "ACTIVITY_UNAVAILABLE" => ActivityUnavailable, @@ -1158,6 +1163,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, diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 2f081b383d5..2817a1c3494 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -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 entry_repo_key, repo_for_namespace, repo_members + + me = repo_for_namespace(org, code_ns) + configured: list[tuple[str, str]] = [] + for r in repo_members(org, entry_repo_key(me.repo, me.git_remote)) 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) @@ -535,15 +525,15 @@ 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 entry_repo_key, 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 + for r in repo_members(org, entry_repo_key(me.repo, me.git_remote)) + if r.namespace != code_ns } diff --git a/server/code/app/bisect.py b/server/code/app/bisect.py index 73ab3b3cf24..0585344c789 100644 --- a/server/code/app/bisect.py +++ b/server/code/app/bisect.py @@ -86,7 +86,7 @@ from server.code.app.spans import code_span, set_code_span_attributes from server.code.domain.index import blame_range as br from server.code.domain.index.coverage_claim import is_test_file -from server.code.domain.index.repos import default_git_dir +from server.code.domain.index.repos import default_git_dir, repo_for_namespace from server.code.domain.time_window import _iso, _parse_when from server.code.store.index import CodeRepo from server.core.errors import ValidationError @@ -273,7 +273,7 @@ async def _mark_stage( logger.info("bisect: ledger records unread (%s)", e) records, stage.status = {}, "ledger_failed" first = bi.mark_bisect_candidates(pool, records=records, frames=frames, diff_kinds={}) - cfg, _siblings = cb.repo_siblings(org, ns) + cfg = repo_for_namespace(org, ns) git_dir, stage.reason = await cb.history_git_dir(cfg, "code.bisect_candidates") targets = ( _diff_targets(pool, first, records, frames_or_paths=bool(frames or paths)) @@ -318,7 +318,7 @@ async def _attach_merge_shas(repo: CodeRepo, org: str, ns: str, ranked: list[bi. except Exception as e: # noqa: BLE001 — the mirror still answers logger.info("bisect: ledger merge commits unread (%s)", e) stored = {} - cfg, _siblings = cb.repo_siblings(org, ns) + cfg = repo_for_namespace(org, ns) # no mirror here yet: the ledger's shas alone (history_dir starts the clone) git_dir = (await history_dir(cfg))[0] if cfg is not None else default_git_dir() branch = (cfg.git_branch if cfg is not None else "") or settings.code_git_branch diff --git a/server/code/app/bisect_fix.py b/server/code/app/bisect_fix.py index 04e2a8b17db..4761f1e2857 100644 --- a/server/code/app/bisect_fix.py +++ b/server/code/app/bisect_fix.py @@ -305,9 +305,10 @@ async def _fix_blame_stage( `code.blame_range`, name the PR that wrote them; those PRs go first with `blamed_by_fix`. Bounded (a few ranges, a wall budget) and fail-open: the pool as it was, and a summary saying why.""" - from server.code.app.blame import handle_code_blame_range, history_git_dir, repo_siblings + from server.code.app.blame import handle_code_blame_range, history_git_dir from server.code.app.index import gitrepo from server.code.domain.index import fix_blame as fb + from server.code.domain.index.repos import repo_for_namespace summary: dict[str, Any] = {"fix_pr": fix_pr} if _short(STAGE_MIN_S, "fix_blame"): @@ -318,7 +319,7 @@ async def _fix_blame_stage( if not merge: summary["skipped"] = "fix_not_in_ledger" return pool, summary - cfg, _ = repo_siblings(org, ns) + cfg = repo_for_namespace(org, ns) git_dir, gap = await history_git_dir(cfg, "code.bisect_candidates") if gap: summary["skipped"] = gap diff --git a/server/code/app/blame.py b/server/code/app/blame.py index 3df89697ec5..70d0612dd92 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -53,7 +53,12 @@ from server.code.domain.index import blame_range as br from server.code.domain.index import symbol_history as sh from server.code.domain.index.compiler_tiers import state_value -from server.code.domain.index.repos import default_git_dir +from server.code.domain.index.repos import ( + default_git_dir, + entry_repo_key, + repo_for_namespace, + repo_members, +) from server.code.store.index import CodeRepo from server.settings import settings from server.tracker.domain import bisect as bi @@ -122,18 +127,6 @@ def _iso(ts: int) -> str: return datetime.fromtimestamp(ts, tz=UTC).isoformat() if ts > 0 else "" -def repo_siblings(org: str, ns: str) -> tuple[Any, list[Any]]: - """(this namespace's repo config, every configured entry on the same - bare clone) — the release-branch namespaces share the mirror.""" - from server.code.domain.index.repos import configured_repos - - cfgs = configured_repos() - mine = next((c for c in cfgs if c.org == org and c.namespace == ns), None) - if mine is None: - return None, [] - return mine, [c for c in cfgs if c.org == org and c.git_dir == mine.git_dir] - - async def history_git_dir(cfg: Any, op: str, *, head: str = "") -> tuple[str, str]: """`mirrors.history_dir` for a read of `op`, the scalar entry's mirror when no entry indexes the namespace.""" @@ -748,7 +741,8 @@ async def handle_code_blame_range(input: Any) -> Any: started = time.monotonic() org, ns = resolve_code_identity(input.org, input.namespace) repo = CodeRepo() - cfg, siblings = repo_siblings(org, ns) + cfg = repo_for_namespace(org, ns) + siblings = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) if cfg else [] # the window's default end is the indexed head: read once, for both head = ( await _namespace_head(repo, org, ns) diff --git a/server/code/app/first_build.py b/server/code/app/first_build.py index a0637655294..fc72657fc48 100644 --- a/server/code/app/first_build.py +++ b/server/code/app/first_build.py @@ -32,7 +32,7 @@ from typing import Any from server.code.api.models_history import CodeFirstBuildOutput -from server.code.app.blame import IndexedView, history_git_dir, repo_siblings +from server.code.app.blame import IndexedView, history_git_dir from server.code.app.common import ( new_trace_run_id, require_code_intel, @@ -43,6 +43,7 @@ from server.code.app.spans import code_span, set_code_span_attributes from server.code.domain.index import first_build as fb from server.code.domain.index.blame_range import sha_text +from server.code.domain.index.repos import entry_repo_key, repo_for_namespace, repo_members from server.code.store.index import CodeRepo from server.core.errors import ValidationError @@ -197,7 +198,8 @@ async def handle_code_first_build(input: Any) -> Any: started = time.monotonic() org, ns = resolve_code_identity(input.org, input.namespace) repo = CodeRepo() - cfg, siblings = repo_siblings(org, ns) + cfg = repo_for_namespace(org, ns) + siblings = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) if cfg else [] git_dir, gap = await history_git_dir(cfg, "code.first_build") sub = Subject(sha=fb.normalize_sha(input.sha), pr_number=int(input.pr_number or 0)) # Shape complaints come after the gate (the transport already ran it on org/namespace), diff --git a/server/code/app/memory_links.py b/server/code/app/memory_links.py index b60e50fad1f..f26f2ea860a 100644 --- a/server/code/app/memory_links.py +++ b/server/code/app/memory_links.py @@ -30,8 +30,9 @@ from server.code.domain.index.repos import ( RepoConfig, configured_repos, - docs_namespaces, + entry_repo_key, repo_for_namespace, + repo_members, ) from server.code.store.index import CodeRepo from server.settings import settings @@ -49,7 +50,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, entry_repo_key(cfg.repo, cfg.git_remote)) + return members[0].namespace if members else namespace def namespace_for_tags(org: str, tags: list[str]) -> str: diff --git a/server/code/app/repo_scope.py b/server/code/app/repo_scope.py index b4d31cfca42..f5d99039ff5 100644 --- a/server/code/app/repo_scope.py +++ b/server/code/app/repo_scope.py @@ -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. """ @@ -15,8 +15,9 @@ from server.code.domain.index.repos import ( RegistryUnread, configured_repos, - docs_namespaces, + entry_repo_key, repo_for_namespace, + repo_members, ) from server.code.domain.scope import current_code_scope from server.operations.base import Role @@ -30,7 +31,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, entry_repo_key(cfg.repo, cfg.git_remote)) + return members[0].namespace if members else "" async def readable_repo_namespace(org: str, code_namespace: str) -> str: @@ -62,8 +64,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 diff --git a/server/code/app/repos.py b/server/code/app/repos.py index e529f2d2835..b36574b02cc 100644 --- a/server/code/app/repos.py +++ b/server/code/app/repos.py @@ -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() @@ -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) @@ -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, repo_key(cfg.repo, cfg.git_remote), every) + trunk_ns = members[0].namespace if members else "" out.append( CodeRepoSummary( org=st.org, @@ -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 diff --git a/server/code/domain/index/repos.py b/server/code/domain/index/repos.py index 226a5ebc798..c716b5f558f 100644 --- a/server/code/domain/index/repos.py +++ b/server/code/domain/index/repos.py @@ -34,6 +34,7 @@ from __future__ import annotations +import functools import json import logging import os @@ -771,15 +772,29 @@ 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()} +@functools.lru_cache(maxsize=4096) +def entry_repo_key(repo: str, git_remote: str) -> str: + """`remote.repo_key` of an entry, memoized: a listing keys every entry against every + other.""" + from server.code.domain.index.remote import repo_key + + return repo_key(repo, git_remote) + + +def repo_members( + org: str, repo_key: str, entries: Iterable[RepoConfig] | None = None +) -> list[RepoConfig]: + """Every configured entry of the repository `repo_key` (`remote.repo_key`) in `org`, + 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. `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 entry_repo_key(c.repo, c.git_remote) == repo_key + ), + key=lambda c: (_trunk_rank(str(c.git_branch or "")), c.namespace), + ) diff --git a/server/core/errors.py b/server/core/errors.py index b9cd37fca62..ddeb926ead6 100644 --- a/server/core/errors.py +++ b/server/core/errors.py @@ -97,6 +97,25 @@ class NotFoundError(LoomServerError): status_code = 404 +class UnknownBranchError(LoomServerError): + """404 — a code call named `@` 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 diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index c506f801261..8b87b186cc6 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -103,7 +103,8 @@ from server.code.domain.index.remote import repo_tag from server.code.domain.index.repos import ( configured_repos, - docs_namespaces, + entry_repo_key, + repo_members, require_registry_read, ) from server.core import leases @@ -1290,7 +1291,10 @@ def _repo_tag(src: KnowledgeSource) -> str: """`repo:` 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, entry_repo_key(cfg.repo, cfg.git_remote), entries) + if members[0].namespace != src.namespace: return "" return repo_tag(cfg.git_remote or cfg.repo) diff --git a/server/transport/gates.py b/server/transport/gates.py index d1590671cd3..6d95fbc428c 100644 --- a/server/transport/gates.py +++ b/server/transport/gates.py @@ -11,6 +11,9 @@ the request's, else the op's plane default (code.* / tracker.*), else the verified token's own org. A namespace is never authorized without an org: that is a refusal (IDENTITY_INCOMPLETE), not a flat-role pass. +- `with_branch_name`: a code op's `namespace` spelled `@` becomes + the namespace of that branch, before validation, so the gate below authorizes the + namespace it names exactly as it does any other. - `with_single_user_identity`: on a single-user server, a call with no token gets the install's org, and on the everyday memory and search ops (SINGLE_USER_FILLED_OPS) its namespace and the op's agent, where it left @@ -180,6 +183,49 @@ def with_resolved_org(op: Operation, args: dict[str, Any], auth: AuthInfo | None return {**args, **update} if update else args +async def may_read(auth: AuthInfo, org: str, namespace: str) -> tuple[bool, bool]: + """(allowed, unverified): whether the gate admits `auth` to read (org, namespace) + — the claim, a grant (or an inheriting service account's creator's), the + org-readable code rule and the restricted two-factor check, decided by + `check_authorized` alone — and, for a refusal, whether it was made + because a read it needed failed (server.auth.fail_closed): still + refused, but the server's failure.""" + from server.auth.authz import check_authorized + from server.operations.base import Role + + try: + await check_authorized(auth, Role.VIEWER, org=org, namespace=namespace) + except PermissionError as e: + return False, bool(getattr(e, "unverified", False)) + except IdentityIncompleteError: + return False, False + return True, False + + +async def with_branch_name( + op: Operation, args: dict[str, Any], auth: AuthInfo | None +) -> dict[str, Any]: + """The arguments with a code op's `namespace` spelled `@` replaced by the namespace that indexes that branch + (`namespace_resolve.resolve_branch`), so HTTP and MCP resolve it alike before + the gate authorizes the namespace it names, as it authorizes any other. A name + that is not that form, or names no repository, is left for the gate to refuse. + Raises UnknownBranchError for a branch the caller cannot read. A copy.""" + name = args.get("namespace") + if not (isinstance(name, str) and "@" in name and op.name.startswith("code.")): + return args + org = resolve_org(op, args.get("org"), auth) + if org is None: + return args + from server.transport import namespace_resolve as nr + + async def readable(ns: str) -> bool: + return auth is None or (await may_read(auth, org, ns))[0] + + resolved = await nr.resolve_branch(org, name.strip(), readable) + return {**args, "namespace": resolved} if resolved else args + + # Ops whose namespace a no-token single-user call may leave out, mapped to the agent # filled when it names none ("": none, so the op reads every agent). Each value is # checked against the op: "http" where it is the writer, or a key read or delete diff --git a/server/transport/http.py b/server/transport/http.py index 21491d3b587..b0b2af88b22 100644 --- a/server/transport/http.py +++ b/server/transport/http.py @@ -36,6 +36,7 @@ AuthInsufficientError, IdentityIncompleteError, LoomServerError, + UnknownBranchError, handler_failure_detail, unverified_class, ) @@ -369,6 +370,24 @@ def _validate_payload(op: Operation, request_id: str, raw_body: Any, auth: AuthI return payload +async def _resolve_branch_name( + op: Operation, call: _HttpCall, args: dict[str, Any] +) -> dict[str, Any]: + """The arguments with a `@` namespace resolved + (`gates.with_branch_name`); a branch the caller cannot read is a 404 + UNKNOWN_BRANCH naming those it can.""" + try: + return await gates.with_branch_name(op, args, call.auth) + except UnknownBranchError as e: + raise _refuse(op, call, e.status_code, error_code=e.code, e=e, detail=e.extra) from e + except LoomServerError as e: + # A read the check could not make past its cache (a 503): counted against the + # server, then answered as raised. + body = _refused_body(call.raw_body, call.auth) + _emit_event(op, call.request_id, body, 0, success=False, error_code=e.code, error=e) + raise + + def _refused_body(raw_body: dict[str, Any], auth: AuthInfo | None) -> dict[str, Any]: """The body a refusal before authorization is ledgered with: one naming an org the token may not act in is recorded in the token's org with @@ -809,9 +828,8 @@ async def endpoint(request: Request, response: Response) -> Any: body = await _read_body(op, request, request_id, auth) call.raw_body = raw_body = await gates.with_single_user_identity(op, body, auth) - payload = _validate_payload( - op, request_id, gates.with_resolved_org(op, raw_body, auth), auth - ) + args = await _resolve_branch_name(op, call, gates.with_resolved_org(op, raw_body, auth)) + payload = _validate_payload(op, request_id, args, auth) payload, raw_body = _resolve_personal(op, call, payload, raw_body, auth) call.raw_body = raw_body diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index 37421cda5e3..352052b0854 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -13,8 +13,8 @@ from server.auth.fanout import knowledge_search_reads_collections from server.code.domain.scope import set_code_scope from server.core.errors import ( - IdentityIncompleteError, LoomServerError, + UnknownBranchError, WrongCellError, classified, unverified_class, @@ -37,22 +37,10 @@ async def _may_read(auth: AuthInfo, org: str, ns: str) -> tuple[bool, bool]: - """(allowed, unverified): whether the gate admits `auth` to read (org, ns) - — the claim, a grant (or an inheriting service account's creator's), the - org-readable code rule and the restricted two-factor check, decided by - `check_authorized` alone — and, for a refusal, whether it was made - because a read it needed failed (server.auth.fail_closed): still - refused, but the server's failure.""" - from server.auth.authz import check_authorized - from server.operations.base import Role + """(allowed, unverified): `gates.may_read`, the one check both transports make.""" + from server.transport import gates - try: - await check_authorized(auth, Role.VIEWER, org=org, namespace=ns) - except PermissionError as e: - return False, bool(getattr(e, "unverified", False)) - except IdentityIncompleteError: - return False, False - return True, False + return await gates.may_read(auth, org, ns) # Where a person asks for a memory namespace's grant in the dashboard, in the namespace @@ -468,6 +456,39 @@ async def _screen_tool_call( raise +async def _branch_namespace( + req: dict[str, Any], + tool_name: Any, + args: dict[str, Any], + auth: AuthInfo, + target_org: str, + req_ns: str, + consumer: str, +) -> str | dict[str, Any] | None: + """For a code tool's `namespace` spelled `@` (as + `gates.with_branch_name` reads it on every transport): the namespace of that + branch, written into `args`; the UNKNOWN_BRANCH result, ledgered, for a branch the + caller cannot read; None for any other name.""" + from server.transport import namespace_resolve as nr + + if "@" not in req_ns or not str(tool_name or "").startswith("loom_code_"): + return None + + async def readable(ns: str) -> bool: + return (await _may_read(auth, target_org, ns))[0] + + try: + to = await nr.resolve_branch(target_org, req_ns.strip(), readable) + except UnknownBranchError as e: + from server.transport.mcp_refusals import refusal_result + + _ledger_refusal(tool_name, auth, error_code=e.code, org=target_org, consumer=consumer) + return _ok(req.get("id"), refusal_result(e)) + if to: + args["namespace"] = to + return to + + async def _screen_namespace( req: dict[str, Any], tool_name: Any, @@ -480,6 +501,10 @@ async def _screen_namespace( """The screen's namespace check: None when the caller may read `req_ns` (or the code/tracker index it resolves to, written into `args`), else the refusal, ledgered.""" + branch = await _branch_namespace(req, tool_name, args, auth, target_org, req_ns, consumer) + if isinstance(branch, dict): + return branch # UNKNOWN_BRANCH + req_ns = branch or req_ns allowed, given_unverified = await _may_read(auth, target_org, req_ns) if not allowed: # A code/tracker tool's `namespace` that is not a namespace resolves diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index e3f300064f2..1ab259b2c77 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -26,6 +26,7 @@ from server.core.errors import ( LoomServerError, SessionProtectionRequiredError, + UnknownBranchError, WrongCellError, unverified_class, ) @@ -286,10 +287,11 @@ async def _call_tool( client_idem_key = _pop_idempotency_key(op, arguments) - validated = _validated_input( + validated = await _named_input( req_id, op, - gates.with_resolved_org(op, arguments, auth), + arguments, + auth, request_id, toolset=toolset, include_example=not explicit_identity, @@ -780,6 +782,32 @@ async def _idempotency_gate( return None, replay.scope, replay.body_hash +async def _named_input( + req_id: Any, + op: Operation, + arguments: dict[str, Any], + auth: Any, + request_id: str, + *, + toolset: str | None = None, + include_example: bool = True, +) -> BaseModel | dict[str, Any]: + """Phase 4 of `_call_tool` on the arguments as the gate reads them + (`gates.with_resolved_org`) with a `@` namespace resolved to + its branch's (`gates.with_branch_name`, as HTTP does). Returns the input model, or + the refusal response: UNKNOWN_BRANCH for a branch the caller cannot read, else + `_validated_input`'s.""" + try: + resolved = gates.with_resolved_org(op, arguments, auth) + named = await gates.with_branch_name(op, resolved, auth) + except UnknownBranchError as e: + _emit_refused(op.name, arguments, error_code=e.code, request_id=request_id, error=e) + return _ok(req_id, refusal_result(e)) + return _validated_input( + req_id, op, named, request_id, toolset=toolset, include_example=include_example + ) + + def _validated_input( req_id: Any, op: Operation, diff --git a/server/transport/namespace_resolve.py b/server/transport/namespace_resolve.py index 029f64eea52..c777730ae05 100644 --- a/server/transport/namespace_resolve.py +++ b/server/transport/namespace_resolve.py @@ -9,6 +9,9 @@ ("clickhouse") or a code namespace without its prefix resolves to that repository's code namespace. The call runs there, and the result says so (`namespace_resolved`). +- `@` names the namespace that indexes that branch of + the repository (`resolve_branch`), on HTTP as on MCP. A branch the repository does + not index answers UNKNOWN_BRANCH with the branches the caller reads. - A code namespace named with a longer or shorter commit hash than the indexed one resolves the same way, when the caller reads exactly one such namespace (`revision_matches`). @@ -24,7 +27,7 @@ import difflib import re -from collections.abc import Iterable +from collections.abc import Awaitable, Callable, Iterable from contextvars import ContextVar from typing import Any @@ -92,6 +95,61 @@ def match(name: str, known: dict[str, str], *, default_branch: set[str] | None = _REVISION = re.compile(r"^(code-.+)-([0-9a-f]{7,40})$") +async def resolve_branch( + org: str, name: str, may_read: Callable[[str], Awaitable[bool]] +) -> str | None: + """The namespace `@` names, for a code call on + any transport. None when `name` is not that form, names no configured repository, + or the caller reads none of the repository's branches: the gate then refuses it + as the namespace it literally is. `@` is not a namespace character + (`server.core.naming`), so the form never collides with a name; a configured + namespace that does hold one (an operator entry is not checked against the rule) + is the name it spells, never a branch. + + A branch the repository does not index, or that the caller may not read, raises + UnknownBranchError naming the branches the caller reads: one answer for both, so + it confirms no branch the caller cannot read. The gate still authorizes the + namespace this returns.""" + from server.code.domain.index.repos import ( + RegistryUnread, + entry_repo_key, + repo_for_namespace, + repo_members, + ) + from server.core.errors import UnknownBranchError + + repository, sep, branch = name.partition("@") + repository, branch = repository.strip(), branch.strip() + if not (sep and repository and branch): + return None + try: + known = known_namespaces(org) + if name in known: # an operator entry is not checked against the name rule + return None + via = match(repository, known, default_branch=default_branches(org)) + cfg = repo_for_namespace(org, via) if via else None + if cfg is None: + return None + members = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) + except RegistryUnread: + return None + readable = [m for m in members if m.git_branch and await may_read(m.namespace)] + if not readable: + return None + hit = next((m for m in readable if m.git_branch == branch), None) + if hit is None: + names = [m.git_branch for m in readable] + raise UnknownBranchError( + f"{cfg.repo!r} indexes no branch {branch!r} that you can read. " + f"Readable branches: {', '.join(names)}.", + repository=cfg.repo, + branch=branch, + branches=names, + ) + RESOLVED.set({"from": name, "to": hit.namespace}) + return hit.namespace + + def revision_matches(name: str, known: Iterable[str]) -> list[str]: """The code namespaces `name` differs from only in the length of its commit hash: the same name up to a trailing hash of 7 to 40 hex characters, and diff --git a/tests/unit/test_backport_release_branch_names.py b/tests/unit/test_backport_release_branch_names.py index 9583c70d762..4eae79c4459 100644 --- a/tests/unit/test_backport_release_branch_names.py +++ b/tests/unit/test_backport_release_branch_names.py @@ -1,7 +1,7 @@ """A release-branch namespace whose git branch is named `release/26.9` (the private repository's convention) carries the version `26.9` for `code.backport_gap`, like the public `26.9` branch does: -such namespaces stay in `release_namespaces` (no empty version, no `unknown` / +such namespaces stay in the release set (no empty version, no `unknown` / `no_branch_version` verdict), and a bare `26.8` in `branches` resolves to its release branch instead of being refused as a namespace named `26.8`.""" @@ -29,7 +29,7 @@ def test_release_branch_names_parse_to_their_version() -> None: def _repos(): mk = lambda ns, repo, br: SimpleNamespace( # noqa: E731 - org="clickhouse", namespace=ns, repo=repo, git_branch=br + org="clickhouse", namespace=ns, repo=repo, git_remote="", git_branch=br ) return [ mk("code-clickhouse", "ClickHouse/ClickHouse", "master"), @@ -43,7 +43,7 @@ def _repos(): def test_private_release_namespaces_carry_their_version_newest_first() -> None: with patch("server.code.domain.index.repos.configured_repos", return_value=_repos()): - got = h.release_namespaces("clickhouse", "code-example-private") + got = h.resolve_branches("clickhouse", "code-example-private", []) assert got == [ ("code-example-private-26-9", "26.9"), ("code-example-private-26-8", "26.8"), @@ -51,7 +51,7 @@ def test_private_release_namespaces_carry_their_version_newest_first() -> None: ] # the public repository's set is untouched and never mixes repositories with patch("server.code.domain.index.repos.configured_repos", return_value=_repos()): - assert h.release_namespaces("clickhouse", "code-clickhouse") == [ + assert h.resolve_branches("clickhouse", "code-clickhouse", []) == [ ("code-clickhouse-26-8", "26.8") ] @@ -78,6 +78,7 @@ def test_another_orgs_entries_never_join_the_branch_set() -> None: org="acme", namespace="code-clickhouse", repo="ClickHouse/ClickHouse", + git_remote="", git_branch="master", git_dir="/acme/mirror", ), @@ -85,17 +86,18 @@ def test_another_orgs_entries_never_join_the_branch_set() -> None: org="acme", namespace="acme-26-3", repo="ClickHouse/ClickHouse", + git_remote="", git_branch="26.3", git_dir="/acme/mirror", ), ] ours = [SimpleNamespace(**{**vars(r), "git_dir": "/ours/mirror"}) for r in _repos()] with patch("server.code.domain.index.repos.configured_repos", return_value=other + ours): - assert h.release_namespaces("clickhouse", "code-clickhouse") == [ + assert h.resolve_branches("clickhouse", "code-clickhouse", []) == [ ("code-clickhouse-26-8", "26.8") ] git_dir, refs = h.branch_refs("clickhouse", "code-clickhouse") assert git_dir == "/ours/mirror" and refs == {"code-clickhouse-26-8": "26.8"} # a namespace this org does not configure has no branches, whoever else does - assert h.release_namespaces("nobody", "code-clickhouse") == [] + assert h.resolve_branches("nobody", "code-clickhouse", []) == [] assert h.branch_refs("nobody", "code-clickhouse") == ("", {}) diff --git a/tests/unit/test_code_backport_gap.py b/tests/unit/test_code_backport_gap.py index 54df5435d1d..1c1154655f5 100644 --- a/tests/unit/test_code_backport_gap.py +++ b/tests/unit/test_code_backport_gap.py @@ -172,6 +172,7 @@ def test_rank_summary_and_overall() -> None: class _Cfg: def __init__(self, ns: str, branch: str, repo: str = "ClickHouse/ClickHouse") -> None: self.org, self.namespace, self.git_branch, self.repo = ORG, ns, branch, repo + self.git_remote = "" @pytest.fixture @@ -188,7 +189,7 @@ def configured(monkeypatch: pytest.MonkeyPatch) -> None: def test_release_namespaces_are_the_same_repository_newest_first(configured) -> None: - got = h.release_namespaces(ORG, NS) + got = h.resolve_branches(ORG, NS, []) assert got[0] == ("code-clickhouse-26-8", "26.8") and got[-1] == ( "code-clickhouse-26-1", "26.1", diff --git a/tests/unit/test_code_backport_gap_exact.py b/tests/unit/test_code_backport_gap_exact.py index 6d4347bb639..0d7b3650d2c 100644 --- a/tests/unit/test_code_backport_gap_exact.py +++ b/tests/unit/test_code_backport_gap_exact.py @@ -382,6 +382,7 @@ def row(verdict: str, basis: str) -> bp.BranchVerdict: class _Cfg: def __init__(self, ns: str, branch: str, repo: str = "ClickHouse/ClickHouse") -> None: self.namespace, self.git_branch, self.repo, self.org = ns, branch, repo, ORG + self.git_remote = "" class _Repo: diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 81713bc4bbb..fdcfdb6dc54 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -48,6 +48,7 @@ class _Cfg: org: str = ORG repo: str = "ClickHouse/ClickHouse" git_dir: str = "var/code_repos/clickhouse.git" + git_remote: str = "" classification: str = "standard" source: str = "config" diff --git a/tests/unit/test_code_bisect_deadline.py b/tests/unit/test_code_bisect_deadline.py index 71782d27d05..16ad9159a1a 100644 --- a/tests/unit/test_code_bisect_deadline.py +++ b/tests/unit/test_code_bisect_deadline.py @@ -75,6 +75,7 @@ def test_a_slow_fix_blame_stops_at_the_deadline_not_its_own_budget( from server.code.app import blame as code_blame from server.code.app.index import gitrepo from server.code.domain.index import fix_blame as fb + from server.code.domain.index import repos class Repo: async def merge_commit_of(self, org: str, ns: str, pr: int) -> str: @@ -87,7 +88,7 @@ async def slow_blame(inp: Any) -> Any: await asyncio.sleep(30) monkeypatch.setattr(gitrepo, "run", run) - monkeypatch.setattr(code_blame, "repo_siblings", lambda org, ns: (None, None)) + monkeypatch.setattr(repos, "repo_for_namespace", lambda org, ns: None) monkeypatch.setattr(code_blame, "handle_code_blame_range", slow_blame) monkeypatch.setattr( fb, "pre_image_ranges", lambda diff: [SimpleNamespace(path="src/a.cpp", start=1, end=2)] diff --git a/tests/unit/test_mcp_session_runs.py b/tests/unit/test_mcp_session_runs.py index 52d6e03b7a7..fb2b1cf34c5 100644 --- a/tests/unit/test_mcp_session_runs.py +++ b/tests/unit/test_mcp_session_runs.py @@ -296,7 +296,7 @@ def test_call_tool_stamps_writes_only_and_binds_the_ledger_run() -> None: call = inspect.getsource(mcp_call._call_tool) stamp_at = call.index("_stamp_session_run(op, arguments, defaults, mcp_session_id)") - validate_at = call.index("_validated_input(") + validate_at = call.index("_named_input(") admitted_at = call.index("refused = await _admission_refusal(call)") begin_at = call.index("await _bind_session_run(op, defaults, mcp_session_id, run_caller)") handler_at = call.index("result = await op.handler(input_obj)") diff --git a/tests/unit/test_merge_shas.py b/tests/unit/test_merge_shas.py index 07b09d7ff2d..bd305ad0e0e 100644 --- a/tests/unit/test_merge_shas.py +++ b/tests/unit/test_merge_shas.py @@ -174,7 +174,7 @@ def _cand(n: int) -> bi.Candidate: @pytest.mark.asyncio async def test_bisect_candidates_carry_merge_shas(mirror, git_calls, monkeypatch) -> None: - monkeypatch.setattr(hb.cb, "repo_siblings", lambda org, ns: (_Cfg(mirror["git_dir"]), [])) + monkeypatch.setattr(hb, "repo_for_namespace", lambda org, ns: _Cfg(mirror["git_dir"])) ranked = [_cand(10), _cand(12), _cand(13), _cand(40)] await hb._attach_merge_shas(_Repo({40: "c" * 40}), "o", "n", ranked) out = { @@ -197,7 +197,7 @@ async def test_bisect_candidates_get_no_merge_sha_from_past_the_indexed_head( ) -> None: """The namespace indexes the merge of #10; the mirror's branch has since landed #12. The search runs from the indexed head, so the later landing is not found.""" - monkeypatch.setattr(hb.cb, "repo_siblings", lambda org, ns: (_Cfg(mirror["git_dir"]), [])) + monkeypatch.setattr(hb, "repo_for_namespace", lambda org, ns: _Cfg(mirror["git_dir"])) ranked = [_cand(10), _cand(12)] await hb._attach_merge_shas(_Repo({}, head=mirror["merge"]), "o", "n", ranked) assert [(c.merge_commit_sha, c.merge_sha_source) for c in ranked] == [ diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index 3439ae27f00..25a391b5698 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -675,7 +675,7 @@ async def pr_records_by_number(self, *_a: Any, **_k: Any) -> dict[int, Any]: return {} monkeypatch.setattr(bootstrap, "clone_and_pin", _clone) - monkeypatch.setattr(blame, "repo_siblings", lambda org, ns: (cfg, [cfg])) + monkeypatch.setattr(bisect, "repo_for_namespace", lambda org, ns: cfg) monkeypatch.setattr(blame, "diff_kind", _no_git) pool = [bi.Candidate(pr_number=1, title="a", author="", merged_at="", minor_version="")] _out, stage = await bisect._mark_stage(_Repo(), "o", "code-r", pool, frames=[], paths=["a.c"]) # type: ignore[arg-type] @@ -687,7 +687,8 @@ async def pr_records_by_number(self, *_a: Any, **_k: Any) -> dict[int, Any]: async def test_fix_blame_says_why_there_is_no_mirror_instead_of_a_git_error( monkeypatch, tmp_path ) -> None: - from server.code.app import bisect_fix, blame + from server.code.app import bisect_fix + from server.code.domain.index import repos cfg = _Cfg(str(tmp_path / "r.git")) @@ -699,7 +700,7 @@ async def merge_commit_of(self, *_a: Any) -> str: return "m" * 40 monkeypatch.setattr(bootstrap, "clone_and_pin", _clone) - monkeypatch.setattr(blame, "repo_siblings", lambda org, ns: (cfg, [cfg])) + monkeypatch.setattr(repos, "repo_for_namespace", lambda org, ns: cfg) _out, summary = await bisect_fix._fix_blame_stage(_Repo(), "o", "code-r", [], 5) # type: ignore[arg-type] assert summary["skipped"].startswith("no_git_mirror: o/code-r: clone failed") diff --git a/tests/unit/test_platform_admin_repository_read.py b/tests/unit/test_platform_admin_repository_read.py index 4cdfc3a3eb3..0f156cde721 100644 --- a/tests/unit/test_platform_admin_repository_read.py +++ b/tests/unit/test_platform_admin_repository_read.py @@ -169,7 +169,6 @@ async def test_admin_listing_returns_actual_heads_and_counts( repository[(ORG, NS)] = replace(repository[(ORG, NS)], classification=level) monkeypatch.setattr(repo_registry, "refresh_db_repos", AsyncMock(return_value=[])) - monkeypatch.setattr(repos, "docs_namespaces", lambda: {}) monkeypatch.setattr(listing.CodeRepo, "all_state_many", AsyncMock(return_value={})) monkeypatch.setattr( listing, diff --git a/tests/unit/test_pr_post_image.py b/tests/unit/test_pr_post_image.py index 0f87c01ae09..53cbe28aa1a 100644 --- a/tests/unit/test_pr_post_image.py +++ b/tests/unit/test_pr_post_image.py @@ -296,7 +296,7 @@ def test_blame_without_history_says_there_is_no_git_history( monkeypatch.setattr(settings, "git_history", "none") monkeypatch.setattr(blame, "require_code_intel", lambda: None) monkeypatch.setattr(blame, "resolve_code_identity", lambda o, n: ("acme", "code-ch")) - monkeypatch.setattr(blame, "repo_siblings", lambda o, n: (None, [])) + monkeypatch.setattr(blame, "repo_for_namespace", lambda o, n: None) monkeypatch.setattr(blame, "CodeRepo", lambda: object()) out = asyncio.run( blame.handle_code_blame_range(CodeBlameRangeInput(path=PATH, start_line=1, end_line=5)) diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py new file mode 100644 index 00000000000..f2f3ba6428b --- /dev/null +++ b/tests/unit/test_repo_at_branch.py @@ -0,0 +1,485 @@ +"""A code call names a branch as `@`. + +HTTP and MCP resolve the form alike, before the gate: the gate then authorizes the +namespace the name resolves to, as it authorizes any other. A branch the repository +does not index, or the caller cannot read, answers UNKNOWN_BRANCH and names the branches +the caller can read. `repo_members` is the one derivation of a repository's entries: the +docs namespace, the release set and the history siblings read it, and each answers as +the derivation it replaced. +""" + +from __future__ import annotations + +import asyncio +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient +from pydantic import BaseModel + +import server.auth.bearer as bearer_mod +import server.transport.mcp_call as mcp_call +import server.transport.mcp_outcome as mcp_outcome +from server.auth.jwt import AuthInfo, TokenError +from server.code.domain.index import repos +from server.operations.base import Operation, Role +from server.operations.registry import OPERATIONS_BY_NAME +from server.settings import settings +from server.settings.catalog import OP_BUDGETS_P99_MS +from server.transport import gates +from server.transport import namespace_resolve as nr +from tests.unit.code_fixtures import repo_config + +ORG = "acme" + + +def _entry(ns: str, repo: str, branch: str, **kw: Any) -> repos.RepoConfig: + return repo_config(org=kw.pop("org", ORG), namespace=ns, repo=repo, git_branch=branch, **kw) + + +ENTRIES = [ + _entry("code-kj-26-7", "Acme/kj", "26.7", git_dir="/m/kj"), + _entry("code-kj-26-10", "Acme/kj", "26.10", git_dir="/m/kj"), + _entry("code-kj", "Acme/kj", "master", git_dir="/m/kj"), + _entry("code-other", "Acme/other", "main", git_dir="/m/other"), + _entry("code-kj", "Acme/kj", "master", org="elsewhere", git_dir="/e/kj"), +] + + +@pytest.fixture(autouse=True) +def _registry(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(repos, "configured_repos", lambda: list(ENTRIES)) + monkeypatch.setattr("server.tracker.domain.namespaces.configured_namespaces", lambda: {}) + + +def _readable(unreadable: set[str] = frozenset()): # type: ignore[assignment] + async def may_read(ns: str) -> bool: + return ns not in unreadable + + return may_read + + +def _resolve(name: str, unreadable: set[str] = frozenset()) -> str | None: # type: ignore[assignment] + return _resolved(name, unreadable)[0] + + +def _resolved(name: str, unreadable: set[str] = frozenset()) -> tuple[str | None, Any]: # type: ignore[assignment] + """(the namespace, the note the resolution left): both read in the task that set it.""" + + async def run() -> tuple[str | None, Any]: + nr.RESOLVED.set(None) + got = await nr.resolve_branch(ORG, name, _readable(unreadable)) + return got, nr.RESOLVED.get() + + return asyncio.run(run()) + + +def _unknown_branch(name: str, unreadable: set[str] = frozenset()) -> Any: # type: ignore[assignment] + from server.core.errors import UnknownBranchError + + with pytest.raises(UnknownBranchError) as e: + _resolve(name, unreadable) + return e.value + + +# ------------------------------------------------------------------ the resolver + + +@pytest.mark.parametrize( + ("name", "want"), + [ + ("Acme/kj@26.7", "code-kj-26-7"), # the repository + ("acme/kj@26.10", "code-kj-26-10"), + ("kj@master", "code-kj"), # its name + ("code-kj@26.7", "code-kj-26-7"), # a namespace of it, any branch's + ("code-kj-26-10@master", "code-kj"), + (" kj @ 26.7 ", "code-kj-26-7"), + ], +) +def test_a_repository_or_namespace_with_a_branch_names_that_branchs_namespace( + name: str, want: str +) -> None: + assert _resolved(name) == (want, {"from": name, "to": want}) + + +@pytest.mark.parametrize( + "name", ["kj", "code-kj", "@me", "@26.7", "kj@", "kj@ ", "nosuch@master", "memory-ns@x"] +) +def test_a_name_that_is_no_branch_of_a_repository_is_left_for_the_gate(name: str) -> None: + assert _resolve(name) is None + + +def test_a_configured_namespace_that_holds_an_at_sign_is_the_name_it_spells( + monkeypatch: pytest.MonkeyPatch, +) -> None: + odd = _entry("code-kj@26.7", "Acme/odd", "main", git_dir="/m/odd") + monkeypatch.setattr(repos, "configured_repos", lambda: [*ENTRIES, odd]) + assert _resolve("code-kj@26.7") is None + assert _resolve("kj@26.7") == "code-kj-26-7" + + +def test_the_branches_of_another_org_never_resolve() -> None: + from server.core.errors import UnknownBranchError + + assert asyncio.run(nr.resolve_branch("elsewhere", "kj@master", _readable())) == "code-kj" + with pytest.raises(UnknownBranchError) as e: # that org indexes the repository's trunk only + asyncio.run(nr.resolve_branch("elsewhere", "kj@26.7", _readable())) + assert e.value.extra["branches"] == ["master"] + + +def test_an_unindexed_branch_names_the_branches_the_caller_can_read() -> None: + err = _unknown_branch("Acme/kj@26.9") + assert err.code == "UNKNOWN_BRANCH" and err.status_code == 404 + assert err.extra["repository"] == "Acme/kj" and err.extra["branch"] == "26.9" + assert err.extra["branches"] == ["master", "26.10", "26.7"] # the page's branch order + assert "26.9" in err.message and "master, 26.10, 26.7" in err.message + + +def test_a_branch_the_caller_cannot_read_is_refused_as_an_unindexed_one() -> None: + """One answer for both: a branch the caller cannot read is not confirmed to exist, and + is not listed.""" + hidden = {"code-kj-26-7"} + unreadable = _unknown_branch("kj@26.7", hidden) + unindexed = _unknown_branch("kj@26.9", hidden) + assert unreadable.extra["branches"] == unindexed.extra["branches"] == ["master", "26.10"] + assert unreadable.message.replace("26.7", "X") == unindexed.message.replace("26.9", "X") + + +def test_a_repository_the_caller_reads_no_branch_of_is_left_for_the_gate_to_refuse() -> None: + everything = {"code-kj", "code-kj-26-7", "code-kj-26-10"} + assert _resolve("kj@26.7", everything) is None + + +def test_a_registry_not_yet_read_resolves_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + def unread() -> list[Any]: + raise repos.RegistryUnread("not read") + + monkeypatch.setattr(repos, "configured_repos", unread) + assert _resolve("kj@26.7") is None + + +# ------------------------------------------------------------------ repo_members + + +def test_repo_members_lists_one_repository_of_one_org_in_the_pages_branch_order() -> None: + key = repos.entry_repo_key("Acme/kj", "") + got = repos.repo_members(ORG, key) + assert [c.namespace for c in got] == ["code-kj", "code-kj-26-10", "code-kj-26-7"] + assert [c.namespace for c in repos.repo_members("elsewhere", key)] == ["code-kj"] + assert repos.repo_members(ORG, repos.entry_repo_key("Acme/nope", "")) == [] + # a snapshot handed in is the one read + assert repos.repo_members(ORG, key, ENTRIES[:1]) == ENTRIES[:1] + + +# ------------------------------------------------------------------ both transports + + +class _In(BaseModel): + org: str = "" + namespace: str = "" + + +class _Out(BaseModel): + ok: bool = True + + +TOOL = "loom_code_test_branch_probe" + + +@pytest.fixture +def probe(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """One code op on both transports; the gate records the (org, namespace) it + authorizes and refuses subject "intruder"; the read check refuses `unreadable`.""" + import server.code.app.member_writes as member_writes + from server.transport import http as http_mod + + seen: dict[str, Any] = {"authz": [], "ran": [], "ledger": [], "unreadable": set()} + + async def _handler(inp: Any) -> _Out: + seen["ran"].append(inp.namespace) + return _Out() + + op = Operation( + name="code.test_branch_probe", + input_model=_In, + output_model=_Out, + handler=_handler, + idempotent=False, + required_role=Role.VIEWER, + ) + + async def _authorize_op(auth: Any, op_: Any, *, org: Any, namespace: Any, **_k: Any) -> None: + seen["authz"].append((org, namespace)) + if auth.subject == "intruder": + raise PermissionError("not a member") + + async def _may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + return ns not in seen["unreadable"], False + + async def _noop(*_a: Any, **_k: Any) -> None: + return None + + tokens = { + "alice": AuthInfo( + subject="alice", + org=ORG, + namespaces=("*",), + roles=(Role.WRITER,), + is_service_account=True, + ), + "intruder": AuthInfo( + subject="intruder", + org=ORG, + namespaces=("*",), + roles=(Role.WRITER,), + is_service_account=True, + ), + } + + def _verify(token: str) -> AuthInfo: + if token not in tokens: + raise TokenError("bad token") + return tokens[token] + + monkeypatch.setattr(member_writes, "authorize_op", _authorize_op) + monkeypatch.setattr(gates, "may_read", _may_read, raising=False) + monkeypatch.setattr("server.transport.gates._admitted", _noop) + monkeypatch.setattr("server.auth.personal_namespace.ensure_personal_namespace_cached", _noop) + monkeypatch.setattr(settings, "code_org", ORG) + monkeypatch.setattr(settings, "code_namespace", "code-kj") + monkeypatch.setattr(settings, "auth_required", True) + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(http_mod, "ALL_OPERATIONS", [op]) + monkeypatch.setitem(OP_BUDGETS_P99_MS, op.name, 10_000) + monkeypatch.setattr(bearer_mod, "authenticate_token", AsyncMock(side_effect=_verify)) + monkeypatch.setattr( + http_mod, "_emit_event", lambda *a, **k: seen["ledger"].append(("http", k["error_code"])) + ) + app = FastAPI() + app.include_router(http_mod.build_router()) + seen["http"] = TestClient(app) + seen["tokens"] = tokens + monkeypatch.setitem(mcp_call.TOOLS_BY_NAME, TOOL, op) + + async def _no_defaults(auth: Any, client_name: str | None = None) -> None: + return None + + monkeypatch.setattr(mcp_call, "_caller_defaults", _no_defaults) + for mod in (mcp_call, mcp_outcome): + monkeypatch.setattr( + mod, + "_emit_mcp_event", + lambda *a, **k: seen["ledger"].append(("mcp", k.get("error_code", ""))), + ) + return seen + + +def _http(seen: dict[str, Any], who: str, namespace: str) -> Any: + return seen["http"].post( + "/v1/code.test_branch_probe", + json={"org": ORG, "namespace": namespace}, + headers={"Authorization": f"Bearer {who}"}, + ) + + +def _mcp(seen: dict[str, Any], who: str, namespace: str) -> dict[str, Any]: + params = {"name": TOOL, "arguments": {"org": ORG, "namespace": namespace}} + return asyncio.run(mcp_call._call_tool(1, params, auth=seen["tokens"][who]))["result"] # type: ignore[no-any-return] + + +def test_both_transports_authorize_and_run_on_the_namespace_a_branch_name_resolves_to( + probe: dict[str, Any], +) -> None: + r = _http(probe, "alice", "Acme/kj@26.7") + assert r.status_code == 200, r.text + out = _mcp(probe, "alice", "Acme/kj@26.7") + assert out["isError"] is False + want = (ORG, "code-kj-26-7") + assert probe["authz"] == [want, want] + assert probe["ran"] == ["code-kj-26-7", "code-kj-26-7"] + + +def test_the_gate_still_refuses_the_resolved_namespace_to_a_caller_it_does_not_admit( + probe: dict[str, Any], +) -> None: + r = _http(probe, "intruder", "kj@26.7") + assert r.status_code == 403 and r.json()["detail"]["code"] == "AUTH_INSUFFICIENT" + out = _mcp(probe, "intruder", "kj@26.7") + assert out["isError"] and out["structuredContent"]["code"] == "AUTH_INSUFFICIENT" + assert probe["authz"] == [(ORG, "code-kj-26-7")] * 2 # the namespace it names, not the form + assert probe["ran"] == [] + + +def test_an_unreadable_or_unindexed_branch_is_refused_before_the_gate_on_both( + probe: dict[str, Any], +) -> None: + probe["unreadable"] = {"code-kj-26-7"} + for name in ("kj@26.7", "kj@26.9"): + r = _http(probe, "alice", name) + detail = r.json()["detail"] + assert r.status_code == 404 and detail["code"] == "UNKNOWN_BRANCH", r.text + assert detail["branches"] == ["master", "26.10"] + out = _mcp(probe, "alice", name) + assert out["isError"] and out["structuredContent"]["code"] == "UNKNOWN_BRANCH" + assert out["structuredContent"]["branches"] == ["master", "26.10"] + assert probe["authz"] == [] and probe["ran"] == [] + assert probe["ledger"] == [("http", "UNKNOWN_BRANCH"), ("mcp", "UNKNOWN_BRANCH")] * 2 + + +def test_a_name_that_is_no_branch_form_reaches_the_gate_as_given(probe: dict[str, Any]) -> None: + for name in ("code-kj", "nosuch@master"): + _http(probe, "alice", name) + _mcp(probe, "alice", name) + assert probe["authz"] == [ + (ORG, "code-kj"), + (ORG, "code-kj"), + (ORG, "nosuch@master"), + (ORG, "nosuch@master"), + ] + + +def test_only_a_code_op_reads_the_form() -> None: + args = {"org": ORG, "namespace": "kj@26.7"} + for name, want in ( + ("code.search", "code-kj-26-7"), + ("memory.search", "kj@26.7"), + ("tracker.item", "kj@26.7"), + ): + got = asyncio.run(gates.with_branch_name(OPERATIONS_BY_NAME[name], args, None)) + assert got["namespace"] == want, name + assert args["namespace"] == "kj@26.7" # a copy + + +# ------------------------------------------------------------------ the MCP screen + + +class _Auth: + org = ORG + subject = "sa:agent-x" + + def can_access(self, org: str, ns: str) -> bool: + return True + + +def _screen(monkeypatch: pytest.MonkeyPatch, tool: str, namespace: str, unreadable: set[str]): # type: ignore[no-untyped-def] + from server.transport import mcp_auth + + async def may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + return ns not in unreadable, False + + monkeypatch.setattr(gates, "may_read", may_read, raising=False) + args = {"namespace": namespace, "query": "q"} + req = { + "jsonrpc": "2.0", + "id": 7, + "method": "tools/call", + "params": {"name": tool, "arguments": args}, + } + + async def run() -> tuple[Any, Any]: + refused = await mcp_auth._screen_tool_call(req, _Auth()) # type: ignore[arg-type] + return refused, nr.RESOLVED.get() + + refused, note = asyncio.run(run()) + return refused, args, note + + +def test_the_mcp_screen_rewrites_a_branch_name_and_notes_the_resolution( + monkeypatch: pytest.MonkeyPatch, +) -> None: + refused, args, note = _screen(monkeypatch, "loom_code_search", "Acme/kj@26.10", set()) + assert refused is None and args["namespace"] == "code-kj-26-10" + assert note == {"from": "Acme/kj@26.10", "to": "code-kj-26-10"} + + +def test_the_mcp_screen_answers_unknown_branch_for_an_unreadable_or_unindexed_one( + monkeypatch: pytest.MonkeyPatch, +) -> None: + for name in ("kj@26.7", "kj@26.9"): + refused, args, _ = _screen(monkeypatch, "loom_code_search", name, {"code-kj-26-7"}) + assert refused is not None and refused["id"] == 7 + body = refused["result"]["structuredContent"] + assert body["code"] == "UNKNOWN_BRANCH" and body["branches"] == ["master", "26.10"] + assert args["namespace"] == name # nothing was rewritten + + +def test_the_mcp_screen_leaves_a_tracker_tool_alone(monkeypatch: pytest.MonkeyPatch) -> None: + refused, args, note = _screen(monkeypatch, "loom_tracker_search", "kj@26.7", set()) + assert args["namespace"] == "kj@26.7" and note is None + assert refused is None # the form is a code call's: the tracker gate reads the name as given + + +# ------------------------------------------------------------------ the callers keep their answers +# +# The three derivations `repo_members` replaced, as they were: each caller's answer on one +# configuration must equal theirs. + + +def _was_docs_namespaces(entries: list[Any]) -> dict[tuple[str, str], str]: + best: dict[tuple[str, str], Any] = {} + for c in entries: + key = (c.org, c.repo) + rank = (repos._trunk_rank(str(c.git_branch or "")), c.namespace) + cur = best.get(key) + if cur is None or rank < (repos._trunk_rank(str(cur.git_branch or "")), cur.namespace): + best[key] = c + return {k: c.namespace for k, c in best.items()} + + +def _was_release_namespaces(entries: list[Any], org: str, ns: str) -> list[tuple[str, str]]: + from server.tracker.domain import backport as bp + + me = next((c for c in entries if (c.org, c.namespace) == (org, ns)), None) + if me is None: + return [] + out = [] + for r in entries: + if r.org != org or r.namespace == ns or r.repo != me.repo: + continue + v = bp.version_key(r.git_branch) + if v is not None: + 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 _was_repo_siblings(entries: list[Any], org: str, ns: str) -> list[str]: + mine = next((c for c in entries if (c.org, c.namespace) == (org, ns)), None) + if mine is None: + return [] + return sorted(c.namespace for c in entries if c.org == org and c.git_dir == mine.git_dir) + + +def test_the_docs_namespace_the_release_set_and_the_siblings_answer_as_they_did() -> None: + from server.code.app import backport, memory_links, repo_scope + + entries = [ + *ENTRIES, + _entry("code-w-dev", "Acme/w", "dev", git_dir="/m/w"), + _entry("code-w-26-1", "Acme/w", "26.1", git_dir="/m/w"), + _entry("code-w-26-3", "Acme/w", "release/26.3", git_dir="/m/w"), + _entry("code-z-b", "Acme/z", "beta", git_dir="/m/z"), + _entry("code-z-a", "Acme/z", "alpha", git_dir="/m/z"), + _entry("code-w-elsewhere", "Acme/w", "26.9", org="elsewhere", git_dir="/e/w"), + ] + docs = _was_docs_namespaces(entries) + ENTRIES_BEFORE = list(ENTRIES) + ENTRIES[:] = entries + try: + for c in entries: + assert repo_scope.trunk_namespace_of(c.org, c.namespace) == docs[(c.org, c.repo)] + assert memory_links.trunk_namespace(c.org, c.namespace) == docs[(c.org, c.repo)] + assert ( + backport.resolve_branches(c.org, c.namespace, []) + == _was_release_namespaces(entries, c.org, c.namespace)[: backport.MAX_BRANCHES] + ) + key = repos.entry_repo_key(c.repo, c.git_remote) + assert sorted(m.namespace for m in repos.repo_members(c.org, key)) == ( + _was_repo_siblings(entries, c.org, c.namespace) + ) + assert repo_scope.trunk_namespace_of(ORG, "code-nosuch") == "" + assert backport.resolve_branches(ORG, "code-nosuch", []) == [] + finally: + ENTRIES[:] = ENTRIES_BEFORE diff --git a/tests/unit/test_repo_docs.py b/tests/unit/test_repo_docs.py index d693476b0ca..1156a1de2cb 100644 --- a/tests/unit/test_repo_docs.py +++ b/tests/unit/test_repo_docs.py @@ -26,7 +26,12 @@ def _cfg(ns: str, repo: str, branch: str) -> Any: - return SimpleNamespace(org=ORG, namespace=ns, repo=repo, git_branch=branch) + return SimpleNamespace(org=ORG, namespace=ns, repo=repo, git_remote="", git_branch=branch) + + +def _docs_namespace(repo: str) -> str: + """The first of the repository's members: the namespace its documents live in.""" + return repos.repo_members(ORG, repos.entry_repo_key(repo, ""))[0].namespace ENTRIES = [ @@ -81,18 +86,16 @@ def _repos(monkeypatch): def test_the_docs_namespace_is_the_trunk_branchs_the_page_order() -> None: - assert repos.docs_namespaces() == { - (ORG, "Acme/kj"): "code-kj", # master first - (ORG, "Acme/w"): "code-w-26-1", # then release branches, newest first - (ORG, "Acme/z"): "code-z-a", # then by name - } + assert _docs_namespace("Acme/kj") == "code-kj" # master first + assert _docs_namespace("Acme/w") == "code-w-26-1" # then release branches, newest first + assert _docs_namespace("Acme/z") == "code-z-a" # then by name # every branch of a repository reads one namespace, its trunk's trunk = repo_scope.trunk_namespace_of(ORG, "code-kj-26-7") assert trunk == "code-kj" assert repo_scope.trunk_namespace_of(ORG, "memory-ns") == "" ENTRIES.append(_cfg("code-kj-27-1", "Acme/kj", "27.1")) try: - assert repos.docs_namespaces()[(ORG, "Acme/kj")] == "code-kj" + assert _docs_namespace("Acme/kj") == "code-kj" assert repos._trunk_rank("26.10") < repos._trunk_rank("26.7") # numeric, not lexical finally: ENTRIES.pop() diff --git a/tests/unit/test_sdk_errors_from_response.py b/tests/unit/test_sdk_errors_from_response.py index 615825e10ff..f94d3fd20b3 100644 --- a/tests/unit/test_sdk_errors_from_response.py +++ b/tests/unit/test_sdk_errors_from_response.py @@ -124,6 +124,7 @@ def test_a_5xx_is_backend_unavailable_and_a_429_rate_limited_whatever_the_code() "AUTH_INSUFFICIENT": AuthInsufficient, "IDENTITY_INCOMPLETE": ValidationError, "RESOURCE_NOT_FOUND": NotFound, + "UNKNOWN_BRANCH": NotFound, # a 404 with no SDK class: mapped by status "PRECONDITION_FAILED": PreconditionFailed, "GRANT_WOULD_DOWNGRADE": PreconditionFailed, "READS_LLM_FREE": PreconditionFailed, From 33f2a9b33ac087df29565c8c57dae343965d2cb1 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:45:21 +0000 Subject: [PATCH 02/10] A call named as `repo@branch` is ledgered under the namespace it ran on Both transports resolved the branch name into a copy of the arguments, so the request identity, the ledger rows and the gates that read the raw body named the text the caller wrote instead of the namespace that served the call. Those rows fell outside the namespace's activity, usage and erasure. HTTP now writes the resolved name into the raw body, as `@me` is written, and MCP writes it into the call's arguments, as the screen does. A unit test reads the rows both transports hand the event writer, and an integration test finds them with an erasure export of the namespace. Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Opus 5.5 --- server/transport/http.py | 14 +++-- server/transport/mcp_call.py | 23 +++++--- .../test_repo_at_branch_ledger_live_ch.py | 52 +++++++++++++++++++ tests/unit/test_repo_at_branch.py | 32 ++++++++++++ 4 files changed, 108 insertions(+), 13 deletions(-) create mode 100644 tests/integration/test_repo_at_branch_ledger_live_ch.py diff --git a/server/transport/http.py b/server/transport/http.py index b0b2af88b22..f4e595f0fce 100644 --- a/server/transport/http.py +++ b/server/transport/http.py @@ -373,9 +373,11 @@ def _validate_payload(op: Operation, request_id: str, raw_body: Any, auth: AuthI async def _resolve_branch_name( op: Operation, call: _HttpCall, args: dict[str, Any] ) -> dict[str, Any]: - """The arguments with a `@` namespace resolved - (`gates.with_branch_name`); a branch the caller cannot read is a 404 - UNKNOWN_BRANCH naming those it can.""" + """The body with a `@` namespace resolved + (`gates.with_branch_name`), as `_resolve_personal` resolves `@me`: the request + identity, the ledger rows and the gates after validation read the namespace the + call runs on. A branch the caller cannot read is a 404 UNKNOWN_BRANCH naming those + it can.""" try: return await gates.with_branch_name(op, args, call.auth) except UnknownBranchError as e: @@ -828,8 +830,10 @@ async def endpoint(request: Request, response: Response) -> Any: body = await _read_body(op, request, request_id, auth) call.raw_body = raw_body = await gates.with_single_user_identity(op, body, auth) - args = await _resolve_branch_name(op, call, gates.with_resolved_org(op, raw_body, auth)) - payload = _validate_payload(op, request_id, args, auth) + call.raw_body = raw_body = await _resolve_branch_name(op, call, raw_body) + payload = _validate_payload( + op, request_id, gates.with_resolved_org(op, raw_body, auth), auth + ) payload, raw_body = _resolve_personal(op, call, payload, raw_body, auth) call.raw_body = raw_body diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index 1ab259b2c77..4b3c9b27414 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -792,19 +792,26 @@ async def _named_input( toolset: str | None = None, include_example: bool = True, ) -> BaseModel | dict[str, Any]: - """Phase 4 of `_call_tool` on the arguments as the gate reads them - (`gates.with_resolved_org`) with a `@` namespace resolved to - its branch's (`gates.with_branch_name`, as HTTP does). Returns the input model, or - the refusal response: UNKNOWN_BRANCH for a branch the caller cannot read, else - `_validated_input`'s.""" + """Phase 4 of `_call_tool` with a `@` namespace resolved to + its branch's (`gates.with_branch_name`, as HTTP does), on the arguments as the gate + reads them (`gates.with_resolved_org`). The resolved name is written into + `arguments`, as the screen writes it, so the ledger and admission rows name the + namespace the call runs on. Returns the input model, or the refusal response: + UNKNOWN_BRANCH for a branch the caller cannot read, else `_validated_input`'s.""" try: - resolved = gates.with_resolved_org(op, arguments, auth) - named = await gates.with_branch_name(op, resolved, auth) + named = await gates.with_branch_name(op, arguments, auth) except UnknownBranchError as e: _emit_refused(op.name, arguments, error_code=e.code, request_id=request_id, error=e) return _ok(req_id, refusal_result(e)) + if named is not arguments: + arguments["namespace"] = named["namespace"] return _validated_input( - req_id, op, named, request_id, toolset=toolset, include_example=include_example + req_id, + op, + gates.with_resolved_org(op, arguments, auth), + request_id, + toolset=toolset, + include_example=include_example, ) diff --git a/tests/integration/test_repo_at_branch_ledger_live_ch.py b/tests/integration/test_repo_at_branch_ledger_live_ch.py new file mode 100644 index 00000000000..ccb74f839b6 --- /dev/null +++ b/tests/integration/test_repo_at_branch_ledger_live_ch.py @@ -0,0 +1,52 @@ +"""A code call that names a branch as `@` is ledgered under the +namespace it ran on, on live ClickHouse: an erasure export of that namespace finds the rows +both transports wrote, and one of the name as written finds none. + +Skips cleanly when LOOM_CH_HOST is unset. +""" + +from __future__ import annotations + +import asyncio +import os +from typing import Any + +import pytest + +from tests.unit.test_repo_at_branch import ORG, _registry, ledgered_rows, probe + +__all__ = ["_registry", "probe"] # the unit file's fixtures, used here + +pytestmark = pytest.mark.skipif( + not os.environ.get("LOOM_CH_HOST"), + reason="LOOM_CH_HOST not set — integration tests require a live CH", +) + + +def test_an_erasure_of_the_resolved_namespace_finds_the_rows_of_a_branch_named_call( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + from server.core.ch import get_client + from server.erasure.store.exports import export_agent_events + + rows = ledgered_rows(probe, monkeypatch, "Acme/kj@26.7") + ids = {e.request_id for e in rows} + assert len(ids) == 2 + + async def run() -> tuple[set[str], set[str]]: + ch = get_client() + await ch.connect() + try: + # As the event writer flushes them. + await ch.insert( + "loom.agent_events", [e.to_row() for e in rows], settings={"async_insert": 0} + ) + found = await export_agent_events(ORG, "namespace", "code-kj-26-7", limit=10**6, ch=ch) + named = await export_agent_events(ORG, "namespace", "Acme/kj@26.7", limit=10**6, ch=ch) + finally: + await ch.disconnect() + return {r["request_id"] for r in found}, {r["request_id"] for r in named} + + found, named = asyncio.run(run()) + assert ids <= found + assert not ids & named diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py index f2f3ba6428b..f15ef208bfd 100644 --- a/tests/unit/test_repo_at_branch.py +++ b/tests/unit/test_repo_at_branch.py @@ -254,6 +254,7 @@ def _verify(token: str) -> AuthInfo: monkeypatch.setattr(http_mod, "ALL_OPERATIONS", [op]) monkeypatch.setitem(OP_BUDGETS_P99_MS, op.name, 10_000) monkeypatch.setattr(bearer_mod, "authenticate_token", AsyncMock(side_effect=_verify)) + seen["http_emit"] = http_mod._emit_event # the ledger writer, for a test that reads its rows monkeypatch.setattr( http_mod, "_emit_event", lambda *a, **k: seen["ledger"].append(("http", k["error_code"])) ) @@ -301,6 +302,37 @@ def test_both_transports_authorize_and_run_on_the_namespace_a_branch_name_resolv assert probe["ran"] == ["code-kj-26-7", "code-kj-26-7"] +def ledgered_rows(probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch, name: str) -> list[Any]: + """The ledger rows of one served call on each transport that names `name`, as the + transports hand them to the event writer.""" + from server.observability import ledger + from server.transport import http as http_mod + from server.transport import mcp_tools + + rows: list[Any] = [] + monkeypatch.setattr(http_mod, "_emit_event", probe["http_emit"]) + for mod in (mcp_call, mcp_outcome): + monkeypatch.setattr(mod, "_emit_mcp_event", mcp_tools._emit_mcp_event) + monkeypatch.setattr(ledger, "_dispatch_event", lambda e: rows.append(e) or True) + assert _http(probe, "alice", name).status_code == 200 + assert _mcp(probe, "alice", name)["isError"] is False + return [e for e in rows if e.operation == "code.test_branch_probe"] + + +def test_a_served_call_is_ledgered_under_the_namespace_it_ran_on( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """The identity tuple of the row is the namespace the call ran on, so the namespace's + activity, usage and erasure reach it; the branch name the caller wrote is nowhere in + it.""" + rows = ledgered_rows(probe, monkeypatch, "Acme/kj@26.7") + assert [(e.transport, e.org, e.namespace, e.success) for e in rows] == [ + ("http", ORG, "code-kj-26-7", True), + ("mcp", ORG, "code-kj-26-7", True), + ] + assert all("Acme/kj@26.7" not in e.args.values() for e in rows) + + def test_the_gate_still_refuses_the_resolved_namespace_to_a_caller_it_does_not_admit( probe: dict[str, Any], ) -> None: From d3a6a7fa59fca2c960ec7d9a9e293538ceca937a Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:51:18 +0000 Subject: [PATCH 03/10] A branch whose read check could not run is refused as the server's failure The resolver kept only whether each branch's read check allowed it, so a check refused because a read it needed failed made a branch the caller may read look absent: the call answered UNKNOWN_BRANCH, the caller's error, and dropped that branch from the list it named. The resolver now reads the check's `unverified` flag, as the screen's repository resolver does. When the branch asked for was not admitted and any check could not run, it raises the gate's refusal marked unverified and notes the request as the server's; each transport answers it as its gate answers a failed check. Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Opus 5.5 --- server/transport/gates.py | 7 +- server/transport/http.py | 7 +- server/transport/mcp_auth.py | 14 +++- server/transport/mcp_call.py | 10 ++- server/transport/namespace_resolve.py | 24 +++++-- tests/unit/test_repo_at_branch.py | 93 ++++++++++++++++++++++++--- 6 files changed, 133 insertions(+), 22 deletions(-) diff --git a/server/transport/gates.py b/server/transport/gates.py index 6d95fbc428c..5c4c48945be 100644 --- a/server/transport/gates.py +++ b/server/transport/gates.py @@ -210,7 +210,8 @@ async def with_branch_name( (`namespace_resolve.resolve_branch`), so HTTP and MCP resolve it alike before the gate authorizes the namespace it names, as it authorizes any other. A name that is not that form, or names no repository, is left for the gate to refuse. - Raises UnknownBranchError for a branch the caller cannot read. A copy.""" + Raises UnknownBranchError for a branch the caller cannot read, and the gate's + PermissionError, marked `unverified`, when a read check could not run. A copy.""" name = args.get("namespace") if not (isinstance(name, str) and "@" in name and op.name.startswith("code.")): return args @@ -219,8 +220,8 @@ async def with_branch_name( return args from server.transport import namespace_resolve as nr - async def readable(ns: str) -> bool: - return auth is None or (await may_read(auth, org, ns))[0] + async def readable(ns: str) -> tuple[bool, bool]: + return (True, False) if auth is None else await may_read(auth, org, ns) resolved = await nr.resolve_branch(org, name.strip(), readable) return {**args, "namespace": resolved} if resolved else args diff --git a/server/transport/http.py b/server/transport/http.py index f4e595f0fce..d86b0bf7833 100644 --- a/server/transport/http.py +++ b/server/transport/http.py @@ -377,11 +377,16 @@ async def _resolve_branch_name( (`gates.with_branch_name`), as `_resolve_personal` resolves `@me`: the request identity, the ledger rows and the gates after validation read the namespace the call runs on. A branch the caller cannot read is a 404 UNKNOWN_BRANCH naming those - it can.""" + it can; a read check that could not run is the gate's 403 for a failed check.""" try: return await gates.with_branch_name(op, args, call.auth) except UnknownBranchError as e: raise _refuse(op, call, e.status_code, error_code=e.code, e=e, detail=e.extra) from e + except PermissionError as e: + # Refused as `_authorize` refuses a code index whose check could not run: the + # server's failure, worth a retry, never a branch that is not there. + why = ar.reason_fields(str(args.get("namespace") or ""), unverified=True) + raise _refuse(op, call, 403, error_code=gates.ROLE_REFUSAL_CODE, e=e, detail=why) from e except LoomServerError as e: # A read the check could not make past its cache (a 503): counted against the # server, then answered as raised. diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index 352052b0854..a34b8513419 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -468,14 +468,15 @@ async def _branch_namespace( """For a code tool's `namespace` spelled `@` (as `gates.with_branch_name` reads it on every transport): the namespace of that branch, written into `args`; the UNKNOWN_BRANCH result, ledgered, for a branch the - caller cannot read; None for any other name.""" + caller cannot read; the refusal of the name given, ledgered as the server's, when + a read check could not run; None for any other name.""" from server.transport import namespace_resolve as nr if "@" not in req_ns or not str(tool_name or "").startswith("loom_code_"): return None - async def readable(ns: str) -> bool: - return (await _may_read(auth, target_org, ns))[0] + async def readable(ns: str) -> tuple[bool, bool]: + return await _may_read(auth, target_org, ns) try: to = await nr.resolve_branch(target_org, req_ns.strip(), readable) @@ -484,6 +485,13 @@ async def readable(ns: str) -> bool: _ledger_refusal(tool_name, auth, error_code=e.code, org=target_org, consumer=consumer) return _ok(req.get("id"), refusal_result(e)) + except PermissionError: + refusal = _not_accessible_result(tool_name, auth, req_ns, unverified=True) + code = str(refusal["structuredContent"]["code"]) + _ledger_refusal( + tool_name, auth, error_code=code, org=target_org, server_fault=True, consumer=consumer + ) + return _ok(req.get("id"), refusal) if to: args["namespace"] = to return to diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index 4b3c9b27414..d9d80deba8b 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -797,12 +797,20 @@ async def _named_input( reads them (`gates.with_resolved_org`). The resolved name is written into `arguments`, as the screen writes it, so the ledger and admission rows name the namespace the call runs on. Returns the input model, or the refusal response: - UNKNOWN_BRANCH for a branch the caller cannot read, else `_validated_input`'s.""" + UNKNOWN_BRANCH for a branch the caller cannot read, the gate's refusal + (`_authorize_call`) when a read check could not run, else `_validated_input`'s.""" try: named = await gates.with_branch_name(op, arguments, auth) except UnknownBranchError as e: _emit_refused(op.name, arguments, error_code=e.code, request_id=request_id, error=e) return _ok(req_id, refusal_result(e)) + except PermissionError as e: + _emit_refused( + op.name, arguments, error_code=gates.ROLE_REFUSAL_CODE, request_id=request_id, error=e + ) + org = gates.resolve_org(op, arguments.get("org"), auth) + ns = str(arguments.get("namespace") or "") + return _ok(req_id, _forbidden_result(op, e, auth, org, ns)) if named is not arguments: arguments["namespace"] = named["namespace"] return _validated_input( diff --git a/server/transport/namespace_resolve.py b/server/transport/namespace_resolve.py index c777730ae05..494a38259fe 100644 --- a/server/transport/namespace_resolve.py +++ b/server/transport/namespace_resolve.py @@ -96,7 +96,7 @@ def match(name: str, known: dict[str, str], *, default_branch: set[str] | None = async def resolve_branch( - org: str, name: str, may_read: Callable[[str], Awaitable[bool]] + org: str, name: str, may_read: Callable[[str], Awaitable[tuple[bool, bool]]] ) -> str | None: """The namespace `@` names, for a code call on any transport. None when `name` is not that form, names no configured repository, @@ -106,10 +106,14 @@ async def resolve_branch( namespace that does hold one (an operator entry is not checked against the rule) is the name it spells, never a branch. - A branch the repository does not index, or that the caller may not read, raises + `may_read(namespace)` is the gate's read check, `(allowed, unverified)`. A branch + the repository does not index, or that the caller may not read, raises UnknownBranchError naming the branches the caller reads: one answer for both, so - it confirms no branch the caller cannot read. The gate still authorizes the - namespace this returns.""" + it confirms no branch the caller cannot read. A check that could not run leaves + the branch unknown, so it is never answered as one that is not there: the gate's + PermissionError, marked `unverified`, and the request is the server's failure + (`server.auth.fail_closed`). The gate still authorizes the namespace this + returns.""" from server.code.domain.index.repos import ( RegistryUnread, entry_repo_key, @@ -133,10 +137,18 @@ async def resolve_branch( members = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) except RegistryUnread: return None - readable = [m for m in members if m.git_branch and await may_read(m.namespace)] + checks = [(m, await may_read(m.namespace)) for m in members if m.git_branch] + readable = [m for m, (allowed, _) in checks if allowed] + hit = next((m for m in readable if m.git_branch == branch), None) + if hit is None and any(unverified for _, (_, unverified) in checks): + from server.auth.fail_closed import note_answered_unverified + + note_answered_unverified() + refused = PermissionError(f"the branches {name!r} names could not be checked") + setattr(refused, "unverified", True) # noqa: B010 — PermissionError declares no field + raise refused if not readable: return None - hit = next((m for m in readable if m.git_branch == branch), None) if hit is None: names = [m.git_branch for m in readable] raise UnknownBranchError( diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py index f15ef208bfd..b191d9f89cf 100644 --- a/tests/unit/test_repo_at_branch.py +++ b/tests/unit/test_repo_at_branch.py @@ -54,9 +54,14 @@ def _registry(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("server.tracker.domain.namespaces.configured_namespaces", lambda: {}) -def _readable(unreadable: set[str] = frozenset()): # type: ignore[assignment] - async def may_read(ns: str) -> bool: - return ns not in unreadable +def _readable(unreadable: set[str] = frozenset(), unchecked: set[str] = frozenset()): # type: ignore[assignment] + """The read check: refused on `unreadable`, and on `unchecked` refused because a read + it needed failed.""" + + async def may_read(ns: str) -> tuple[bool, bool]: + if ns in unchecked: + return False, True + return ns not in unreadable, False return may_read @@ -152,6 +157,21 @@ def test_a_repository_the_caller_reads_no_branch_of_is_left_for_the_gate_to_refu assert _resolve("kj@26.7", everything) is None +def test_a_check_that_could_not_run_is_the_servers_failure_never_an_unknown_branch() -> None: + """A branch whose read check failed may be readable: the refusal is the gate's, marked + unverified, and no list of branches is given from a partial check.""" + for asked in ("kj@26.7", "kj@26.9"): + with pytest.raises(PermissionError) as e: + asyncio.run(nr.resolve_branch(ORG, asked, _readable(unchecked={"code-kj-26-7"}))) + assert getattr(e.value, "unverified", False) is True, asked + with pytest.raises(PermissionError): # no branch could be checked + everything = {"code-kj", "code-kj-26-7", "code-kj-26-10"} + asyncio.run(nr.resolve_branch(ORG, "kj@26.7", _readable(unchecked=everything))) + # The branch asked for was checked and is readable: it resolves. + got = asyncio.run(nr.resolve_branch(ORG, "kj@26.10", _readable(unchecked={"code-kj-26-7"}))) + assert got == "code-kj-26-10" + + def test_a_registry_not_yet_read_resolves_nothing(monkeypatch: pytest.MonkeyPatch) -> None: def unread() -> list[Any]: raise repos.RegistryUnread("not read") @@ -195,7 +215,13 @@ def probe(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: import server.code.app.member_writes as member_writes from server.transport import http as http_mod - seen: dict[str, Any] = {"authz": [], "ran": [], "ledger": [], "unreadable": set()} + seen: dict[str, Any] = { + "authz": [], + "ran": [], + "ledger": [], + "unreadable": set(), + "unchecked": set(), + } async def _handler(inp: Any) -> _Out: seen["ran"].append(inp.namespace) @@ -216,6 +242,8 @@ async def _authorize_op(auth: Any, op_: Any, *, org: Any, namespace: Any, **_k: raise PermissionError("not a member") async def _may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + if ns in seen["unchecked"]: + return False, True return ns not in seen["unreadable"], False async def _noop(*_a: Any, **_k: Any) -> None: @@ -302,9 +330,9 @@ def test_both_transports_authorize_and_run_on_the_namespace_a_branch_name_resolv assert probe["ran"] == ["code-kj-26-7", "code-kj-26-7"] -def ledgered_rows(probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch, name: str) -> list[Any]: - """The ledger rows of one served call on each transport that names `name`, as the - transports hand them to the event writer.""" +def _ledger_rows(probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> list[Any]: + """The list the probe op's ledger rows land in from here on, as the transports hand + them to the event writer.""" from server.observability import ledger from server.transport import http as http_mod from server.transport import mcp_tools @@ -314,6 +342,12 @@ def ledgered_rows(probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch, name: for mod in (mcp_call, mcp_outcome): monkeypatch.setattr(mod, "_emit_mcp_event", mcp_tools._emit_mcp_event) monkeypatch.setattr(ledger, "_dispatch_event", lambda e: rows.append(e) or True) + return rows + + +def ledgered_rows(probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch, name: str) -> list[Any]: + """The ledger rows of one served call on each transport that names `name`.""" + rows = _ledger_rows(probe, monkeypatch) assert _http(probe, "alice", name).status_code == 200 assert _mcp(probe, "alice", name)["isError"] is False return [e for e in rows if e.operation == "code.test_branch_probe"] @@ -360,6 +394,26 @@ def test_an_unreadable_or_unindexed_branch_is_refused_before_the_gate_on_both( assert probe["ledger"] == [("http", "UNKNOWN_BRANCH"), ("mcp", "UNKNOWN_BRANCH")] * 2 +def test_a_check_that_could_not_run_is_refused_as_the_servers_failure_on_both( + probe: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """Not UNKNOWN_BRANCH, the caller's error: the gate's refusal, marked as the check's + failure, as the gate answers its own failed check on each transport.""" + probe["unchecked"] = {"code-kj-26-7"} + rows = _ledger_rows(probe, monkeypatch) + r = _http(probe, "alice", "kj@26.7") + detail = r.json()["detail"] + assert r.status_code == 403 and detail["code"] == "AUTH_INSUFFICIENT", r.text + assert detail["retry"] is True and detail["category"] == "dependency" + out = _mcp(probe, "alice", "kj@26.7") + assert out["isError"] and out["structuredContent"]["code"] == "AUTH_INSUFFICIENT" + assert probe["authz"] == [] and probe["ran"] == [] + assert [(e.transport, e.error_code, e.status_class) for e in rows] == [ + ("http", "AUTH_INSUFFICIENT", "server"), + ("mcp", "AUTH_INSUFFICIENT", "server"), + ] + + def test_a_name_that_is_no_branch_form_reaches_the_gate_as_given(probe: dict[str, Any]) -> None: for name in ("code-kj", "nosuch@master"): _http(probe, "alice", name) @@ -395,10 +449,18 @@ def can_access(self, org: str, ns: str) -> bool: return True -def _screen(monkeypatch: pytest.MonkeyPatch, tool: str, namespace: str, unreadable: set[str]): # type: ignore[no-untyped-def] +def _screen( # type: ignore[no-untyped-def] + monkeypatch: pytest.MonkeyPatch, + tool: str, + namespace: str, + unreadable: set[str], + unchecked: set[str] = frozenset(), # type: ignore[assignment] +): from server.transport import mcp_auth async def may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + if ns in unchecked: + return False, True return ns not in unreadable, False monkeypatch.setattr(gates, "may_read", may_read, raising=False) @@ -437,6 +499,21 @@ def test_the_mcp_screen_answers_unknown_branch_for_an_unreadable_or_unindexed_on assert args["namespace"] == name # nothing was rewritten +def test_the_mcp_screen_refuses_a_check_that_could_not_run_as_the_servers_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.transport import mcp_auth + + faults: list[bool] = [] + monkeypatch.setattr( + mcp_auth, "_ledger_refusal", lambda *a, **k: faults.append(k.get("server_fault", False)) + ) + refused, args, _ = _screen(monkeypatch, "loom_code_search", "kj@26.7", set(), {"code-kj-26-7"}) + assert refused is not None + assert refused["result"]["structuredContent"]["code"] == "AUTH_INSUFFICIENT" + assert args["namespace"] == "kj@26.7" and faults == [True] + + def test_the_mcp_screen_leaves_a_tracker_tool_alone(monkeypatch: pytest.MonkeyPatch) -> None: refused, args, note = _screen(monkeypatch, "loom_tracker_search", "kj@26.7", set()) assert args["namespace"] == "kj@26.7" and note is None From 3dd3d4d8fbae5856242f9fb8767f5c47a9d48939 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:58:22 +0000 Subject: [PATCH 04/10] A repository's members are its entries that spell it alike `repo_members` grouped entries by `remote.repo_key`, which lets a URL remote decide the key. An entry that names the repository as the others do but fetches it from a fork became a repository of its own: its own trunk, documents and decisions namespace, and a release set without it. The documents namespace and the release set grouped by the spelling of `repo`, so a configuration with such an entry changed meaning. `repo_members(org, repo)` now groups by `repo` as written, the grouping those derivations had, and a test holds a fork-remote entry to the repository's trunk, release set and branch names. Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Opus 5.5 --- docs/architecture/code-index-architecture.md | 4 +- server/code/app/backport.py | 10 ++--- server/code/app/blame.py | 3 +- server/code/app/first_build.py | 4 +- server/code/app/memory_links.py | 3 +- server/code/app/repo_scope.py | 3 +- server/code/app/repos.py | 2 +- server/code/domain/index/repos.py | 26 ++++--------- server/knowledge/app/source_sync.py | 3 +- server/transport/namespace_resolve.py | 3 +- tests/unit/test_repo_at_branch.py | 39 ++++++++++++++++---- tests/unit/test_repo_docs.py | 2 +- 12 files changed, 55 insertions(+), 47 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 9b809ab8dbd..432d56371de 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -85,8 +85,8 @@ it on the host that served the call; every other host's sweep removes its own co ### A repository's branches -The entries of one org that name the same repository (`remote.repo_key`) are the -repository's members, and `repo_members(org, repo_key)` in +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 diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 2817a1c3494..ae0165c4121 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -103,11 +103,11 @@ def resolve_branches(org: str, code_ns: str, wanted: list[str]) -> list[tuple[st 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 entry_repo_key, repo_for_namespace, repo_members + 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, entry_repo_key(me.repo, me.git_remote)) if me else []: + 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]}")) @@ -525,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 entry_repo_key, repo_for_namespace, repo_members + 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 repo_members(org, entry_repo_key(me.repo, me.git_remote)) - if r.namespace != code_ns + r.namespace: r.git_branch for r in repo_members(org, me.repo) if r.namespace != code_ns } diff --git a/server/code/app/blame.py b/server/code/app/blame.py index 70d0612dd92..99d6f57b510 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -55,7 +55,6 @@ from server.code.domain.index.compiler_tiers import state_value from server.code.domain.index.repos import ( default_git_dir, - entry_repo_key, repo_for_namespace, repo_members, ) @@ -742,7 +741,7 @@ async def handle_code_blame_range(input: Any) -> Any: org, ns = resolve_code_identity(input.org, input.namespace) repo = CodeRepo() cfg = repo_for_namespace(org, ns) - siblings = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) if cfg else [] + siblings = repo_members(org, cfg.repo) if cfg else [] # the window's default end is the indexed head: read once, for both head = ( await _namespace_head(repo, org, ns) diff --git a/server/code/app/first_build.py b/server/code/app/first_build.py index fc72657fc48..2e83587cf5c 100644 --- a/server/code/app/first_build.py +++ b/server/code/app/first_build.py @@ -43,7 +43,7 @@ from server.code.app.spans import code_span, set_code_span_attributes from server.code.domain.index import first_build as fb from server.code.domain.index.blame_range import sha_text -from server.code.domain.index.repos import entry_repo_key, repo_for_namespace, repo_members +from server.code.domain.index.repos import repo_for_namespace, repo_members from server.code.store.index import CodeRepo from server.core.errors import ValidationError @@ -199,7 +199,7 @@ async def handle_code_first_build(input: Any) -> Any: org, ns = resolve_code_identity(input.org, input.namespace) repo = CodeRepo() cfg = repo_for_namespace(org, ns) - siblings = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) if cfg else [] + siblings = repo_members(org, cfg.repo) if cfg else [] git_dir, gap = await history_git_dir(cfg, "code.first_build") sub = Subject(sha=fb.normalize_sha(input.sha), pr_number=int(input.pr_number or 0)) # Shape complaints come after the gate (the transport already ran it on org/namespace), diff --git a/server/code/app/memory_links.py b/server/code/app/memory_links.py index f26f2ea860a..92bafe2b9ab 100644 --- a/server/code/app/memory_links.py +++ b/server/code/app/memory_links.py @@ -30,7 +30,6 @@ from server.code.domain.index.repos import ( RepoConfig, configured_repos, - entry_repo_key, repo_for_namespace, repo_members, ) @@ -50,7 +49,7 @@ def trunk_namespace(org: str, namespace: str) -> str: cfg = repo_for_namespace(org, namespace) if cfg is None: return "" - members = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) + members = repo_members(org, cfg.repo) return members[0].namespace if members else namespace diff --git a/server/code/app/repo_scope.py b/server/code/app/repo_scope.py index f5d99039ff5..129cfa3138c 100644 --- a/server/code/app/repo_scope.py +++ b/server/code/app/repo_scope.py @@ -15,7 +15,6 @@ from server.code.domain.index.repos import ( RegistryUnread, configured_repos, - entry_repo_key, repo_for_namespace, repo_members, ) @@ -31,7 +30,7 @@ def trunk_namespace_of(org: str, code_namespace: str) -> str: cfg = repo_for_namespace(org, code_namespace) if cfg is None: return "" - members = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) + members = repo_members(org, cfg.repo) return members[0].namespace if members else "" diff --git a/server/code/app/repos.py b/server/code/app/repos.py index b36574b02cc..a707cf46db7 100644 --- a/server/code/app/repos.py +++ b/server/code/app/repos.py @@ -184,7 +184,7 @@ 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, repo_key(cfg.repo, cfg.git_remote), every) + members = repo_members(cfg.org, cfg.repo, every) trunk_ns = members[0].namespace if members else "" out.append( CodeRepoSummary( diff --git a/server/code/domain/index/repos.py b/server/code/domain/index/repos.py index c716b5f558f..6a227749493 100644 --- a/server/code/domain/index/repos.py +++ b/server/code/domain/index/repos.py @@ -34,7 +34,6 @@ from __future__ import annotations -import functools import json import logging import os @@ -772,29 +771,20 @@ def _trunk_rank(branch: str) -> tuple[int, Any]: return (2, branch) -@functools.lru_cache(maxsize=4096) -def entry_repo_key(repo: str, git_remote: str) -> str: - """`remote.repo_key` of an entry, memoized: a listing keys every entry against every - other.""" - from server.code.domain.index.remote import repo_key - - return repo_key(repo, git_remote) - - def repo_members( - org: str, repo_key: str, entries: Iterable[RepoConfig] | None = None + org: str, repo: str, entries: Iterable[RepoConfig] | None = None ) -> list[RepoConfig]: - """Every configured entry of the repository `repo_key` (`remote.repo_key`) in `org`, - 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. `entries` is one snapshot to read, default the - configured entries.""" + """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 entry_repo_key(c.repo, c.git_remote) == repo_key + if c.org == org and c.repo == repo ), key=lambda c: (_trunk_rank(str(c.git_branch or "")), c.namespace), ) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 8b87b186cc6..b7ce13957af 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -103,7 +103,6 @@ from server.code.domain.index.remote import repo_tag from server.code.domain.index.repos import ( configured_repos, - entry_repo_key, repo_members, require_registry_read, ) @@ -1293,7 +1292,7 @@ def _repo_tag(src: KnowledgeSource) -> str: cfg = next((c for c in entries if (c.org, c.namespace) == (src.org, src.namespace)), None) if cfg is None: return "" - members = repo_members(cfg.org, entry_repo_key(cfg.repo, cfg.git_remote), entries) + members = repo_members(cfg.org, cfg.repo, entries) if members[0].namespace != src.namespace: return "" return repo_tag(cfg.git_remote or cfg.repo) diff --git a/server/transport/namespace_resolve.py b/server/transport/namespace_resolve.py index 494a38259fe..9e284a2d377 100644 --- a/server/transport/namespace_resolve.py +++ b/server/transport/namespace_resolve.py @@ -116,7 +116,6 @@ async def resolve_branch( returns.""" from server.code.domain.index.repos import ( RegistryUnread, - entry_repo_key, repo_for_namespace, repo_members, ) @@ -134,7 +133,7 @@ async def resolve_branch( cfg = repo_for_namespace(org, via) if via else None if cfg is None: return None - members = repo_members(org, entry_repo_key(cfg.repo, cfg.git_remote)) + members = repo_members(org, cfg.repo) except RegistryUnread: return None checks = [(m, await may_read(m.namespace)) for m in members if m.git_branch] diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py index b191d9f89cf..93a72de86e4 100644 --- a/tests/unit/test_repo_at_branch.py +++ b/tests/unit/test_repo_at_branch.py @@ -184,13 +184,39 @@ def unread() -> list[Any]: def test_repo_members_lists_one_repository_of_one_org_in_the_pages_branch_order() -> None: - key = repos.entry_repo_key("Acme/kj", "") - got = repos.repo_members(ORG, key) + got = repos.repo_members(ORG, "Acme/kj") assert [c.namespace for c in got] == ["code-kj", "code-kj-26-10", "code-kj-26-7"] - assert [c.namespace for c in repos.repo_members("elsewhere", key)] == ["code-kj"] - assert repos.repo_members(ORG, repos.entry_repo_key("Acme/nope", "")) == [] + assert [c.namespace for c in repos.repo_members("elsewhere", "Acme/kj")] == ["code-kj"] + assert repos.repo_members(ORG, "Acme/nope") == [] + # the repository as its entries spell it, as the documents namespace always grouped + assert repos.repo_members(ORG, "acme/kj") == [] # a snapshot handed in is the one read - assert repos.repo_members(ORG, key, ENTRIES[:1]) == ENTRIES[:1] + assert repos.repo_members(ORG, "Acme/kj", ENTRIES[:1]) == ENTRIES[:1] + + +def test_an_entry_of_the_repository_on_a_fork_remote_stays_one_of_its_branches( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An entry that spells the repository as the others do and fetches it from a fork is + one of its branches: it reads the trunk's documents, is in its release set, and its + branch resolves, as before `repo_members`.""" + from server.code.app import backport, memory_links, repo_scope + + fork = "https://github.com/SomeFork/kj.git" + entries = [ + *ENTRIES, + _entry("code-kj-fork", "Acme/kj", "26.9", git_dir="/m/kf", git_remote=fork), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + assert repo_scope.trunk_namespace_of(ORG, "code-kj-fork") == "code-kj" + assert memory_links.trunk_namespace(ORG, "code-kj-fork") == "code-kj" + assert backport.resolve_branches(ORG, "code-kj", []) == [ + ("code-kj-26-10", "26.10"), + ("code-kj-fork", "26.9"), + ("code-kj-26-7", "26.7"), + ] + assert "code-kj-fork" in backport.branch_refs(ORG, "code-kj")[1] + assert _resolve("kj@26.9") == "code-kj-fork" # ------------------------------------------------------------------ both transports @@ -584,8 +610,7 @@ def test_the_docs_namespace_the_release_set_and_the_siblings_answer_as_they_did( backport.resolve_branches(c.org, c.namespace, []) == _was_release_namespaces(entries, c.org, c.namespace)[: backport.MAX_BRANCHES] ) - key = repos.entry_repo_key(c.repo, c.git_remote) - assert sorted(m.namespace for m in repos.repo_members(c.org, key)) == ( + assert sorted(m.namespace for m in repos.repo_members(c.org, c.repo)) == ( _was_repo_siblings(entries, c.org, c.namespace) ) assert repo_scope.trunk_namespace_of(ORG, "code-nosuch") == "" diff --git a/tests/unit/test_repo_docs.py b/tests/unit/test_repo_docs.py index 1156a1de2cb..59f8aa783b7 100644 --- a/tests/unit/test_repo_docs.py +++ b/tests/unit/test_repo_docs.py @@ -31,7 +31,7 @@ def _cfg(ns: str, repo: str, branch: str) -> Any: def _docs_namespace(repo: str) -> str: """The first of the repository's members: the namespace its documents live in.""" - return repos.repo_members(ORG, repos.entry_repo_key(repo, ""))[0].namespace + return repos.repo_members(ORG, repo)[0].namespace ENTRIES = [ From 66a7a581abcf1ac3a2eaf67f7bc665d4508ec420 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 03:02:36 +0000 Subject: [PATCH 05/10] The history reads keep the branches on their own clone `code.blame_range` and `code.first_build` took their siblings from `repo_members`, which lists every entry of the repository. An entry an operator gave its own clone then became a sibling of the others: the indexed view tested its head against this clone, and a release ref resolved to its head was read in a clone that may not hold it. The history reads resolve refs in one clone, so their siblings are the entries on that clone again (`repo_siblings`), and bisect reads its entry as before. A test reads the siblings both ops hand their history reads for a configuration with a branch on a clone of its own. Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Opus 5.5 --- server/code/app/bisect.py | 6 +- server/code/app/bisect_fix.py | 5 +- server/code/app/blame.py | 21 ++-- server/code/app/first_build.py | 6 +- tests/unit/test_code_bisect_deadline.py | 3 +- tests/unit/test_merge_shas.py | 4 +- tests/unit/test_mirrors.py | 7 +- tests/unit/test_pr_post_image.py | 2 +- tests/unit/test_repo_at_branch.py | 123 ++++++++++++++++++------ 9 files changed, 122 insertions(+), 55 deletions(-) diff --git a/server/code/app/bisect.py b/server/code/app/bisect.py index 0585344c789..73ab3b3cf24 100644 --- a/server/code/app/bisect.py +++ b/server/code/app/bisect.py @@ -86,7 +86,7 @@ from server.code.app.spans import code_span, set_code_span_attributes from server.code.domain.index import blame_range as br from server.code.domain.index.coverage_claim import is_test_file -from server.code.domain.index.repos import default_git_dir, repo_for_namespace +from server.code.domain.index.repos import default_git_dir from server.code.domain.time_window import _iso, _parse_when from server.code.store.index import CodeRepo from server.core.errors import ValidationError @@ -273,7 +273,7 @@ async def _mark_stage( logger.info("bisect: ledger records unread (%s)", e) records, stage.status = {}, "ledger_failed" first = bi.mark_bisect_candidates(pool, records=records, frames=frames, diff_kinds={}) - cfg = repo_for_namespace(org, ns) + cfg, _siblings = cb.repo_siblings(org, ns) git_dir, stage.reason = await cb.history_git_dir(cfg, "code.bisect_candidates") targets = ( _diff_targets(pool, first, records, frames_or_paths=bool(frames or paths)) @@ -318,7 +318,7 @@ async def _attach_merge_shas(repo: CodeRepo, org: str, ns: str, ranked: list[bi. except Exception as e: # noqa: BLE001 — the mirror still answers logger.info("bisect: ledger merge commits unread (%s)", e) stored = {} - cfg = repo_for_namespace(org, ns) + cfg, _siblings = cb.repo_siblings(org, ns) # no mirror here yet: the ledger's shas alone (history_dir starts the clone) git_dir = (await history_dir(cfg))[0] if cfg is not None else default_git_dir() branch = (cfg.git_branch if cfg is not None else "") or settings.code_git_branch diff --git a/server/code/app/bisect_fix.py b/server/code/app/bisect_fix.py index 4761f1e2857..04e2a8b17db 100644 --- a/server/code/app/bisect_fix.py +++ b/server/code/app/bisect_fix.py @@ -305,10 +305,9 @@ async def _fix_blame_stage( `code.blame_range`, name the PR that wrote them; those PRs go first with `blamed_by_fix`. Bounded (a few ranges, a wall budget) and fail-open: the pool as it was, and a summary saying why.""" - from server.code.app.blame import handle_code_blame_range, history_git_dir + from server.code.app.blame import handle_code_blame_range, history_git_dir, repo_siblings from server.code.app.index import gitrepo from server.code.domain.index import fix_blame as fb - from server.code.domain.index.repos import repo_for_namespace summary: dict[str, Any] = {"fix_pr": fix_pr} if _short(STAGE_MIN_S, "fix_blame"): @@ -319,7 +318,7 @@ async def _fix_blame_stage( if not merge: summary["skipped"] = "fix_not_in_ledger" return pool, summary - cfg = repo_for_namespace(org, ns) + cfg, _ = repo_siblings(org, ns) git_dir, gap = await history_git_dir(cfg, "code.bisect_candidates") if gap: summary["skipped"] = gap diff --git a/server/code/app/blame.py b/server/code/app/blame.py index 99d6f57b510..3df89697ec5 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -53,11 +53,7 @@ from server.code.domain.index import blame_range as br from server.code.domain.index import symbol_history as sh from server.code.domain.index.compiler_tiers import state_value -from server.code.domain.index.repos import ( - default_git_dir, - repo_for_namespace, - repo_members, -) +from server.code.domain.index.repos import default_git_dir from server.code.store.index import CodeRepo from server.settings import settings from server.tracker.domain import bisect as bi @@ -126,6 +122,18 @@ def _iso(ts: int) -> str: return datetime.fromtimestamp(ts, tz=UTC).isoformat() if ts > 0 else "" +def repo_siblings(org: str, ns: str) -> tuple[Any, list[Any]]: + """(this namespace's repo config, every configured entry on the same + bare clone) — the release-branch namespaces share the mirror.""" + from server.code.domain.index.repos import configured_repos + + cfgs = configured_repos() + mine = next((c for c in cfgs if c.org == org and c.namespace == ns), None) + if mine is None: + return None, [] + return mine, [c for c in cfgs if c.org == org and c.git_dir == mine.git_dir] + + async def history_git_dir(cfg: Any, op: str, *, head: str = "") -> tuple[str, str]: """`mirrors.history_dir` for a read of `op`, the scalar entry's mirror when no entry indexes the namespace.""" @@ -740,8 +748,7 @@ async def handle_code_blame_range(input: Any) -> Any: started = time.monotonic() org, ns = resolve_code_identity(input.org, input.namespace) repo = CodeRepo() - cfg = repo_for_namespace(org, ns) - siblings = repo_members(org, cfg.repo) if cfg else [] + cfg, siblings = repo_siblings(org, ns) # the window's default end is the indexed head: read once, for both head = ( await _namespace_head(repo, org, ns) diff --git a/server/code/app/first_build.py b/server/code/app/first_build.py index 2e83587cf5c..a0637655294 100644 --- a/server/code/app/first_build.py +++ b/server/code/app/first_build.py @@ -32,7 +32,7 @@ from typing import Any from server.code.api.models_history import CodeFirstBuildOutput -from server.code.app.blame import IndexedView, history_git_dir +from server.code.app.blame import IndexedView, history_git_dir, repo_siblings from server.code.app.common import ( new_trace_run_id, require_code_intel, @@ -43,7 +43,6 @@ from server.code.app.spans import code_span, set_code_span_attributes from server.code.domain.index import first_build as fb from server.code.domain.index.blame_range import sha_text -from server.code.domain.index.repos import repo_for_namespace, repo_members from server.code.store.index import CodeRepo from server.core.errors import ValidationError @@ -198,8 +197,7 @@ async def handle_code_first_build(input: Any) -> Any: started = time.monotonic() org, ns = resolve_code_identity(input.org, input.namespace) repo = CodeRepo() - cfg = repo_for_namespace(org, ns) - siblings = repo_members(org, cfg.repo) if cfg else [] + cfg, siblings = repo_siblings(org, ns) git_dir, gap = await history_git_dir(cfg, "code.first_build") sub = Subject(sha=fb.normalize_sha(input.sha), pr_number=int(input.pr_number or 0)) # Shape complaints come after the gate (the transport already ran it on org/namespace), diff --git a/tests/unit/test_code_bisect_deadline.py b/tests/unit/test_code_bisect_deadline.py index 16ad9159a1a..71782d27d05 100644 --- a/tests/unit/test_code_bisect_deadline.py +++ b/tests/unit/test_code_bisect_deadline.py @@ -75,7 +75,6 @@ def test_a_slow_fix_blame_stops_at_the_deadline_not_its_own_budget( from server.code.app import blame as code_blame from server.code.app.index import gitrepo from server.code.domain.index import fix_blame as fb - from server.code.domain.index import repos class Repo: async def merge_commit_of(self, org: str, ns: str, pr: int) -> str: @@ -88,7 +87,7 @@ async def slow_blame(inp: Any) -> Any: await asyncio.sleep(30) monkeypatch.setattr(gitrepo, "run", run) - monkeypatch.setattr(repos, "repo_for_namespace", lambda org, ns: None) + monkeypatch.setattr(code_blame, "repo_siblings", lambda org, ns: (None, None)) monkeypatch.setattr(code_blame, "handle_code_blame_range", slow_blame) monkeypatch.setattr( fb, "pre_image_ranges", lambda diff: [SimpleNamespace(path="src/a.cpp", start=1, end=2)] diff --git a/tests/unit/test_merge_shas.py b/tests/unit/test_merge_shas.py index bd305ad0e0e..07b09d7ff2d 100644 --- a/tests/unit/test_merge_shas.py +++ b/tests/unit/test_merge_shas.py @@ -174,7 +174,7 @@ def _cand(n: int) -> bi.Candidate: @pytest.mark.asyncio async def test_bisect_candidates_carry_merge_shas(mirror, git_calls, monkeypatch) -> None: - monkeypatch.setattr(hb, "repo_for_namespace", lambda org, ns: _Cfg(mirror["git_dir"])) + monkeypatch.setattr(hb.cb, "repo_siblings", lambda org, ns: (_Cfg(mirror["git_dir"]), [])) ranked = [_cand(10), _cand(12), _cand(13), _cand(40)] await hb._attach_merge_shas(_Repo({40: "c" * 40}), "o", "n", ranked) out = { @@ -197,7 +197,7 @@ async def test_bisect_candidates_get_no_merge_sha_from_past_the_indexed_head( ) -> None: """The namespace indexes the merge of #10; the mirror's branch has since landed #12. The search runs from the indexed head, so the later landing is not found.""" - monkeypatch.setattr(hb, "repo_for_namespace", lambda org, ns: _Cfg(mirror["git_dir"])) + monkeypatch.setattr(hb.cb, "repo_siblings", lambda org, ns: (_Cfg(mirror["git_dir"]), [])) ranked = [_cand(10), _cand(12)] await hb._attach_merge_shas(_Repo({}, head=mirror["merge"]), "o", "n", ranked) assert [(c.merge_commit_sha, c.merge_sha_source) for c in ranked] == [ diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index 25a391b5698..3439ae27f00 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -675,7 +675,7 @@ async def pr_records_by_number(self, *_a: Any, **_k: Any) -> dict[int, Any]: return {} monkeypatch.setattr(bootstrap, "clone_and_pin", _clone) - monkeypatch.setattr(bisect, "repo_for_namespace", lambda org, ns: cfg) + monkeypatch.setattr(blame, "repo_siblings", lambda org, ns: (cfg, [cfg])) monkeypatch.setattr(blame, "diff_kind", _no_git) pool = [bi.Candidate(pr_number=1, title="a", author="", merged_at="", minor_version="")] _out, stage = await bisect._mark_stage(_Repo(), "o", "code-r", pool, frames=[], paths=["a.c"]) # type: ignore[arg-type] @@ -687,8 +687,7 @@ async def pr_records_by_number(self, *_a: Any, **_k: Any) -> dict[int, Any]: async def test_fix_blame_says_why_there_is_no_mirror_instead_of_a_git_error( monkeypatch, tmp_path ) -> None: - from server.code.app import bisect_fix - from server.code.domain.index import repos + from server.code.app import bisect_fix, blame cfg = _Cfg(str(tmp_path / "r.git")) @@ -700,7 +699,7 @@ async def merge_commit_of(self, *_a: Any) -> str: return "m" * 40 monkeypatch.setattr(bootstrap, "clone_and_pin", _clone) - monkeypatch.setattr(repos, "repo_for_namespace", lambda org, ns: cfg) + monkeypatch.setattr(blame, "repo_siblings", lambda org, ns: (cfg, [cfg])) _out, summary = await bisect_fix._fix_blame_stage(_Repo(), "o", "code-r", [], 5) # type: ignore[arg-type] assert summary["skipped"].startswith("no_git_mirror: o/code-r: clone failed") diff --git a/tests/unit/test_pr_post_image.py b/tests/unit/test_pr_post_image.py index 53cbe28aa1a..0f87c01ae09 100644 --- a/tests/unit/test_pr_post_image.py +++ b/tests/unit/test_pr_post_image.py @@ -296,7 +296,7 @@ def test_blame_without_history_says_there_is_no_git_history( monkeypatch.setattr(settings, "git_history", "none") monkeypatch.setattr(blame, "require_code_intel", lambda: None) monkeypatch.setattr(blame, "resolve_code_identity", lambda o, n: ("acme", "code-ch")) - monkeypatch.setattr(blame, "repo_for_namespace", lambda o, n: None) + monkeypatch.setattr(blame, "repo_siblings", lambda o, n: (None, [])) monkeypatch.setattr(blame, "CodeRepo", lambda: object()) out = asyncio.run( blame.handle_code_blame_range(CodeBlameRangeInput(path=PATH, start_line=1, end_line=5)) diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py index 93a72de86e4..c0599f738ea 100644 --- a/tests/unit/test_repo_at_branch.py +++ b/tests/unit/test_repo_at_branch.py @@ -3,9 +3,9 @@ HTTP and MCP resolve the form alike, before the gate: the gate then authorizes the namespace the name resolves to, as it authorizes any other. A branch the repository does not index, or the caller cannot read, answers UNKNOWN_BRANCH and names the branches -the caller can read. `repo_members` is the one derivation of a repository's entries: the -docs namespace, the release set and the history siblings read it, and each answers as -the derivation it replaced. +the caller can read. `repo_members` lists a repository's entries for the docs namespace +and the release set, each answering as the derivation it replaced; the history reads keep +the entries on their own clone. """ from __future__ import annotations @@ -548,7 +548,7 @@ def test_the_mcp_screen_leaves_a_tracker_tool_alone(monkeypatch: pytest.MonkeyPa # ------------------------------------------------------------------ the callers keep their answers # -# The three derivations `repo_members` replaced, as they were: each caller's answer on one +# The two derivations `repo_members` replaced, as they were: each caller's answer on one # configuration must equal theirs. @@ -580,14 +580,9 @@ def _was_release_namespaces(entries: list[Any], org: str, ns: str) -> list[tuple return out -def _was_repo_siblings(entries: list[Any], org: str, ns: str) -> list[str]: - mine = next((c for c in entries if (c.org, c.namespace) == (org, ns)), None) - if mine is None: - return [] - return sorted(c.namespace for c in entries if c.org == org and c.git_dir == mine.git_dir) - - -def test_the_docs_namespace_the_release_set_and_the_siblings_answer_as_they_did() -> None: +def test_the_docs_namespace_and_the_release_set_answer_as_they_did( + monkeypatch: pytest.MonkeyPatch, +) -> None: from server.code.app import backport, memory_links, repo_scope entries = [ @@ -595,25 +590,95 @@ def test_the_docs_namespace_the_release_set_and_the_siblings_answer_as_they_did( _entry("code-w-dev", "Acme/w", "dev", git_dir="/m/w"), _entry("code-w-26-1", "Acme/w", "26.1", git_dir="/m/w"), _entry("code-w-26-3", "Acme/w", "release/26.3", git_dir="/m/w"), + _entry("code-w-26-4", "Acme/w", "26.4", git_dir="/m/wf", git_remote="https://f.example/w"), + _entry("code-w-26-2", "acme/w", "26.2", git_dir="/m/w"), # another spelling _entry("code-z-b", "Acme/z", "beta", git_dir="/m/z"), _entry("code-z-a", "Acme/z", "alpha", git_dir="/m/z"), _entry("code-w-elsewhere", "Acme/w", "26.9", org="elsewhere", git_dir="/e/w"), ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) docs = _was_docs_namespaces(entries) - ENTRIES_BEFORE = list(ENTRIES) - ENTRIES[:] = entries - try: - for c in entries: - assert repo_scope.trunk_namespace_of(c.org, c.namespace) == docs[(c.org, c.repo)] - assert memory_links.trunk_namespace(c.org, c.namespace) == docs[(c.org, c.repo)] - assert ( - backport.resolve_branches(c.org, c.namespace, []) - == _was_release_namespaces(entries, c.org, c.namespace)[: backport.MAX_BRANCHES] - ) - assert sorted(m.namespace for m in repos.repo_members(c.org, c.repo)) == ( - _was_repo_siblings(entries, c.org, c.namespace) - ) - assert repo_scope.trunk_namespace_of(ORG, "code-nosuch") == "" - assert backport.resolve_branches(ORG, "code-nosuch", []) == [] - finally: - ENTRIES[:] = ENTRIES_BEFORE + for c in entries: + assert repo_scope.trunk_namespace_of(c.org, c.namespace) == docs[(c.org, c.repo)] + assert memory_links.trunk_namespace(c.org, c.namespace) == docs[(c.org, c.repo)] + assert ( + backport.resolve_branches(c.org, c.namespace, []) + == _was_release_namespaces(entries, c.org, c.namespace)[: backport.MAX_BRANCHES] + ) + assert repo_scope.trunk_namespace_of(ORG, "code-nosuch") == "" + assert backport.resolve_branches(ORG, "code-nosuch", []) == [] + + +class _Stop(Exception): + """Raised where a history read is handed its siblings: nothing after it runs.""" + + +def _history_siblings(monkeypatch: pytest.MonkeyPatch, op: str, ns: str) -> list[str]: + """The siblings `code.blame_range` or `code.first_build` hands its history reads, for + a call on `ns`.""" + from types import SimpleNamespace + + from server.code.app import blame, first_build + + mod = blame if op == "blame_range" else first_build + seen: list[str] = [] + + def stop(*args: Any) -> Any: + seen.extend(c.namespace for c in next(a for a in args if isinstance(a, list))) + raise _Stop + + async def git_dir(cfg: Any, op: str, **_k: Any) -> tuple[str, str]: + return cfg.git_dir, "" + + async def no_head(*_a: Any) -> str: + return "" + + monkeypatch.setattr(mod, "require_code_intel", lambda: None) + monkeypatch.setattr(mod, "resolve_code_identity", lambda o, n: (ORG, ns)) + monkeypatch.setattr(mod, "CodeRepo", lambda: object()) + monkeypatch.setattr(mod, "history_git_dir", git_dir) + monkeypatch.setattr(blame, "history_enabled", lambda: True) + monkeypatch.setattr(blame, "_namespace_head", no_head) + monkeypatch.setattr(blame, "_resolve_window", stop) + monkeypatch.setattr(first_build, "IndexedView", stop) + inp = SimpleNamespace( + org=ORG, + namespace=ns, + sha="a" * 40, + pr_number=0, + path="a.py", + start_line=1, + end_line=2, + stage="", + to_sha="a" * 40, + to_version="", + from_sha="", + from_version="", + ) + handler = ( + blame.handle_code_blame_range + if op == "blame_range" + else first_build.handle_code_first_build + ) + with pytest.raises(_Stop): + asyncio.run(handler(inp)) + return seen + + +@pytest.mark.parametrize("op", ["blame_range", "first_build"]) +def test_the_history_reads_keep_the_entries_on_their_own_clone( + monkeypatch: pytest.MonkeyPatch, op: str +) -> None: + """A branch the operator gave its own clone is no sibling of the others: a history + read resolves its refs in one clone. The entries on that clone are, however the + repository is spelled, in the configuration's order.""" + entries = [ + _entry("code-x-26-1", "Acme/x", "26.1", git_dir="/m/x-own"), + _entry("code-x", "Acme/x", "master", git_dir="/m/x"), + _entry("code-x-26-2", "acme/x", "26.2", git_dir="/m/x"), + _entry("code-x-26-3", "Acme/x", "26.3", git_dir="/m/x"), + _entry("code-x", "Acme/x", "master", org="elsewhere", git_dir="/m/x"), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + assert _history_siblings(monkeypatch, op, "code-x") == ["code-x", "code-x-26-2", "code-x-26-3"] + assert _history_siblings(monkeypatch, op, "code-x-26-1") == ["code-x-26-1"] From b92827be65b907db1818a0a418349cd3ff2c2db7 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 03:07:44 +0000 Subject: [PATCH 06/10] Backport and docs test entries no longer carry a remote they do not use The entries these tests configure gained a `git_remote` field when the repository's members were keyed on the remote. They are grouped by `repo` alone now, which the stubs always had, so the field goes. Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_backport_release_branch_names.py | 4 +--- tests/unit/test_code_backport_gap.py | 1 - tests/unit/test_code_backport_gap_exact.py | 1 - tests/unit/test_code_backport_gaps.py | 1 - tests/unit/test_repo_docs.py | 2 +- 5 files changed, 2 insertions(+), 7 deletions(-) diff --git a/tests/unit/test_backport_release_branch_names.py b/tests/unit/test_backport_release_branch_names.py index 4eae79c4459..43d39bc55ed 100644 --- a/tests/unit/test_backport_release_branch_names.py +++ b/tests/unit/test_backport_release_branch_names.py @@ -29,7 +29,7 @@ def test_release_branch_names_parse_to_their_version() -> None: def _repos(): mk = lambda ns, repo, br: SimpleNamespace( # noqa: E731 - org="clickhouse", namespace=ns, repo=repo, git_remote="", git_branch=br + org="clickhouse", namespace=ns, repo=repo, git_branch=br ) return [ mk("code-clickhouse", "ClickHouse/ClickHouse", "master"), @@ -78,7 +78,6 @@ def test_another_orgs_entries_never_join_the_branch_set() -> None: org="acme", namespace="code-clickhouse", repo="ClickHouse/ClickHouse", - git_remote="", git_branch="master", git_dir="/acme/mirror", ), @@ -86,7 +85,6 @@ def test_another_orgs_entries_never_join_the_branch_set() -> None: org="acme", namespace="acme-26-3", repo="ClickHouse/ClickHouse", - git_remote="", git_branch="26.3", git_dir="/acme/mirror", ), diff --git a/tests/unit/test_code_backport_gap.py b/tests/unit/test_code_backport_gap.py index 1c1154655f5..da7824398e2 100644 --- a/tests/unit/test_code_backport_gap.py +++ b/tests/unit/test_code_backport_gap.py @@ -172,7 +172,6 @@ def test_rank_summary_and_overall() -> None: class _Cfg: def __init__(self, ns: str, branch: str, repo: str = "ClickHouse/ClickHouse") -> None: self.org, self.namespace, self.git_branch, self.repo = ORG, ns, branch, repo - self.git_remote = "" @pytest.fixture diff --git a/tests/unit/test_code_backport_gap_exact.py b/tests/unit/test_code_backport_gap_exact.py index 0d7b3650d2c..6d4347bb639 100644 --- a/tests/unit/test_code_backport_gap_exact.py +++ b/tests/unit/test_code_backport_gap_exact.py @@ -382,7 +382,6 @@ def row(verdict: str, basis: str) -> bp.BranchVerdict: class _Cfg: def __init__(self, ns: str, branch: str, repo: str = "ClickHouse/ClickHouse") -> None: self.namespace, self.git_branch, self.repo, self.org = ns, branch, repo, ORG - self.git_remote = "" class _Repo: diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index fdcfdb6dc54..81713bc4bbb 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -48,7 +48,6 @@ class _Cfg: org: str = ORG repo: str = "ClickHouse/ClickHouse" git_dir: str = "var/code_repos/clickhouse.git" - git_remote: str = "" classification: str = "standard" source: str = "config" diff --git a/tests/unit/test_repo_docs.py b/tests/unit/test_repo_docs.py index 59f8aa783b7..dad1630ee3b 100644 --- a/tests/unit/test_repo_docs.py +++ b/tests/unit/test_repo_docs.py @@ -26,7 +26,7 @@ def _cfg(ns: str, repo: str, branch: str) -> Any: - return SimpleNamespace(org=ORG, namespace=ns, repo=repo, git_remote="", git_branch=branch) + return SimpleNamespace(org=ORG, namespace=ns, repo=repo, git_branch=branch) def _docs_namespace(repo: str) -> str: From a02e24621d61e6cbe7a836bae6580a0ef4060ff1 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:49:49 +0000 Subject: [PATCH 07/10] An omitted org resolves repo@branch in the code plane's org on MCP too A code call that names no org acts in the code plane's org on HTTP, but the MCP screen resolved `repo@branch` and read the namespace in the token's org. With a token org that is not the code plane (dev mode, federated login) the same call answered on HTTP and was refused on MCP. `gates.org_for_op` is the one derivation of the org a call acts in, and `resolve_org` is now its op form. The MCP screen resolves the branch in that org and makes the read check on the resolved namespace in it. Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Sonnet 5.5 --- server/transport/gates.py | 11 +++++--- server/transport/mcp_auth.py | 20 ++++++++++---- tests/unit/test_repo_at_branch.py | 43 +++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 8 deletions(-) diff --git a/server/transport/gates.py b/server/transport/gates.py index 5c4c48945be..ee2ef0822e6 100644 --- a/server/transport/gates.py +++ b/server/transport/gates.py @@ -155,10 +155,15 @@ def _plane_default(op: Operation, org: str | None) -> str: return "" +def org_for_op(op_name: str, org: Any, auth: AuthInfo | None) -> str | None: + """The org a call to the op named `op_name` acts in: the request's, else the op's + plane default (code.* / tracker.*), else the verified token's own single org.""" + return present(org) or present(plane_org_for(op_name)) or _token_org(auth) + + def resolve_org(op: Operation, org: Any, auth: AuthInfo | None) -> str | None: - """The org a call acts in: the request's, else the op's plane default - (code.* / tracker.*), else the verified token's own single org.""" - return present(org) or present(plane_org_for(op.name)) or _token_org(auth) + """`org_for_op` of `op`.""" + return org_for_op(op.name, org, auth) def with_resolved_org(op: Operation, args: dict[str, Any], auth: AuthInfo | None) -> dict[str, Any]: diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index a34b8513419..82343ca1ac6 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -462,6 +462,7 @@ async def _branch_namespace( args: dict[str, Any], auth: AuthInfo, target_org: str, + org: str, req_ns: str, consumer: str, ) -> str | dict[str, Any] | None: @@ -469,17 +470,18 @@ async def _branch_namespace( `gates.with_branch_name` reads it on every transport): the namespace of that branch, written into `args`; the UNKNOWN_BRANCH result, ledgered, for a branch the caller cannot read; the refusal of the name given, ledgered as the server's, when - a read check could not run; None for any other name.""" + a read check could not run; None for any other name. `org` is the one the branch + resolves in, `gates.org_for_op`'s, as on HTTP.""" from server.transport import namespace_resolve as nr if "@" not in req_ns or not str(tool_name or "").startswith("loom_code_"): return None async def readable(ns: str) -> tuple[bool, bool]: - return await _may_read(auth, target_org, ns) + return await _may_read(auth, org, ns) try: - to = await nr.resolve_branch(target_org, req_ns.strip(), readable) + to = await nr.resolve_branch(org, req_ns.strip(), readable) except UnknownBranchError as e: from server.transport.mcp_refusals import refusal_result @@ -509,11 +511,19 @@ async def _screen_namespace( """The screen's namespace check: None when the caller may read `req_ns` (or the code/tracker index it resolves to, written into `args`), else the refusal, ledgered.""" - branch = await _branch_namespace(req, tool_name, args, auth, target_org, req_ns, consumer) + from server.transport import gates + + # A code call that omits `org` acts in the code plane's, as on HTTP: the org its + # branch resolves in and the namespace it names is then read in. + branch_org = gates.org_for_op("code.", args.get("org"), auth) or target_org + branch = await _branch_namespace( + req, tool_name, args, auth, target_org, branch_org, req_ns, consumer + ) if isinstance(branch, dict): return branch # UNKNOWN_BRANCH + read_org = branch_org if branch else target_org req_ns = branch or req_ns - allowed, given_unverified = await _may_read(auth, target_org, req_ns) + allowed, given_unverified = await _may_read(auth, read_org, req_ns) if not allowed: # A code/tracker tool's `namespace` that is not a namespace resolves # to one or says so — never the claim text meant for a real refusal. diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py index c0599f738ea..64309fba64a 100644 --- a/tests/unit/test_repo_at_branch.py +++ b/tests/unit/test_repo_at_branch.py @@ -682,3 +682,46 @@ def test_the_history_reads_keep_the_entries_on_their_own_clone( monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) assert _history_siblings(monkeypatch, op, "code-x") == ["code-x", "code-x-26-2", "code-x-26-3"] assert _history_siblings(monkeypatch, op, "code-x-26-1") == ["code-x-26-1"] + + +def test_an_omitted_org_resolves_and_reads_in_the_code_plane_org_on_both_transports( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A code call that names no org acts in the code plane's, not the token's: the + branch resolves there and the namespace it names is read there, on HTTP (the + resolver the transport calls) and on the MCP screen.""" + from server.transport import mcp_auth + + plane = "plane" + entries = [ + *ENTRIES, + _entry("code-pl-26-7", "Acme/pl", "26.7", org=plane, git_dir="/p/pl"), + _entry("code-pl", "Acme/pl", "master", org=plane, git_dir="/p/pl"), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + monkeypatch.setattr(settings, "code_org", plane) + reads: list[tuple[str, str]] = [] + + async def may_read(auth: Any, org: str, ns: str) -> tuple[bool, bool]: + reads.append((org, ns)) + return True, False + + monkeypatch.setattr(gates, "may_read", may_read, raising=False) + + op = OPERATIONS_BY_NAME["code.search"] + http = asyncio.run(gates.with_branch_name(op, {"namespace": "pl@26.7"}, _Auth())) # type: ignore[arg-type] + http_reads = list(reads) + reads.clear() + + args = {"namespace": "pl@26.7", "query": "q"} + req = { + "jsonrpc": "2.0", + "id": 7, + "method": "tools/call", + "params": {"name": "loom_code_search", "arguments": args}, + } + assert asyncio.run(mcp_auth._screen_tool_call(req, _Auth())) is None # type: ignore[arg-type] + assert http["namespace"] == args["namespace"] == "code-pl-26-7" + # the screen then reads the namespace it resolved to: in that org too, never the token's + assert reads[: len(http_reads)] == http_reads and reads[-1] == (plane, "code-pl-26-7") + assert {org for org, _ in reads} == {plane} From 83ec4e31f980f0984e768a07cb0e01cbda3518a1 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 12:20:46 +0000 Subject: [PATCH 08/10] Find a repository's branches by the spelling `match` uses `resolve_branch` finds the repository by its normalized spelling, but `repo_members` compares `repo` exactly, so a repository configured under two spellings (`Acme/kj` and `acme/kj`) hid the other group's branches and answered UNKNOWN_BRANCH. The resolver now lists the entries of every spelling that normalizes to the repository's, its own spelling first. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/transport/namespace_resolve.py | 22 ++++++++++++++++------ tests/unit/test_repo_at_branch.py | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/server/transport/namespace_resolve.py b/server/transport/namespace_resolve.py index 9e284a2d377..ed8bc24768e 100644 --- a/server/transport/namespace_resolve.py +++ b/server/transport/namespace_resolve.py @@ -91,6 +91,20 @@ def match(name: str, known: dict[str, str], *, default_branch: set[str] | None = return sorted(main or code, key=lambda c: (len(c), c))[0] +def _members(org: str, repo: str) -> list[Any]: + """The entries of `repo` and of every other spelling of it that `match` takes for + the same repository (case, surrounding slashes), `repo`'s own spelling first.""" + from server.code.domain.index.repos import configured_repos, repo_members + + spellings = { + c.repo for c in configured_repos() if c.org == org and _norm(c.repo) == _norm(repo) + } + spellings.add(repo) + return [ + m for s in sorted(spellings, key=lambda s: (s != repo, s)) for m in repo_members(org, s) + ] + + # A code namespace that ends in a commit hash: (the name up to it, the hash). _REVISION = re.compile(r"^(code-.+)-([0-9a-f]{7,40})$") @@ -114,11 +128,7 @@ async def resolve_branch( PermissionError, marked `unverified`, and the request is the server's failure (`server.auth.fail_closed`). The gate still authorizes the namespace this returns.""" - from server.code.domain.index.repos import ( - RegistryUnread, - repo_for_namespace, - repo_members, - ) + from server.code.domain.index.repos import RegistryUnread, repo_for_namespace from server.core.errors import UnknownBranchError repository, sep, branch = name.partition("@") @@ -133,7 +143,7 @@ async def resolve_branch( cfg = repo_for_namespace(org, via) if via else None if cfg is None: return None - members = repo_members(org, cfg.repo) + members = _members(org, cfg.repo) except RegistryUnread: return None checks = [(m, await may_read(m.namespace)) for m in members if m.git_branch] diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py index 64309fba64a..f39a39297bd 100644 --- a/tests/unit/test_repo_at_branch.py +++ b/tests/unit/test_repo_at_branch.py @@ -219,6 +219,24 @@ def test_an_entry_of_the_repository_on_a_fork_remote_stays_one_of_its_branches( assert _resolve("kj@26.9") == "code-kj-fork" +def test_a_repository_configured_under_two_spellings_resolves_a_branch_of_either( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """`match` finds a repository by its normalized spelling, so the branches listed + for it must be found the same way: an entry that spells it `acme/kj` is a branch + of `Acme/kj`, whichever spelling the name lands on.""" + entries = [ + *ENTRIES, + _entry("code-kj-27-1", "acme/kj", "27.1", git_dir="/m/kj"), + ] + monkeypatch.setattr(repos, "configured_repos", lambda: list(entries)) + assert _resolve("kj@27.1") == "code-kj-27-1" + assert _resolve("kj@26.7") == "code-kj-26-7" + assert _resolve("code-kj-27-1@master") == "code-kj" + err = _unknown_branch("kj@nope") + assert "27.1" in str(err) and "26.7" in str(err) + + # ------------------------------------------------------------------ both transports From 8924d8a8c0d69fb76536eaaae6b248ce15308b58 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 17:22:26 +0000 Subject: [PATCH 09/10] The branch resolver keeps its members' narrow type `_members` returned `list[Any]`, so `hit.namespace` was `Any` and `resolve_branch` returned it from a `str | None` signature. The mypy ratchet caught it as `no-any-return`. Annotate the helper with the `RepoConfig` that `repo_members` already returns, imported for typing only so the registry stays a lazy import. Signed-off-by: Kaloyan Naumov Co-Authored-By: Claude Opus 5.5 --- server/transport/namespace_resolve.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/server/transport/namespace_resolve.py b/server/transport/namespace_resolve.py index ed8bc24768e..ca7ccba4ad0 100644 --- a/server/transport/namespace_resolve.py +++ b/server/transport/namespace_resolve.py @@ -29,7 +29,10 @@ import re from collections.abc import Awaitable, Callable, Iterable from contextvars import ContextVar -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: # the registry reads are lazy: no import cycle at runtime + from server.code.domain.index.repos import RepoConfig UNKNOWN_NAMESPACE = "UNKNOWN_NAMESPACE" @@ -91,7 +94,7 @@ def match(name: str, known: dict[str, str], *, default_branch: set[str] | None = return sorted(main or code, key=lambda c: (len(c), c))[0] -def _members(org: str, repo: str) -> list[Any]: +def _members(org: str, repo: str) -> list[RepoConfig]: """The entries of `repo` and of every other spelling of it that `match` takes for the same repository (case, surrounding slashes), `repo`'s own spelling first.""" from server.code.domain.index.repos import configured_repos, repo_members From 86eb526b6e8b8fffbe8d5a070169fcf6441f5784 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 19:39:03 +0000 Subject: [PATCH 10/10] Point the history-read test at the resolver each handler uses blame calls mirrors.history_dir and first_build calls the history_dir it imported; the wrapper history_git_dir went out with the default-mirror change, so both cases died at setattr before the handler ran and the clone-isolation assertions never executed. Patch the seam each handler reads: the mirrors module attribute for blame, the imported name for first_build. The assertions are unchanged. Signed-off-by: Kaloyan Naumov --- tests/unit/test_repo_at_branch.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_repo_at_branch.py b/tests/unit/test_repo_at_branch.py index f39a39297bd..19c0c1bcc51 100644 --- a/tests/unit/test_repo_at_branch.py +++ b/tests/unit/test_repo_at_branch.py @@ -654,7 +654,12 @@ async def no_head(*_a: Any) -> str: monkeypatch.setattr(mod, "require_code_intel", lambda: None) monkeypatch.setattr(mod, "resolve_code_identity", lambda o, n: (ORG, ns)) monkeypatch.setattr(mod, "CodeRepo", lambda: object()) - monkeypatch.setattr(mod, "history_git_dir", git_dir) + # The seam each handler reads: blame reaches the resolver on the mirrors + # module it imports, first_build imported the name itself. + if op == "blame_range": + monkeypatch.setattr(blame.mirrors, "history_dir", git_dir) + else: + monkeypatch.setattr(first_build, "history_dir", git_dir) monkeypatch.setattr(blame, "history_enabled", lambda: True) monkeypatch.setattr(blame, "_namespace_head", no_head) monkeypatch.setattr(blame, "_resolve_window", stop)