diff --git a/docs/features/code-index/repositories.md b/docs/features/code-index/repositories.md index 43d548a34b8..eb2d6ee3c1c 100644 --- a/docs/features/code-index/repositories.md +++ b/docs/features/code-index/repositories.md @@ -192,8 +192,10 @@ profile identifies the ClickHouse-only SQL registration, error-code and stateles conventions; those assumptions are not inferred merely because a project contains C++ or SQL. -`compiler_candidates` is inferred from build manifests. A candidate without a watermark -appears in `quality_warnings` with the workers to enable: +`compiler_candidates` is inferred from build manifests, and `compiler_tier_rules` names +the rule that runs each tier: `scip_producer`, `scip_extra_producers`, `tree`, or +`scip_excluded_producers` for a tier the entry drops. A candidate without a watermark +that the entry does not exclude appears in `quality_warnings` with the workers to enable: | Candidate | Preflight in the worker environment | Worker | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md index 273f4c837b4..ebbe4ecc68d 100644 --- a/docs/getting-started/quickstart.md +++ b/docs/getting-started/quickstart.md @@ -572,7 +572,8 @@ LOOM_CODE_REPOS_JSON=[{"org":"dev","namespace":"code-myrepo","repo":"acme/myrepo - Loom picks the compiler-tier indexers from the repository's build files (`go.mod`, `package.json`, `pyproject.toml`, a root `CMakeLists.txt`, …); `scip_producer` names - one instead ([Compiler tier](../operations/code-index-operations.md#compiler-tier)). + the primary one and `scip_excluded_producers` drops one + ([Compiler tier](../operations/code-index-operations.md#compiler-tier)). C/C++ also needs a configured build tree, so without one a C/C++ repository gets only the parser tier. - For a private repository, add a GitHub token (`LOOM_CODE_GITHUB_TOKEN` in `.env`, or diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index fb5f49aa400..b63f528fa46 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -135,8 +135,9 @@ LOOM_CODE_REPOS_JSON='[ | `embed_reuse_from` | a namespace whose embeddings are reused when the chunk text is identical (a release branch of the same repository) | | `public` | the repository is public on its host: anyone in the org can join its index as a reader at once | | `classification` | `restricted` for a private repository: a maintainer approves each reader, and it is never org-readable | -| `scip_producer`, `scip_checkout_dir` | the compiler-tier indexer (`clang`, `typescript`, `python`, `go`; unset, the tree's build files pick) and its working tree | +| `scip_producer`, `scip_checkout_dir` | the primary compiler tier (`clang`, `typescript`, `python`, `go`; unset, the tree's build files pick) and its working tree | | `scip_extra_producers` | further compiler-tier producers over the same tree (a Python repository with a TypeScript frontend), each in its own checkout | +| `scip_excluded_producers` | compiler-tier producers never run although the tree has their build file (a `pyproject.toml` that only serves test tooling) | | `git_extra_branches` | globs of other remote branches the shared mirror should carry | | `github_token` | per-entry override of `LOOM_CODE_GITHUB_TOKEN` | | `forge` | `forgejo` for a Forgejo host: its pull requests are read from the host's API | @@ -482,15 +483,33 @@ index does. | Python | `python` | `LOOM_CODE_SCIP_PY_DELTA_ENABLED` | scip-python (in the image) | | Go | `go` | `LOOM_CODE_SCIP_GO_DELTA_ENABLED` | Go and scip-go (in the image) | -An entry that names no `scip_producer` gets every tier whose build file its tree -carries: `go.mod` (at any depth) for Go; `tsconfig.json`, `jsconfig.json` or -`package.json` at the root for TypeScript; a root `CMakeLists.txt` for C/C++; -`pyproject.toml`, `setup.py` or `requirements.txt` at the root for Python. -`code.index_status` lists them as `compiler_candidates`. Name the producer where a build -file is incidental, such as a C++ repository whose `pyproject.toml` only serves its test -tooling; `scip_extra_producers` adds tiers beside a named one. Each tier works in its own -tree: the named producer (C/C++ when the entry names none) in `scip_checkout_dir`, every -other one in `.`. +An entry runs the tiers it names and every tier whose build file its tree carries: +`go.mod` (at any depth) for Go; `tsconfig.json`, `jsconfig.json` or `package.json` at +the root for TypeScript; a root `CMakeLists.txt` for C/C++; `pyproject.toml`, +`setup.py` or `requirements.txt` at the root for Python. `scip_producer` names the +primary tier and its checkout, and `scip_extra_producers` adds a tier the tree has no +build file for, such as TypeScript with no root `package.json`. Where a build file is +incidental, such as a C++ repository whose `pyproject.toml` only serves its test +tooling, list that tier in `scip_excluded_producers`. A tier the entry names runs even +when it is also excluded. An entry added through `code.repo.add` takes `scip_producer` +only, so it runs every tier its tree has a build file for. + +`code.index_status` lists the tiers the tree calls for as `compiler_candidates` and +names the rule behind each tier in `compiler_tier_rules`: `scip_producer`, +`scip_extra_producers`, `tree` (the build file is in the tree and the entry does not +exclude it) or `scip_excluded_producers` (the tier does not run). A tier that stops +running, because the entry excludes it or the tree loses its last build file for it, +keeps its watermark. `compiler_tiers` shows no card for it, and neither +`commit_coverage` nor a coverage watch waits for it. `run_python_delta.sh` runs a +Python tier only when the entry runs it. + +When a tree gains a build file, the tier starts on the next pass. A tier that never ran +indexes its modules in full, as a first run does. That costs build time and memory, +about 4 GB for each Go module job (`LOOM_CODE_SCIP_GO_JOBS`). A tier that ran before +resumes from its old watermark, or indexes in full when that commit has left the +history, and a commit waits on it until it catches up. Each tier works in its own tree: +the named producer (C/C++ when the entry names none) in `scip_checkout_dir`, every other +one in `.`. All the workers are enabled by default, and the Docker image carries every indexer: scip-python, scip-typescript, scip-go, and for C/C++ clang 21, lld, CMake, ninja and diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index d271d547248..78da96e705c 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -962,12 +962,13 @@ Health of the code index: indexed head commit, compiler-tier commit, row counts, | `provider` | `str` | | | `profile` | `str` | | | `compiler_candidates` | `list[str]` | Compiler tiers inferred from the indexed tree, even before a compiler worker has produced its first watermark. | +| `compiler_tier_rules` | `dict[str, str]` | Why each tier runs, by producer: `scip_producer`, `scip_extra_producers`, `tree` (a build file in the tree) or `scip_excluded_producers` (the entry drops it, so it is off). | | `quality_warnings` | `list[str]` | Actionable readiness gaps. | | `git_head` | `str` | The fast tier's watermark: the last commit whose files are ingested; '' before the first pass. | | `scip_commit` | `str` | `scip_commit` / `scip_lag` are the ENTRY'S compiler tier — the one `scip_producer` names — not the C++ key by name; a TypeScript repository reports its scip-typescript watermark here. | | `scip_commit_py` | `str` | The scip-python watermark by name, whatever the entry's primary tier; '' when unset. | | `scip_producer` | `str` | The primary compiler tier's producer (clang \| typescript \| go \| python); '' when no tier has a watermark. | -| `compiler_tiers` | `list[CodeCompilerTier]` | Every compiler tier with a watermark or configured for the entry, the primary first. | +| `compiler_tiers` | `list[CodeCompilerTier]` | The entry's configured tier and every other tier it runs over its current tree that has a watermark, the primary first. | | `tier_health` | `list[CodeTierHealth]` | The last recorded outcome of each tier that has one (fetch, ingest, the compiler tiers and the weekly C++ full run): a failing tier names its error kind, since when, and the fix. | | `pr_cursor` | `str` | The PR-history poller's cursor: the newest `updated_at` (ISO-8601) of the merged PRs it fetched; '' before its first pass. | | `commit_coverage` | `CodeCommitCoverage \| None` | Set when the request named a `commit`. | diff --git a/scripts/scip_harness/run_python_delta.sh b/scripts/scip_harness/run_python_delta.sh index 5685197b7cc..d605af1c267 100755 --- a/scripts/scip_harness/run_python_delta.sh +++ b/scripts/scip_harness/run_python_delta.sh @@ -79,12 +79,14 @@ async def m(): cfg = next((r for r in configured_repos() if r.org == org and r.namespace == ns), None) bare = os.path.abspath(cfg.git_dir or settings.code_git_dir) if cfg else "" producer = cfg.scip_producer if cfg else "" - if cfg and settings.code_scip_py_delta_enabled and await worker_owns(repo, cfg, "python"): + owns = cfg is not None and await worker_owns(repo, cfg, "python") + if owns and settings.code_scip_py_delta_enabled: owner = "worker" elif producer in ("go", "typescript"): owner = producer # its in-process worker moves this checkout - elif cfg and not producer and not await worker_owns(repo, cfg, "python"): - owner = "none" # the tree calls for no Python tier + elif cfg and not owns: + # the entry excludes the tier, or neither it nor its tree calls for one + owner = "excluded" if "python" in cfg.scip_excluded_producers else "none" else: owner = "manual" print(org, ns, wm or "-", head or "-", bare or "-", owner) @@ -99,7 +101,11 @@ PYEOF exit 0 fi if [[ "$OWNER" == "none" ]]; then - echo ">> $NS: the tree has no Python build file — no python tier" + echo ">> $NS: the tree has no Python build file and the entry names no python tier" + exit 0 + fi + if [[ "$OWNER" == "excluded" ]]; then + echo ">> $NS: scip_excluded_producers drops the python tier, skipping" exit 0 fi if [[ "$OWNER" != "manual" ]]; then diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 56ecddafb5f..68b7d49fa5d 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1671,6 +1671,7 @@ type CodeIndexStatusOutput struct { Provider *string `json:"provider,omitempty"` Profile *string `json:"profile,omitempty"` CompilerCandidates *[]string `json:"compiler_candidates,omitempty"` + CompilerTierRules *map[string]string `json:"compiler_tier_rules,omitempty"` QualityWarnings *[]string `json:"quality_warnings,omitempty"` GitHead *string `json:"git_head,omitempty"` ScipCommit *string `json:"scip_commit,omitempty"` diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index a7db4259e1e..acd086001ed 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -7572,6 +7572,7 @@ class CodeIndexStatusOutput(TypedDict, total=False): provider: NotRequired[str] profile: NotRequired[str] compiler_candidates: NotRequired[list[str]] + compiler_tier_rules: NotRequired[dict[str, str]] quality_warnings: NotRequired[list[str]] git_head: NotRequired[str] scip_commit: NotRequired[str] diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 06ad53a47b2..ab0249185e1 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -11634,6 +11634,8 @@ pub struct CodeIndexStatusOutput { pub profile: String, #[serde(default = "default_code_index_status_output_compiler_candidates")] pub compiler_candidates: Vec, + #[serde(default = "default_code_index_status_output_compiler_tier_rules")] + pub compiler_tier_rules: std::collections::HashMap, #[serde(default = "default_code_index_status_output_quality_warnings")] pub quality_warnings: Vec, #[serde(default = "default_code_index_status_output_git_head")] @@ -68687,6 +68689,10 @@ fn default_code_index_status_output_profile() -> String { fn default_code_index_status_output_compiler_candidates() -> Vec { serde_json::from_str("[]").expect("schema default") } +fn default_code_index_status_output_compiler_tier_rules( +) -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") +} fn default_code_index_status_output_quality_warnings() -> Vec { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index cdcc98e5d8b..e2f09c25f16 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -11798,6 +11798,11 @@ fn code_index_status() { serde_json::from_str::("[]").unwrap(), "code.index_status:compiler_candidates" ); + assert_eq!( + encoded["compiler_tier_rules"], + serde_json::from_str::("{}").unwrap(), + "code.index_status:compiler_tier_rules" + ); assert_eq!( encoded["quality_warnings"], serde_json::from_str::("[]").unwrap(), diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 3eddf91d394..06b9f841913 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -1239,6 +1239,7 @@ export interface CodeIndexStatusOutput { provider?: string; profile?: string; compiler_candidates?: string[]; + compiler_tier_rules?: Record; quality_warnings?: string[]; git_head?: string; scip_commit?: string; diff --git a/server/cli/code_scip.py b/server/cli/code_scip.py index f07ecedd236..5c06ce260b1 100644 --- a/server/cli/code_scip.py +++ b/server/cli/code_scip.py @@ -70,16 +70,17 @@ async def _scip_full(args: argparse.Namespace) -> int: cfg = _repo_cfg(args) # before declaring the org: an unconfigured entry records nothing await connect_code_plane(get_client(), args) org, ns = _identity(args) - # scip-full runs scip-clang; an entry another compiler tier owns (Go, - # Python, TypeScript) is that worker's to re-index, and its checkout is - # the worker's to fetch. Same ownership test the delta pass applies. + # scip-full runs scip-clang, only for an entry that runs the clang tier: the + # same ownership test the delta pass applies. from server.code.app.index.producer_inference import worker_owns from server.code.store.index import CodeRepo if not await worker_owns(CodeRepo(), cfg, "clang"): - producer = cfg.scip_producer or "inferred" - print(f"skip {ns}: its compiler tier is {producer}, not clang; that tier's worker owns it") - _note(skipped="not_clang", producer=producer) + print( + f"skip {ns}: the entry does not run the clang tier " + "(not named, excluded, or no root CMakeLists.txt in its tree)" + ) + _note(skipped="not_clang", producer=cfg.scip_producer or "inferred") return 0 # The whole entry runs under its lock, so a delta skips this entry while # the checkout moves and the watermark is written; other entries' deltas diff --git a/server/code/api/models_status.py b/server/code/api/models_status.py index 9f079c0b3d4..634dff002d5 100644 --- a/server/code/api/models_status.py +++ b/server/code/api/models_status.py @@ -146,6 +146,9 @@ class CodeIndexStatusOutput(BaseModel): # Compiler tiers inferred from the indexed tree, even before a compiler # worker has produced its first watermark. compiler_candidates: list[str] = Field(default_factory=list) + # Why each tier runs, by producer: `scip_producer`, `scip_extra_producers`, `tree` (a + # build file in the tree) or `scip_excluded_producers` (the entry drops it, so it is off). + compiler_tier_rules: dict[str, str] = Field(default_factory=dict) # Actionable readiness gaps. Empty means the indexed fast/vector tiers are healthy; # compiler candidates remain optional precision upgrades. quality_warnings: list[str] = Field(default_factory=list) @@ -161,7 +164,8 @@ class CodeIndexStatusOutput(BaseModel): # The primary compiler tier's producer (clang | typescript | go | python); '' when no tier has # a watermark. scip_producer: str = "" - # Every compiler tier with a watermark or configured for the entry, the primary first. + # The entry's configured tier and every other tier it runs over its current tree that + # has a watermark, the primary first. compiler_tiers: list[CodeCompilerTier] = Field(default_factory=list) # The last recorded outcome of each tier that has one (fetch, ingest, the compiler # tiers and the weekly C++ full run): a failing tier names its error kind, since diff --git a/server/code/app/coverage_watch.py b/server/code/app/coverage_watch.py index a5d66096ab1..c1cabd1895c 100644 --- a/server/code/app/coverage_watch.py +++ b/server/code/app/coverage_watch.py @@ -102,7 +102,8 @@ async def handle_code_coverage_watch(input: CodeCoverageWatchInput) -> CodeCover if watch is None: watch = svc.new_watch(org, ns, sha, input.inbox, _caller_subject()) await repo.insert_watch_version(watch) - coverage = await svc.coverage_for(cfg, sha, await CodeRepo().all_state(org, ns)) + state = await CodeRepo().all_state(org, ns) + coverage = await svc.coverage_for(cfg, sha, state, await svc.running_tiers(cfg, state)) emitted = False if coverage.get("ready") and watch.delivered_at is None: emitted, watch = await svc.deliver(watch, coverage) diff --git a/server/code/app/index/compiler_tier.py b/server/code/app/index/compiler_tier.py index 1f9834339b6..beb0edb5751 100644 --- a/server/code/app/index/compiler_tier.py +++ b/server/code/app/index/compiler_tier.py @@ -128,8 +128,7 @@ async def run_entry(repo: CodeRepo, cfg: RepoConfig) -> None: with record_pass(worker) as rec: repo = CodeRepo() for cfg in configured_repos(): - if not await worker_owns(repo, cfg, producer): - await tier_health.forget(repo, cfg.org, cfg.namespace, not_run) + if not await _owned(repo, cfg, producer, not_run, worker, result): continue erased = await erasing.being_erased(cfg.org, cfg.namespace) if ( @@ -163,6 +162,28 @@ async def run_entry(repo: CodeRepo, cfg: RepoConfig) -> None: return result +async def _owned( + repo: CodeRepo, + cfg: RepoConfig, + producer: str, + not_run: tuple[str, ...], + worker: str, + result: TierResult, +) -> bool: + """Whether the tier runs the entry. One it does not own drops the `not_run` health + records. A failed read of its tree is the entry's error and leaves them as they are.""" + try: + owns = await worker_owns(repo, cfg, producer) + except Exception as e: # one entry's tree read must not stop the pass + logger.exception("%s: %s ownership read failed", worker, cfg.namespace) + result.errors.append(f"{cfg.namespace}: tree read failed: {type(e).__name__}") + pass_context.note_failure(e, cfg.namespace) + return False + if not owns: + await tier_health.forget(repo, cfg.org, cfg.namespace, not_run) + return owns + + async def _gc_checkout(cfg: RepoConfig, producer: str) -> None: import asyncio diff --git a/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index ace2f4beffc..cd68ec38020 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -42,7 +42,7 @@ restrict_if_restricted, ) from server.code.app.index.mirror_locks import fetch_lock_path, partial_mirror, try_lock -from server.code.app.index.producer_inference import PRODUCERS +from server.code.app.index.producer_inference import PRODUCERS, runnable_producers from server.code.domain.index import repos from server.code.store import index as code_store from server.core import readiness @@ -482,17 +482,9 @@ async def _named_paths() -> tuple[set[str], set[str]] | None: logger.info("mirror sweep skipped: registry unreadable (%s)", e) return None mirrors = {c.git_dir for c in cfgs} | {repo_registry.git_dir_for(str(r["repo"])) for r in rows} - # An entry naming no producer runs whichever tiers its tree calls for, so every - # tier's tree is named; one naming its producer runs that tier and its extras. - checkouts = { - repos.checkout_for(c, p) - for c in cfgs - for p in ( - (c.scip_producer, *c.scip_extra_producers) - if c.scip_producer - else (*PRODUCERS, *c.scip_extra_producers) - ) - } + # An entry runs the tiers it names and whichever others its tree calls for, so each + # tier's tree is named but a tier the entry excludes. + checkouts = {repos.checkout_for(c, p) for c in cfgs for p in runnable_producers(c)} for r in rows: base = repo_registry.checkout_dir_for(str(r["namespace"])) checkouts |= {base, *(repos.sibling_checkout(base, p) for p in PRODUCERS)} diff --git a/server/code/app/index/producer_inference.py b/server/code/app/index/producer_inference.py index 4ff90d09fdd..3aec47383c1 100644 --- a/server/code/app/index/producer_inference.py +++ b/server/code/app/index/producer_inference.py @@ -1,11 +1,8 @@ -"""Which compiler tier a repository's tree calls for. +"""Which compiler tiers a repository entry runs. -An entry that names no producer (the default, from the page or from -LOOM_CODE_REPOS_JSON) leaves it to its tree: the workers that keep the compiler tiers -current (`code_scip_delta` for scip-clang, the TypeScript, Go and Python workers) ask -the tree. The rule is the languages' own build manifests, read from the namespace's -live paths — one membership read of a handful of basenames — never a guess from file -counts: +An entry runs the tiers it names and the tiers its tree calls for. The tree's rule is +the languages' own build manifests, read from the namespace's live paths (one +membership read of a handful of basenames), never a guess from file counts: go.mod → go tsconfig.json / jsconfig.json / package.json → typescript (scip-typescript @@ -13,19 +10,32 @@ CMakeLists.txt at the root → clang pyproject.toml / setup.py / requirements.txt → python -A tree with several manifests calls for several tiers, and each worker -answers only for its own; an explicit `scip_producer` on the entry wins -over every inference, and `scip_extra_producers` adds tiers beside it. +A tree with several manifests calls for several tiers, and each worker answers only for +its own. `scip_producer` names the primary tier and its checkout, `scip_extra_producers` +adds a tier the tree does not call for, and `scip_excluded_producers` drops a tier the +tree calls for. A tier the entry names runs even when it also excludes it. """ from __future__ import annotations +import logging from collections.abc import Iterable from typing import TYPE_CHECKING +from server.code.app.ttl_cache import TtlCache +from server.code.domain.index.compiler_tiers import state_value +from server.observability import degradations +from server.settings import settings + if TYPE_CHECKING: from server.code.domain.index.repos import RepoConfig +logger = logging.getLogger(__name__) + +# (org, namespace, git_head) -> `tree_producers`: polls at one indexed head read it once, +# and a new head reads it again +_trees: TtlCache[tuple[str, str, str], list[str]] = TtlCache(lambda: settings.code_status_ttl_s) + MARKERS: dict[str, tuple[str, ...]] = { "go": ("go.mod",), "typescript": ("tsconfig.json", "jsconfig.json", "package.json"), @@ -33,6 +43,8 @@ "python": ("pyproject.toml", "setup.py", "requirements.txt"), } PRODUCERS: tuple[str, ...] = tuple(MARKERS) +# `tier_rules`' value for a tier the tree calls for and the entry drops +EXCLUDED = "scip_excluded_producers" ALL_MARKERS: tuple[str, ...] = tuple(m for ms in MARKERS.values() for m in ms) @@ -49,12 +61,36 @@ def infer_producers(paths: Iterable[str], *, root_only_clang: bool = True) -> li return [prod for prod, marks in MARKERS.items() if any(m in names for m in marks)] -def applies(entry_producer: str, worker_producer: str, tree_producers: Iterable[str]) -> bool: - """Does a compiler-tier worker own this entry? An explicit producer - decides alone; an empty one defers to the tree.""" - if entry_producer: - return entry_producer == worker_producer - return worker_producer in set(tree_producers) +def selected_by(cfg: RepoConfig, producer: str, tree: Iterable[str]) -> str: + """The rule that runs `producer` on the entry: `scip_producer`, `scip_extra_producers` + or `tree` (the tree calls for it and the entry does not exclude it). '' when no rule + does.""" + if producer == cfg.scip_producer: + return "scip_producer" + if producer in cfg.scip_extra_producers: + return "scip_extra_producers" + if producer in cfg.scip_excluded_producers: + return "" + return "tree" if producer in set(tree) else "" + + +def tier_rules(cfg: RepoConfig, tree: Iterable[str]) -> dict[str, str]: + """The rule behind each tier the entry names or its tree calls for, as + `code.index_status` reports it: `selected_by`, or `EXCLUDED` for a tier the tree calls + for and the entry drops, which does not run.""" + called_for = list(tree) + named = (cfg.scip_producer, *cfg.scip_extra_producers) + producers = dict.fromkeys(p for p in (*named, *called_for) if p) + return {p: selected_by(cfg, p, called_for) or EXCLUDED for p in producers} + + +def runnable_producers(cfg: RepoConfig, tree: Iterable[str] | None = None) -> tuple[str, ...]: + """The tiers the entry runs when its tree calls for the producers in `tree`: the ones + it names, then each other one `selected_by` picks. With the tree unknown (None), every + tier it may run, since its tree can come to call for any of them.""" + named = tuple(p for p in (cfg.scip_producer, *cfg.scip_extra_producers) if p) + called_for = PRODUCERS if tree is None else tuple(tree) + return (*named, *(p for p in PRODUCERS if p not in named and selected_by(cfg, p, called_for))) async def tree_producers(repo: object, org: str, ns: str) -> list[str]: @@ -69,27 +105,54 @@ async def tree_producers(repo: object, org: str, ns: str) -> list[str]: return infer_producers(paths) +async def read_tree(repo: object, cfg: RepoConfig, head: str) -> list[str] | None: + """`tree_producers` of the entry while its indexed head (`git_head`) is `head`, read at + most once per status TTL and head (the workers read their own), so a tier the next head + calls for is waited on from that head's first answer. None when the read fails or the + head moved while it ran, since what it saw may be the next head's tree: a status or + coverage answer then waits on every tier the entry may run, so it never makes a commit + ready early.""" + key = (cfg.org, cfg.namespace, head) + if (tree := _trees.get(key)) is not None: + return tree + try: + tree = await tree_producers(repo, cfg.org, cfg.namespace) + state = await repo.all_state(cfg.org, cfg.namespace) # type: ignore[attr-defined] + except Exception as e: # noqa: BLE001 — a status or coverage answer must not fail on it + degradations.partial("code_index", "compiler_inference_unread", e) + logger.debug("compiler inference unavailable for %s: %s", cfg.namespace, e) + return None + if state_value(state, "git_head") != head: + return None + _trees.put(key, tree) + return tree + + async def worker_owns( repo: object, cfg: RepoConfig, worker_producer: str, ) -> bool: - """The compiler-tier worker's ownership test — the entry's explicit producer, else - (an entry naming none, `''`) the tree's manifests.""" - if worker_producer in cfg.scip_extra_producers: - return True # a further tier the entry names beside its primary one - if cfg.scip_producer: - return cfg.scip_producer == worker_producer + """The compiler-tier worker's ownership test: the entry names the tier, or its tree + calls for it and the entry does not exclude it.""" + if selected_by(cfg, worker_producer, ()): + return True # named: no tree read + if worker_producer in cfg.scip_excluded_producers: + return False tree = await tree_producers(repo, cfg.org, cfg.namespace) - return applies("", worker_producer, tree) + return bool(selected_by(cfg, worker_producer, tree)) __all__ = [ "ALL_MARKERS", + "EXCLUDED", "MARKERS", "PRODUCERS", - "applies", "infer_producers", + "read_tree", + "runnable_producers", + "selected_by", + "tier_rules", "tree_producers", "worker_owns", ] diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 6efb4d3861d..ac058e8ad3e 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -8,7 +8,7 @@ import json import logging import time -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Collection from datetime import UTC, datetime from typing import Any, NamedTuple @@ -35,7 +35,7 @@ from server.code.app.index.ingest_stats import shown_index_error from server.code.app.spans import set_code_span_attributes from server.code.app.ttl_cache import TtlCache -from server.code.domain.index.compiler_tiers import state_value +from server.code.domain.index.compiler_tiers import compiler_tiers, state_value from server.code.domain.index.state import IndexState, shown_detail from server.code.store.index import CodeRepo from server.core.background import create_deferred_task @@ -326,7 +326,8 @@ async def _repo_status(cfg: Any, *, state: IndexState | None = None) -> CodeInde code.index_status (one repo, full detail) and code.repos (every readable repo, summary). `state`: the namespace's state when the caller read every namespace's in one statement; the shared counts row rides in it.""" - from server.code.domain.index.compiler_tiers import WATERMARK_KEYS, compiler_tiers + from server.code.app.index.producer_inference import read_tree, runnable_producers + from server.code.domain.index.compiler_tiers import WATERMARK_KEYS org, ns = cfg.org, cfg.namespace repo = CodeRepo() @@ -370,9 +371,10 @@ def detail(key: str) -> str: lags.update(published_lags(state, {k: val(k) for k in lags}, clone_head)) else: clone_head, lags = await _clone_lags(cfg, state, lags, val) - # The entry's own tier is the headline; every tier with a watermark is - # listed. An entry naming no producer defers to whichever watermark is set. - tiers = compiler_tiers(cfg.scip_producer, state, lags) + # The entry's own tier is the headline, then each other tier it runs over its tree + # now. An entry naming no producer defers to whichever of those is set. + tree = await read_tree(repo, cfg, git_head) + tiers = compiler_tiers(cfg.scip_producer, state, lags, runnable_producers(cfg, tree)) primary = next((t for t in tiers if t["primary"]), None) scip_commit = str(primary["commit"]) if primary else "" scip_lag = int(primary["lag"]) if primary else -1 @@ -410,8 +412,8 @@ def detail(key: str) -> str: logger.debug("code status: worker snapshot unavailable: %s", e) coverage = coverage_fields(counts) - candidates, warnings = await _index_quality( - repo, cfg, state, git_head=git_head, fetch_overdue=fetch_overdue + candidates, rules, warnings = _index_quality( + cfg, state, tree or [], git_head=git_head, fetch_overdue=fetch_overdue ) return CodeIndexStatusOutput( @@ -422,6 +424,7 @@ def detail(key: str) -> str: provider=cfg.provider, profile=cfg.profile, compiler_candidates=candidates, + compiler_tier_rules=rules, quality_warnings=warnings + await _calibration_warnings(org, ns), git_head=git_head, scip_commit=scip_commit, @@ -474,38 +477,42 @@ async def _calibration_warnings(org: str, namespace: str) -> list[str]: ] -async def _index_quality( - repo: CodeRepo, +def _index_quality( cfg: Any, state: IndexState, + candidates: list[str], *, git_head: str, fetch_overdue: bool, -) -> tuple[list[str], list[str]]: - from server.code.app.index.producer_inference import tree_producers - from server.code.domain.index.compiler_tiers import TIERS - - try: - candidates = await tree_producers(repo, cfg.org, cfg.namespace) - except Exception as e: # noqa: BLE001 — diagnostics must not break status - degradations.partial("code_index", "compiler_inference_unread", e) - logger.debug("code status: compiler inference unavailable for %s: %s", cfg.namespace, e) - candidates = [] - - def value(key: str) -> str: - return _s((state.get(key) or {}).get("value")) +) -> tuple[list[str], dict[str, str], list[str]]: + from server.code.app.index.producer_inference import tier_rules warnings: list[str] = [] if not git_head: warnings.append("Fast index has not completed its first pass.") if fetch_overdue: warnings.append("The repository mirror is overdue for a fetch.") + rules = tier_rules(cfg, candidates) + return candidates, rules, warnings + _unrun_tier_warnings(state, candidates, rules) + + +_UNRUN_TIER = "is available for this tree but has not run" + + +def _unrun_tier_warnings( + state: IndexState, candidates: list[str], rules: dict[str, str] +) -> list[str]: + """One warning for each tier the tree calls for that runs on this entry and has no + watermark.""" + from server.code.app.index.producer_inference import EXCLUDED + from server.code.domain.index.compiler_tiers import TIERS + + out: list[str] = [] for producer in candidates: spec = next((tier for tier in TIERS if tier.producer == producer), None) - if spec and not value(spec.watermark_key): - names = ", ".join(spec.workers) - warnings.append(f"{spec.tool} is available for this tree but has not run ({names}).") - return candidates, warnings + if spec and rules[producer] != EXCLUDED and not state_value(state, spec.watermark_key): + out.append(f"{spec.tool} {_UNRUN_TIER} ({', '.join(spec.workers)}).") + return out def published_clone_head(state: IndexState, branch: str) -> str: @@ -672,9 +679,14 @@ async def handle_code_index_status(input: CodeIndexStatusInput) -> CodeIndexStat if input.commit: # Per-commit coverage, after the cached status (it is # this call's question, not the repository's). - _fresh_heads(st, state) # Never a cached head from server.code.app.index.commit_coverage import commit_coverage from server.code.app.index.mirrors import history_dir + from server.code.app.index.producer_inference import read_tree, runnable_producers + + tree = await read_tree(CodeRepo(), cfg, state_value(state, "git_head")) + runs = runnable_producers(cfg, tree) + _fresh_heads(st, state, cfg.scip_producer, runs) # Never a cached head or tier + _fresh_selection(st, cfg, state, tree) git_dir, gap = await history_dir(entry) # the stand-in has no mirror to name cov = await commit_coverage( @@ -709,19 +721,53 @@ async def handle_code_index_status(input: CodeIndexStatusInput) -> CodeIndexStat _NOT_LOOKED_UP: Any = object() -def _fresh_heads(st: CodeIndexStatusOutput, state: IndexState) -> None: - """The heads a coverage answer is judged against, from this call's state read. The cached - status is stale-while-revalidate: a web process not asked for an hour would answer its - hour-old `git_head`, so one call could say a commit was covered and the next that it was - not.""" +def _fresh_heads( + st: CodeIndexStatusOutput, state: IndexState, entry_producer: str, runs: Collection[str] +) -> None: + """The heads and compiler tiers a coverage answer is judged against, the primary tier's + fields and `scip_commit_py`: this call's state read and the tiers the entry `runs` over + its tree now. A lag stays only while its watermark is the one that lag counts from. + The cached status is stale-while-revalidate: a web process not asked for an hour would + answer its hour-old `git_head` and tiers, so one call could say a commit was covered and + the next that it was not. An empty state (a failed read) keeps the cached ones.""" for key in ("git_head", "clone_head"): if value := state_value(state, key): setattr(st, key, value) - st.compiler_tiers = [t.model_copy() for t in st.compiler_tiers] # not the cached row's - for tier in st.compiler_tiers: - if (value := state_value(state, tier.watermark_key)) and value != tier.commit: - tier.commit = value - tier.updated_at = str((state.get(tier.watermark_key) or {}).get("updated_at") or "") + if not state: + return + if (py := state_value(state, "scip_commit_py")) != st.scip_commit_py: + st.scip_commit_py, st.scip_py_lag = py, -1 + lags = { + t.watermark_key: t.lag + for t in st.compiler_tiers + if t.commit == state_value(state, t.watermark_key) + } + tiers = [CodeCompilerTier(**t) for t in compiler_tiers(entry_producer, state, lags, runs)] + primary = next((t for t in tiers if t.primary), None) + st.compiler_tiers = tiers + st.scip_producer = primary.producer if primary else "" + st.scip_commit = primary.commit if primary else "" + st.scip_lag = primary.lag if primary else -1 + + +def _fresh_selection( + st: CodeIndexStatusOutput, cfg: Any, state: IndexState, tree: list[str] | None +) -> None: + """The tiers the tree calls for, the rule behind each and the warnings about the ones + that have not run, from the tree `_fresh_heads` judged the tiers on (none when it is + unread, as in a computed status), so a cached status never names a tier the answer's + cards and coverage have dropped. An empty state keeps the cached ones.""" + from server.code.app.index.producer_inference import tier_rules + + if not state: + return + candidates = tree or [] + rules = tier_rules(cfg, candidates) + st.compiler_candidates, st.compiler_tier_rules = candidates, rules + st.quality_warnings = [ + *(w for w in st.quality_warnings if _UNRUN_TIER not in w), + *_unrun_tier_warnings(state, candidates, rules), + ] async def _state_for_status(org: str, ns: str) -> dict[str, Any]: diff --git a/server/code/app/watches.py b/server/code/app/watches.py index ab1e6a032eb..84b5a7fc250 100644 --- a/server/code/app/watches.py +++ b/server/code/app/watches.py @@ -36,14 +36,28 @@ ACTOR = "process:code_coverage_notify" -async def coverage_for(cfg: Any, commit: str, state: IndexState) -> dict[str, Any]: +async def running_tiers(cfg: Any, state: IndexState) -> tuple[str, ...]: + """The tiers the entry runs over its tree as indexed at `state`'s `git_head`, as the + status reads them.""" + from server.code.app.index.producer_inference import read_tree, runnable_producers + from server.code.domain.index.compiler_tiers import state_value + from server.code.store.index import CodeRepo + + head = state_value(state, "git_head") + return runnable_producers(cfg, await read_tree(CodeRepo(), cfg, head)) + + +async def coverage_for( + cfg: Any, commit: str, state: IndexState, runs: tuple[str, ...] +) -> dict[str, Any]: """`code.index_status`'s `commit_coverage` block for `commit`, judged - against the heads in `state` (the namespace's `code_index_state` rows).""" + against the heads in `state` (the namespace's `code_index_state` rows) and + the tiers the entry `runs` (`running_tiers`).""" from server.code.app.index.commit_coverage import commit_coverage from server.code.app.index.mirrors import history_dir from server.code.domain.index.compiler_tiers import compiler_tiers, state_value - tiers = compiler_tiers(cfg.scip_producer, state, {}) + tiers = compiler_tiers(cfg.scip_producer, state, {}, runs) git_dir, gap = await history_dir(cfg) head = state_value(state, "git_head") return await commit_coverage(git_dir, commit, head, tiers, gap=gap) @@ -179,9 +193,10 @@ async def notify_once(*, limit: int = 5000) -> NotifyResult: unknown += len(rows) continue state = states.get((org, ns)) or {} + runs = await running_tiers(cfg, state) for w in rows: try: - coverage = await coverage_for(cfg, w.commit_sha, state) + coverage = await coverage_for(cfg, w.commit_sha, state, runs) if not coverage.get("ready"): continue posted, _ = await deliver(w, coverage) diff --git a/server/code/domain/index/compiler_tiers.py b/server/code/domain/index/compiler_tiers.py index 58c8b5cf2fa..615ac988302 100644 --- a/server/code/domain/index/compiler_tiers.py +++ b/server/code/domain/index/compiler_tiers.py @@ -11,6 +11,7 @@ from __future__ import annotations +from collections.abc import Collection from typing import Any, NamedTuple from server.code.domain.index.state import IndexState @@ -103,14 +104,15 @@ def normalize_producer(producer: str) -> str: return low -def primary_producer(entry_producer: str, state: IndexState) -> str: +def primary_producer(entry_producer: str, state: IndexState, runs: Collection[str]) -> str: """The tier the entry is configured for; an entry without one (a registry - row) is the tier whose watermark is set, in TIERS order; '' when none.""" + row) is the first tier in TIERS order that it `runs` and whose watermark is + set; '' when none.""" p = normalize_producer(entry_producer) if p: return p for t in TIERS: - if _value(state, t.watermark_key): + if t.producer in runs and _value(state, t.watermark_key): return t.producer return "" @@ -119,15 +121,19 @@ def compiler_tiers( entry_producer: str, state: IndexState, lags: dict[str, int], + runs: Collection[str], ) -> list[dict[str, Any]]: """The cards: the primary tier always (its watermark may be unset — a repository whose first compiler run has not happened yet), then every - other tier whose watermark is set. `lags` is keyed by watermark key.""" - primary = primary_producer(entry_producer, state) + other tier the entry `runs` whose watermark is set. `runs` is + `producer_inference.runnable_producers` over the entry's tree: a tier it + stopped running keeps a watermark nothing moves, so it gets no card and no + readiness check waits on it. `lags` is keyed by watermark key.""" + primary = primary_producer(entry_producer, state, runs) out: list[dict[str, Any]] = [] for t in TIERS: commit = _value(state, t.watermark_key) - if t.producer != primary and not commit: + if t.producer != primary and (not commit or t.producer not in runs): continue row = state.get(t.watermark_key) or {} out.append( diff --git a/server/code/domain/index/repos.py b/server/code/domain/index/repos.py index de9e4783304..909d6a86038 100644 --- a/server/code/domain/index/repos.py +++ b/server/code/domain/index/repos.py @@ -75,6 +75,9 @@ class RepoConfig: # (`checkout_for`) so two producers never move one working tree under each other: # a Python repository with a TypeScript frontend runs both. scip_extra_producers: tuple[str, ...] = () + # Tiers the entry never runs although its tree calls for them (a build file that only + # serves tooling). Every other tier the tree calls for runs beside the named ones. + scip_excluded_producers: tuple[str, ...] = () # The scip-typescript projects when the root is not one (no root tsconfig or # workspace): directories, each with its own tsconfig or indexed through one the # harness writes for its JavaScript. '' = the harness's own inference at the root. @@ -678,6 +681,7 @@ def _configured_from_env(config: Settings, errors: dict[str, str]) -> list[RepoC ), scip_producer=str(e.get("scip_producer") or base.scip_producer), scip_extra_producers=_globs(e.get("scip_extra_producers")), + scip_excluded_producers=_globs(e.get("scip_excluded_producers")), scip_ts_projects=_globs(e.get("scip_ts_projects")), embed_reuse_from=str(e.get("embed_reuse_from") or ""), git_extra_branches=( diff --git a/server/code/workers/crossref.py b/server/code/workers/crossref.py index 526d4b384c9..ce6b1f495d5 100644 --- a/server/code/workers/crossref.py +++ b/server/code/workers/crossref.py @@ -34,12 +34,13 @@ async def run_pass() -> CodeCrossrefResult: with record_pass("code_crossref") as rec: repo = CodeRepo() for cfg in configured_repos(): - if not await worker_owns(repo, cfg, "clang"): - continue - result.repos_checked += 1 - pass_context.set_namespace(cfg.namespace) - pass_context.check_stop() try: + # in the try: a failed read of one entry's tree fails that entry only + if not await worker_owns(repo, cfg, "clang"): + continue + result.repos_checked += 1 + pass_context.set_namespace(cfg.namespace) + pass_context.check_stop() head = await repo.get_state(cfg.org, cfg.namespace, "git_head") if not head or head == await repo.get_state(cfg.org, cfg.namespace, WATERMARK): continue diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index 8cdf5c9a565..c28ecec0424 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -1,17 +1,16 @@ """Per-merge compiler-tier freshness for Go. -`code_scip_delta` keeps the C++ compiler tier current, `code_scip_ts_delta` - the TypeScript one. This worker is the Go row: for every -repository entry whose `scip_producer` is "go" it compares `git_head` with -`scip_commit_go`, moves the configured checkout to `git_head` (fetching from -the LOCAL bare clone code_ingest already advanced — never the network), -works out which Go modules the window touched (the nearest `go.mod` above -every changed `.go` / `go.mod` / `go.sum`; the first run with no watermark -is every module), runs `run_go_monorepo_delta.sh` in DELTA_OUT_DIR mode over -those modules only (scip-go per module, repository-relative paths, generated -documents dropped) and applies each module's -JSON delta in-process through the same validated apply path the upload ops -use. +`code_scip_delta` keeps the C++ compiler tier current, `code_scip_ts_delta` the +TypeScript one. This worker is the Go row: for every repository entry that runs +the Go tier (`producer_inference.worker_owns`) it compares `git_head` with +`scip_commit_go`, moves the configured checkout to `git_head` (fetching from the +LOCAL bare clone code_ingest already advanced — never the network), works out +which Go modules the window touched (the nearest `go.mod` above every changed +`.go` / `go.mod` / `go.sum`; the first run with no watermark is every module), +runs `run_go_monorepo_delta.sh` in DELTA_OUT_DIR mode over those modules only +(scip-go per module, repository-relative paths, generated documents dropped) and +applies each module's JSON delta in-process through the same validated apply +path the upload ops use. scip-go indexes a module whole (a type-checked build), so a window that touched three of hundreds of modules costs three module builds, not the tree; the diff --git a/server/code/workers/scip_py_delta.py b/server/code/workers/scip_py_delta.py index ee7498de2e3..07ca365c735 100644 --- a/server/code/workers/scip_py_delta.py +++ b/server/code/workers/scip_py_delta.py @@ -1,19 +1,19 @@ """Python compiler-tier deltas per merge. -The parser tier binds a Python call through its imports, receivers, chains -and heritage and still misses the calls only -inference types — attributes set on a base in another file, unannotated -parameters, metaclass-built APIs — the compiler tier's ground. Without this -worker an operator runs `scripts/scip_harness/run_python_delta.sh` against -the server with a writer token by hand. For a repository entry whose -`scip_producer` is "python" (explicit, or inferred from its manifests) this -worker compares `git_head` with `scip_commit_py` and, -when the head has moved, runs scip-python and converts the index to a delta -bounded to the Python files the window touched (a first run indexes the -whole tree) in DELTA_OUT mode, then applies it in process — the TypeScript -worker's shape without an install step: scip-python reads -the repository's own modules from the tree and third-party packages from an -environment file the operator may leave empty. +The parser tier binds a Python call through its imports, receivers, chains and +heritage and still misses the calls only inference types — attributes set on a +base in another file, unannotated parameters, metaclass-built APIs — the +compiler tier's ground. Without this worker an operator runs +`scripts/scip_harness/run_python_delta.sh` against the server with a writer +token by hand. For a repository entry that runs the Python tier +(`producer_inference.worker_owns`: it names it, or its tree has a Python build +file it does not exclude) this worker compares `git_head` with `scip_commit_py` +and, when the head has moved, runs scip-python and converts the index to a delta +bounded to the Python files the window touched (a first run indexes the whole +tree) in DELTA_OUT mode, then applies it in process — the TypeScript worker's +shape without an install step: scip-python reads the repository's own modules +from the tree and third-party packages from an environment file the operator may +leave empty. """ from __future__ import annotations diff --git a/server/code/workers/scip_ts_delta.py b/server/code/workers/scip_ts_delta.py index af0a5b34b83..64afc93e36f 100644 --- a/server/code/workers/scip_ts_delta.py +++ b/server/code/workers/scip_ts_delta.py @@ -1,16 +1,16 @@ """Per-merge compiler-tier freshness for TypeScript. -`code_scip_delta` keeps the C++ compiler tier current by running scip-clang -over the changed translation units when the fast tier's `git_head` outruns -`scip_commit`. This worker is the TypeScript row: for every repository -entry whose `scip_producer` is "typescript" it compares `git_head` with -`scip_commit_ts`, moves the configured checkout to `git_head` (fetching -from the LOCAL bare clone code_ingest already advanced — never the -network), runs `run_typescript_delta.sh` in DELTA_OUT mode (scip-typescript -over the workspace, the converter's `--changed-files` bounding the delta to -the window's TypeScript files; the first run with no watermark is a full -index) and applies the JSON delta in-process through the same validated -apply path the upload ops use. +`code_scip_delta` keeps the C++ compiler tier current by running scip-clang over +the changed translation units when the fast tier's `git_head` outruns +`scip_commit`. This worker is the TypeScript row: for every repository entry +that runs the TypeScript tier (`producer_inference.worker_owns`) it compares +`git_head` with `scip_commit_ts`, moves the configured checkout to `git_head` +(fetching from the LOCAL bare clone code_ingest already advanced — never the +network), runs `run_typescript_delta.sh` in DELTA_OUT mode (scip-typescript over +the workspace, the converter's `--changed-files` bounding the delta to the +window's TypeScript files; the first run with no watermark is a full index) and +applies the JSON delta in-process through the same validated apply path the +upload ops use. scip-typescript has no per-file mode, so every pass re-indexes the workspace (~4–5 min for a 5k-file workspace); one pass covers every merge diff --git a/tests/unit/test_code_compiler_tier_runner.py b/tests/unit/test_code_compiler_tier_runner.py index 8438a1998d7..425dc5928a4 100644 --- a/tests/unit/test_code_compiler_tier_runner.py +++ b/tests/unit/test_code_compiler_tier_runner.py @@ -30,6 +30,7 @@ class _Cfg: git_branch = "" scip_producer = "" scip_extra_producers: tuple[str, ...] = () + scip_excluded_producers: tuple[str, ...] = () scip_ts_projects: tuple[str, ...] = () exclude_generated = False source = "config" @@ -86,6 +87,39 @@ async def test_an_entry_the_tier_does_not_own_is_not_counted( assert ctx.count == 0 and _outcome(worker)["reason"] == "current" +@pytest.mark.asyncio +async def test_a_failed_ownership_read_fails_only_its_entry( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The Go pass reads the tree of an entry that names clang, and the read fails. That is + the entry's error, and the next entry, which names Go, still runs.""" + from server.code.workers import scip_go_delta as w + + first, second = _Cfg(tmp_path), _Cfg(tmp_path) + first.namespace, first.scip_producer = "code-a", "clang" + second.namespace, second.scip_producer = "code-b", "go" + repo = _repo(w.WATERMARK) + repo.live_paths_present.side_effect = RuntimeError("manifest read timed out") + ran: list[str] = [] + + async def run_repo(_repo: Any, cfg: Any, _result: Any) -> None: + ran.append(cfg.namespace) + + monkeypatch.setattr(w, "_run_repo", run_repo) + ctx = pass_context.begin("w") + try: + with ( + patch("server.code.store.index.CodeRepo", return_value=repo), + patch("server.code.domain.index.repos.configured_repos", return_value=[first, second]), + ): + result = await w.run_pass() + finally: + pass_context.clear() + assert ran == ["code-b"] + assert result.errors == ["code-a: tree read failed: RuntimeError"] + assert ctx.count == 1 and ctx.failures[0][:2] == ("code-a", "RuntimeError") + + @pytest.mark.asyncio async def test_an_operator_scip_clang_entry_without_its_build_tree_is_skipped( tmp_path: Path, diff --git a/tests/unit/test_code_compiler_tiers.py b/tests/unit/test_code_compiler_tiers.py index dd7410b0fc5..126bb18cfa2 100644 --- a/tests/unit/test_code_compiler_tiers.py +++ b/tests/unit/test_code_compiler_tiers.py @@ -54,8 +54,9 @@ def test_typescript_entry_headlines_its_own_tier_and_lists_the_stale_cpp_key() - scip_commit_ts=(TS_HEAD, "2026-09-18 20:54:08"), ) lags = {"scip_commit": 5, "scip_commit_ts": 0} - assert primary_producer("typescript", state) == "typescript" - tiers = compiler_tiers("typescript", state, lags) + runs = ("typescript", "clang") # a root CMakeLists.txt beside the TypeScript project + assert primary_producer("typescript", state, runs) == "typescript" + tiers = compiler_tiers("typescript", state, lags, runs) assert [t["producer"] for t in tiers] == ["clang", "typescript"] ts = next(t for t in tiers if t["primary"]) assert ts["producer"] == "typescript" and ts["tool"] == "scip-typescript" @@ -68,7 +69,7 @@ def test_typescript_entry_headlines_its_own_tier_and_lists_the_stale_cpp_key() - def test_configured_tier_is_listed_unset_before_its_first_run() -> None: state = _state(git_head=(TS_HEAD, "x")) - tiers = compiler_tiers("go", state, {}) + tiers = compiler_tiers("go", state, {}, ("go",)) assert len(tiers) == 1 assert tiers[0]["producer"] == "go" and tiers[0]["commit"] == "" and tiers[0]["lag"] == -1 assert tiers[0]["updated_at"] == "" and tiers[0]["primary"] is True @@ -76,9 +77,17 @@ def test_configured_tier_is_listed_unset_before_its_first_run() -> None: def test_registry_row_without_a_producer_takes_the_tier_whose_watermark_is_set() -> None: state = _state(scip_commit_py=("a" * 40, "x")) - assert primary_producer("", state) == "python" - assert primary_producer("", {}) == "" - assert compiler_tiers("", {}, {}) == [] + assert primary_producer("", state, ("python",)) == "python" + assert primary_producer("", {}, ("python",)) == "" + assert compiler_tiers("", {}, {}, ()) == [] + + +def test_a_tier_the_entry_no_longer_runs_is_neither_a_card_nor_the_primary() -> None: + """Go ran before the entry excluded it or its last go.mod went: its watermark stays + and is skipped.""" + state = _state(scip_commit_go=("a" * 40, "x"), scip_commit_py=("b" * 40, "x")) + assert primary_producer("", state, ("python",)) == "python" + assert [t["producer"] for t in compiler_tiers("", state, {}, ("python",))] == ["python"] # --- the status handler ------------------------------------------------------ @@ -100,6 +109,12 @@ async def all_state(self, org: str, ns: str) -> dict[str, dict[str, Any]]: async def table_counts(self, org: str, ns: str, **_: Any) -> dict[str, int]: return {"code_files": 3} + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + return {"package.json", "CMakeLists.txt"} # both tiers run + + async def live_paths_named(self, org: str, ns: str, name: str, *, limit: int) -> list[str]: + return [] + class _FakeGit: @staticmethod diff --git a/tests/unit/test_code_coverage_watch.py b/tests/unit/test_code_coverage_watch.py index 4c9e8f5f6d3..2e78c9f0ab6 100644 --- a/tests/unit/test_code_coverage_watch.py +++ b/tests/unit/test_code_coverage_watch.py @@ -58,6 +58,7 @@ def __init__(self, git_dir: str) -> None: self.watches: dict[tuple[str, str, str, str], CoverageWatch] = {} self.events: list[dict[str, Any]] = [] self.state: dict[str, dict[str, Any]] = {} + self.tree: set[str] = {"CMakeLists.txt"} # the build files in the indexed tree self.inboxes = {(ORG, INBOX): {"org": ORG, "inbox": INBOX, "owner_namespace": "bots"}} self.fail_watch_writes = 0 @@ -141,8 +142,21 @@ async def get_state(self, org, ns, key): async def all_state_many(self, pairs): return {p: f.state for p in pairs} + async def live_paths_present(self, org, ns, paths): + return {p for p in paths if p in f.tree} + + async def live_paths_named(self, org, ns, name, *, limit): + return [p for p in f.tree if p.rsplit("/", 1)[-1] == name][:limit] + monkeypatch.setattr(code_repo, "CodeRepo", _State) - cfg = SimpleNamespace(org=ORG, namespace=NS, git_dir=f.git_dir, scip_producer="clang") + cfg = SimpleNamespace( + org=ORG, + namespace=NS, + git_dir=f.git_dir, + scip_producer="clang", + scip_extra_producers=(), + scip_excluded_producers=(), + ) monkeypatch.setattr( repos, "repo_for_namespace", lambda o, n: cfg if (o, n) == (ORG, NS) else None ) @@ -193,6 +207,111 @@ async def test_watch_then_the_pass_once_covered_emits_one_event( assert (got.pending, got.emitted) == (0, 0) and len(fake.events) == 1 +@pytest.mark.asyncio +async def test_a_tier_excluded_after_it_ran_holds_back_no_watch( + fake: Fake, history: tuple[str, list[str]] +) -> None: + """Go indexed up to A before the entry excluded it, and its watermark never moves + again: a commit the fast and C++ tiers cover is delivered.""" + from server.code.domain.index import repos + + _, (a, b, c) = history + repos.repo_for_namespace(ORG, NS).scip_excluded_producers = ("go",) + fake.state = { + "git_head": {"value": c}, + "scip_commit": {"value": b}, + "scip_commit_go": {"value": a}, + } + out = await h.handle_code_coverage_watch(_watch(b)) + assert out.commit_coverage is not None and out.commit_coverage.waiting_on == [] + assert out.ready and out.emitted and len(fake.events) == 1 + + +@pytest.mark.asyncio +async def test_a_tier_whose_last_build_file_went_holds_back_no_watch( + fake: Fake, history: tuple[str, list[str]] +) -> None: + """The tree called for Go, which indexed up to A, until C removed the last go.mod. + The Go worker stops there, so the first pass at C delivers a watch on B that the + fast and C++ tiers cover, while the tree read at B is still fresh.""" + _, (a, b, c) = history + fake.tree = {"CMakeLists.txt", "tools/go.mod"} + fake.state = { + "git_head": {"value": b}, + "scip_commit": {"value": b}, + "scip_commit_go": {"value": a}, + } + out = await h.handle_code_coverage_watch(_watch(b)) + assert out.commit_coverage is not None and out.commit_coverage.waiting_on == ["Go"] + + fake.tree = {"CMakeLists.txt"} + fake.state["git_head"] = {"value": c} + got = await svc.notify_once() + assert (got.delivered, got.emitted) == (1, 1) and len(fake.events) == 1 + out = await h.handle_code_coverage_watch(_watch(b)) + assert out.commit_coverage is not None and out.commit_coverage.waiting_on == [] + + +@pytest.mark.asyncio +async def test_a_tier_whose_build_file_returns_holds_back_the_watch( + fake: Fake, history: tuple[str, list[str]] +) -> None: + """A has no go.mod and Go's watermark stays at A. B adds a go.mod, so once the fast + and C++ tiers reach B the watch on B waits for Go, while the tree read at A is still + fresh.""" + _, (a, b, _) = history + fake.state = { + "git_head": {"value": a}, + "scip_commit": {"value": a}, + "scip_commit_go": {"value": a}, + } + out = await h.handle_code_coverage_watch(_watch(b)) + assert not out.ready + + fake.tree = {"CMakeLists.txt", "go.mod"} + fake.state["git_head"] = fake.state["scip_commit"] = {"value": b} + got = await svc.notify_once() + assert (got.delivered, got.emitted) == (0, 0) and not fake.events + out = await h.handle_code_coverage_watch(_watch(b)) + assert out.commit_coverage is not None and out.commit_coverage.waiting_on == ["Go"] + + fake.state["scip_commit_go"] = {"value": b} + got = await svc.notify_once() + assert (got.delivered, got.emitted) == (1, 1) and len(fake.events) == 1 + + +@pytest.mark.asyncio +async def test_a_tree_read_while_the_head_moves_does_not_decide_the_tiers_of_the_old_head( + fake: Fake, history: tuple[str, list[str]], monkeypatch: pytest.MonkeyPatch +) -> None: + """The pass judges B, which has a go.mod. C removes it and is published while the tree + is read, so the read sees C's tree. B's tiers then stay every tier the entry may run, + so Go is still waited on.""" + from server.code.store import index as code_repo + + _, (_, b, c) = history + fake.tree = {"CMakeLists.txt", "go.mod"} + fake.state = {"git_head": {"value": b}, "scip_commit": {"value": b}} + at_b = dict(fake.state) + state_repo = code_repo.CodeRepo + + class HeadMoves(state_repo): # type: ignore[valid-type, misc] + async def live_paths_present(self, org, ns, paths): + fake.tree.discard("go.mod") + fake.state["git_head"] = {"value": c} + return await super().live_paths_present(org, ns, paths) + + monkeypatch.setattr(code_repo, "CodeRepo", HeadMoves) + cfg = SimpleNamespace( + org=ORG, + namespace=NS, + scip_producer="clang", + scip_extra_producers=(), + scip_excluded_producers=(), + ) + assert "go" in await svc.running_tiers(cfg, at_b) + + @pytest.mark.asyncio async def test_a_crash_between_the_event_and_the_watch_update_does_not_duplicate( fake: Fake, history: tuple[str, list[str]] @@ -222,7 +341,8 @@ async def test_two_racing_deliveries_report_one_emitted_event( await h.handle_code_coverage_watch(_watch(b)) fake.set_heads(fast=c, clang=c) watch = fake.watches[(ORG, NS, b, INBOX)] - coverage = await svc.coverage_for(repos.repo_for_namespace(ORG, NS), b, fake.state) + cfg = repos.repo_for_namespace(ORG, NS) + coverage = await svc.coverage_for(cfg, b, fake.state, ("clang",)) # The event check yields, so without the delivery's lease both deliverers # would check before either posted. @@ -319,7 +439,10 @@ async def test_a_commit_the_index_has_not_reached_is_watched_by_its_full_sha( assert [t.covered for t in coverage.tiers] == [None] assert coverage.waiting_on == ["commit not in the index's mirror yet"] unknown = await svc.coverage_for( - SimpleNamespace(git_dir=fake.git_dir, scip_producer="clang"), "f" * 40, fake.state + SimpleNamespace(git_dir=fake.git_dir, scip_producer="clang"), + "f" * 40, + fake.state, + ("clang",), ) assert coverage.model_dump() == {**unknown, "commit": c} diff --git a/tests/unit/test_code_passes_derive_once.py b/tests/unit/test_code_passes_derive_once.py index ff07e9d6ac2..c9ad31fa7cc 100644 --- a/tests/unit/test_code_passes_derive_once.py +++ b/tests/unit/test_code_passes_derive_once.py @@ -474,7 +474,10 @@ async def pending_watches(*, limit: int) -> list[Any]: async def states(self: Any, pairs: list[tuple[str, str]]) -> dict[Any, Any]: return {} - async def coverage_for(cfg: Any, commit: str, state: Any) -> dict[str, Any]: + async def running_tiers(cfg: Any, state: Any) -> tuple[str, ...]: + return () + + async def coverage_for(cfg: Any, commit: str, state: Any, runs: Any) -> dict[str, Any]: return {"ready": commit != "c4", "repo": cfg.repo} async def deliver(watch: Any, coverage: dict[str, Any]) -> tuple[bool, Any]: @@ -483,6 +486,7 @@ async def deliver(watch: Any, coverage: dict[str, Any]) -> tuple[bool, Any]: monkeypatch.setattr(watches.repo, "pending_watches", pending_watches) monkeypatch.setattr("server.code.store.index.CodeRepo.all_state_many", states) + monkeypatch.setattr(watches, "running_tiers", running_tiers) monkeypatch.setattr(watches, "coverage_for", coverage_for) monkeypatch.setattr(watches, "deliver", deliver) return await watches.notify_once(), delivered diff --git a/tests/unit/test_code_repo_indexing_knobs.py b/tests/unit/test_code_repo_indexing_knobs.py index 60990b4fa74..c9e2a1d8782 100644 --- a/tests/unit/test_code_repo_indexing_knobs.py +++ b/tests/unit/test_code_repo_indexing_knobs.py @@ -33,12 +33,38 @@ def test_manifests_name_their_producers() -> None: assert pi.infer_producers(["README.md", "docs/a.md"]) == [] -def test_explicit_producer_wins_and_empty_defers_to_the_tree() -> None: - assert pi.applies("clang", "clang", ["go"]) is True # an .env entry's default - assert pi.applies("clang", "go", ["go"]) is False - assert pi.applies("", "go", ["go", "typescript"]) is True - assert pi.applies("", "typescript", ["go"]) is False - assert pi.applies("", "clang", []) is False +def test_a_named_tier_runs_and_a_detected_one_runs_unless_excluded() -> None: + named = _Entry(scip_producer="clang", scip_extra_producers=("typescript",)) + assert pi.selected_by(named, "clang", ["go"]) == "scip_producer" + assert pi.selected_by(named, "typescript", []) == "scip_extra_producers" + assert pi.selected_by(named, "go", ["go"]) == "tree" + assert pi.selected_by(named, "python", ["go"]) == "" + excluding = _Entry(scip_producer="clang", scip_excluded_producers=("python",)) + assert pi.selected_by(excluding, "python", ["python"]) == "" + # naming a tier beats excluding it + both = _Entry(scip_producer="python", scip_excluded_producers=("python",)) + assert pi.selected_by(both, "python", ["python"]) == "scip_producer" + # an entry naming none defers to its tree + assert pi.selected_by(_Entry(), "go", ["go", "typescript"]) == "tree" + assert pi.selected_by(_Entry(), "clang", []) == "" + + +def test_the_status_names_the_rule_behind_each_tier() -> None: + cfg = _Entry( + scip_producer="python", + scip_extra_producers=("typescript",), + scip_excluded_producers=("clang",), + ) + assert pi.tier_rules(cfg, ["go", "clang", "typescript", "python"]) == { + "python": "scip_producer", + "typescript": "scip_extra_producers", + "go": "tree", + "clang": "scip_excluded_producers", + } + assert pi.tier_rules(cfg, []) == { + "python": "scip_producer", + "typescript": "scip_extra_producers", + } @pytest.mark.asyncio @@ -61,7 +87,7 @@ def _Entry(**kw: Any) -> Any: @pytest.mark.asyncio -async def test_worker_ownership_by_explicit_producer_or_by_marker() -> None: +async def test_worker_ownership_by_name_or_by_marker() -> None: repo = AsyncMock() repo.live_paths_present.return_value = {"go.mod"} repo.live_paths_named.return_value = [] @@ -69,9 +95,96 @@ async def test_worker_ownership_by_explicit_producer_or_by_marker() -> None: assert await pi.worker_owns(repo, _Entry(), "typescript") is False assert await pi.worker_owns(repo, _Entry(), "clang") is False - assert await pi.worker_owns(repo, _Entry(scip_producer="clang"), "clang") is True - assert await pi.worker_owns(repo, _Entry(scip_producer="clang"), "go") is False - repo.live_paths_present.assert_awaited() # only the inferred entry read the tree + # a named tier owns its entry without a tree read + quiet = AsyncMock() + assert await pi.worker_owns(quiet, _Entry(scip_producer="clang"), "clang") is True + quiet.live_paths_present.assert_not_awaited() + # a tier the tree calls for runs beside the named one + assert await pi.worker_owns(repo, _Entry(scip_producer="clang"), "go") is True + assert await pi.worker_owns(repo, _Entry(scip_producer="clang"), "typescript") is False + + +def test_the_tiers_an_entry_runs_follow_its_tree() -> None: + cfg = _Entry(scip_producer="clang", scip_excluded_producers=("python",)) + assert pi.runnable_producers(cfg, ["go", "python"]) == ("clang", "go") + assert pi.runnable_producers(cfg, []) == ("clang",) + # the tree unknown: every tier the entry may run + assert pi.runnable_producers(cfg) == ("clang", "go", "typescript") + + +@pytest.mark.asyncio +async def test_an_unread_tree_is_none_not_an_empty_one() -> None: + """A status or coverage answer then waits on every tier the entry may run.""" + repo = AsyncMock() + repo.live_paths_present.side_effect = RuntimeError("manifest read timed out") + assert await pi.read_tree(repo, _Entry(scip_producer="clang"), "b" * 40) is None + + +@pytest.mark.asyncio +async def test_a_tree_read_while_the_head_moves_is_not_kept_for_the_old_head() -> None: + """The next head is published while the read runs, so what it saw is that head's tree. + The old head gets no entry from it, and the caller judging on the old head is told the + tree is unread.""" + cfg = _Entry(scip_producer="clang") + b, c = "b" * 40, "c" * 40 + + class HeadMoves: + head, paths, moves = b, {"go.mod"}, True + + async def all_state(self, org: str, ns: str) -> dict[str, Any]: + return {"git_head": {"value": self.head}} + + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + if self.moves: + self.head, self.paths = c, set() # c removes the go.mod + return {p for p in paths if p in self.paths} + + async def live_paths_named(self, org: str, ns: str, name: str, *, limit: int) -> list[str]: + return [] + + repo = HeadMoves() + assert await pi.read_tree(repo, cfg, b) is None + repo.head, repo.moves = b, False + repo.paths = {"go.mod"} + assert await pi.read_tree(repo, cfg, b) == ["go"] + + +@pytest.mark.asyncio +async def test_a_tree_read_is_kept_but_a_failed_one_is_not() -> None: + """A tree with no build file is an answer and is kept for its head; a failed read is + retried, and so is a read at a new head.""" + cfg = _Entry(scip_producer="clang") + b, c = "b" * 40, "c" * 40 + failing = AsyncMock() + failing.live_paths_present.side_effect = RuntimeError("manifest read timed out") + assert await pi.read_tree(failing, cfg, b) is None + bare = AsyncMock() + bare.live_paths_present.return_value = set() + bare.live_paths_named.return_value = [] + bare.all_state.return_value = {"git_head": {"value": b}} + assert await pi.read_tree(bare, cfg, b) == [] + assert await pi.read_tree(bare, cfg, b) == [] + assert bare.live_paths_present.await_count == 1 + bare.all_state.return_value = {"git_head": {"value": c}} + assert await pi.read_tree(bare, cfg, c) == [] + assert bare.live_paths_present.await_count == 2 + + +@pytest.mark.asyncio +async def test_an_excluded_tier_does_not_run_though_the_tree_calls_for_it() -> None: + repo = AsyncMock() + repo.live_paths_present.return_value = {"go.mod", "pyproject.toml"} + repo.live_paths_named.return_value = [] + cfg = _Entry(scip_producer="clang", scip_excluded_producers=("python",)) + assert await pi.worker_owns(repo, cfg, "go") is True + repo.live_paths_present.reset_mock() + assert await pi.worker_owns(repo, cfg, "python") is False + repo.live_paths_present.assert_not_awaited() # the entry's answer needs no tree read + # an entry naming no producer can exclude too + assert await pi.worker_owns(repo, _Entry(scip_excluded_producers=("go",)), "go") is False + # a tier the entry names runs even when it is also excluded + both = _Entry(scip_extra_producers=("python",), scip_excluded_producers=("python",)) + assert await pi.worker_owns(repo, both, "python") is True def test_registry_row_carries_the_knobs_and_defaults_them_for_old_rows() -> None: diff --git a/tests/unit/test_code_scip_extra_producers.py b/tests/unit/test_code_scip_extra_producers.py index dc3edaa2a8f..75e3e4b8498 100644 --- a/tests/unit/test_code_scip_extra_producers.py +++ b/tests/unit/test_code_scip_extra_producers.py @@ -1,12 +1,14 @@ """A repository entry can run more than one compiler tier: `scip_extra_producers` -names the tiers beside its primary `scip_producer`, each in its own checkout, and -`scip_ts_projects` names the TypeScript projects of a tree whose root is not one.""" +names the tiers beside its primary `scip_producer`, each in its own checkout, a tier its +tree calls for runs too unless `scip_excluded_producers` drops it, and `scip_ts_projects` +names the TypeScript projects of a tree whose root is not one.""" from __future__ import annotations import asyncio import json from pathlib import Path +from unittest.mock import AsyncMock import pytest @@ -32,11 +34,36 @@ def _cfg(**kw) -> RepoConfig: return RepoConfig(**base) +def _tree(*manifests: str) -> AsyncMock: + """A repository whose live tree holds these build files (a `go.mod` at the root).""" + repo = AsyncMock() + repo.live_paths_present.return_value = set(manifests) + repo.live_paths_named.return_value = [] + return repo + + def test_extra_producers_are_owned_beside_the_primary_one() -> None: cfg = _cfg(scip_extra_producers=("typescript",)) - owned = {p: asyncio.run(worker_owns(None, cfg, p)) for p in ("python", "typescript", "go")} + bare = _tree() + owned = {p: asyncio.run(worker_owns(bare, cfg, p)) for p in ("python", "typescript", "go")} assert owned == {"python": True, "typescript": True, "go": False} - assert not asyncio.run(worker_owns(None, _cfg(), "typescript")) + assert not asyncio.run(worker_owns(bare, _cfg(), "typescript")) + + +def test_a_tier_the_tree_calls_for_runs_beside_the_named_ones() -> None: + cfg = _cfg(scip_extra_producers=("typescript",)) + tree = _tree("pyproject.toml", "go.mod", "CMakeLists.txt") + owned = { + p: asyncio.run(worker_owns(tree, cfg, p)) for p in ("python", "typescript", "go", "clang") + } + assert owned == {"python": True, "typescript": True, "go": True, "clang": True} + + +def test_an_excluded_tier_stays_off_though_the_tree_calls_for_it() -> None: + cfg = _cfg(scip_producer="clang", scip_excluded_producers=("python",)) + tree = _tree("CMakeLists.txt", "pyproject.toml", "go.mod") + owned = {p: asyncio.run(worker_owns(tree, cfg, p)) for p in ("clang", "python", "go")} + assert owned == {"clang": True, "python": False, "go": True} def test_each_extra_producer_indexes_its_own_checkout() -> None: @@ -65,11 +92,13 @@ def test_the_entry_json_carries_the_extra_producers_and_the_projects(monkeypatch "repo": "o/x", "scip_producer": "python", "scip_extra_producers": ["typescript"], + "scip_excluded_producers": ["clang", "go"], "scip_ts_projects": "frontend, sdk/typescript", } monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) (cfg,) = repos._configured_from_env(settings, {}) assert cfg.scip_extra_producers == ("typescript",) + assert cfg.scip_excluded_producers == ("clang", "go") assert cfg.scip_ts_projects == ("frontend", "sdk/typescript") diff --git a/tests/unit/test_code_scip_full_worker.py b/tests/unit/test_code_scip_full_worker.py index a518bf3ad2e..8d60752781d 100644 --- a/tests/unit/test_code_scip_full_worker.py +++ b/tests/unit/test_code_scip_full_worker.py @@ -149,6 +149,31 @@ async def test_crossref_runs_once_per_git_head(tmp_path, monkeypatch): assert state[("code-a", "crossref_commit")] == "a" * 40 +@pytest.mark.asyncio +async def test_a_failed_ownership_read_fails_only_its_crossref_entry(tmp_path, monkeypatch): + """Crossref reads the tree of an entry that names Go, and the read fails. That is the + entry's error, and the next entry, which names clang, still gets its pass.""" + from server.code.domain.extract import crossref as extract + + state = {("code-b", "git_head"): "b" * 40} + monkeypatch.setattr( + extract, "run_crossref_pass", AsyncMock(return_value=extract.CrossrefResult()) + ) + repo = _repo(state) + repo.live_paths_present.side_effect = RuntimeError("manifest read timed out") + go_entry = repo_config(org="o", namespace="code-a", scip_producer="go") + with ( + patch("server.code.store.index.CodeRepo", return_value=repo), + patch( + "server.code.domain.index.repos.configured_repos", + return_value=[go_entry, _cfg(tmp_path, "code-b")], + ), + ): + result = await crossref.run_pass() + assert result.passes_run == 1 and state[("code-b", "crossref_commit")] == "b" * 40 + assert result.errors == ["code-a: RuntimeError: manifest read timed out"] + + @pytest.mark.asyncio async def test_every_hours_zero_only_seeds(tmp_path, monkeypatch): from server.settings import settings diff --git a/tests/unit/test_code_status_ops.py b/tests/unit/test_code_status_ops.py index 8f53691ebd1..c929d7f894a 100644 --- a/tests/unit/test_code_status_ops.py +++ b/tests/unit/test_code_status_ops.py @@ -202,6 +202,310 @@ async def test_index_status_reports_lag_and_refresh_breadcrumb() -> None: assert out.path_prefixes == [""] +@pytest.mark.asyncio +async def test_index_status_names_the_rule_behind_each_compiler_tier( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import json + + from server.code.api.models_status import CodeIndexStatusInput + + class MixedTree(_FakeRepo): + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + return {"package.json", "pyproject.toml"} + + async def live_paths_named(self, org: str, ns: str, name: str, *, limit: int) -> list[str]: + return ["tools/go.mod"] + + entry = { + "namespace": "code-clickhouse", + "scip_producer": "clang", + "scip_extra_producers": ["typescript"], + "scip_excluded_producers": ["python"], + } + monkeypatch.setattr(index_status, "CodeRepo", MixedTree) + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + + out = await index_status.handle_code_index_status(CodeIndexStatusInput()) + + assert out.compiler_candidates == ["go", "typescript", "python"] + assert out.compiler_tier_rules == { + "clang": "scip_producer", + "typescript": "scip_extra_producers", + "go": "tree", + "python": "scip_excluded_producers", + } + # the excluded tier is no readiness gap: only the two that run and have not yet + assert [w for w in out.quality_warnings if w.startswith("scip-")] == [ + "scip-go is available for this tree but has not run (code_scip_go_delta).", + "scip-typescript is available for this tree but has not run (code_scip_ts_delta).", + ] + + +@pytest.mark.asyncio +async def test_a_tier_excluded_after_it_ran_holds_back_no_commit( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Go indexed up to A before the entry excluded it. Its watermark stays at A and + never moves, so a commit the fast and Python tiers hold at B is ready.""" + import json + + from server.code.api.models_status import CodeIndexStatusInput + from server.code.app.index import mirrors + + a, b = "a" * 40, "b" * 40 + + class GoLeftBehind(_FakeRepo): + async def all_state(self, org: str, ns: str) -> dict[str, dict[str, Any]]: + return { + "git_head": {"value": b}, + "scip_commit_py": {"value": b}, + "scip_commit_go": {"value": a}, + } + + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + return {"go.mod", "pyproject.toml"} + + async def no_mirror(cfg: Any, **_: Any) -> tuple[str, str]: + return "", "no mirror here" + + entry = { + "namespace": "code-clickhouse", + "scip_producer": "python", + "scip_excluded_producers": ["go"], + } + monkeypatch.setattr(index_status, "CodeRepo", GoLeftBehind) + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + monkeypatch.setattr(mirrors, "history_dir", no_mirror) + + out = await index_status.handle_code_index_status(CodeIndexStatusInput(commit=b)) + + assert out.compiler_tier_rules["go"] == "scip_excluded_producers" + assert out.commit_coverage is not None + assert (out.commit_coverage.ready, out.commit_coverage.waiting_on) == (True, []) + assert [t.producer for t in out.compiler_tiers] == ["python"] + + +@pytest.mark.asyncio +async def test_a_tier_whose_last_build_file_went_holds_back_no_commit( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A clang entry's tree called for Go at A, and B removed its last go.mod. The Go + worker stops with its watermark at A, so a commit the fast and C++ tiers hold at B + is ready.""" + import json + + from server.code.api.models_status import CodeIndexStatusInput + from server.code.app.index import mirrors + from server.code.app.index.producer_inference import worker_owns + from server.code.domain.index.repos import repo_for_namespace + + a, b = "a" * 40, "b" * 40 + + class GoModGone(_FakeRepo): + async def all_state(self, org: str, ns: str) -> dict[str, dict[str, Any]]: + return { + "git_head": {"value": b}, + "scip_commit": {"value": b}, + "scip_commit_go": {"value": a}, + } + + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + return {"CMakeLists.txt"} + + async def live_paths_named(self, org: str, ns: str, name: str, *, limit: int) -> list[str]: + return [] + + async def no_mirror(cfg: Any, **_: Any) -> tuple[str, str]: + return "", "no mirror here" + + entry = {"namespace": "code-clickhouse", "scip_producer": "clang"} + monkeypatch.setattr(index_status, "CodeRepo", GoModGone) + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + monkeypatch.setattr(mirrors, "history_dir", no_mirror) + + out = await index_status.handle_code_index_status(CodeIndexStatusInput(commit=b)) + + cfg = repo_for_namespace(out.org, out.namespace) + assert cfg is not None and not await worker_owns(GoModGone(), cfg, "go") + assert out.commit_coverage is not None + assert (out.commit_coverage.ready, out.commit_coverage.waiting_on) == (True, []) + assert [t.producer for t in out.compiler_tiers] == ["clang"] + + +@pytest.mark.asyncio +async def test_a_tree_the_status_cannot_read_keeps_every_tier_the_entry_may_run( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Without the tree the status cannot tell that Go stopped, so the commit waits on it + rather than answering ready early.""" + import json + + from server.code.api.models_status import CodeIndexStatusInput + from server.code.app.index import mirrors + + a, b = "a" * 40, "b" * 40 + + class TreeUnread(_FakeRepo): + async def all_state(self, org: str, ns: str) -> dict[str, dict[str, Any]]: + return { + "git_head": {"value": b}, + "scip_commit": {"value": b}, + "scip_commit_go": {"value": a}, + } + + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + raise RuntimeError("manifest read timed out") + + async def no_mirror(cfg: Any, **_: Any) -> tuple[str, str]: + return "", "no mirror here" + + entry = {"namespace": "code-clickhouse", "scip_producer": "clang"} + monkeypatch.setattr(index_status, "CodeRepo", TreeUnread) + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + monkeypatch.setattr(mirrors, "history_dir", no_mirror) + + out = await index_status.handle_code_index_status(CodeIndexStatusInput(commit=b)) + + assert out.compiler_candidates == [] + assert [t.producer for t in out.compiler_tiers] == ["clang", "go"] + assert out.commit_coverage is not None and out.commit_coverage.waiting_on == ["Go"] + + +@pytest.mark.asyncio +async def test_a_commit_is_judged_on_the_tiers_the_tree_calls_for_now_not_the_cached_ones( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A head that drops the go.mod, then one that brings it back, changes whether its + commit waits on Go at the next call, while the status and the tree read at the head + before are still cached.""" + import json + + from server.code.api.models_status import CodeIndexStatusInput + from server.code.app.index import mirrors + + a = "a" * 40 + head = "b" * 40 + tree = {"CMakeLists.txt", "go.mod"} + + class GoModComesAndGoes(_FakeRepo): + async def all_state(self, org: str, ns: str) -> dict[str, dict[str, Any]]: + return { + "git_head": {"value": head}, + "scip_commit": {"value": head}, + "scip_commit_go": {"value": a}, + } + + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + return {p for p in paths if p in tree} + + async def live_paths_named(self, org: str, ns: str, name: str, *, limit: int) -> list[str]: + return [] + + async def no_mirror(cfg: Any, **_: Any) -> tuple[str, str]: + return "", "no mirror here" + + entry = {"namespace": "code-clickhouse", "scip_producer": "clang"} + monkeypatch.setattr(index_status, "CodeRepo", GoModComesAndGoes) + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + monkeypatch.setattr(mirrors, "history_dir", no_mirror) + + async def answer() -> Any: + out = await index_status.handle_code_index_status(CodeIndexStatusInput(commit=head)) + assert out.commit_coverage is not None + return out + + # the selection fields and the warnings follow the same tree as the coverage + out = await answer() + assert out.commit_coverage.waiting_on == ["Go"] + assert out.compiler_candidates == ["go", "clang"] + assert out.compiler_tier_rules == {"clang": "scip_producer", "go": "tree"} + tree.discard("go.mod") + head = "c" * 40 + out = await answer() + assert out.commit_coverage.waiting_on == [] + assert out.compiler_candidates == ["clang"] + assert out.compiler_tier_rules == {"clang": "scip_producer"} + tree.add("go.mod") # Go resumes from its watermark at A + head = "d" * 40 + assert (await answer()).commit_coverage.waiting_on == ["Go"] + + +@pytest.mark.asyncio +async def test_a_warning_about_a_tier_the_tree_no_longer_calls_for_goes_with_it( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Go has never run. The cached status warns about it while the tree has a go.mod. A + commit asked after the last go.mod went is answered without that warning.""" + import json + + from server.code.api.models_status import CodeIndexStatusInput + from server.code.app.index import mirrors + + tree = {"CMakeLists.txt", "go.mod"} + + class GoModGoes(_FakeRepo): + async def all_state(self, org: str, ns: str) -> dict[str, dict[str, Any]]: + return {"git_head": {"value": head}, "scip_commit": {"value": head}} + + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + return {p for p in paths if p in tree} + + async def live_paths_named(self, org: str, ns: str, name: str, *, limit: int) -> list[str]: + return [] + + async def no_mirror(cfg: Any, **_: Any) -> tuple[str, str]: + return "", "no mirror here" + + head = "b" * 40 + entry = {"namespace": "code-clickhouse", "scip_producer": "clang"} + monkeypatch.setattr(index_status, "CodeRepo", GoModGoes) + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + monkeypatch.setattr(mirrors, "history_dir", no_mirror) + + out = await index_status.handle_code_index_status(CodeIndexStatusInput(commit=head)) + assert [w for w in out.quality_warnings if w.startswith("scip-go")] + tree.discard("go.mod") + head = "c" * 40 + out = await index_status.handle_code_index_status(CodeIndexStatusInput(commit=head)) + assert out.compiler_candidates == ["clang"] + assert not [w for w in out.quality_warnings if w.startswith("scip-go")] + + +@pytest.mark.asyncio +async def test_a_poller_reads_the_tree_once_per_status_ttl( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A commit poll asks for the tree on every call; the status and the polls inside one + status TTL share one read of it.""" + import json + + from server.code.api.models_status import CodeIndexStatusInput + from server.code.app.index import mirrors + + reads: list[str] = [] + + class CountedTree(_FakeRepo): + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> set[str]: + reads.append(ns) + return {"CMakeLists.txt"} + + async def live_paths_named(self, org: str, ns: str, name: str, *, limit: int) -> list[str]: + return [] + + async def no_mirror(cfg: Any, **_: Any) -> tuple[str, str]: + return "", "no mirror here" + + entry = {"namespace": "code-clickhouse", "scip_producer": "clang"} + monkeypatch.setattr(index_status, "CodeRepo", CountedTree) + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + monkeypatch.setattr(mirrors, "history_dir", no_mirror) + + for _ in range(3): + await index_status.handle_code_index_status(CodeIndexStatusInput(commit="b" * 40)) + assert reads == ["code-clickhouse"] + + @pytest.mark.asyncio async def test_index_status_uses_repo_entry_branch_not_scalar() -> None: from server.code.api.models_status import CodeIndexStatusInput diff --git a/tests/unit/test_coverage_fresh_heads.py b/tests/unit/test_coverage_fresh_heads.py index 4a8080c6495..4cfdeaf3e4a 100644 --- a/tests/unit/test_coverage_fresh_heads.py +++ b/tests/unit/test_coverage_fresh_heads.py @@ -32,15 +32,74 @@ def test_a_stale_cached_status_takes_the_fresh_state_rows() -> None: "clone_head": {"value": b"5e65b017\x00"}, "scip_commit": {"value": "5e65b017", "updated_at": "2026-09-25 17:32:00"}, } - _fresh_heads(st, state) + _fresh_heads(st, state, "clang", ("clang",)) assert (st.git_head, st.clone_head) == ("585f97e8", "5e65b017") assert st.compiler_tiers[0].commit == "5e65b017" assert st.compiler_tiers[0].updated_at == "2026-09-25 17:32:00" + # the cached lag counted from old0, not from the watermark the card now shows + assert st.compiler_tiers[0].lag == -1 # the cached row itself is untouched (model_copy is shallow) assert cached.git_head == "5d00ecff" and cached.compiler_tiers[0].commit == "old0" def test_an_empty_state_read_keeps_the_cached_heads() -> None: st = _cached().model_copy() - _fresh_heads(st, {}) + _fresh_heads(st, {}, "clang", ("clang",)) assert st.git_head == "5d00ecff" and st.compiler_tiers[0].commit == "old0" + + +def test_a_cached_card_of_a_tier_the_entry_stopped_running_goes() -> None: + """Go's card is cached from before its last go.mod went: this call's tiers decide.""" + st = _cached().model_copy() + go = st.compiler_tiers[0].model_copy( + update={"producer": "go", "label": "Go", "watermark_key": "scip_commit_go"} + ) + st.compiler_tiers = [*st.compiler_tiers, go] + state = {"scip_commit": {"value": "old0"}, "scip_commit_go": {"value": "0ld60"}} + _fresh_heads(st, state, "clang", ("clang",)) + assert [(t.producer, t.commit, t.lag) for t in st.compiler_tiers] == [("clang", "old0", 3)] + + +def test_the_primary_fields_follow_the_fresh_tiers() -> None: + """An entry naming no producer was cached with Go as its primary; its tree now calls for + Python only, so the answer names Python as the primary throughout.""" + st = CodeIndexStatusOutput.model_construct( + git_head="5d00ecff", + clone_head="5d00ecff", + scip_producer="go", + scip_commit="a" * 8, + scip_lag=2, + compiler_tiers=[ + CodeCompilerTier( + producer="go", + tool="scip-go", + label="Go", + watermark_key="scip_commit_go", + commit="a" * 8, + lag=2, + primary=True, + ) + ], + ) + state = {"scip_commit_go": {"value": "a" * 8}, "scip_commit_py": {"value": "b" * 8}} + _fresh_heads(st, state, "", ("python",)) + assert [(t.producer, t.primary) for t in st.compiler_tiers] == [("python", True)] + assert (st.scip_producer, st.scip_commit, st.scip_lag) == ("python", "b" * 8, -1) + + +def test_the_python_watermark_by_name_follows_the_state_too() -> None: + st = _cached().model_copy(update={"scip_commit_py": "0ldpy", "scip_py_lag": 4}) + _fresh_heads( + st, + {"scip_commit": {"value": "old0"}, "scip_commit_py": {"value": "0ldpy"}}, + "clang", + ("clang",), + ) + assert (st.scip_commit_py, st.scip_py_lag) == ("0ldpy", 4) + _fresh_heads( + st, + {"scip_commit": {"value": "old0"}, "scip_commit_py": {"value": "n3wpy"}}, + "clang", + ("clang",), + ) + assert (st.scip_commit_py, st.scip_py_lag) == ("n3wpy", -1) diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index 5bff67483ac..bb85fbe351f 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -23,6 +23,7 @@ def __init__(self, git_dir: str, ns: str = "code-r", source: str = "config") -> self.source, self.git_fetch_pr_heads = source, True self.scip_producer = "" self.scip_extra_producers: tuple[str, ...] = () + self.scip_excluded_producers: tuple[str, ...] = () self.scip_checkout_dir = "" @@ -483,17 +484,23 @@ async def registry_rows(self) -> list[dict[str, Any]]: @pytest.mark.asyncio -async def test_the_sweep_removes_a_tier_checkout_an_explicit_entry_no_longer_names( +async def test_the_sweep_keeps_every_tier_checkout_an_explicit_entry_does_not_exclude( monkeypatch, tmp_path ) -> None: - """An entry that names its producer runs that tier and its extras only, so the - old checkout of a tier dropped from the extras goes while the named ones stay.""" + """An entry that names its producer also runs the tiers its tree calls for, so the + sweep keeps each tier's checkout but a tier the entry excludes.""" from server.code.store import index as store root = tmp_path / "self" monkeypatch.setattr(settings, "code_repos_root", str(root)) monkeypatch.setattr(settings, "code_self_service_enabled", True) - for name in ("checkout-code-go", "checkout-code-go.python", "checkout-code-go.typescript"): + names = ( + "checkout-code-go", + "checkout-code-go.python", + "checkout-code-go.typescript", + "checkout-code-go.clang", + ) + for name in names: _old(root / name) class _Repo: @@ -504,12 +511,14 @@ async def registry_rows(self) -> list[dict[str, Any]]: cfg.scip_producer = "go" cfg.scip_checkout_dir = str(root / "checkout-code-go") cfg.scip_extra_producers = ("python",) + cfg.scip_excluded_producers = ("typescript",) monkeypatch.setattr(store, "CodeRepo", _Repo) _repos(monkeypatch, [cfg]) removed = {os.path.basename(p) for p in await mirrors.sweep()} assert removed == {"checkout-code-go.typescript"} assert sorted(p.name for p in root.iterdir() if p.is_dir()) == [ "checkout-code-go", + "checkout-code-go.clang", "checkout-code-go.python", ] diff --git a/tests/unit/test_run_python_delta_upload_mode.py b/tests/unit/test_run_python_delta_upload_mode.py index 893390c6c56..460fa124269 100644 --- a/tests/unit/test_run_python_delta_upload_mode.py +++ b/tests/unit/test_run_python_delta_upload_mode.py @@ -148,6 +148,15 @@ def test_a_tree_without_a_python_build_file_gets_no_python_pass(repos) -> None: assert _git(Path(str(repos["checkout"])), "rev-parse", "HEAD") == repos["c1"] +def test_a_python_tier_the_entry_excludes_gets_no_pass(repos) -> None: + out, calls = _run( + repos, wm=str(repos["c1"]), head=str(repos["c2"]), bare=str(repos["bare"]), owner="excluded" + ) + assert "scip_excluded_producers drops the python tier" in out + assert calls == "" + assert _git(Path(str(repos["checkout"])), "rev-parse", "HEAD") == repos["c1"] + + def test_an_unseeded_git_head_indexes_nothing(repos) -> None: out, calls = _run(repos, wm="-", head="-", bare=str(repos["bare"])) assert "git_head not seeded" in out @@ -178,26 +187,39 @@ def _ident_snippet() -> str: @pytest.mark.parametrize( - ("tree", "producer", "extras", "py_worker", "owner"), + ("tree", "producer", "extras", "excluded", "py_worker", "owner"), [ - (["go.mod"], "", (), False, "none"), - (["go.mod", "pyproject.toml"], "", (), False, "manual"), - (["pyproject.toml"], "", (), False, "manual"), - (["CMakeLists.txt"], "", (), False, "none"), - (["go.mod", "pyproject.toml"], "go", (), False, "go"), - (["go.mod", "pyproject.toml"], "go", ("python",), False, "go"), - (["CMakeLists.txt"], "clang", (), False, "manual"), - (["go.mod"], "", (), True, "none"), - (["go.mod", "pyproject.toml"], "", (), True, "worker"), - (["go.mod", "pyproject.toml"], "go", ("python",), True, "worker"), + (["go.mod"], "", (), (), False, "none"), + (["go.mod", "pyproject.toml"], "", (), (), False, "manual"), + (["pyproject.toml"], "", (), (), False, "manual"), + (["CMakeLists.txt"], "", (), (), False, "none"), + (["go.mod", "pyproject.toml"], "go", (), (), False, "go"), + (["go.mod", "pyproject.toml"], "go", ("python",), (), False, "go"), + # a named entry runs a Python tier only when it names one or its tree calls for it + (["CMakeLists.txt"], "clang", (), (), False, "none"), + (["CMakeLists.txt"], "clang", (), (), True, "none"), + (["CMakeLists.txt"], "clang", ("python",), (), False, "manual"), + (["CMakeLists.txt", "pyproject.toml"], "clang", (), (), False, "manual"), + (["go.mod"], "", (), (), True, "none"), + (["go.mod", "pyproject.toml"], "", (), (), True, "worker"), + (["go.mod", "pyproject.toml"], "go", ("python",), (), True, "worker"), + # a tier the tree calls for runs beside the named one, unless the entry drops it + (["go.mod", "pyproject.toml"], "go", (), (), True, "worker"), + (["go.mod", "pyproject.toml"], "go", (), ("python",), True, "go"), + (["go.mod", "pyproject.toml"], "", (), ("python",), True, "excluded"), + (["CMakeLists.txt", "pyproject.toml"], "clang", (), ("python",), True, "excluded"), + (["CMakeLists.txt", "pyproject.toml"], "clang", (), ("python",), False, "excluded"), + # naming the tier beats excluding it + (["CMakeLists.txt"], "clang", ("python",), ("python",), False, "manual"), ], ) def test_the_manual_python_pass_goes_where_the_entry_and_its_tree_say( - monkeypatch, capsys, tree, producer, extras, py_worker, owner + monkeypatch, capsys, tree, producer, extras, excluded, py_worker, owner ) -> None: """The Python worker takes what it owns; a Go or TypeScript entry's worker moves its - checkout; an entry naming no producer gets the manual pass only where its tree has a - Python build file (its Go and TypeScript tiers work in their own trees).""" + checkout; any other entry gets the manual pass only for a Python tier it runs, one it + names or its tree has a build file for (its other tiers work in their own trees), and + no entry gets it for a Python tier it excludes.""" from unittest.mock import AsyncMock from server.code.app.index import repo_registry @@ -214,7 +236,11 @@ def test_the_manual_python_pass_goes_where_the_entry_and_its_tree_say( monkeypatch.setattr(ch, "get_client", lambda: AsyncMock()) monkeypatch.setattr(settings, "code_scip_py_delta_enabled", py_worker) cfg = repo_config( - org="org", namespace="code-x", scip_producer=producer, scip_extra_producers=extras + org="org", + namespace="code-x", + scip_producer=producer, + scip_extra_producers=extras, + scip_excluded_producers=excluded, ) monkeypatch.setattr(repos, "configured_repos", lambda: [cfg]) monkeypatch.setattr(repo_registry, "read_registry", AsyncMock(return_value=True)) diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index aeb093e4ac0..425ab849fc2 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -191,15 +191,27 @@ async def locked(args, org, ns, cfg): @pytest.mark.asyncio @pytest.mark.parametrize( - ("producer", "extra"), - [("go", ()), ("typescript", ()), ("python", ("typescript",))], + ("producer", "extra", "excluded"), + [ + ("go", (), ()), + ("typescript", (), ()), + ("python", ("typescript",), ()), + # no worker runs a clang tier the entry excludes + ("python", (), ("clang",)), + ], ) -async def test_scip_full_skips_an_entry_another_tier_owns(producer, extra, capsys) -> None: +async def test_scip_full_skips_an_entry_that_does_not_run_the_clang_tier( + producer, extra, excluded, capsys +) -> None: from server.cli import code_scip cfg = repo_config( - org="acme", namespace="code-web", scip_producer=producer, scip_extra_producers=extra + org="acme", + namespace="code-web", + scip_producer=producer, + scip_extra_producers=extra, + scip_excluded_producers=excluded, ) locked = AsyncMock(return_value=0) args = argparse.Namespace(org="acme", namespace="code-web") @@ -209,8 +221,8 @@ async def test_scip_full_skips_an_entry_another_tier_owns(producer, extra, capsy patch.object(code_scip, "_scip_full_locked", locked), ): assert await code_scip._scip_full(args) == 0 - assert not locked.await_count, "scip-clang ran on an entry another compiler tier owns" - assert f"its compiler tier is {producer}" in capsys.readouterr().out + assert not locked.await_count, "scip-clang ran on an entry that does not run the clang tier" + assert "code-web: the entry does not run the clang tier" in capsys.readouterr().out @pytest.mark.asyncio