diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 740da22376..574b44fdf3 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -225,10 +225,36 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac the work, since the unembedded rows are the embed phase's queue. `--commit ` pins the tree (and implies `--no-fetch`); `--concurrency N` parallelises files; `--limit N` indexes a sample. +- One process parses and extracts at about one core. `--workers N` runs the index + phase's batches of 200 files and the edge pass in N more processes. Each worker is the + same command, started with the same arguments, so it runs as the command does: as + `background` traffic, under the command's query tag and operation, enrolled and + admitted for model work, with its own connection and `--concurrency`, its own + `cli.code.backfill` root span (stamped `loom.cli.worker`) and its own start and exit + log lines. The cursor moves past a batch once every earlier one is written, the header + batches are all written before the first source batch starts, and after a held batch + nothing more is handed out. A worker resolves names and imports against what it last + read of the index, so during the index phase it misses what the other workers are + writing; each worker reads the index again at the sources and at the edge pass, and + such a run owes the edge pass whatever the flags say (`--paths-file` and + `--no-edges-second-pass` runs included), so the pass binds them against the finished + index. One difference remains: a Python call or base class that resolves through + another file's inherited members reads the `inherits` edges the pass has rewritten so + far, which one process reads in tree order and the workers in the order they finish, + so a few such edges can carry another confidence (the same edge, its target found by + another rule). A later `loom code backfill` that finds the pass owed runs it; the + server's own first index does not. Each worker parses in its own child, so the run holds up to N + times the parse memory (`LOOM_CODE_PARSE_MEMORY_MB`) plus one server process per + worker. Stopping the command (SIGTERM or Ctrl-C, to the command or its whole process + group) or killing it stops every worker inside its batch before the worker retires, + and a worker that fails, its retirement included, fails the command with its batch + named, after the command has written its own end of the run. - The first full backfill of a namespace also re-derives every file's edges after the name table is complete, so cross-file references bind (`--no-edges-second-pass` skips - it). `--dialect-folder-pass` lets SQL files of undecided dialect take the dialect their - directory agrees on. + it). The run records that it owes the pass before its first batch and clears the record + once the pass is done, so a resumed run, or a rerun after an interrupted pass, still + runs it. `--dialect-folder-pass` lets SQL files of undecided dialect take the dialect + their directory agrees on. - `backfill-prs` loads merged-PR history from GitHub, resumable by cursor and bounded by GitHub's rate limit (`LOOM_CODE_PR_BACKFILL_MONTHS`, default 12). `backfill-reviews` adds inline review comments, `backfill-assignees` requested reviewers, and diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 2bd191143d..7c2f9a9482 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -228,7 +228,7 @@ python scripts/codegen/docs_reference.py | --- | --- | --- | | `loom code` | Code intelligence plane operations. | | | `loom code init` | Create the bare clone + seed state. | `--org`, `--namespace` | -| `loom code backfill` | Full-tree indexing (resumable). | `--org`, `--namespace`, `--phase`, `--embed`, `--include-poisoned`, `--allow-fake-embedder`, `--no-fetch`, `--limit`, `--commit`, `--paths-file`, `--concurrency`, `--edges-second-pass`, `--no-edges-second-pass`, `--dialect-folder-pass`, `--embedding-model-suffix`, `--context-callees`, `--callers-from` | +| `loom code backfill` | Full-tree indexing (resumable). | `--org`, `--namespace`, `--phase`, `--embed`, `--include-poisoned`, `--allow-fake-embedder`, `--no-fetch`, `--limit`, `--commit`, `--paths-file`, `--concurrency`, `--workers`, `--edges-second-pass`, `--no-edges-second-pass`, `--dialect-folder-pass`, `--embedding-model-suffix`, `--context-callees`, `--callers-from` | | `loom code reconcile` | Content-based staleness check: paths whose chunks predate their last change at the branch head; --heal re-ingests them (watermark untouched). | `--org`, `--namespace`, `--heal`, `--limit`, `--max-commits`, `--no-fetch`, `--show` | | `loom code compact` | OPTIMIZE ... FINAL a code vector table when its physical copies per key reach --min-ratio, and wait for the merge. | `--table`, `--min-ratio`, `--apply`, `--dry-run`, `--timeout-s` | | `loom code reembed` | Write the namespace's live chunks under a second embedding model's label: in-database, resumable, no checkout. | `--org`, `--namespace`, `--embedding-model`, `--source-model`, `--prefix`, `--batch` | diff --git a/server/cli/__init__.py b/server/cli/__init__.py index c031b61446..4c397e8a5e 100644 --- a/server/cli/__init__.py +++ b/server/cli/__init__.py @@ -14,14 +14,16 @@ The console entrypoint is `loom = server.cli:main`; `python -m server.cli` runs the same `main` through `__main__`. `app` builds the parser tree and -dispatches; each command family lives in its own module and registers its -own subcommands: +hands the parsed command to `dispatch`; each command family lives in its own +module and registers its own subcommands: access mint-token, revoke-token, claim-release ch_setup ch-setup code the `loom code …` tree (code-intelligence ingest and upkeep) code_* its subcommand bodies: run, backfill, prs, scip, maintenance demo demo + dispatch run_parsed: a parsed command in its own context, for `app` and + a process that runs a share of a command deployment deployment doctor doctor, report doctor_client the `doctor --client` checks of this machine as a client @@ -47,7 +49,7 @@ up up Imports run one way: `app` imports the family modules; a family module never -imports `app`. +imports `app`. `dispatch` imports neither, and both may import it. """ from server.cli.app import main diff --git a/server/cli/app.py b/server/cli/app.py index e82bab470f..8892f34233 100644 --- a/server/cli/app.py +++ b/server/cli/app.py @@ -9,9 +9,10 @@ import sys from typing import Any -from server.cli._apply import add_apply_flags, dry_run_hint +from server.cli._apply import add_apply_flags from server.cli.access import _add_mint_token_parser, _add_revoke_token_parser, _cmd_claim_release from server.cli.cell import _add_cell_parser +from server.cli.dispatch import run_parsed from server.cli.doctor import _DOCTOR_HELP, _add_doctor_flags, _cmd_doctor, _cmd_report, _version from server.cli.hygiene import _add_namespace_hygiene_parsers, _add_namespaces_adopt_parser from server.cli.import_brain import _add_brain_import_parser @@ -51,7 +52,6 @@ ) from server.cli.tracker_feed import register_tracker_feed from server.core.env_file import env_file_path -from server.wiring import wire def _cmd_version(_args: argparse.Namespace) -> int: @@ -89,68 +89,6 @@ def _load_dotenv_like_the_container() -> None: ) -def _dispatch(args: argparse.Namespace) -> int: - """Run the parsed command. A one-shot command runs bound to its own - context: every write names its principal (the CLI has no auth context, - so `writer_actor()` would otherwise read '' on every import and backfill), - the reads run as `background` unless the command names a class of its own - (`--traffic-class`), and every ClickHouse query is tagged - `cli.[.]`. Each binding is undone afterwards so an in-process - caller (a test) is left as it was. - - `serve` runs unbound: it is a server, not a command. Its requests and - worker passes bind their own class and tag, and a process-wide - `process:cli:serve` actor would outrank the fallback of every tokenless - request and every worker write (`writer_actor` reads the pipeline actor - first).""" - if getattr(args, "cmd", "") == "serve": - return int(args.func(args)) - - from server.core.ch import query_tag_var - from server.core.pg import AuthorityMismatch - from server.llm import customer - from server.memory.domain.provenance import cli_actor, pipeline_actor - from server.observability.traffic_class import ( - bind_background, - normalize_class, - reset_traffic_class, - ) - - token = None - if not normalize_class(getattr(args, "traffic_class", "")): - token = bind_background(f"cli:{getattr(args, 'cmd', '') or ''}") - path = (getattr(args, d, "") for d in ("cmd", "code_cmd", "subcommand")) - tag_token = query_tag_var.set(".".join(["cli", *filter(None, path)])) - try: - # A command for one org (`--org`, or `LOOM_CODE_ORG` for `loom code`) bills - # its model calls there; one that walks several orgs names each as it goes. - org = getattr(args, "org", "") or "" - if not org and getattr(args, "cmd", "") == "code": - from server.settings import settings - - org = settings.code_org - # Its namespace too, when it names one: whose agent the identity headers name. - namespace = str(getattr(args, "namespace", "") or "") - with ( - pipeline_actor(cli_actor(getattr(args, "cmd", ""))), - customer.cli_command(), - customer.for_org(str(org), namespace=namespace), - ): - try: - rc = int(args.func(args)) - except AuthorityMismatch as e: - print(f" ✗ {e}", file=sys.stderr) - return 2 - if hint := dry_run_hint(args, rc): - # stderr: a command's --json output stays the only thing on stdout - print(hint, file=sys.stderr) - return rc - finally: - query_tag_var.reset(tag_token) - if token is not None: - reset_traffic_class(token) - - # Subcommands registered by their own function (kept out of `main` for the # function-length gate). _SPLIT_PARSERS: tuple[Any, ...] = ( @@ -386,6 +324,4 @@ def main(argv: list[str] | None = None) -> int: sub = parser.add_subparsers(dest="cmd", required=True) for _add_parsers in _SUBCOMMAND_BUILDERS: _add_parsers(sub) - args = parser.parse_args(argv) - wire() - return _dispatch(args) + return run_parsed(parser.parse_args(argv)) diff --git a/server/cli/code.py b/server/cli/code.py index 7a1c59f742..8a6527f085 100644 --- a/server/cli/code.py +++ b/server/cli/code.py @@ -41,6 +41,7 @@ ) from server.cli.code_run import _identity, _run from server.cli.code_scip import _entries, _entry_locked, _scip_delta, _scip_full, _scip_retry +from server.cli.ops import _positive_int from server.code.domain.index.tier_health import COMPILER_TIERS @@ -197,6 +198,13 @@ def _add_backfill_parser(csub: argparse._SubParsersAction[argparse.ArgumentParse "the branch tip; leaves the git_head watermark and cursor untouched", ) p_bf.add_argument("--concurrency", type=int, default=4) + p_bf.add_argument( + "--workers", + type=_positive_int, + default=1, + help="--phase index: processes that index the cursor batches and run the edge " + "pass, each with its own connection and --concurrency (1: this process)", + ) _add_backfill_pass_flags(p_bf) p_bf.set_defaults(func=_cmd_backfill) diff --git a/server/cli/code_backfill.py b/server/cli/code_backfill.py index d7bc9fd40b..7943c596d2 100644 --- a/server/cli/code_backfill.py +++ b/server/cli/code_backfill.py @@ -5,14 +5,18 @@ import argparse import asyncio +import contextlib +import itertools import logging import os import pathlib import sys import time -from collections.abc import Awaitable, Callable +from collections.abc import AsyncGenerator, Awaitable, Callable +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Literal +from server.cli import code_backfill_workers from server.cli._ch import connect_code_plane from server.cli.code_maintenance import _compact_after_bulk from server.cli.code_run import _identity, _note, _repo_cfg @@ -26,7 +30,7 @@ def _count_record(counters: dict[str, int], recorded: FileIngestStats | Literal[False]) -> None: - """Count an oversize file's record as `_one` counts an ingested file.""" + """Count an oversize file's record as `_Run.one` counts an ingested file.""" key = "errors" if recorded is False else "excluded" if recorded.excluded else "files" counters[key] = counters.get(key, 0) + 1 @@ -51,14 +55,290 @@ async def _source(path: str) -> tuple[str, bytes | None]: return _source +def _cursor_batches(paths: list[str], start: int = 0) -> list[tuple[int, list[str]]]: + """The paths from `start` in cursor batches of 200, each with its first index. The + headers `headers_first` put first end their own batch, so no batch holds both a + header and a source: every header can be written before any source batch starts.""" + from server.code.app.index.ingest_headers import HEADER_EXTS + + batch = 200 + split = next((i for i, p in enumerate(paths) if not p.endswith(HEADER_EXTS)), len(paths)) + cuts = {*range(0, split, batch), *range(split, len(paths), batch), start, len(paths)} + return [(a, paths[a:b]) for a, b in itertools.pairwise(sorted(c for c in cuts if c >= start))] + + +def index_counters() -> dict[str, int]: + return {"files": 0, "chunks": 0, "symbols": 0, "edges": 0, "errors": 0} + + +def edge_counters() -> dict[str, int]: + return {"files": 0, "edges": 0, "errors": 0} + + +def add_counters(total: dict[str, int], part: dict[str, int]) -> None: + for key, n in part.items(): + total[key] = total.get(key, 0) + n + + +@dataclass +class _Run: + """What the index phase's cursor batches and its edge pass run with: one in the CLI + process, and one in each `--workers` process (`code_backfill_workers`).""" + + repo: Any + cfg: Any + args: argparse.Namespace + org: str + ns: str + head: str + model_name: str + embedder: Any + denylist: Any + sem: asyncio.Semaphore + counters: dict[str, int] = field(default_factory=index_counters) + edges: dict[str, int] = field(default_factory=edge_counters) + + @classmethod + async def open( + cls, + repo: Any, + cfg: Any, + args: argparse.Namespace, + head: str, + *, + org: str, + ns: str, + embedder: Any, + ) -> _Run: + from server.code.app.index import gitrepo + from server.code.app.index.denylist import load_denylist + from server.embedding.embedder import get_embedder + + return cls( + repo=repo, + cfg=cfg, + args=args, + org=org, + ns=ns, + head=head, + model_name=get_embedder().model_name + + str(getattr(args, "embedding_model_suffix", "") or ""), + embedder=embedder, + denylist=await load_denylist(cfg, head, gitrepo.show_file), + sem=asyncio.Semaphore(max(1, args.concurrency)), + ) + + async def source(self, path: str) -> tuple[str, bytes | None]: + from server.code.app.index import gitrepo + from server.code.app.index.ingest import read_capped + + async with self.sem: + source, recorded = await read_capped( + gitrepo.show_file, + self.repo, + self.org, + self.ns, + git_dir=self.cfg.git_dir, + path=path, + commit_sha=self.head, + embedding_model=self.model_name, + denylist=self.denylist, + ) + if recorded is not None: + _count_record(self.counters, recorded) + return path, source + + async def one(self, reads: Any, path: str, source: bytes) -> None: + from server.code.app.index.ingest import ingest_file + from server.settings import settings + + counters, args = self.counters, self.args + async with self.sem: + try: + stats = await ingest_file( + reads, + self.org, + self.ns, + path=path, + source=source, + commit_sha=self.head, + embedding_model=self.model_name, + embedder=self.embedder, + max_chunk_chars=settings.code_chunk_max_chars, + embed_reuse_from=self.cfg.embed_reuse_from, + denylist=self.denylist, + context_callees=str(getattr(args, "context_callees", "") or "off"), + callers_namespace=str(getattr(args, "callers_from", "") or ""), + parsed=reads.parsed.get(path), + ) + except customer.HOLDS: + raise # the org's model calls are held: the run stops, its cursor kept + except Exception as e: # noqa: BLE001 — per-file, keep going + counters["errors"] += 1 + print(f" ! {path}: {type(e).__name__}: {e}", file=sys.stderr) + return + if stats.excluded: + counters["excluded"] = counters.get("excluded", 0) + 1 + return + counters["files"] += 1 + counters["chunks"] += stats.chunks_new + counters["symbols"] += stats.symbols_new + counters["moved"] = counters.get("moved", 0) + stats.chunks_moved + stats.symbols_moved + counters["edges"] += stats.edges_new + counters["embed_reused"] = counters.get("embed_reused", 0) + stats.embed_reused + + async def batch(self, paths: list[str]) -> str: + """One cursor batch of the index phase: "" once written, else why it was held.""" + return await _held_batch( + self.repo, + self.org, + self.ns, + paths, + source=self.source, + one=self.one, + denylist=self.denylist, + git_dir=self.cfg.git_dir, + head=self.head, + ) + + async def edge_one(self, reads: Any, path: str, src: bytes) -> None: + from server.code.app.index.ingest import ingest_file + + async with self.sem: + try: + stats = await ingest_file( + reads, + self.org, + self.ns, + path=path, + source=src, + commit_sha=self.head, + embedding_model=self.model_name, + edges_only=True, + denylist=self.denylist, + parsed=reads.parsed.get(path), + ) + except Exception as e: # noqa: BLE001 — per-file, keep going + self.edges["errors"] += 1 + print(f" ! second pass {path}: {type(e).__name__}: {e}", file=sys.stderr) + return + self.edges["files"] += 1 + self.edges["edges"] += stats.edges_new + + async def edge_batch(self, paths: list[str]) -> None: + """One batch of the edge pass.""" + await _backfill_batch_rounds( + self.repo, + self.org, + self.ns, + paths, + source=_edge_source(self.cfg.git_dir, self.head, self.sem), + one=self.edge_one, + denylist=self.denylist, + git_dir=self.cfg.git_dir, + head=self.head, + ) + + +async def worker_run(args: argparse.Namespace, head: str) -> _Run: + """A `--workers` process's run: its own connection, the entry's config and denylist + at the parent's `head`. The worker is the command itself (`code_backfill_workers`), + so this runs once the registry is read and the active configuration loaded.""" + from server.code.store.index import CodeRepo + from server.core.ch import get_client + from server.embedding.embedder import get_embedder + + cfg = _repo_cfg(args) + await connect_code_plane(get_client(), args) + org, ns = _identity(args) + embedder = get_embedder() if args.embed else None + return await _Run.open(CodeRepo(), cfg, args, head, org=org, ns=ns, embedder=embedder) + + +def _workers_for( + args: argparse.Namespace, head: str, batches: int, edge_batches: int +) -> contextlib.AbstractAsyncContextManager[code_backfill_workers.Workers | None]: + """The run's `--workers` processes, for both passes and no more than either has + batches; None runs them in this one.""" + n = min(args.workers, max(batches, edge_batches)) + if n > 1: + return code_backfill_workers.opened(n, args, head) + return contextlib.nullcontext(None) + + +async def _index_batches( + run: _Run, batches: list[tuple[int, list[str]]], workers: code_backfill_workers.Workers | None +) -> AsyncGenerator[tuple[int, list[str], dict[str, int], str], None]: + """The index phase's cursor batches in order, each with its own counters and why the + org's switch held it ("" once written): in this process, or across `workers`.""" + if workers is not None: + async for done in workers.index_batches(batches): + yield done + return + for b, chunk in batches: + run.counters = index_counters() + held = await run.batch(chunk) + yield b, chunk, run.counters, held + if held: + return + + +async def _index_phase( + run: _Run, + paths: list[str], + batches: list[tuple[int, list[str]]], + workers: code_backfill_workers.Workers | None, + *, + counters: dict[str, int], + cursor_key: str, + started: float, +) -> str: + """Run the batches, moving the cursor past each one once every earlier one is + written; why the org's switch held one, "" once all are written. A batch written + beside the held one is counted and the cursor stays.""" + held = "" + paths_file = bool(getattr(run.args, "paths_file", "")) + async with contextlib.aclosing(_index_batches(run, batches, workers)) as done: + async for b_start, chunk_paths, part, why in done: + add_counters(counters, part) + if held: + continue + if why: + held = why + print(f"backfill stopped at {b_start}/{len(paths)}: {held}", file=sys.stderr) + continue + if not paths_file: + await run.repo.set_state( + run.org, run.ns, cursor_key, str(b_start + len(chunk_paths)) + ) + rate = counters["files"] / max(time.monotonic() - started, 1e-9) + print( + f" [{b_start + len(chunk_paths)}/{len(paths)}] files={counters['files']} " + f"chunks={counters['chunks']} symbols={counters['symbols']} " + f"edges={counters['edges']} errors={counters['errors']} " + f"({rate:.1f} files/s)" + ) + return held + + async def _backfill(args: argparse.Namespace) -> int: - from server.code.app.index import gitrepo + # The run's `--workers` processes close on this stack once the run returns, its + # records written, as one process retires after its command returns. + async with contextlib.AsyncExitStack() as stack: + return await _backfill_run(args, stack) + + +async def _backfill_run(args: argparse.Namespace, stack: contextlib.AsyncExitStack) -> int: from server.code.store.index import CodeRepo from server.core.ch import get_client - from server.settings import settings if args.phase == "embed": + if args.workers > 1: + print("--workers applies to --phase index", file=sys.stderr) + return 2 return await _backfill_embed(CodeRepo(), *_identity(args), args) + if (worker := getattr(args, "backfill_worker", None)) is not None: + return await code_backfill_workers.serve(await worker_run(args, worker.head), worker) # Before declaring the org: an unconfigured entry records nothing. cfg = _repo_cfg(args) await connect_code_plane(get_client(), args) @@ -99,125 +379,51 @@ async def _backfill(args: argparse.Namespace) -> int: model = get_embedder().model_name print(f"chunks stored as dim=0 stubs for model {model}; run --phase embed after") - from server.code.app.index.denylist import load_denylist - from server.code.app.index.ingest import ingest_file, read_capped - suffix = str(getattr(args, "embedding_model_suffix", "") or "") - model_name = get_embedder().model_name + suffix + run = await _Run.open(repo, cfg, args, head, org=org, ns=ns, embedder=embedder) + model_name = run.model_name if suffix: print(f"twin label: rows written under embedding_model={model_name!r}") - denylist = await load_denylist(cfg, head, gitrepo.show_file) cursor_key = f"backfill_cursor:index{suffix}" + owed_key = f"backfill_edges_owed:index{suffix}" mode = "repair" if paths_file else "twin" if suffix else "backfill" done_upto = "" if paths_file else await repo.get_state(org, ns, cursor_key) start_idx = int(done_upto) if done_upto.isdigit() else 0 + batches = _cursor_batches(paths, start_idx) + owed, recorded = await _record_edge_pass( + repo, + org, + ns, + args, + owed_key, + str(done_upto or ""), + side_by_side=args.workers > 1 and code_backfill_workers.side_by_side(batches), + ) started = time.monotonic() - sem = asyncio.Semaphore(max(1, args.concurrency)) - counters = {"files": 0, "chunks": 0, "symbols": 0, "edges": 0, "errors": 0} - - async def _source(path: str) -> tuple[str, bytes | None]: - async with sem: - source, recorded = await read_capped( - gitrepo.show_file, - repo, - org, - ns, - git_dir=cfg.git_dir, - path=path, - commit_sha=head, - embedding_model=model_name, - denylist=denylist, - ) - if recorded is not None: - _count_record(counters, recorded) - return path, source - - async def _one(reads: Any, path: str, source: bytes) -> None: - async with sem: - try: - stats = await ingest_file( - reads, - org, - ns, - path=path, - source=source, - commit_sha=head, - embedding_model=model_name, - embedder=embedder, - max_chunk_chars=settings.code_chunk_max_chars, - embed_reuse_from=cfg.embed_reuse_from, - denylist=denylist, - context_callees=str(getattr(args, "context_callees", "") or "off"), - callers_namespace=str(getattr(args, "callers_from", "") or ""), - parsed=reads.parsed.get(path), - ) - except customer.HOLDS: - raise # the org's model calls are held: the run stops, its cursor kept - except Exception as e: # noqa: BLE001 — per-file, keep going - counters["errors"] += 1 - print(f" ! {path}: {type(e).__name__}: {e}", file=sys.stderr) - return - if stats.excluded: - counters["excluded"] = counters.get("excluded", 0) + 1 - return - counters["files"] += 1 - counters["chunks"] += stats.chunks_new - counters["symbols"] += stats.symbols_new - counters["moved"] = counters.get("moved", 0) + stats.chunks_moved + stats.symbols_moved - counters["edges"] += stats.edges_new - counters["embed_reused"] = counters.get("embed_reused", 0) + stats.embed_reused - - batch = 200 - for b_start in range(start_idx, len(paths), batch): - chunk_paths = paths[b_start : b_start + batch] - held = await _held_batch( - repo, - org, - ns, - chunk_paths, - source=_source, - one=_one, - denylist=denylist, - git_dir=cfg.git_dir, - head=head, - ) - if held: - print(f"backfill stopped at {b_start}/{len(paths)}: {held}", file=sys.stderr) - # The batches written before the hold are compacted and recorded. - await _close_index(repo, counters, org, ns, model_name, started, head, mode) - return 1 - if not paths_file: - await repo.set_state(org, ns, cursor_key, str(b_start + len(chunk_paths))) - rate = counters["files"] / max(time.monotonic() - started, 1e-9) - print( - f" [{b_start + len(chunk_paths)}/{len(paths)}] files={counters['files']} " - f"chunks={counters['chunks']} symbols={counters['symbols']} " - f"edges={counters['edges']} errors={counters['errors']} " - f"({rate:.1f} files/s)" - ) - - if second_pass_wanted( - explicit=bool(getattr(args, "edges_second_pass", False)), - declined=bool(getattr(args, "no_edges_second_pass", False)), - paths_file=bool(paths_file), - done_upto=str(done_upto or ""), - ): - if not getattr(args, "edges_second_pass", False): + counters = index_counters() + second: dict[str, int] | None = None + edge_batches = len(_cursor_batches(paths)) if owed else 0 + workers = await stack.enter_async_context(_workers_for(args, head, len(batches), edge_batches)) + held = await _index_phase( + run, paths, batches, workers, counters=counters, cursor_key=cursor_key, started=started + ) + if owed and not held: + if recorded: + print(f"edge second pass owed by an earlier run of this backfill ({recorded})") + elif owed == "first-backfill": print("first full backfill of this namespace: edge second pass implied") - second = await _second_edge_pass( - repo, - org, - ns, - paths, - source=_edge_source(cfg.git_dir, head, sem), - denylist=denylist, - head=head, - model_name=model_name, - sem=sem, - git_dir=cfg.git_dir, - ) + elif owed == "workers": + print("--workers: batches were written side by side; the edge pass binds them") + second = await _second_edge_pass(run, paths, workers) + if held: + # The batches written before the hold are compacted, republished and recorded. + await _close_index(repo, counters, org, ns, model_name, started, head, mode) + return 1 + if second is not None: counters["edges_second_pass"] = second["edges"] counters["errors"] += second["errors"] + if not paths_file and not second["errors"]: + await repo.set_state(org, ns, owed_key, "") if getattr(args, "dialect_folder_pass", False): folder = await _dialect_folder_pass(repo, org, ns, head) counters["dialect_inherited"] = folder["inherited"] @@ -307,81 +513,96 @@ async def _backfill_paths( return headers_first(paths) -def second_pass_wanted(*, explicit: bool, declined: bool, paths_file: bool, done_upto: str) -> bool: - """A namespace's FIRST full backfill indexes files in - tree order, so a call to a function whose file comes later binds - nothing (a call in fastify.js to `buildRouting(…)` reads `unresolved, - 0 candidates` while lib/route.js is not yet indexed). The edges-only - second pass is what repairs that, so a first full - backfill implies it; `--edges-second-pass` asks for it on any run, - `--no-edges-second-pass` declines the implied one. A resumed run - (cursor set) or a `--paths-file` repair implies nothing.""" +async def _record_edge_pass( + repo: Any, + org: str, + ns: str, + args: argparse.Namespace, + owed_key: str, + done_upto: str, + *, + side_by_side: bool, +) -> tuple[str, str]: + """(why this run owes the edge pass, why an earlier run recorded it owed). A cursor + run records its reason before its first batch, so a run interrupted from there on + leaves the pass owed; a `--paths-file` repair records nothing.""" + paths_file = bool(getattr(args, "paths_file", "")) + recorded = "" if paths_file else await repo.get_state(org, ns, owed_key) + owed = edge_pass_owed( + explicit=bool(getattr(args, "edges_second_pass", False)), + declined=bool(getattr(args, "no_edges_second_pass", False)), + paths_file=paths_file, + done_upto=done_upto, + recorded=recorded, + side_by_side=side_by_side, + ) + if not paths_file and owed != recorded: + await repo.set_state(org, ns, owed_key, owed) + return owed, recorded + + +def edge_pass_owed( + *, + explicit: bool, + declined: bool, + paths_file: bool, + done_upto: str, + recorded: str, + side_by_side: bool, +) -> str: + """Why this run owes the edges-only second pass, '' when it does not. A + namespace's FIRST full backfill indexes files in tree order, so a call to a + function whose file comes later binds nothing (a call in fastify.js to + `buildRouting(…)` reads `unresolved, 0 candidates` while lib/route.js is not + yet indexed); the second pass repairs that, so a first full backfill implies + it. `--edges-second-pass` asks for it on any run, `--no-edges-second-pass` + declines it. A cursor run records the reason before its first batch and + clears it once the pass is done (`recorded`), so a resumed run, or a rerun + after an interrupted pass, still runs it. A resumed run with nothing + recorded, and a `--paths-file` repair, imply nothing. + + A run whose `--workers` wrote batches side by side (`side_by_side`) owes it + whatever the flags say: a file there resolved against a name table the other + workers were still filling, where one process would have bound it, so a + `--paths-file` repair runs it too and `--no-edges-second-pass` does not + decline it.""" + if side_by_side or recorded == "workers": + return "workers" if explicit: - return True + return "requested" if declined or paths_file: - return False - return not done_upto + return "" + if recorded: + return recorded + return "" if done_upto else "first-backfill" async def _second_edge_pass( - repo: Any, - org: str, - ns: str, - paths: list[str], - *, - source: Any, - denylist: Any, - head: str, - model_name: str, - sem: asyncio.Semaphore, - git_dir: str, + run: _Run, paths: list[str], workers: code_backfill_workers.Workers | None ) -> dict[str, int]: """The edges-only pass over the same paths once the whole tree is indexed. The first pass resolved each file against the name table as it stood — a fresh namespace's dbt model indexed before the model it `ref()`s bound nothing (bench callers F1 0.286 → 1.0 on the second pass). Same rounds as the index phase; chunks, symbols and facets are - left alone, edges are key-diffed against the live rows.""" - from server.code.app.index.ingest import ingest_file - + left alone, edges are key-diffed against the live rows. It starts from the + index as it now stands (`forget_index_reads`), not what the index phase cached + of it. Across `workers` its batches run in any order: names resolve against the + finished symbols, but a Python class's inherited members are read from the edges + the pass has rewritten so far, which one process reads in tree order.""" + from server.code.app.index.ingest_resolve import forget_index_reads + + forget_index_reads() started = time.monotonic() - counters = {"files": 0, "edges": 0, "errors": 0} - - async def _one(reads: Any, path: str, src: bytes) -> None: - async with sem: - try: - stats = await ingest_file( - reads, - org, - ns, - path=path, - source=src, - commit_sha=head, - embedding_model=model_name, - edges_only=True, - denylist=denylist, - parsed=reads.parsed.get(path), - ) - except Exception as e: # noqa: BLE001 — per-file, keep going - counters["errors"] += 1 - print(f" ! second pass {path}: {type(e).__name__}: {e}", file=sys.stderr) - return - counters["files"] += 1 - counters["edges"] += stats.edges_new - + counters = run.edges + batches = _cursor_batches(paths) print(f"second edge pass: {len(paths)} files against the finished name table") - for b_start in range(0, len(paths), 200): - await _backfill_batch_rounds( - repo, - org, - ns, - paths[b_start : b_start + 200], - source=source, - one=_one, - denylist=denylist, - git_dir=git_dir, - head=head, - ) + if workers is None: + for _b, chunk in batches: + await run.edge_batch(chunk) + else: + for part in await workers.edge_batches(batches): + add_counters(counters, part) print( f"second edge pass complete: files={counters['files']} edges=+{counters['edges']} " f"errors={counters['errors']} in {time.monotonic() - started:.0f}s" diff --git a/server/cli/code_backfill_workers.py b/server/cli/code_backfill_workers.py new file mode 100644 index 0000000000..73aa2b2938 --- /dev/null +++ b/server/cli/code_backfill_workers.py @@ -0,0 +1,324 @@ +"""`loom code backfill --workers N`: the index phase's cursor batches and its edge pass +in N processes. + +One process parses and extracts at about one core: every tree-sitter parse holds the +interpreter lock and runs one at a time per process (`bounded_parse`), and the chunk, +symbol and edge extraction after it walks the tree in Python. A parse tree does not +cross a process boundary, and a file's extraction reads the index between its steps +(name candidates, then the targets they resolve), so the unit a worker takes is a whole +cursor batch: its own connection, reads, parse, extraction and writes, as one process +runs them. + +A worker is the command itself. It is started with the command's own parsed arguments +and enters through `dispatch.run_parsed`, as `loom` does, so it runs under every binding +the command runs under (traffic class, query tag, operation identity, the org it bills, +logging, telemetry, signal handling, the model-work admission and the registry read); +`_backfill` then serves the batches it is sent instead of walking the tree. One pipe +per worker carries its batches and their counters. The parent hands a worker its next +batch when the worker reports its last, so nothing runs that it did not hand out. + +A worker leaves when its pipe closes: between batches it returns and retires as the +command does; during a batch, the parent stopped or died, so the closing pipe cancels +the command's task as a SIGTERM or a Ctrl-C would, and the batch unwinds before the +worker retires and exits non-zero. The parent reads every worker's exit code. + +Each worker caches what it reads of the index (header texts, the live path set, the +resolver's layouts and listings), and another worker's writes do not reach those caches. +A worker forgets them whenever it moves to the next group of batches: the sources once +the headers are written, then the edge pass, which therefore reads the finished index. +""" + +from __future__ import annotations + +import argparse +import asyncio +import contextlib +import multiprocessing +import signal +import sys +from collections import deque +from collections.abc import AsyncGenerator, AsyncIterator, Coroutine +from dataclasses import dataclass +from multiprocessing.connection import Connection +from typing import Any + +from server.cli.dispatch import run_parsed +from server.code.app.index.ingest_headers import HEADER_EXTS + +_SPAWN = multiprocessing.get_context("spawn") # a fresh interpreter: no copy of the parent's loop + +# (first index, paths, counters, why the org's switch held it: "" once written) +Done = tuple[int, list[str], dict[str, int], str] + + +@dataclass(frozen=True) +class Assignment: + """What a worker process serves: the parent's head, its number, its end of the pipe.""" + + head: str + number: int + conn: Connection + + +@dataclass +class _Worker: + number: int + process: Any # multiprocessing.context.SpawnProcess + conn: Connection + + def send(self, kind: str, group: str, paths: list[str]) -> None: + # A worker that exited between batches has closed its end: `receive` then + # reads the end of the pipe, and its exit code says why. + with contextlib.suppress(OSError): + self.conn.send((kind, group, paths)) + + async def receive(self) -> Any: + """The worker's next message, None once it has exited.""" + await _readable(self.conn.fileno()) + try: + return self.conn.recv() + except (EOFError, OSError): + return None + + async def exit_code(self) -> int: + await _readable(self.process.sentinel) + self.process.join() + return int(self.process.exitcode) + + +class Workers: + """The worker processes of one run, for both of its passes.""" + + def __init__(self, workers: list[_Worker]) -> None: + self._workers = workers + + async def index_batches( + self, batches: list[tuple[int, list[str]]] + ) -> AsyncGenerator[Done, None]: + """Each batch with its counters and why it was held, in batch order. The header + batches are all written before the first source batch is handed out. Once a batch + is held nothing more is handed out; the batches still running finish and are + yielded after the ones before them.""" + held = False + for group, part in _groups(batches): + if held: + return + order = deque(b for b, _paths in part) + ready: dict[int, Done] = {} + async with contextlib.aclosing(self._run("index", group, part)) as finished: + async for done in finished: + ready[done[0]] = done + held = held or bool(done[3]) + while order and order[0] in ready: + yield ready.pop(order.popleft()) + for b in sorted(ready): # after a hold: those that ran beside it + yield ready[b] + + async def edge_batches(self, batches: list[tuple[int, list[str]]]) -> list[dict[str, int]]: + """The edge pass's batches, in any order; each one's counters.""" + async with contextlib.aclosing(self._run("edges", "edges", batches)) as finished: + return [counters async for _b, _p, counters, _h in finished] + + async def _run( + self, kind: str, group: str, batches: list[tuple[int, list[str]]] + ) -> AsyncGenerator[Done, None]: + """`batches` across the workers as each one finishes its last, yielded as they + finish; none handed out once one comes back held.""" + todo = deque(batches) + idle = list(self._workers) + running: dict[asyncio.Future[Any], tuple[_Worker, int, list[str]]] = {} + held = False + try: + while running or (todo and not held): + while todo and idle and not held: + worker, (b, paths) = idle.pop(), todo.popleft() + worker.send(kind, group, paths) + running[asyncio.ensure_future(worker.receive())] = (worker, b, paths) + finished, _ = await asyncio.wait(running, return_when=asyncio.FIRST_COMPLETED) + for fut in finished: + worker, b, paths = running.pop(fut) + reply = fut.result() + if reply is None: + code = await worker.exit_code() + raise SystemExit( + f"backfill worker {worker.number} {_ended(code)} during the {kind} " + f"batch at {b} ({len(paths)} files)" + _above(code) + ) + _tag, counters, why = reply + held = held or bool(why) + idle.append(worker) + yield b, paths, counters, why + finally: + for fut in running: + fut.cancel() + + +def _groups(batches: list[tuple[int, list[str]]]) -> list[tuple[str, list[tuple[int, list[str]]]]]: + """The header batches, then the source batches (`_cursor_batches` never mixes them).""" + headers = [(b, p) for b, p in batches if p[0].endswith(HEADER_EXTS)] + sources = [(b, p) for b, p in batches if not p[0].endswith(HEADER_EXTS)] + return [(g, part) for g, part in (("headers", headers), ("sources", sources)) if part] + + +def side_by_side(batches: list[tuple[int, list[str]]]) -> bool: + """Whether N workers would write any of `batches` beside another of its group.""" + return any(len(part) > 1 for _g, part in _groups(batches)) + + +@contextlib.asynccontextmanager +async def opened(n: int, args: argparse.Namespace, head: str) -> AsyncIterator[Workers]: + """N workers running `args` at `head`, each ready (its run opened) when this yields. + On a normal exit their pipes close and each one retires; a worker that exits + non-zero then (its drain or retirement failed) fails the run, so the caller keeps + its own durable end inside the block. On an exception or a cancellation the pipes + close too, and each worker leaves its batch at once.""" + workers = [_start(i, args, head) for i in range(1, n + 1)] + try: + for worker in workers: + if await worker.receive() is None: + code = await worker.exit_code() + raise SystemExit( + f"backfill worker {worker.number} {_ended(code)} before its run opened" + + _above(code) + ) + yield Workers(workers) + except BaseException: # stop every worker, then raise the run's own failure + await _close(workers) + raise + codes = await _close(workers) + failed = [(w.number, code) for w, code in zip(workers, codes, strict=True) if code] + if failed: + raise SystemExit( + "backfill workers did not retire cleanly (" + + ", ".join(f"worker {n} {_ended(code)}" for n, code in failed) + + ")" + + ("; their errors are above" if any(code > 0 for _n, code in failed) else "") + ) + + +def _ended(code: int) -> str: + """How a worker process ended: its exit code, or the signal that killed it.""" + if code >= 0: + return f"exited {code}" + name = signal.Signals(-code).name + return f"was killed by {name}" + (" (out of memory?)" if -code == signal.SIGKILL else "") + + +def _above(code: int) -> str: + """Where the operator finds why: a worker that exited printed it; a killed one did not.""" + return "; its error is above" if code > 0 else "" + + +def _start(number: int, args: argparse.Namespace, head: str) -> _Worker: + mine, theirs = _SPAWN.Pipe() + command = argparse.Namespace( + **vars(args), backfill_worker=Assignment(head=head, number=number, conn=theirs) + ) + process = _SPAWN.Process( + target=_worker_main, args=(command,), name=f"loom-backfill-worker-{number}" + ) + process.start() + theirs.close() # the worker's end lives in the worker only: either side's exit is an EOF + return _Worker(number=number, process=process, conn=mine) + + +async def _close(workers: list[_Worker]) -> list[int]: + for worker in workers: + worker.conn.close() + return [await worker.exit_code() for worker in workers] + + +def _worker_main(command: argparse.Namespace) -> None: + """A worker process: the command, entered as `loom` enters it.""" + try: + code = run_parsed(command) + except KeyboardInterrupt: # the parent reports the interruption; one traceback is enough + code = 130 + sys.exit(code) + + +async def serve(run: Any, assignment: Assignment) -> int: + """A worker's share of the command: the batches the parent sends, each awaited in + this command's own task, until the parent closes the pipe. A pipe that closes during + a batch cancels that task, as a SIGTERM or a Ctrl-C does, so every stop unwinds + through the batch before the command retires.""" + from server.cli.code_backfill import edge_counters, index_counters + from server.cli.code_run import _note + from server.code.app.index.ingest_resolve import forget_index_reads + + async def _batch(kind: str, paths: list[str]) -> tuple[dict[str, int], str]: + if kind == "index": + run.counters = index_counters() + held = await run.batch(paths) + return run.counters, held + run.edges = edge_counters() + await run.edge_batch(paths) + return run.edges, "" + + conn = assignment.conn + _note(worker=assignment.number) + try: + conn.send(("ready",)) + except OSError: + return 0 # the run stopped while this worker opened (another worker was refused) + group = "" + while True: + await _readable(conn.fileno()) + try: + kind, batch_group, paths = conn.recv() + except (EOFError, OSError): + return 0 # the run is done + if batch_group != group: + # What this process read of the index may predate another worker's writes. + forget_index_reads() + group = batch_group + counters, held = await _until_closed(conn, _batch(kind, paths), assignment.number) + try: + conn.send(("done", counters, held)) + except OSError: + return 1 # the run stopped as this batch finished + + +async def _until_closed[T](conn: Connection, work: Coroutine[Any, Any, T], number: int) -> T: + """`work`, awaited in this task, which a closing pipe cancels; that cancellation + becomes the worker's exit, any other (a signal) stays a cancellation.""" + task = asyncio.current_task() + assert task is not None + loop = asyncio.get_running_loop() + closed = False + + def _on_readable() -> None: # the parent sends nothing during a batch: it went away + nonlocal closed + # Once: a closed pipe stays readable, and the batch's unwind must not spin on it. + loop.remove_reader(conn.fileno()) + if task.cancelling() == 0: # a signal already unwinding the batch keeps its exit + closed = True + task.cancel() + + loop.add_reader(conn.fileno(), _on_readable) + try: + return await work + except asyncio.CancelledError: + if closed and task.uncancel() == 0: + raise SystemExit( + f"backfill worker {number}: the run stopped during its batch; the batch was left" + ) from None + raise + finally: + loop.remove_reader(conn.fileno()) + + +async def _readable(fd: int) -> None: + """Until `fd` can be read (data, or its other end closed).""" + loop = asyncio.get_running_loop() + ready: asyncio.Future[None] = loop.create_future() + + def _ready() -> None: + if not ready.done(): + ready.set_result(None) + + loop.add_reader(fd, _ready) + try: + await ready + finally: + loop.remove_reader(fd) diff --git a/server/cli/dispatch.py b/server/cli/dispatch.py new file mode 100644 index 0000000000..b94352f3cc --- /dev/null +++ b/server/cli/dispatch.py @@ -0,0 +1,81 @@ +"""How a parsed `loom` command runs: the process's seams wired, then the command in +its own context. `app.main` parses and enters here; so does a process that runs a share +of a command's work (a `loom code backfill --workers` process), with the command's own +parsed arguments, so it runs under every binding the command does. `app` and the +family modules both import this module; it imports neither.""" + +from __future__ import annotations + +import argparse +import sys + +from server.cli._apply import dry_run_hint +from server.wiring import wire + + +def run_parsed(args: argparse.Namespace) -> int: + """Run a parsed command as `loom` runs it.""" + wire() + return _dispatch(args) + + +def _dispatch(args: argparse.Namespace) -> int: + """Run the parsed command. A one-shot command runs bound to its own + context: every write names its principal (the CLI has no auth context, + so `writer_actor()` would otherwise read '' on every import and backfill), + the reads run as `background` unless the command names a class of its own + (`--traffic-class`), and every ClickHouse query is tagged + `cli.[.]`. Each binding is undone afterwards so an in-process + caller (a test) is left as it was. + + `serve` runs unbound: it is a server, not a command. Its requests and + worker passes bind their own class and tag, and a process-wide + `process:cli:serve` actor would outrank the fallback of every tokenless + request and every worker write (`writer_actor` reads the pipeline actor + first).""" + if getattr(args, "cmd", "") == "serve": + return int(args.func(args)) + + from server.core.ch import query_tag_var + from server.core.pg import AuthorityMismatch + from server.llm import customer + from server.memory.domain.provenance import cli_actor, pipeline_actor + from server.observability.traffic_class import ( + bind_background, + normalize_class, + reset_traffic_class, + ) + + token = None + if not normalize_class(getattr(args, "traffic_class", "")): + token = bind_background(f"cli:{getattr(args, 'cmd', '') or ''}") + path = (getattr(args, d, "") for d in ("cmd", "code_cmd", "subcommand")) + tag_token = query_tag_var.set(".".join(["cli", *filter(None, path)])) + try: + # A command for one org (`--org`, or `LOOM_CODE_ORG` for `loom code`) bills + # its model calls there; one that walks several orgs names each as it goes. + org = getattr(args, "org", "") or "" + if not org and getattr(args, "cmd", "") == "code": + from server.settings import settings + + org = settings.code_org + # Its namespace too, when it names one: whose agent the identity headers name. + namespace = str(getattr(args, "namespace", "") or "") + with ( + pipeline_actor(cli_actor(getattr(args, "cmd", ""))), + customer.cli_command(), + customer.for_org(str(org), namespace=namespace), + ): + try: + rc = int(args.func(args)) + except AuthorityMismatch as e: + print(f" ✗ {e}", file=sys.stderr) + return 2 + if hint := dry_run_hint(args, rc): + # stderr: a command's --json output stays the only thing on stdout + print(hint, file=sys.stderr) + return rc + finally: + query_tag_var.reset(tag_token) + if token is not None: + reset_traffic_class(token) diff --git a/server/code/app/index/ingest_headers.py b/server/code/app/index/ingest_headers.py index 1c315c4846..8ad50fd8bf 100644 --- a/server/code/app/index/ingest_headers.py +++ b/server/code/app/index/ingest_headers.py @@ -47,6 +47,13 @@ def forget_header(org: str, ns: str, path: str) -> None: _header_cache.pop((org, ns, path), None) +def forget_headers() -> None: + """Forget every header text this process read, for a process whose headers another + one wrote (a `loom code backfill --workers` process moving to its next pass).""" + _header_cache.clear() + _sibling_includes.clear() + + def include_candidates(from_path: str, include: str) -> list[str]: """Indexed paths an include target may name, nearest first: relative to the includer's directory, then to each ancestor directory, `MAX_ANCESTOR_DIRS` diff --git a/server/code/app/index/ingest_resolve.py b/server/code/app/index/ingest_resolve.py index 765c26966a..35a5518627 100644 --- a/server/code/app/index/ingest_resolve.py +++ b/server/code/app/index/ingest_resolve.py @@ -14,7 +14,7 @@ from contextvars import ContextVar from typing import TYPE_CHECKING, Any, cast -from server.code.app.index.ingest_headers import include_candidates +from server.code.app.index.ingest_headers import forget_headers, include_candidates from server.code.app.index.ingest_parse import ( _LANE_INCLUDE_LANGS, CODE_ISLAND_LANGS, @@ -127,6 +127,25 @@ async def _reload() -> tuple[float, set[str]]: return hit[1] +def forget_index_reads() -> None: + """Forget what this process cached of the index for a file's edges: the header + texts and, for import resolution, the live path sets, layouts, manifests, listings + and barrels. A pass that must read the finished index (the edges-only second pass) + starts here, whichever process wrote the rows.""" + forget_headers() + _LIVE_PATHS_CACHE.clear() + for cache in ( + _PY_LAYOUT_CACHE, + _GO_LISTING_CACHE, + _GO_MODULE_INDEX_CACHE, + _PACKAGE_JSON_CACHE, + _TSCONFIG_CACHE, + _WORKSPACE_CACHE, + _BARREL_CACHE, + ): + cache.clear() + + def _probes(wanted: Callable[[str], list[str]], specs: list[str]) -> list[str]: """The first `_MAX_INCLUDE_PROBES` distinct candidates of the specifiers, in order, read one specifier at a time and no further than the cut: a file's whole list can run to diff --git a/server/llm/customer.py b/server/llm/customer.py index 77aecad699..cd83b17950 100644 --- a/server/llm/customer.py +++ b/server/llm/customer.py @@ -55,7 +55,7 @@ _system: contextvars.ContextVar[bool] = contextvars.ContextVar( "loom_model_call_system", default=False ) -# Inside a `loom` command (server/cli/app.py), which names its namespace or none. +# Inside a `loom` command (server/cli/dispatch.py), which names its namespace or none. _cli: contextvars.ContextVar[bool] = contextvars.ContextVar("loom_model_call_cli", default=False) # Not an org: the identity tuple's "none", and an org-wide token's wildcard. diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index fd848f2a93..7ce07e3261 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -15,8 +15,8 @@ "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE" ], "loom code backfill": [ - "usage: loom code backfill [-h] [--org ORG] [--namespace NAMESPACE] [--phase {index,embed}] [--embed] [--include-poisoned] [--allow-fake-embedder] [--no-fetch] [--limit LIMIT] [--commit COMMIT] [--paths-file PATHS_FILE] [--concurrency CONCURRENCY] [--edges-second-pass] [--no-edges-second-pass] [--dialect-folder-pass] [--embedding-model-suffix EMBEDDING_MODEL_SUFFIX] [--context-callees {off,calls,calls_callers}] [--callers-from CALLERS_FROM]", - "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE --phase {index,embed} index: parse+chunk+symbols+edges (stubs unless --embed); embed: fill pending embedding stubs --embed embed inline during index --include-poisoned --phase embed: also retry rows that exhausted code_embed_max_attempts --allow-fake-embedder dev only: permit --embed with the fake n-gram fallback embedder --no-fetch index the clone's current tip without fetching upstream --limit LIMIT max files (0 = all) --commit COMMIT index THIS commit (sha or ref present in the clone) instead of the branch tip; implies --no-fetch. Paired arms pin the same tree while the shared mirror keeps moving --paths-file PATHS_FILE repair mode: re-ingest ONLY these repo-relative paths (one per line) at the branch tip; leaves the git_head watermark and cursor untouched --concurrency CONCURRENCY --edges-second-pass after the index phase, derive every file's edges again against the finished name table (a fresh namespace binds cross-file references only once their targets are indexed). Implied by a FIRST full backfill of a namespace; --no-edges-second-pass opts out --no-edges-second-pass skip the implied second pass of a first full backfill --dialect-folder-pass after the index phase, give each undecided SQL file the dialect its own directory's decided files agree on (confidence 0.5) --embedding-model-suffix EMBEDDING_MODEL_SUFFIX twin label: write rows under (e.g. '+ctx2') beside the live label — its own ORDER BY range, its own backfill cursor, no git_head watermark write; readable through code.search's embedding_model override --context-callees {off,calls,calls_callers} callee outline in the context text for THIS run --callers-from CALLERS_FROM namespace whose code_edges supply the 'Called by:' names (default: the indexed namespace; a prefix twin reads the full index's graph)" + "usage: loom code backfill [-h] [--org ORG] [--namespace NAMESPACE] [--phase {index,embed}] [--embed] [--include-poisoned] [--allow-fake-embedder] [--no-fetch] [--limit LIMIT] [--commit COMMIT] [--paths-file PATHS_FILE] [--concurrency CONCURRENCY] [--workers WORKERS] [--edges-second-pass] [--no-edges-second-pass] [--dialect-folder-pass] [--embedding-model-suffix EMBEDDING_MODEL_SUFFIX] [--context-callees {off,calls,calls_callers}] [--callers-from CALLERS_FROM]", + "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE --phase {index,embed} index: parse+chunk+symbols+edges (stubs unless --embed); embed: fill pending embedding stubs --embed embed inline during index --include-poisoned --phase embed: also retry rows that exhausted code_embed_max_attempts --allow-fake-embedder dev only: permit --embed with the fake n-gram fallback embedder --no-fetch index the clone's current tip without fetching upstream --limit LIMIT max files (0 = all) --commit COMMIT index THIS commit (sha or ref present in the clone) instead of the branch tip; implies --no-fetch. Paired arms pin the same tree while the shared mirror keeps moving --paths-file PATHS_FILE repair mode: re-ingest ONLY these repo-relative paths (one per line) at the branch tip; leaves the git_head watermark and cursor untouched --concurrency CONCURRENCY --workers WORKERS --phase index: processes that index the cursor batches and run the edge pass, each with its own connection and --concurrency (1: this process) --edges-second-pass after the index phase, derive every file's edges again against the finished name table (a fresh namespace binds cross-file references only once their targets are indexed). Implied by a FIRST full backfill of a namespace; --no-edges-second-pass opts out --no-edges-second-pass skip the implied second pass of a first full backfill --dialect-folder-pass after the index phase, give each undecided SQL file the dialect its own directory's decided files agree on (confidence 0.5) --embedding-model-suffix EMBEDDING_MODEL_SUFFIX twin label: write rows under (e.g. '+ctx2') beside the live label — its own ORDER BY range, its own backfill cursor, no git_head watermark write; readable through code.search's embedding_model override --context-callees {off,calls,calls_callers} callee outline in the context text for THIS run --callers-from CALLERS_FROM namespace whose code_edges supply the 'Called by:' names (default: the indexed namespace; a prefix twin reads the full index's graph)" ], "loom code reconcile": [ "usage: loom code reconcile [-h] [--org ORG] [--namespace NAMESPACE] [--heal] [--limit LIMIT] [--max-commits MAX_COMMITS] [--no-fetch] [--show SHOW]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index b5ea5829ab..7c6ea36f19 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -237,6 +237,7 @@ "commit", "paths_file", "concurrency", + "workers", "edges_second_pass", "no_edges_second_pass", "dialect_folder_pass", @@ -432,6 +433,21 @@ "help": null, "metavar": null }, + { + "option_strings": [ + "--workers" + ], + "dest": "workers", + "action": "_StoreAction", + "default": 1, + "const": null, + "choices": null, + "nargs": null, + "type": "server.cli.ops:_positive_int", + "required": false, + "help": "--phase index: processes that index the cursor batches and run the edge pass, each with its own connection and --concurrency (1: this process)", + "metavar": null + }, { "option_strings": [ "--edges-second-pass" diff --git a/tests/unit/test_cli_apply_default.py b/tests/unit/test_cli_apply_default.py index ecc2ea884a..ebb268a174 100644 --- a/tests/unit/test_cli_apply_default.py +++ b/tests/unit/test_cli_apply_default.py @@ -7,7 +7,7 @@ import pytest -from server.cli import app +from server.cli import app, dispatch from server.cli._apply import APPLY_HINT, add_apply_flags, dry_run_hint # (argv without the write switch) for every --apply-gated command @@ -59,7 +59,7 @@ def test_dispatch_prints_the_hint_on_stderr(capsys: pytest.CaptureFixture[str]) args = p.parse_args([]) args.cmd = "demo-cmd" args.func = lambda a: print('{"ok": true}') or 0 - assert app._dispatch(args) == 0 + assert dispatch._dispatch(args) == 0 out = capsys.readouterr() assert out.out == '{"ok": true}\n' and APPLY_HINT in out.err diff --git a/tests/unit/test_cli_backfill_publishes_counts.py b/tests/unit/test_cli_backfill_publishes_counts.py index 45a1783e10..ae685e03dc 100644 --- a/tests/unit/test_cli_backfill_publishes_counts.py +++ b/tests/unit/test_cli_backfill_publishes_counts.py @@ -180,6 +180,7 @@ async def no_denylist(*_a: Any) -> None: limit=0, paths_file="", concurrency=1, + workers=1, no_edges_second_pass=True, ) asyncio.run(code_backfill._backfill(args)) diff --git a/tests/unit/test_cli_backfill_second_pass.py b/tests/unit/test_cli_backfill_second_pass.py index 40ea62dd0c..9b1537e281 100644 --- a/tests/unit/test_cli_backfill_second_pass.py +++ b/tests/unit/test_cli_backfill_second_pass.py @@ -1,30 +1,206 @@ """A namespace's first full backfill implies the edges-only second pass — indexing order otherwise leaves every call -to a later file unresolved with zero candidates.""" +to a later file unresolved with zero candidates. The pass is recorded as owed +before the first batch, so a run interrupted before it finishes leaves it to the +next run.""" from __future__ import annotations -from server.cli.code_backfill import second_pass_wanted +import argparse +import asyncio +from typing import Any + +import pytest + +from server.cli import code_backfill +from server.cli.code_backfill import edge_pass_owed +from tests.unit.code_fixtures import repo_config + + +def _owed(**kw: Any) -> str: + base: dict[str, Any] = { + "explicit": False, + "declined": False, + "paths_file": False, + "done_upto": "", + "recorded": "", + "side_by_side": False, + } + return edge_pass_owed(**{**base, **kw}) def test_first_full_backfill_implies_the_second_pass() -> None: - assert ( - second_pass_wanted(explicit=False, declined=False, paths_file=False, done_upto="") is True - ) + assert _owed() == "first-backfill" def test_a_resumed_run_or_a_repair_does_not_imply_it() -> None: - assert ( - second_pass_wanted(explicit=False, declined=False, paths_file=False, done_upto="412") - is False - ) - assert ( - second_pass_wanted(explicit=False, declined=False, paths_file=True, done_upto="") is False - ) + assert not _owed(done_upto="412") + assert not _owed(paths_file=True) + + +def test_a_resumed_run_runs_the_pass_an_earlier_run_owed() -> None: + assert _owed(done_upto="412", recorded="first-backfill") == "first-backfill" def test_the_flags_decide_when_given() -> None: - assert second_pass_wanted(explicit=True, declined=False, paths_file=True, done_upto="9") is True - assert ( - second_pass_wanted(explicit=False, declined=True, paths_file=False, done_upto="") is False - ) + assert _owed(explicit=True, paths_file=True, done_upto="9") == "requested" + assert not _owed(declined=True, recorded="first-backfill") + + +def test_batches_written_side_by_side_owe_the_pass_whatever_the_flags_say() -> None: + assert _owed(side_by_side=True, paths_file=True) == "workers" + assert _owed(side_by_side=True, declined=True, done_upto="412") == "workers" + # and a later run, with one process or the pass declined, still owes it + assert _owed(declined=True, done_upto="412", recorded="workers") == "workers" + + +class _Interrupted(Exception): + """The process went away in the middle of a pass.""" + + +class _Store: + """The namespace's state rows, kept across the runs of one test.""" + + def __init__(self) -> None: + self.state: dict[str, str] = {} + + def __call__(self) -> _Store: + return self # `CodeRepo()` in `_backfill` + + async def get_state(self, org: str, ns: str, key: str) -> str: + return self.state.get(key, "") + + async def set_state(self, org: str, ns: str, key: str, value: str, **_k: Any) -> None: + self.state[key] = value + + +def _harness( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any, paths: list[str] +) -> tuple[_Store, dict[str, Any]]: + """`_backfill` on a stubbed store and checkout; `plan` says which batch or pass + is interrupted, and records the batches and edge passes that ran.""" + from server.code.app.index import bootstrap, denylist + from server.code.store import index + + store = _Store() + plan: dict[str, Any] = { + "fail_batch": None, + "fail_edges": False, + "edge_errors": 0, + "batches": [], + "edges": 0, + } + cfg = repo_config(org="acme", namespace="code-x", git_dir=str(tmp_path)) + + async def _noop(*_a: object, **_k: object) -> None: + return None + + async def _head(*_a: object) -> str: + return "f" * 40 + + async def _paths(*_a: object) -> list[str]: + return list(paths) + + async def _batch(_repo: Any, _org: str, _ns: str, chunk: list[str], **_k: Any) -> str: + if chunk[0] == plan["fail_batch"]: + raise _Interrupted(chunk[0]) + plan["batches"].append(chunk[0]) + return "" + + async def _edges(*_a: object, **_k: object) -> dict[str, int]: + if plan["fail_edges"]: + raise _Interrupted("edge pass") + plan["edges"] += 1 + return {"files": len(paths), "edges": 0, "errors": plan["edge_errors"]} + + monkeypatch.setattr(index, "CodeRepo", store) + monkeypatch.setattr(code_backfill, "_repo_cfg", lambda _a: cfg) + monkeypatch.setattr(code_backfill, "connect_code_plane", _noop) + monkeypatch.setattr(code_backfill, "_backfill_head", _head) + monkeypatch.setattr(code_backfill, "_backfill_paths", _paths) + monkeypatch.setattr(code_backfill, "_held_batch", _batch) + monkeypatch.setattr(code_backfill, "_second_edge_pass", _edges) + monkeypatch.setattr(code_backfill, "_close_index", _noop) + monkeypatch.setattr(denylist, "load_denylist", _noop) + monkeypatch.setattr(bootstrap, "record_backfill_stamps", _noop) + return store, plan + + +def _backfill(**kw: Any) -> int: + base: dict[str, Any] = { + "org": "acme", + "namespace": "code-x", + "phase": "index", + "embed": False, + "paths_file": "", + "limit": 0, + "concurrency": 2, + "workers": 1, + "edges_second_pass": False, + "no_edges_second_pass": False, + "dialect_folder_pass": False, + "embedding_model_suffix": "", + } + base.update(kw) + return asyncio.run(code_backfill._backfill(argparse.Namespace(**base))) + + +_PATHS = [f"f{i}.py" for i in range(450)] + + +def test_a_first_backfill_interrupted_in_its_index_phase_gets_its_edge_pass_on_resume( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +) -> None: + store, plan = _harness(monkeypatch, tmp_path, _PATHS) + plan["fail_batch"] = "f200.py" + with pytest.raises(_Interrupted): + _backfill() + assert store.state["backfill_cursor:index"] == "200" + plan["fail_batch"] = None + assert _backfill() == 0 # resumed at 200 + assert plan["batches"] == ["f0.py", "f200.py", "f400.py"] + assert plan["edges"] == 1 + assert store.state["backfill_edges_owed:index"] == "" + assert store.state["git_head"] == "f" * 40 + + +def test_a_rerun_after_an_interrupted_edge_pass_runs_the_pass( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +) -> None: + store, plan = _harness(monkeypatch, tmp_path, _PATHS) + plan["fail_edges"] = True + with pytest.raises(_Interrupted): + _backfill() + assert store.state["backfill_cursor:index"] == str(len(_PATHS)) + assert "git_head" not in store.state + plan["fail_edges"] = False + assert _backfill() == 0 # no batch left, the pass still owed + assert plan["edges"] == 1 + assert store.state["git_head"] == "f" * 40 + + +def test_declining_the_pass_clears_what_an_earlier_run_owed( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +) -> None: + store, plan = _harness(monkeypatch, tmp_path, _PATHS) + plan["fail_batch"] = "f200.py" + with pytest.raises(_Interrupted): + _backfill() + plan["fail_batch"] = None + assert _backfill(no_edges_second_pass=True) == 0 + assert plan["edges"] == 0 + assert store.state["backfill_edges_owed:index"] == "" + + +def test_an_edge_pass_with_a_failed_file_write_stays_owed_until_a_rerun_finishes_clean( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +) -> None: + store, plan = _harness(monkeypatch, tmp_path, _PATHS) + plan["edge_errors"] = 1 # one file's edge write failed + _backfill() + assert plan["edges"] == 1 + assert store.state["backfill_edges_owed:index"] == "first-backfill" + plan["edge_errors"] = 0 + assert _backfill() == 0 # no batch left, the pass still owed + assert plan["edges"] == 2 + assert store.state["backfill_edges_owed:index"] == "" diff --git a/tests/unit/test_cli_code_backfill_batches.py b/tests/unit/test_cli_code_backfill_batches.py new file mode 100644 index 0000000000..a00bae78a8 --- /dev/null +++ b/tests/unit/test_cli_code_backfill_batches.py @@ -0,0 +1,34 @@ +"""`loom code backfill`'s cursor batches: 200 files each, each with its first index, +and the headers `headers_first` put first end their own batch, so no batch holds both +a header and a source.""" + +from __future__ import annotations + +from server.cli.code_backfill import _cursor_batches + + +def _shape(batches: list[tuple[int, list[str]]]) -> list[tuple[int, int]]: + return [(b, len(chunk)) for b, chunk in batches] + + +def test_no_batch_holds_both_a_header_and_a_source() -> None: + paths = [f"h{i}.h" for i in range(250)] + [f"s{i}.cpp" for i in range(300)] + batches = _cursor_batches(paths) + assert _shape(batches) == [(0, 200), (200, 50), (250, 200), (450, 100)] + for _b, chunk in batches: + assert len({p.endswith(".h") for p in chunk}) == 1 + assert [p for _b, chunk in batches for p in chunk] == paths + + +def test_a_resumed_run_starts_at_its_cursor_wherever_an_earlier_build_cut() -> None: + paths = [f"h{i}.h" for i in range(250)] + [f"s{i}.cpp" for i in range(300)] + # 400 is where 200-file batches cut before the boundary was a cut too + assert _shape(_cursor_batches(paths, 400)) == [(400, 50), (450, 100)] + assert _shape(_cursor_batches(paths, 250)) == [(250, 200), (450, 100)] + assert _cursor_batches(paths, 550) == [] + + +def test_a_tree_without_headers_is_cut_every_200_files() -> None: + paths = [f"f{i}.py" for i in range(450)] + assert _shape(_cursor_batches(paths)) == [(0, 200), (200, 200), (400, 50)] + assert _shape(_cursor_batches([f"h{i}.h" for i in range(3)])) == [(0, 3)] diff --git a/tests/unit/test_cli_code_backfill_workers.py b/tests/unit/test_cli_code_backfill_workers.py new file mode 100644 index 0000000000..d5d453042e --- /dev/null +++ b/tests/unit/test_cli_code_backfill_workers.py @@ -0,0 +1,584 @@ +"""`loom code backfill --workers N`. + +The hand-out (`Workers`) is tested against workers on real pipes run by threads: +batches come back in batch order, the header batches are written before a source +batch starts, nothing is handed out after a hold, and a worker that dies names its +batch. The rest runs the real command, `loom code backfill`, in spawned processes on +stubbed stores: a worker runs its batches under the same bindings as the command's own +batch, it stops inside its batch and then retires when the command, its workers or +their whole process group is signalled or killed, and a worker that cannot start or +retire fails the command. They need no ClickHouse and no server, so they are unit +tests; each starts three interpreters and takes a few seconds.""" + +from __future__ import annotations + +import contextvars +import dataclasses +import functools +import json +import logging +import multiprocessing +import os +import signal +import sys +import threading +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.cli import code_backfill_workers as pool + +# --- the hand-out, against threads on real pipes ------------------------------------- + + +class _Exited: + """A worker process that has exited with `code` (its sentinel reads at once).""" + + def __init__(self, code: int) -> None: + self._r, w = os.pipe() + os.close(w) + self.exitcode = code + + @property + def sentinel(self) -> int: + return self._r + + def join(self) -> None: + return None + + +def _thread_workers( + n: int, log: list[str], *, slow: str = "", held: str = "", dies: str = "" +) -> pool.Workers: + """N workers, each a thread on its own pipe: it logs when each batch starts and ends, + counts a file per path, holds the batch whose first path is `held`, and exits (code + 9) in the batch whose first path is `dies`.""" + lock = threading.Lock() + workers = [] + for i in range(1, n + 1): + mine, theirs = multiprocessing.Pipe() + + def _serve(conn: Any = theirs) -> None: + while True: + try: + _kind, group, paths = conn.recv() + except EOFError: + return + with lock: + log.append(f"start {paths[0]} {group}") + if paths[0] == dies: + conn.close() + return + if paths[0] == slow: + time.sleep(0.3) + with lock: + log.append(f"end {paths[0]}") + conn.send(("done", {"files": len(paths)}, "held" if paths[0] == held else "")) + + threading.Thread(target=_serve, daemon=True).start() + workers.append(pool._Worker(number=i, process=_Exited(9), conn=mine)) + return pool.Workers(workers) + + +async def _index(workers: pool.Workers, batches: list[tuple[int, list[str]]]) -> list[Any]: + return [(b, c["files"], h) async for b, _p, c, h in workers.index_batches(batches)] + + +def test_batches_come_back_in_batch_order_and_headers_are_written_first() -> None: + import asyncio + + log: list[str] = [] + workers = _thread_workers(3, log, slow="b.h") + batches = [(0, ["a.h"]), (1, ["b.h", "c.h"]), (3, ["x.cpp"]), (4, ["y.cpp", "z.cpp"])] + assert asyncio.run(_index(workers, batches)) == [(0, 1, ""), (1, 2, ""), (3, 1, ""), (4, 2, "")] + sources = [i for i, e in enumerate(log) if e.startswith(("start x.cpp", "start y.cpp"))] + assert min(sources) > log.index("end b.h") # the slow header batch ended first + # each batch names its group, so a worker knows when to read the headers again + assert {e.split()[2] for e in log if e.startswith("start")} == {"headers", "sources"} + + +def test_nothing_is_handed_out_after_a_held_batch_and_what_ran_beside_it_is_counted() -> None: + import asyncio + + log: list[str] = [] + workers = _thread_workers(2, log, slow="a.py", held="b.py") + batches = [(i, [f"{c}.py"]) for i, c in enumerate("abcdef")] + # b is held while a still runs: a comes back first, then b, and nothing else ran + assert asyncio.run(_index(workers, batches)) == [(0, 1, ""), (1, 1, "held")] + assert sorted(e for e in log if e.startswith("start")) == [ + "start a.py sources", + "start b.py sources", + ] + + +def test_a_worker_that_exits_in_a_batch_names_the_batch_and_its_exit_code() -> None: + import asyncio + + workers = _thread_workers(2, [], dies="c.py") + batches = [(0, ["a.py"]), (200, ["c.py", "d.py"])] + with pytest.raises(SystemExit, match=r"exited 9 during the index batch at 200 \(2 files\)"): + asyncio.run(_index(workers, batches)) + + +def test_the_edge_pass_takes_its_batches_in_any_order() -> None: + import asyncio + + log: list[str] = [] + workers = _thread_workers(2, log, slow="a.py") + got = asyncio.run(workers.edge_batches([(0, ["a.py"]), (1, ["b.py", "c.py"])])) + assert sorted(c["files"] for c in got) == [1, 2] + assert {e.split()[2] for e in log if e.startswith("start")} == {"edges"} + + +# --- the real command, in spawned processes ------------------------------------------ + + +def _note(path: str, **event: Any) -> None: + with open(path, "a") as f: + f.write(json.dumps({"pid": os.getpid(), **event}) + "\n") + + +def _events(path: Path) -> list[dict[str, Any]]: + return [json.loads(ln) for ln in path.read_text().splitlines()] if path.exists() else [] + + +def _plain(value: Any) -> Any: + """A context value as it can be compared across processes.""" + if value is None or isinstance(value, str | int | float | bool): + return value + if isinstance(value, tuple | list): + return [_plain(v) for v in value] + if type(value) is dict: + return {str(k): _plain(v) for k, v in value.items()} + if dataclasses.is_dataclass(value) and not isinstance(value, type): + return {f.name: _plain(getattr(value, f.name)) for f in dataclasses.fields(value)} + return type(value).__qualname__ # a span, a decimal context: per process by nature + + +def _context_probe(run: Any) -> dict[str, Any]: + """What a batch runs under: every context variable, and the process-wide state the + command sets up (logging, the SIGTERM handler, the umask, the wired seams, the + enrollment and model-work admission).""" + from server.auth.directory import directory + from server.core import retirement + from server.core.model_work_gate import get_model_work_gate + + umask = os.umask(0) + os.umask(umask) + try: + directory() + wired = True + except Exception: # noqa: BLE001 — unwired is what the probe reports + wired = False + root = logging.getLogger() + return { + "context": { + v.name: _plain(x) for v, x in contextvars.copy_context().items() if v.name != "_task" + }, + "log_level": root.level, + "stderr_handler": any(getattr(h, "stream", None) is sys.stderr for h in root.handlers), + "sigterm": getattr(signal.getsignal(signal.SIGTERM), "__name__", ""), + "umask": umask, + "wired": wired, + "admitted": (get_model_work_gate().active, retirement.get_gate().active), + "namespace": run.cfg.namespace, + "model": run.model, + } + + +def _prepare(log: str, opts: dict[str, Any]) -> None: + """The stores and providers of a spawned command or worker: a client that only + opens, a registry holding acme/code-x, an active configuration whose model is + `stored-model`, a checkout of 1000 paths, and a run whose batches note the context + they run in. The workers this process starts are prepared the same way.""" + import asyncio + + from server.cli import _ch, code_backfill + from server.code.app.index import bootstrap, repo_registry + from server.code.store.index import CodeRepo + from server.core import ch as ch_mod + from server.core import pg_profile, settings_overrides + from server.embedding import embedder + from server.insights.app import provider_command + from server.settings import settings + + role = "worker" if opts.get("is_worker") else "command" + settings.code_self_service_enabled = True + settings.code_repos_root = opts["root"] + os.makedirs(repo_registry.git_dir_for("acme/x"), exist_ok=True) + row = {"org": "acme", "namespace": "code-x", "repo": "acme/x", "active": True} + + class _Client: + connected = False + + async def connect(self) -> None: + self.connected = True + + async def disconnect(self) -> None: + self.connected = False + + client = _Client() + saved = Path(opts["root"]) / "state.json" # the namespace's state rows, kept across runs + state: dict[str, str] = json.loads(saved.read_text()) if saved.exists() else {} + + async def _noop(*_a: object, **_k: object) -> None: + return None + + async def _true(*_a: object, **_k: object) -> bool: + return True + + async def _rows(self: object) -> list[dict[str, Any]]: + if opts.get("unread") and role == "worker": + raise RuntimeError("registry unreachable") + _note(log, role=role, event="registry read") + return [row] + + async def _enroll() -> None: + from server.core import retirement + + _note(log, role=role, event="enrolled") + retirement.get_gate().enrolled = True + + async def _load() -> None: + embedder._cached = SimpleNamespace(model_name="stored-model") + + async def _retire(*_a: object) -> bool: + _note(log, role=role, event="retired") + return not (opts.get("retire_fails") and role == "worker") + + async def _get_state(self: object, org: str, ns: str, key: str) -> str: + return state.get(key, "") + + async def _set_state(self: object, org: str, ns: str, key: str, value: str, **_k: Any) -> None: + state[key] = value + saved.write_text(json.dumps(state)) + _note(log, role=role, event="state", key=key, value=value) + + async def _close_index(_repo: object, counters: dict[str, int], *_a: object, **k: Any) -> None: + _note(log, role=role, event="closed", files=counters["files"]) + if k.get("republish", True): + await _republish(_repo) + + async def _republish(*_a: object) -> None: + _note(log, role=role, event="republished") + + class _Run: + def __init__(self, repo: Any, cfg: Any, args: Any, kw: dict[str, Any]) -> None: + self.repo, self.cfg, self.args, self.org, self.ns = repo, cfg, args, kw["org"], kw["ns"] + emb = kw["embedder"] + self.model = self.model_name = emb.model_name if emb else "" + self.counters = code_backfill.index_counters() + self.edges = code_backfill.edge_counters() + + async def batch(self, paths: list[str]) -> str: + _note(log, role=role, event="batch", first=paths[0], probe=_context_probe(self)) + if opts.get("live"): + await _write_and_resolve(self, paths) + if opts.get("block"): + try: + await asyncio.sleep(120) + finally: + _note(log, role=role, event="cancelled") + # what a round writes on its way out (`RoundReads.__aexit__`) + await asyncio.sleep(1.0) + _note(log, role=role, event="flushed") + if paths[0] == opts.get("slow"): + await asyncio.sleep(1.0) + if paths[0] == opts.get("held"): + return "acme's model calls are switched off" + self.counters["files"] += len(paths) + return "" + + async def edge_batch(self, paths: list[str]) -> None: + live = await _resolve(self, paths[0]) if opts.get("live") else None + _note(log, role=role, event="edges", first=paths[0], live=live) + self.edges["files"] += len(paths) + if paths[0] == opts.get("edge_fails"): + self.edges["errors"] += 1 # a file's edge write failed in this batch + + written = Path(opts["root"]) / "written.txt" + + async def _live_path_set(self: object, org: str, ns: str) -> list[str]: + return written.read_text().split() if written.exists() else [] + + async def _resolve(run: Any, path: str) -> int: + # the import resolver's own oracle, as a file's ingest reads it + from server.code.app.index.ingest_resolve import _live_paths + + live = await _live_paths(run.repo, "acme", "code-x", SimpleNamespace(path=path)) + return len(live or ()) + + async def _write_and_resolve(run: Any, paths: list[str]) -> None: + await _resolve(run, paths[0]) # this batch's files resolve against the set as read + _append(paths) # and then land in the index + await asyncio.sleep(0.3) + + def _append(paths: list[str]) -> None: + with written.open("a") as f: + f.write("\n".join(paths) + "\n") + + async def _open(cls: object, repo: object, cfg: Any, args: Any, head: str, **kw: Any) -> Any: + return _Run(repo, cfg, args, kw) + + async def _head(*_a: object) -> str: + return "f" * 40 + + async def _paths(*_a: object) -> list[str]: + return [f"f{i}.py" for i in range(opts.get("files", 1000))] + + ch_mod.get_client = lambda: client + pg_profile.check_configured = _noop + _ch.check_acceptance = _noop + settings_overrides.refresh = _noop + CodeRepo.registry_rows = _rows + CodeRepo.get_state = _get_state + CodeRepo.set_state = _set_state + CodeRepo.live_path_set = _live_path_set + provider_command.register_process = _enroll + provider_command.load_active_configuration = _load + provider_command.drain_task_sets = _true + provider_command.flush_registered_buffers = _true + provider_command._retire_until = _retire + code_backfill.connect_code_plane = _noop + code_backfill._backfill_head = _head + code_backfill._backfill_paths = _paths + code_backfill._close_index = _close_index + code_backfill._republish_counts = _republish + bootstrap.record_backfill_stamps = _noop + code_backfill._Run.open = classmethod(_open) # type: ignore[method-assign,assignment] + if not opts.get("is_worker"): + # The workers this command starts run `_worker`, which stubs them the same way. + worker = functools.partial(_worker, log, {**opts, "is_worker": True}) + pool._worker_main = worker # type: ignore[assignment] + + +def _worker(log: str, opts: dict[str, Any], command: Any) -> None: + """A worker process on the stubbed stores, entered as the pool enters one.""" + _prepare(log, opts) + pool._worker_main(command) + + +def _command(argv: list[str], log: str, opts: dict[str, Any]) -> None: + """`loom ` in this process, on the stubbed stores; in its own process group + when `group` is set, so a test can signal the command and its workers together.""" + if opts.get("group"): + os.setpgid(0, 0) + _prepare(log, opts) + from server.cli.app import main + + sys.exit(main(argv)) + + +def _spawn(tmp_path: Path, workers: int, **opts: Any) -> tuple[Any, Path]: + log = tmp_path / f"events-{workers}.jsonl" + argv = ["code", "backfill", "--org", "acme", "--namespace", "code-x", "--embed"] + argv += ["--no-fetch", "--workers", str(workers)] + proc = multiprocessing.get_context("spawn").Process( + target=_command, args=(argv, str(log), {"root": str(tmp_path / "repos"), **opts}) + ) + proc.start() + return proc, log + + +def _wait_for(check: Any, timeout: float = 60.0) -> Any: + end = time.monotonic() + timeout + while time.monotonic() < end: + got = check() + if got: + return got + time.sleep(0.1) + raise AssertionError("timed out") + + +def _gone(pid: int) -> bool: + """Whether `pid` has exited (a zombie waiting for its reaper has).""" + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + stat = Path(f"/proc/{pid}/stat") + if not stat.exists(): + return False # alive, and no /proc to tell a zombie: not gone + return stat.read_text().rsplit(")", 1)[1].split()[0] == "Z" + + +def test_a_worker_runs_its_batches_under_the_bindings_the_command_s_own_batch_runs_under( + tmp_path: Path, +) -> None: + """The same command with one process and with two: every context variable and the + process-wide setup a batch sees is the same in a worker, so a binding added to the + command reaches the workers without a list to keep.""" + one, one_log = _spawn(tmp_path, 1, files=10) + two, two_log = _spawn(tmp_path, 2, files=1000) + one.join(120) + two.join(120) + assert (one.exitcode, two.exitcode) == (0, 0) + [command] = [e["probe"] for e in _events(one_log) if e["event"] == "batch"] + in_workers = [e for e in _events(two_log) if e["event"] == "batch"] + assert {e["role"] for e in in_workers} == {"worker"} and len(in_workers) == 5 + assert len({e["pid"] for e in in_workers}) == 2 + for e in in_workers: + assert e["probe"] == command + assert command["context"]["loom_traffic_class"] == ["background", "cli:code"] + assert (command["namespace"], command["model"], command["wired"]) == ( + "code-x", + "stored-model", + True, + ) + # each worker read the registry once enrolled, and retired when the run closed + per_worker: dict[int, list[str]] = {} + for e in _events(two_log): + if e["role"] == "worker" and e["event"] in ("enrolled", "registry read", "retired"): + per_worker.setdefault(e["pid"], []).append(e["event"]) + assert list(per_worker.values()) == [["enrolled", "registry read", "retired"]] * 2 + + +def test_a_held_batch_on_real_workers_starts_nothing_more_and_what_ran_beside_it_is_counted( + tmp_path: Path, +) -> None: + proc, log = _spawn(tmp_path, 2, slow="f0.py", held="f200.py") + proc.join(120) + assert proc.exitcode == 1 + events = _events(log) + assert sorted(e["first"] for e in events if e["event"] == "batch") == ["f0.py", "f200.py"] + cursor = [e["value"] for e in events if e.get("key") == "backfill_cursor:index"] + assert cursor == ["200"] + assert [e["files"] for e in events if e["event"] == "closed"] == [200] + # the held run republishes once, after its last state write + written = [e["event"] for e in events if e["event"] in ("state", "republished")] + assert written[-1] == "republished" and written.count("republished") == 1 + # the edge pass the run owes stays recorded for the next run + owed = [e["value"] for e in events if e.get("key") == "backfill_edges_owed:index"] + assert owed == ["workers"] + + +def test_an_edge_batch_that_fails_a_write_leaves_the_pass_owed_for_a_resume_without_workers( + tmp_path: Path, +) -> None: + """A worker's edge batch returns with a failed file write. The run still ends (the + cursor clears, `git_head` is written), but the pass stays owed, so a resume with one + process runs it again and only a clean pass clears the record.""" + first, first_log = _spawn(tmp_path, 2, files=400, edge_fails="f200.py") + first.join(120) + assert first.exitcode == 0 # one failed file in 400 does not fail the run + owed = [e["value"] for e in _events(first_log) if e.get("key") == "backfill_edges_owed:index"] + assert owed == ["workers"] # recorded, and never cleared + resume, resume_log = _spawn(tmp_path, 1, files=400) + resume.join(120) + assert resume.exitcode == 0 + events = _events(resume_log) + assert [e["first"] for e in events if e["event"] == "edges"] == ["f0.py", "f200.py"] + owed = [e["value"] for e in events if e.get("key") == "backfill_edges_owed:index"] + assert owed == [""] # cleared once the pass ran without errors + + +@pytest.mark.parametrize("sig", [signal.SIGTERM, signal.SIGKILL]) +def test_a_terminated_or_killed_command_leaves_no_worker_running( + tmp_path: Path, sig: signal.Signals +) -> None: + """Both workers are in a two-minute batch. SIGTERM: the command stops them, they + retire, and it exits 143 at once. SIGKILL: the command cannot, and its closed pipes + stop them just the same.""" + proc, log = _spawn(tmp_path, 2, block=True) + + def _in_batches() -> list[int]: + pids = [e["pid"] for e in _events(log) if e["event"] == "batch"] + return pids if len(pids) == 2 else [] + + pids = _wait_for(_in_batches) + started = time.monotonic() + os.kill(proc.pid, sig) + proc.join(60) + assert proc.exitcode == (143 if sig == signal.SIGTERM else -signal.SIGKILL) + _wait_for(lambda: all(_gone(p) for p in pids)) + assert time.monotonic() - started < 60 + retired = {e["pid"] for e in _events(log) if e["event"] == "retired"} + assert set(pids) <= retired + + +def test_a_worker_whose_retirement_fails_fails_the_command( + tmp_path: Path, capfd: pytest.CaptureFixture[str] +) -> None: + """The command still writes its durable end (the owed pass cleared, `git_head`, + the counts) before it reports the workers that did not retire, as one process + retires after its command has returned: a rerun repeats nothing.""" + proc, log = _spawn(tmp_path, 2, files=400, retire_fails=True) + proc.join(120) + assert proc.exitcode == 1 + assert "backfill workers did not retire cleanly (worker 1 exited 1" in capfd.readouterr().err + events = [e for e in _events(log) if e["role"] == "command"] + state = {e["key"]: e["value"] for e in events if e["event"] == "state"} + assert state["git_head"] == "f" * 40 and state["backfill_edges_owed:index"] == "" + kinds = [e["event"] for e in events] + watermark = next(i for i, e in enumerate(events) if e.get("key") == "git_head") + assert "republished" in kinds[watermark:] # the counts carry the new watermark + + +@pytest.mark.parametrize("sig", [signal.SIGTERM, signal.SIGINT]) +def test_a_signal_to_the_whole_group_stops_each_batch_before_its_worker_retires( + tmp_path: Path, sig: signal.Signals +) -> None: + """A terminal's Ctrl-C, `timeout` and a systemd stop signal every process of the + group: each worker's own handler cancels its command, and the batch, awaited in + that command's task, unwinds before the worker retires.""" + proc, log = _spawn(tmp_path, 2, block=True, group=True) + + def _in_batches() -> list[int]: + pids = [e["pid"] for e in _events(log) if e["event"] == "batch"] + return pids if len(pids) == 2 else [] + + pids = _wait_for(_in_batches) + os.killpg(proc.pid, sig) + proc.join(60) + assert proc.exitcode != 0 + _wait_for(lambda: all(_gone(p) for p in pids)) + for pid in pids: + mine = [e["event"] for e in _events(log) if e["pid"] == pid] + # cancelled once: the batch's own cleanup completes before the worker retires + assert mine.index("cancelled") < mine.index("flushed") < mine.index("retired") + + +def test_the_edge_pass_in_a_worker_resolves_imports_to_files_another_worker_wrote( + tmp_path: Path, +) -> None: + """The import resolver caches the namespace's live paths per process. Two workers + write their batches; in the edge pass each one resolves against every file written, + its own and the other's, as one process would.""" + proc, log = _spawn(tmp_path, 2, live=True) + proc.join(120) + assert proc.exitcode == 0 + edges = [e for e in _events(log) if e["event"] == "edges"] + assert {e["role"] for e in edges} == {"worker"} and len({e["pid"] for e in edges}) == 2 + assert {e["live"] for e in edges} == {1000} + + +def test_a_worker_that_cannot_open_its_run_fails_the_command_with_its_reason( + tmp_path: Path, capfd: pytest.CaptureFixture[str] +) -> None: + proc, log = _spawn(tmp_path, 2, unread=True) + proc.join(120) + assert proc.exitcode == 1 + err = capfd.readouterr().err + assert "exited 1 before its run opened; its error is above" in err + assert "BrokenPipeError" not in err # the other worker leaves quietly + assert "repository registry" in err.lower() # the worker's own one-line reason + assert not [e for e in _events(log) if e["event"] == "batch"] + + +def test_a_run_starts_no_more_workers_than_either_pass_has_batches() -> None: + import argparse + import contextlib + + from server.cli.code_backfill import _workers_for + + args = argparse.Namespace(workers=4) + assert isinstance(_workers_for(args, "h", 1, 1), contextlib.nullcontext) + assert isinstance(_workers_for(args, "h", 0, 0), contextlib.nullcontext) + + +def test_a_worker_killed_by_a_signal_is_named_so_not_sent_to_an_error_that_is_not_there() -> None: + assert pool._ended(-9) + pool._above(-9) == "was killed by SIGKILL (out of memory?)" + assert pool._ended(1) + pool._above(1) == "exited 1; its error is above" diff --git a/tests/unit/test_cli_hygiene.py b/tests/unit/test_cli_hygiene.py index 630ca7d2de..2ba6398c73 100644 --- a/tests/unit/test_cli_hygiene.py +++ b/tests/unit/test_cli_hygiene.py @@ -259,7 +259,7 @@ def test_dispatch_tags_every_clickhouse_query_with_the_command( ) -> None: import asyncio - from server.cli.app import _dispatch + from server.cli.dispatch import _dispatch from server.core.ch import current_query_tag seen: list[str] = [] @@ -280,7 +280,7 @@ def _func(_: argparse.Namespace) -> int: def test_serve_runs_with_no_command_context_bound() -> None: """The server's writes and reads bind their own actor, class and tag; a process-wide `process:cli:serve` would outrank every worker's fallback.""" - from server.cli.app import _dispatch + from server.cli.dispatch import _dispatch from server.core.ch import current_query_tag from server.memory.app.provenance import writer_actor from server.observability.traffic_class import current_traffic_class @@ -300,7 +300,7 @@ def _serve(_: argparse.Namespace) -> int: def test_a_command_refused_for_another_deployment_prints_one_line_and_exits_2( capsys: pytest.CaptureFixture[str], ) -> None: - from server.cli.app import _dispatch + from server.cli.dispatch import _dispatch from server.core.pg import AuthorityMismatch def _func(_: argparse.Namespace) -> int: diff --git a/tests/unit/test_decision_extract.py b/tests/unit/test_decision_extract.py index 163151ecbe..ced69c0a28 100644 --- a/tests/unit/test_decision_extract.py +++ b/tests/unit/test_decision_extract.py @@ -1190,7 +1190,7 @@ def test_the_command_is_dry_run_by_default() -> None: def test_a_cli_run_writes_as_the_decisions_command() -> None: - from server.cli.app import _dispatch + from server.cli.dispatch import _dispatch from server.memory.app.provenance import writer_actor seen: list[str] = [] diff --git a/tests/unit/test_model_call_customer.py b/tests/unit/test_model_call_customer.py index 4ef861b651..15a0b2e36d 100644 --- a/tests/unit/test_model_call_customer.py +++ b/tests/unit/test_model_call_customer.py @@ -288,7 +288,7 @@ def test_a_provider_rebuild_batch_makes_one_call_per_org(metered, monkeypatch) - def test_a_cli_command_for_one_org_bills_it(metered, monkeypatch) -> None: import argparse - from server.cli import app + from server.cli import dispatch seen: list[str] = [] @@ -296,10 +296,10 @@ def command(args: argparse.Namespace) -> int: seen.append(customer.current()) return 0 - app._dispatch(argparse.Namespace(cmd="reembed", org="acme", func=command)) + dispatch._dispatch(argparse.Namespace(cmd="reembed", org="acme", func=command)) monkeypatch.setattr(settings, "code_org", "code-org") - app._dispatch(argparse.Namespace(cmd="code", org=None, func=command)) # LOOM_CODE_ORG - app._dispatch( + dispatch._dispatch(argparse.Namespace(cmd="code", org=None, func=command)) # LOOM_CODE_ORG + dispatch._dispatch( argparse.Namespace(cmd="reembed", func=command) ) # every org: each row names its own assert seen == ["acme", "code-org", ""] diff --git a/tests/unit/test_model_call_identity.py b/tests/unit/test_model_call_identity.py index 0a7535b6a1..e9e5e4d0f8 100644 --- a/tests/unit/test_model_call_identity.py +++ b/tests/unit/test_model_call_identity.py @@ -603,7 +603,7 @@ def test_a_loom_command_bills_its_namespaces_agent_and_one_naming_none_is_refuse ) -> None: import argparse - from server.cli import app + from server.cli import dispatch seen: list[dict[str, str]] = [] @@ -611,11 +611,13 @@ def command(args: argparse.Namespace) -> int: seen.append(_sent()) return 0 - app._dispatch(argparse.Namespace(cmd="import", org="acme", namespace=AGENT_NS, func=command)) + dispatch._dispatch( + argparse.Namespace(cmd="import", org="acme", namespace=AGENT_NS, func=command) + ) assert seen[0]["X-Agent"] == "agent-7" # the agent whose namespace it writes into with pytest.raises(customer.Unattributed, match="--namespace"): # --org alone: no agent to name, and never the gateway's default agent - app._dispatch(argparse.Namespace(cmd="import", org="acme", func=command)) + dispatch._dispatch(argparse.Namespace(cmd="import", org="acme", func=command)) assert len(seen) == 1 # the refused call returned nothing @@ -624,7 +626,7 @@ def test_a_deployment_call_inside_a_loom_command_is_never_refused(directory) -> deployment's own calls (`customer.system()`): no namespace is needed for them.""" import argparse - from server.cli import app + from server.cli import dispatch seen: list[dict[str, str]] = [] @@ -634,5 +636,5 @@ def command(args: argparse.Namespace) -> int: return 0 for org in ("", "acme"): - app._dispatch(argparse.Namespace(cmd="recalibrate", org=org, func=command)) + dispatch._dispatch(argparse.Namespace(cmd="recalibrate", org=org, func=command)) assert len(seen) == 2 and not any("X-Agent" in h for h in seen) diff --git a/tests/unit/test_model_calls_switch.py b/tests/unit/test_model_calls_switch.py index 5620a434bc..4066c04a06 100644 --- a/tests/unit/test_model_calls_switch.py +++ b/tests/unit/test_model_calls_switch.py @@ -96,7 +96,7 @@ def test_a_cli_command_for_a_switched_off_org_sends_nothing(monkeypatch, cmd: st # customer header it is what puts the org's switch in force. import argparse - from server.cli import app + from server.cli import dispatch from server.embedding.fake import FakeNGramEmbedder monkeypatch.setattr(settings, "inference_customer_header", "") @@ -109,7 +109,7 @@ def command(args: argparse.Namespace) -> int: return 0 with pytest.raises(customer.ModelCallsDisabled): - app._dispatch( + dispatch._dispatch( argparse.Namespace(cmd=cmd, org="acme" if cmd != "code" else None, func=command) ) assert sent == [] diff --git a/tests/unit/test_model_calls_switch_workers.py b/tests/unit/test_model_calls_switch_workers.py index 27fcf98293..66e3dd7fff 100644 --- a/tests/unit/test_model_calls_switch_workers.py +++ b/tests/unit/test_model_calls_switch_workers.py @@ -661,6 +661,7 @@ def __new__(cls) -> Any: limit=0, paths_file="", concurrency=1, + workers=1, ) assert asyncio.run(code_backfill._backfill(args)) == 1 assert sent == [] # nothing of the switched-off org's code went out diff --git a/tests/unit/test_period_digest.py b/tests/unit/test_period_digest.py index 59fa70ab87..00d2aba1bf 100644 --- a/tests/unit/test_period_digest.py +++ b/tests/unit/test_period_digest.py @@ -698,7 +698,7 @@ def test_loom_period_digest_writes_as_its_command(monkeypatch: pytest.MonkeyPatc import argparse import asyncio - from server.cli import app, maintenance + from server.cli import dispatch, maintenance from server.memory.app import period_digest from server.memory.app.provenance import writer_actor @@ -723,7 +723,7 @@ async def _run(cfg: Any, **_: Any) -> Any: rewrite=False, dry_run=True, ) - assert app._dispatch(args) == 0 + assert dispatch._dispatch(args) == 0 assert seen == ["process:cli:period-digest"] diff --git a/tests/unit/test_pg_authority.py b/tests/unit/test_pg_authority.py index 28b1555e40..8613091cee 100644 --- a/tests/unit/test_pg_authority.py +++ b/tests/unit/test_pg_authority.py @@ -6507,7 +6507,7 @@ def test_the_worker_and_the_cli_wire_the_commits_writer(monkeypatch: pytest.Monk """Each root calls `wire()` before it runs: a commit in a process that never did is refused (`WriterNotWired`).""" from server import worker_main - from server.cli import app + from server.cli import app, dispatch from server.memory.app import provenance from server.memory.store import pg_publish from server.workers import child @@ -6523,7 +6523,7 @@ def _ran(coro: Any) -> None: worker_main.main(["--lease-fd", "3", "--alive-fd", "4"]) assert pg_publish._writer is provenance.writer_actor - monkeypatch.setattr(app, "_dispatch", lambda args: 0) + monkeypatch.setattr(dispatch, "_dispatch", lambda args: 0) monkeypatch.setattr(app, "_load_dotenv_like_the_container", lambda: None) monkeypatch.setattr(pg_publish, "_writer", None) assert app.main(["period-digest", "--org", "o", "--namespace", "n"]) == 0