From 851f4b438b923162ed7219e602de5234972c7be5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 00:42:50 +0000 Subject: [PATCH 01/81] Skip a SCIP document that fails to decode or convert; its file keeps its rows, marked stale One document python-protobuf refuses (a string that is not UTF-8) or that fails to convert no longer fails the compiler-tier pass. The converter names it once on stderr, lists it in the delta's `skipped_files` and counts it; `run_harness` logs the warning for every tier. A full run does not retire a skipped file, and `apply_delta` marks it stale (`scip_stale:` in `code_index_state`) until a delta applies or deletes it, which `scip_stale_paths` reads. `code_scip_stop_on_failed_document` fails the pass on such a document instead. An index that cannot be read to its end still fails. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 29 ++-- docs/reference/configuration.md | 1 + docs/reference/status.md | 3 +- loom.example.yaml | 5 + schemas/loom-settings.schema.json | 5 + scripts/scip_harness/README.md | 10 ++ scripts/scip_harness/lib.sh | 6 +- scripts/scip_harness/run_go_monorepo_delta.sh | 5 +- scripts/scip_harness/scip_to_delta.py | 150 +++++++++++++----- server/code/api/models_symbol.py | 4 +- server/code/app/index/compiler_tier.py | 21 ++- server/code/app/index/delta_file.py | 31 ++-- server/code/app/index/scip_delta.py | 29 +++- server/code/app/symbol/graph.py | 3 +- server/code/domain/index/epistemic.py | 8 +- server/code/domain/index/state.py | 5 + server/code/store/index/symbols.py | 33 +++- server/settings/catalog.py | 4 + .../integration/test_code_scip_stale_mark.py | 41 +++++ tests/unit/snapshots/settings_defaults.json | 1 + tests/unit/test_code_ctor_call_edges.py | 5 +- tests/unit/test_code_ctor_edges_remainder.py | 2 +- tests/unit/test_code_delta_stream.py | 3 + .../unit/test_code_scip_skipped_documents.py | 79 +++++++++ tests/unit/test_code_scip_ts_delta_worker.py | 48 ++++++ tests/unit/test_scip_apply_rounds.py | 6 + tests/unit/test_scip_entry_lock.py | 3 + tests/unit/test_scip_to_delta_skip.py | 137 ++++++++++++++++ 28 files changed, 587 insertions(+), 90 deletions(-) create mode 100644 tests/integration/test_code_scip_stale_mark.py create mode 100644 tests/unit/test_code_scip_skipped_documents.py create mode 100644 tests/unit/test_scip_to_delta_skip.py diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 5edd518d2e8..1cfb3eecd60 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1257,20 +1257,21 @@ the output to read. ## Failure model -| Failure | Behaviour | Recovery | -| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `git fetch` fails | watermark unmoved; the entry's `fetch` tier records the error, its kind and fix (`tier_health`) | the next pass (supervisor backoff) | -| crash mid-commit | the commit is re-run | idempotent upserts | -| a file fails to parse | chunks without symbols, `code_files.index_error` set (a parse past `code_parse_timeout_s` or `code_parse_memory_mb` included, and one that could not run in its process) | `code.index_errors` lists them; fixed by the next change or a repair (raising either limit re-reads none) | -| every file fails to parse with `LookupError` "... is loaded from outside the interpreter's site-packages" | chunks without symbols for every file: tree-sitter or a grammar is installed where the parse process does not see it | install the tree-sitter packages into the server interpreter's own environment, not through `PYTHONPATH` or the user site | -| embedding provider down | chunks stored without vectors; lexical search still serves | `code_embed_recovery` | -| compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | -| a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | -| compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | -| a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | -| GitHub rate limit | the pass ends, cursor unmoved | the next pass | -| branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | -| weekly graph stats fail | last week's ranks keep serving | the next weekly pass | +| Failure | Behaviour | Recovery | +| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `git fetch` fails | watermark unmoved; the entry's `fetch` tier records the error, its kind and fix (`tier_health`) | the next pass (supervisor backoff) | +| crash mid-commit | the commit is re-run | idempotent upserts | +| a file fails to parse | chunks without symbols, `code_files.index_error` set (a parse past `code_parse_timeout_s` or `code_parse_memory_mb` included, and one that could not run in its process) | `code.index_errors` lists them; fixed by the next change or a repair (raising either limit re-reads none) | +| every file fails to parse with `LookupError` "... is loaded from outside the interpreter's site-packages" | chunks without symbols for every file: tree-sitter or a grammar is installed where the parse process does not see it | install the tree-sitter packages into the server interpreter's own environment, not through `PYTHONPATH` or the user site | +| embedding provider down | chunks stored without vectors; lexical search still serves | `code_embed_recovery` | +| compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | +| a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | +| compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | +| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows, marked stale (callers and impact name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | +| a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | +| GitHub rate limit | the pass ends, cursor unmoved | the next pass | +| branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | +| weekly graph stats fail | last week's ranks keep serving | the next weekly pass | The code index's gauges (`loom.code.index_lag_commits`, `loom.code.stale_files`, `loom.code.tier_lag_seconds`, `loom.code.embed_backlog`, `loom.code.files_errored`) are diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 251101e9d6c..6272a784ef4 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -457,6 +457,7 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through | `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` | `int` | `180` | live | Largest compiler-tier delta file the server reads, in MiB; a larger one fails the entry's pass. It bounds the work of an entry's pass and the path text kept (code-index-operations.md). | | `LOOM_CODE_SCIP_DELTA_MAX_NODES` | `int` | `6000000` | live | Most `{`, `[` and `,` bytes a compiler-tier delta may hold, counted before it is parsed; more fails the entry's pass (sizing: code-index-operations.md). | | `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES` | `int` | `3000000` | live | Most `{`, `[` and `,` bytes one apply round of a compiler-tier delta parses: its memory bound; one value over it fails the pass (code-index-operations.md). | +| `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT` | `bool` | `False` | | True fails the entry's compiler-tier pass on a document that fails to parse or convert (a string that is not UTF-8, say). False: the document is skipped and logged, and its file keeps its compiler rows, marked stale. | | `LOOM_CODE_SCIP_FULL_ENABLED` | `bool` | `True` | | C++ full re-index: seeds an entry the delta has no watermark for, and re-indexes each entry every `code_scip_full_every_hours` (heals deltas that hit the TU cap). One entry per pass, under its entry lock. | | `LOOM_CODE_SCIP_FULL_INTERVAL_SECONDS` | `int` | `900` | | Seconds between the C++ full re-index's checks for an entry that is due. | | `LOOM_CODE_SCIP_FULL_EVERY_HOURS` | `int` | `168` | | Hours between full re-indexes of one entry. | diff --git a/docs/reference/status.md b/docs/reference/status.md index 693dec19cca..5d528bb68f3 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -89,7 +89,7 @@ default is `off`) are not listed here. -54 boolean settings load false. +55 boolean settings load false. | Setting | Meaning | | --- | --- | @@ -108,6 +108,7 @@ default is `off`) are not listed here. | `LOOM_CODE_REPO_PUBLIC` | The scalar repo entry is public: its namespace registers join_policy=open and discoverable. | | `LOOM_CODE_SANDBOX_REQUIRED` | Set by deployments that ship the sandbox profiles: a repository job refuses to run rather than run unsandboxed, and /v1/health reports the missing sandbox as an error. | | `LOOM_CODE_SCIP_APPLY_ENABLED` | SCIP delta apply (compiler-grade tier uploaded via code.scip_ingest). | +| `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT` | True fails the entry's compiler-tier pass on a document that fails to parse or convert (a string that is not UTF-8, say). | | `LOOM_CODE_SEARCH_CARD_LEG` | The card leg: file cards are searched by cosine and the top files' chunks join fusion as a capped RRF list (the history leg's shape). | | `LOOM_CODE_SELF_SERVICE_GIT_UNSANDBOXED` | True lets a host without the sandbox add and fetch a self-service entry with a network remote: its git jobs (ls-remote, clone, fetch) run as plain processes and it gets no compiler tier. | | `LOOM_CODE_SELF_SERVICE_PLATFORM_ADMIN_ONLY` | True leaves code.repo.remote_branches, code.repo.add and code.repo.add_branch to platform admins: a token scoped to namespaces, or a trusted caller acting for another subject, is refused too. | diff --git a/loom.example.yaml b/loom.example.yaml index 8dbfc14df7e..1243e495062 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -1505,6 +1505,11 @@ settings: # memory bound; one value over it fails the pass (code-index-operations.md). [live] # code_scip_delta_round_max_nodes: 3000000 + # True fails the entry's compiler-tier pass on a document that fails to parse or + # convert (a string that is not UTF-8, say). False: the document is skipped and + # logged, and its file keeps its compiler rows, marked stale. [restart] + # code_scip_stop_on_failed_document: false + # C++ full re-index: seeds an entry the delta has no watermark for, and re-indexes # each entry every `code_scip_full_every_hours` (heals deltas that hit the TU cap). # One entry per pass, under its entry lock. [restart] diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index d1defd9cc84..affe247766d 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -1913,6 +1913,11 @@ "type": "string", "description": "The scip-python binary: a name looked up on PATH, or a path." }, + "code_scip_stop_on_failed_document": { + "default": false, + "type": "boolean", + "description": "True fails the entry's compiler-tier pass on a document that fails to parse or convert (a string that is not UTF-8, say). False: the document is skipped and logged, and its file keeps its compiler rows, marked stale." + }, "code_scip_ts_delta_enabled": { "default": true, "type": "boolean", diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 4be22c1eca7..18daee8d7ac 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -35,6 +35,16 @@ The in-server workers call the scripts by path with rerun as a full index; no delta is written. Any other exit is a failed run. The converter prints one `delta: N files, …` summary line, then `wrote (sha …)`. +A document the converter cannot parse or convert (a string that is not UTF-8, +say) is skipped: it is named once on stderr (`scip_to_delta: warning: skipped +document …`), listed in the delta's `skipped_files` and counted in the summary +line, and the rest of the index converts. The server keeps that file's compiler +rows and marks them stale until a later delta converts it. With +`SCIP_STOP_ON_FAILED_DOCUMENT=1` (the server sets it from +`LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT`) `convert_delta` passes +`--stop-on-failed-document`, and such a document fails the run. An index whose +records cannot be read to the end fails the run either way. + ## Requirements - a ClickHouse checkout that `cmake -G Ninja` can configure (the harness diff --git a/scripts/scip_harness/lib.sh b/scripts/scip_harness/lib.sh index 356fb19c44d..84408ea12f9 100644 --- a/scripts/scip_harness/lib.sh +++ b/scripts/scip_harness/lib.sh @@ -87,8 +87,12 @@ window_files() { # convert_delta : with DELTA_OUT set, write the # JSON delta there (the in-server workers' mode); otherwise upload it to # LOOM_BASE_URL with the writer token LOOM_API_KEY, addressed to ORG / NS -# when they are set. +# when they are set. A document that fails to parse or convert is skipped with +# a warning on stderr; SCIP_STOP_ON_FAILED_DOCUMENT=1 fails the run on it instead. convert_delta() { + if [[ "${SCIP_STOP_ON_FAILED_DOCUMENT:-0}" == "1" ]]; then + set -- "$@" --stop-on-failed-document + fi if [[ -n "${DELTA_OUT:-}" ]]; then "$PYTHON" "$HARNESS_DIR/scip_to_delta.py" "$@" --dry-run "$DELTA_OUT" return diff --git a/scripts/scip_harness/run_go_monorepo_delta.sh b/scripts/scip_harness/run_go_monorepo_delta.sh index 623653c7b92..fb600efbbb3 100755 --- a/scripts/scip_harness/run_go_monorepo_delta.sh +++ b/scripts/scip_harness/run_go_monorepo_delta.sh @@ -102,10 +102,11 @@ run_module() { echo "skip $dir: scip-go failed: $(tail -1 "$work/scip-go.log")" >&2 return 0 fi + # the converter's summary line and its last line (where the delta went) if [[ -n "${DELTA_OUT_DIR:-}" ]]; then - DELTA_OUT="$DELTA_OUT_DIR/${prefix//\//__}.json" convert_delta "${args[@]}" | tail -1 + DELTA_OUT="$DELTA_OUT_DIR/${prefix//\//__}.json" convert_delta "${args[@]}" | sed -n '/^delta: /p;$p' else - convert_delta "${args[@]}" | tail -1 + convert_delta "${args[@]}" | sed -n '/^delta: /p;$p' fi echo "done $dir" } diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index d4777f7e10d..e25b200209c 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -386,11 +386,11 @@ def _ts_def_kind(symbol: str, occ, lines: list[str] | None) -> str: return "" -def _ts_prepass(data: bytes, scip_pb2, ctx: _TsContext) -> None: +def _ts_prepass(data: bytes, scip_pb2, ctx: _TsContext, skips: _Skips) -> None: """Every definition's kind, index-wide, so a reference to a term in another document knows whether its target is a function (a `calls` edge) or a type (`uses_type`) — one streaming pass before the emit.""" - for doc in _stream_documents(data, scip_pb2): + for doc in _stream_documents(data, scip_pb2, skips=skips): if doc.relative_path.startswith("node_modules/") or "/node_modules/" in doc.relative_path: continue lines = ctx.src.lines(doc.relative_path) @@ -428,7 +428,7 @@ def _ts_prepass(data: bytes, scip_pb2, ctx: _TsContext) -> None: } -def _go_prepass(data: bytes, scip_pb2, ctx: _GoContext) -> None: +def _go_prepass(data: bytes, scip_pb2, ctx: _GoContext, skips: _Skips) -> None: """Every definition's kind from the indexer's own SymbolInformation.kind, index-wide, before any symbol is parsed. Without it the descriptor loop leaves a struct field (`Stats#MaxIdleConns.`) and an @@ -443,7 +443,7 @@ def _go_prepass(data: bytes, scip_pb2, ctx: _GoContext) -> None: } except (AttributeError, KeyError): return - for doc in _stream_documents(data, scip_pb2): + for doc in _stream_documents(data, scip_pb2, skips=skips): for si in doc.symbols: if not si.symbol.startswith(GO_SCHEME + " ") or si.symbol in ctx.def_kinds: continue @@ -452,12 +452,12 @@ def _go_prepass(data: bytes, scip_pb2, ctx: _GoContext) -> None: ctx.def_kinds[si.symbol] = mapped -def _go_definition_modules(data: bytes, scip_pb2) -> set[str]: +def _go_definition_modules(data: bytes, scip_pb2, skips: _Skips) -> set[str]: """The module paths the index DEFINES symbols for: what a checkout's go.mod files would say, read from the definitions when no checkout is at hand — one streaming pass.""" out: set[str] = set() - for doc in _stream_documents(data, scip_pb2): + for doc in _stream_documents(data, scip_pb2, skips=skips): for occ in doc.occurrences: if occ.symbol_roles & 0x1 and occ.symbol.startswith(GO_SCHEME + " gomod "): parts = occ.symbol.split(" ", 4) @@ -567,12 +567,12 @@ def _line_of(rng) -> int: _INHERIT_KINDS = frozenset({"class", "struct", "interface", "type", "enum"}) # incl. struct -def _implementation_targets(data: bytes, scip_pb2) -> dict[str, set[str]]: +def _implementation_targets(data: bytes, scip_pb2, skips: _Skips) -> dict[str, set[str]]: """symbol -> the symbols it `is_implementation`-relates to, over the whole index (one streaming pass): what `_direct_targets` needs to tell a declared base from an ancestor the emitter listed transitively.""" out: dict[str, set[str]] = {} - for doc in _stream_documents(data, scip_pb2): + for doc in _stream_documents(data, scip_pb2, skips=skips): for si in doc.symbols: targets = { rel.symbol @@ -712,7 +712,7 @@ def _is_ctor_qname(qname: str) -> bool: return len(parts) >= 2 and bool(parts[-1]) and parts[-1] == parts[-2] -def _ctor_overloads(records, scip_pb2) -> dict[str, list[str]]: +def _ctor_overloads(data, scip_pb2, skips: _Skips) -> dict[str, list[str]]: """class qualified name -> sorted constructor signature hints, from every occurrence of a constructor symbol in the index (declarations in a class body are reference-role occurrences, so a class whose header is included @@ -720,11 +720,7 @@ def _ctor_overloads(records, scip_pb2) -> dict[str, list[str]]: this delta). The hash IS scip-clang's overload identity, so each entry is one symbol_id on the server.""" out: dict[str, set[str]] = {} - for field, payload in records: - if field != 2: - continue - doc = scip_pb2.Document() - doc.ParseFromString(payload) + for doc in _stream_documents(data, scip_pb2, skips=skips): for occ in doc.occurrences: parsed = _parse_symbol(occ.symbol) if parsed is None or parsed[1] != "function" or not _is_ctor_qname(parsed[0]): @@ -822,6 +818,8 @@ def varint(p: int) -> tuple[int, int]: field, wire = tag >> 3, tag & 7 if wire == 2: # length-delimited length, pos = varint(pos) + if pos + length > end: + raise ValueError(f"record at {pos} runs {pos + length - end} bytes past the end") payload = data[pos : pos + length] pos += length yield field, payload @@ -837,42 +835,81 @@ def varint(p: int) -> tuple[int, int]: def _document_path(payload) -> str: """A serialized Document's relative_path (field 1), read without parsing - its occurrences.""" - for field, value in _top_level_records(payload): - if field == 1: - return bytes(value).decode("utf-8", "replace") + its occurrences; "" when it cannot be read.""" + try: + for field, value in _top_level_records(payload): + if field == 1: + return bytes(value).decode("utf-8", "replace") + except (IndexError, ValueError): + pass return "" -def _stream_documents(data, scip_pb2, *, paths: set[str] | None = None, ordered: bool = False): +class _Skips: + """The documents one run skipped: one python-protobuf refuses (a string field that + is not UTF-8, say) or one that fails to convert. Each is named once on stderr, the + delta lists the named ones (`skipped_files`: the server keeps their rows and marks + them stale) and counts all of them. With `stop` the failure fails the run instead.""" + + def __init__(self, stop: bool = False) -> None: + self.stop = stop + self.labels: set[str] = set() + self.paths: set[str] = set() + + def add(self, path: str, err: Exception, index: int = -1) -> None: + if self.stop: + raise err + # a document whose path cannot be read is told apart by its place in the index + label = path or f"" + if label in self.labels: + return # several passes read the index; the warning is printed once + self.labels.add(label) + if path: + self.paths.add(path) + print(f"{SKIPPED_WARNING} {label!r}: {err!r}", file=sys.stderr) + + +# The line the converter writes to stderr for each skipped document; the server logs it. +SKIPPED_WARNING = "scip_to_delta: warning: skipped document" + + +def _stream_documents( + data, scip_pb2, *, skips: _Skips, paths: set[str] | None = None, ordered: bool = False +): """Yield scip.Document messages by streaming the Index's top-level records (field 2 = documents) instead of parsing one giant message — a full ClickHouse index is ~1GB, which trips python-protobuf's whole-message limits ("Wire format was corrupt"). `paths` parses only the documents with those relative paths; `ordered` yields them sorted by path (index order among equal paths), so the delta does not depend on - the order a parallel indexer wrote its documents in.""" - records = (payload for field, payload in _top_level_records(data) if field == 2) + the order a parallel indexer wrote its documents in. A document that does + not parse is skipped (`skips`); an index whose records cannot be read to the + end raises.""" + records = enumerate(payload for field, payload in _top_level_records(data) if field == 2) if paths is not None or ordered: - keyed = [(_document_path(payload), payload) for payload in records] + keyed = [(_document_path(payload), i, payload) for i, payload in records] if paths is not None: - keyed = [kp for kp in keyed if kp[0] in paths] + keyed = [k for k in keyed if k[0] in paths] if ordered: - keyed.sort(key=lambda kp: kp[0]) - records = (payload for _path, payload in keyed) - for payload in records: + keyed.sort(key=lambda k: k[0]) + records = ((i, payload) for _path, i, payload in keyed) + for i, payload in records: doc = scip_pb2.Document() - doc.ParseFromString(payload) + try: + doc.ParseFromString(payload) + except Exception as e: # noqa: BLE001 — any failure of one document skips it + skips.add(_document_path(payload), e, i) + continue yield doc _TS_TYPE_KINDS = frozenset({"class", "interface", "type", "enum"}) -def _index_scheme(data: bytes, scip_pb2) -> str: +def _index_scheme(data: bytes, scip_pb2, skips: _Skips) -> str: """The scheme of the first non-local symbol in the index (`cxx` for scip-clang, `scip-python`, `scip-typescript`, `scip-go`).""" - for doc in _stream_documents(data, scip_pb2): + for doc in _stream_documents(data, scip_pb2, skips=skips): for si in doc.symbols: if not si.symbol.startswith("local "): return si.symbol.split(" ", 1)[0] @@ -959,7 +996,12 @@ def __init__( def _prepare( - data, scip_pb2, source_root: str | None, exclude_generated: bool, path_prefix: str + data, + scip_pb2, + source_root: str | None, + exclude_generated: bool, + path_prefix: str, + skips: _Skips, ) -> _Run: """The index-wide passes before the emit: the source root, the scheme's context (Go package scopes, TypeScript workspace map and definition @@ -970,7 +1012,7 @@ def _prepare( src = _SourceLines(Path(source_root) if source_root else None) global _TS, _GO _TS = None - scheme = _index_scheme(data, scip_pb2) + scheme = _index_scheme(data, scip_pb2, skips) is_ts = scheme == TS_SCHEME # Go symbols take the fast tier's package scope _GO = ( @@ -979,20 +1021,20 @@ def _prepare( else None ) if _GO is not None and not _GO.modules: - _GO.modules = _go_definition_modules(data, scip_pb2) + _GO.modules = _go_definition_modules(data, scip_pb2, skips) if _GO is not None: - _go_prepass(data, scip_pb2, _GO) + _go_prepass(data, scip_pb2, _GO, skips) if is_ts: # The workspace map and the definition kinds before # any symbol is parsed (a term's kind is its definition's shape) _TS = _TsContext(ts_package_dirs(src.root if src.available else None), src) - _ts_prepass(data, scip_pb2, _TS) + _ts_prepass(data, scip_pb2, _TS, skips) ctors: dict[str, list[str]] = {} # constructor calls through factories are a C++ form (`std::make_shared`) is_cxx = scheme == CXX_SCHEME if src.available and is_cxx: - ctors = _ctor_overloads(_top_level_records(data), scip_pb2) - ancestors = _implementation_targets(data, scip_pb2) + ctors = _ctor_overloads(data, scip_pb2, skips) + ancestors = _implementation_targets(data, scip_pb2, skips) return _Run( src, is_ts, is_cxx, ctors, ancestors, exclude_generated, is_python=scheme == "scip-python" ) @@ -1204,8 +1246,9 @@ def _enclosing(line: int) -> tuple[str, str] | None: class DeltaStream: """A delta produced one file at a time: `head` (version, commit, base), `files` (a one-shot iterator, sorted by path), then `tail()` — the - deleted paths, the stats and the features, complete once `files` is - exhausted.""" + deleted paths, the skipped ones, the stats and the features, complete once + `files` is exhausted. A document that fails to parse or convert is skipped + (`_Skips`), or fails the run with `stop_on_failed_document`.""" def __init__( self, @@ -1219,10 +1262,14 @@ def __init__( full: bool = False, exclude_generated: bool = False, path_prefix: str = "", + stop_on_failed_document: bool = False, ) -> None: scip_pb2 = _ensure_scip_pb2() data = _read_index(index_path) - self._run = _prepare(data, scip_pb2, source_root, exclude_generated, path_prefix) + self._skips = _Skips(stop_on_failed_document) + self._run = _prepare( + data, scip_pb2, source_root, exclude_generated, path_prefix, self._skips + ) self._deleted = sorted(set(deleted)) self._prefix = path_prefix # A FULL index converted with its source claims the feature: the @@ -1239,10 +1286,16 @@ def __init__( self.files = self._files(data, scip_pb2, changed) def _files(self, data, scip_pb2, changed: set[str] | None): - for doc in _stream_documents(data, scip_pb2, paths=changed, ordered=True): + for doc in _stream_documents( + data, scip_pb2, skips=self._skips, paths=changed, ordered=True + ): if changed is not None and doc.relative_path not in changed: continue - entry = _convert_document(doc, self._run) + try: + entry = _convert_document(doc, self._run) + except Exception as e: # noqa: BLE001 — any failure of one document skips it + self._skips.add(doc.relative_path, e) + continue if entry is None: continue if self._prefix: @@ -1252,9 +1305,14 @@ def _files(self, data, scip_pb2, changed: set[str] | None): def tail(self) -> dict: out: dict = { "deleted_files": self._deleted, + # repository-relative, as the emitted paths are + "skipped_files": sorted( + f"{self._prefix}/{p}" if self._prefix else p for p in self._skips.paths + ), "stats": { "factory_ctor_edges": self._run.factory_edges, "skipped_generated": self._run.skipped_generated, + "skipped_failed": len(self._skips.labels), }, } if self._claims_ctor_calls: @@ -1273,6 +1331,7 @@ def convert( full: bool = False, exclude_generated: bool = False, path_prefix: str = "", + stop_on_failed_document: bool = False, ) -> dict: """The whole delta as one dict (the command line streams it instead). `changed`: the relative paths to emit (None = every document). @@ -1293,6 +1352,7 @@ def convert( full=full, exclude_generated=exclude_generated, path_prefix=path_prefix, + stop_on_failed_document=stop_on_failed_document, ) files = list(stream.files) return {**stream.head, "files": files, **stream.tail()} @@ -1403,6 +1463,7 @@ def _summary(counts: dict) -> str: f"delta: {counts['files']} files, {counts['symbols']} symbols, {counts['edges']} edges " f"({counts['factory_ctor_edges']} constructor calls through factories; " f"{counts['skipped_generated']} generated files dropped; " + f"{counts['skipped_failed']} failed documents skipped; " f"features {counts['features']})" ) @@ -1440,6 +1501,12 @@ def main() -> int: "scip-go run per module of a monorepo); prefixed onto every file path so " "the delta's paths are repository-relative like the parser tier's", ) + ap.add_argument( + "--stop-on-failed-document", + action="store_true", + help="fail the run on a document that cannot be parsed or converted, instead " + "of skipping it with a warning", + ) ap.add_argument( "--source-root", default=None, @@ -1475,6 +1542,7 @@ def main() -> int: full=args.full, exclude_generated=bool(args.exclude_generated), path_prefix=prefix, + stop_on_failed_document=bool(args.stop_on_failed_document), ) if args.dry_run: diff --git a/server/code/api/models_symbol.py b/server/code/api/models_symbol.py index 7ebd2d8333e..d22a51b07f4 100644 --- a/server/code/api/models_symbol.py +++ b/server/code/api/models_symbol.py @@ -516,8 +516,8 @@ def _drop_unrequested_candidates( # treesitter_only_files, external_calls, ctor_edges_absent (a # constructor seed with no edge in an index that predates constructor # calls through factories), scip_stale_files (a compiler-tier edge - # served from a file changed since that tier last ran), truncated (the - # walk stopped short of the graph)}. + # served from a file changed since that tier last ran, or one it skipped), + # truncated (the walk stopped short of the graph)}. epistemic: str = "lower_bound" # Why `epistemic` is `lower_bound`, from the set above; empty when it is `exact`. causes: list[str] = Field(default_factory=list) diff --git a/server/code/app/index/compiler_tier.py b/server/code/app/index/compiler_tier.py index 656f281c8fa..ff5dfd73fdd 100644 --- a/server/code/app/index/compiler_tier.py +++ b/server/code/app/index/compiler_tier.py @@ -41,6 +41,10 @@ logger = logging.getLogger("loom.code_index.compiler_tier") +# The line the converter (scripts/scip_harness/scip_to_delta.py) writes for each +# document it skipped. +SKIPPED_WARNING = "scip_to_delta: warning: skipped document" + # The exit code every tier harness gives when the window's base commit is # not in the checkout (history rewritten, a squashed or force-pushed branch): # the window cannot be diffed, and only a full index can bring the tier back. @@ -563,12 +567,13 @@ def gone_documents(live: set[str], delta: DeltaFile, producer: str) -> list[str] """The live compiler-tier paths of `producer`'s languages the full-run delta does not mention, joined with the paths it already marks deleted — sorted, so the apply is deterministic. Another tier's documents in the same namespace are never gone: - a full TypeScript run must not retire the Python tier's rows.""" + a full TypeScript run must not retire the Python tier's rows. Neither is a document + the converter skipped (`skipped_files`): the file is there, and its rows stay.""" from server.code.domain.index.compiler_tiers import owns_path present = set(delta.paths) mine = {p for p in live if owns_path(producer, p)} - return sorted((mine - present) | set(delta.deleted_files)) + return sorted(((mine - present) | set(delta.deleted_files)) - set(delta.skipped_files)) def resolve_binary(configured: str) -> Path: @@ -698,13 +703,16 @@ async def run_harness( repository's own build files, so only the checkout, `out_dir` and `writable` are writable; the checkout's .git stays read-only (a hook or config planted there would run outside the sandbox later), as do the harness scripts. - RuntimeError naming the timeout past `timeout_s`.""" + RuntimeError naming the timeout past `timeout_s`. The converter skips a document + that fails, or stops on it with `code_scip_stop_on_failed_document`; each skipped + document's warning line is logged here, once.""" from server.core.paths import SCIP_HARNESS_DIR + stop = "1" if settings.code_scip_stop_on_failed_document else "0" try: done = await run_job( ["bash", str(harness), str(checkout), *args], - env=env, + env={**env, "SCIP_STOP_ON_FAILED_DOCUMENT": stop}, timeout_s=timeout_s, writable=[checkout, out_dir, *writable], readonly=[checkout / ".git", SCIP_HARNESS_DIR, *readonly], @@ -713,4 +721,7 @@ async def run_harness( ) except TimeoutError: raise tier_health.ToolOutputError(f"harness timed out after {timeout_s}s") from None - return done.returncode, done.stdout.decode("utf-8", "replace") + out = done.stdout.decode("utf-8", "replace") + for line in dict.fromkeys(ln for ln in out.splitlines() if ln.startswith(SKIPPED_WARNING)): + logger.warning("%s: %s", harness.name, line) + return done.returncode, out diff --git a/server/code/app/index/delta_file.py b/server/code/app/index/delta_file.py index eba3cdb4321..a6abc57bfb0 100644 --- a/server/code/app/index/delta_file.py +++ b/server/code/app/index/delta_file.py @@ -250,6 +250,7 @@ def __init__( self._path, self._stamp = path, stamp self.commit, self.features = header.commit, header.features self.deleted_files = parsed.deleted + self.skipped_files = parsed.skipped # each entry's path, counted bytes and characters, by index self.paths, self._nodes, self._chars = parsed.paths, parsed.nodes, parsed.chars self._round_nodes, self._max_bytes = round_nodes, max_bytes # as read at open @@ -333,7 +334,8 @@ def _read(self, plan: list[array[int]], tail: list[ScipFile]) -> Iterator[list[S # Any other key is checked for its shape and size only, and neither it nor its value is # kept. _HEADER = frozenset({"delta_version", "commit", "base", "features"}) -_READ = _HEADER | {"files", "deleted_files"} +_PATH_LISTS = frozenset({"deleted_files", "skipped_files"}) +_READ = _HEADER | {"files"} | _PATH_LISTS # each header field as `ScipDelta` checks it, so a value past its cap is refused as it # is read, not held while the entries are parsed _HEADER_FIELDS: dict[str, TypeAdapter[Any]] = { @@ -349,11 +351,13 @@ def _header_value(key: str, value: Any) -> Any: raise ValueError(f"delta invalid: {key!r}") from None -def _deleted_path(value: Any) -> str: +def _listed_path(value: Any, key: str) -> str: + """One path of `deleted_files` or `skipped_files`.""" + what = key.removesuffix("_files") if not isinstance(value, str): - raise ValueError("delta invalid: a deleted path is not a string") + raise ValueError(f"delta invalid: a {what} path is not a string") if len(value.encode()) > PATH_BYTES: - raise ValueError(f"delta invalid: a deleted path is over {PATH_BYTES} bytes") + raise ValueError(f"delta invalid: a {what} path is over {PATH_BYTES} bytes") return value @@ -362,9 +366,9 @@ def _deleted(paths: list[str]) -> list[ScipFile]: def _skip(values: _Values, key: str) -> None: - """Read past a top-level value: the deleted paths one at a time, as `open_delta` - reads them, any other value whole.""" - if key == "deleted_files": + """Read past a top-level value: a path list one path at a time, as `open_delta` + reads it, any other value whole.""" + if key in _PATH_LISTS: for _ in _array(values): values.span() else: @@ -391,11 +395,12 @@ def _count(path: Path, fd: int, stamp: _Stamp, max_nodes: int) -> None: @dataclass class _Parsed: - """What the checking parse keeps: the small header values, the deleted paths, and - each entry's path, counted bytes and characters.""" + """What the checking parse keeps: the small header values, the deleted and skipped + paths, and each entry's path, counted bytes and characters.""" header: dict[str, Any] = field(default_factory=dict) deleted: list[str] = field(default_factory=list) + skipped: list[str] = field(default_factory=list) paths: list[str] = field(default_factory=list) nodes: array[int] = field(default_factory=lambda: array("I")) chars: array[int] = field(default_factory=lambda: array("Q")) @@ -410,9 +415,13 @@ def _parse(values: _Values) -> _Parsed: if key in seen: raise ValueError(f"delta invalid: {key!r} twice") seen.add(key) - if key == "deleted_files": + if key in _PATH_LISTS: # one path at a time: a long list is many small values, not one large one - out.deleted = [_deleted_path(values.value()) for _ in _array(values)] + listed = [_listed_path(values.value(), key) for _ in _array(values)] + if key == "deleted_files": + out.deleted = listed + else: + out.skipped = listed elif key == "files": for index, _ in enumerate(_array(values)): text, nodes = values.text(index) diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 6ba5c322e0b..1c6cc99cc8e 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -8,8 +8,9 @@ Apply semantics per touched file: upsert every symbol/edge the delta emits for it, tombstone scip rows in that file the delta no longer emits; -files in `deleted_files` tombstone entirely. Idempotent — re-applying the -same delta converges to the same live set. +files in `deleted_files` tombstone entirely. A file in `skipped_files` (its +document failed to convert) keeps its rows and is marked stale. Idempotent — +re-applying the same delta converges to the same live set. """ from __future__ import annotations @@ -24,6 +25,7 @@ from server.code.app.index.entry_lock import check_held from server.code.domain.extract.treesitter import symbol_id +from server.code.domain.index.state import SCIP_STALE_PREFIX from server.code.store.index import CodeRepo, build_row from server.workers import pass_context @@ -82,6 +84,8 @@ class ScipDelta(BaseModel): base: str = Field(default="", max_length=64) files: list[ScipFile] = Field(default_factory=list) deleted_files: list[str] = Field(default_factory=list) + # documents the converter skipped: their rows stay, marked stale + skipped_files: list[str] = Field(default_factory=list) features: list[Annotated[str, Field(max_length=64)]] = Field( default_factory=list, max_length=16 ) @@ -99,6 +103,7 @@ class _Delta(Protocol): commit: str deleted_files: list[str] + skipped_files: list[str] features: list[str] def rounds(self, max_files: int, keep: Callable[[str], bool]) -> Generator[list[ScipFile]]: ... @@ -114,6 +119,7 @@ class ScipApplyStats(BaseModel): edges_dropped_declarations: int = 0 files_skipped_out_of_scope: int = 0 files_skipped_excluded: int = 0 # the entry's path denylist + files_skipped_failed: int = 0 # the converter skipped them; their rows are marked stale def _path_refusal(org: str, ns: str) -> Any: @@ -250,6 +256,7 @@ def keep(path: str) -> bool: rounds = delta.rounds(APPLY_ROUND_FILES, keep) reading = False + refreshed: set[str] = set() try: while True: reading = True @@ -257,6 +264,7 @@ def keep(path: str) -> bool: reading = False if batch is None: break + refreshed.update(f.path for f in batch) await _apply_files(repo, org, ns, delta.commit, batch, stats) del batch # freed before the next round is read finally: @@ -264,6 +272,8 @@ def keep(path: str) -> bool: # its thread keeps it until that read returns and the rounds are collected if not reading: rounds.close() + await _mark_stale(repo, org, ns, delta, refreshed) + stats.files_skipped_failed = len(delta.skipped_files) if FEATURE_CTOR_CALLS in delta.features: check_held() await repo.set_state( @@ -277,6 +287,21 @@ def keep(path: str) -> bool: return stats +async def _mark_stale(repo: Any, org: str, ns: str, delta: _Delta, refreshed: set[str]) -> None: + """Mark each skipped file stale at the delta's commit, and drop the mark of a file + this delta applied or deleted (`SCIP_STALE_PREFIX`).""" + skipped = set(delta.skipped_files) + refreshed -= skipped + if not skipped and not refreshed: + return + check_held() + for path in sorted(skipped): + await repo.set_state(org, ns, SCIP_STALE_PREFIX + path, delta.commit) + if refreshed: + for path in sorted(await repo.scip_stale_marks(org, ns) & refreshed): + await repo.set_state(org, ns, SCIP_STALE_PREFIX + path, "") + + async def _apply_files( repo: Any, org: str, ns: str, commit: str, files: list[ScipFile], stats: ScipApplyStats ) -> None: diff --git a/server/code/app/symbol/graph.py b/server/code/app/symbol/graph.py index 0c8047461ca..0581ddcd6ef 100644 --- a/server/code/app/symbol/graph.py +++ b/server/code/app/symbol/graph.py @@ -486,5 +486,6 @@ def _stale_note(stale_paths: set[str]) -> str: return "" return ( f"compiler-tier edges from {len(stale_paths)} file(s) changed since that tier " - f"last ran ({', '.join(sorted(stale_paths)[:3])}): their lines may be stale" + f"last ran or skipped by it ({', '.join(sorted(stale_paths)[:3])}): their lines " + "may be stale" ) diff --git a/server/code/domain/index/epistemic.py b/server/code/domain/index/epistemic.py index f3bdbd30ab3..dfa3aa35645 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -24,7 +24,8 @@ its callers are external to the graph scip_stale_files a compiler-tier edge served from a file the fast tier rewrote after the compiler - tier's last run: its line and caller come + tier's last run, or whose document that + run skipped: its line and caller come from content that tier never saw truncated the walk stopped short of the graph (a node cap, a hop read cut at its row limit, a @@ -50,8 +51,9 @@ # other line and the graph would not know. Cleared once the tier that answers for the # seed carries them. CAUSE_CTOR = "ctor_edges_absent" -# A served scip edge whose file changed after the compiler tier last ran: the row -# survives from an older tree (its call may have moved or gone), so it is no proof. +# A served scip edge whose file changed after the compiler tier last ran, or whose +# document that run skipped: the row survives from an older tree (its call may have +# moved or gone), so it is no proof. CAUSE_STALE = "scip_stale_files" # The walk stopped before the graph did: whatever else holds, the rows are part of it. CAUSE_TRUNCATED = "truncated" diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index b3d25262b1b..0386e1b6b76 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -24,6 +24,11 @@ class StateEntry(TypedDict, total=False): # The state key of an entry's bootstrap stage, whose detail is JSON. STAGE_KEY = "bootstrap_stage" +# A compiler-tier file whose last delta skipped its document (it failed to parse or +# convert) keeps the rows of an earlier state: `SCIP_STALE_PREFIX + path` holds the +# commit of that delta until a later delta applies or deletes the file, and +# `scip_stale_paths` reads the file as stale meanwhile. +SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's # `{"reason": ...}` detail; `code.repos` and `code.index_status` show only these, and # `CLONE_FAILED` for a reason in no shape the job writes. diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index c2cd2cb855b..626fd8db95d 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -9,6 +9,7 @@ from clickhouse_connect.driver.binding import format_bind_value +from server.code.domain.index.state import SCIP_STALE_PREFIX from server.code.domain.index.test_gate import TEST_PATH_PATTERN from server.code.store.index.base import CodeRepoBase from server.code.store.index.sql import _batched, _hex, like_contains @@ -538,10 +539,12 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str """Paths a compiler-tier edge may not be read from as current: the fast tier wrote the file's row after the compiler tier last ran (the `.py` watermark, `scip_commit_py`, for a Python file when there is one, `scip_commit` - otherwise), deleted the file, or holds no row for it. The fast tier writes a - file row when the file's bytes change, so a row newer than the watermark is - content the compiler tier has not seen; a deleted or unknown file is a tree - the compiler tier's rows no longer describe.""" + otherwise), deleted the file, or holds no row for it, or the compiler tier's + last delta for it skipped its document (`SCIP_STALE_PREFIX`). The fast tier + writes a file row when the file's bytes change, so a row newer than the + watermark is content the compiler tier has not seen; a deleted or unknown file + is a tree the compiler tier's rows no longer describe; a skipped document left + the rows of its earlier state.""" if not paths: return set() asked = list(dict.fromkeys(paths))[:200] @@ -559,12 +562,32 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL AND created_at <= if(endsWith(path, '.py') AND t_py > toDateTime(0), t_py, t_scip) + AND path NOT IN ( + SELECT substring(state_key, length({mark:String}) + 1) + FROM loom.code_index_state FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND startsWith(state_key, {mark:String}) AND state_value != '' + ) """, - {"org": org, "ns": ns, "paths": asked}, + {"org": org, "ns": ns, "paths": asked, "mark": SCIP_STALE_PREFIX}, ) # the query names the FRESH paths; every other asked path is stale return set(asked) - {str(r["path"]) for r in rows} + async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + """The paths marked stale because a compiler-tier delta skipped their document + (`SCIP_STALE_PREFIX`); a cleared mark holds an empty value.""" + rows = await self._ch.query_all( + """ + SELECT substring(state_key, length({mark:String}) + 1) AS path + FROM loom.code_index_state FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND startsWith(state_key, {mark:String}) AND state_value != '' + """, + {"org": org, "ns": ns, "mark": SCIP_STALE_PREFIX}, + ) + return {str(r["path"]) for r in rows} + async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: one namespace-wide distinct read, taken once per full compiler run so diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 1c941424ea8..233539f9e2f 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1300,6 +1300,10 @@ def _check_git_proxy(self) -> CodeSettings: # Most `{`, `[` and `,` bytes one apply round of a compiler-tier delta parses: its # memory bound; one value over it fails the pass (code-index-operations.md). code_scip_delta_round_max_nodes: Annotated[int, LIVE] = Field(default=3_000_000, ge=1) + # True fails the entry's compiler-tier pass on a document that fails to parse or + # convert (a string that is not UTF-8, say). False: the document is skipped and + # logged, and its file keeps its compiler rows, marked stale. + code_scip_stop_on_failed_document: bool = False # C++ full re-index: seeds an entry the delta has no watermark for, and # re-indexes each entry every `code_scip_full_every_hours` (heals deltas # that hit the TU cap). One entry per pass, under its entry lock. diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py new file mode 100644 index 00000000000..ac7811863f3 --- /dev/null +++ b/tests/integration/test_code_scip_stale_mark.py @@ -0,0 +1,41 @@ +"""A file whose compiler-tier document a delta skipped reads as stale, although the +tier's watermark moved past the file's last change, until a later delta applies it.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import Any + +import pytest + +from server.code.app.index.scip_delta import ScipDelta, ScipFile, apply_delta +from server.code.store.index import CodeRepo +from server.core.ch import get_client +from tests.integration._resources import unique_org + + +@pytest.mark.asyncio +async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: Any) -> None: + org, ns = unique_org("scip-stale-mark"), "code-stale-mark" + paths = ["src/a.cpp", "src/bad.cpp"] + changed = datetime.now(UTC).replace(tzinfo=None, microsecond=0) - timedelta(hours=1) + ch_client.insert( + "loom.code_files", + [[org, ns, p, changed] for p in paths], + column_names=["org", "namespace", "path", "created_at"], + ) + await get_client().connect() + repo = CodeRepo() + await repo.set_state(org, ns, "scip_commit", "a" * 40) # the tier ran after the change + assert await repo.scip_stale_paths(org, ns, paths) == set() + + await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=["src/bad.cpp"])) + await repo.set_state(org, ns, "scip_commit", "b" * 40) + assert await repo.scip_stale_paths(org, ns, paths) == {"src/bad.cpp"} + assert await repo.scip_stale_marks(org, ns) == {"src/bad.cpp"} + + await apply_delta( + repo, org, ns, ScipDelta(commit="c" * 40, files=[ScipFile(path="src/bad.cpp")]) + ) + assert await repo.scip_stale_paths(org, ns, paths) == set() + assert await repo.scip_stale_marks(org, ns) == set() diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 9c9fe62ec5a..f764ce3abf3 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -338,6 +338,7 @@ "code_scip_py_delta_timeout_seconds": 3600, "code_scip_py_heap_mb": 16384, "code_scip_python_path": "scip-python", + "code_scip_stop_on_failed_document": false, "code_scip_ts_delta_enabled": true, "code_scip_ts_delta_interval_seconds": 600, "code_scip_ts_delta_timeout_seconds": 3600, diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 8e9ecf07106..6dcfe0bed5a 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -356,7 +356,7 @@ def _convert(tmp_path: Path, *, changed=None, source: bool = True, full: bool = patch.object( scip_to_delta, "_ctor_overloads", - lambda records, pb: { + lambda data, pb, skips: { "DB::Widget": [ "(scip:49f6e7a06ebc5aa8)", "(scip:d4f767463ce0a6b3)", @@ -474,6 +474,9 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state.append((key, value, detail)) + async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + return set() + @pytest.mark.asyncio async def test_apply_carries_confidence_and_records_the_feature() -> None: diff --git a/tests/unit/test_code_ctor_edges_remainder.py b/tests/unit/test_code_ctor_edges_remainder.py index d97c0c44871..1a12471e029 100644 --- a/tests/unit/test_code_ctor_edges_remainder.py +++ b/tests/unit/test_code_ctor_edges_remainder.py @@ -501,7 +501,7 @@ def _convert(tmp_path: Path) -> dict: patch.object( scip_to_delta, "_ctor_overloads", - lambda records, pb: { + lambda data, pb, skips: { "DB::Widget": [ "(scip:49f6e7a06ebc5aa8)", "(scip:d4f767463ce0a6b3)", diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index b0a9e4e12c6..e8e75a7f883 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -172,6 +172,9 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def set_state(self, org: str, ns: str, key: str, value: str, **_: Any) -> None: self.state[key] = value + async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + return set() + @pytest.mark.asyncio async def test_the_apply_takes_the_file_a_round_at_a_time( diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py new file mode 100644 index 00000000000..6b3d906f17b --- /dev/null +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -0,0 +1,79 @@ +"""The server's side of a document the converter skipped: every tier's harness run logs +its warning once and carries the stop switch, and the apply marks the file stale until a +later delta applies or deletes it.""" + +from __future__ import annotations + +import logging +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest + +from server.code.app.index import compiler_tier, sandbox +from server.code.app.index.scip_delta import ScipDelta, ScipFile + +_WARNING = "scip_to_delta: warning: skipped document 'pkg/bad.py': DecodeError()" + + +def _job(envs: list[dict[str, str]], out: str): + async def run_job(argv: list[str], **kw: object) -> sandbox.JobResult: + envs.append(kw["env"]) # type: ignore[arg-type] + return sandbox.JobResult(0, out.encode(), b"") + + return run_job + + +async def _harness(tmp_path: Path) -> tuple[int, str]: + return await compiler_tier.run_harness( + Path("run_python_delta.sh"), tmp_path, [], {"A": "1"}, out_dir=tmp_path, timeout_s=5 + ) + + +@pytest.mark.asyncio +async def test_a_harness_run_logs_each_skipped_document_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """Every compiler tier (C++, its full run, Python, TypeScript, Go) runs its harness + through `run_harness`, so this is where the converter's warnings reach the log.""" + out = f"{_WARNING}\nother line\n{_WARNING}\ndelta: 3 files, ...\n" + monkeypatch.setattr(compiler_tier, "run_job", _job([], out)) + with caplog.at_level(logging.WARNING, logger=compiler_tier.logger.name): + assert await _harness(tmp_path) == (0, out) + assert [r.getMessage() for r in caplog.records] == [f"run_python_delta.sh: {_WARNING}"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stop", [False, True]) +async def test_a_harness_run_carries_the_stop_switch( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, stop: bool +) -> None: + envs: list[dict[str, str]] = [] + monkeypatch.setattr(compiler_tier, "run_job", _job(envs, "")) + monkeypatch.setattr(compiler_tier.settings, "code_scip_stop_on_failed_document", stop) + await _harness(tmp_path) + assert envs == [{"A": "1", "SCIP_STOP_ON_FAILED_DOCUMENT": "1" if stop else "0"}] + + +@pytest.mark.asyncio +async def test_a_delta_marks_a_skipped_file_and_clears_the_mark_of_one_it_applies_or_deletes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.code.app.index import scip_delta + + monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) + repo = AsyncMock() + repo.scip_stale_marks.return_value = {"src/a.cpp", "src/gone.cpp", "src/other.cpp"} + delta = ScipDelta( + commit="c" * 40, + files=[ScipFile(path="src/a.cpp")], + deleted_files=["src/gone.cpp"], + skipped_files=["src/bad.cpp"], + ) + stats = await scip_delta.apply_delta(repo, "o", "n", delta) + assert [c.args for c in repo.set_state.await_args_list] == [ + ("o", "n", "scip_stale:src/bad.cpp", "c" * 40), + ("o", "n", "scip_stale:src/a.cpp", ""), + ("o", "n", "scip_stale:src/gone.cpp", ""), + ] + assert stats.files_skipped_failed == 1 diff --git a/tests/unit/test_code_scip_ts_delta_worker.py b/tests/unit/test_code_scip_ts_delta_worker.py index fffab7f1894..a19aa07d697 100644 --- a/tests/unit/test_code_scip_ts_delta_worker.py +++ b/tests/unit/test_code_scip_ts_delta_worker.py @@ -260,3 +260,51 @@ async def test_dependency_failure_does_not_run_indexer_or_advance_watermark(monk harness.assert_not_awaited() # the only write is the failure's health record, never the watermark assert [c.args[2] for c in repo.set_state.await_args_list] == ["tier_health:typescript"] + + +@pytest.mark.asyncio +async def test_a_full_run_keeps_a_skipped_documents_rows_and_marks_the_file_stale( + monkeypatch, tmp_path: Path, checkout: Path +): + """The converter skipped web/bad.ts: the full run retires web/gone.ts, which the new + index no longer has, keeps web/bad.ts's rows and marks the file stale at the run's + commit; the watermark moves.""" + (checkout / "node_modules").mkdir(parents=True) + bare = tmp_path / "repo.git" + bare.mkdir() + monkeypatch.setattr(w.settings, "code_scip_checkout_dir", str(checkout)) + monkeypatch.setattr(w.settings, "code_git_dir", str(bare)) + + async def fake_git(cwd, *args, **kw): + return None + + async def fake_harness(co, base, head, delta_path, projects=(), **_): + delta_path.write_text( + json.dumps( + { + "delta_version": 1, + "commit": head, + "files": [{"path": "web/a.ts", "symbols": [], "edges": []}], + "skipped_files": ["web/bad.ts"], + } + ) + ) + + applied: list[tuple[str, bool]] = [] + + async def fake_apply_files(repo, org, ns, commit, files, stats): + applied.extend((f.path, f.deleted) for f in files) + + monkeypatch.setattr(w, "git", fake_git) + monkeypatch.setattr(w, "_run_harness", fake_harness) + monkeypatch.setattr("server.code.app.index.scip_delta._apply_files", fake_apply_files) + repo = _repo("b" * 40, "") + repo.live_scip_paths.return_value = {"web/a.ts", "web/bad.ts", "web/gone.ts"} + repo.scip_stale_marks.return_value = set() + p1, p2 = _patched(repo, [_Cfg()]) + with p1, p2: + res = await w.run_pass() + assert res.deltas_applied == 1 and not res.errors, res.errors + assert applied == [("web/a.ts", False), ("web/gone.ts", True)] + repo.set_state.assert_any_await("org", "code-ts", "scip_stale:web/bad.ts", "b" * 40) + repo.set_state.assert_awaited_with("org", "code-ts", "scip_commit_ts", "b" * 40) diff --git a/tests/unit/test_scip_apply_rounds.py b/tests/unit/test_scip_apply_rounds.py index 59f130003a2..8d9ef7604f6 100644 --- a/tests/unit/test_scip_apply_rounds.py +++ b/tests/unit/test_scip_apply_rounds.py @@ -98,6 +98,9 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state[key] = value + async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + return set() + def test_a_delta_is_applied_in_rounds_with_one_read_and_one_insert_per_table() -> None: repo = _RoundRepo() @@ -139,6 +142,9 @@ async def insert_rows(self, table, rows): async def set_state(self, *a: Any, **k: Any) -> None: return None + async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + return set() + def test_a_repository_without_round_reads_keeps_the_per_file_path() -> None: from unittest.mock import AsyncMock diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index 1fe8c68c2b0..0b6b5eaff8b 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -567,6 +567,9 @@ async def insert_rows(self, table, rows) -> None: async def set_state(self, org, ns, key, value, detail="") -> None: self.states.append(key) + async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + return set() + def _delta() -> Any: from server.code.app.index.scip_delta import ScipDelta diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py new file mode 100644 index 00000000000..bdd9f3b0670 --- /dev/null +++ b/tests/unit/test_scip_to_delta_skip.py @@ -0,0 +1,137 @@ +"""A document that fails to decode or convert is skipped, not fatal: it is named once on +stderr, listed in the delta's `skipped_files` and counted in its stats and summary line, +and the rest of the index converts. `--stop-on-failed-document` (the harness's +SCIP_STOP_ON_FAILED_DOCUMENT=1) fails the run on it instead. An index whose records +cannot be read to the end still fails (test_scip_to_delta_cli.py's +`test_a_failed_conversion_leaves_no_delta_file`).""" + +from __future__ import annotations + +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from tests.unit.test_scip_to_delta_cli import _CONVERTER, _add_doc, _fn, _pb + +_MARK = b"ZZBADUTF8ZZ" +_LIB = _CONVERTER.parent / "lib.sh" + + +def _index_with(tmp_path: Path, bad_symbol: str) -> Path: + """src/a.cpp and src/bad.cpp, each defining one function.""" + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///nonexistent-checkout" + _add_doc(index, "src/a.cpp", [(_fn("f", "aa"), 0)], []) + _add_doc(index, "src/bad.cpp", [(_fn(bad_symbol, "bb"), 0)], []) + out = tmp_path / "index.scip" + out.write_bytes(index.SerializeToString()) + return out + + +def _bad_utf8_index(tmp_path: Path) -> Path: + index = _index_with(tmp_path, _MARK.decode()) + raw = index.read_bytes() + assert raw.count(_MARK) == 1 + # same length, so every length prefix still holds; python-protobuf refuses the string + index.write_bytes(raw.replace(_MARK, b"\xff\xfe" + _MARK[2:])) + return index + + +def _run(index: Path, out: Path, *extra: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(_CONVERTER), "--index", str(index), "--commit", "h" * 40] + + ["--source-root", "", "--full", "--dry-run", str(out), *extra], + capture_output=True, + text=True, + check=False, + ) + + +def test_a_document_with_a_string_that_is_not_utf8_is_skipped_and_listed( + tmp_path: Path, +) -> None: + out = tmp_path / "delta.json" + proc = _run(_bad_utf8_index(tmp_path), out) + assert proc.returncode == 0, proc.stderr + delta = json.loads(out.read_text()) + assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] + assert delta["skipped_files"] == ["src/bad.cpp"] + assert delta["stats"]["skipped_failed"] == 1 + assert "1 failed documents skipped" in proc.stdout + # named once, though several passes over the index read it + assert proc.stderr.count("warning: skipped document 'src/bad.cpp'") == 1, proc.stderr + + +def test_the_switch_stops_the_run_on_a_failed_document(tmp_path: Path) -> None: + out = tmp_path / "delta.json" + proc = _run(_bad_utf8_index(tmp_path), out, "--stop-on-failed-document") + assert proc.returncode != 0 + assert "DecodeError" in proc.stderr + assert not out.exists() + + +@pytest.mark.parametrize(("stop", "fails"), [("1", True), ("0", False)]) +def test_the_harness_passes_the_switch_to_the_converter( + tmp_path: Path, stop: str, fails: bool +) -> None: + """Every tier converts through lib.sh's `convert_delta`, which reads the switch the + server sets (SCIP_STOP_ON_FAILED_DOCUMENT).""" + index, out = _bad_utf8_index(tmp_path), tmp_path / "delta.json" + env = { + "PATH": os.environ["PATH"], + "PYTHON": sys.executable, + "DELTA_OUT": str(out), + "SCIP_STOP_ON_FAILED_DOCUMENT": stop, + } + script = ( + f'source "{_LIB}"; convert_delta --index "{index}" --commit {"h" * 40} ' + '--source-root "" --full' + ) + proc = subprocess.run( + ["bash", "-c", script], capture_output=True, text=True, env=env, check=False + ) + assert (proc.returncode != 0) is fails, proc.stderr + assert out.exists() is not fails + + +def _converter(): + spec = importlib.util.spec_from_file_location("scip_to_delta_skip", _CONVERTER) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def test_a_document_that_fails_to_convert_is_skipped_and_listed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + conv = _converter() + real = conv._convert_document + + def convert_document(doc, run): + if doc.relative_path == "src/bad.cpp": + raise KeyError("boom") + return real(doc, run) + + monkeypatch.setattr(conv, "_convert_document", convert_document) + index = str(_index_with(tmp_path, "g")) + delta = conv.convert(index, None, [], "h" * 40, "", source_root="", full=True) + assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] + assert delta["skipped_files"] == ["src/bad.cpp"] + assert delta["stats"]["skipped_failed"] == 1 + assert "warning: skipped document 'src/bad.cpp': KeyError('boom')" in capsys.readouterr().err + # a Go module's paths are prefixed with its directory, the skipped one too + moduled = conv.convert(index, None, [], "h" * 40, "", source_root="", path_prefix="mod") + assert moduled["skipped_files"] == ["mod/src/bad.cpp"] + # each run keeps its own record: a second stream leaves the first one's as it was + first = conv.DeltaStream(index, None, [], "h" * 40, "", source_root="", full=True) + list(first.files) + conv.DeltaStream(index, None, [], "h" * 40, "", source_root="", full=True) + assert first.tail()["skipped_files"] == ["src/bad.cpp"] + assert first.tail()["stats"]["skipped_failed"] == 1 From 2d75e22d9a5e1dcd5a9ad15a472d10163127dfcc Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 01:08:11 +0000 Subject: [PATCH 02/81] Keep each tier's stale paths in one state row; the Go harness fails with the stop switch A tier's stale files are one `code_index_state` row, `scip_stale:`, rewritten in one insert by an apply that changes it, and left out of the whole-namespace state reads. A skipped path the entry's scope or denylist refuses is not marked. `run_module` in the Go harness sets `pipefail` and returns 1 on a failed conversion. `run_harness` logs the first five skipped documents and the count. A conversion failure carries the document's place in the index, and the server's warning prefix is pinned to the converter's. Signed-off-by: Kaloyan Naumov --- docs/reference/configuration.md | 2 +- docs/reference/status.md | 2 +- loom.example.yaml | 5 +- schemas/loom-settings.schema.json | 2 +- scripts/scip_harness/run_go_monorepo_delta.sh | 7 +- scripts/scip_harness/scip_to_delta.py | 18 +++-- server/code/app/index/compiler_tier.py | 12 ++-- server/code/app/index/scip_delta.py | 43 ++++++++---- server/code/domain/index/state.py | 8 +-- server/code/store/index/base.py | 18 +++-- server/code/store/index/symbols.py | 19 +++--- server/settings/catalog.py | 5 +- tests/analyzer/shapes.txt | 2 +- .../integration/test_code_scip_stale_mark.py | 8 ++- tests/unit/test_code_ctor_call_edges.py | 6 +- tests/unit/test_code_ctor_edges_remainder.py | 2 +- tests/unit/test_code_delta_stream.py | 4 +- .../unit/test_code_scip_skipped_documents.py | 68 +++++++++++++------ tests/unit/test_code_scip_ts_delta_worker.py | 10 +-- tests/unit/test_scip_apply_rounds.py | 8 +-- tests/unit/test_scip_entry_lock.py | 4 +- tests/unit/test_scip_harness_windows.py | 25 +++++++ tests/unit/test_scip_to_delta_skip.py | 6 ++ 23 files changed, 189 insertions(+), 95 deletions(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 6272a784ef4..783cf0b9ce8 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -457,7 +457,7 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through | `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` | `int` | `180` | live | Largest compiler-tier delta file the server reads, in MiB; a larger one fails the entry's pass. It bounds the work of an entry's pass and the path text kept (code-index-operations.md). | | `LOOM_CODE_SCIP_DELTA_MAX_NODES` | `int` | `6000000` | live | Most `{`, `[` and `,` bytes a compiler-tier delta may hold, counted before it is parsed; more fails the entry's pass (sizing: code-index-operations.md). | | `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES` | `int` | `3000000` | live | Most `{`, `[` and `,` bytes one apply round of a compiler-tier delta parses: its memory bound; one value over it fails the pass (code-index-operations.md). | -| `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT` | `bool` | `False` | | True fails the entry's compiler-tier pass on a document that fails to parse or convert (a string that is not UTF-8, say). False: the document is skipped and logged, and its file keeps its compiler rows, marked stale. | +| `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT` | `bool` | `False` | | True fails the compiler-tier pass on a document that fails to parse or convert; false skips and logs it, and its file's compiler rows stay, marked stale. | | `LOOM_CODE_SCIP_FULL_ENABLED` | `bool` | `True` | | C++ full re-index: seeds an entry the delta has no watermark for, and re-indexes each entry every `code_scip_full_every_hours` (heals deltas that hit the TU cap). One entry per pass, under its entry lock. | | `LOOM_CODE_SCIP_FULL_INTERVAL_SECONDS` | `int` | `900` | | Seconds between the C++ full re-index's checks for an entry that is due. | | `LOOM_CODE_SCIP_FULL_EVERY_HOURS` | `int` | `168` | | Hours between full re-indexes of one entry. | diff --git a/docs/reference/status.md b/docs/reference/status.md index 5d528bb68f3..8a2f7d7a527 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -108,7 +108,7 @@ default is `off`) are not listed here. | `LOOM_CODE_REPO_PUBLIC` | The scalar repo entry is public: its namespace registers join_policy=open and discoverable. | | `LOOM_CODE_SANDBOX_REQUIRED` | Set by deployments that ship the sandbox profiles: a repository job refuses to run rather than run unsandboxed, and /v1/health reports the missing sandbox as an error. | | `LOOM_CODE_SCIP_APPLY_ENABLED` | SCIP delta apply (compiler-grade tier uploaded via code.scip_ingest). | -| `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT` | True fails the entry's compiler-tier pass on a document that fails to parse or convert (a string that is not UTF-8, say). | +| `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT` | True fails the compiler-tier pass on a document that fails to parse or convert; false skips and logs it, and its file's compiler rows stay, marked stale. | | `LOOM_CODE_SEARCH_CARD_LEG` | The card leg: file cards are searched by cosine and the top files' chunks join fusion as a capped RRF list (the history leg's shape). | | `LOOM_CODE_SELF_SERVICE_GIT_UNSANDBOXED` | True lets a host without the sandbox add and fetch a self-service entry with a network remote: its git jobs (ls-remote, clone, fetch) run as plain processes and it gets no compiler tier. | | `LOOM_CODE_SELF_SERVICE_PLATFORM_ADMIN_ONLY` | True leaves code.repo.remote_branches, code.repo.add and code.repo.add_branch to platform admins: a token scoped to namespaces, or a trusted caller acting for another subject, is refused too. | diff --git a/loom.example.yaml b/loom.example.yaml index 1243e495062..c4157bf10cc 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -1505,9 +1505,8 @@ settings: # memory bound; one value over it fails the pass (code-index-operations.md). [live] # code_scip_delta_round_max_nodes: 3000000 - # True fails the entry's compiler-tier pass on a document that fails to parse or - # convert (a string that is not UTF-8, say). False: the document is skipped and - # logged, and its file keeps its compiler rows, marked stale. [restart] + # True fails the compiler-tier pass on a document that fails to parse or convert; + # false skips and logs it, and its file's compiler rows stay, marked stale. [restart] # code_scip_stop_on_failed_document: false # C++ full re-index: seeds an entry the delta has no watermark for, and re-indexes diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index affe247766d..402aa6c988e 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -1916,7 +1916,7 @@ "code_scip_stop_on_failed_document": { "default": false, "type": "boolean", - "description": "True fails the entry's compiler-tier pass on a document that fails to parse or convert (a string that is not UTF-8, say). False: the document is skipped and logged, and its file keeps its compiler rows, marked stale." + "description": "True fails the compiler-tier pass on a document that fails to parse or convert; false skips and logs it, and its file's compiler rows stay, marked stale." }, "code_scip_ts_delta_enabled": { "default": true, diff --git a/scripts/scip_harness/run_go_monorepo_delta.sh b/scripts/scip_harness/run_go_monorepo_delta.sh index fb600efbbb3..93505426186 100755 --- a/scripts/scip_harness/run_go_monorepo_delta.sh +++ b/scripts/scip_harness/run_go_monorepo_delta.sh @@ -62,6 +62,8 @@ else fi run_module() { + # an xargs child: without these a failed conversion would pass as `tail`'s exit + set -o pipefail local dir=$1 work work=$(mktemp -d) trap 'rm -rf "$work"' RETURN @@ -102,11 +104,10 @@ run_module() { echo "skip $dir: scip-go failed: $(tail -1 "$work/scip-go.log")" >&2 return 0 fi - # the converter's summary line and its last line (where the delta went) if [[ -n "${DELTA_OUT_DIR:-}" ]]; then - DELTA_OUT="$DELTA_OUT_DIR/${prefix//\//__}.json" convert_delta "${args[@]}" | sed -n '/^delta: /p;$p' + DELTA_OUT="$DELTA_OUT_DIR/${prefix//\//__}.json" convert_delta "${args[@]}" | tail -1 || return 1 else - convert_delta "${args[@]}" | sed -n '/^delta: /p;$p' + convert_delta "${args[@]}" | tail -1 || return 1 fi echo "done $dir" } diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index e25b200209c..0b28715b1ef 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -856,7 +856,7 @@ def __init__(self, stop: bool = False) -> None: self.labels: set[str] = set() self.paths: set[str] = set() - def add(self, path: str, err: Exception, index: int = -1) -> None: + def add(self, path: str, err: Exception, index: int) -> None: if self.stop: raise err # a document whose path cannot be read is told apart by its place in the index @@ -876,7 +876,13 @@ def add(self, path: str, err: Exception, index: int = -1) -> None: def _stream_documents( data, scip_pb2, *, skips: _Skips, paths: set[str] | None = None, ordered: bool = False ): - """Yield scip.Document messages by streaming the Index's top-level + """`_indexed_documents` without each document's place in the index.""" + for _i, doc in _indexed_documents(data, scip_pb2, skips, paths, ordered): + yield doc + + +def _indexed_documents(data, scip_pb2, skips: _Skips, paths: set[str] | None, ordered: bool): + """Yield (place in the index, scip.Document) by streaming the Index's top-level records (field 2 = documents) instead of parsing one giant message — a full ClickHouse index is ~1GB, which trips python-protobuf's whole-message limits ("Wire format was corrupt"). `paths` parses only @@ -900,7 +906,7 @@ def _stream_documents( except Exception as e: # noqa: BLE001 — any failure of one document skips it skips.add(_document_path(payload), e, i) continue - yield doc + yield i, doc _TS_TYPE_KINDS = frozenset({"class", "interface", "type", "enum"}) @@ -1286,15 +1292,13 @@ def __init__( self.files = self._files(data, scip_pb2, changed) def _files(self, data, scip_pb2, changed: set[str] | None): - for doc in _stream_documents( - data, scip_pb2, skips=self._skips, paths=changed, ordered=True - ): + for i, doc in _indexed_documents(data, scip_pb2, self._skips, changed, True): if changed is not None and doc.relative_path not in changed: continue try: entry = _convert_document(doc, self._run) except Exception as e: # noqa: BLE001 — any failure of one document skips it - self._skips.add(doc.relative_path, e) + self._skips.add(doc.relative_path, e, i) continue if entry is None: continue diff --git a/server/code/app/index/compiler_tier.py b/server/code/app/index/compiler_tier.py index ff5dfd73fdd..5b440fb5a61 100644 --- a/server/code/app/index/compiler_tier.py +++ b/server/code/app/index/compiler_tier.py @@ -42,8 +42,9 @@ logger = logging.getLogger("loom.code_index.compiler_tier") # The line the converter (scripts/scip_harness/scip_to_delta.py) writes for each -# document it skipped. +# document it skipped; a harness run logs the first few of them and the count. SKIPPED_WARNING = "scip_to_delta: warning: skipped document" +_SKIPPED_LOGGED = 5 # The exit code every tier harness gives when the window's base commit is # not in the checkout (history rewritten, a squashed or force-pushed branch): @@ -704,8 +705,8 @@ async def run_harness( are writable; the checkout's .git stays read-only (a hook or config planted there would run outside the sandbox later), as do the harness scripts. RuntimeError naming the timeout past `timeout_s`. The converter skips a document - that fails, or stops on it with `code_scip_stop_on_failed_document`; each skipped - document's warning line is logged here, once.""" + that fails, or stops on it with `code_scip_stop_on_failed_document`; the first + skipped documents' warning lines are logged here, and how many there were.""" from server.core.paths import SCIP_HARNESS_DIR stop = "1" if settings.code_scip_stop_on_failed_document else "0" @@ -722,6 +723,9 @@ async def run_harness( except TimeoutError: raise tier_health.ToolOutputError(f"harness timed out after {timeout_s}s") from None out = done.stdout.decode("utf-8", "replace") - for line in dict.fromkeys(ln for ln in out.splitlines() if ln.startswith(SKIPPED_WARNING)): + skipped = list(dict.fromkeys(ln for ln in out.splitlines() if ln.startswith(SKIPPED_WARNING))) + for line in skipped[:_SKIPPED_LOGGED]: logger.warning("%s: %s", harness.name, line) + if len(skipped) > _SKIPPED_LOGGED: + logger.warning("%s: %d documents skipped in all", harness.name, len(skipped)) return done.returncode, out diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 1c6cc99cc8e..4f4db4cc4ac 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -9,7 +9,7 @@ Apply semantics per touched file: upsert every symbol/edge the delta emits for it, tombstone scip rows in that file the delta no longer emits; files in `deleted_files` tombstone entirely. A file in `skipped_files` (its -document failed to convert) keeps its rows and is marked stale. Idempotent — +document failed to convert) keeps its rows and joins its tier's stale row. Idempotent — re-applying the same delta converges to the same live set. """ @@ -25,6 +25,7 @@ from server.code.app.index.entry_lock import check_held from server.code.domain.extract.treesitter import symbol_id +from server.code.domain.index.compiler_tiers import SUFFIXES, owns_path from server.code.domain.index.state import SCIP_STALE_PREFIX from server.code.store.index import CodeRepo, build_row from server.workers import pass_context @@ -119,7 +120,6 @@ class ScipApplyStats(BaseModel): edges_dropped_declarations: int = 0 files_skipped_out_of_scope: int = 0 files_skipped_excluded: int = 0 # the entry's path denylist - files_skipped_failed: int = 0 # the converter skipped them; their rows are marked stale def _path_refusal(org: str, ns: str) -> Any: @@ -238,11 +238,14 @@ async def apply_delta(repo: CodeRepo, org: str, ns: str, delta: _Delta) -> ScipA prefixes = _indexable_prefixes(org, ns) refused = _path_refusal(org, ns) + def out_of_scope(path: str) -> bool: + return bool(prefixes) and not any(path.startswith(p) for p in prefixes) + def keep(path: str) -> bool: # Server-side scope enforcement: a full scip index sweeps the whole compile # graph (contrib/, build/, system headers). Only the repo's configured # prefixes belong in the index. - if prefixes and not any(path.startswith(p) for p in prefixes): + if out_of_scope(path): stats.files_skipped_out_of_scope += 1 return False # The entry's path denylist (exclude globs, the built-in rules) binds the @@ -272,8 +275,9 @@ def keep(path: str) -> bool: # its thread keeps it until that read returns and the rounds are collected if not reading: rounds.close() - await _mark_stale(repo, org, ns, delta, refreshed) - stats.files_skipped_failed = len(delta.skipped_files) + # a skipped file the entry would not keep is never marked: nothing would clear it + skipped = {p for p in delta.skipped_files if not out_of_scope(p) and not refused(p)} + await _mark_stale(repo, org, ns, skipped, refreshed) if FEATURE_CTOR_CALLS in delta.features: check_held() await repo.set_state( @@ -287,19 +291,28 @@ def keep(path: str) -> bool: return stats -async def _mark_stale(repo: Any, org: str, ns: str, delta: _Delta, refreshed: set[str]) -> None: - """Mark each skipped file stale at the delta's commit, and drop the mark of a file - this delta applied or deleted (`SCIP_STALE_PREFIX`).""" - skipped = set(delta.skipped_files) +def _stale_key(path: str) -> str: + """The stale row of the tier whose documents `path` is one of.""" + return SCIP_STALE_PREFIX + next((t for t in SUFFIXES if owns_path(t, path)), "") + + +async def _mark_stale(repo: Any, org: str, ns: str, skipped: set[str], refreshed: set[str]) -> None: + """Rewrite each tier's stale row (`SCIP_STALE_PREFIX`) this delta changes: the files + it held, plus the ones skipped, minus the ones applied or deleted. One read, and at + most one insert.""" refreshed -= skipped if not skipped and not refreshed: return - check_held() - for path in sorted(skipped): - await repo.set_state(org, ns, SCIP_STALE_PREFIX + path, delta.commit) - if refreshed: - for path in sorted(await repo.scip_stale_marks(org, ns) & refreshed): - await repo.set_state(org, ns, SCIP_STALE_PREFIX + path, "") + marks = await repo.scip_stale_marks(org, ns) + rows: dict[str, str] = {} + for key in set(marks) | {_stale_key(p) for p in skipped}: + before = marks.get(key, set()) + after = (before - refreshed) | {p for p in skipped if _stale_key(p) == key} + if after != before: + rows[key] = json.dumps(sorted(after)) + if rows: + check_held() + await repo.set_states(org, ns, rows) async def _apply_files( diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index 0386e1b6b76..580513e5ff7 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -24,10 +24,10 @@ class StateEntry(TypedDict, total=False): # The state key of an entry's bootstrap stage, whose detail is JSON. STAGE_KEY = "bootstrap_stage" -# A compiler-tier file whose last delta skipped its document (it failed to parse or -# convert) keeps the rows of an earlier state: `SCIP_STALE_PREFIX + path` holds the -# commit of that delta until a later delta applies or deletes the file, and -# `scip_stale_paths` reads the file as stale meanwhile. +# The files of a compiler tier whose last delta skipped their document (it failed to +# parse or convert) keep the rows of an earlier state: `SCIP_STALE_PREFIX + tier` holds +# them as a JSON list, rewritten by each apply, and `scip_stale_paths` reads them as +# stale. The whole-namespace state reads leave these rows out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's # `{"reason": ...}` detail; `code.repos` and `code.index_status` show only these, and diff --git a/server/code/store/index/base.py b/server/code/store/index/base.py index 5f538bb4632..7c0d848d544 100644 --- a/server/code/store/index/base.py +++ b/server/code/store/index/base.py @@ -7,7 +7,7 @@ from typing import Any -from server.code.domain.index.state import IndexState, StateEntry +from server.code.domain.index.state import SCIP_STALE_PREFIX, IndexState, StateEntry from server.code.store.index.rows import ( _TABLE_COLS, VERSION_INVARIANT_COLS, @@ -111,9 +111,10 @@ async def all_state(self, org: str, ns: str) -> IndexState: SELECT state_key, state_value, detail, updated_at FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} + AND NOT startsWith(state_key, {stale:String}) ORDER BY state_key """, - {"org": org, "ns": ns}, + {"org": org, "ns": ns, "stale": SCIP_STALE_PREFIX}, ) return { str(r["state_key"]): StateEntry( @@ -135,9 +136,10 @@ async def all_state_many( SELECT org, namespace, state_key, state_value, detail, updated_at FROM loom.code_index_state FINAL WHERE (org, namespace) IN {pairs:Array(Tuple(String, String))} + AND NOT startsWith(state_key, {stale:String}) ORDER BY org, namespace, state_key """, - {"pairs": [(str(o), str(n)) for o, n in pairs]}, + {"pairs": [(str(o), str(n)) for o, n in pairs], "stale": SCIP_STALE_PREFIX}, ) out: dict[tuple[str, str], IndexState] = {(str(o), str(n)): {} for o, n in pairs} for r in rows: @@ -147,6 +149,11 @@ async def all_state_many( return out async def set_state(self, org: str, ns: str, key: str, value: str, detail: str = "") -> None: + await self.set_states(org, ns, {key: value}, detail) + + async def set_states(self, org: str, ns: str, values: dict[str, str], detail: str = "") -> None: + """Several state rows of one namespace in one insert.""" + now, version = _now(), version_now() await self._ch.insert( "loom.code_index_state", [ @@ -156,9 +163,10 @@ async def set_state(self, org: str, ns: str, key: str, value: str, detail: str = "state_key": key, "state_value": value, "detail": detail, - "updated_at": _now(), - "version": version_now(), + "updated_at": now, + "version": version, } + for key, value in values.items() ], ) diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 626fd8db95d..90622e5fa6b 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -5,6 +5,7 @@ from __future__ import annotations +import json from typing import Any from clickhouse_connect.driver.binding import format_bind_value @@ -540,7 +541,7 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str wrote the file's row after the compiler tier last ran (the `.py` watermark, `scip_commit_py`, for a Python file when there is one, `scip_commit` otherwise), deleted the file, or holds no row for it, or the compiler tier's - last delta for it skipped its document (`SCIP_STALE_PREFIX`). The fast tier + last delta for it skipped its document (its tier's `SCIP_STALE_PREFIX` row). The fast tier writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left @@ -563,10 +564,10 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str AND path IN {paths:Array(String)} AND tombstoned_at IS NULL AND created_at <= if(endsWith(path, '.py') AND t_py > toDateTime(0), t_py, t_scip) AND path NOT IN ( - SELECT substring(state_key, length({mark:String}) + 1) + SELECT arrayJoin(JSONExtract(state_value, 'Array(String)')) FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} - AND startsWith(state_key, {mark:String}) AND state_value != '' + AND startsWith(state_key, {mark:String}) ) """, {"org": org, "ns": ns, "paths": asked, "mark": SCIP_STALE_PREFIX}, @@ -574,19 +575,19 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str # the query names the FRESH paths; every other asked path is stale return set(asked) - {str(r["path"]) for r in rows} - async def scip_stale_marks(self, org: str, ns: str) -> set[str]: - """The paths marked stale because a compiler-tier delta skipped their document - (`SCIP_STALE_PREFIX`); a cleared mark holds an empty value.""" + async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: + """Each tier's stale row (`SCIP_STALE_PREFIX` + tier): the paths whose document + that tier's last delta for them skipped.""" rows = await self._ch.query_all( """ - SELECT substring(state_key, length({mark:String}) + 1) AS path + SELECT state_key, state_value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} - AND startsWith(state_key, {mark:String}) AND state_value != '' + AND startsWith(state_key, {mark:String}) """, {"org": org, "ns": ns, "mark": SCIP_STALE_PREFIX}, ) - return {str(r["path"]) for r in rows} + return {str(r["state_key"]): set(json.loads(r["state_value"] or "[]")) for r in rows} async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 233539f9e2f..728d720b2df 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1300,9 +1300,8 @@ def _check_git_proxy(self) -> CodeSettings: # Most `{`, `[` and `,` bytes one apply round of a compiler-tier delta parses: its # memory bound; one value over it fails the pass (code-index-operations.md). code_scip_delta_round_max_nodes: Annotated[int, LIVE] = Field(default=3_000_000, ge=1) - # True fails the entry's compiler-tier pass on a document that fails to parse or - # convert (a string that is not UTF-8, say). False: the document is skipped and - # logged, and its file keeps its compiler rows, marked stale. + # True fails the compiler-tier pass on a document that fails to parse or convert; + # false skips and logs it, and its file's compiler rows stay, marked stale. code_scip_stop_on_failed_document: bool = False # C++ full re-index: seeds an entry the delta has no watermark for, and # re-indexes each entry every `code_scip_full_every_hours` (heals deltas diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 7db49c7ddaf..5d0bc1e7f12 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -1773,6 +1773,7 @@ c6cde2e02fad ALTER TABLE loom.conversations DELETE WHERE (org = {org:String} AND c6d2cd622bdf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g c6e9dc907dc7 SELECT value FROM loom.oauth_signin_state WHERE claim_key = {k:String} c6fedc654be3 SELECT count() AS n FROM loom.code_context_packs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND pr_number = {pr:UInt32} +c7139b45f19a SELECT state_key, state_value, detail, updated_at FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND NOT startsWith(state_key, {stale:String}) ORDER BY state_key c71b88136b17 SELECT count() AS n FROM loom.learnings_supporters WHERE org = {org:String} AND user_id = {uid:String} AND ? c72e7e6dceb9 SELECT count() AS n FROM loom.working_memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} c77ef954081d SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to @@ -1968,7 +1969,6 @@ da1d5a654f1e SELECT count() AS n FROM loom.knowledge_uploads WHERE org = {org:St da366d9eb046 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist daa35ab01384 SELECT count() AS n, countIf(embedding_dim > ?) AS embedded, countIf(NOT startsWith(embed_last_error, {unembedded:String})) AS embeddable FROM loom.code_chunks FINAL WHERE org = {org:String} AND names daa9953aad14 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user -dabe37717488 SELECT state_key, state_value, detail, updated_at FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} ORDER BY state_key dae0d2378112 SELECT count() AS n FROM loom.memory_code_links FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL dae4a1968b69 ALTER TABLE loom.context_blobs UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutat db13fde1fa1b SELECT count() AS n FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index ac7811863f3..c95bc565631 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -1,5 +1,6 @@ """A file whose compiler-tier document a delta skipped reads as stale, although the -tier's watermark moved past the file's last change, until a later delta applies it.""" +tier's watermark moved past the file's last change, until a later delta applies it. The +tier's stale row stays out of the namespace's state reads.""" from __future__ import annotations @@ -32,10 +33,11 @@ async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: A await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=["src/bad.cpp"])) await repo.set_state(org, ns, "scip_commit", "b" * 40) assert await repo.scip_stale_paths(org, ns, paths) == {"src/bad.cpp"} - assert await repo.scip_stale_marks(org, ns) == {"src/bad.cpp"} + assert await repo.scip_stale_marks(org, ns) == {"scip_stale:clang": {"src/bad.cpp"}} + assert "scip_stale:clang" not in await repo.all_state(org, ns) await apply_delta( repo, org, ns, ScipDelta(commit="c" * 40, files=[ScipFile(path="src/bad.cpp")]) ) assert await repo.scip_stale_paths(org, ns, paths) == set() - assert await repo.scip_stale_marks(org, ns) == set() + assert await repo.scip_stale_marks(org, ns) == {"scip_stale:clang": set()} diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 6dcfe0bed5a..56a5189f926 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -351,7 +351,7 @@ def _convert(tmp_path: Path, *, changed=None, source: bool = True, full: bool = docs = _docs() with ( patch.object(scip_to_delta, "_ensure_scip_pb2", return_value=_PB), - patch.object(scip_to_delta, "_stream_documents", lambda data, pb, **_: iter(docs)), + patch.object(scip_to_delta, "_indexed_documents", lambda *a: enumerate(docs)), patch.object(scip_to_delta, "_top_level_records", lambda data: iter([])), patch.object( scip_to_delta, @@ -474,8 +474,8 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state.append((key, value, detail)) - async def scip_stale_marks(self, org: str, ns: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: + return {} @pytest.mark.asyncio diff --git a/tests/unit/test_code_ctor_edges_remainder.py b/tests/unit/test_code_ctor_edges_remainder.py index 1a12471e029..38c9a977dd7 100644 --- a/tests/unit/test_code_ctor_edges_remainder.py +++ b/tests/unit/test_code_ctor_edges_remainder.py @@ -496,7 +496,7 @@ def _convert(tmp_path: Path) -> dict: docs = _docs() with ( patch.object(scip_to_delta, "_ensure_scip_pb2", return_value=_PB), - patch.object(scip_to_delta, "_stream_documents", lambda data, pb, **_: iter(docs)), + patch.object(scip_to_delta, "_indexed_documents", lambda *a: enumerate(docs)), patch.object(scip_to_delta, "_top_level_records", lambda data: iter([])), patch.object( scip_to_delta, diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index e8e75a7f883..00daeec038f 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -172,8 +172,8 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def set_state(self, org: str, ns: str, key: str, value: str, **_: Any) -> None: self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: + return {} @pytest.mark.asyncio diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index 6b3d906f17b..be18606d15f 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -1,19 +1,22 @@ """The server's side of a document the converter skipped: every tier's harness run logs -its warning once and carries the stop switch, and the apply marks the file stale until a -later delta applies or deletes it.""" +the first warnings and the count and carries the stop switch, and the apply keeps each +tier's stale row: the files it skipped, until a later delta applies or deletes them.""" from __future__ import annotations +import json import logging from pathlib import Path from unittest.mock import AsyncMock import pytest -from server.code.app.index import compiler_tier, sandbox +from server.code.app.index import compiler_tier, sandbox, scip_delta from server.code.app.index.scip_delta import ScipDelta, ScipFile -_WARNING = "scip_to_delta: warning: skipped document 'pkg/bad.py': DecodeError()" + +def _warning(path: str) -> str: + return f"scip_to_delta: warning: skipped document {path!r}: DecodeError()" def _job(envs: list[dict[str, str]], out: str): @@ -31,16 +34,20 @@ async def _harness(tmp_path: Path) -> tuple[int, str]: @pytest.mark.asyncio -async def test_a_harness_run_logs_each_skipped_document_once( +async def test_a_harness_run_logs_the_first_skipped_documents_and_the_count( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: """Every compiler tier (C++, its full run, Python, TypeScript, Go) runs its harness through `run_harness`, so this is where the converter's warnings reach the log.""" - out = f"{_WARNING}\nother line\n{_WARNING}\ndelta: 3 files, ...\n" + lines = [_warning(f"pkg/bad{i}.py") for i in range(7)] + out = "\n".join([lines[0], "other line", *lines, "delta: 3 files, ..."]) + "\n" monkeypatch.setattr(compiler_tier, "run_job", _job([], out)) with caplog.at_level(logging.WARNING, logger=compiler_tier.logger.name): assert await _harness(tmp_path) == (0, out) - assert [r.getMessage() for r in caplog.records] == [f"run_python_delta.sh: {_WARNING}"] + assert [r.getMessage() for r in caplog.records] == [ + *(f"run_python_delta.sh: {line}" for line in lines[:5]), + "run_python_delta.sh: 7 documents skipped in all", + ] @pytest.mark.asyncio @@ -56,24 +63,47 @@ async def test_a_harness_run_carries_the_stop_switch( @pytest.mark.asyncio -async def test_a_delta_marks_a_skipped_file_and_clears_the_mark_of_one_it_applies_or_deletes( +async def test_one_apply_rewrites_each_tiers_stale_row_in_one_insert( monkeypatch: pytest.MonkeyPatch, ) -> None: - from server.code.app.index import scip_delta - + """The row keeps what it held, gains the skipped files the entry keeps, and drops + the files this delta applies or deletes. An out-of-scope or refused path is never + marked: no delta would clear it.""" monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) + monkeypatch.setattr(scip_delta, "_indexable_prefixes", lambda *a: ("src/",)) + monkeypatch.setattr( + scip_delta, "_path_refusal", lambda *a: lambda p: "denied" if p.endswith(".env.ts") else "" + ) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"src/a.cpp", "src/gone.cpp", "src/other.cpp"} + repo.scip_stale_marks.return_value = { + "scip_stale:clang": {"src/a.cpp", "src/gone.cpp", "src/other.cpp"}, + "scip_stale:python": {"src/kept.py"}, + } delta = ScipDelta( commit="c" * 40, files=[ScipFile(path="src/a.cpp")], deleted_files=["src/gone.cpp"], - skipped_files=["src/bad.cpp"], + skipped_files=["src/bad.cpp", "src/web.ts", "contrib/x.cpp", "src/conf.env.ts"], ) - stats = await scip_delta.apply_delta(repo, "o", "n", delta) - assert [c.args for c in repo.set_state.await_args_list] == [ - ("o", "n", "scip_stale:src/bad.cpp", "c" * 40), - ("o", "n", "scip_stale:src/a.cpp", ""), - ("o", "n", "scip_stale:src/gone.cpp", ""), - ] - assert stats.files_skipped_failed == 1 + await scip_delta.apply_delta(repo, "o", "n", delta) + repo.set_state.assert_not_awaited() + repo.set_states.assert_awaited_once() + org, ns, rows = repo.set_states.await_args.args + assert (org, ns) == ("o", "n") + assert {k: json.loads(v) for k, v in rows.items()} == { + "scip_stale:clang": ["src/bad.cpp", "src/other.cpp"], + "scip_stale:typescript": ["src/web.ts"], + } + + +@pytest.mark.asyncio +async def test_an_apply_that_changes_no_stale_row_writes_none( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) + repo = AsyncMock() + repo.scip_stale_marks.return_value = {"scip_stale:clang": {"src/other.cpp"}} + await scip_delta.apply_delta( + repo, "o", "n", ScipDelta(commit="c" * 40, files=[ScipFile(path="src/a.cpp")]) + ) + repo.set_states.assert_not_awaited() diff --git a/tests/unit/test_code_scip_ts_delta_worker.py b/tests/unit/test_code_scip_ts_delta_worker.py index a19aa07d697..945c4a0be40 100644 --- a/tests/unit/test_code_scip_ts_delta_worker.py +++ b/tests/unit/test_code_scip_ts_delta_worker.py @@ -267,8 +267,8 @@ async def test_a_full_run_keeps_a_skipped_documents_rows_and_marks_the_file_stal monkeypatch, tmp_path: Path, checkout: Path ): """The converter skipped web/bad.ts: the full run retires web/gone.ts, which the new - index no longer has, keeps web/bad.ts's rows and marks the file stale at the run's - commit; the watermark moves.""" + index no longer has, keeps web/bad.ts's rows and puts the file in the TypeScript + tier's stale row; the watermark moves.""" (checkout / "node_modules").mkdir(parents=True) bare = tmp_path / "repo.git" bare.mkdir() @@ -300,11 +300,13 @@ async def fake_apply_files(repo, org, ns, commit, files, stats): monkeypatch.setattr("server.code.app.index.scip_delta._apply_files", fake_apply_files) repo = _repo("b" * 40, "") repo.live_scip_paths.return_value = {"web/a.ts", "web/bad.ts", "web/gone.ts"} - repo.scip_stale_marks.return_value = set() + repo.scip_stale_marks.return_value = {} p1, p2 = _patched(repo, [_Cfg()]) with p1, p2: res = await w.run_pass() assert res.deltas_applied == 1 and not res.errors, res.errors assert applied == [("web/a.ts", False), ("web/gone.ts", True)] - repo.set_state.assert_any_await("org", "code-ts", "scip_stale:web/bad.ts", "b" * 40) + repo.set_states.assert_awaited_once_with( + "org", "code-ts", {"scip_stale:typescript": '["web/bad.ts"]'} + ) repo.set_state.assert_awaited_with("org", "code-ts", "scip_commit_ts", "b" * 40) diff --git a/tests/unit/test_scip_apply_rounds.py b/tests/unit/test_scip_apply_rounds.py index 8d9ef7604f6..21773bf254a 100644 --- a/tests/unit/test_scip_apply_rounds.py +++ b/tests/unit/test_scip_apply_rounds.py @@ -98,8 +98,8 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: + return {} def test_a_delta_is_applied_in_rounds_with_one_read_and_one_insert_per_table() -> None: @@ -142,8 +142,8 @@ async def insert_rows(self, table, rows): async def set_state(self, *a: Any, **k: Any) -> None: return None - async def scip_stale_marks(self, org: str, ns: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: + return {} def test_a_repository_without_round_reads_keeps_the_per_file_path() -> None: diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index 0b6b5eaff8b..52f1cf7fd5e 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -567,8 +567,8 @@ async def insert_rows(self, table, rows) -> None: async def set_state(self, org, ns, key, value, detail="") -> None: self.states.append(key) - async def scip_stale_marks(self, org: str, ns: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: + return {} def _delta() -> Any: diff --git a/tests/unit/test_scip_harness_windows.py b/tests/unit/test_scip_harness_windows.py index c0a9b9fe652..d7df9bc72a7 100644 --- a/tests/unit/test_scip_harness_windows.py +++ b/tests/unit/test_scip_harness_windows.py @@ -137,6 +137,31 @@ def test_a_modified_file_is_read_from_the_index(tmp_path: Path, tier: str) -> No assert delta["deleted_files"] == [] and delta["base"] == w.base +@pytest.mark.parametrize("tier", sorted(_TIERS)) +def test_with_the_stop_switch_a_failed_document_fails_the_run(tmp_path: Path, tier: str) -> None: + """SCIP_STOP_ON_FAILED_DOCUMENT=1 (`code_scip_stop_on_failed_document`): a document + that does not parse fails the run and writes no delta, so the worker keeps its + watermark. The Go harness converts each module in an `xargs` job, which passes the + failure on.""" + w = _Window(tmp_path, tier) + (w.repo / w.path("a")).write_text("x_a = 2\n") + head = _commit(w.repo, "edit a") + _write_index(w.index, [w.path("a")]) + raw = w.index.read_bytes() + # same length, so every length prefix holds; python-protobuf refuses the path + w.index.write_bytes(raw.replace(b"src/a.", b"src/\xff.")) + proc = subprocess.run( + ["bash", str(w.script), str(w.repo), w.base, head], + env={**w.env, "SCIP_STOP_ON_FAILED_DOCUMENT": "1"}, + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode != 0, proc.stdout + proc.stderr + assert "DecodeError" in proc.stderr + assert not w.delta.exists() + + @pytest.mark.parametrize("tier", sorted(_TIERS)) def test_a_rename_tombstones_the_old_path(tmp_path: Path, tier: str) -> None: w = _Window(tmp_path, tier) diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index bdd9f3b0670..11dc36d58a3 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -108,6 +108,12 @@ def _converter(): return mod +def test_the_server_logs_the_converters_warning_line() -> None: + from server.code.app.index.compiler_tier import SKIPPED_WARNING + + assert _converter().SKIPPED_WARNING == SKIPPED_WARNING + + def test_a_document_that_fails_to_convert_is_skipped_and_listed( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: From 12decef42b08192e52203d15c4e01501b2ea265f Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 01:30:23 +0000 Subject: [PATCH 03/81] Mark a skipped file stale in its own row under the tier that applied the delta `apply_delta` takes the delta's tier from every caller (an upload's is the tier whose watermark its producer moves) and writes `scip_stale::` rows: each skipped file marked at the delta's commit, and each of that tier's marked files the delta applied or deleted emptied, in one insert. A tier reads and writes only its own marks, so tiers applying side by side keep each other's. `scip_stale_paths` reads the marks by prefix; the whole-namespace state reads leave them out. Signed-off-by: Kaloyan Naumov --- server/cli/code_scip.py | 2 +- server/code/app/index/scip_delta.py | 46 ++++---- server/code/app/index/scip_full.py | 2 +- server/code/domain/index/state.py | 9 +- server/code/store/index/symbols.py | 23 ++-- server/code/workers/scip_apply.py | 13 ++- server/code/workers/scip_delta.py | 2 +- server/code/workers/scip_go_delta.py | 2 +- server/code/workers/scip_py_delta.py | 2 +- server/code/workers/scip_ts_delta.py | 2 +- .../integration/test_code_scip_stale_mark.py | 20 ++-- tests/unit/test_code_ctor_call_edges.py | 3 - tests/unit/test_code_delta_stream.py | 3 - tests/unit/test_code_scip_go_delta_worker.py | 4 +- tests/unit/test_code_scip_py_delta_worker.py | 6 +- .../unit/test_code_scip_skipped_documents.py | 102 +++++++++++++----- tests/unit/test_code_scip_ts_delta_worker.py | 10 +- tests/unit/test_scip_apply_any_namespace.py | 4 +- tests/unit/test_scip_apply_rounds.py | 6 -- tests/unit/test_scip_entry_lock.py | 3 - 20 files changed, 161 insertions(+), 103 deletions(-) diff --git a/server/cli/code_scip.py b/server/cli/code_scip.py index f07ecedd236..464d93a06d7 100644 --- a/server/cli/code_scip.py +++ b/server/cli/code_scip.py @@ -44,7 +44,7 @@ async def _scip_apply_only( file=sys.stderr, ) print(f"applying {args.apply_delta} ({len(delta.paths)} files)…") - stats = await apply_delta(repo, org, ns, delta) + stats = await apply_delta(repo, org, ns, delta, tier="clang") # scip-full runs scip-clang only, so its delta moves the C++ watermark, also # where clang is an extra tier beside the entry's own. key = watermark_key_for("clang") diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 4f4db4cc4ac..6d286b0e677 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -9,7 +9,7 @@ Apply semantics per touched file: upsert every symbol/edge the delta emits for it, tombstone scip rows in that file the delta no longer emits; files in `deleted_files` tombstone entirely. A file in `skipped_files` (its -document failed to convert) keeps its rows and joins its tier's stale row. Idempotent — +document failed to convert) keeps its rows and is marked stale. Idempotent — re-applying the same delta converges to the same live set. """ @@ -25,7 +25,6 @@ from server.code.app.index.entry_lock import check_held from server.code.domain.extract.treesitter import symbol_id -from server.code.domain.index.compiler_tiers import SUFFIXES, owns_path from server.code.domain.index.state import SCIP_STALE_PREFIX from server.code.store.index import CodeRepo, build_row from server.workers import pass_context @@ -231,9 +230,12 @@ def _has_round_reads(repo: Any) -> bool: return isinstance(repo, CodeRepo) or getattr(repo, "supports_round_reads", False) is True -async def apply_delta(repo: CodeRepo, org: str, ns: str, delta: _Delta) -> ScipApplyStats: +async def apply_delta( + repo: CodeRepo, org: str, ns: str, delta: _Delta, *, tier: str = "" +) -> ScipApplyStats: """Apply `delta` a round of files at a time, each round read off the event loop; - its deleted paths go last.""" + its deleted paths go last. `tier` is the compiler tier the delta comes from: its + skipped files are marked stale under it (`_mark_stale`); without one, nothing is.""" stats = ScipApplyStats() prefixes = _indexable_prefixes(org, ns) refused = _path_refusal(org, ns) @@ -277,7 +279,7 @@ def keep(path: str) -> bool: rounds.close() # a skipped file the entry would not keep is never marked: nothing would clear it skipped = {p for p in delta.skipped_files if not out_of_scope(p) and not refused(p)} - await _mark_stale(repo, org, ns, skipped, refreshed) + await _mark_stale(repo, org, ns, tier, delta.commit, skipped, refreshed) if FEATURE_CTOR_CALLS in delta.features: check_held() await repo.set_state( @@ -291,25 +293,25 @@ def keep(path: str) -> bool: return stats -def _stale_key(path: str) -> str: - """The stale row of the tier whose documents `path` is one of.""" - return SCIP_STALE_PREFIX + next((t for t in SUFFIXES if owns_path(t, path)), "") - - -async def _mark_stale(repo: Any, org: str, ns: str, skipped: set[str], refreshed: set[str]) -> None: - """Rewrite each tier's stale row (`SCIP_STALE_PREFIX`) this delta changes: the files - it held, plus the ones skipped, minus the ones applied or deleted. One read, and at - most one insert.""" +async def _mark_stale( + repo: Any, + org: str, + ns: str, + tier: str, + commit: str, + skipped: set[str], + refreshed: set[str], +) -> None: + """One write of `tier`'s rows only (`SCIP_STALE_PREFIX`): each skipped file marked at + `commit`, and the mark of each file this delta applied or deleted emptied. Another + tier's marks are never read or written, so tiers applying side by side keep both.""" refreshed -= skipped - if not skipped and not refreshed: + if not tier or not (skipped or refreshed): return - marks = await repo.scip_stale_marks(org, ns) - rows: dict[str, str] = {} - for key in set(marks) | {_stale_key(p) for p in skipped}: - before = marks.get(key, set()) - after = (before - refreshed) | {p for p in skipped if _stale_key(p) == key} - if after != before: - rows[key] = json.dumps(sorted(after)) + prefix = f"{SCIP_STALE_PREFIX}{tier}:" + marked = await repo.scip_stale_marks(org, ns, tier) if refreshed else set() + rows = {prefix + p: commit for p in sorted(skipped)} + rows.update({prefix + p: "" for p in sorted(marked & refreshed)}) if rows: check_held() await repo.set_states(org, ns, rows) diff --git a/server/code/app/index/scip_full.py b/server/code/app/index/scip_full.py index 6548e498318..f86c1940718 100644 --- a/server/code/app/index/scip_full.py +++ b/server/code/app/index/scip_full.py @@ -189,7 +189,7 @@ async def _index_and_apply( await asyncio.to_thread(_keep, delta_path, keep_delta) delta = await asyncio.to_thread(open_delta, delta_path) # applied while the file is there: the rounds are read from it - stats = await apply_delta(repo, cfg.org, cfg.namespace, delta) + stats = await apply_delta(repo, cfg.org, cfg.namespace, delta, tier="clang") check_held() await mark_done(repo, cfg.org, cfg.namespace, target) return stats, out diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index 580513e5ff7..c72c4faac02 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -24,10 +24,11 @@ class StateEntry(TypedDict, total=False): # The state key of an entry's bootstrap stage, whose detail is JSON. STAGE_KEY = "bootstrap_stage" -# The files of a compiler tier whose last delta skipped their document (it failed to -# parse or convert) keep the rows of an earlier state: `SCIP_STALE_PREFIX + tier` holds -# them as a JSON list, rewritten by each apply, and `scip_stale_paths` reads them as -# stale. The whole-namespace state reads leave these rows out. +# A file whose compiler-tier document the tier's last delta for it skipped (it failed +# to parse or convert) keeps the rows of an earlier state: `scip_stale::` +# holds that delta's commit, under the tier that applied it whatever the path's suffix, +# until a later delta of that tier applies or deletes the file and empties it. +# `scip_stale_paths` reads these rows by prefix; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's # `{"reason": ...}` detail; `code.repos` and `code.index_status` show only these, and diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 90622e5fa6b..4248e43b113 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -5,7 +5,6 @@ from __future__ import annotations -import json from typing import Any from clickhouse_connect.driver.binding import format_bind_value @@ -541,7 +540,7 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str wrote the file's row after the compiler tier last ran (the `.py` watermark, `scip_commit_py`, for a Python file when there is one, `scip_commit` otherwise), deleted the file, or holds no row for it, or the compiler tier's - last delta for it skipped its document (its tier's `SCIP_STALE_PREFIX` row). The fast tier + last delta for it skipped its document (a `SCIP_STALE_PREFIX` row). The fast tier writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left @@ -564,10 +563,11 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str AND path IN {paths:Array(String)} AND tombstoned_at IS NULL AND created_at <= if(endsWith(path, '.py') AND t_py > toDateTime(0), t_py, t_scip) AND path NOT IN ( - SELECT arrayJoin(JSONExtract(state_value, 'Array(String)')) + -- `scip_stale::`; a path may hold ':' itself + SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} - AND startsWith(state_key, {mark:String}) + AND startsWith(state_key, {mark:String}) AND state_value != '' ) """, {"org": org, "ns": ns, "paths": asked, "mark": SCIP_STALE_PREFIX}, @@ -575,19 +575,20 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str # the query names the FRESH paths; every other asked path is stale return set(asked) - {str(r["path"]) for r in rows} - async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: - """Each tier's stale row (`SCIP_STALE_PREFIX` + tier): the paths whose document - that tier's last delta for them skipped.""" + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + """The paths `tier` holds marked stale (`SCIP_STALE_PREFIX`): its last delta for + each skipped the file's document.""" + prefix = f"{SCIP_STALE_PREFIX}{tier}:" rows = await self._ch.query_all( """ - SELECT state_key, state_value + SELECT substring(state_key, length({mark:String}) + 1) AS path FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} - AND startsWith(state_key, {mark:String}) + AND startsWith(state_key, {mark:String}) AND state_value != '' """, - {"org": org, "ns": ns, "mark": SCIP_STALE_PREFIX}, + {"org": org, "ns": ns, "mark": prefix}, ) - return {str(r["state_key"]): set(json.loads(r["state_value"] or "[]")) for r in rows} + return {str(r["path"]) for r in rows} async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: diff --git a/server/code/workers/scip_apply.py b/server/code/workers/scip_apply.py index 34feccb961f..3c9dc8b78c5 100644 --- a/server/code/workers/scip_apply.py +++ b/server/code/workers/scip_apply.py @@ -47,6 +47,15 @@ def watermark_key_for(producer: str) -> str: return "scip_commit" +def tier_for(producer: str) -> str: + """The compiler tier an upload's producer applies for: the one whose watermark it + moves (`watermark_key_for`).""" + from server.code.domain.index.compiler_tiers import TIERS + + key = watermark_key_for(producer) + return next(t.producer for t in TIERS if t.watermark_key == key) + + async def run_pass() -> CodeScipApplyResult: result = CodeScipApplyResult() with record_pass("code_scip_apply") as rec: @@ -91,7 +100,9 @@ async def _run(result: CodeScipApplyResult) -> None: raise ValidationError(f"the batch is not a SCIP delta (at {where})") from e if delta.delta_version != 1: raise ValidationError(f"unsupported delta_version {delta.delta_version}") - stats = await apply_delta(repo, org, ns, delta) + stats = await apply_delta( + repo, org, ns, delta, tier=tier_for(str(batch.get("producer") or "")) + ) await repo.upsert_scip_batch( org, ns, diff --git a/server/code/workers/scip_delta.py b/server/code/workers/scip_delta.py index 9832e6cdb13..700e191ecad 100644 --- a/server/code/workers/scip_delta.py +++ b/server/code/workers/scip_delta.py @@ -178,7 +178,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipDeltaResult from server.code.app.index.scip_delta import apply_delta - stats = await apply_delta(repo, cfg.org, cfg.namespace, delta) + stats = await apply_delta(repo, cfg.org, cfg.namespace, delta, tier=PRODUCER) check_held() await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) result.deltas_applied += 1 diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index ba2a4572d4e..41eeba248d4 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -265,7 +265,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu paths = await asyncio.to_thread(_deltas, out_dir, len(expected)) for path in paths: delta = await open_tier_delta(repo, cfg, WATERMARK, scip_commit, target, path, shape) - stats = await apply_delta(repo, cfg.org, cfg.namespace, delta) + stats = await apply_delta(repo, cfg.org, cfg.namespace, delta, tier=PRODUCER) del delta # free this module's paths before the next one is read result.modules_indexed += 1 logger.info( diff --git a/server/code/workers/scip_py_delta.py b/server/code/workers/scip_py_delta.py index a5252bea97c..43fa63ad5e8 100644 --- a/server/code/workers/scip_py_delta.py +++ b/server/code/workers/scip_py_delta.py @@ -122,7 +122,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipPyDeltaResu delta, PRODUCER, ) - stats = await apply_delta(repo, cfg.org, cfg.namespace, delta) + stats = await apply_delta(repo, cfg.org, cfg.namespace, delta, tier=PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) result.deltas_applied += 1 logger.info( diff --git a/server/code/workers/scip_ts_delta.py b/server/code/workers/scip_ts_delta.py index 89370d8b102..224c16c09f0 100644 --- a/server/code/workers/scip_ts_delta.py +++ b/server/code/workers/scip_ts_delta.py @@ -164,7 +164,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipTsDeltaResu delta, PRODUCER, ) - stats = await apply_delta(repo, cfg.org, cfg.namespace, delta) + stats = await apply_delta(repo, cfg.org, cfg.namespace, delta, tier=PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) result.deltas_applied += 1 logger.info( diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index c95bc565631..a2fcd83c6d2 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -1,6 +1,6 @@ """A file whose compiler-tier document a delta skipped reads as stale, although the tier's watermark moved past the file's last change, until a later delta applies it. The -tier's stale row stays out of the namespace's state reads.""" +marks stay out of the whole-namespace state reads.""" from __future__ import annotations @@ -30,14 +30,22 @@ async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: A await repo.set_state(org, ns, "scip_commit", "a" * 40) # the tier ran after the change assert await repo.scip_stale_paths(org, ns, paths) == set() - await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=["src/bad.cpp"])) + skip = ScipDelta(commit="b" * 40, skipped_files=["src/bad.cpp"]) + await apply_delta(repo, org, ns, skip, tier="clang") await repo.set_state(org, ns, "scip_commit", "b" * 40) assert await repo.scip_stale_paths(org, ns, paths) == {"src/bad.cpp"} - assert await repo.scip_stale_marks(org, ns) == {"scip_stale:clang": {"src/bad.cpp"}} - assert "scip_stale:clang" not in await repo.all_state(org, ns) + assert await repo.scip_stale_marks(org, ns, "clang") == {"src/bad.cpp"} + assert await repo.scip_stale_marks(org, ns, "python") == set() + assert not any(k.startswith("scip_stale:") for k in await repo.all_state(org, ns)) + many = await repo.all_state_many([(org, ns)]) + assert not any(k.startswith("scip_stale:") for k in many[(org, ns)]) await apply_delta( - repo, org, ns, ScipDelta(commit="c" * 40, files=[ScipFile(path="src/bad.cpp")]) + repo, + org, + ns, + ScipDelta(commit="c" * 40, files=[ScipFile(path="src/bad.cpp")]), + tier="clang", ) assert await repo.scip_stale_paths(org, ns, paths) == set() - assert await repo.scip_stale_marks(org, ns) == {"scip_stale:clang": set()} + assert await repo.scip_stale_marks(org, ns, "clang") == set() diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 56a5189f926..55656ad52d5 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -474,9 +474,6 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state.append((key, value, detail)) - async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: - return {} - @pytest.mark.asyncio async def test_apply_carries_confidence_and_records_the_feature() -> None: diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index 00daeec038f..b0a9e4e12c6 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -172,9 +172,6 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def set_state(self, org: str, ns: str, key: str, value: str, **_: Any) -> None: self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: - return {} - @pytest.mark.asyncio async def test_the_apply_takes_the_file_a_round_at_a_time( diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index d302e8eef93..849f485217c 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -151,7 +151,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): monkeypatch.setattr(w, "_module_dirs", AsyncMock(return_value=["lib", "svc"])) applied: list[str] = [] - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): applied.append(delta.paths[0]) from server.code.app.index.scip_delta import ScipApplyStats @@ -257,7 +257,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return "done lib\n" - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=0) diff --git a/tests/unit/test_code_scip_py_delta_worker.py b/tests/unit/test_code_scip_py_delta_worker.py index 763f47ade01..16294e11fdc 100644 --- a/tests/unit/test_code_scip_py_delta_worker.py +++ b/tests/unit/test_code_scip_py_delta_worker.py @@ -121,7 +121,7 @@ async def fake_harness(co, base, head, delta_path): monkeypatch.setattr(w, "_run_harness", fake_harness) applied: list[str] = [] - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): applied.append(delta.commit) from server.code.app.index.scip_delta import ScipApplyStats @@ -189,7 +189,7 @@ async def fake_harness(co, base, head, delta_path): files = [{"path": "pkg/a.py", "symbols": [], "edges": []}] delta_path.write_text(json.dumps({"delta_version": 1, "commit": head, "files": files})) - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=1) @@ -244,7 +244,7 @@ async def fake_harness(co, base, head, delta_path): files = [{"path": f"pkg/m{i}.py", "symbols": [], "edges": []} for i in range(n)] delta_path.write_text(json.dumps({"delta_version": 1, "commit": head, "files": files})) - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=0) diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index be18606d15f..50edc425aeb 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -1,10 +1,11 @@ """The server's side of a document the converter skipped: every tier's harness run logs -the first warnings and the count and carries the stop switch, and the apply keeps each -tier's stale row: the files it skipped, until a later delta applies or deletes them.""" +the first warnings and the count and carries the stop switch, and the apply marks the +files it skipped stale under its tier, until a later delta of that tier applies or +deletes them.""" from __future__ import annotations -import json +import asyncio import logging from pathlib import Path from unittest.mock import AsyncMock @@ -63,47 +64,96 @@ async def test_a_harness_run_carries_the_stop_switch( @pytest.mark.asyncio -async def test_one_apply_rewrites_each_tiers_stale_row_in_one_insert( +async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( monkeypatch: pytest.MonkeyPatch, ) -> None: - """The row keeps what it held, gains the skipped files the entry keeps, and drops - the files this delta applies or deletes. An out-of-scope or refused path is never - marked: no delta would clear it.""" + """Each skipped file the entry keeps is marked under the applying tier, whatever its + suffix, and the mark of each file this delta applies or deletes is emptied. An + out-of-scope or refused path is never marked: no delta would clear it.""" monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) monkeypatch.setattr(scip_delta, "_indexable_prefixes", lambda *a: ("src/",)) monkeypatch.setattr( - scip_delta, "_path_refusal", lambda *a: lambda p: "denied" if p.endswith(".env.ts") else "" + scip_delta, "_path_refusal", lambda *a: lambda p: "denied" if p.endswith(".env.h") else "" ) repo = AsyncMock() - repo.scip_stale_marks.return_value = { - "scip_stale:clang": {"src/a.cpp", "src/gone.cpp", "src/other.cpp"}, - "scip_stale:python": {"src/kept.py"}, - } + repo.scip_stale_marks.return_value = {"src/a.cpp", "src/gone.cpp", "src/other.cpp"} delta = ScipDelta( commit="c" * 40, files=[ScipFile(path="src/a.cpp")], deleted_files=["src/gone.cpp"], - skipped_files=["src/bad.cpp", "src/web.ts", "contrib/x.cpp", "src/conf.env.ts"], + skipped_files=["src/bad.cpp", "src/k.cu", "contrib/x.cpp", "src/conf.env.h"], ) - await scip_delta.apply_delta(repo, "o", "n", delta) + await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") + repo.scip_stale_marks.assert_awaited_once_with("o", "n", "clang") repo.set_state.assert_not_awaited() - repo.set_states.assert_awaited_once() - org, ns, rows = repo.set_states.await_args.args - assert (org, ns) == ("o", "n") - assert {k: json.loads(v) for k, v in rows.items()} == { - "scip_stale:clang": ["src/bad.cpp", "src/other.cpp"], - "scip_stale:typescript": ["src/web.ts"], - } + repo.set_states.assert_awaited_once_with( + "o", + "n", + { + "scip_stale:clang:src/bad.cpp": "c" * 40, + "scip_stale:clang:src/k.cu": "c" * 40, + "scip_stale:clang:src/a.cpp": "", + "scip_stale:clang:src/gone.cpp": "", + }, + ) @pytest.mark.asyncio -async def test_an_apply_that_changes_no_stale_row_writes_none( +async def test_an_apply_that_marks_and_clears_nothing_writes_nothing( monkeypatch: pytest.MonkeyPatch, ) -> None: monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"scip_stale:clang": {"src/other.cpp"}} - await scip_delta.apply_delta( - repo, "o", "n", ScipDelta(commit="c" * 40, files=[ScipFile(path="src/a.cpp")]) - ) + repo.scip_stale_marks.return_value = {"src/other.cpp"} + delta = ScipDelta(commit="c" * 40, files=[ScipFile(path="src/a.cpp")]) + await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") repo.set_states.assert_not_awaited() + + +class _State: + """`code_index_state` as last writer wins, both applies' reads landing before + either one's write.""" + + def __init__(self, rows: dict[str, str]) -> None: + self.rows = rows + self.read = asyncio.Barrier(2) + + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + prefix = f"scip_stale:{tier}:" + marked = {k[len(prefix) :] for k, v in self.rows.items() if k.startswith(prefix) and v} + await self.read.wait() + return marked + + async def set_states(self, org: str, ns: str, rows: dict[str, str]) -> None: + self.rows.update(rows) + + +@pytest.mark.asyncio +async def test_a_cpp_delta_beside_a_python_one_keeps_the_python_marks( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A C++ window lists every file it deleted, a `.py` one too; the Python tier's marks + are not its own, so it neither reads nor writes them.""" + monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) + state = _State({"scip_stale:python:pkg/a.py": "a" * 40}) + cpp = ScipDelta(commit="b" * 40, files=[ScipFile(path="src/x.cpp")], deleted_files=["pkg/a.py"]) + py = ScipDelta(commit="c" * 40, files=[ScipFile(path="pkg/c.py")], skipped_files=["pkg/b.py"]) + await asyncio.gather( + scip_delta.apply_delta(state, "o", "n", cpp, tier="clang"), # type: ignore[arg-type] + scip_delta.apply_delta(state, "o", "n", py, tier="python"), # type: ignore[arg-type] + ) + assert state.rows == { + "scip_stale:python:pkg/a.py": "a" * 40, + "scip_stale:python:pkg/b.py": "c" * 40, + } + + +def test_an_upload_applies_for_the_tier_whose_watermark_it_moves() -> None: + from server.code.workers.scip_apply import tier_for + + assert [tier_for(p) for p in ("scip_harness@ci", "scip-python", "scip-typescript", "go")] == [ + "clang", + "python", + "typescript", + "go", + ] diff --git a/tests/unit/test_code_scip_ts_delta_worker.py b/tests/unit/test_code_scip_ts_delta_worker.py index 945c4a0be40..c40c12848d7 100644 --- a/tests/unit/test_code_scip_ts_delta_worker.py +++ b/tests/unit/test_code_scip_ts_delta_worker.py @@ -146,7 +146,7 @@ async def fake_harness(co, base, head, delta_path, projects=(), **_): monkeypatch.setattr(w, "_run_harness", fake_harness) applied: list[str] = [] - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): applied.append(delta.commit) from server.code.app.index.scip_delta import ScipApplyStats @@ -267,8 +267,8 @@ async def test_a_full_run_keeps_a_skipped_documents_rows_and_marks_the_file_stal monkeypatch, tmp_path: Path, checkout: Path ): """The converter skipped web/bad.ts: the full run retires web/gone.ts, which the new - index no longer has, keeps web/bad.ts's rows and puts the file in the TypeScript - tier's stale row; the watermark moves.""" + index no longer has, keeps web/bad.ts's rows and marks the file stale under the + TypeScript tier; the watermark moves.""" (checkout / "node_modules").mkdir(parents=True) bare = tmp_path / "repo.git" bare.mkdir() @@ -300,13 +300,13 @@ async def fake_apply_files(repo, org, ns, commit, files, stats): monkeypatch.setattr("server.code.app.index.scip_delta._apply_files", fake_apply_files) repo = _repo("b" * 40, "") repo.live_scip_paths.return_value = {"web/a.ts", "web/bad.ts", "web/gone.ts"} - repo.scip_stale_marks.return_value = {} + repo.scip_stale_marks.return_value = set() p1, p2 = _patched(repo, [_Cfg()]) with p1, p2: res = await w.run_pass() assert res.deltas_applied == 1 and not res.errors, res.errors assert applied == [("web/a.ts", False), ("web/gone.ts", True)] repo.set_states.assert_awaited_once_with( - "org", "code-ts", {"scip_stale:typescript": '["web/bad.ts"]'} + "org", "code-ts", {"scip_stale:typescript:web/bad.ts": "b" * 40} ) repo.set_state.assert_awaited_with("org", "code-ts", "scip_commit_ts", "b" * 40) diff --git a/tests/unit/test_scip_apply_any_namespace.py b/tests/unit/test_scip_apply_any_namespace.py index 194d625cbab..cf8a82a538b 100644 --- a/tests/unit/test_scip_apply_any_namespace.py +++ b/tests/unit/test_scip_apply_any_namespace.py @@ -57,7 +57,7 @@ def _patch(monkeypatch, repo, *, apply=None) -> None: classmethod(lambda cls, payload: SimpleNamespace(delta_version=1)), ) - async def fake_apply(repo_, org, ns, delta): + async def fake_apply(repo_, org, ns, delta, **_): return SimpleNamespace(files=3, symbols_new=2, edges_new=1) monkeypatch.setattr(sd, "apply_delta", apply or fake_apply) @@ -80,7 +80,7 @@ async def test_a_failed_failure_mark_does_not_stop_the_next_batch(monkeypatch): repo = _Repo([_batch("ns-a", "bad"), _batch("ns-b", "good")]) repo.fail_mark = {"bad"} - async def apply(repo_, org, ns, delta): + async def apply(repo_, org, ns, delta, **_): if ns == "ns-a": raise ValueError("corrupt delta") return SimpleNamespace(files=1, symbols_new=0, edges_new=0) diff --git a/tests/unit/test_scip_apply_rounds.py b/tests/unit/test_scip_apply_rounds.py index 21773bf254a..59f130003a2 100644 --- a/tests/unit/test_scip_apply_rounds.py +++ b/tests/unit/test_scip_apply_rounds.py @@ -98,9 +98,6 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: - return {} - def test_a_delta_is_applied_in_rounds_with_one_read_and_one_insert_per_table() -> None: repo = _RoundRepo() @@ -142,9 +139,6 @@ async def insert_rows(self, table, rows): async def set_state(self, *a: Any, **k: Any) -> None: return None - async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: - return {} - def test_a_repository_without_round_reads_keeps_the_per_file_path() -> None: from unittest.mock import AsyncMock diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index 52f1cf7fd5e..1fe8c68c2b0 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -567,9 +567,6 @@ async def insert_rows(self, table, rows) -> None: async def set_state(self, org, ns, key, value, detail="") -> None: self.states.append(key) - async def scip_stale_marks(self, org: str, ns: str) -> dict[str, set[str]]: - return {} - def _delta() -> Any: from server.code.app.index.scip_delta import ScipDelta From 47bc8e4bedf4753e261c0ad06c8bba969c216f4a Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 01:46:44 +0000 Subject: [PATCH 04/81] Read the asked paths' stale marks by key; a delta lists only the skipped files it converts `scip_stale_paths` looks up each asked path's mark under each tier instead of scanning every mark of the namespace. `skipped_files` holds only the failing documents among the files the delta converts, so a document outside a window is counted but not marked again. `tier` is a required keyword of `apply_delta`. Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/README.md | 5 +++-- scripts/scip_harness/scip_to_delta.py | 7 +++++-- server/code/app/index/scip_delta.py | 6 +++--- server/code/store/index/symbols.py | 7 +++++-- tests/integration/test_code_plane.py | 6 +++--- tests/unit/test_code_ctor_call_edges.py | 7 +++++-- tests/unit/test_code_delta_stream.py | 9 ++++++--- tests/unit/test_pass_stop.py | 4 ++-- tests/unit/test_scip_apply_rounds.py | 10 ++++++++-- tests/unit/test_scip_entry_lock.py | 7 +++++-- tests/unit/test_scip_scope_enforcement.py | 8 ++++---- tests/unit/test_scip_to_delta_skip.py | 10 ++++++++++ tests/unit/test_scip_typescript.py | 4 ++-- 13 files changed, 61 insertions(+), 29 deletions(-) diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 18daee8d7ac..518f906d89c 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -37,8 +37,9 @@ line, then `wrote (sha …)`. A document the converter cannot parse or convert (a string that is not UTF-8, say) is skipped: it is named once on stderr (`scip_to_delta: warning: skipped -document …`), listed in the delta's `skipped_files` and counted in the summary -line, and the rest of the index converts. The server keeps that file's compiler +document …`) and counted in the summary line, and listed in the delta's +`skipped_files` when it is one of the files the delta converts (a window's +own, or any in a full run), and the rest of the index converts. The server keeps that file's compiler rows and marks them stale until a later delta converts it. With `SCIP_STOP_ON_FAILED_DOCUMENT=1` (the server sets it from `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT`) `convert_delta` passes diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 0b28715b1ef..897fe55db1a 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1273,6 +1273,7 @@ def __init__( scip_pb2 = _ensure_scip_pb2() data = _read_index(index_path) self._skips = _Skips(stop_on_failed_document) + self._changed = changed self._run = _prepare( data, scip_pb2, source_root, exclude_generated, path_prefix, self._skips ) @@ -1309,9 +1310,11 @@ def _files(self, data, scip_pb2, changed: set[str] | None): def tail(self) -> dict: out: dict = { "deleted_files": self._deleted, - # repository-relative, as the emitted paths are + # the window's files only, the server marks them; repository-relative "skipped_files": sorted( - f"{self._prefix}/{p}" if self._prefix else p for p in self._skips.paths + f"{self._prefix}/{p}" if self._prefix else p + for p in self._skips.paths + if self._changed is None or p in self._changed ), "stats": { "factory_ctor_edges": self._run.factory_edges, diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 6d286b0e677..a2e075d0ad4 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -231,11 +231,11 @@ def _has_round_reads(repo: Any) -> bool: async def apply_delta( - repo: CodeRepo, org: str, ns: str, delta: _Delta, *, tier: str = "" + repo: CodeRepo, org: str, ns: str, delta: _Delta, *, tier: str ) -> ScipApplyStats: """Apply `delta` a round of files at a time, each round read off the event loop; its deleted paths go last. `tier` is the compiler tier the delta comes from: its - skipped files are marked stale under it (`_mark_stale`); without one, nothing is.""" + skipped files are marked stale under it (`_mark_stale`).""" stats = ScipApplyStats() prefixes = _indexable_prefixes(org, ns) refused = _path_refusal(org, ns) @@ -306,7 +306,7 @@ async def _mark_stale( `commit`, and the mark of each file this delta applied or deleted emptied. Another tier's marks are never read or written, so tiers applying side by side keep both.""" refreshed -= skipped - if not tier or not (skipped or refreshed): + if not (skipped or refreshed): return prefix = f"{SCIP_STALE_PREFIX}{tier}:" marked = await repo.scip_stale_marks(org, ns, tier) if refreshed else set() diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 4248e43b113..dbc79be6b0d 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -9,6 +9,7 @@ from clickhouse_connect.driver.binding import format_bind_value +from server.code.domain.index.compiler_tiers import TIERS from server.code.domain.index.state import SCIP_STALE_PREFIX from server.code.domain.index.test_gate import TEST_PATH_PATTERN from server.code.store.index.base import CodeRepoBase @@ -548,6 +549,8 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str if not paths: return set() asked = list(dict.fromkeys(paths))[:200] + # the asked paths' marks under every tier: point keys, never the whole prefix + marks = [f"{SCIP_STALE_PREFIX}{t.producer}:{p}" for t in TIERS for p in asked] rows = await self._ch.query_all( """ WITH @@ -567,10 +570,10 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} - AND startsWith(state_key, {mark:String}) AND state_value != '' + AND state_key IN {marks:Array(String)} AND state_value != '' ) """, - {"org": org, "ns": ns, "paths": asked, "mark": SCIP_STALE_PREFIX}, + {"org": org, "ns": ns, "paths": asked, "marks": marks}, ) # the query names the FRESH paths; every other asked path is stale return set(asked) - {str(r["path"]) for r in rows} diff --git a/tests/integration/test_code_plane.py b/tests/integration/test_code_plane.py index f4fda24ca51..837dc6beed6 100644 --- a/tests/integration/test_code_plane.py +++ b/tests/integration/test_code_plane.py @@ -329,7 +329,7 @@ async def test_scip_tier_coexists_and_wins(code_env) -> None: ], } ) - stats = await apply_delta(repo, org, ns, delta) + stats = await apply_delta(repo, org, ns, delta, tier="clang") assert stats.symbols_new == 1 and stats.edges_new == 1 rows = await repo.symbols_by_name(org, ns, "DB::Squasher::flush") @@ -339,7 +339,7 @@ async def test_scip_tier_coexists_and_wins(code_env) -> None: assert str(rows[0]["tier"]) == "scip" # idempotent re-apply converges (no new rows) - stats2 = await apply_delta(repo, org, ns, delta) + stats2 = await apply_delta(repo, org, ns, delta, tier="clang") assert stats2.symbols_new == 0 and stats2.edges_new == 0 @@ -1093,7 +1093,7 @@ async def test_edit_context_does_not_attach_indirect_example_to_an_overload( ], } ) - await apply_delta(repo, org, ns, delta) + await apply_delta(repo, org, ns, delta, tier="clang") result = await handle_code_edit_context( CodeEditContextInput(org=org, namespace=ns, name="DB::value", include_lessons=False) diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 55656ad52d5..8919583eae4 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -474,6 +474,9 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state.append((key, value, detail)) + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() + @pytest.mark.asyncio async def test_apply_carries_confidence_and_records_the_feature() -> None: @@ -510,7 +513,7 @@ async def test_apply_carries_confidence_and_records_the_feature() -> None: ) repo = _ApplyRepo() with patch("server.code.app.index.scip_delta._indexable_prefixes", return_value=()): - stats = await apply_delta(repo, "o", "n", delta) # type: ignore[arg-type] + stats = await apply_delta(repo, "o", "n", delta, tier="clang") # type: ignore[arg-type] confs = sorted(float(r["confidence"]) for r in repo.rows["code_edges"]) assert confs == [0.8, 1.0] assert stats.ctor_calls_recorded is True @@ -525,7 +528,7 @@ async def test_apply_without_the_feature_writes_no_state() -> None: delta = ScipDelta.model_validate({"commit": "c0ffee", "files": []}) repo = _ApplyRepo() with patch("server.code.app.index.scip_delta._indexable_prefixes", return_value=()): - stats = await apply_delta(repo, "o", "n", delta) # type: ignore[arg-type] + stats = await apply_delta(repo, "o", "n", delta, tier="clang") # type: ignore[arg-type] assert stats.ctor_calls_recorded is False and repo.state == [] diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index b0a9e4e12c6..dc4704728ba 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -172,6 +172,9 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def set_state(self, org: str, ns: str, key: str, value: str, **_: Any) -> None: self.state[key] = value + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() + @pytest.mark.asyncio async def test_the_apply_takes_the_file_a_round_at_a_time( @@ -181,7 +184,7 @@ async def test_the_apply_takes_the_file_a_round_at_a_time( path = tmp_path / "delta.json" _write(path, 30) repo = _Repo() - stats = await apply_delta(repo, "o", "code-x", open_delta(path)) # type: ignore[arg-type] + stats = await apply_delta(repo, "o", "code-x", open_delta(path), tier="clang") # type: ignore[arg-type] assert stats.files == 31 # 30 entries and the deleted path assert [len(r) for r in repo.rounds] == [14, 14, 3] assert repo.rounds[-1][-1] == "src/gone.cpp" and stats.ctor_calls_recorded @@ -360,7 +363,7 @@ async def failing(*a: Any) -> None: monkeypatch.setattr(scip_delta, "_apply_files", failing) before = _fds() with pytest.raises(RuntimeError): - await apply_delta(_Repo(), "o", "code-x", delta) # type: ignore[arg-type] + await apply_delta(_Repo(), "o", "code-x", delta, tier="clang") # type: ignore[arg-type] assert _fds() == before @@ -391,7 +394,7 @@ def slow(text: str, index: int) -> Any: # Unrelated cyclic garbage must close its descriptors before the baseline. gc.collect() before = _fds() - task = asyncio.create_task(apply_delta(_Repo(), "o", "code-x", delta)) # type: ignore[arg-type] + task = asyncio.create_task(apply_delta(_Repo(), "o", "code-x", delta, tier="clang")) # type: ignore[arg-type] assert await asyncio.to_thread(in_read.wait, 10) task.cancel() with pytest.raises(asyncio.CancelledError): diff --git a/tests/unit/test_pass_stop.py b/tests/unit/test_pass_stop.py index e48596b9d86..77070c509da 100644 --- a/tests/unit/test_pass_stop.py +++ b/tests/unit/test_pass_stop.py @@ -105,7 +105,7 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def run() -> None: pass_context.begin("code_scip_delta") try: - await sd.apply_delta(repo, "o", "n", _delta(250)) # type: ignore[arg-type] + await sd.apply_delta(repo, "o", "n", _delta(250), tier="clang") # type: ignore[arg-type] finally: pass_context.clear() @@ -134,7 +134,7 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def run() -> None: token = el._current.set(lease) # type: ignore[arg-type] try: - await sd.apply_delta(repo, "o", "n", _delta(250)) # type: ignore[arg-type] + await sd.apply_delta(repo, "o", "n", _delta(250), tier="clang") # type: ignore[arg-type] finally: el._current.reset(token) diff --git a/tests/unit/test_scip_apply_rounds.py b/tests/unit/test_scip_apply_rounds.py index 59f130003a2..f0ed0066be3 100644 --- a/tests/unit/test_scip_apply_rounds.py +++ b/tests/unit/test_scip_apply_rounds.py @@ -98,11 +98,14 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state[key] = value + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() + def test_a_delta_is_applied_in_rounds_with_one_read_and_one_insert_per_table() -> None: repo = _RoundRepo() with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = asyncio.run(sd.apply_delta(repo, "o", "n", _delta(250))) # type: ignore[arg-type] + stats = asyncio.run(sd.apply_delta(repo, "o", "n", _delta(250), tier="clang")) # type: ignore[arg-type] # 250 files + 1 deletion = 251 → three rounds of ≤100; three reads each rounds = [r for r in repo.reads if r[0] == "symbols:scip"] assert [len(r[1]) for r in rounds] == [100, 100, 51] @@ -139,6 +142,9 @@ async def insert_rows(self, table, rows): async def set_state(self, *a: Any, **k: Any) -> None: return None + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() + def test_a_repository_without_round_reads_keeps_the_per_file_path() -> None: from unittest.mock import AsyncMock @@ -149,7 +155,7 @@ def test_a_repository_without_round_reads_keeps_the_per_file_path() -> None: assert sd._has_round_reads(CodeRepo.__new__(CodeRepo)) is True repo = _PerFileRepo() with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = asyncio.run(sd.apply_delta(repo, "o", "n", _delta(3))) # type: ignore[arg-type] + stats = asyncio.run(sd.apply_delta(repo, "o", "n", _delta(3), tier="clang")) # type: ignore[arg-type] assert repo.calls == ["src/f0.cpp", "src/f1.cpp", "src/f2.cpp", "src/gone.cpp"] assert stats.files == 4 and stats.symbols_new == 3 and stats.edges_new == 3 # per file: one insert per table, even when empty (the historical shape) diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index 1fe8c68c2b0..5dd1ee5d366 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -567,6 +567,9 @@ async def insert_rows(self, table, rows) -> None: async def set_state(self, org, ns, key, value, detail="") -> None: self.states.append(key) + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() + def _delta() -> Any: from server.code.app.index.scip_delta import ScipDelta @@ -593,7 +596,7 @@ async def test_apply_delta_publishes_rows_and_watermarks_while_held(monkeypatch) monkeypatch.setattr(scip_delta, "_path_refusal", lambda *a: lambda p: False) repo = _IndexRepo() with _inside_lease(HeldLease()): - await scip_delta.apply_delta(repo, "acme", "code-web", _delta()) # type: ignore[arg-type] + await scip_delta.apply_delta(repo, "acme", "code-web", _delta(), tier="clang") # type: ignore[arg-type] assert repo.inserted and repo.states @@ -608,7 +611,7 @@ async def test_a_lease_lost_mid_round_publishes_no_row_or_watermark(monkeypatch) lease = HeldLease() repo = _IndexRepo(on_read=lambda: setattr(lease, "lost", True)) with _inside_lease(lease), pytest.raises(EntryLockLost): - await scip_delta.apply_delta(repo, "acme", "code-web", _delta()) # type: ignore[arg-type] + await scip_delta.apply_delta(repo, "acme", "code-web", _delta(), tier="clang") # type: ignore[arg-type] assert repo.inserted == [] and repo.states == [] diff --git a/tests/unit/test_scip_scope_enforcement.py b/tests/unit/test_scip_scope_enforcement.py index 9f2dfc584b3..26fd68da6b5 100644 --- a/tests/unit/test_scip_scope_enforcement.py +++ b/tests/unit/test_scip_scope_enforcement.py @@ -37,7 +37,7 @@ def _Cfg(*_a: Any, **_k: Any) -> Any: return repo_config(path_prefixes=("src/", "base/", "programs/", "tests/queries/")) with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = await apply_delta(repo, "org", "ns", delta) + stats = await apply_delta(repo, "org", "ns", delta, tier="clang") assert stats.files == 1 assert stats.files_skipped_out_of_scope == 2 @@ -98,12 +98,12 @@ def _Cfg(*_a: Any, **_k: Any) -> Any: return repo_config(path_prefixes=("src/",)) with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = await apply_delta(repo, "org", "ns", delta) + stats = await apply_delta(repo, "org", "ns", delta, tier="clang") assert stats.symbols_new == 1 and stats.symbols_tombstoned == 0 # same lines, same kind: the live row is kept repo.live_symbols_for_path.return_value[0]["kind"] = "function" with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = await apply_delta(repo, "org", "ns", delta) + stats = await apply_delta(repo, "org", "ns", delta, tier="clang") assert stats.symbols_new == 0 @@ -135,7 +135,7 @@ def _Cfg(*_a: Any, **_k: Any) -> Any: ) with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = await apply_delta(repo, "org", "ns", delta) + stats = await apply_delta(repo, "org", "ns", delta, tier="clang") assert stats.files == 1 assert stats.files_skipped_excluded == 2 diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 11dc36d58a3..86f6f301f40 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -141,3 +141,13 @@ def convert_document(doc, run): conv.DeltaStream(index, None, [], "h" * 40, "", source_root="", full=True) assert first.tail()["skipped_files"] == ["src/bad.cpp"] assert first.tail()["stats"]["skipped_failed"] == 1 + + +def test_a_window_lists_only_its_own_failed_documents(tmp_path: Path) -> None: + """The index-wide passes meet a bad document the window does not hold: it is warned + about and counted, but not listed, so the server marks only what the window asked.""" + conv = _converter() + index = str(_bad_utf8_index(tmp_path)) + delta = conv.convert(index, {"src/a.cpp"}, [], "h" * 40, "b" * 40, source_root="") + assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] + assert delta["skipped_files"] == [] and delta["stats"]["skipped_failed"] == 1 diff --git a/tests/unit/test_scip_typescript.py b/tests/unit/test_scip_typescript.py index 47340dcc9e3..0e63c3d34b3 100644 --- a/tests/unit/test_scip_typescript.py +++ b/tests/unit/test_scip_typescript.py @@ -199,7 +199,7 @@ class _Cfg: path_prefixes = ("packages/",) with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = await apply_delta(repo, "org", "ns", delta) + stats = await apply_delta(repo, "org", "ns", delta, tier="clang") assert stats.edges_dropped_declarations == 1 and stats.edges_new == 3 inserted = [ r @@ -313,7 +313,7 @@ class _Cfg: path_prefixes = ("src/",) with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): - stats = await apply_delta(repo, "org", "ns", delta) + stats = await apply_delta(repo, "org", "ns", delta, tier="clang") # line 808 is inside the function symbol: a call; line 47 sits in a # skeleton window and no function: a declaration assert stats.edges_new == 1 and stats.edges_dropped_declarations == 1 From 2e3beaf8d15c5ce04c710d675fead9cebc1a5dfb Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 10:27:03 +0000 Subject: [PATCH 05/81] Say that a delta marks only the skipped files in its window Split the harness README's spliced sentence about a skipped document in two, and add the window rule to the failure-table row. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 2 +- scripts/scip_harness/README.md | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 1cfb3eecd60..0a43c7aa7fc 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1267,7 +1267,7 @@ the output to read. | compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | | a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | | compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | -| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows, marked stale (callers and impact name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | +| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window (callers and impact name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | | a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | | GitHub rate limit | the pass ends, cursor unmoved | the next pass | | branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 518f906d89c..ec33e5aecc0 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -37,10 +37,11 @@ line, then `wrote (sha …)`. A document the converter cannot parse or convert (a string that is not UTF-8, say) is skipped: it is named once on stderr (`scip_to_delta: warning: skipped -document …`) and counted in the summary line, and listed in the delta's +document …`) and counted in the summary line. It is listed in the delta's `skipped_files` when it is one of the files the delta converts (a window's -own, or any in a full run), and the rest of the index converts. The server keeps that file's compiler -rows and marks them stale until a later delta converts it. With +own, or any in a full run). The rest of the index converts. The server keeps +that file's compiler rows and marks them stale until a later delta converts +it. With `SCIP_STOP_ON_FAILED_DOCUMENT=1` (the server sets it from `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT`) `convert_delta` passes `--stop-on-failed-document`, and such a document fails the run. An index whose From 2da922726e7a760f39505408a0b9a5ac826f4778 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 11:57:21 +0000 Subject: [PATCH 06/81] Fail a full run on a failed document whose path cannot be read A run over every document lists each skipped document's path in `skipped_files`, and the TypeScript and Python workers retire the live files such a delta does not name. A document whose path could not be read was only counted, so its file landed in that deletion set. The converter now fails such a run before anything is applied; a window, which names its own files, still counts it and converts. A path that is not UTF-8 is one that cannot be read: it is no longer decoded with replacement characters into a name no file has. Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/README.md | 5 ++++- scripts/scip_harness/scip_to_delta.py | 18 +++++++++++------- tests/unit/test_scip_to_delta_skip.py | 20 ++++++++++++++++++++ 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index ec33e5aecc0..46a92a03f5a 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -39,7 +39,10 @@ A document the converter cannot parse or convert (a string that is not UTF-8, say) is skipped: it is named once on stderr (`scip_to_delta: warning: skipped document …`) and counted in the summary line. It is listed in the delta's `skipped_files` when it is one of the files the delta converts (a window's -own, or any in a full run). The rest of the index converts. The server keeps +own, or any in a full run). The rest of the index converts. In a run over +every document (no `--changed-files`), a failed document whose path cannot be +read (one that is not UTF-8, say) fails the run: the server would read its +file as gone. The server keeps that file's compiler rows and marks them stale until a later delta converts it. With `SCIP_STOP_ON_FAILED_DOCUMENT=1` (the server sets it from diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 897fe55db1a..2600c97751b 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -835,12 +835,12 @@ def varint(p: int) -> tuple[int, int]: def _document_path(payload) -> str: """A serialized Document's relative_path (field 1), read without parsing - its occurrences; "" when it cannot be read.""" + its occurrences; "" when it cannot be read, a path that is not UTF-8 among them.""" try: for field, value in _top_level_records(payload): if field == 1: - return bytes(value).decode("utf-8", "replace") - except (IndexError, ValueError): + return bytes(value).decode("utf-8") + except (IndexError, ValueError): # UnicodeDecodeError is a ValueError pass return "" @@ -849,16 +849,20 @@ class _Skips: """The documents one run skipped: one python-protobuf refuses (a string field that is not UTF-8, say) or one that fails to convert. Each is named once on stderr, the delta lists the named ones (`skipped_files`: the server keeps their rows and marks - them stale) and counts all of them. With `stop` the failure fails the run instead.""" + them stale) and counts all of them. With `stop` the failure fails the run instead. + So does one whose path cannot be read in a run over every document (`whole`): the + server reads a file such a delta does not name as gone and retires its rows.""" - def __init__(self, stop: bool = False) -> None: - self.stop = stop + def __init__(self, stop: bool = False, whole: bool = False) -> None: + self.stop, self.whole = stop, whole self.labels: set[str] = set() self.paths: set[str] = set() def add(self, path: str, err: Exception, index: int) -> None: if self.stop: raise err + if self.whole and not path: + raise ValueError(f"document {index} failed and its path cannot be read") from err # a document whose path cannot be read is told apart by its place in the index label = path or f"" if label in self.labels: @@ -1272,7 +1276,7 @@ def __init__( ) -> None: scip_pb2 = _ensure_scip_pb2() data = _read_index(index_path) - self._skips = _Skips(stop_on_failed_document) + self._skips = _Skips(stop_on_failed_document, whole=changed is None) self._changed = changed self._run = _prepare( data, scip_pb2, source_root, exclude_generated, path_prefix, self._skips diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 86f6f301f40..a0933f6be38 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -114,6 +114,26 @@ def test_the_server_logs_the_converters_warning_line() -> None: assert _converter().SKIPPED_WARNING == SKIPPED_WARNING +def test_a_run_over_every_document_fails_on_one_whose_path_cannot_be_read( + tmp_path: Path, +) -> None: + """The server reads a file a full run's delta does not name as gone: a failed document + whose path cannot be recovered (here not UTF-8) fails the run, and no delta is written. + A window, which names its own files, counts it and converts.""" + index = _bad_utf8_index(tmp_path) + raw = index.read_bytes() + assert raw.count(b"src/bad.cpp") == 1 + index.write_bytes(raw.replace(b"src/bad.cpp", b"src/\xffad.cpp")) + out = tmp_path / "delta.json" + proc = _run(index, out) + assert proc.returncode != 0 + assert "document 1 failed and its path cannot be read" in proc.stderr, proc.stderr + assert not out.exists() + delta = _converter().convert(str(index), {"src/a.cpp"}, [], "h" * 40, "b" * 40, source_root="") + assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] + assert delta["skipped_files"] == [] and delta["stats"]["skipped_failed"] == 1 + + def test_a_document_that_fails_to_convert_is_skipped_and_listed( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: From 3ac33f58306c36f016812c5f29bed33fbef47380 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 11:59:47 +0000 Subject: [PATCH 07/81] Write a delta that lists skipped files as version 2 An upload is applied by whichever build leads the workers. Build N-1's `code_scip_apply` ignores `skipped_files`, so it would apply such a delta, move the watermark and write no stale mark, and N would then read the old rows as current. The converter now writes `delta_version` 2 when the delta lists a skipped file, and 1 otherwise; the version goes last, since a document that fails to convert is known only once the files are written. N's worker applies both versions. N-1's applies version 1 only, so it fails such a batch and leaves the watermark. The rolling-upgrade rules gain the entry. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 12 ++++ scripts/scip_harness/README.md | 3 +- scripts/scip_harness/scip_to_delta.py | 25 ++++--- server/code/workers/scip_apply.py | 6 +- .../unit/test_code_scip_skipped_documents.py | 72 +++++++++++++++++++ tests/unit/test_scip_to_delta_skip.py | 2 + 6 files changed, 108 insertions(+), 12 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index ecb2e281d00..3ef4b800ff7 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -980,6 +980,18 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline N-1 reads as any other version. `renamed` is one more number in the pass outcome. No gate holds the rollout. +68. **A SCIP delta that lists skipped files** (`skipped_files`, written by + `scripts/scip_harness/scip_to_delta.py`) is `delta_version` 2; one that lists none + stays 1. N's `code_scip_apply` applies both and marks each skipped file stale. N-1's + applies version 1 only and ignores `skipped_files`, so it fails a version-2 batch + (`unsupported delta_version 2`) and leaves the tier's watermark, and a rollback past + N does the same; `loom code scip-retry ` applies it once N runs the + workers, as long as no later batch for that tier has applied (a retry after one + would move the watermark back). A compiler-tier worker applies the delta its own build's harness wrote. In + `tests/unit/test_code_scip_skipped_documents.py`, a converted upload with a skipped + document fails under a worker that applies version 1 only and applies with its mark + under N's. No gate holds the rollout. + ## What checks them `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 46a92a03f5a..95a431c4820 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -44,7 +44,8 @@ every document (no `--changed-files`), a failed document whose path cannot be read (one that is not UTF-8, say) fails the run: the server would read its file as gone. The server keeps that file's compiler rows and marks them stale until a later delta converts -it. With +it. A delta that lists skipped files is `delta_version` 2, which a server that +applies version 1 only refuses. With `SCIP_STOP_ON_FAILED_DOCUMENT=1` (the server sets it from `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT`) `convert_delta` passes `--stop-on-failed-document`, and such a document fails the run. An index whose diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 2600c97751b..7ad21a3d83b 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1254,10 +1254,10 @@ def _enclosing(line: int) -> tuple[str, str] | None: class DeltaStream: - """A delta produced one file at a time: `head` (version, commit, base), + """A delta produced one file at a time: `head` (commit, base), `files` (a one-shot iterator, sorted by path), then `tail()` — the - deleted paths, the skipped ones, the stats and the features, complete once - `files` is exhausted. A document that fails to parse or convert is skipped + deleted paths, the skipped ones, the stats, the features and the version, + complete once `files` is exhausted. A document that fails to parse or convert is skipped (`_Skips`), or fails the run with `stop_on_failed_document`.""" def __init__( @@ -1293,7 +1293,7 @@ def __init__( self._claims_ctor_calls = ( (changed is None or full) and self._run.src.available and self._run.is_cxx ) - self.head = {"delta_version": 1, "commit": commit, "base": base} + self.head = {"commit": commit, "base": base} self.files = self._files(data, scip_pb2, changed) def _files(self, data, scip_pb2, changed: set[str] | None): @@ -1312,14 +1312,15 @@ def _files(self, data, scip_pb2, changed: set[str] | None): yield entry def tail(self) -> dict: + # the window's files only, the server marks them; repository-relative + skipped = sorted( + f"{self._prefix}/{p}" if self._prefix else p + for p in self._skips.paths + if self._changed is None or p in self._changed + ) out: dict = { "deleted_files": self._deleted, - # the window's files only, the server marks them; repository-relative - "skipped_files": sorted( - f"{self._prefix}/{p}" if self._prefix else p - for p in self._skips.paths - if self._changed is None or p in self._changed - ), + "skipped_files": skipped, "stats": { "factory_ctor_edges": self._run.factory_edges, "skipped_generated": self._run.skipped_generated, @@ -1328,6 +1329,10 @@ def tail(self) -> dict: } if self._claims_ctor_calls: out["features"] = [CTOR_CALLS_FEATURE] + # 2 lists skipped files: a server that applies version 1 only refuses it instead of + # applying it without their stale marks. Last, since a document that fails to + # convert is known only once `files` is written. + out["delta_version"] = 2 if skipped else 1 return out diff --git a/server/code/workers/scip_apply.py b/server/code/workers/scip_apply.py index 3c9dc8b78c5..c0f08354fea 100644 --- a/server/code/workers/scip_apply.py +++ b/server/code/workers/scip_apply.py @@ -22,6 +22,10 @@ logger = logging.getLogger("loom.workers.code_scip_apply") +# The delta versions this worker applies. A version-2 delta lists skipped files, whose +# stale marks a build that applies version 1 only does not write, so that build refuses it. +DELTA_VERSIONS = (1, 2) + @dataclass class CodeScipApplyResult: @@ -98,7 +102,7 @@ async def _run(result: CodeScipApplyResult) -> None: # The uploader reads `code.scip_status`: the first bad field, not its value. where = ".".join(str(x) for x in e.errors()[0]["loc"]) or "the top" raise ValidationError(f"the batch is not a SCIP delta (at {where})") from e - if delta.delta_version != 1: + if delta.delta_version not in DELTA_VERSIONS: raise ValidationError(f"unsupported delta_version {delta.delta_version}") stats = await apply_delta( repo, org, ns, delta, tier=tier_for(str(batch.get("producer") or "")) diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index 50edc425aeb..d25af4b4502 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -148,6 +148,78 @@ async def test_a_cpp_delta_beside_a_python_one_keeps_the_python_marks( } +class _Uploads: + """`CodeRepo` for the apply worker: one complete pending batch holding `payload`.""" + + def __init__(self, payload: str) -> None: + self.payload = payload + self.statuses: list[str] = [] + self.marks: dict[str, str] = {} + self.states: dict[str, str] = {} + + async def pending_scip_batches(self, **kw: object) -> list[dict[str, object]]: + return [ + { + "org": "o", + "namespace": "n", + "batch_id": "b1", + "commit_sha": "c" * 40, + "base_sha": "", + "total_parts": 1, + "producer": "scip_harness@ci", + "created_at": None, + } + ] + + async def scip_parts(self, org: str, ns: str, batch_id: str) -> list[dict[str, object]]: + return [{"seq": 0, "payload": self.payload, "payload_hash": ""}] + + async def upsert_scip_batch(self, org: str, ns: str, batch_id: str, **kw: object) -> None: + self.statuses.append(f"{kw['status']}: {kw.get('error', '')}") + + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() + + async def set_states(self, org: str, ns: str, rows: dict[str, str]) -> None: + self.marks.update(rows) + + async def set_state(self, org: str, ns: str, key: str, value: str, detail: str = "") -> None: + self.states[key] = value + + +@pytest.mark.asyncio +@pytest.mark.parametrize("older", [True, False]) +async def test_an_upload_that_skipped_a_document_waits_for_a_worker_that_marks_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, older: bool +) -> None: + """Whichever build leads the workers applies an upload. Build N-1's worker applies + version 1 only and ignores `skipped_files`, so a delta that lists one is version 2: + under N-1 the batch fails and the watermark stays; under this build it applies and + the file is marked stale.""" + import json + + from server.code.workers import scip_apply + from tests.unit.test_scip_to_delta_skip import _bad_utf8_index, _converter + + delta = _converter().convert( + str(_bad_utf8_index(tmp_path)), None, [], "c" * 40, "", source_root="" + ) + assert delta["delta_version"] == 2 + repo = _Uploads(json.dumps(delta)) + monkeypatch.setattr("server.code.store.index.CodeRepo", lambda: repo) + monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) + if older: + monkeypatch.setattr(scip_apply, "DELTA_VERSIONS", (1,)) + await scip_apply._run(scip_apply.CodeScipApplyResult()) + if older: + assert repo.statuses == ["failed: VALIDATION_FAILED: unsupported delta_version 2"] + assert repo.marks == {} and repo.states == {} + else: + assert repo.statuses == ["applied: "] + assert repo.marks == {"scip_stale:clang:src/bad.cpp": "c" * 40} + assert repo.states == {"scip_commit": "c" * 40} + + def test_an_upload_applies_for_the_tier_whose_watermark_it_moves() -> None: from server.code.workers.scip_apply import tier_for diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index a0933f6be38..c7927f50f3e 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -63,6 +63,7 @@ def test_a_document_with_a_string_that_is_not_utf8_is_skipped_and_listed( assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] assert delta["skipped_files"] == ["src/bad.cpp"] assert delta["stats"]["skipped_failed"] == 1 + assert delta["delta_version"] == 2 assert "1 failed documents skipped" in proc.stdout # named once, though several passes over the index read it assert proc.stderr.count("warning: skipped document 'src/bad.cpp'") == 1, proc.stderr @@ -171,3 +172,4 @@ def test_a_window_lists_only_its_own_failed_documents(tmp_path: Path) -> None: delta = conv.convert(index, {"src/a.cpp"}, [], "h" * 40, "b" * 40, source_root="") assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] assert delta["skipped_files"] == [] and delta["stats"]["skipped_failed"] == 1 + assert delta["delta_version"] == 1 From 8bc15ff939f4de2b22a9e576b144da396d443287 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 12:09:44 +0000 Subject: [PATCH 08/81] Pass the apply's tier to one more stand-in; align the failure table The `apply_delta` stand-in of the tier-health test takes the `tier` keyword, and the batched-state test expects the `scip_stale:` prefix parameter that `all_state_many` binds to leave the marks out. Prettier realigns the operations guide's failure table after its widened row. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 28 ++++++++++----------- tests/unit/test_code_repos_batched_state.py | 5 +++- tests/unit/test_code_tier_health.py | 2 +- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 0a43c7aa7fc..9cd57f43866 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1257,21 +1257,21 @@ the output to read. ## Failure model -| Failure | Behaviour | Recovery | -| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `git fetch` fails | watermark unmoved; the entry's `fetch` tier records the error, its kind and fix (`tier_health`) | the next pass (supervisor backoff) | -| crash mid-commit | the commit is re-run | idempotent upserts | -| a file fails to parse | chunks without symbols, `code_files.index_error` set (a parse past `code_parse_timeout_s` or `code_parse_memory_mb` included, and one that could not run in its process) | `code.index_errors` lists them; fixed by the next change or a repair (raising either limit re-reads none) | -| every file fails to parse with `LookupError` "... is loaded from outside the interpreter's site-packages" | chunks without symbols for every file: tree-sitter or a grammar is installed where the parse process does not see it | install the tree-sitter packages into the server interpreter's own environment, not through `PYTHONPATH` or the user site | -| embedding provider down | chunks stored without vectors; lexical search still serves | `code_embed_recovery` | -| compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | -| a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | -| compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | +| Failure | Behaviour | Recovery | +| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `git fetch` fails | watermark unmoved; the entry's `fetch` tier records the error, its kind and fix (`tier_health`) | the next pass (supervisor backoff) | +| crash mid-commit | the commit is re-run | idempotent upserts | +| a file fails to parse | chunks without symbols, `code_files.index_error` set (a parse past `code_parse_timeout_s` or `code_parse_memory_mb` included, and one that could not run in its process) | `code.index_errors` lists them; fixed by the next change or a repair (raising either limit re-reads none) | +| every file fails to parse with `LookupError` "... is loaded from outside the interpreter's site-packages" | chunks without symbols for every file: tree-sitter or a grammar is installed where the parse process does not see it | install the tree-sitter packages into the server interpreter's own environment, not through `PYTHONPATH` or the user site | +| embedding provider down | chunks stored without vectors; lexical search still serves | `code_embed_recovery` | +| compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | +| a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | +| compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | | a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window (callers and impact name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | -| a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | -| GitHub rate limit | the pass ends, cursor unmoved | the next pass | -| branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | -| weekly graph stats fail | last week's ranks keep serving | the next weekly pass | +| a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | +| GitHub rate limit | the pass ends, cursor unmoved | the next pass | +| branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | +| weekly graph stats fail | last week's ranks keep serving | the next weekly pass | The code index's gauges (`loom.code.index_lag_commits`, `loom.code.stale_files`, `loom.code.tier_lag_seconds`, `loom.code.embed_backlog`, `loom.code.files_errored`) are diff --git a/tests/unit/test_code_repos_batched_state.py b/tests/unit/test_code_repos_batched_state.py index 09382adef06..4a984a9570d 100644 --- a/tests/unit/test_code_repos_batched_state.py +++ b/tests/unit/test_code_repos_batched_state.py @@ -67,7 +67,10 @@ async def test_all_state_many_reads_every_namespace_in_one_statement() -> None: out = await repo.all_state_many([("o", "a"), ("o", "b"), ("o", "empty")]) assert len(ch.sqls) == 1 assert "(org, namespace) IN {pairs:Array(Tuple(String, String))}" in ch.sqls[0] - assert ch.params[0] == {"pairs": [("o", "a"), ("o", "b"), ("o", "empty")]} + assert ch.params[0] == { + "pairs": [("o", "a"), ("o", "b"), ("o", "empty")], + "stale": "scip_stale:", + } assert out[("o", "a")]["git_head"]["value"] == "aaa" assert out[("o", "a")]["table_counts"]["detail"] == "aaa||" assert out[("o", "b")] == {"git_head": {"value": "bbb", "detail": "", "updated_at": "t"}} diff --git a/tests/unit/test_code_tier_health.py b/tests/unit/test_code_tier_health.py index f6a6149d04b..46179428112 100644 --- a/tests/unit/test_code_tier_health.py +++ b/tests/unit/test_code_tier_health.py @@ -836,7 +836,7 @@ async def test_apply_delta_records_the_apply_not_the_callers_input( if outcome != "missing": path.write_text("{" if outcome == "bad" else json.dumps({"commit": "a" * 40})) - async def apply(*_: Any) -> Any: + async def apply(*_: Any, **__: Any) -> Any: if outcome == "boom": raise RuntimeError("clickhouse down") return scip_delta.ScipApplyStats() From 03041efa329ca997c276997cbfbf8f8ca15111ed Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 18:17:55 +0000 Subject: [PATCH 09/81] Keep the rows of a file that a delta both converts and skips Two documents can cover one path, one converting and one failing. The delta then names the path in `files`, holding only the converted document's symbols, and in `skipped_files`. The apply took it through the key diff, which tombstoned each symbol only the failed document defined, and then marked the file stale. `apply_delta` now leaves such a path out of the files it applies, as it does a path that only `skipped_files` names: its rows stay as they are and the file is marked stale until a delta converts it whole. Also fix a comment: `scip_stale_paths` reads the marks by key. Signed-off-by: Kaloyan Naumov --- server/code/app/index/scip_delta.py | 5 +++- server/code/domain/index/state.py | 2 +- .../unit/test_code_scip_skipped_documents.py | 24 +++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index a2e075d0ad4..ea1ce196943 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -237,6 +237,7 @@ async def apply_delta( its deleted paths go last. `tier` is the compiler tier the delta comes from: its skipped files are marked stale under it (`_mark_stale`).""" stats = ScipApplyStats() + skipped_paths = set(delta.skipped_files) prefixes = _indexable_prefixes(org, ns) refused = _path_refusal(org, ns) @@ -257,7 +258,9 @@ def keep(path: str) -> bool: if refused(path): stats.files_skipped_excluded += 1 return False - return True + # Two documents of one path, one failed: this entry lacks what the failed one + # defined, so a key diff against it would tombstone those rows. They stay. + return path not in skipped_paths rounds = delta.rounds(APPLY_ROUND_FILES, keep) reading = False diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index c72c4faac02..6c24be489cb 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -28,7 +28,7 @@ class StateEntry(TypedDict, total=False): # to parse or convert) keeps the rows of an earlier state: `scip_stale::` # holds that delta's commit, under the tier that applied it whatever the path's suffix, # until a later delta of that tier applies or deletes the file and empties it. -# `scip_stale_paths` reads these rows by prefix; the whole-namespace reads leave them out. +# `scip_stale_paths` reads these rows by key; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's # `{"reason": ...}` detail; `code.repos` and `code.index_status` show only these, and diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index d25af4b4502..29ae6488967 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -98,6 +98,30 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( ) +@pytest.mark.asyncio +async def test_a_path_in_files_and_skipped_files_keeps_its_rows_and_is_marked( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Two documents of one path, one converted and one not: `files` holds the converted + document's symbols only, so a key diff against it would tombstone what the failed + document defined. The apply leaves the file's rows as they are and marks it.""" + apply_files = AsyncMock() + monkeypatch.setattr(scip_delta, "_apply_files", apply_files) + repo = AsyncMock() + repo.scip_stale_marks.return_value = {"src/b.cpp"} + delta = ScipDelta( + commit="c" * 40, + files=[ScipFile(path="src/both.cpp"), ScipFile(path="src/b.cpp")], + skipped_files=["src/both.cpp"], + ) + await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") + applied = [f.path for call in apply_files.await_args_list for f in call.args[4]] + assert applied == ["src/b.cpp"] + repo.set_states.assert_awaited_once_with( + "o", "n", {"scip_stale:clang:src/both.cpp": "c" * 40, "scip_stale:clang:src/b.cpp": ""} + ) + + @pytest.mark.asyncio async def test_an_apply_that_marks_and_clears_nothing_writes_nothing( monkeypatch: pytest.MonkeyPatch, From a46fdc923a1b9e20f562588e57d38796aae2ad86 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 20:39:29 +0000 Subject: [PATCH 10/81] Keep the rows of a skipped path that a delta also deletes A path listed in both `deleted_files` and `skipped_files` went to the writer as a deletion and was then marked stale. The apply now leaves a deleted path that the delta also skips out of the files it applies, as the full run's deletions already do, so its rows stay and the mark is written. Signed-off-by: Kaloyan Naumov --- server/code/app/index/scip_delta.py | 4 ++++ .../unit/test_code_scip_skipped_documents.py | 21 +++++++++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index ea1ce196943..58cf0d33609 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -272,6 +272,10 @@ def keep(path: str) -> bool: reading = False if batch is None: break + # a skipped path keeps its rows, deleted or not (the full run's rule) + batch = [f for f in batch if not (f.deleted and f.path in skipped_paths)] + if not batch: + continue refreshed.update(f.path for f in batch) await _apply_files(repo, org, ns, delta.commit, batch, stats) del batch # freed before the next round is read diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index 29ae6488967..d875a144fce 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -99,26 +99,35 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( @pytest.mark.asyncio -async def test_a_path_in_files_and_skipped_files_keeps_its_rows_and_is_marked( +async def test_a_skipped_path_that_files_or_deleted_files_name_keeps_its_rows_and_is_marked( monkeypatch: pytest.MonkeyPatch, ) -> None: """Two documents of one path, one converted and one not: `files` holds the converted document's symbols only, so a key diff against it would tombstone what the failed - document defined. The apply leaves the file's rows as they are and marks it.""" + document defined. A path in `deleted_files` that is also skipped is no deletion + either. The apply leaves such a file's rows as they are and marks it.""" apply_files = AsyncMock() monkeypatch.setattr(scip_delta, "_apply_files", apply_files) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"src/b.cpp"} + repo.scip_stale_marks.return_value = {"src/b.cpp", "src/gone.cpp"} delta = ScipDelta( commit="c" * 40, files=[ScipFile(path="src/both.cpp"), ScipFile(path="src/b.cpp")], - skipped_files=["src/both.cpp"], + deleted_files=["src/gone.cpp", "src/lost.cpp"], + skipped_files=["src/both.cpp", "src/lost.cpp"], ) await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") applied = [f.path for call in apply_files.await_args_list for f in call.args[4]] - assert applied == ["src/b.cpp"] + assert applied == ["src/b.cpp", "src/gone.cpp"] repo.set_states.assert_awaited_once_with( - "o", "n", {"scip_stale:clang:src/both.cpp": "c" * 40, "scip_stale:clang:src/b.cpp": ""} + "o", + "n", + { + "scip_stale:clang:src/both.cpp": "c" * 40, + "scip_stale:clang:src/lost.cpp": "c" * 40, + "scip_stale:clang:src/b.cpp": "", + "scip_stale:clang:src/gone.cpp": "", + }, ) From d9b4f0d52983cbb5dec654474b10ca4ee0d695c4 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sun, 29 Nov 2026 22:08:31 +0000 Subject: [PATCH 11/81] Make no constructor-call claim when a full run skipped a document A full C++ conversion that skipped a document still listed `ctor_calls` in its features, so applying it set the namespace's coverage bit. If the skipped file was the only factory caller and had no prior edge, `code.callers` had no edge to check for staleness and read the empty answer as exact. The claim is now withheld when the delta lists a skipped file. Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/README.md | 4 +-- scripts/scip_harness/scip_to_delta.py | 3 ++- tests/unit/test_scip_to_delta_skip.py | 38 ++++++++++++++++++++++++++- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 95a431c4820..19223367bb5 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -91,8 +91,8 @@ constructor inside the library template, so scip-clang records only a type reference at the template argument. The converter reads the source line under that reference (`--source-root`, default: the index's `project_root`, i.e. the checkout the harness ran in) and emits a `calls` edge to each known -constructor overload of `T`. A `--full` run claims the `ctor_calls` feature -in the delta; the server records it in `code_index_state` and `code.callers` +constructor overload of `T`. A `--full` run that skipped no document claims the `ctor_calls` +feature in the delta; the server records it in `code_index_state` and `code.callers` stops labelling a constructor's empty answer `ctor_edges_absent` for that namespace. Per-merge deltas emit the edges for their files but make no namespace-wide claim — run `--full` once to make it. diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 7ad21a3d83b..46a81e271b8 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1327,7 +1327,8 @@ def tail(self) -> dict: "skipped_failed": len(self._skips.labels), }, } - if self._claims_ctor_calls: + # a skipped document may hold a factory call: an incomplete run makes no claim + if self._claims_ctor_calls and not skipped: out["features"] = [CTOR_CALLS_FEATURE] # 2 lists skipped files: a server that applies version 1 only refuses it instead of # applying it without their stale marks. Last, since a document that fails to diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index c7927f50f3e..90ba3cc315e 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -16,7 +16,14 @@ import pytest -from tests.unit.test_scip_to_delta_cli import _CONVERTER, _add_doc, _fn, _pb +from tests.unit.test_scip_to_delta_cli import ( + _CONVERTER, + _FACTORY_SRC, + _add_doc, + _factory_index, + _fn, + _pb, +) _MARK = b"ZZBADUTF8ZZ" _LIB = _CONVERTER.parent / "lib.sh" @@ -173,3 +180,32 @@ def test_a_window_lists_only_its_own_failed_documents(tmp_path: Path) -> None: assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] assert delta["skipped_files"] == [] and delta["stats"]["skipped_failed"] == 1 assert delta["delta_version"] == 1 + + +def test_a_full_run_that_skipped_a_document_does_not_claim_constructor_calls( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """`ctor_calls` says every factory constructor call of the namespace is in the delta. + Here the only factory caller is the document that fails: with no edge from it and the + claim set, `code.callers` would read the empty answer as exact.""" + index = _factory_index(tmp_path, "cxx") + pb_index = _pb().Index() + pb_index.ParseFromString(index.read_bytes()) + _add_doc(pb_index, "src/ok.cpp", [(_fn("f", "aa"), 0)], []) + index.write_bytes(pb_index.SerializeToString()) + root = tmp_path / "checkout" + (root / "src").mkdir(parents=True) + (root / "src" / "a.cpp").write_text(_FACTORY_SRC) + conv = _converter() + real = conv._convert_document + + def convert_document(doc, run): + if doc.relative_path == "src/a.cpp": + raise KeyError("boom") + return real(doc, run) + + monkeypatch.setattr(conv, "_convert_document", convert_document) + delta = conv.convert(str(index), None, [], "h" * 40, "", source_root=str(root), full=True) + assert delta["skipped_files"] == ["src/a.cpp"] + assert delta["stats"]["factory_ctor_edges"] == 0 + assert "features" not in delta From bff33c48d20c8930b60a36fab557cc9d048da0db Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sun, 29 Nov 2026 22:10:41 +0000 Subject: [PATCH 12/81] Refuse a kept delta file of a version the build does not apply The streamed reader behind `scip-full --apply-delta` read a delta file without checking its `delta_version`, so a version this build does not apply was read as one it does. It now refuses it, as the worker does for an upload, and the list of applied versions lives in one place. Rule 68 says a kept version-2 file is applied with the CLI of the build that wrote it during a rollout or a rollback, since the previous build's CLI applies it without its skipped files. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 5 ++++- server/code/app/index/delta_file.py | 4 +++- server/code/app/index/scip_delta.py | 3 +++ server/code/workers/scip_apply.py | 6 +----- tests/unit/test_code_delta_stream.py | 15 +++++++++++++++ tests/unit/test_code_scip_skipped_documents.py | 2 +- 6 files changed, 27 insertions(+), 8 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 3ef4b800ff7..103c8096b81 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -990,7 +990,10 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline would move the watermark back). A compiler-tier worker applies the delta its own build's harness wrote. In `tests/unit/test_code_scip_skipped_documents.py`, a converted upload with a skipped document fails under a worker that applies version 1 only and applies with its mark - under N's. No gate holds the rollout. + under N's. A kept delta file (`scip-full --apply-delta`) is read by the CLI that + applies it: N-1's CLI applies a retained version-2 file without its skipped files, so + apply a kept file with the CLI of the build that wrote it, during a rollout or a + rollback. N's reader refuses a version it does not apply. No gate holds the rollout. ## What checks them diff --git a/server/code/app/index/delta_file.py b/server/code/app/index/delta_file.py index a6abc57bfb0..6c1e9f8f3ad 100644 --- a/server/code/app/index/delta_file.py +++ b/server/code/app/index/delta_file.py @@ -37,7 +37,7 @@ import pydantic_core from pydantic import TypeAdapter, ValidationError -from server.code.app.index.scip_delta import ScipDelta, ScipFile +from server.code.app.index.scip_delta import DELTA_VERSIONS, ScipDelta, ScipFile from server.code.app.index.untrusted_files import FileRefused, changed_while_read, open_regular from server.settings import settings @@ -480,4 +480,6 @@ def open_delta(path: Path, caps: DeltaCaps | None = None) -> DeltaFile: checked = ScipDelta.model_validate(parsed.header) except ValidationError as e: raise ValueError(f"delta invalid: {e.error_count()} error(s)") from None + if checked.delta_version not in DELTA_VERSIONS: + raise ValueError(f"delta invalid: unsupported delta_version {checked.delta_version}") return DeltaFile(path, stamp, checked, parsed, round_nodes=round_nodes, max_bytes=max_bytes) diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 58cf0d33609..0feada7f4d9 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -30,6 +30,9 @@ from server.workers import pass_context DELTA_VERSION = 1 +# The delta versions this build applies. A version-2 delta lists skipped files, whose +# stale marks a build that applies version 1 only does not write, so that build refuses it. +DELTA_VERSIONS = (1, 2) class ScipSymbol(BaseModel): diff --git a/server/code/workers/scip_apply.py b/server/code/workers/scip_apply.py index c0f08354fea..1060793e671 100644 --- a/server/code/workers/scip_apply.py +++ b/server/code/workers/scip_apply.py @@ -22,10 +22,6 @@ logger = logging.getLogger("loom.workers.code_scip_apply") -# The delta versions this worker applies. A version-2 delta lists skipped files, whose -# stale marks a build that applies version 1 only does not write, so that build refuses it. -DELTA_VERSIONS = (1, 2) - @dataclass class CodeScipApplyResult: @@ -75,7 +71,7 @@ async def run_pass() -> CodeScipApplyResult: async def _run(result: CodeScipApplyResult) -> None: - from server.code.app.index.scip_delta import ScipDelta, apply_delta + from server.code.app.index.scip_delta import DELTA_VERSIONS, ScipDelta, apply_delta from server.code.store.index import CodeRepo repo = CodeRepo() diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index dc4704728ba..57f2c44ceba 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -678,3 +678,18 @@ def test_a_header_past_its_caps_is_refused_before_the_entries_are_parsed( with pytest.raises(ValueError, match=r"^delta invalid: 'features'$"): open_delta(path) assert parsed == [] + + +@pytest.mark.parametrize(("version", "opens"), [(1, True), (2, True), (3, False), (0, False)]) +def test_a_delta_version_the_build_does_not_apply_is_refused( + tmp_path: Path, caps: None, version: int, opens: bool +) -> None: + """A kept delta file is read by `scip-full --apply-delta` as an upload is read by the + worker: a version this build does not apply is not read as one it does.""" + path = tmp_path / "delta.json" + _write(path, 1, delta_version=version, skipped_files=["src/bad.cpp"]) + if opens: + assert open_delta(path).skipped_files == ["src/bad.cpp"] + return + with pytest.raises(ValueError, match=rf"unsupported delta_version {version}"): + open_delta(path) diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index d875a144fce..607eebe6a20 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -242,7 +242,7 @@ async def test_an_upload_that_skipped_a_document_waits_for_a_worker_that_marks_i monkeypatch.setattr("server.code.store.index.CodeRepo", lambda: repo) monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) if older: - monkeypatch.setattr(scip_apply, "DELTA_VERSIONS", (1,)) + monkeypatch.setattr(scip_delta, "DELTA_VERSIONS", (1,)) await scip_apply._run(scip_apply.CodeScipApplyResult()) if older: assert repo.statuses == ["failed: VALIDATION_FAILED: unsupported delta_version 2"] From 41f3fd9f0119c4ab4676d586b54e4802c8eb0e48 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sun, 29 Nov 2026 22:45:40 +0000 Subject: [PATCH 13/81] Read a namespace's constructor-call claim as withdrawn while a file is stale Withholding `ctor_calls` from a delta that skipped a document does not undo a claim an earlier clean full run already made: the coverage bit stays set. A later run that skips a new file with no prior edge left `code.callers` with an empty answer it still read as exact, since the staleness read looks at served edges and this file has none. The coverage probe now counts the compiler tier as not carrying constructor calls while any file it holds is marked stale, so the answer is a lower bound until a delta converts the file and clears its mark. Rule 68 now says what the previous build's CLI does with a kept version-2 file: a skipped file's partial entry replaces its rows and no stale mark is written. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 7 ++++--- scripts/scip_harness/README.md | 6 ++++-- server/code/app/symbol/coverage.py | 8 ++++++-- tests/unit/test_code_ctor_call_edges.py | 24 ++++++++++++++++++++++++ 4 files changed, 38 insertions(+), 7 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 103c8096b81..a35ec971416 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -991,9 +991,10 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `tests/unit/test_code_scip_skipped_documents.py`, a converted upload with a skipped document fails under a worker that applies version 1 only and applies with its mark under N's. A kept delta file (`scip-full --apply-delta`) is read by the CLI that - applies it: N-1's CLI applies a retained version-2 file without its skipped files, so - apply a kept file with the CLI of the build that wrote it, during a rollout or a - rollback. N's reader refuses a version it does not apply. No gate holds the rollout. + applies it: N-1's CLI applies a retained version-2 file as version 1, so a skipped + file's partial entry replaces its rows and no stale mark is written. Apply a kept + file with the CLI of the build that wrote it, during a rollout or a rollback. N's + reader refuses a version it does not apply. No gate holds the rollout. ## What checks them diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 19223367bb5..0591ea2e486 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -94,8 +94,10 @@ i.e. the checkout the harness ran in) and emits a `calls` edge to each known constructor overload of `T`. A `--full` run that skipped no document claims the `ctor_calls` feature in the delta; the server records it in `code_index_state` and `code.callers` stops labelling a constructor's empty answer `ctor_edges_absent` for that -namespace. Per-merge deltas emit the edges for their files but make no -namespace-wide claim — run `--full` once to make it. +namespace. While a compiler-tier file is marked stale (a run skipped its document), +`code.callers` gives the label back, since that file may hold the only factory call; +the label lifts once a delta converts the file. Per-merge deltas emit the edges for +their files but make no namespace-wide claim — run `--full` once to make it. ## Go diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index 2fc24b9a6a7..32f572d4966 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -150,7 +150,9 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, """(compiler tier, parser tier): does each carry constructor calls through factories? One code_index_state read, cached 1 h per namespace like the `overrides` probe. The compiler tier says so when a full index converted with its source was applied - (`scip_ctor_calls`); the parser tier when the namespace's edge stage has converged on + (`scip_ctor_calls`) and no compiler-tier file is marked stale, since a file whose + document a run skipped may hold the only factory call and has no edge to show it; + the parser tier when the namespace's edge stage has converged on the running extractor stamp (or was indexed by it). Fail closed to (False, False): an error can only lower an answer, and that answer is kept only PROBE_ERROR_TTL_S.""" hit = _CTOR_CACHE.get((org, ns)) @@ -162,7 +164,9 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, from server.code.domain.extract.extractor_stamp import stage_stamps state = await repo.all_state(org, ns) - scip_ok = state_value(state, STATE_SCIP_CTOR_CALLS) == "1" + scip_ok = state_value(state, STATE_SCIP_CTOR_CALLS) == "1" and not ( + await repo.scip_stale_marks(org, ns, "clang") + ) edge_stamp = state_value(state, "extractor_stamp_edge") ts_ok = bool(edge_stamp) and edge_stamp == stage_stamps()["edge"] cov = (scip_ok, ts_ok) diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 8919583eae4..11dd8783713 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -585,6 +585,7 @@ def __init__( self._scip_paths = scip_paths self._edges = edges or [] self.state_reads = 0 + self.stale_marks: set[str] = set() async def symbols_by_name(self, org, ns, name, *, limit=50): s = self.symbols.get(name) @@ -607,6 +608,9 @@ async def scip_covered_paths(self, org, ns, paths): async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} + async def scip_stale_marks(self, org, ns, tier): + return set(self.stale_marks) if tier == "clang" else set() + async def all_state(self, org, ns): self.state_reads += 1 return {k: {"value": v, "detail": "", "updated_at": None} for k, v in self._state.items()} @@ -687,6 +691,26 @@ async def test_constructor_goes_back_to_exact_once_the_compiler_tier_carries_cto assert "constructor" not in out.note +async def test_a_skipped_file_withdraws_the_claim_a_clean_full_run_made(intel) -> None: + from server.code.api.models_symbol import CodeCallersInput + + # a clean full run set the bit; a later run skipped src/new.cpp, which may hold the + # only factory call and has no edge: the empty answer is a lower bound until it converts + repo = _ReadRepo(state={"scip_ctor_calls": "1"}, scip_paths={"src/A.cpp"}) + repo.stale_marks = {"src/new.cpp"} + with ( + patch.object(intel, "CodeRepo", return_value=repo), + patch.object(dispatch, "_namespace_has_override_edges", return_value=True), + ): + out = await intel.handle_code_callers( + CodeCallersInput( + org="o", namespace="n", name="DB::ConcurrentHashJoin::ConcurrentHashJoin" + ) + ) + assert out.edges == [] and out.epistemic == "lower_bound" + assert out.causes == [ep.CAUSE_CTOR] + + async def test_parser_only_seed_needs_the_edge_stage_at_the_running_stamp(intel) -> None: from server.code.api.models_symbol import CodeCallersInput from server.code.domain.extract.extractor_stamp import stage_stamps From bc2177a1923504d1cb9968e69f239dfed8440c51 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Mon, 30 Nov 2026 11:17:20 +0000 Subject: [PATCH 14/81] Read the compiler tier's stale marks outside the coverage cache The constructor-coverage probe cached the bit and the stale-mark read together for an hour, so a process that answered `exact` after a clean full run kept answering `exact` after a later delta marked an edge-free file stale. The cache now holds only the `code_index_state` read (the `scip_ctor_calls` bit and the parser stamp); while the bit is set, the marks are read on each call, which happens only for a constructor seed with no edges. A mark is then seen on the next answer, and so is its clearing by a converting delta. A failed marks read lowers that one answer and is not cached. Signed-off-by: Kaloyan Naumov --- server/code/app/symbol/coverage.py | 30 ++++++++++++++++++------- tests/unit/test_code_ctor_call_edges.py | 27 ++++++++++++++++++++++ 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index 32f572d4966..b23f69e410f 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -148,12 +148,28 @@ async def _declined_calls_for( async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, bool]: """(compiler tier, parser tier): does each carry constructor calls through factories? - One code_index_state read, cached 1 h per namespace like the `overrides` probe. The - compiler tier says so when a full index converted with its source was applied + The compiler tier says so when a full index converted with its source was applied (`scip_ctor_calls`) and no compiler-tier file is marked stale, since a file whose - document a run skipped may hold the only factory call and has no edge to show it; - the parser tier when the namespace's edge stage has converged on - the running extractor stamp (or was indexed by it). Fail closed to (False, False): an + document a run skipped may hold the only factory call and has no edge to show it. + The marks are read on every call the bit is set, outside the cache: a delta may mark + a file at any time, and a cached yes would outlive the mark. A failed marks read + says no, for that call only.""" + scip_bit, ts_ok = await _ctor_state(repo, org, ns) + if not scip_bit: + return False, ts_ok + try: + marked = await repo.scip_stale_marks(org, ns, "clang") + except Exception as e: # noqa: BLE001 — fail closed: an error can only lower an answer + logger.debug("scip stale-marks read skipped: %s", e) + return False, ts_ok + return not marked, ts_ok + + +async def _ctor_state(repo: CodeRepo, org: str, ns: str) -> tuple[bool, bool]: + """(`scip_ctor_calls` set, parser tier carries constructor calls): one + code_index_state read, cached 1 h per namespace like the `overrides` probe. The + parser tier carries them when the namespace's edge stage has converged on the + running extractor stamp (or was indexed by it). Fail closed to (False, False): an error can only lower an answer, and that answer is kept only PROBE_ERROR_TTL_S.""" hit = _CTOR_CACHE.get((org, ns)) if hit is not None: @@ -164,9 +180,7 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, from server.code.domain.extract.extractor_stamp import stage_stamps state = await repo.all_state(org, ns) - scip_ok = state_value(state, STATE_SCIP_CTOR_CALLS) == "1" and not ( - await repo.scip_stale_marks(org, ns, "clang") - ) + scip_ok = state_value(state, STATE_SCIP_CTOR_CALLS) == "1" edge_stamp = state_value(state, "extractor_stamp_edge") ts_ok = bool(edge_stamp) and edge_stamp == stage_stamps()["edge"] cov = (scip_ok, ts_ok) diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 11dd8783713..dfd3f0fae9d 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -711,6 +711,33 @@ async def test_a_skipped_file_withdraws_the_claim_a_clean_full_run_made(intel) - assert out.causes == [ep.CAUSE_CTOR] +async def test_a_mark_written_after_the_probe_is_cached_withdraws_exact(intel) -> None: + from server.code.api.models_symbol import CodeCallersInput + + # one process, no cache clear: a clean full run set the bit and the first answer is + # exact; a later delta marks src/new.cpp stale, then a converting delta clears it + repo = _ReadRepo(state={"scip_ctor_calls": "1"}, scip_paths={"src/A.cpp"}) + + async def callers() -> Any: + with ( + patch.object(intel, "CodeRepo", return_value=repo), + patch.object(dispatch, "_namespace_has_override_edges", return_value=True), + ): + return await intel.handle_code_callers( + CodeCallersInput( + org="o", namespace="n", name="DB::ConcurrentHashJoin::ConcurrentHashJoin" + ) + ) + + assert (await callers()).epistemic == "exact" + repo.stale_marks = {"src/new.cpp"} + out = await callers() + assert out.epistemic == "lower_bound" and out.causes == [ep.CAUSE_CTOR] + repo.stale_marks = set() + assert (await callers()).epistemic == "exact" + assert repo.state_reads == 1 # all three answers went through the one cached probe + + async def test_parser_only_seed_needs_the_edge_stage_at_the_running_stamp(intel) -> None: from server.code.api.models_symbol import CodeCallersInput from server.code.domain.extract.extractor_stamp import stage_stamps From 76a2b61353df6b7d215357f7ae0eef58acc85288 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 09:45:54 +0000 Subject: [PATCH 15/81] Retire a stale mark once any build applies the file The previous build applies version-1 deltas and never empties a mark. When it converts a file this build marked, it refreshes the file's compiler rows and moves the watermark, and the mark kept the file stale and constructor coverage incomplete with no later pass to clear it. scip_stale_paths and scip_stale_marks now count a mark only while no compiler-tier symbol or edge row of its file has a higher version: a delta that applies or deletes the file writes one, whichever build runs it. The integration test applies a skipped document with this build, then a clean delta with the apply the previous build runs, and checks that the file reads fresh and coverage complete, and that a mark written after the refresh counts again. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 6 +- server/code/domain/index/state.py | 4 +- server/code/store/index/symbols.py | 57 ++++++++++++++----- .../integration/test_code_scip_stale_mark.py | 52 ++++++++++++++++- 4 files changed, 101 insertions(+), 18 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 99a4e0ade1f..f19698abd7e 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1011,7 +1011,11 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline would move the watermark back). A compiler-tier worker applies the delta its own build's harness wrote. In `tests/unit/test_code_scip_skipped_documents.py`, a converted upload with a skipped document fails under a worker that applies version 1 only and applies with its mark - under N's. A kept delta file (`scip-full --apply-delta`) is read by the CLI that + under N's. N-1 never empties a mark, so when it applies a later version-1 delta that + converts a marked file, the mark stays and the watermark moves past the refresh. N + counts a mark only while no compiler-tier row of the file is newer, so that refresh + retires it; `tests/integration/test_code_scip_stale_mark.py` applies the two in that + order. A kept delta file (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI applies a retained version-2 file as version 1, so a skipped file's partial entry replaces its rows and no stale mark is written. Apply a kept file with the CLI of the build that wrote it, during a rollout or a rollback. N's diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index 6c24be489cb..ce1624b167f 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -27,7 +27,9 @@ class StateEntry(TypedDict, total=False): # A file whose compiler-tier document the tier's last delta for it skipped (it failed # to parse or convert) keeps the rows of an earlier state: `scip_stale::` # holds that delta's commit, under the tier that applied it whatever the path's suffix, -# until a later delta of that tier applies or deletes the file and empties it. +# until a later delta of that tier applies or deletes the file and empties it. A mark +# counts only while no compiler-tier row of the file is newer, so a refresh by a build +# that writes no marks retires it too. # `scip_stale_paths` reads these rows by key; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index dbc79be6b0d..c1a439438fb 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -29,6 +29,40 @@ NameCandidates = dict[str, list[tuple[str, str, str]]] +def _marks_in_force(keys: str) -> str: + """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches + `keys` and that no compiler-tier row of the file was written after. A delta that + applies or deletes a file writes such a row whichever build runs it, and a build that + predates the marks never empties one, so its refresh retires the mark here.""" + return f""" + WITH marks AS ( + -- `scip_stale::`; a path may hold ':' itself + SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path, + max(version) AS marked + FROM loom.code_index_state FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND {keys} AND state_value != '' + GROUP BY path + ), + written AS ( + SELECT path, max(version) AS refreshed + FROM ( + SELECT path, version FROM loom.code_symbols + WHERE org = {{org:String}} AND namespace = {{ns:String}} AND tier = 'scip' + AND path IN (SELECT path FROM marks) + UNION ALL + SELECT path, version FROM loom.code_edges + WHERE org = {{org:String}} AND namespace = {{ns:String}} AND tier = 'scip' + AND path IN (SELECT path FROM marks) + ) + GROUP BY path + ) + SELECT marks.path AS path + FROM marks LEFT JOIN written ON written.path = marks.path + WHERE marks.marked > ifNull(written.refreshed, 0) + """ + + def _concat_key_parts(refs: list[str]) -> str: """Keep each concatenation small even for a name spanning thousands of fields.""" while len(refs) > 1: @@ -545,7 +579,8 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left - the rows of its earlier state.""" + the rows of its earlier state, until any build applies the file again + (`_marks_in_force`).""" if not paths: return set() asked = list(dict.fromkeys(paths))[:200] @@ -565,13 +600,9 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL AND created_at <= if(endsWith(path, '.py') AND t_py > toDateTime(0), t_py, t_scip) - AND path NOT IN ( - -- `scip_stale::`; a path may hold ':' itself - SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') - FROM loom.code_index_state FINAL - WHERE org = {org:String} AND namespace = {ns:String} - AND state_key IN {marks:Array(String)} AND state_value != '' - ) + AND path NOT IN (""" + + _marks_in_force("state_key IN {marks:Array(String)}") + + """) """, {"org": org, "ns": ns, "paths": asked, "marks": marks}, ) @@ -580,15 +611,11 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: """The paths `tier` holds marked stale (`SCIP_STALE_PREFIX`): its last delta for - each skipped the file's document.""" + each skipped the file's document, and no build has applied the file since + (`_marks_in_force`).""" prefix = f"{SCIP_STALE_PREFIX}{tier}:" rows = await self._ch.query_all( - """ - SELECT substring(state_key, length({mark:String}) + 1) AS path - FROM loom.code_index_state FINAL - WHERE org = {org:String} AND namespace = {ns:String} - AND startsWith(state_key, {mark:String}) AND state_value != '' - """, + _marks_in_force("startsWith(state_key, {mark:String})"), {"org": org, "ns": ns, "mark": prefix}, ) return {str(r["path"]) for r in rows} diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index a2fcd83c6d2..13b09bc7495 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -9,7 +9,9 @@ import pytest -from server.code.app.index.scip_delta import ScipDelta, ScipFile, apply_delta +from server.code.app.index import scip_delta +from server.code.app.index.scip_delta import ScipDelta, ScipFile, ScipSymbol, apply_delta +from server.code.app.symbol.coverage import _ctor_edge_coverage from server.code.store.index import CodeRepo from server.core.ch import get_client from tests.integration._resources import unique_org @@ -49,3 +51,51 @@ async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: A ) assert await repo.scip_stale_paths(org, ns, paths) == set() assert await repo.scip_stale_marks(org, ns, "clang") == set() + + +@pytest.mark.asyncio +async def test_a_refresh_by_the_previous_build_retires_the_mark( + ch_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """Rollout order: this build marks a skipped file, then the previous build, which + writes no marks, applies a clean delta for the file and moves the watermark. Its + apply is this build's without `_mark_stale` (a version-1 delta lists no skipped + files). The file reads fresh and constructor coverage complete; a mark written after + that refresh counts again.""" + org, ns = unique_org("scip-stale-rollout"), "code-stale-rollout" + path = "src/bad.cpp" + changed = datetime.now(UTC).replace(tzinfo=None, microsecond=0) - timedelta(hours=1) + ch_client.insert( + "loom.code_files", + [[org, ns, path, changed]], + column_names=["org", "namespace", "path", "created_at"], + ) + await get_client().connect() + repo = CodeRepo() + await repo.set_state(org, ns, "scip_ctor_calls", "1") + + async def read() -> tuple[set[str], set[str], bool]: + coverage, _ = await _ctor_edge_coverage(repo, org, ns) + return ( + await repo.scip_stale_paths(org, ns, [path]), + await repo.scip_stale_marks(org, ns, "clang"), + coverage, + ) + + await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=[path]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "b" * 40) + assert await read() == ({path}, {path}, False) + + async def no_marks(*a: Any) -> None: + return None + + clean = ScipFile(path=path, symbols=[ScipSymbol(qualified_name="make", line_start=3)]) + with monkeypatch.context() as previous_build: + previous_build.setattr(scip_delta, "_mark_stale", no_marks) + await apply_delta(repo, org, ns, ScipDelta(commit="c" * 40, files=[clean]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "c" * 40) + assert await read() == (set(), set(), True) + + await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, skipped_files=[path]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "d" * 40) + assert await read() == ({path}, {path}, False) From c6d0e2ea87e83db1aabf6322f65006dfce7acce1 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 10:16:18 +0000 Subject: [PATCH 16/81] Correct the stale-mark comments: a refresh that writes no row keeps the mark [allow-secret] The `_marks_in_force` docstring and the `SCIP_STALE_PREFIX` comment said a delta that applies or deletes a file always writes a compiler-tier row. The key diff writes no row for a file whose conversion equals the rows it holds, and deleting a file that has no compiler rows writes none either. In both cases the mark keeps counting, which fails closed. Comments only. Signed-off-by: Kaloyan Naumov --- server/code/domain/index/state.py | 4 ++-- server/code/store/index/symbols.py | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index ce1624b167f..e54d1f14447 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -28,8 +28,8 @@ class StateEntry(TypedDict, total=False): # to parse or convert) keeps the rows of an earlier state: `scip_stale::` # holds that delta's commit, under the tier that applied it whatever the path's suffix, # until a later delta of that tier applies or deletes the file and empties it. A mark -# counts only while no compiler-tier row of the file is newer, so a refresh by a build -# that writes no marks retires it too. +# counts only while no compiler-tier row of the file is newer, so a refresh that writes +# a row, by a build that writes no marks, retires it too. # `scip_stale_paths` reads these rows by key; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index c1a439438fb..485896a14ba 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -32,8 +32,9 @@ def _marks_in_force(keys: str) -> str: """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches `keys` and that no compiler-tier row of the file was written after. A delta that - applies or deletes a file writes such a row whichever build runs it, and a build that - predates the marks never empties one, so its refresh retires the mark here.""" + changes or retires a file's compiler rows writes such a row whichever build runs it, and + a build that predates the marks never empties one, so its refresh retires the mark + here. A refresh that writes no row leaves the mark counting.""" return f""" WITH marks AS ( -- `scip_stale::`; a path may hold ':' itself From 9dfae11eb353b3a9a33daad6e5a54f074db0f940 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 21:14:42 +0000 Subject: [PATCH 17/81] Keep a stale mark until the apply that refreshes its file completes A round inserts its symbols and its edges separately. A retry of a skipped file whose edge insert failed after its symbol insert left a symbol row newer than the mark, so the reads dropped the mark although the edges and the watermark were never written, and constructor coverage read complete. A refresh now retires a mark only once the mark's tier has also moved its watermark after the file's newest compiler row. Every build writes the watermark after the whole apply, so the previous build's completed refresh still retires the mark. The integration test fails the edge insert of a retry and checks the mark still counts, then completes the refresh and moves the watermark. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 7 +- server/code/domain/index/state.py | 5 +- server/code/store/index/symbols.py | 38 +++++++--- .../integration/test_code_scip_stale_mark.py | 76 ++++++++++++++++++- 4 files changed, 110 insertions(+), 16 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index f19698abd7e..952267861bb 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1013,9 +1013,10 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline document fails under a worker that applies version 1 only and applies with its mark under N's. N-1 never empties a mark, so when it applies a later version-1 delta that converts a marked file, the mark stays and the watermark moves past the refresh. N - counts a mark only while no compiler-tier row of the file is newer, so that refresh - retires it; `tests/integration/test_code_scip_stale_mark.py` applies the two in that - order. A kept delta file (`scip-full --apply-delta`) is read by the CLI that + counts a mark until a compiler-tier row of the file is newer and the tier's + watermark moved after that row, so the refresh retires it once its apply completes, + and a retry whose edge insert fails after its symbol insert does not; + `tests/integration/test_code_scip_stale_mark.py` applies both orders. A kept delta file (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI applies a retained version-2 file as version 1, so a skipped file's partial entry replaces its rows and no stale mark is written. Apply a kept file with the CLI of the build that wrote it, during a rollout or a rollback. N's diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index e54d1f14447..3252d825550 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -28,8 +28,9 @@ class StateEntry(TypedDict, total=False): # to parse or convert) keeps the rows of an earlier state: `scip_stale::` # holds that delta's commit, under the tier that applied it whatever the path's suffix, # until a later delta of that tier applies or deletes the file and empties it. A mark -# counts only while no compiler-tier row of the file is newer, so a refresh that writes -# a row, by a build that writes no marks, retires it too. +# counts until a compiler-tier row of the file is newer and the tier's watermark moved +# after that row, so a completed refresh that writes a row, by a build that writes no +# marks, retires it too, and the rows of an apply that failed part way do not. # `scip_stale_paths` reads these rows by key; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 485896a14ba..7f36ae5ccc8 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -31,19 +31,27 @@ def _marks_in_force(keys: str) -> str: """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches - `keys` and that no compiler-tier row of the file was written after. A delta that - changes or retires a file's compiler rows writes such a row whichever build runs it, and - a build that predates the marks never empties one, so its refresh retires the mark - here. A refresh that writes no row leaves the mark counting.""" + `keys` and that no completed apply has refreshed. A refresh retires a mark once a + compiler-tier row of the file is newer than the mark and the mark's tier has since + moved its watermark (`TIERS`). An apply writes a round's symbols and edges in + separate inserts and the worker moves the watermark only after the whole apply, so + the rows of an apply that failed part way leave the mark counting. A delta that + changes or retires a file's compiler rows writes such a row whichever build runs it, + and a build that predates the marks never empties one, so its completed refresh + retires the mark here. A refresh that writes no row leaves the mark counting.""" + producers = ", ".join(f"'{t.producer}'" for t in TIERS) + watermarks = ", ".join(f"'{t.watermark_key}'" for t in TIERS) return f""" WITH marks AS ( -- `scip_stale::`; a path may hold ':' itself SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path, + transform(splitByChar(':', state_key)[2], [{producers}], [{watermarks}], '') + AS watermark, max(version) AS marked FROM loom.code_index_state FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} AND {keys} AND state_value != '' - GROUP BY path + GROUP BY path, watermark ), written AS ( SELECT path, max(version) AS refreshed @@ -57,10 +65,20 @@ def _marks_in_force(keys: str) -> str: AND path IN (SELECT path FROM marks) ) GROUP BY path + ), + done AS ( + -- a tier's watermark is written once the whole apply has landed + SELECT state_key AS watermark, version AS completed + FROM loom.code_index_state FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND state_key IN ({watermarks}) AND state_value != '' ) - SELECT marks.path AS path - FROM marks LEFT JOIN written ON written.path = marks.path + SELECT DISTINCT marks.path AS path + FROM marks + LEFT JOIN written ON written.path = marks.path + LEFT JOIN done ON done.watermark = marks.watermark WHERE marks.marked > ifNull(written.refreshed, 0) + OR ifNull(done.completed, 0) < ifNull(written.refreshed, 0) """ @@ -580,7 +598,7 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left - the rows of its earlier state, until any build applies the file again + the rows of its earlier state, until an apply of the file by any build completes (`_marks_in_force`).""" if not paths: return set() @@ -612,8 +630,8 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: """The paths `tier` holds marked stale (`SCIP_STALE_PREFIX`): its last delta for - each skipped the file's document, and no build has applied the file since - (`_marks_in_force`).""" + each skipped the file's document, and no apply of the file by any build has + completed since (`_marks_in_force`).""" prefix = f"{SCIP_STALE_PREFIX}{tier}:" rows = await self._ch.query_all( _marks_in_force("startsWith(state_key, {mark:String})"), diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 13b09bc7495..639760cb0e1 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -10,7 +10,13 @@ import pytest from server.code.app.index import scip_delta -from server.code.app.index.scip_delta import ScipDelta, ScipFile, ScipSymbol, apply_delta +from server.code.app.index.scip_delta import ( + ScipDelta, + ScipEdge, + ScipFile, + ScipSymbol, + apply_delta, +) from server.code.app.symbol.coverage import _ctor_edge_coverage from server.code.store.index import CodeRepo from server.core.ch import get_client @@ -99,3 +105,71 @@ async def no_marks(*a: Any) -> None: await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, skipped_files=[path]), tier="clang") await repo.set_state(org, ns, "scip_commit", "d" * 40) assert await read() == ({path}, {path}, False) + + +@pytest.mark.asyncio +async def test_a_failed_apply_keeps_the_mark( + ch_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """A retry of a skipped file inserts its symbols, then the round's edge insert + fails: the watermark stays where the skip left it. The mark still counts, so the + file reads stale and constructor coverage incomplete. The previous build's retry + that lands both inserts retires the mark once the tier's watermark moves.""" + org, ns = unique_org("scip-stale-partial"), "code-stale-partial" + path = "src/bad.cpp" + changed = datetime.now(UTC).replace(tzinfo=None, microsecond=0) - timedelta(hours=1) + ch_client.insert( + "loom.code_files", + [[org, ns, path, changed]], + column_names=["org", "namespace", "path", "created_at"], + ) + await get_client().connect() + repo = CodeRepo() + await repo.set_state(org, ns, "scip_ctor_calls", "1") + + async def read() -> tuple[set[str], set[str], bool]: + coverage, _ = await _ctor_edge_coverage(repo, org, ns) + return ( + await repo.scip_stale_paths(org, ns, [path]), + await repo.scip_stale_marks(org, ns, "clang"), + coverage, + ) + + await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=[path]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "b" * 40) + assert await read() == ({path}, {path}, False) + + retry = ScipDelta( + commit="c" * 40, + files=[ + ScipFile( + path=path, + symbols=[ScipSymbol(qualified_name="make", line_start=3, line_end=5)], + edges=[ScipEdge(from_qualified_name="make", to_qualified_name="Widget", line=4)], + ) + ], + ) + insert_rows = repo.insert_rows + + async def edges_fail(table: str, rows: list[dict[str, Any]]) -> None: + if table == "code_edges": + raise ConnectionError("edge insert failed") + await insert_rows(table, rows) + + with monkeypatch.context() as failing: + failing.setattr(repo, "insert_rows", edges_fail) + with pytest.raises(ConnectionError): + await apply_delta(repo, org, ns, retry, tier="clang") + # the round's symbol insert landed before the edge insert failed + assert (await repo.live_symbols_for_paths(org, ns, [path], "scip")).get(path) + assert await read() == ({path}, {path}, False) + + async def no_marks(*a: Any) -> None: + return None + + with monkeypatch.context() as previous_build: + previous_build.setattr(scip_delta, "_mark_stale", no_marks) + await apply_delta(repo, org, ns, retry, tier="clang") + assert await read() == ({path}, {path}, False) # rows whole, watermark not yet moved + await repo.set_state(org, ns, "scip_commit", "c" * 40) + assert await read() == (set(), set(), True) From 831373cdf6b77f77ec11ca6a0b42bd97405555d7 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 21:12:12 +0000 Subject: [PATCH 18/81] The TypeScript merge copies records instead of parsing whole indexes scip_merge_indexes.py parsed each member's index as one scip.Index, and python-protobuf refuses a whole message when any string in it is not UTF-8. scip-typescript writes such strings, so one document failed the merge, and the pass, after every member had been indexed. The merge now reads the top-level records and each document's relative_path with the converter's reader, applies the same ownership rule, and writes the kept records out byte for byte. Nothing is decoded, the parts are memory-mapped, and the converter decides what to do with a document it cannot read. The output is written beside its target and swapped in with os.replace, so --output may name one of the inputs while those are still mapped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 137 ++++++++++++--------- tests/unit/test_scip_merge_indexes.py | 98 ++++++++++++--- 2 files changed, 164 insertions(+), 71 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index c4a32d9fb21..be7e81fd44e 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -12,46 +12,43 @@ the first non-empty input. External symbols are concatenated. An all-empty input list, or only empty files, writes a zero-byte output so the converter treats it as an empty index. + +The merge reads only the top-level records and each document's +relative_path, and copies the records it keeps byte for byte. Nothing is +decoded, so a document python-protobuf would refuse (a string field that +is not UTF-8) reaches the converter, which decides what to do with it. """ from __future__ import annotations import argparse import importlib.util -import sys +import os from pathlib import Path -from typing import Any +from typing import Any, BinaryIO _HARNESS = Path(__file__).resolve().parent -_VENDOR = _HARNESS / "vendor" -def _load_ts_projects() -> Any: - spec = importlib.util.spec_from_file_location( - "scip_ts_projects", _HARNESS / "scip_ts_projects.py" - ) +def _load_harness_module(name: str) -> Any: + path = _HARNESS / f"{name}.py" + spec = importlib.util.spec_from_file_location(name, path) if spec is None or spec.loader is None: - raise SystemExit(f"cannot load {_HARNESS / 'scip_ts_projects.py'}") + raise SystemExit(f"cannot load {path}") mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod -_ts_projects = _load_ts_projects() +_ts_projects = _load_harness_module("scip_ts_projects") project_owns = _ts_projects.project_owns project_scope = _ts_projects.project_scope +_converter = _load_harness_module("scip_to_delta") +_read_index = _converter._read_index +_top_level_records = _converter._top_level_records +_document_path = _converter._document_path - -def _ensure_scip_pb2() -> Any: - if str(_VENDOR) not in sys.path: - sys.path.insert(0, str(_VENDOR)) - try: - import scip_pb2 - except Exception as e: # ImportError, or protobuf VersionError - raise SystemExit( - f"cannot load vendor/scip_pb2.py ({e}): merging indexes needs protobuf>=7.35.1" - ) from e - return scip_pb2 +_METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 def _scope_specificity(project: str) -> int: @@ -75,6 +72,38 @@ def _preferred_owner(projects: list[str], relpath: str) -> str | None: return tied[0] +def _keeps(project: str, relpath: str, owners: list[str]) -> bool: + # Keep documents this member owns. Documents followed through + # TypeScript project references into another package are + # dropped even when that package is not in this merge, so a + # subset rebuild cannot overwrite the other package's rows. + # owners is the full discovered set: a root-level tsconfig owns + # every path, so ownership still prefers a longer member that + # was not indexed in this run. + if not project_owns(project, relpath): + return False + owner = _preferred_owner(owners, relpath) + # Compare scopes, not raw project strings: a generated member + # target is dir/tsconfig.scip.json, while --known-project still + # names dir. + return owner is None or project_scope(owner) == project_scope(project) + + +def _encode_varint(value: int) -> bytes: + out = bytearray() + while value > 0x7F: + out.append(value & 0x7F | 0x80) + value >>= 7 + out.append(value) + return bytes(out) + + +def _write_record(out: BinaryIO, field: int, payload: Any) -> None: + out.write(_encode_varint(field << 3 | 2)) # wire type 2, length-delimited + out.write(_encode_varint(len(payload))) + out.write(payload) + + def merge_indexes( paths: list[Path], output: Path, @@ -83,49 +112,43 @@ def merge_indexes( ) -> None: if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") - scip_pb2 = _ensure_scip_pb2() - merged = scip_pb2.Index() - documents: dict[str, object] = {} + owners = known_projects if known_projects is not None else (projects or []) + metadata = None + documents: dict[str, Any] = {} + external_symbols: list[Any] = [] has_payload = False for i, path in enumerate(paths): - data = path.read_bytes() if path.is_file() else b"" + data = _read_index(str(path)) if path.is_file() else b"" if not data: continue - idx = scip_pb2.Index() - idx.ParseFromString(data) - if not has_payload and idx.HasField("metadata"): - merged.metadata.CopyFrom(idx.metadata) project = projects[i] if projects is not None else None - for doc in idx.documents: - rel = doc.relative_path - if projects is not None and project is not None: - # Keep documents this member owns. Documents followed through - # TypeScript project references into another package are - # dropped even when that package is not in this merge, so a - # subset rebuild cannot overwrite the other package's rows. - # known_projects is the full discovered set: a root-level - # tsconfig owns every path, so ownership still prefers a - # longer member that was not indexed in this run. - if not project_owns(project, rel): - continue - owners = known_projects if known_projects is not None else projects - owner = _preferred_owner(owners, rel) - # Compare scopes, not raw project strings: a generated - # member target is dir/tsconfig.scip.json, while - # --known-project still names dir. - if owner is not None and project_scope(owner) != project_scope(project): - continue - copied = scip_pb2.Document() - copied.CopyFrom(doc) - documents[rel] = copied - merged.external_symbols.extend(idx.external_symbols) + for field, payload in _top_level_records(data): + if field == _METADATA and not has_payload: + metadata = payload + elif field == _DOCUMENT: + rel = _document_path(payload) + if project is None or _keeps(project, rel, owners): + documents[rel] = payload + elif field == _EXTERNAL_SYMBOL: + external_symbols.append(payload) has_payload = True - if not has_payload: - output.write_bytes(b"") - return - for doc in documents.values(): - merged.documents.append(doc) - output.write_bytes(merged.SerializeToString()) + # The parts stay mapped while the output is written, so write beside the + # output and swap it in; truncating an input that is also the output would + # pull the mapped pages away. + tmp = output.with_name(output.name + ".tmp") + try: + with open(tmp, "wb") as out: + if has_payload: + if metadata is not None: + _write_record(out, _METADATA, metadata) + for payload in documents.values(): + _write_record(out, _DOCUMENT, payload) + for payload in external_symbols: + _write_record(out, _EXTERNAL_SYMBOL, payload) + os.replace(tmp, output) + except BaseException: + tmp.unlink(missing_ok=True) + raise def main(argv: list[str] | None = None) -> int: diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 45c2990217f..f663d73d288 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -2,17 +2,27 @@ from __future__ import annotations +import importlib import importlib.util +import sys from pathlib import Path +from typing import Any _SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" _SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) _MOD = importlib.util.module_from_spec(_SPEC) _SPEC.loader.exec_module(_MOD) +_VENDOR = _SCRIPT.parent / "vendor" + + +def _scip_pb2() -> Any: + if str(_VENDOR) not in sys.path: + sys.path.insert(0, str(_VENDOR)) + return importlib.import_module("scip_pb2") def _index_with_docs(relative_paths: list[str], texts: list[str] | None = None) -> bytes: - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() idx = scip_pb2.Index() idx.metadata.project_root = "file:///repo" for i, path in enumerate(relative_paths): @@ -32,7 +42,7 @@ def test_merge_concatenates_documents_and_skips_empty_parts(tmp_path: Path) -> N empty.write_bytes(b"") out = tmp_path / "merged.scip" _MOD.merge_indexes([a, empty, b], out) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) assert merged.metadata.project_root == "file:///repo" @@ -67,7 +77,7 @@ def test_merge_drops_referenced_documents_in_favor_of_the_owner(tmp_path: Path) out, projects=["packages/app", "packages/lib"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -84,7 +94,7 @@ def test_merge_without_projects_keeps_the_last_copy_of_a_path(tmp_path: Path) -> second.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["second"])) out = tmp_path / "merged.scip" _MOD.merge_indexes([first, second], out) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/lib/src/b.ts"] @@ -107,7 +117,7 @@ def test_merge_prefers_the_longest_project_scope(tmp_path: Path) -> None: out, projects=["packages/app", "packages/app/widget"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -129,7 +139,7 @@ def test_merge_keeps_documents_from_sibling_tsconfigs(tmp_path: Path) -> None: out, projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -152,7 +162,7 @@ def test_merge_sibling_tsconfigs_keep_the_last_copy_of_an_overlapping_path( out, projects=["packages/app/tsconfig.app.json", "packages/app/tsconfig.test.json"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/app/src/shared.ts"] @@ -170,7 +180,7 @@ def test_merge_drops_unowned_references_when_the_owner_is_absent(tmp_path: Path) ) out = tmp_path / "merged.scip" _MOD.merge_indexes([dependent], out, projects=["packages/app"]) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -183,7 +193,7 @@ def test_merge_keeps_documents_from_a_root_level_tsconfig(tmp_path: Path) -> Non app.write_bytes(_index_with_docs(["src/main.ts"], ["from-app"])) out = tmp_path / "merged.scip" _MOD.merge_indexes([app], out, projects=["tsconfig.app.json"]) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -206,7 +216,7 @@ def test_merge_prefers_a_nested_member_over_a_root_tsconfig(tmp_path: Path) -> N out, projects=["tsconfig.app.json", "packages/app"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -231,7 +241,7 @@ def test_merge_drops_followed_docs_from_a_root_tsconfig_when_the_member_is_absen projects=["tsconfig.app.json"], known_projects=["tsconfig.app.json", "packages/app"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -251,7 +261,7 @@ def test_merge_keeps_docs_when_project_is_a_generated_tsconfig_scip_json( projects=["packages/app/tsconfig.scip.json"], known_projects=["packages/app"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -283,7 +293,7 @@ def test_merge_drops_root_docs_when_sibling_app_configs_share_the_owner_scope( "tsconfig.app.json", ], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} @@ -312,8 +322,68 @@ def test_merge_prefers_a_one_character_member_over_a_root_tsconfig(tmp_path: Pat projects=["tsconfig.app.json", "a"], known_projects=["tsconfig.app.json", "a"], ) - scip_pb2 = _MOD._ensure_scip_pb2() + scip_pb2 = _scip_pb2() merged = scip_pb2.Index() merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} assert docs == {"src/main.ts": "from-root", "a/src/a.ts": "from-a"} + + +def test_merge_copies_a_document_whose_strings_are_not_utf8(tmp_path: Path) -> None: + """scip-typescript can write a string that is not UTF-8. The merge copies + the document as it is and leaves the decision to the converter.""" + part = tmp_path / "app.scip" + raw = _index_with_docs( + ["packages/app/src/a.ts", "packages/app/src/bad.ts", "packages/lib/src/b.ts"], + ["from-app", "ZZBADUTF8ZZ", "from-app-ref"], + ) + part.write_bytes(raw.replace(b"ZZBADUTF8ZZ", b"\xff\xfeBADUTF8ZZ")) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + [part], + out, + projects=["packages/app"], + known_projects=["packages/app", "packages/lib"], + ) + data = out.read_bytes() + assert b"\xff\xfeBADUTF8ZZ" in data + merged = _scip_pb2().Index() + merged.ParseFromString(data.replace(b"\xff\xfeBADUTF8ZZ", b"ZZBADUTF8ZZ")) + assert merged.metadata.project_root == "file:///repo" + docs = {d.relative_path: d.text for d in merged.documents} + assert docs == {"packages/app/src/a.ts": "from-app", "packages/app/src/bad.ts": "ZZBADUTF8ZZ"} + + +def test_merge_keeps_every_parts_external_symbols(tmp_path: Path) -> None: + scip_pb2 = _scip_pb2() + parts = [] + for name in ("lodash", "react"): + idx = scip_pb2.Index() + idx.metadata.project_root = "file:///repo" + idx.external_symbols.add().symbol = f"scip-typescript npm {name} 1.0.0 `index.d.ts`/" + part = tmp_path / f"{name}.scip" + part.write_bytes(idx.SerializeToString()) + parts.append(part) + out = tmp_path / "merged.scip" + _MOD.merge_indexes(parts, out) + merged = scip_pb2.Index() + merged.ParseFromString(out.read_bytes()) + assert [s.symbol for s in merged.external_symbols] == [ + "scip-typescript npm lodash 1.0.0 `index.d.ts`/", + "scip-typescript npm react 1.0.0 `index.d.ts`/", + ] + + +def test_merge_may_write_over_one_of_its_inputs(tmp_path: Path) -> None: + a = tmp_path / "a.scip" + b = tmp_path / "b.scip" + a.write_bytes(_index_with_docs(["packages/app/src/a.ts"])) + b.write_bytes(_index_with_docs(["packages/lib/src/b.ts"])) + _MOD.merge_indexes([a, b], a) + merged = _scip_pb2().Index() + merged.ParseFromString(a.read_bytes()) + assert [d.relative_path for d in merged.documents] == [ + "packages/app/src/a.ts", + "packages/lib/src/b.ts", + ] + assert not (tmp_path / "a.scip.tmp").exists() From 4d081c03c0c16c61658eeb9c8dff16f5af1ae831 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 22:02:04 +0000 Subject: [PATCH 19/81] TypeScript project filter reads window paths that are not UTF-8 git_paths prints a name as the tree stores it, and scip_ts_projects.py read the window lists as strict UTF-8. One file name with a Latin-1 byte anywhere in the window, a Markdown file included, raised UnicodeDecodeError, so the TypeScript pass exited 1 and the watermark stayed where it was on every pass. The lists are decoded with os.fsdecode, as Python decodes argv, so a path compares equal to a member path given on the command line; the selected members are written back with os.fsencode, byte for byte. The harness test commits a TypeScript edit beside caf\xe9.md and expects only the edited member to be indexed; the helper test reads and prints a member whose name is not UTF-8 with a strict stdout. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_ts_projects.py | 9 +++-- .../test_run_typescript_delta_umbrella.py | 13 +++++++ tests/unit/test_scip_ts_projects.py | 34 +++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index 48a1d08e210..079ee5b586d 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -14,6 +14,7 @@ import argparse import json +import os import re import sys from pathlib import Path @@ -277,7 +278,11 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> def _read_lines(path: Path | None) -> list[str]: if path is None or not path.is_file(): return [] - return [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + # git_paths prints a name as the tree stores it, which need not be UTF-8. + # Decode it as argv is decoded, so it compares equal to a member path + # passed on the command line and is printed back unchanged. + text = os.fsdecode(path.read_bytes()) + return [line.strip() for line in text.splitlines() if line.strip()] def main(argv: list[str] | None = None) -> int: @@ -321,7 +326,7 @@ def main(argv: list[str] | None = None) -> int: # One path per line so a member whose path contains a space is not split # by the shell when it loads the list. for project in projects: - sys.stdout.write(f"{project}\n") + sys.stdout.buffer.write(os.fsencode(project) + b"\n") return 0 diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 1890760170b..e420087ed95 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -455,3 +455,16 @@ def test_unowned_package_json_skips_the_indexer(tmp_path: Path) -> None: log = _run(tmp_path, repo, base, head) assert _runs(log) == [] assert not (tmp_path / "delta.json").exists() + + +def test_delta_with_a_non_utf8_file_name_in_the_window(tmp_path: Path) -> None: + """git prints a name as the tree stores it; a Latin-1 byte must not fail the pass.""" + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / os.fsdecode(b"packages/lib/caf\xe9.md")).write_text("notes\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "latin-1 name") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, base, head) + assert _targets(_runs(log)) == ["packages/app"] diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index 98cf5f5bab7..743c29e595c 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -4,6 +4,9 @@ import importlib.util import json +import os +import subprocess +import sys from pathlib import Path _SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_ts_projects.py" @@ -206,3 +209,34 @@ def test_delta_selects_a_root_tsconfig_for_a_root_source_change() -> None: "tsconfig.app.json", "packages/lib", ] + + +def test_filter_reads_and_prints_names_that_are_not_utf8(tmp_path: Path) -> None: + """Window lists carry raw git names; a member path is printed back byte for byte.""" + changed = tmp_path / "changed.txt" + changed.write_bytes(b"packages/caf\xe9/src/a.ts\npackages/lib/caf\xe9.md\n") + # A UTF-8 locale other than C gives stdout the strict error handler; + # pin it so the test does not depend on the host's locale. + env = {**os.environ, "PYTHONIOENCODING": "utf-8:strict"} + env.pop("PYTHONUTF8", None) + out = subprocess.run( + [ + sys.executable, + os.fsencode(_SCRIPT), + b"filter", + b"--changed-file-list", + os.fsencode(changed), + b"--", + b"packages/caf\xe9", + b"packages/lib", + ], + env=env, + check=True, + capture_output=True, + ) + assert out.stdout == b"packages/caf\xe9\n" + changed.write_bytes(b"caf\xe9.md\npackage.json\n") + for cmd in (b"has-config", b"has-shared"): + argv = [sys.executable, os.fsencode(_SCRIPT), cmd, b"--changed-file-list"] + rc = subprocess.run([*argv, os.fsencode(changed)], env=env, capture_output=True) + assert rc.returncode == 0, rc.stderr From a99d74eaeb9afa825be96ac04bc1df2e9fc2322f Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 22:07:40 +0000 Subject: [PATCH 20/81] Write the stale marks in force again before a tier moves its watermark Any later watermark write of the tier retired a mark over the rows of an apply that failed part way: a completed apply that did not name the file, a window with nothing to apply, or the delta after a failed full run, which holds only the files changed since the watermark. Every apply now reads the tier's marks and writes those still in force again with the commit they hold, and each delta worker does the same before it moves the watermark over a window with nothing to apply. The failed apply's rows stay older than the mark, so the watermark no longer retires it. `scip_stale_marks` returns each mark's commit for that write. The previous build writes no marks, so its watermark write still does. The integration tests run the three orders against ClickHouse. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 30 +- server/code/app/index/scip_delta.py | 25 +- server/code/domain/index/state.py | 5 +- server/code/store/index/symbols.py | 48 +-- server/code/workers/scip_delta.py | 3 + server/code/workers/scip_go_delta.py | 3 + server/code/workers/scip_py_delta.py | 3 + server/code/workers/scip_ts_delta.py | 3 + .../integration/test_code_scip_stale_mark.py | 282 ++++++++++++------ tests/unit/test_code_ctor_call_edges.py | 6 +- tests/unit/test_code_delta_stream.py | 4 +- tests/unit/test_code_scip_delta_worker.py | 1 + tests/unit/test_code_scip_go_delta_worker.py | 9 +- tests/unit/test_code_scip_py_delta_worker.py | 6 + .../unit/test_code_scip_skipped_documents.py | 39 ++- tests/unit/test_code_scip_ts_delta_worker.py | 8 +- tests/unit/test_scip_apply_rounds.py | 8 +- tests/unit/test_scip_entry_lock.py | 4 +- 18 files changed, 331 insertions(+), 156 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 952267861bb..ead4ecf4185 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1008,19 +1008,23 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline (`unsupported delta_version 2`) and leaves the tier's watermark, and a rollback past N does the same; `loom code scip-retry ` applies it once N runs the workers, as long as no later batch for that tier has applied (a retry after one - would move the watermark back). A compiler-tier worker applies the delta its own build's harness wrote. In - `tests/unit/test_code_scip_skipped_documents.py`, a converted upload with a skipped - document fails under a worker that applies version 1 only and applies with its mark - under N's. N-1 never empties a mark, so when it applies a later version-1 delta that - converts a marked file, the mark stays and the watermark moves past the refresh. N - counts a mark until a compiler-tier row of the file is newer and the tier's - watermark moved after that row, so the refresh retires it once its apply completes, - and a retry whose edge insert fails after its symbol insert does not; - `tests/integration/test_code_scip_stale_mark.py` applies both orders. A kept delta file (`scip-full --apply-delta`) is read by the CLI that - applies it: N-1's CLI applies a retained version-2 file as version 1, so a skipped - file's partial entry replaces its rows and no stale mark is written. Apply a kept - file with the CLI of the build that wrote it, during a rollout or a rollback. N's - reader refuses a version it does not apply. No gate holds the rollout. + would move the watermark back). A compiler-tier worker applies the delta its own build's + harness wrote. In `tests/unit/test_code_scip_skipped_documents.py`, a converted upload + with a skipped document fails under a worker that applies version 1 only and applies + with its mark under N's. N-1 never empties a mark, so when it applies a later version-1 + delta that converts a marked file, the mark stays and the watermark moves past the + refresh. N counts a mark until a compiler-tier row of the file is newer and the tier's + watermark moved after that row, so the refresh retires it once its apply completes. A + retry whose edge insert fails after its symbol insert does not retire it: N writes every + mark still in force again before it moves the tier's watermark, after an apply or over a + window with nothing to apply, so the failed retry's rows stay older than the mark. N-1 + does not, so its next watermark write for the tier retires the mark over those rows. + `tests/integration/test_code_scip_stale_mark.py` applies these orders. A kept delta file + (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI applies a + retained version-2 file as version 1, so a skipped file's partial entry replaces its + rows and no stale mark is written. Apply a kept file with the CLI of the build that + wrote it, during a rollout or a rollback. N's reader refuses a version it does not + apply. No gate holds the rollout. ## What checks them diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 0feada7f4d9..5e5dccc2d4c 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -313,20 +313,31 @@ async def _mark_stale( refreshed: set[str], ) -> None: """One write of `tier`'s rows only (`SCIP_STALE_PREFIX`): each skipped file marked at - `commit`, and the mark of each file this delta applied or deleted emptied. Another - tier's marks are never read or written, so tiers applying side by side keep both.""" + `commit`, the mark of each file this delta applied or deleted emptied, and every other + mark still in force written again with the commit it holds. Another tier's marks are + never read or written, so tiers applying side by side keep both. + + The marks are read before the caller moves the watermark. A file whose apply failed + part way is still in force here, and its mark written again stays newer than the rows + that apply left, so the watermark write cannot retire it (`_marks_in_force`).""" refreshed -= skipped - if not (skipped or refreshed): - return prefix = f"{SCIP_STALE_PREFIX}{tier}:" - marked = await repo.scip_stale_marks(org, ns, tier) if refreshed else set() - rows = {prefix + p: commit for p in sorted(skipped)} - rows.update({prefix + p: "" for p in sorted(marked & refreshed)}) + marked = await repo.scip_stale_marks(org, ns, tier) + rows = {prefix + p: c for p, c in sorted(marked.items()) if p not in refreshed} + rows.update({prefix + p: "" for p in sorted(marked.keys() & refreshed)}) + rows.update({prefix + p: commit for p in sorted(skipped)}) if rows: check_held() await repo.set_states(org, ns, rows) +async def keep_stale_marks(repo: Any, org: str, ns: str, tier: str) -> None: + """Before `tier` moves its watermark over a window with nothing to apply: its marks + still in force written again (`_mark_stale`), so the rows a failed apply left stay + older than their mark.""" + await _mark_stale(repo, org, ns, tier, "", set(), set()) + + async def _apply_files( repo: Any, org: str, ns: str, commit: str, files: list[ScipFile], stats: ScipApplyStats ) -> None: diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index 3252d825550..2de4b491ed0 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -30,7 +30,10 @@ class StateEntry(TypedDict, total=False): # until a later delta of that tier applies or deletes the file and empties it. A mark # counts until a compiler-tier row of the file is newer and the tier's watermark moved # after that row, so a completed refresh that writes a row, by a build that writes no -# marks, retires it too, and the rows of an apply that failed part way do not. +# marks, retires it too. A build that writes marks writes every mark still in force +# again before it moves a tier's watermark, so the rows of an apply that failed part way +# stay older than the mark; a watermark write by a build that writes no marks retires +# it over them. # `scip_stale_paths` reads these rows by key; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 7f36ae5ccc8..80ac7ddd8f8 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -29,16 +29,19 @@ NameCandidates = dict[str, list[tuple[str, str, str]]] -def _marks_in_force(keys: str) -> str: - """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches - `keys` and that no completed apply has refreshed. A refresh retires a mark once a - compiler-tier row of the file is newer than the mark and the mark's tier has since - moved its watermark (`TIERS`). An apply writes a round's symbols and edges in - separate inserts and the worker moves the watermark only after the whole apply, so - the rows of an apply that failed part way leave the mark counting. A delta that - changes or retires a file's compiler rows writes such a row whichever build runs it, - and a build that predates the marks never empties one, so its completed refresh - retires the mark here. A refresh that writes no row leaves the mark counting.""" +def _marks_in_force(keys: str, columns: str = "marks.path AS path") -> str: + """`columns` (`path`, and `marked_at`, the commit a mark holds) of the non-empty + `SCIP_STALE_PREFIX` rows whose `state_key` matches `keys` and that no completed apply + has refreshed. A refresh retires a mark once a compiler-tier row of the file is newer + than the mark and the mark's tier has since moved its watermark (`TIERS`). An apply + writes a round's symbols and edges in separate inserts, and this build writes every + mark still in force again before it moves a tier's watermark (`_mark_stale`), so the + rows of an apply that failed part way stay older than the mark and leave it counting. + A delta that changes or retires a file's compiler rows writes such a row whichever + build runs it, and a build that predates the marks never empties one, so its + completed refresh retires the mark here; that build's watermark write after an apply + that failed part way does too. A refresh that writes no row leaves the mark + counting.""" producers = ", ".join(f"'{t.producer}'" for t in TIERS) watermarks = ", ".join(f"'{t.watermark_key}'" for t in TIERS) return f""" @@ -47,7 +50,8 @@ def _marks_in_force(keys: str) -> str: SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path, transform(splitByChar(':', state_key)[2], [{producers}], [{watermarks}], '') AS watermark, - max(version) AS marked + max(version) AS marked, + argMax(state_value, version) AS marked_at FROM loom.code_index_state FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} AND {keys} AND state_value != '' @@ -73,7 +77,7 @@ def _marks_in_force(keys: str) -> str: WHERE org = {{org:String}} AND namespace = {{ns:String}} AND state_key IN ({watermarks}) AND state_value != '' ) - SELECT DISTINCT marks.path AS path + SELECT DISTINCT {columns} FROM marks LEFT JOIN written ON written.path = marks.path LEFT JOIN done ON done.watermark = marks.watermark @@ -598,8 +602,8 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left - the rows of its earlier state, until an apply of the file by any build completes - (`_marks_in_force`).""" + the rows of its earlier state, until a build writes a row of the file after the + mark and the tier's watermark after that row (`_marks_in_force`).""" if not paths: return set() asked = list(dict.fromkeys(paths))[:200] @@ -628,16 +632,20 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str # the query names the FRESH paths; every other asked path is stale return set(asked) - {str(r["path"]) for r in rows} - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - """The paths `tier` holds marked stale (`SCIP_STALE_PREFIX`): its last delta for - each skipped the file's document, and no apply of the file by any build has - completed since (`_marks_in_force`).""" + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + """Path -> commit of each mark `tier` holds in force (`SCIP_STALE_PREFIX`): its + last delta for the file, at that commit, skipped its document, and no build has + since written a row of the file followed by the tier's watermark + (`_marks_in_force`).""" prefix = f"{SCIP_STALE_PREFIX}{tier}:" rows = await self._ch.query_all( - _marks_in_force("startsWith(state_key, {mark:String})"), + _marks_in_force( + "startsWith(state_key, {mark:String})", + "marks.path AS path, marks.marked_at AS marked_at", + ), {"org": org, "ns": ns, "mark": prefix}, ) - return {str(r["path"]) for r in rows} + return {str(r["path"]): str(r["marked_at"]) for r in rows} async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: diff --git a/server/code/workers/scip_delta.py b/server/code/workers/scip_delta.py index 700e191ecad..d8fb5a8688a 100644 --- a/server/code/workers/scip_delta.py +++ b/server/code/workers/scip_delta.py @@ -172,6 +172,9 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipDeltaResult except FileNotFoundError: # harness legitimately exits 0 with no delta when no C++ TU changed logger.info("code_scip_delta: %s no C++ changes in window", cfg.namespace) + from server.code.app.index.scip_delta import keep_stale_marks + + await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) check_held() await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index 41eeba248d4..1ab81241b74 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -248,6 +248,9 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu modules = modules_for_window(changed, await _module_dirs(checkout)) if not modules: logger.info("code_scip_go_delta: %s no Go change in window", cfg.namespace) + from server.code.app.index.scip_delta import keep_stale_marks + + await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return not await _kept_when_nothing_built(repo, cfg) else: diff --git a/server/code/workers/scip_py_delta.py b/server/code/workers/scip_py_delta.py index 43fa63ad5e8..29500b1a916 100644 --- a/server/code/workers/scip_py_delta.py +++ b/server/code/workers/scip_py_delta.py @@ -110,6 +110,9 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipPyDeltaResu except FileNotFoundError: # the harness exits 0 with no delta when no Python file changed logger.info("code_scip_py_delta: %s no Python changes in window", cfg.namespace) + from server.code.app.index.scip_delta import keep_stale_marks + + await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return from server.code.app.index.scip_delta import apply_delta diff --git a/server/code/workers/scip_ts_delta.py b/server/code/workers/scip_ts_delta.py index 224c16c09f0..aaab6d5e86c 100644 --- a/server/code/workers/scip_ts_delta.py +++ b/server/code/workers/scip_ts_delta.py @@ -151,6 +151,9 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipTsDeltaResu except FileNotFoundError: # the harness exits 0 with no delta when no TypeScript file changed logger.info("code_scip_ts_delta: %s no TypeScript changes in window", cfg.namespace) + from server.code.app.index.scip_delta import keep_stale_marks + + await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return from server.code.app.index.scip_delta import apply_delta diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 639760cb0e1..0b4fc5211e0 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -4,12 +4,15 @@ from __future__ import annotations +import asyncio +import json from datetime import UTC, datetime, timedelta +from pathlib import Path from typing import Any import pytest -from server.code.app.index import scip_delta +from server.code.app.index import scip_delta, scip_full from server.code.app.index.scip_delta import ( ScipDelta, ScipEdge, @@ -19,14 +22,17 @@ ) from server.code.app.symbol.coverage import _ctor_edge_coverage from server.code.store.index import CodeRepo +from server.code.workers import scip_delta as delta_worker from server.core.ch import get_client from tests.integration._resources import unique_org +from tests.unit.code_fixtures import repo_config +BAD = "src/bad.cpp" +OTHER = "src/a.cpp" -@pytest.mark.asyncio -async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: Any) -> None: - org, ns = unique_org("scip-stale-mark"), "code-stale-mark" - paths = ["src/a.cpp", "src/bad.cpp"] + +async def _repo(ch_client: Any, org: str, ns: str, paths: list[str]) -> CodeRepo: + """The files, changed before the tier ran, and the constructor-calls bit set.""" changed = datetime.now(UTC).replace(tzinfo=None, microsecond=0) - timedelta(hours=1) ch_client.insert( "loom.code_files", @@ -35,28 +41,82 @@ async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: A ) await get_client().connect() repo = CodeRepo() + await repo.set_state(org, ns, "scip_ctor_calls", "1") + return repo + + +async def _read(repo: CodeRepo, org: str, ns: str) -> tuple[set[str], set[str], bool]: + """(stale paths of `BAD`, clang marks, constructor coverage complete).""" + coverage, _ = await _ctor_edge_coverage(repo, org, ns) + return ( + await repo.scip_stale_paths(org, ns, [BAD]), + set(await repo.scip_stale_marks(org, ns, "clang")), + coverage, + ) + + +async def _skip(repo: CodeRepo, org: str, ns: str) -> None: + """A delta that skips `BAD`'s document, and the watermark after it.""" + await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=[BAD]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "b" * 40) + + +def _retry() -> ScipFile: + return ScipFile( + path=BAD, + symbols=[ScipSymbol(qualified_name="make", line_start=3, line_end=5)], + edges=[ScipEdge(from_qualified_name="make", to_qualified_name="Widget", line=4)], + ) + + +def _other() -> ScipFile: + return ScipFile(path=OTHER, symbols=[ScipSymbol(qualified_name="other", line_start=1)]) + + +def _fail_edges(repo: CodeRepo, monkeypatch: pytest.MonkeyPatch) -> None: + """Every `code_edges` insert raises after the round's symbol insert landed.""" + insert_rows = repo.insert_rows + + async def edges_fail(table: str, rows: list[dict[str, Any]]) -> None: + if table == "code_edges": + raise ConnectionError("edge insert failed") + await insert_rows(table, rows) + + monkeypatch.setattr(repo, "insert_rows", edges_fail) + + +async def _failed_retry(repo: CodeRepo, org: str, ns: str, monkeypatch: pytest.MonkeyPatch) -> None: + with monkeypatch.context() as failing: + _fail_edges(repo, failing) + with pytest.raises(ConnectionError): + await apply_delta( + repo, org, ns, ScipDelta(commit="c" * 40, files=[_retry()]), tier="clang" + ) + # the round's symbol insert landed before the edge insert failed + assert (await repo.live_symbols_for_paths(org, ns, [BAD], "scip")).get(BAD) + + +@pytest.mark.asyncio +async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: Any) -> None: + org, ns = unique_org("scip-stale-mark"), "code-stale-mark" + paths = [OTHER, BAD] + repo = await _repo(ch_client, org, ns, paths) await repo.set_state(org, ns, "scip_commit", "a" * 40) # the tier ran after the change assert await repo.scip_stale_paths(org, ns, paths) == set() - skip = ScipDelta(commit="b" * 40, skipped_files=["src/bad.cpp"]) - await apply_delta(repo, org, ns, skip, tier="clang") - await repo.set_state(org, ns, "scip_commit", "b" * 40) - assert await repo.scip_stale_paths(org, ns, paths) == {"src/bad.cpp"} - assert await repo.scip_stale_marks(org, ns, "clang") == {"src/bad.cpp"} - assert await repo.scip_stale_marks(org, ns, "python") == set() + await _skip(repo, org, ns) + assert await repo.scip_stale_paths(org, ns, paths) == {BAD} + assert await repo.scip_stale_marks(org, ns, "clang") == {BAD: "b" * 40} + assert await repo.scip_stale_marks(org, ns, "python") == {} assert not any(k.startswith("scip_stale:") for k in await repo.all_state(org, ns)) many = await repo.all_state_many([(org, ns)]) assert not any(k.startswith("scip_stale:") for k in many[(org, ns)]) await apply_delta( - repo, - org, - ns, - ScipDelta(commit="c" * 40, files=[ScipFile(path="src/bad.cpp")]), - tier="clang", + repo, org, ns, ScipDelta(commit="c" * 40, files=[ScipFile(path=BAD)]), tier="clang" ) assert await repo.scip_stale_paths(org, ns, paths) == set() - assert await repo.scip_stale_marks(org, ns, "clang") == set() + assert await repo.scip_stale_marks(org, ns, "clang") == {} @pytest.mark.asyncio @@ -69,42 +129,23 @@ async def test_a_refresh_by_the_previous_build_retires_the_mark( files). The file reads fresh and constructor coverage complete; a mark written after that refresh counts again.""" org, ns = unique_org("scip-stale-rollout"), "code-stale-rollout" - path = "src/bad.cpp" - changed = datetime.now(UTC).replace(tzinfo=None, microsecond=0) - timedelta(hours=1) - ch_client.insert( - "loom.code_files", - [[org, ns, path, changed]], - column_names=["org", "namespace", "path", "created_at"], - ) - await get_client().connect() - repo = CodeRepo() - await repo.set_state(org, ns, "scip_ctor_calls", "1") - - async def read() -> tuple[set[str], set[str], bool]: - coverage, _ = await _ctor_edge_coverage(repo, org, ns) - return ( - await repo.scip_stale_paths(org, ns, [path]), - await repo.scip_stale_marks(org, ns, "clang"), - coverage, - ) - - await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=[path]), tier="clang") - await repo.set_state(org, ns, "scip_commit", "b" * 40) - assert await read() == ({path}, {path}, False) + repo = await _repo(ch_client, org, ns, [BAD]) + await _skip(repo, org, ns) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) async def no_marks(*a: Any) -> None: return None - clean = ScipFile(path=path, symbols=[ScipSymbol(qualified_name="make", line_start=3)]) + clean = ScipFile(path=BAD, symbols=[ScipSymbol(qualified_name="make", line_start=3)]) with monkeypatch.context() as previous_build: previous_build.setattr(scip_delta, "_mark_stale", no_marks) await apply_delta(repo, org, ns, ScipDelta(commit="c" * 40, files=[clean]), tier="clang") await repo.set_state(org, ns, "scip_commit", "c" * 40) - assert await read() == (set(), set(), True) + assert await _read(repo, org, ns) == (set(), set(), True) - await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, skipped_files=[path]), tier="clang") + await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, skipped_files=[BAD]), tier="clang") await repo.set_state(org, ns, "scip_commit", "d" * 40) - assert await read() == ({path}, {path}, False) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) @pytest.mark.asyncio @@ -116,60 +157,117 @@ async def test_a_failed_apply_keeps_the_mark( file reads stale and constructor coverage incomplete. The previous build's retry that lands both inserts retires the mark once the tier's watermark moves.""" org, ns = unique_org("scip-stale-partial"), "code-stale-partial" - path = "src/bad.cpp" - changed = datetime.now(UTC).replace(tzinfo=None, microsecond=0) - timedelta(hours=1) - ch_client.insert( - "loom.code_files", - [[org, ns, path, changed]], - column_names=["org", "namespace", "path", "created_at"], - ) - await get_client().connect() - repo = CodeRepo() - await repo.set_state(org, ns, "scip_ctor_calls", "1") + repo = await _repo(ch_client, org, ns, [BAD]) + await _skip(repo, org, ns) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) - async def read() -> tuple[set[str], set[str], bool]: - coverage, _ = await _ctor_edge_coverage(repo, org, ns) - return ( - await repo.scip_stale_paths(org, ns, [path]), - await repo.scip_stale_marks(org, ns, "clang"), - coverage, - ) - - await apply_delta(repo, org, ns, ScipDelta(commit="b" * 40, skipped_files=[path]), tier="clang") - await repo.set_state(org, ns, "scip_commit", "b" * 40) - assert await read() == ({path}, {path}, False) - - retry = ScipDelta( - commit="c" * 40, - files=[ - ScipFile( - path=path, - symbols=[ScipSymbol(qualified_name="make", line_start=3, line_end=5)], - edges=[ScipEdge(from_qualified_name="make", to_qualified_name="Widget", line=4)], - ) - ], - ) - insert_rows = repo.insert_rows - - async def edges_fail(table: str, rows: list[dict[str, Any]]) -> None: - if table == "code_edges": - raise ConnectionError("edge insert failed") - await insert_rows(table, rows) - - with monkeypatch.context() as failing: - failing.setattr(repo, "insert_rows", edges_fail) - with pytest.raises(ConnectionError): - await apply_delta(repo, org, ns, retry, tier="clang") - # the round's symbol insert landed before the edge insert failed - assert (await repo.live_symbols_for_paths(org, ns, [path], "scip")).get(path) - assert await read() == ({path}, {path}, False) + await _failed_retry(repo, org, ns, monkeypatch) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) async def no_marks(*a: Any) -> None: return None with monkeypatch.context() as previous_build: previous_build.setattr(scip_delta, "_mark_stale", no_marks) - await apply_delta(repo, org, ns, retry, tier="clang") - assert await read() == ({path}, {path}, False) # rows whole, watermark not yet moved + await apply_delta(repo, org, ns, ScipDelta(commit="c" * 40, files=[_retry()]), tier="clang") + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) # rows whole, watermark not moved await repo.set_state(org, ns, "scip_commit", "c" * 40) - assert await read() == (set(), set(), True) + assert await _read(repo, org, ns) == (set(), set(), True) + + +@pytest.mark.asyncio +async def test_an_apply_of_another_file_keeps_the_mark_over_a_failed_apply( + ch_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failed retry of the marked file, then a completed apply that does not name it + (an upload's next batch) and the tier's watermark after it: the mark still counts + and holds the commit that skipped the file, until an apply of the file completes.""" + org, ns = unique_org("scip-stale-other"), "code-stale-other" + repo = await _repo(ch_client, org, ns, [BAD, OTHER]) + await _skip(repo, org, ns) + await _failed_retry(repo, org, ns, monkeypatch) + + await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, files=[_other()]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "d" * 40) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + assert await repo.scip_stale_marks(org, ns, "clang") == {BAD: "b" * 40} + + await apply_delta(repo, org, ns, ScipDelta(commit="e" * 40, files=[_retry()]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "e" * 40) + assert await _read(repo, org, ns) == (set(), set(), True) + + +@pytest.mark.asyncio +async def test_a_failed_full_run_then_a_delta_without_the_file_keeps_the_mark( + ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """The weekly full run converts every file, the marked one too, and its edge insert + fails: `scip_full_at` moves, the watermark stays. The next delta window holds only + the files changed since the watermark, so it applies the other file and moves the + watermark; the marked file still reads stale.""" + org, ns = unique_org("scip-stale-full"), "code-stale-full" + repo = await _repo(ch_client, org, ns, [BAD, OTHER]) + await _skip(repo, org, ns) + + async def no_move(*a: Any, **kw: Any) -> None: + return None + + async def harness(checkout: Path, scip_clang: Path, delta_path: Path, **kw: Any): + files = [f.model_dump() for f in (_retry(), _other())] + body = json.dumps({"delta_version": 1, "commit": "c" * 40, "files": files}) + await asyncio.to_thread(delta_path.write_text, body) + return 0, "" + + with monkeypatch.context() as full_run: + full_run.setattr(scip_full, "move_checkout", no_move) + full_run.setattr(scip_full, "run_full_harness", harness) + _fail_edges(repo, full_run) + with pytest.raises(ConnectionError): + await scip_full.full_index( + repo, + repo_config(org=org, namespace=ns), + tmp_path, + tmp_path, + tmp_path / "scip-clang", + "c" * 40, + timeout_s=60, + ) + assert await repo.get_state(org, ns, scip_full.FULL_AT) + assert await repo.get_state(org, ns, "scip_commit") == "b" * 40 + assert (await repo.live_symbols_for_paths(org, ns, [BAD], "scip")).get(BAD) + + await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, files=[_other()]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "d" * 40) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + +@pytest.mark.asyncio +async def test_a_window_with_nothing_to_apply_keeps_the_mark( + ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """After a failed retry, the delta worker's next window changes no C++ file: the + harness writes no delta and the worker moves the watermark. The mark still counts.""" + org, ns = unique_org("scip-stale-nochange"), "code-stale-nochange" + repo = await _repo(ch_client, org, ns, [BAD]) + await _skip(repo, org, ns) + await _failed_retry(repo, org, ns, monkeypatch) + await repo.set_state(org, ns, "git_head", "d" * 40) + + async def no_git(*a: Any, **kw: Any) -> None: + return None + + async def no_delta(*a: Any, **kw: Any) -> tuple[int, str]: + return 0, "" # the harness writes no delta when no C++ file changed + + monkeypatch.setattr( + delta_worker, + "_resolve_paths", + lambda cfg: (tmp_path, str(tmp_path / "scip-clang"), tmp_path, None), + ) + monkeypatch.setattr(delta_worker, "git", no_git) + monkeypatch.setattr(delta_worker, "run_harness", no_delta) + result = delta_worker.CodeScipDeltaResult() + await delta_worker._run_repo(repo, repo_config(org=org, namespace=ns), result) + assert not result.errors and not result.skipped + assert await repo.get_state(org, ns, "scip_commit") == "d" * 40 + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index dfd3f0fae9d..8b05d3006fb 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -474,8 +474,8 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state.append((key, value, detail)) - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + return {} @pytest.mark.asyncio @@ -609,7 +609,7 @@ async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} async def scip_stale_marks(self, org, ns, tier): - return set(self.stale_marks) if tier == "clang" else set() + return dict.fromkeys(self.stale_marks, "a" * 40) if tier == "clang" else {} async def all_state(self, org, ns): self.state_reads += 1 diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index 3d37da1265a..1f94356fea3 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -172,8 +172,8 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def set_state(self, org: str, ns: str, key: str, value: str, **_: Any) -> None: self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + return {} @pytest.mark.asyncio diff --git a/tests/unit/test_code_scip_delta_worker.py b/tests/unit/test_code_scip_delta_worker.py index 12b4bc0fe72..b3bbc468ac8 100644 --- a/tests/unit/test_code_scip_delta_worker.py +++ b/tests/unit/test_code_scip_delta_worker.py @@ -40,6 +40,7 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit": scip_commit}.get(key, "") repo.get_state.side_effect = get_state + repo.scip_stale_marks.return_value = {} # no file marked stale return repo diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index 849f485217c..8bebbc1c4db 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -41,6 +41,7 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit_go": scip_commit_go}.get(key, "") repo.get_state.side_effect = get_state + repo.scip_stale_marks.return_value = {} # no file marked stale return repo @@ -430,6 +431,7 @@ async def set_state(org, ns, key, value, detail=""): repo.get_state.side_effect = get_state repo.set_state.side_effect = set_state repo.writes = writes + repo.scip_stale_marks.return_value = {} # no file marked stale return repo @@ -538,5 +540,10 @@ async def test_a_window_with_no_go_change_keeps_the_note(monkeypatch, tmp_path: state = {"git_head": "c" * 40, "scip_commit_go": "b" * 40, "tier_health:go": note} monkeypatch.setattr(w, "_changed_paths", AsyncMock(return_value=["README.md"])) monkeypatch.setattr(w, "modules_for_window", lambda changed, dirs: []) - await _one_pass(monkeypatch, tmp_path, state, "") + _, repo = await _one_pass(monkeypatch, tmp_path, state, "") assert state["tier_health:go"] == note and state["scip_commit_go"] == "c" * 40 + # the tier's marks in force are written again before the watermark moves + repo.scip_stale_marks.assert_awaited_once_with("org", "code-go", "go") + calls = repo.mock_calls + marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") + assert marks < calls.index(("set_state", ("org", "code-go", "scip_commit_go", "c" * 40), {})) diff --git a/tests/unit/test_code_scip_py_delta_worker.py b/tests/unit/test_code_scip_py_delta_worker.py index 16294e11fdc..20f806781d0 100644 --- a/tests/unit/test_code_scip_py_delta_worker.py +++ b/tests/unit/test_code_scip_py_delta_worker.py @@ -33,6 +33,7 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit_py": scip_commit_py}.get(key, "") repo.get_state.side_effect = get_state + repo.scip_stale_marks.return_value = {} # no file marked stale repo.live_scip_paths.return_value = set() return repo @@ -164,6 +165,11 @@ async def fake_harness(co, base, head, delta_path): res = await w.run_pass() assert res.deltas_applied == 0 and not res.errors repo.set_state.assert_awaited_with("org", "code-py", "scip_commit_py", "b" * 40) + # the tier's marks in force are written again before the watermark moves + repo.scip_stale_marks.assert_awaited_once_with("org", "code-py", "python") + calls = repo.mock_calls + marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") + assert marks < calls.index(("set_state", ("org", "code-py", "scip_commit_py", "b" * 40), {})) @pytest.mark.asyncio diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index 607eebe6a20..94f34fdb5e8 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -68,15 +68,20 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( monkeypatch: pytest.MonkeyPatch, ) -> None: """Each skipped file the entry keeps is marked under the applying tier, whatever its - suffix, and the mark of each file this delta applies or deletes is emptied. An - out-of-scope or refused path is never marked: no delta would clear it.""" + suffix, the mark of each file this delta applies or deletes is emptied, and every + other mark still in force is written again with its commit. An out-of-scope or + refused path is never marked: no delta would clear it.""" monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) monkeypatch.setattr(scip_delta, "_indexable_prefixes", lambda *a: ("src/",)) monkeypatch.setattr( scip_delta, "_path_refusal", lambda *a: lambda p: "denied" if p.endswith(".env.h") else "" ) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"src/a.cpp", "src/gone.cpp", "src/other.cpp"} + repo.scip_stale_marks.return_value = { + "src/a.cpp": "a" * 40, + "src/gone.cpp": "a" * 40, + "src/other.cpp": "b" * 40, + } delta = ScipDelta( commit="c" * 40, files=[ScipFile(path="src/a.cpp")], @@ -94,6 +99,7 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( "scip_stale:clang:src/k.cu": "c" * 40, "scip_stale:clang:src/a.cpp": "", "scip_stale:clang:src/gone.cpp": "", + "scip_stale:clang:src/other.cpp": "b" * 40, }, ) @@ -109,7 +115,7 @@ async def test_a_skipped_path_that_files_or_deleted_files_name_keeps_its_rows_an apply_files = AsyncMock() monkeypatch.setattr(scip_delta, "_apply_files", apply_files) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"src/b.cpp", "src/gone.cpp"} + repo.scip_stale_marks.return_value = {"src/b.cpp": "a" * 40, "src/gone.cpp": "a" * 40} delta = ScipDelta( commit="c" * 40, files=[ScipFile(path="src/both.cpp"), ScipFile(path="src/b.cpp")], @@ -132,14 +138,27 @@ async def test_a_skipped_path_that_files_or_deleted_files_name_keeps_its_rows_an @pytest.mark.asyncio -async def test_an_apply_that_marks_and_clears_nothing_writes_nothing( +async def test_an_apply_writes_each_mark_still_in_force_again( monkeypatch: pytest.MonkeyPatch, ) -> None: + """A mark the apply neither sets nor empties is written again with the commit it + holds, so rows a failed apply left of its file stay older than the mark when the + caller moves the watermark. A window with nothing to apply does the same before its + watermark write. With no mark in force, nothing is written.""" monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"src/other.cpp"} + repo.scip_stale_marks.return_value = {"src/other.cpp": "b" * 40} delta = ScipDelta(commit="c" * 40, files=[ScipFile(path="src/a.cpp")]) await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") + kept = {"scip_stale:clang:src/other.cpp": "b" * 40} + repo.set_states.assert_awaited_once_with("o", "n", kept) + repo.set_states.reset_mock() + await scip_delta.keep_stale_marks(repo, "o", "n", "clang") + repo.set_states.assert_awaited_once_with("o", "n", kept) + repo.set_states.reset_mock() + repo.scip_stale_marks.return_value = {} + await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") + await scip_delta.keep_stale_marks(repo, "o", "n", "clang") repo.set_states.assert_not_awaited() @@ -151,9 +170,9 @@ def __init__(self, rows: dict[str, str]) -> None: self.rows = rows self.read = asyncio.Barrier(2) - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: prefix = f"scip_stale:{tier}:" - marked = {k[len(prefix) :] for k, v in self.rows.items() if k.startswith(prefix) and v} + marked = {k[len(prefix) :]: v for k, v in self.rows.items() if k.startswith(prefix) and v} await self.read.wait() return marked @@ -210,8 +229,8 @@ async def scip_parts(self, org: str, ns: str, batch_id: str) -> list[dict[str, o async def upsert_scip_batch(self, org: str, ns: str, batch_id: str, **kw: object) -> None: self.statuses.append(f"{kw['status']}: {kw.get('error', '')}") - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + return {} async def set_states(self, org: str, ns: str, rows: dict[str, str]) -> None: self.marks.update(rows) diff --git a/tests/unit/test_code_scip_ts_delta_worker.py b/tests/unit/test_code_scip_ts_delta_worker.py index c40c12848d7..fdb41f12e7b 100644 --- a/tests/unit/test_code_scip_ts_delta_worker.py +++ b/tests/unit/test_code_scip_ts_delta_worker.py @@ -48,6 +48,7 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit_ts": scip_commit_ts}.get(key, "") repo.get_state.side_effect = get_state + repo.scip_stale_marks.return_value = {} # no file marked stale return repo @@ -190,6 +191,11 @@ async def fake_harness(co, base, head, delta_path, projects=(), **_): res = await w.run_pass() assert res.deltas_applied == 0 and not res.errors repo.set_state.assert_awaited_with("org", "code-ts", "scip_commit_ts", "b" * 40) + # the tier's marks in force are written again before the watermark moves + repo.scip_stale_marks.assert_awaited_once_with("org", "code-ts", "typescript") + calls = repo.mock_calls + marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") + assert marks < calls.index(("set_state", ("org", "code-ts", "scip_commit_ts", "b" * 40), {})) def test_registry_and_producer_field(): @@ -300,7 +306,7 @@ async def fake_apply_files(repo, org, ns, commit, files, stats): monkeypatch.setattr("server.code.app.index.scip_delta._apply_files", fake_apply_files) repo = _repo("b" * 40, "") repo.live_scip_paths.return_value = {"web/a.ts", "web/bad.ts", "web/gone.ts"} - repo.scip_stale_marks.return_value = set() + repo.scip_stale_marks.return_value = {} p1, p2 = _patched(repo, [_Cfg()]) with p1, p2: res = await w.run_pass() diff --git a/tests/unit/test_scip_apply_rounds.py b/tests/unit/test_scip_apply_rounds.py index f0ed0066be3..85e17690d3f 100644 --- a/tests/unit/test_scip_apply_rounds.py +++ b/tests/unit/test_scip_apply_rounds.py @@ -98,8 +98,8 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + return {} def test_a_delta_is_applied_in_rounds_with_one_read_and_one_insert_per_table() -> None: @@ -142,8 +142,8 @@ async def insert_rows(self, table, rows): async def set_state(self, *a: Any, **k: Any) -> None: return None - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + return {} def test_a_repository_without_round_reads_keeps_the_per_file_path() -> None: diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index 5dd1ee5d366..3da74bc8f41 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -567,8 +567,8 @@ async def insert_rows(self, table, rows) -> None: async def set_state(self, org, ns, key, value, detail="") -> None: self.states.append(key) - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - return set() + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + return {} def _delta() -> Any: From b0cef9c9378a5c3f0c6d25570da0c372c8d1ca30 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 22:29:06 +0000 Subject: [PATCH 21/81] Keep the stale marks when a Go window applies no module delta The Go worker moved its watermark after the module loop even when the harness skipped every module and wrote no delta. No apply ran, so nothing wrote the tier's marks again, and the watermark retired the mark of an earlier failed apply. It now writes the marks in force again before that watermark write when no delta was applied, as the other three delta workers do on their no-change path. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/code/workers/scip_go_delta.py | 4 +++- tests/unit/test_code_scip_go_delta_worker.py | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index 1ab81241b74..0b4c608b988 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -261,7 +261,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu log = await _run_harness(checkout, scip_commit or "--full", target, out_dir, modules, cfg) failed = module_failures(log) result.modules_skipped.extend(f"{cfg.namespace}: {line}" for line in failed) - from server.code.app.index.scip_delta import apply_delta + from server.code.app.index.scip_delta import apply_delta, keep_stale_marks # One delta per module the harness ran over (a full run: every go.mod it lists) expected = modules or await _module_dirs(checkout) @@ -277,6 +277,8 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu path.stem.replace("__", "/"), stats.model_dump(), ) + if not paths: # no module delta applied, so no apply wrote the marks again + await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) result.deltas_applied += 1 logger.info( diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index 8bebbc1c4db..2273d448540 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -547,3 +547,21 @@ async def test_a_window_with_no_go_change_keeps_the_note(monkeypatch, tmp_path: calls = repo.mock_calls marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") assert marks < calls.index(("set_state", ("org", "code-go", "scip_commit_go", "c" * 40), {})) + + +@pytest.mark.asyncio +async def test_a_window_whose_modules_the_harness_skips_keeps_the_marks_in_force( + monkeypatch, tmp_path: Path +) -> None: + """A failed apply left a mark. The next window names a module, the harness skips it + and writes no delta, so no apply writes the marks again: the worker does, before it + moves the watermark.""" + state = {"git_head": "c" * 40, "scip_commit_go": "b" * 40} + monkeypatch.setattr(w, "_changed_paths", AsyncMock(return_value=["svc/a.go"])) + monkeypatch.setattr(w, "modules_for_window", lambda changed, dirs: ["svc"]) + _, repo = await _one_pass(monkeypatch, tmp_path, state, "skip svc: scip-go failed\n") + assert state["scip_commit_go"] == "c" * 40 + repo.scip_stale_marks.assert_awaited_once_with("org", "code-go", "go") + calls = repo.mock_calls + marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") + assert marks < calls.index(("set_state", ("org", "code-go", "scip_commit_go", "c" * 40), {})) From 28684e7a62be7214cb36442cad2b9b7ae23187f5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:02:40 +0000 Subject: [PATCH 22/81] The non-UTF-8 harness test builds its window with Git plumbing The test wrote caf\xe9.md into the working tree, which macOS rejects with Errno 92 before the filter runs. It now stores the name in a commit built with hash-object, update-index --cacheinfo, write-tree and commit-tree, so no file with that name is created and git_paths prints it from the tree as in production. It still fails on main (UnicodeDecodeError in the filter) and passes with the fix. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- .../test_run_typescript_delta_umbrella.py | 50 +++++++++++++++++-- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index e420087ed95..0a2823992f5 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -457,14 +457,54 @@ def test_unowned_package_json_skips_the_indexer(tmp_path: Path) -> None: assert not (tmp_path / "delta.json").exists() +def _commit_tree_files(repo: Path, parent: str, files: dict[bytes, bytes]) -> str: + """Commit `files` on top of `parent` with Git plumbing and return the new sha. + + Nothing is written to the working tree, so a name that is not valid UTF-8 + reaches Git without the filesystem (macOS rejects it) having to create it. + """ + for name, content in files.items(): + blob = subprocess.run( + ["git", "-C", str(repo), "hash-object", "-w", "--stdin"], + input=content, + check=True, + capture_output=True, + ).stdout.strip() + entry = b"100644," + blob + b"," + name + _git(repo, "update-index", "--add", "--cacheinfo", os.fsdecode(entry)) + tree = _git(repo, "write-tree") + return _git( + repo, + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit-tree", + tree, + "-p", + parent, + "-m", + "latin-1 name", + ) + + def test_delta_with_a_non_utf8_file_name_in_the_window(tmp_path: Path) -> None: """git prints a name as the tree stores it; a Latin-1 byte must not fail the pass.""" repo = _repo(tmp_path) base = _git(repo, "rev-parse", "HEAD") - (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") - (repo / os.fsdecode(b"packages/lib/caf\xe9.md")).write_text("notes\n") - _git(repo, "add", "-A") - _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "latin-1 name") - head = _git(repo, "rev-parse", "HEAD") + head = _commit_tree_files( + repo, + base, + { + b"packages/app/src/a.ts": b"export const a = 2;\n", + b"packages/lib/caf\xe9.md": b"notes\n", + }, + ) + window = subprocess.run( + ["git", "-C", str(repo), "-c", "core.quotePath=false", "diff", "--name-only", base, head], + check=True, + capture_output=True, + ).stdout + assert b"packages/lib/caf\xe9.md" in window.split(b"\n") log = _run(tmp_path, repo, base, head) assert _targets(_runs(log)) == ["packages/app"] From a4c39d1827fb8d4f8d82159fedce09282a973083 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:10:31 +0000 Subject: [PATCH 23/81] The record reader refuses a record that runs past the end of its data _top_level_records cut a record to the bytes that were left when its declared length ran past the end of the data. The merge then wrote a fresh header for the shorter slice, so a truncated or damaged part came out as a valid document where the whole-index parse had refused it. The converter read the same slice and converted it. The reader now raises ValueError naming the offset and how far the record overruns. The merge stops with the part's name for that error and for a part that ends inside a record header. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 27 ++++++++----- scripts/scip_harness/scip_to_delta.py | 2 + tests/unit/test_scip_merge_indexes.py | 46 ++++++++++++++++++++++ tests/unit/test_scip_to_delta_cli.py | 21 ++++++++++ 4 files changed, 86 insertions(+), 10 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index be7e81fd44e..9eaf079a8f8 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -16,7 +16,9 @@ The merge reads only the top-level records and each document's relative_path, and copies the records it keeps byte for byte. Nothing is decoded, so a document python-protobuf would refuse (a string field that -is not UTF-8) reaches the converter, which decides what to do with it. +is not UTF-8) reaches the converter, which decides what to do with it. A +record that runs past the end of its part is corrupt: the merge stops and names +the part, as the whole-index parse used to. """ from __future__ import annotations @@ -122,15 +124,20 @@ def merge_indexes( if not data: continue project = projects[i] if projects is not None else None - for field, payload in _top_level_records(data): - if field == _METADATA and not has_payload: - metadata = payload - elif field == _DOCUMENT: - rel = _document_path(payload) - if project is None or _keeps(project, rel, owners): - documents[rel] = payload - elif field == _EXTERNAL_SYMBOL: - external_symbols.append(payload) + try: + for field, payload in _top_level_records(data): + if field == _METADATA and not has_payload: + metadata = payload + elif field == _DOCUMENT: + rel = _document_path(payload) + if project is None or _keeps(project, rel, owners): + documents[rel] = payload + elif field == _EXTERNAL_SYMBOL: + external_symbols.append(payload) + except ValueError as e: + raise SystemExit(f"{path}: corrupt part: {e}") from e + except IndexError as e: + raise SystemExit(f"{path}: corrupt part: it ends inside a record header") from e has_payload = True # The parts stay mapped while the output is written, so write beside the # output and swap it in; truncating an input that is also the output would diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index d4777f7e10d..c23bd7927f1 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -822,6 +822,8 @@ def varint(p: int) -> tuple[int, int]: field, wire = tag >> 3, tag & 7 if wire == 2: # length-delimited length, pos = varint(pos) + if pos + length > end: + raise ValueError(f"record at {pos} runs {pos + length - end} bytes past the end") payload = data[pos : pos + length] pos += length yield field, payload diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index f663d73d288..ba1771673b7 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -8,6 +8,8 @@ from pathlib import Path from typing import Any +import pytest + _SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" _SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) _MOD = importlib.util.module_from_spec(_SPEC) @@ -387,3 +389,47 @@ def test_merge_may_write_over_one_of_its_inputs(tmp_path: Path) -> None: "packages/lib/src/b.ts", ] assert not (tmp_path / "a.scip.tmp").exists() + + +def _last_record_header(raw: bytes) -> tuple[int, int]: + """The offset of the last document's length byte and that length. The index + ends with the document, whose length is below 128.""" + last = _scip_pb2().Index.FromString(raw).documents[-1].SerializeToString() + at = len(raw) - len(last) - 1 + assert raw[at] == len(last) < 0x80 + return at, len(last) + + +def _damaged(raw: bytes, how: str) -> bytes: + at, length = _last_record_header(raw) + if how == "length one byte too long": + return raw[:at] + bytes([length + 1]) + raw[at + 1 :] + if how == "last byte cut off": + return raw[:-1] + return raw[:at] # ends right after the record's tag + + +@pytest.mark.parametrize( + "how", ["length one byte too long", "last byte cut off", "ends inside the record header"] +) +def test_merge_rejects_a_part_whose_record_runs_past_its_end(tmp_path: Path, how: str) -> None: + """The old merge parsed the whole index and refused such a part. Copying the + record with a fresh header would turn the corruption into a valid document.""" + good = tmp_path / "good.scip" + broken = tmp_path / "broken.scip" + good.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["from-lib"])) + raw = _index_with_docs(["packages/app/src/a.ts", "packages/app/src/c.ts"], ["a", "c"]) + broken.write_bytes(_damaged(raw, how)) + out = tmp_path / "merged.scip" + with pytest.raises(SystemExit, match=r"broken\.scip: corrupt part"): + _MOD.merge_indexes([good, broken], out) + assert not out.exists() + assert not (tmp_path / "merged.scip.tmp").exists() + + +def test_the_reader_names_the_offset_of_a_record_that_runs_past_the_end() -> None: + raw = _index_with_docs(["packages/app/src/a.ts"], ["a"]) + at, _ = _last_record_header(raw) + grown = _damaged(raw, "length one byte too long") + with pytest.raises(ValueError, match=rf"record at {at + 1} runs 1 bytes past the end"): + list(_MOD._top_level_records(grown)) diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index 1e74c15ae35..4afbd9fa074 100644 --- a/tests/unit/test_scip_to_delta_cli.py +++ b/tests/unit/test_scip_to_delta_cli.py @@ -344,3 +344,24 @@ def test_only_a_scip_clang_index_claims_constructor_calls( assert (delta.get("features") == ["ctor_calls"]) is claims assert (delta["stats"]["factory_ctor_edges"] == 1) is claims assert bool(factory) is claims + + +def test_a_record_that_runs_past_the_end_of_the_index_fails_the_run(tmp_path: Path) -> None: + """The reader used to cut such a record to the bytes left, so one more byte + in a document's length made the run succeed on the document it had.""" + index = _index(tmp_path) + raw = index.read_bytes() + last = _pb().Index.FromString(raw).documents[-1].SerializeToString() + at = len(raw) - len(last) - 1 + assert raw[at] == len(last) < 0x80 + index.write_bytes(raw[:at] + bytes([len(last) + 1]) + raw[at + 1 :]) + proc = subprocess.run( + [sys.executable, str(_CONVERTER), "--index", str(index), "--commit", "h" * 40] + + ["--source-root", "", "--dry-run", str(tmp_path / "delta.json")], + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode != 0 + assert "past the end" in proc.stderr + assert not (tmp_path / "delta.json").exists() From f33c2dce390e4506aec6e709f83bfae5c59d2749 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:17:26 +0000 Subject: [PATCH 24/81] Keep a stale mark until this build applies the file A round writes its symbols and its edges in separate inserts, so neither a compiler row of the file nor a later watermark write shows that an apply of the file completed. The previous build writes both and never writes marks, so its watermark write could retire a mark over a retry that failed between the two inserts. A mark now counts while it is set; only this build's apply of the file empties it, after every round has landed. The re-stamp before each watermark write is no longer needed and is removed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 37 ++++---- server/code/app/index/scip_delta.py | 25 ++---- server/code/domain/index/state.py | 10 +-- server/code/store/index/symbols.py | 84 ++++------------- server/code/workers/scip_delta.py | 3 - server/code/workers/scip_go_delta.py | 7 +- server/code/workers/scip_py_delta.py | 3 - server/code/workers/scip_ts_delta.py | 3 - .../integration/test_code_scip_stale_mark.py | 89 ++++++++++++------- tests/unit/test_code_ctor_call_edges.py | 6 +- tests/unit/test_code_delta_stream.py | 4 +- tests/unit/test_code_scip_delta_worker.py | 1 - tests/unit/test_code_scip_go_delta_worker.py | 27 +----- tests/unit/test_code_scip_py_delta_worker.py | 6 -- .../unit/test_code_scip_skipped_documents.py | 39 +++----- tests/unit/test_code_scip_ts_delta_worker.py | 8 +- tests/unit/test_scip_apply_rounds.py | 8 +- tests/unit/test_scip_entry_lock.py | 4 +- 18 files changed, 130 insertions(+), 234 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index ead4ecf4185..8fcfbf30ef5 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1008,23 +1008,26 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline (`unsupported delta_version 2`) and leaves the tier's watermark, and a rollback past N does the same; `loom code scip-retry ` applies it once N runs the workers, as long as no later batch for that tier has applied (a retry after one - would move the watermark back). A compiler-tier worker applies the delta its own build's - harness wrote. In `tests/unit/test_code_scip_skipped_documents.py`, a converted upload - with a skipped document fails under a worker that applies version 1 only and applies - with its mark under N's. N-1 never empties a mark, so when it applies a later version-1 - delta that converts a marked file, the mark stays and the watermark moves past the - refresh. N counts a mark until a compiler-tier row of the file is newer and the tier's - watermark moved after that row, so the refresh retires it once its apply completes. A - retry whose edge insert fails after its symbol insert does not retire it: N writes every - mark still in force again before it moves the tier's watermark, after an apply or over a - window with nothing to apply, so the failed retry's rows stay older than the mark. N-1 - does not, so its next watermark write for the tier retires the mark over those rows. - `tests/integration/test_code_scip_stale_mark.py` applies these orders. A kept delta file - (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI applies a - retained version-2 file as version 1, so a skipped file's partial entry replaces its - rows and no stale mark is written. Apply a kept file with the CLI of the build that - wrote it, during a rollout or a rollback. N's reader refuses a version it does not - apply. No gate holds the rollout. + would move the watermark back). A compiler-tier worker applies the delta its own + build's harness wrote. In `tests/unit/test_code_scip_skipped_documents.py`, a + converted upload with a skipped document fails under a worker that applies version 1 + only and applies with its mark under N's. Only N's apply of a marked file empties its + mark, once every round of that apply has landed. N-1 neither reads nor empties a + mark. A round writes its symbols and its edges in separate inserts, so N-1's rows of + the file and its watermark writes cannot show that its apply of the file completed, + and N keeps counting the mark: after N-1 refreshes the file, and after an N-1 retry + whose edge insert failed followed by an N-1 watermark write over a window with no + change, the file reads stale and constructor coverage incomplete until N applies the + file again, by a delta that changes it or by N's weekly C++ full run. A rollback and + a roll forward do the same. A marked file that N-1 deletes is never applied by N + again, so its mark stays until it is deleted by hand + (`DELETE FROM loom.code_index_state WHERE state_key = 'scip_stale::'`). + `tests/integration/test_code_scip_stale_mark.py` applies these orders. A kept delta + file (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI + applies a retained version-2 file as version 1, so a skipped file's partial entry + replaces its rows and no stale mark is written. Apply a kept file with the CLI of + the build that wrote it, during a rollout or a rollback. N's reader refuses a version + it does not apply. No gate holds the rollout. ## What checks them diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 5e5dccc2d4c..0feada7f4d9 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -313,31 +313,20 @@ async def _mark_stale( refreshed: set[str], ) -> None: """One write of `tier`'s rows only (`SCIP_STALE_PREFIX`): each skipped file marked at - `commit`, the mark of each file this delta applied or deleted emptied, and every other - mark still in force written again with the commit it holds. Another tier's marks are - never read or written, so tiers applying side by side keep both. - - The marks are read before the caller moves the watermark. A file whose apply failed - part way is still in force here, and its mark written again stays newer than the rows - that apply left, so the watermark write cannot retire it (`_marks_in_force`).""" + `commit`, and the mark of each file this delta applied or deleted emptied. Another + tier's marks are never read or written, so tiers applying side by side keep both.""" refreshed -= skipped + if not (skipped or refreshed): + return prefix = f"{SCIP_STALE_PREFIX}{tier}:" - marked = await repo.scip_stale_marks(org, ns, tier) - rows = {prefix + p: c for p, c in sorted(marked.items()) if p not in refreshed} - rows.update({prefix + p: "" for p in sorted(marked.keys() & refreshed)}) - rows.update({prefix + p: commit for p in sorted(skipped)}) + marked = await repo.scip_stale_marks(org, ns, tier) if refreshed else set() + rows = {prefix + p: commit for p in sorted(skipped)} + rows.update({prefix + p: "" for p in sorted(marked & refreshed)}) if rows: check_held() await repo.set_states(org, ns, rows) -async def keep_stale_marks(repo: Any, org: str, ns: str, tier: str) -> None: - """Before `tier` moves its watermark over a window with nothing to apply: its marks - still in force written again (`_mark_stale`), so the rows a failed apply left stay - older than their mark.""" - await _mark_stale(repo, org, ns, tier, "", set(), set()) - - async def _apply_files( repo: Any, org: str, ns: str, commit: str, files: list[ScipFile], stats: ScipApplyStats ) -> None: diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index 2de4b491ed0..47a9c64ce6e 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -27,13 +27,9 @@ class StateEntry(TypedDict, total=False): # A file whose compiler-tier document the tier's last delta for it skipped (it failed # to parse or convert) keeps the rows of an earlier state: `scip_stale::` # holds that delta's commit, under the tier that applied it whatever the path's suffix, -# until a later delta of that tier applies or deletes the file and empties it. A mark -# counts until a compiler-tier row of the file is newer and the tier's watermark moved -# after that row, so a completed refresh that writes a row, by a build that writes no -# marks, retires it too. A build that writes marks writes every mark still in force -# again before it moves a tier's watermark, so the rows of an apply that failed part way -# stay older than the mark; a watermark write by a build that writes no marks retires -# it over them. +# until a later delta of that tier applies or deletes the file and empties it once the +# whole apply has landed. A build that writes no marks never empties one, and neither +# its rows of the file nor its watermark write retire it. # `scip_stale_paths` reads these rows by key; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 80ac7ddd8f8..0db81af3f9a 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -29,60 +29,18 @@ NameCandidates = dict[str, list[tuple[str, str, str]]] -def _marks_in_force(keys: str, columns: str = "marks.path AS path") -> str: - """`columns` (`path`, and `marked_at`, the commit a mark holds) of the non-empty - `SCIP_STALE_PREFIX` rows whose `state_key` matches `keys` and that no completed apply - has refreshed. A refresh retires a mark once a compiler-tier row of the file is newer - than the mark and the mark's tier has since moved its watermark (`TIERS`). An apply - writes a round's symbols and edges in separate inserts, and this build writes every - mark still in force again before it moves a tier's watermark (`_mark_stale`), so the - rows of an apply that failed part way stay older than the mark and leave it counting. - A delta that changes or retires a file's compiler rows writes such a row whichever - build runs it, and a build that predates the marks never empties one, so its - completed refresh retires the mark here; that build's watermark write after an apply - that failed part way does too. A refresh that writes no row leaves the mark - counting.""" - producers = ", ".join(f"'{t.producer}'" for t in TIERS) - watermarks = ", ".join(f"'{t.watermark_key}'" for t in TIERS) +def _marks_in_force(keys: str) -> str: + """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches + `keys`. Only an apply that writes marks empties one (`_mark_stale`), once every round + of it has landed. A round writes its symbols and its edges in separate inserts, so + the rows and the watermark write of a build that predates the marks cannot show that + its apply of the file completed: they leave the mark counting.""" return f""" - WITH marks AS ( - -- `scip_stale::`; a path may hold ':' itself - SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path, - transform(splitByChar(':', state_key)[2], [{producers}], [{watermarks}], '') - AS watermark, - max(version) AS marked, - argMax(state_value, version) AS marked_at - FROM loom.code_index_state FINAL - WHERE org = {{org:String}} AND namespace = {{ns:String}} - AND {keys} AND state_value != '' - GROUP BY path, watermark - ), - written AS ( - SELECT path, max(version) AS refreshed - FROM ( - SELECT path, version FROM loom.code_symbols - WHERE org = {{org:String}} AND namespace = {{ns:String}} AND tier = 'scip' - AND path IN (SELECT path FROM marks) - UNION ALL - SELECT path, version FROM loom.code_edges - WHERE org = {{org:String}} AND namespace = {{ns:String}} AND tier = 'scip' - AND path IN (SELECT path FROM marks) - ) - GROUP BY path - ), - done AS ( - -- a tier's watermark is written once the whole apply has landed - SELECT state_key AS watermark, version AS completed - FROM loom.code_index_state FINAL - WHERE org = {{org:String}} AND namespace = {{ns:String}} - AND state_key IN ({watermarks}) AND state_value != '' - ) - SELECT DISTINCT {columns} - FROM marks - LEFT JOIN written ON written.path = marks.path - LEFT JOIN done ON done.watermark = marks.watermark - WHERE marks.marked > ifNull(written.refreshed, 0) - OR ifNull(done.completed, 0) < ifNull(written.refreshed, 0) + -- `scip_stale::`; a path may hold ':' itself + SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path + FROM loom.code_index_state FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND {keys} AND state_value != '' """ @@ -602,8 +560,8 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left - the rows of its earlier state, until a build writes a row of the file after the - mark and the tier's watermark after that row (`_marks_in_force`).""" + the rows of its earlier state, until this build applies the file again + (`_marks_in_force`).""" if not paths: return set() asked = list(dict.fromkeys(paths))[:200] @@ -632,20 +590,16 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str # the query names the FRESH paths; every other asked path is stale return set(asked) - {str(r["path"]) for r in rows} - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: - """Path -> commit of each mark `tier` holds in force (`SCIP_STALE_PREFIX`): its - last delta for the file, at that commit, skipped its document, and no build has - since written a row of the file followed by the tier's watermark - (`_marks_in_force`).""" + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + """The paths `tier` holds marked stale (`SCIP_STALE_PREFIX`): its last delta for + each skipped the file's document, and no apply of the file by this build has + completed since (`_marks_in_force`).""" prefix = f"{SCIP_STALE_PREFIX}{tier}:" rows = await self._ch.query_all( - _marks_in_force( - "startsWith(state_key, {mark:String})", - "marks.path AS path, marks.marked_at AS marked_at", - ), + _marks_in_force("startsWith(state_key, {mark:String})"), {"org": org, "ns": ns, "mark": prefix}, ) - return {str(r["path"]): str(r["marked_at"]) for r in rows} + return {str(r["path"]) for r in rows} async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: diff --git a/server/code/workers/scip_delta.py b/server/code/workers/scip_delta.py index d8fb5a8688a..700e191ecad 100644 --- a/server/code/workers/scip_delta.py +++ b/server/code/workers/scip_delta.py @@ -172,9 +172,6 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipDeltaResult except FileNotFoundError: # harness legitimately exits 0 with no delta when no C++ TU changed logger.info("code_scip_delta: %s no C++ changes in window", cfg.namespace) - from server.code.app.index.scip_delta import keep_stale_marks - - await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) check_held() await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index 0b4c608b988..41eeba248d4 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -248,9 +248,6 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu modules = modules_for_window(changed, await _module_dirs(checkout)) if not modules: logger.info("code_scip_go_delta: %s no Go change in window", cfg.namespace) - from server.code.app.index.scip_delta import keep_stale_marks - - await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return not await _kept_when_nothing_built(repo, cfg) else: @@ -261,7 +258,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu log = await _run_harness(checkout, scip_commit or "--full", target, out_dir, modules, cfg) failed = module_failures(log) result.modules_skipped.extend(f"{cfg.namespace}: {line}" for line in failed) - from server.code.app.index.scip_delta import apply_delta, keep_stale_marks + from server.code.app.index.scip_delta import apply_delta # One delta per module the harness ran over (a full run: every go.mod it lists) expected = modules or await _module_dirs(checkout) @@ -277,8 +274,6 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu path.stem.replace("__", "/"), stats.model_dump(), ) - if not paths: # no module delta applied, so no apply wrote the marks again - await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) result.deltas_applied += 1 logger.info( diff --git a/server/code/workers/scip_py_delta.py b/server/code/workers/scip_py_delta.py index 29500b1a916..43fa63ad5e8 100644 --- a/server/code/workers/scip_py_delta.py +++ b/server/code/workers/scip_py_delta.py @@ -110,9 +110,6 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipPyDeltaResu except FileNotFoundError: # the harness exits 0 with no delta when no Python file changed logger.info("code_scip_py_delta: %s no Python changes in window", cfg.namespace) - from server.code.app.index.scip_delta import keep_stale_marks - - await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return from server.code.app.index.scip_delta import apply_delta diff --git a/server/code/workers/scip_ts_delta.py b/server/code/workers/scip_ts_delta.py index aaab6d5e86c..224c16c09f0 100644 --- a/server/code/workers/scip_ts_delta.py +++ b/server/code/workers/scip_ts_delta.py @@ -151,9 +151,6 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipTsDeltaResu except FileNotFoundError: # the harness exits 0 with no delta when no TypeScript file changed logger.info("code_scip_ts_delta: %s no TypeScript changes in window", cfg.namespace) - from server.code.app.index.scip_delta import keep_stale_marks - - await keep_stale_marks(repo, cfg.org, cfg.namespace, PRODUCER) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return from server.code.app.index.scip_delta import apply_delta diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 0b4fc5211e0..ee8e0cf5290 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -1,6 +1,6 @@ """A file whose compiler-tier document a delta skipped reads as stale, although the -tier's watermark moved past the file's last change, until a later delta applies it. The -marks stay out of the whole-namespace state reads.""" +tier's watermark moved past the file's last change, until a later delta of this build +applies it. The marks stay out of the whole-namespace state reads.""" from __future__ import annotations @@ -50,7 +50,7 @@ async def _read(repo: CodeRepo, org: str, ns: str) -> tuple[set[str], set[str], coverage, _ = await _ctor_edge_coverage(repo, org, ns) return ( await repo.scip_stale_paths(org, ns, [BAD]), - set(await repo.scip_stale_marks(org, ns, "clang")), + await repo.scip_stale_marks(org, ns, "clang"), coverage, ) @@ -73,6 +73,21 @@ def _other() -> ScipFile: return ScipFile(path=OTHER, symbols=[ScipSymbol(qualified_name="other", line_start=1)]) +async def _previous_build_apply( + repo: CodeRepo, org: str, ns: str, commit: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """The previous build's completed apply of `BAD` and its watermark write: this + build's apply without `_mark_stale` (a version-1 delta lists no skipped files).""" + + async def no_marks(*a: Any) -> None: + return None + + with monkeypatch.context() as previous_build: + previous_build.setattr(scip_delta, "_mark_stale", no_marks) + await apply_delta(repo, org, ns, ScipDelta(commit=commit, files=[_retry()]), tier="clang") + await repo.set_state(org, ns, "scip_commit", commit) + + def _fail_edges(repo: CodeRepo, monkeypatch: pytest.MonkeyPatch) -> None: """Every `code_edges` insert raises after the round's symbol insert landed.""" insert_rows = repo.insert_rows @@ -106,8 +121,8 @@ async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: A await _skip(repo, org, ns) assert await repo.scip_stale_paths(org, ns, paths) == {BAD} - assert await repo.scip_stale_marks(org, ns, "clang") == {BAD: "b" * 40} - assert await repo.scip_stale_marks(org, ns, "python") == {} + assert await repo.scip_stale_marks(org, ns, "clang") == {BAD} + assert await repo.scip_stale_marks(org, ns, "python") == set() assert not any(k.startswith("scip_stale:") for k in await repo.all_state(org, ns)) many = await repo.all_state_many([(org, ns)]) assert not any(k.startswith("scip_stale:") for k in many[(org, ns)]) @@ -116,37 +131,55 @@ async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: A repo, org, ns, ScipDelta(commit="c" * 40, files=[ScipFile(path=BAD)]), tier="clang" ) assert await repo.scip_stale_paths(org, ns, paths) == set() - assert await repo.scip_stale_marks(org, ns, "clang") == {} + assert await repo.scip_stale_marks(org, ns, "clang") == set() @pytest.mark.asyncio -async def test_a_refresh_by_the_previous_build_retires_the_mark( +async def test_a_refresh_by_the_previous_build_keeps_the_mark_until_this_build_applies_the_file( ch_client: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - """Rollout order: this build marks a skipped file, then the previous build, which - writes no marks, applies a clean delta for the file and moves the watermark. Its - apply is this build's without `_mark_stale` (a version-1 delta lists no skipped - files). The file reads fresh and constructor coverage complete; a mark written after - that refresh counts again.""" + """Rollout or rollback order: this build marks a skipped file, then the previous + build, which writes no marks, applies the file and moves the watermark. Its rows + cannot show that both inserts landed, so the mark still counts. Once this build is + back and applies the file, the mark is emptied; a later skip marks it again.""" org, ns = unique_org("scip-stale-rollout"), "code-stale-rollout" repo = await _repo(ch_client, org, ns, [BAD]) await _skip(repo, org, ns) assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) - async def no_marks(*a: Any) -> None: - return None + await _previous_build_apply(repo, org, ns, "c" * 40, monkeypatch) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) - clean = ScipFile(path=BAD, symbols=[ScipSymbol(qualified_name="make", line_start=3)]) - with monkeypatch.context() as previous_build: - previous_build.setattr(scip_delta, "_mark_stale", no_marks) - await apply_delta(repo, org, ns, ScipDelta(commit="c" * 40, files=[clean]), tier="clang") - await repo.set_state(org, ns, "scip_commit", "c" * 40) + await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, files=[_retry()]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "d" * 40) assert await _read(repo, org, ns) == (set(), set(), True) - await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, skipped_files=[BAD]), tier="clang") + await apply_delta(repo, org, ns, ScipDelta(commit="e" * 40, skipped_files=[BAD]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "e" * 40) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + +@pytest.mark.asyncio +async def test_a_watermark_write_by_the_previous_build_keeps_the_mark_over_a_failed_apply( + ch_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """This build marks a skipped file; a retry inserts its symbols and its edge insert + fails; then a worker of the previous build moves the tier's watermark over a window + that changes no C++ file. That build's no-change step is the watermark write alone. + The mark still counts until this build applies the file.""" + org, ns = unique_org("scip-stale-prev-wm"), "code-stale-prev-wm" + repo = await _repo(ch_client, org, ns, [BAD]) + await _skip(repo, org, ns) + await _failed_retry(repo, org, ns, monkeypatch) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + await repo.set_state(org, ns, "scip_commit", "d" * 40) assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + await apply_delta(repo, org, ns, ScipDelta(commit="e" * 40, files=[_retry()]), tier="clang") + await repo.set_state(org, ns, "scip_commit", "e" * 40) + assert await _read(repo, org, ns) == (set(), set(), True) + @pytest.mark.asyncio async def test_a_failed_apply_keeps_the_mark( @@ -155,7 +188,7 @@ async def test_a_failed_apply_keeps_the_mark( """A retry of a skipped file inserts its symbols, then the round's edge insert fails: the watermark stays where the skip left it. The mark still counts, so the file reads stale and constructor coverage incomplete. The previous build's retry - that lands both inserts retires the mark once the tier's watermark moves.""" + that lands both inserts and moves the watermark leaves it counting too.""" org, ns = unique_org("scip-stale-partial"), "code-stale-partial" repo = await _repo(ch_client, org, ns, [BAD]) await _skip(repo, org, ns) @@ -164,15 +197,8 @@ async def test_a_failed_apply_keeps_the_mark( await _failed_retry(repo, org, ns, monkeypatch) assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) - async def no_marks(*a: Any) -> None: - return None - - with monkeypatch.context() as previous_build: - previous_build.setattr(scip_delta, "_mark_stale", no_marks) - await apply_delta(repo, org, ns, ScipDelta(commit="c" * 40, files=[_retry()]), tier="clang") - assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) # rows whole, watermark not moved - await repo.set_state(org, ns, "scip_commit", "c" * 40) - assert await _read(repo, org, ns) == (set(), set(), True) + await _previous_build_apply(repo, org, ns, "c" * 40, monkeypatch) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) @pytest.mark.asyncio @@ -181,7 +207,7 @@ async def test_an_apply_of_another_file_keeps_the_mark_over_a_failed_apply( ) -> None: """A failed retry of the marked file, then a completed apply that does not name it (an upload's next batch) and the tier's watermark after it: the mark still counts - and holds the commit that skipped the file, until an apply of the file completes.""" + until an apply of the file completes.""" org, ns = unique_org("scip-stale-other"), "code-stale-other" repo = await _repo(ch_client, org, ns, [BAD, OTHER]) await _skip(repo, org, ns) @@ -190,7 +216,6 @@ async def test_an_apply_of_another_file_keeps_the_mark_over_a_failed_apply( await apply_delta(repo, org, ns, ScipDelta(commit="d" * 40, files=[_other()]), tier="clang") await repo.set_state(org, ns, "scip_commit", "d" * 40) assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) - assert await repo.scip_stale_marks(org, ns, "clang") == {BAD: "b" * 40} await apply_delta(repo, org, ns, ScipDelta(commit="e" * 40, files=[_retry()]), tier="clang") await repo.set_state(org, ns, "scip_commit", "e" * 40) diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 8b05d3006fb..dfd3f0fae9d 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -474,8 +474,8 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state.append((key, value, detail)) - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: - return {} + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() @pytest.mark.asyncio @@ -609,7 +609,7 @@ async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} async def scip_stale_marks(self, org, ns, tier): - return dict.fromkeys(self.stale_marks, "a" * 40) if tier == "clang" else {} + return set(self.stale_marks) if tier == "clang" else set() async def all_state(self, org, ns): self.state_reads += 1 diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index 1f94356fea3..3d37da1265a 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -172,8 +172,8 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: async def set_state(self, org: str, ns: str, key: str, value: str, **_: Any) -> None: self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: - return {} + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() @pytest.mark.asyncio diff --git a/tests/unit/test_code_scip_delta_worker.py b/tests/unit/test_code_scip_delta_worker.py index b3bbc468ac8..12b4bc0fe72 100644 --- a/tests/unit/test_code_scip_delta_worker.py +++ b/tests/unit/test_code_scip_delta_worker.py @@ -40,7 +40,6 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit": scip_commit}.get(key, "") repo.get_state.side_effect = get_state - repo.scip_stale_marks.return_value = {} # no file marked stale return repo diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index 2273d448540..849f485217c 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -41,7 +41,6 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit_go": scip_commit_go}.get(key, "") repo.get_state.side_effect = get_state - repo.scip_stale_marks.return_value = {} # no file marked stale return repo @@ -431,7 +430,6 @@ async def set_state(org, ns, key, value, detail=""): repo.get_state.side_effect = get_state repo.set_state.side_effect = set_state repo.writes = writes - repo.scip_stale_marks.return_value = {} # no file marked stale return repo @@ -540,28 +538,5 @@ async def test_a_window_with_no_go_change_keeps_the_note(monkeypatch, tmp_path: state = {"git_head": "c" * 40, "scip_commit_go": "b" * 40, "tier_health:go": note} monkeypatch.setattr(w, "_changed_paths", AsyncMock(return_value=["README.md"])) monkeypatch.setattr(w, "modules_for_window", lambda changed, dirs: []) - _, repo = await _one_pass(monkeypatch, tmp_path, state, "") + await _one_pass(monkeypatch, tmp_path, state, "") assert state["tier_health:go"] == note and state["scip_commit_go"] == "c" * 40 - # the tier's marks in force are written again before the watermark moves - repo.scip_stale_marks.assert_awaited_once_with("org", "code-go", "go") - calls = repo.mock_calls - marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") - assert marks < calls.index(("set_state", ("org", "code-go", "scip_commit_go", "c" * 40), {})) - - -@pytest.mark.asyncio -async def test_a_window_whose_modules_the_harness_skips_keeps_the_marks_in_force( - monkeypatch, tmp_path: Path -) -> None: - """A failed apply left a mark. The next window names a module, the harness skips it - and writes no delta, so no apply writes the marks again: the worker does, before it - moves the watermark.""" - state = {"git_head": "c" * 40, "scip_commit_go": "b" * 40} - monkeypatch.setattr(w, "_changed_paths", AsyncMock(return_value=["svc/a.go"])) - monkeypatch.setattr(w, "modules_for_window", lambda changed, dirs: ["svc"]) - _, repo = await _one_pass(monkeypatch, tmp_path, state, "skip svc: scip-go failed\n") - assert state["scip_commit_go"] == "c" * 40 - repo.scip_stale_marks.assert_awaited_once_with("org", "code-go", "go") - calls = repo.mock_calls - marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") - assert marks < calls.index(("set_state", ("org", "code-go", "scip_commit_go", "c" * 40), {})) diff --git a/tests/unit/test_code_scip_py_delta_worker.py b/tests/unit/test_code_scip_py_delta_worker.py index 20f806781d0..16294e11fdc 100644 --- a/tests/unit/test_code_scip_py_delta_worker.py +++ b/tests/unit/test_code_scip_py_delta_worker.py @@ -33,7 +33,6 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit_py": scip_commit_py}.get(key, "") repo.get_state.side_effect = get_state - repo.scip_stale_marks.return_value = {} # no file marked stale repo.live_scip_paths.return_value = set() return repo @@ -165,11 +164,6 @@ async def fake_harness(co, base, head, delta_path): res = await w.run_pass() assert res.deltas_applied == 0 and not res.errors repo.set_state.assert_awaited_with("org", "code-py", "scip_commit_py", "b" * 40) - # the tier's marks in force are written again before the watermark moves - repo.scip_stale_marks.assert_awaited_once_with("org", "code-py", "python") - calls = repo.mock_calls - marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") - assert marks < calls.index(("set_state", ("org", "code-py", "scip_commit_py", "b" * 40), {})) @pytest.mark.asyncio diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index 94f34fdb5e8..607eebe6a20 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -68,20 +68,15 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( monkeypatch: pytest.MonkeyPatch, ) -> None: """Each skipped file the entry keeps is marked under the applying tier, whatever its - suffix, the mark of each file this delta applies or deletes is emptied, and every - other mark still in force is written again with its commit. An out-of-scope or - refused path is never marked: no delta would clear it.""" + suffix, and the mark of each file this delta applies or deletes is emptied. An + out-of-scope or refused path is never marked: no delta would clear it.""" monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) monkeypatch.setattr(scip_delta, "_indexable_prefixes", lambda *a: ("src/",)) monkeypatch.setattr( scip_delta, "_path_refusal", lambda *a: lambda p: "denied" if p.endswith(".env.h") else "" ) repo = AsyncMock() - repo.scip_stale_marks.return_value = { - "src/a.cpp": "a" * 40, - "src/gone.cpp": "a" * 40, - "src/other.cpp": "b" * 40, - } + repo.scip_stale_marks.return_value = {"src/a.cpp", "src/gone.cpp", "src/other.cpp"} delta = ScipDelta( commit="c" * 40, files=[ScipFile(path="src/a.cpp")], @@ -99,7 +94,6 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( "scip_stale:clang:src/k.cu": "c" * 40, "scip_stale:clang:src/a.cpp": "", "scip_stale:clang:src/gone.cpp": "", - "scip_stale:clang:src/other.cpp": "b" * 40, }, ) @@ -115,7 +109,7 @@ async def test_a_skipped_path_that_files_or_deleted_files_name_keeps_its_rows_an apply_files = AsyncMock() monkeypatch.setattr(scip_delta, "_apply_files", apply_files) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"src/b.cpp": "a" * 40, "src/gone.cpp": "a" * 40} + repo.scip_stale_marks.return_value = {"src/b.cpp", "src/gone.cpp"} delta = ScipDelta( commit="c" * 40, files=[ScipFile(path="src/both.cpp"), ScipFile(path="src/b.cpp")], @@ -138,27 +132,14 @@ async def test_a_skipped_path_that_files_or_deleted_files_name_keeps_its_rows_an @pytest.mark.asyncio -async def test_an_apply_writes_each_mark_still_in_force_again( +async def test_an_apply_that_marks_and_clears_nothing_writes_nothing( monkeypatch: pytest.MonkeyPatch, ) -> None: - """A mark the apply neither sets nor empties is written again with the commit it - holds, so rows a failed apply left of its file stay older than the mark when the - caller moves the watermark. A window with nothing to apply does the same before its - watermark write. With no mark in force, nothing is written.""" monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) repo = AsyncMock() - repo.scip_stale_marks.return_value = {"src/other.cpp": "b" * 40} + repo.scip_stale_marks.return_value = {"src/other.cpp"} delta = ScipDelta(commit="c" * 40, files=[ScipFile(path="src/a.cpp")]) await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") - kept = {"scip_stale:clang:src/other.cpp": "b" * 40} - repo.set_states.assert_awaited_once_with("o", "n", kept) - repo.set_states.reset_mock() - await scip_delta.keep_stale_marks(repo, "o", "n", "clang") - repo.set_states.assert_awaited_once_with("o", "n", kept) - repo.set_states.reset_mock() - repo.scip_stale_marks.return_value = {} - await scip_delta.apply_delta(repo, "o", "n", delta, tier="clang") - await scip_delta.keep_stale_marks(repo, "o", "n", "clang") repo.set_states.assert_not_awaited() @@ -170,9 +151,9 @@ def __init__(self, rows: dict[str, str]) -> None: self.rows = rows self.read = asyncio.Barrier(2) - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: prefix = f"scip_stale:{tier}:" - marked = {k[len(prefix) :]: v for k, v in self.rows.items() if k.startswith(prefix) and v} + marked = {k[len(prefix) :] for k, v in self.rows.items() if k.startswith(prefix) and v} await self.read.wait() return marked @@ -229,8 +210,8 @@ async def scip_parts(self, org: str, ns: str, batch_id: str) -> list[dict[str, o async def upsert_scip_batch(self, org: str, ns: str, batch_id: str, **kw: object) -> None: self.statuses.append(f"{kw['status']}: {kw.get('error', '')}") - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: - return {} + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() async def set_states(self, org: str, ns: str, rows: dict[str, str]) -> None: self.marks.update(rows) diff --git a/tests/unit/test_code_scip_ts_delta_worker.py b/tests/unit/test_code_scip_ts_delta_worker.py index fdb41f12e7b..c40c12848d7 100644 --- a/tests/unit/test_code_scip_ts_delta_worker.py +++ b/tests/unit/test_code_scip_ts_delta_worker.py @@ -48,7 +48,6 @@ async def get_state(org, ns, key): return {"git_head": git_head, "scip_commit_ts": scip_commit_ts}.get(key, "") repo.get_state.side_effect = get_state - repo.scip_stale_marks.return_value = {} # no file marked stale return repo @@ -191,11 +190,6 @@ async def fake_harness(co, base, head, delta_path, projects=(), **_): res = await w.run_pass() assert res.deltas_applied == 0 and not res.errors repo.set_state.assert_awaited_with("org", "code-ts", "scip_commit_ts", "b" * 40) - # the tier's marks in force are written again before the watermark moves - repo.scip_stale_marks.assert_awaited_once_with("org", "code-ts", "typescript") - calls = repo.mock_calls - marks = next(i for i, c in enumerate(calls) if c[0] == "scip_stale_marks") - assert marks < calls.index(("set_state", ("org", "code-ts", "scip_commit_ts", "b" * 40), {})) def test_registry_and_producer_field(): @@ -306,7 +300,7 @@ async def fake_apply_files(repo, org, ns, commit, files, stats): monkeypatch.setattr("server.code.app.index.scip_delta._apply_files", fake_apply_files) repo = _repo("b" * 40, "") repo.live_scip_paths.return_value = {"web/a.ts", "web/bad.ts", "web/gone.ts"} - repo.scip_stale_marks.return_value = {} + repo.scip_stale_marks.return_value = set() p1, p2 = _patched(repo, [_Cfg()]) with p1, p2: res = await w.run_pass() diff --git a/tests/unit/test_scip_apply_rounds.py b/tests/unit/test_scip_apply_rounds.py index 85e17690d3f..f0ed0066be3 100644 --- a/tests/unit/test_scip_apply_rounds.py +++ b/tests/unit/test_scip_apply_rounds.py @@ -98,8 +98,8 @@ async def insert_rows(self, table, rows): async def set_state(self, org, ns, key, value, detail=""): self.state[key] = value - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: - return {} + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() def test_a_delta_is_applied_in_rounds_with_one_read_and_one_insert_per_table() -> None: @@ -142,8 +142,8 @@ async def insert_rows(self, table, rows): async def set_state(self, *a: Any, **k: Any) -> None: return None - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: - return {} + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() def test_a_repository_without_round_reads_keeps_the_per_file_path() -> None: diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index 3da74bc8f41..5dd1ee5d366 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -567,8 +567,8 @@ async def insert_rows(self, table, rows) -> None: async def set_state(self, org, ns, key, value, detail="") -> None: self.states.append(key) - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> dict[str, str]: - return {} + async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: + return set() def _delta() -> Any: From 619be75bc3da58d9307a47c2cc6b38250a755941 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:43:37 +0000 Subject: [PATCH 25/81] The record reader refuses every truncated wire type _top_level_records bounds-checked length-delimited records only. A fixed32 or fixed64 field cut short was skipped by moving past the end of the data, so a part whose valid records were followed by one payload byte merged and converted with exit 0 where the protobuf parser refuses the index. The reader now refuses what the parser refuses and raises ValueError in the existing form: fixed32 and fixed64 spans that run past the end, a varint or tag that runs off the end or exceeds ten bytes, field number 0, and unbalanced or mismatched groups and wire types 6 and 7. A closed group in an unknown field is skipped, as the parser skips it. The merge's IndexError branch is gone because the reader no longer raises it. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 7 +-- scripts/scip_harness/scip_to_delta.py | 68 +++++++++++++++++----- tests/unit/test_scip_merge_indexes.py | 63 ++++++++++++++++++++ tests/unit/test_scip_to_delta_cli.py | 54 +++++++++++++++++ 4 files changed, 174 insertions(+), 18 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 9eaf079a8f8..b30eab0aaef 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -17,8 +17,9 @@ relative_path, and copies the records it keeps byte for byte. Nothing is decoded, so a document python-protobuf would refuse (a string field that is not UTF-8) reaches the converter, which decides what to do with it. A -record that runs past the end of its part is corrupt: the merge stops and names -the part, as the whole-index parse used to. +record, fixed-width value, varint, tag or group that the protobuf parser would +refuse is corrupt: the merge stops and names the part, as the whole-index parse +used to. """ from __future__ import annotations @@ -136,8 +137,6 @@ def merge_indexes( external_symbols.append(payload) except ValueError as e: raise SystemExit(f"{path}: corrupt part: {e}") from e - except IndexError as e: - raise SystemExit(f"{path}: corrupt part: it ends inside a record header") from e has_payload = True # The parts stay mapped while the output is written, so write beside the # output and swap it in; truncating an input that is also the output would diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index c23bd7927f1..23c3da6d4fd 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -804,37 +804,77 @@ def _factory_type_ref_span( def _top_level_records(data: bytes): """Yield (field, payload) for every length-delimited top-level record of - an Index message (1 = metadata, 2 = documents, 3 = external_symbols).""" - pos, end = 0, len(data) + an Index message (1 = metadata, 2 = documents, 3 = external_symbols). + + Every other field is skipped the way the protobuf parser skips it, and + anything the parser refuses is refused here with a ValueError: a record, + fixed-width value, varint or tag that runs past the end, a varint longer + than ten bytes, field number 0, an unbalanced group, and wire types 6 and 7. + """ + end, max_depth = len(data), 100 # the parser's own group nesting limit def varint(p: int) -> tuple[int, int]: shift = result = 0 + start = p while True: + if p >= end: + raise ValueError(f"record at {start} runs past the end inside a varint") b = data[p] result |= (b & 0x7F) << shift p += 1 if not b & 0x80: return result, p shift += 7 - + if shift >= 70: + raise ValueError(f"varint at {start} is longer than 10 bytes") + + def span(p: int, size: int) -> int: + if p + size > end: + raise ValueError(f"record at {p} runs {p + size - end} bytes past the end") + return p + size + + def skip(p: int, wire: int, field: int, depth: int) -> int: + """The position after one value of an unknown field.""" + if wire == 0: + return varint(p)[1] + if wire == 1: + return span(p, 8) + if wire == 5: + return span(p, 4) + if wire == 2: + length, p = varint(p) + return span(p, length) + if wire == 3: + if depth >= max_depth: + raise ValueError(f"group at {p} nests deeper than {max_depth}") + while True: + if p >= end: + raise ValueError(f"group {field} at {p} is not closed before the end") + tag, p = varint(p) + inner, inner_wire = tag >> 3, tag & 7 + if inner == 0: + raise ValueError(f"field number 0 at {p}") + if inner_wire == 4: + if inner != field: + raise ValueError(f"group {field} is closed by group {inner} at {p}") + return p + p = skip(p, inner_wire, inner, depth + 1) + raise ValueError(f"unexpected wire type {wire} at {p}") + + pos = 0 while pos < end: tag, pos = varint(pos) field, wire = tag >> 3, tag & 7 + if field == 0: + raise ValueError(f"field number 0 at {pos}") if wire == 2: # length-delimited length, pos = varint(pos) - if pos + length > end: - raise ValueError(f"record at {pos} runs {pos + length - end} bytes past the end") - payload = data[pos : pos + length] - pos += length + stop = span(pos, length) + payload = data[pos:stop] + pos = stop yield field, payload - elif wire == 0: - _, pos = varint(pos) - elif wire == 5: - pos += 4 - elif wire == 1: - pos += 8 else: - raise ValueError(f"unexpected wire type {wire} at {pos}") + pos = skip(pos, wire, field, 0) def _document_path(payload) -> str: diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index ba1771673b7..6dfe301c4a5 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -9,6 +9,7 @@ from typing import Any import pytest +from google.protobuf.message import DecodeError _SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" _SPEC = importlib.util.spec_from_file_location("scip_merge_indexes", _SCRIPT) @@ -433,3 +434,65 @@ def test_the_reader_names_the_offset_of_a_record_that_runs_past_the_end() -> Non grown = _damaged(raw, "length one byte too long") with pytest.raises(ValueError, match=rf"record at {at + 1} runs 1 bytes past the end"): list(_MOD._top_level_records(grown)) + + +# Bytes after a valid index that the protobuf parser refuses. Each is a field 9 +# (tag byte 0x48 | wire type) unless the case is about the tag itself. +_REFUSED_TAILS = { + "fixed32 with one payload byte": bytes([0x4D, 0x01]), + "fixed32 with no payload": bytes([0x4D]), + "fixed64 with seven payload bytes": bytes([0x49]) + bytes(7), + "fixed64 with no payload": bytes([0x49]), + "varint that runs off the end": bytes([0x48, 0x80]), + "varint with no byte": bytes([0x48]), + "varint longer than ten bytes": bytes([0x48]) + bytes([0x80] * 10) + bytes([0x00]), + "tag that runs off the end": bytes([0x80]), + "field number 0": bytes([0x00, 0x01]), + "group that is never closed": bytes([0x4B, 0x08, 0x01]), + "group closed by another field": bytes([0x4B, 0x54]), + "end group with no start": bytes([0x4C]), + "wire type 6": bytes([0x4E]), + "wire type 7": bytes([0x4F]), + "unknown record with a long length": bytes([0x4A, 0x05, 0x01]), +} +_REFUSED = pytest.mark.parametrize("how", list(_REFUSED_TAILS)) + + +def _refused_part(how: str) -> bytes: + raw = _index_with_docs(["packages/app/src/a.ts"], ["a"]) + _REFUSED_TAILS[how] + with pytest.raises(DecodeError): + _scip_pb2().Index.FromString(raw) # the case is one the parser refuses + return raw + + +@_REFUSED +def test_the_reader_refuses_what_the_protobuf_parser_refuses(how: str) -> None: + with pytest.raises(ValueError): + list(_MOD._top_level_records(_refused_part(how))) + + +@_REFUSED +def test_merge_rejects_a_part_the_protobuf_parser_rejects(tmp_path: Path, how: str) -> None: + """A fixed-width value, varint or group cut short is as corrupt as a cut record.""" + good = tmp_path / "good.scip" + broken = tmp_path / "broken.scip" + good.write_bytes(_index_with_docs(["packages/lib/src/b.ts"], ["from-lib"])) + broken.write_bytes(_refused_part(how)) + out = tmp_path / "merged.scip" + with pytest.raises(SystemExit, match=r"broken\.scip: corrupt part"): + _MOD.merge_indexes([good, broken], out) + assert not out.exists() + assert not (tmp_path / "merged.scip.tmp").exists() + + +def test_merge_accepts_a_part_with_a_balanced_unknown_group(tmp_path: Path) -> None: + """The parser skips a closed group in a field it does not know, nested or not.""" + part = tmp_path / "grouped.scip" + part.write_bytes( + _index_with_docs(["packages/app/src/a.ts"], ["a"]) + bytes([0x4B, 0x53, 0x54, 0x4C]) + ) + _scip_pb2().Index.FromString(part.read_bytes()) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index 4afbd9fa074..96539d99089 100644 --- a/tests/unit/test_scip_to_delta_cli.py +++ b/tests/unit/test_scip_to_delta_cli.py @@ -12,6 +12,7 @@ from pathlib import Path import pytest +from google.protobuf.message import DecodeError _HARNESS = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" _CONVERTER = _HARNESS / "scip_to_delta.py" @@ -365,3 +366,56 @@ def test_a_record_that_runs_past_the_end_of_the_index_fails_the_run(tmp_path: Pa assert proc.returncode != 0 assert "past the end" in proc.stderr assert not (tmp_path / "delta.json").exists() + + +# Bytes after a valid index that the protobuf parser refuses (field 9 unless the case +# is about the tag itself). +_REFUSED_TAILS = { + "fixed32 with one payload byte": bytes([0x4D, 0x01]), + "fixed32 with no payload": bytes([0x4D]), + "fixed64 with seven payload bytes": bytes([0x49]) + bytes(7), + "fixed64 with no payload": bytes([0x49]), + "varint that runs off the end": bytes([0x48, 0x80]), + "varint with no byte": bytes([0x48]), + "varint longer than ten bytes": bytes([0x48]) + bytes([0x80] * 10) + bytes([0x00]), + "tag that runs off the end": bytes([0x80]), + "field number 0": bytes([0x00, 0x01]), + "group that is never closed": bytes([0x4B, 0x08, 0x01]), + "group closed by another field": bytes([0x4B, 0x54]), + "end group with no start": bytes([0x4C]), + "wire type 6": bytes([0x4E]), + "wire type 7": bytes([0x4F]), + "unknown record with a long length": bytes([0x4A, 0x05, 0x01]), +} + + +def _convert_raw(tmp_path: Path, raw: bytes) -> subprocess.CompletedProcess[str]: + index = tmp_path / "damaged.scip" + index.write_bytes(raw) + return subprocess.run( + [sys.executable, str(_CONVERTER), "--index", str(index), "--commit", "h" * 40] + + ["--source-root", "", "--dry-run", str(tmp_path / "delta.json")], + capture_output=True, + text=True, + check=False, + ) + + +@pytest.mark.parametrize("how", list(_REFUSED_TAILS)) +def test_the_converter_refuses_what_the_protobuf_parser_refuses(tmp_path: Path, how: str) -> None: + """A fixed-width value, varint, tag or group cut short used to be skipped, so + the run converted the records before it and exited 0.""" + raw = _index(tmp_path).read_bytes() + _REFUSED_TAILS[how] + with pytest.raises(DecodeError): + _pb().Index.FromString(raw) # the case is one the parser refuses + proc = _convert_raw(tmp_path, raw) + assert proc.returncode != 0 + assert "ValueError" in proc.stderr + assert not (tmp_path / "delta.json").exists() + + +def test_the_converter_skips_a_balanced_unknown_group(tmp_path: Path) -> None: + raw = _index(tmp_path).read_bytes() + bytes([0x4B, 0x53, 0x54, 0x4C]) + _pb().Index.FromString(raw) + proc = _convert_raw(tmp_path, raw) + assert proc.returncode == 0, proc.stderr From 041480670978ef584d58b2e561bd5f397e38ad3d Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:47:25 +0000 Subject: [PATCH 26/81] Empty the mark of a file the previous build deleted A marked file that the previous build deletes is never applied by this build again, so its mark kept constructor coverage incomplete for the whole namespace and no weekly run cleared it. Each apply now also empties the tier's marks whose path has no blob at the delta's commit in the entry's mirror. A commit the mirror lacks, a failed read or a short cat-file reply keeps every mark. The rollout note says the Python, TypeScript and Go tiers have no weekly full run, so a mark there waits for a delta that changes the file. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 12 ++-- server/code/app/index/gitrepo.py | 10 ++- server/code/app/index/scip_delta.py | 32 +++++++-- .../integration/test_code_scip_stale_mark.py | 70 +++++++++++++++++++ 4 files changed, 112 insertions(+), 12 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 8fcfbf30ef5..67fa758eb45 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1018,10 +1018,14 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline and N keeps counting the mark: after N-1 refreshes the file, and after an N-1 retry whose edge insert failed followed by an N-1 watermark write over a window with no change, the file reads stale and constructor coverage incomplete until N applies the - file again, by a delta that changes it or by N's weekly C++ full run. A rollback and - a roll forward do the same. A marked file that N-1 deletes is never applied by N - again, so its mark stays until it is deleted by hand - (`DELETE FROM loom.code_index_state WHERE state_key = 'scip_stale::'`). + file again, by a delta that changes it or, for C++, by N's weekly full run. The + Python, TypeScript and Go tiers have no weekly full run, so for them the wait has no + upper bound: only a delta that changes the file ends it, and a file that never + changes reads stale until it does. A rollback and a roll forward do the same. A + marked file that N-1 deletes is never applied by N again, so N's next apply of the + tier empties its mark when the entry's mirror holds the delta's commit and the + commit has no blob at that path; a mirror that cannot be read, or lacks the commit, + keeps the mark. `tests/integration/test_code_scip_stale_mark.py` applies these orders. A kept delta file (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI applies a retained version-2 file as version 1, so a skipped file's partial entry diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index 99ba4b65cde..58d4a59f369 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -1326,8 +1326,12 @@ async def ls_tree(git_dir: str, sha: str, prefixes: tuple[str, ...] = ()) -> lis return paths -async def blob_paths_at(git_dir: str, sha: str, paths: set[str]) -> set[str]: - """Exact blob paths present at a pinned revision, with no blob reads.""" +async def blob_paths_at( + git_dir: str, sha: str, paths: set[str], *, strict: bool = False +) -> set[str]: + """Exact blob paths present at a pinned revision, with no blob reads. A reply whose + line count does not match the request reads as no blob; `strict` raises GitError + instead, for a caller that treats a missing path as proof the file is gone.""" wanted = sorted(path for path in paths if "\n" not in path and "\r" not in path) if not wanted: return set() @@ -1336,5 +1340,7 @@ async def blob_paths_at(git_dir: str, sha: str, paths: set[str]) -> set[str]: out = await _git(git_dir, "cat-file", "--batch-check=%(objecttype)", stdin=payload) lines = out.splitlines() if len(lines) != len(wanted): + if strict: + raise GitError(f"git cat-file answered {len(lines)} lines for {len(wanted)} paths") return set() return {path for path, kind in zip(wanted, lines, strict=True) if kind == "blob"} diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 0feada7f4d9..14802dde2f3 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -303,6 +303,25 @@ def keep(path: str) -> bool: return stats +async def _gone_at(org: str, ns: str, commit: str, paths: set[str]) -> set[str]: + """The marked `paths` with no file at `commit` in the entry's mirror. Empty when the + mirror cannot say (no entry, no mirror, a commit it lacks, a failed or short read), + so a failed read keeps every mark.""" + if not paths or not commit: + return set() + try: + from server.code.app.index import gitrepo + from server.code.domain.index.repos import repo_for_namespace + + cfg = repo_for_namespace(org, ns) + if cfg is None or not cfg.git_dir or not await gitrepo.has_commit(cfg.git_dir, commit): + return set() + asked = {p for p in paths if "\n" not in p and "\r" not in p} + return asked - await gitrepo.blob_paths_at(cfg.git_dir, commit, asked, strict=True) + except Exception: # noqa: BLE001 — a failed read can only keep a mark + return set() + + async def _mark_stale( repo: Any, org: str, @@ -313,15 +332,16 @@ async def _mark_stale( refreshed: set[str], ) -> None: """One write of `tier`'s rows only (`SCIP_STALE_PREFIX`): each skipped file marked at - `commit`, and the mark of each file this delta applied or deleted emptied. Another - tier's marks are never read or written, so tiers applying side by side keep both.""" + `commit`, and the mark of each file this delta applied or deleted emptied, as is the + mark of a file with no blob at `commit` (one the previous build deleted, which no + apply of this build names again). Another tier's marks are never read or written, so + tiers applying side by side keep both.""" refreshed -= skipped - if not (skipped or refreshed): - return prefix = f"{SCIP_STALE_PREFIX}{tier}:" - marked = await repo.scip_stale_marks(org, ns, tier) if refreshed else set() + marked = await repo.scip_stale_marks(org, ns, tier) + gone = await _gone_at(org, ns, commit, marked - refreshed - skipped) rows = {prefix + p: commit for p in sorted(skipped)} - rows.update({prefix + p: "" for p in sorted(marked & refreshed)}) + rows.update({prefix + p: "" for p in sorted((marked & refreshed) | gone)}) if rows: check_held() await repo.set_states(org, ns, rows) diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index ee8e0cf5290..1d86bcf0a66 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -6,6 +6,7 @@ import asyncio import json +import subprocess from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any @@ -296,3 +297,72 @@ async def no_delta(*a: Any, **kw: Any) -> tuple[int, str]: assert not result.errors and not result.skipped assert await repo.get_state(org, ns, "scip_commit") == "d" * 40 assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + +def _mirror(tmp_path: Path) -> tuple[str, str, str]: + """A git dir whose first commit holds `BAD` and `OTHER` and whose second deletes + `BAD`: (git dir, first commit, second commit).""" + work = tmp_path / "mirror" + work.mkdir() + + def git(*args: str) -> str: + done = subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], + cwd=work, + check=True, + capture_output=True, + text=True, + ) + return done.stdout.strip() + + git("init", "-q") + for p in (BAD, OTHER): + (work / p).parent.mkdir(parents=True, exist_ok=True) + (work / p).write_text("int x;\n") + git("add", ".") + git("commit", "-q", "-m", "one") + first = git("rev-parse", "HEAD") + git("rm", "-q", BAD) + git("commit", "-q", "-m", "two") + return str(work / ".git"), first, git("rev-parse", "HEAD") + + +@pytest.mark.asyncio +async def test_a_mark_for_a_file_the_previous_build_deleted_is_emptied_by_the_next_apply( + ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """This build marks a skipped file; the previous build deletes it, which no apply + of this build names again. Constructor coverage would stay incomplete for the whole + namespace. This build's next apply of any file empties the mark of a path that has + no blob at the delta's commit, and keeps it when the mirror cannot say.""" + org, ns = unique_org("scip-stale-gone"), "code-stale-gone" + git_dir, first, second = _mirror(tmp_path) + cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) + monkeypatch.setattr("server.code.domain.index.repos.repo_for_namespace", lambda o, n: cfg) + repo = await _repo(ch_client, org, ns, [BAD, OTHER]) + await apply_delta(repo, org, ns, ScipDelta(commit=first, skipped_files=[BAD]), tier="clang") + await repo.set_state(org, ns, "scip_commit", first) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + async def no_marks(*a: Any) -> None: + return None + + with monkeypatch.context() as previous_build: + previous_build.setattr(scip_delta, "_mark_stale", no_marks) + await apply_delta( + repo, org, ns, ScipDelta(commit=second, deleted_files=[BAD]), tier="clang" + ) + await repo.set_state(org, ns, "scip_commit", second) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + # a commit the mirror does not hold: the mark stays + await apply_delta(repo, org, ns, ScipDelta(commit="f" * 40, files=[_other()]), tier="clang") + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + # the file is still in the tree at the first commit: the mark stays + await apply_delta(repo, org, ns, ScipDelta(commit=first, files=[_other()]), tier="clang") + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + await apply_delta(repo, org, ns, ScipDelta(commit=second, files=[_other()]), tier="clang") + await repo.set_state(org, ns, "scip_commit", second) + assert await _read(repo, org, ns) == (set(), set(), True) From c5f7902524e9c26a268469679297f8c54f641ccc Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 23:05:18 +0000 Subject: [PATCH 27/81] A failing TypeScript member keeps the other members' rows With a member list, one member whose indexer exited non-zero failed the whole pass under `set -e`, the watermark stayed, and the next pass failed the same way. One member with an option its bundled TypeScript does not know stopped the tier for the whole repository. The harness now logs the member and its exit status and goes on. The merge takes the parts that succeeded and writes the files the failed members own (the window's, or every TypeScript file when the converter reads whole indexes); the converter lists them in `skipped_files` through the new `--failed-files`, so the server keeps their rows and marks them stale, as it does for a document the converter skips. A pass in which every member failed still fails, and SCIP_STOP_ON_FAILED_DOCUMENT=1 fails it on the first failed member. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/code-index-architecture.md | 12 +-- scripts/scip_harness/run_typescript_delta.sh | 37 ++++++- scripts/scip_harness/scip_merge_indexes.py | 26 +++++ scripts/scip_harness/scip_to_delta.py | 11 +++ .../test_run_typescript_delta_umbrella.py | 96 ++++++++++++++++++- tests/unit/test_scip_merge_indexes.py | 10 ++ tests/unit/test_scip_to_delta_skip.py | 26 +++++ 7 files changed, 205 insertions(+), 13 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 1573ed82c17..766c11b2765 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -348,12 +348,12 @@ applies it. Per touched file the apply upserts what the delta emits and tombston file's `scip` rows it no longer emits; a deleted file is tombstoned whole. Re-applying a delta gives the same live set. -| Producer | Language | Watermark | Workers | How it runs | -| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | -| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. The converter still bounds the output to the TypeScript window. | -| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | -| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | +| Producer | Language | Watermark | Workers | How it runs | +| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | +| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. A project whose indexer fails leaves the others; its files keep their rows, marked stale. The converter still bounds the output to the TypeScript window. | +| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | +| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | `code/domain/index/compiler_tiers.py` (`TIERS`) is the one table of watermark, label and workers per producer; status handlers and the dashboard read it. A delta worker diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 2353888518d..acc606a76ab 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -161,22 +161,53 @@ JSONEOF fi return fi + # A member whose indexer fails leaves the others: its files go to the converter + # as failed, so the server keeps their rows and marks them stale. With + # SCIP_STOP_ON_FAILED_DOCUMENT=1, or when every member failed, the pass fails. + local indexed=() failed=() rc for target in "${targets[@]}"; do part="$WORK/index.part.$i.scip" + rc=0 NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ - "$SCIP_TYPESCRIPT" index "${ws[@]}" "$target" --output "$part" >&2 - parts+=("$part") + "$SCIP_TYPESCRIPT" index "${ws[@]}" "$target" --output "$part" >&2 || rc=$? i=$((i + 1)) + if [[ $rc -ne 0 ]]; then + echo ">> member $target failed (exit $rc)" >&2 + [[ "${SCIP_STOP_ON_FAILED_DOCUMENT:-0}" == "1" ]] && exit "$rc" + failed+=("$target") + continue + fi + parts+=("$part") + indexed+=("$target") done + if [[ ${#indexed[@]} -eq 0 ]]; then + echo ">> every member failed — no delta" >&2 + exit 1 + fi # Always merge so a single member that followed project references # also drops documents it does not own. local merge_args=() t - for t in "${targets[@]}"; do + for t in "${indexed[@]}"; do merge_args+=(--project "$t") done for t in "${ALL_PROJECTS[@]}"; do merge_args+=(--known-project "$t") done + if [[ ${#failed[@]} -gt 0 ]]; then + # The candidates are the files the delta converts: the window's, or every + # TypeScript file when the converter reads whole indexes (a full pass or a + # config rebuild). + if [[ "$BASE" == "--full" || "$CONFIG_ONLY_REBUILD" == "1" ]]; then + git_paths ls-files -- "${TS_GLOBS[@]}" >"$WORK/candidates.txt" + else + cp "$WORK/changed.txt" "$WORK/candidates.txt" + fi + for t in "${failed[@]}"; do + merge_args+=(--failed-project "$t") + done + merge_args+=(--paths "$WORK/candidates.txt" --failed-paths "$WORK/failed.txt") + CONVERT_ARGS+=(--failed-files "$WORK/failed.txt") + fi "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" \ "${merge_args[@]}" "${parts[@]}" } diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index c4a32d9fb21..6d6f0787828 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -75,6 +75,18 @@ def _preferred_owner(projects: list[str], relpath: str) -> str | None: return tied[0] +def owned_by(paths: list[str], members: list[str], known_projects: list[str]) -> list[str]: + """The paths whose document the merge would take from one of `members`: the + files of a member whose indexer failed, which no other part may stand in for.""" + scopes = {project_scope(member) for member in members} + out = [] + for path in paths: + owner = _preferred_owner(known_projects, path) + if owner is not None and project_scope(owner) in scopes: + out.append(path) + return out + + def merge_indexes( paths: list[Path], output: Path, @@ -146,10 +158,24 @@ def main(argv: list[str] | None = None) -> int: "dropped when a more specific member owns it, even if that member " "was not indexed in this run", ) + parser.add_argument( + "--failed-project", + action="append", + default=[], + help="a member whose indexer failed; with --paths, the paths it owns are " + "written to --failed-paths", + ) + parser.add_argument("--paths", type=Path, help="newline list of candidate paths") + parser.add_argument("--failed-paths", type=Path, help="where the failed members' paths go") parser.add_argument("indexes", nargs="+", type=Path) args = parser.parse_args(argv) projects = args.project or None known = args.known_project or None + if args.failed_paths is not None: + lines = args.paths.read_text(encoding="utf-8").splitlines() if args.paths else [] + candidates = [line for line in lines if line] + failed = owned_by(candidates, args.failed_project, known or args.failed_project) + args.failed_paths.write_text("".join(f"{path}\n" for path in failed), encoding="utf-8") merge_indexes(args.indexes, args.output, projects, known) return 0 diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 46a81e271b8..049133363a7 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1273,10 +1273,13 @@ def __init__( exclude_generated: bool = False, path_prefix: str = "", stop_on_failed_document: bool = False, + failed: list[str] | None = None, ) -> None: scip_pb2 = _ensure_scip_pb2() data = _read_index(index_path) self._skips = _Skips(stop_on_failed_document, whole=changed is None) + # files whose indexer run failed: in no index, their rows stay, marked stale + self._skips.paths.update(failed or ()) self._changed = changed self._run = _prepare( data, scip_pb2, source_root, exclude_generated, path_prefix, self._skips @@ -1349,6 +1352,7 @@ def convert( exclude_generated: bool = False, path_prefix: str = "", stop_on_failed_document: bool = False, + failed: list[str] | None = None, ) -> dict: """The whole delta as one dict (the command line streams it instead). `changed`: the relative paths to emit (None = every document). @@ -1370,6 +1374,7 @@ def convert( exclude_generated=exclude_generated, path_prefix=path_prefix, stop_on_failed_document=stop_on_failed_document, + failed=failed, ) files = list(stream.files) return {**stream.head, "files": files, **stream.tail()} @@ -1524,6 +1529,11 @@ def main() -> int: help="fail the run on a document that cannot be parsed or converted, instead " "of skipping it with a warning", ) + ap.add_argument( + "--failed-files", + help="newline list of files whose indexer run failed (a TypeScript member, say): " + "listed as skipped, so the server keeps their rows and marks them stale", + ) ap.add_argument( "--source-root", default=None, @@ -1560,6 +1570,7 @@ def main() -> int: exclude_generated=bool(args.exclude_generated), path_prefix=prefix, stop_on_failed_document=bool(args.stop_on_failed_document), + failed=_path_list(args.failed_files), ) if args.dry_run: diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 1890760170b..a127c29d75a 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -18,6 +18,12 @@ for a in "$@"; do printf '\\t%s' "$a"; done printf '\\n' } >>"$CALLS" +for a in "$@"; do + if [[ -n "${FAIL_TARGET:-}" && "$a" == "$FAIL_TARGET" ]]; then + echo "error TS5023: Unknown compiler option" >&2 + exit 1 + fi +done while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done """ @@ -31,6 +37,12 @@ for a in "$@"; do printf '\\t%s' "$a"; done printf '\\n' } >>"$CALLS" +args=("$@") +for ((i = 0; i < ${#args[@]}; i++)); do + if [[ "${args[i]}" == --failed-files ]]; then + while IFS= read -r p; do printf 'failed\\t%s\\n' "$p" >>"$CALLS"; done <"${args[i + 1]}" + fi +done while [[ $# -gt 0 ]]; do [[ "$1" == "--dry-run" ]] && echo '{}' >"$2"; shift; done """ @@ -62,7 +74,17 @@ def _repo(tmp_path: Path) -> Path: return repo -def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: +def _run( + tmp_path: Path, repo: Path, base: str, head: str, extra_env: dict[str, str] | None = None +) -> str: + proc, log = _run_status(tmp_path, repo, base, head, extra_env) + assert proc.returncode == 0, proc.stderr + return log + + +def _run_status( + tmp_path: Path, repo: Path, base: str, head: str, extra_env: dict[str, str] | None = None +) -> tuple[subprocess.CompletedProcess[str], str]: bin_dir = tmp_path / "bin" bin_dir.mkdir(exist_ok=True) calls = tmp_path / "calls" @@ -84,14 +106,16 @@ def _run(tmp_path: Path, repo: Path, base: str, head: str) -> str: } # Don't leak a parent SCIP_TS_PROJECTS into the test. env.pop("SCIP_TS_PROJECTS", None) - subprocess.run( + env.pop("SCIP_STOP_ON_FAILED_DOCUMENT", None) + env.update(extra_env or {}) + proc = subprocess.run( ["bash", str(_SCRIPT), str(repo), base, head], env=env, - check=True, + check=False, capture_output=True, text=True, ) - return calls.read_text() if calls.exists() else "" + return proc, calls.read_text() if calls.exists() else "" def _runs(log: str) -> list[list[str]]: @@ -134,6 +158,70 @@ def test_delta_indexes_only_the_project_that_changed(tmp_path: Path) -> None: assert _targets(_runs(log)) == ["packages/app"] +def _failed(log: str) -> list[str]: + return [line.split("\t", 1)[1] for line in log.splitlines() if line.startswith("failed\t")] + + +def test_a_failing_member_leaves_the_others_and_lists_its_files(tmp_path: Path) -> None: + """A full pass: packages/lib's indexer exits non-zero. packages/app's index is + still merged and converted, and packages/lib's files go to the converter as + failed, so the server keeps their rows and marks them stale.""" + repo = _repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + proc, log = _run_status(tmp_path, repo, "--full", head, {"FAIL_TARGET": "packages/lib"}) + assert proc.returncode == 0, proc.stderr + assert _targets(_runs(log)) == ["packages/app", "packages/lib"] + assert "packages/lib failed (exit 1)" in proc.stderr + assert _failed(log) == ["packages/lib/src/b.ts"] + assert "--full" in _convert_args(log) + + +def test_a_failing_member_in_a_delta_lists_only_its_window_files(tmp_path: Path) -> None: + repo = _repo(tmp_path) + (repo / "packages/lib/src/c.ts").write_text("export const c = 1;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "add c") + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + (repo / "packages/lib/src/b.ts").write_text("export const b = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "both") + head = _git(repo, "rev-parse", "HEAD") + proc, log = _run_status(tmp_path, repo, base, head, {"FAIL_TARGET": "packages/lib"}) + assert proc.returncode == 0, proc.stderr + assert _failed(log) == ["packages/lib/src/b.ts"] + assert "--changed-files" in _convert_args(log) + + +def test_a_pass_whose_every_member_failed_fails(tmp_path: Path) -> None: + """Nothing converted: the pass fails and the watermark stays, as before.""" + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + (repo / "packages/lib/src/b.ts").write_text("export const b = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "lib") + head = _git(repo, "rev-parse", "HEAD") + proc, log = _run_status(tmp_path, repo, base, head, {"FAIL_TARGET": "packages/lib"}) + assert proc.returncode != 0 + assert not any(line.startswith("convert") for line in log.splitlines()) + assert not (tmp_path / "delta.json").exists() + + +def test_the_stop_switch_fails_the_pass_on_a_failing_member(tmp_path: Path) -> None: + repo = _repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + proc, log = _run_status( + tmp_path, + repo, + "--full", + head, + {"FAIL_TARGET": "packages/app", "SCIP_STOP_ON_FAILED_DOCUMENT": "1"}, + ) + assert proc.returncode != 0 + assert _targets(_runs(log)) == ["packages/app"] + assert not (tmp_path / "delta.json").exists() + + def test_delta_with_shared_config_indexes_every_member(tmp_path: Path) -> None: repo = _repo(tmp_path) (repo / "package.json").write_text('{"name": "root", "private": true}\n') diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 45c2990217f..6eae75e3e9f 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -317,3 +317,13 @@ def test_merge_prefers_a_one_character_member_over_a_root_tsconfig(tmp_path: Pat merged.ParseFromString(out.read_bytes()) docs = {d.relative_path: d.text for d in merged.documents} assert docs == {"src/main.ts": "from-root", "a/src/a.ts": "from-a"} + + +def test_a_failed_member_owns_the_paths_the_merge_would_take_from_it() -> None: + """A nested member that indexed keeps its own paths; a generated target names + its directory's scope.""" + known = ["src", "src/infra", "pkg", "tsconfig.repo.json"] + paths = ["src/main.ts", "src/infra/net.ts", "pkg/a.ts", "eslint.config.mjs", "x/y.ts"] + assert _MOD.owned_by(paths, ["src"], known) == ["src/main.ts"] + assert _MOD.owned_by(paths, ["pkg/tsconfig.scip.json"], known) == ["pkg/a.ts"] + assert _MOD.owned_by(paths, ["tsconfig.repo.json"], known) == ["eslint.config.mjs", "x/y.ts"] diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 90ba3cc315e..8235db3237d 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -171,6 +171,32 @@ def convert_document(doc, run): assert first.tail()["stats"]["skipped_failed"] == 1 +def test_failed_files_are_listed_as_skipped(tmp_path: Path) -> None: + """`--failed-files` names the files of a member whose indexer failed: they are + in no index, and the delta lists them as skipped so their rows stay, marked + stale. A window lists only its own.""" + index = _index_with(tmp_path, "g") + failed = tmp_path / "failed.txt" + failed.write_text("pkg/b.ts\npkg/c.ts\n") + out = tmp_path / "delta.json" + proc = _run(index, out, "--failed-files", str(failed)) + assert proc.returncode == 0, proc.stderr + delta = json.loads(out.read_text()) + assert [f["path"] for f in delta["files"]] == ["src/a.cpp", "src/bad.cpp"] + assert delta["skipped_files"] == ["pkg/b.ts", "pkg/c.ts"] + assert delta["delta_version"] == 2 + window = _converter().convert( + str(index), + {"src/a.cpp", "pkg/b.ts"}, + [], + "h" * 40, + "b" * 40, + source_root="", + failed=["pkg/b.ts", "pkg/c.ts"], + ) + assert window["skipped_files"] == ["pkg/b.ts"] + + def test_a_window_lists_only_its_own_failed_documents(tmp_path: Path) -> None: """The index-wide passes meet a bad document the window does not hold: it is warned about and counted, but not listed, so the server marks only what the window asked.""" From d03cbec8e7ef58dab46e49e031040165026ace81 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 23:23:17 +0000 Subject: [PATCH 28/81] A file that calls into a failed TypeScript member keeps its rows too A reference to an arrow-function constant becomes a `calls` edge only when the index holds the constant's definition (`_ts_prepass`). With a member failed, its definitions are in no index, so a converted file of another member that calls into it would be written without those edges, which the pass before the failure would have kept. With `--failed-files`, a document that refers to a term defined in a failed file whose kind the index does not hold is skipped like the failed files: it is named on stderr, listed in `skipped_files`, and the server keeps its rows, marked stale. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 45 ++++++++++++++++++++- tests/unit/test_scip_to_delta_skip.py | 57 +++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 049133363a7..5330aab9c63 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -49,6 +49,7 @@ import time import uuid from pathlib import Path +from typing import Any _HERE = Path(__file__).resolve().parent _VENDOR = _HERE / "vendor" @@ -271,6 +272,41 @@ def _ts_descriptors(desc: str) -> list[tuple[str, str, str]]: return out +def _ts_symbol_file(symbol: str) -> str | None: + """The workspace file a scip-typescript symbol is defined in; None for locals, + externals and a symbol with no file.""" + ctx = _TS + if ctx is None or symbol.startswith("local "): + return None + parts = symbol.split(" ", 4) + if len(parts) < 5 or parts[1] != "npm" or parts[2] not in ctx.pkg_dirs: + return None + segs: list[str] = [] + for name, suffix, _disamb in _ts_descriptors(parts[4]): + if suffix != "/": + return None + segs.append(name) + if name.endswith(_TS_CODE_EXTS): + pkg_dir = ctx.pkg_dirs[parts[2]] + return f"{pkg_dir}/{'/'.join(segs)}" if pkg_dir else "/".join(segs) + return None + + +def _ts_needs_failed_kind(doc: Any, failed: set[str]) -> bool: + """`doc` refers to a term defined in one of the `failed` files whose kind the index + does not hold. A term's kind decides whether a reference is a `calls` edge, and + only its definition gives it (`_ts_prepass`).""" + if _TS is None: + return False + for occ in doc.occurrences: + symbol = occ.symbol + if occ.symbol_roles & 0x1 or not symbol.endswith(".") or symbol.endswith(")."): + continue + if symbol not in _TS.def_kinds and _ts_symbol_file(symbol) in failed: + return True + return False + + def _parse_ts_symbol(symbol: str) -> tuple[str, str, str] | None: """(qualified_name, kind, signature) for a scip-typescript symbol of a workspace package; None for locals, externals, files, parameters, meta @@ -1279,7 +1315,8 @@ def __init__( data = _read_index(index_path) self._skips = _Skips(stop_on_failed_document, whole=changed is None) # files whose indexer run failed: in no index, their rows stay, marked stale - self._skips.paths.update(failed or ()) + self._failed = set(failed or ()) + self._skips.paths.update(self._failed) self._changed = changed self._run = _prepare( data, scip_pb2, source_root, exclude_generated, path_prefix, self._skips @@ -1303,6 +1340,12 @@ def _files(self, data, scip_pb2, changed: set[str] | None): for i, doc in _indexed_documents(data, scip_pb2, self._skips, changed, True): if changed is not None and doc.relative_path not in changed: continue + if self._failed and _ts_needs_failed_kind(doc, self._failed): + # Converted, it would lose the `calls` edges into the failed files that a + # complete index writes: its rows stay instead, marked stale. + failure = ValueError("refers to a definition in a file whose indexer failed") + self._skips.add(doc.relative_path, failure, i) + continue try: entry = _convert_document(doc, self._run) except Exception as e: # noqa: BLE001 — any failure of one document skips it diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 8235db3237d..45d51ab2973 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -197,6 +197,63 @@ def test_failed_files_are_listed_as_skipped(tmp_path: Path) -> None: assert window["skipped_files"] == ["pkg/b.ts"] +def _ts_index(tmp_path: Path, *, with_b: bool) -> tuple[Path, Path]: + """pkg/a/`a.ts` defines run(), which calls the arrow-function constant `helper` of + pkg/b/`b.ts`. Without b's document the index cannot say `helper` is a function.""" + root = tmp_path / "checkout" + (root / "pkg" / "a").mkdir(parents=True, exist_ok=True) + (root / "pkg" / "b").mkdir(parents=True, exist_ok=True) + (root / "package.json").write_text('{"name": "fx", "version": "0.0.0"}') + (root / "pkg" / "a" / "a.ts").write_text( + 'import { helper } from "../b/b.js";\nexport function run() {\n return helper();\n}\n' + ) + (root / "pkg" / "b" / "b.ts").write_text("export const helper = () => 1;\n") + pkg = "scip-typescript npm fx 0.0.0 " + run, helper = pkg + "pkg/a/`a.ts`/run().", pkg + "pkg/b/`b.ts`/helper." + pb = _pb() + index = pb.Index() + index.metadata.project_root = root.as_uri() + a = index.documents.add() + a.relative_path = "pkg/a/a.ts" + a.occurrences.add(range=[1, 16, 19], symbol=run, symbol_roles=1, enclosing_range=[1, 0, 3, 1]) + a.occurrences.add(range=[2, 9, 15], symbol=helper) + a.symbols.add(symbol=run) + if with_b: + b = index.documents.add() + b.relative_path = "pkg/b/b.ts" + b.occurrences.add(range=[0, 13, 19], symbol=helper, symbol_roles=1) + b.symbols.add(symbol=helper) + out = tmp_path / "index.scip" + out.write_bytes(index.SerializeToString()) + return out, root + + +def test_a_document_that_calls_into_a_failed_member_is_skipped_too(tmp_path: Path) -> None: + """Converted without the failed member's definitions, pkg/a/a.ts would lose its + `calls` edge to `helper`, which the index with b's document writes. It keeps its + rows instead, marked stale, like the failed member's own files.""" + conv = _converter() + index, root = _ts_index(tmp_path, with_b=True) + whole = conv.convert(str(index), {"pkg/a/a.ts"}, [], "h" * 40, "b" * 40, source_root=str(root)) + assert [e["to_qualified_name"] for e in whole["files"][0]["edges"]] == ["pkg.b.b::helper"] + index, root = _ts_index(tmp_path, with_b=False) + delta = conv.convert( + str(index), + {"pkg/a/a.ts"}, + [], + "h" * 40, + "b" * 40, + source_root=str(root), + failed=["pkg/b/b.ts"], + ) + assert delta["files"] == [] + assert delta["skipped_files"] == ["pkg/a/a.ts"] + # with no failed member it converts as before, without the edge + plain = conv.convert(str(index), {"pkg/a/a.ts"}, [], "h" * 40, "b" * 40, source_root=str(root)) + assert [f["path"] for f in plain["files"]] == ["pkg/a/a.ts"] + assert plain["files"][0]["edges"] == [] + + def test_a_window_lists_only_its_own_failed_documents(tmp_path: Path) -> None: """The index-wide passes meet a bad document the window does not hold: it is warned about and counted, but not listed, so the server marks only what the window asked.""" From c8f53c83cb095df695ed7e70c941e8ce771bc1d5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 01:54:21 +0000 Subject: [PATCH 29/81] Fail the TypeScript pass on a member killed by a signal A member whose scip-typescript is killed by a signal (exit above 128: a V8 heap abort, a SIGKILL) now fails the pass, so the watermark stays and the next pass retries it; an error of the member's own still leaves the others. The merge now gets every TypeScript file as a candidate, so the converter knows all of a failed member's files and skips a caller whose callee file is outside the window. The failed files the delta converts are warned about in the skipped-document format and counted in `skipped_failed`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/code-index-architecture.md | 12 ++--- scripts/scip_harness/README.md | 9 ++++ scripts/scip_harness/run_typescript_delta.sh | 20 +++++---- scripts/scip_harness/scip_merge_indexes.py | 10 ++++- scripts/scip_harness/scip_to_delta.py | 9 +++- .../test_run_typescript_delta_umbrella.py | 23 ++++++++-- tests/unit/test_scip_to_delta_skip.py | 44 +++++++++++++++++++ 7 files changed, 105 insertions(+), 22 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 766c11b2765..28fb50eed60 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -348,12 +348,12 @@ applies it. Per touched file the apply upserts what the delta emits and tombston file's `scip` rows it no longer emits; a deleted file is tombstoned whole. Re-applying a delta gives the same live set. -| Producer | Language | Watermark | Workers | How it runs | -| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | -| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. A project whose indexer fails leaves the others; its files keep their rows, marked stale. The converter still bounds the output to the TypeScript window. | -| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | -| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | +| Producer | Language | Watermark | Workers | How it runs | +| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scip-clang` | C++ | `scip_commit` | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly. | +| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta` | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. A project whose indexer exits with an error leaves the others; its files keep their rows, marked stale. The converter still bounds the output to the TypeScript window. | +| `scip-go` | Go | `scip_commit_go` | `code_scip_go_delta` | One build per module (`run_go_monorepo_delta.sh`). | +| `scip-python` | Python | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply` | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree. | `code/domain/index/compiler_tiers.py` (`TIERS`) is the one table of watermark, label and workers per producer; status handlers and the dashboard read it. A delta worker diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 0591ea2e486..d4ee5e62028 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -51,6 +51,15 @@ applies version 1 only refuses. With `--stop-on-failed-document`, and such a document fails the run. An index whose records cannot be read to the end fails the run either way. +`run_typescript_delta.sh` treats a member whose scip-typescript exits with an +error the same way: the other members' parts are merged, and the files the +failed member owns go to the converter as `--failed-files`. Those in the +delta are warned about, counted and listed in `skipped_files`; a converted +file that refers to a constant defined in one of them is skipped too. The +pass fails instead with `SCIP_STOP_ON_FAILED_DOCUMENT=1`, when a member is +killed by a signal (exit above 128: a heap abort, a SIGKILL), or when every +member failed. + ## Requirements - a ClickHouse checkout that `cmake -G Ninja` can configure (the harness diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index acc606a76ab..56cf4735472 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -163,7 +163,8 @@ JSONEOF fi # A member whose indexer fails leaves the others: its files go to the converter # as failed, so the server keeps their rows and marks them stale. With - # SCIP_STOP_ON_FAILED_DOCUMENT=1, or when every member failed, the pass fails. + # SCIP_STOP_ON_FAILED_DOCUMENT=1, a member killed by a signal, or when every + # member failed, the pass fails. local indexed=() failed=() rc for target in "${targets[@]}"; do part="$WORK/index.part.$i.scip" @@ -173,6 +174,11 @@ JSONEOF i=$((i + 1)) if [[ $rc -ne 0 ]]; then echo ">> member $target failed (exit $rc)" >&2 + # Above 128 the indexer was killed by a signal (a V8 heap abort is 134, a + # SIGKILL 137), not stopped by its sources: the pass fails, so the watermark + # stays and the next pass retries the member. scip-typescript's own errors + # (a tsconfig it cannot load, no file indexed) and an uncaught exception exit 1. + [[ $rc -gt 128 ]] && exit "$rc" [[ "${SCIP_STOP_ON_FAILED_DOCUMENT:-0}" == "1" ]] && exit "$rc" failed+=("$target") continue @@ -194,14 +200,10 @@ JSONEOF merge_args+=(--known-project "$t") done if [[ ${#failed[@]} -gt 0 ]]; then - # The candidates are the files the delta converts: the window's, or every - # TypeScript file when the converter reads whole indexes (a full pass or a - # config rebuild). - if [[ "$BASE" == "--full" || "$CONFIG_ONLY_REBUILD" == "1" ]]; then - git_paths ls-files -- "${TS_GLOBS[@]}" >"$WORK/candidates.txt" - else - cp "$WORK/changed.txt" "$WORK/candidates.txt" - fi + # Every file a failed member owns: the converter lists only the delta's own as + # skipped (`DeltaStream.tail`) and needs the rest to know which references + # lost their definition. + git_paths ls-files -- "${TS_GLOBS[@]}" >"$WORK/candidates.txt" for t in "${failed[@]}"; do merge_args+=(--failed-project "$t") done diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 6d6f0787828..e9ecfcdbdc4 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -172,10 +172,16 @@ def main(argv: list[str] | None = None) -> int: projects = args.project or None known = args.known_project or None if args.failed_paths is not None: - lines = args.paths.read_text(encoding="utf-8").splitlines() if args.paths else [] + # git prints a name that is not UTF-8 as its raw bytes + text = ( + args.paths.read_text(encoding="utf-8", errors="surrogateescape") if args.paths else "" + ) + lines = text.splitlines() candidates = [line for line in lines if line] failed = owned_by(candidates, args.failed_project, known or args.failed_project) - args.failed_paths.write_text("".join(f"{path}\n" for path in failed), encoding="utf-8") + args.failed_paths.write_text( + "".join(f"{path}\n" for path in failed), encoding="utf-8", errors="surrogateescape" + ) merge_indexes(args.indexes, args.output, projects, known) return 0 diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 5330aab9c63..db91864b3f9 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1314,9 +1314,14 @@ def __init__( scip_pb2 = _ensure_scip_pb2() data = _read_index(index_path) self._skips = _Skips(stop_on_failed_document, whole=changed is None) - # files whose indexer run failed: in no index, their rows stay, marked stale + # files whose indexer run failed: in no index, their rows stay, marked stale. + # The delta's own are warned about and counted as skipped documents; the rest + # tell `_ts_needs_failed_kind` which definitions the index lacks. self._failed = set(failed or ()) - self._skips.paths.update(self._failed) + failure = RuntimeError("its indexer run failed") + for path in sorted(self._failed): + if changed is None or path in changed: + self._skips.add(path, failure, -1) self._changed = changed self._run = _prepare( data, scip_pb2, source_root, exclude_generated, path_prefix, self._skips diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index a127c29d75a..1c329f3b3bd 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -8,6 +8,8 @@ import subprocess from pathlib import Path +import pytest + _SCRIPT = ( Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_typescript_delta.sh" ) @@ -21,7 +23,7 @@ for a in "$@"; do if [[ -n "${FAIL_TARGET:-}" && "$a" == "$FAIL_TARGET" ]]; then echo "error TS5023: Unknown compiler option" >&2 - exit 1 + exit "${FAIL_RC:-1}" fi done while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done @@ -176,7 +178,9 @@ def test_a_failing_member_leaves_the_others_and_lists_its_files(tmp_path: Path) assert "--full" in _convert_args(log) -def test_a_failing_member_in_a_delta_lists_only_its_window_files(tmp_path: Path) -> None: +def test_a_failing_member_in_a_delta_lists_every_file_it_owns(tmp_path: Path) -> None: + """The converter lists only the window's files as skipped; it needs the rest to + know which references in the window lost their definition.""" repo = _repo(tmp_path) (repo / "packages/lib/src/c.ts").write_text("export const c = 1;\n") _git(repo, "add", "-A") @@ -189,10 +193,23 @@ def test_a_failing_member_in_a_delta_lists_only_its_window_files(tmp_path: Path) head = _git(repo, "rev-parse", "HEAD") proc, log = _run_status(tmp_path, repo, base, head, {"FAIL_TARGET": "packages/lib"}) assert proc.returncode == 0, proc.stderr - assert _failed(log) == ["packages/lib/src/b.ts"] + assert _failed(log) == ["packages/lib/src/b.ts", "packages/lib/src/c.ts"] assert "--changed-files" in _convert_args(log) +@pytest.mark.parametrize("rc", [134, 137]) +def test_a_member_killed_by_a_signal_fails_the_pass(tmp_path: Path, rc: int) -> None: + """A V8 heap abort (134) or a SIGKILL (137) says nothing about the member's + sources: the pass fails, so the watermark stays and the next pass retries it.""" + repo = _repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + env = {"FAIL_TARGET": "packages/lib", "FAIL_RC": str(rc)} + proc, log = _run_status(tmp_path, repo, "--full", head, env) + assert proc.returncode == rc + assert not any(line.startswith("convert") for line in log.splitlines()) + assert not (tmp_path / "delta.json").exists() + + def test_a_pass_whose_every_member_failed_fails(tmp_path: Path) -> None: """Nothing converted: the pass fails and the watermark stays, as before.""" repo = _repo(tmp_path) diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 45d51ab2973..68a2955f740 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -254,6 +254,50 @@ def test_a_document_that_calls_into_a_failed_member_is_skipped_too(tmp_path: Pat assert plain["files"][0]["edges"] == [] +def test_failed_files_are_warned_about_and_counted(tmp_path: Path, capsys) -> None: + """A failed member's files are named on stderr in the skipped-document format the + server logs, and counted in `skipped_failed`; a window only its own.""" + conv = _converter() + index = _index_with(tmp_path, "g") + whole = conv.convert( + str(index), None, [], "h" * 40, "b" * 40, source_root="", failed=["pkg/b.ts", "pkg/c.ts"] + ) + assert whole["stats"]["skipped_failed"] == 2 + err = capsys.readouterr().err + assert f"{conv.SKIPPED_WARNING} 'pkg/b.ts'" in err + assert f"{conv.SKIPPED_WARNING} 'pkg/c.ts'" in err + window = conv.convert( + str(index), + {"src/a.cpp", "pkg/b.ts"}, + [], + "h" * 40, + "b" * 40, + source_root="", + failed=["pkg/b.ts", "pkg/c.ts"], + ) + assert window["stats"]["skipped_failed"] == 1 + err = capsys.readouterr().err + assert f"{conv.SKIPPED_WARNING} 'pkg/b.ts'" in err + assert "pkg/c.ts" not in err + + +def test_a_caller_whose_callee_file_is_outside_the_window_is_skipped(tmp_path: Path) -> None: + """The window holds the caller and another file of the failed member, not the + callee's file: the caller is skipped all the same, and only the window is listed.""" + index, root = _ts_index(tmp_path, with_b=False) + delta = _converter().convert( + str(index), + {"pkg/a/a.ts", "pkg/b/other.ts"}, + [], + "h" * 40, + "b" * 40, + source_root=str(root), + failed=["pkg/b/b.ts", "pkg/b/other.ts"], + ) + assert delta["files"] == [] + assert delta["skipped_files"] == ["pkg/a/a.ts", "pkg/b/other.ts"] + + def test_a_window_lists_only_its_own_failed_documents(tmp_path: Path) -> None: """The index-wide passes meet a bad document the window does not hold: it is warned about and counted, but not listed, so the server marks only what the window asked.""" From 0ac767eae110fecf863637f5bc529d0a74e2b900 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:32:45 +0000 Subject: [PATCH 30/81] A failing sibling tsconfig fails only the files no sibling indexed `owned_by` listed a path as failed when its preferred owner's scope matched a failed member's. Sibling tsconfigs share a scope (a root `tsconfig.app.json` and `tsconfig.node.json` both own `.`), so one failing sibling listed every TypeScript file, including those the other indexed. A path is now failed only when a failed member is one of its preferred owners, compared by name, and no part the merge kept holds its document: a sibling that indexed a file stands in for one that failed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 60 ++++++++++++++++------ tests/unit/test_scip_merge_indexes.py | 29 +++++++++++ 2 files changed, 73 insertions(+), 16 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index e9ecfcdbdc4..5579398bc84 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -40,6 +40,7 @@ def _load_ts_projects() -> Any: _ts_projects = _load_ts_projects() project_owns = _ts_projects.project_owns project_scope = _ts_projects.project_scope +posix_path = _ts_projects.posix_path def _ensure_scip_pb2() -> Any: @@ -63,26 +64,51 @@ def _scope_specificity(project: str) -> int: return len(scope) -def _preferred_owner(projects: list[str], relpath: str) -> str | None: +def _preferred_owners(projects: list[str], relpath: str) -> list[str]: + """The owners of `relpath` with the longest scope: one member, or sibling + explicit tsconfigs that share a directory.""" owners = [project for project in projects if project_owns(project, relpath)] if not owners: - return None + return [] best_scope = max(_scope_specificity(project) for project in owners) - tied = [project for project in owners if _scope_specificity(project) == best_scope] + return [project for project in owners if _scope_specificity(project) == best_scope] + + +def _preferred_owner(projects: list[str], relpath: str) -> str | None: + tied = _preferred_owners(projects, relpath) # Sibling explicit tsconfigs share a directory scope. Returning one of # them still lets each sibling keep its documents (scopes match) while # a shorter ancestor, such as a root tsconfig, is dropped. - return tied[0] - - -def owned_by(paths: list[str], members: list[str], known_projects: list[str]) -> list[str]: - """The paths whose document the merge would take from one of `members`: the - files of a member whose indexer failed, which no other part may stand in for.""" - scopes = {project_scope(member) for member in members} + return tied[0] if tied else None + + +def _member_id(project: str) -> str: + """A member as --known-project names it: the harness indexes a directory + without a tsconfig through a generated dir/tsconfig.scip.json.""" + path = posix_path(project).rstrip("/") + if path == "tsconfig.scip.json" or path.endswith("/tsconfig.scip.json"): + return str(project_scope(path)) + return path or "." + + +def owned_by( + paths: list[str], + members: list[str], + known_projects: list[str], + kept: set[str] | frozenset[str] = frozenset(), +) -> list[str]: + """The paths a member whose indexer failed would have given the merge: one of + `members` is among the path's preferred owners and no part kept its document + (`kept`, from `merge_indexes`). Sibling tsconfigs share a scope, so a sibling + that indexed a file stands in for one that failed; the rest of the failed + sibling's files stay failed.""" + failed = {_member_id(member) for member in members} out = [] for path in paths: - owner = _preferred_owner(known_projects, path) - if owner is not None and project_scope(owner) in scopes: + if path in kept: + continue + owners = _preferred_owners(known_projects, path) + if any(_member_id(owner) in failed for owner in owners): out.append(path) return out @@ -92,7 +118,8 @@ def merge_indexes( output: Path, projects: list[str] | None = None, known_projects: list[str] | None = None, -) -> None: +) -> set[str]: + """Write the merged index; return the paths whose document it holds.""" if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") scip_pb2 = _ensure_scip_pb2() @@ -134,10 +161,11 @@ def merge_indexes( has_payload = True if not has_payload: output.write_bytes(b"") - return + return set() for doc in documents.values(): merged.documents.append(doc) output.write_bytes(merged.SerializeToString()) + return set(documents) def main(argv: list[str] | None = None) -> int: @@ -171,6 +199,7 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) projects = args.project or None known = args.known_project or None + kept = merge_indexes(args.indexes, args.output, projects, known) if args.failed_paths is not None: # git prints a name that is not UTF-8 as its raw bytes text = ( @@ -178,11 +207,10 @@ def main(argv: list[str] | None = None) -> int: ) lines = text.splitlines() candidates = [line for line in lines if line] - failed = owned_by(candidates, args.failed_project, known or args.failed_project) + failed = owned_by(candidates, args.failed_project, known or args.failed_project, kept) args.failed_paths.write_text( "".join(f"{path}\n" for path in failed), encoding="utf-8", errors="surrogateescape" ) - merge_indexes(args.indexes, args.output, projects, known) return 0 diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 6eae75e3e9f..da4ca0975de 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -327,3 +327,32 @@ def test_a_failed_member_owns_the_paths_the_merge_would_take_from_it() -> None: assert _MOD.owned_by(paths, ["src"], known) == ["src/main.ts"] assert _MOD.owned_by(paths, ["pkg/tsconfig.scip.json"], known) == ["pkg/a.ts"] assert _MOD.owned_by(paths, ["tsconfig.repo.json"], known) == ["eslint.config.mjs", "x/y.ts"] + + +def _failed_paths(tmp_path: Path, indexed: str, failed: str, docs: list[str]) -> str: + """Root `tsconfig.app.json` and `tsconfig.node.json`, one indexed, one failed.""" + part = tmp_path / "part.scip" + part.write_bytes(_index_with_docs(docs)) + candidates = tmp_path / "candidates.txt" + candidates.write_text("src/main.ts\nsrc/App.tsx\nvite.config.ts\n") + out = tmp_path / "failed.txt" + args = ["--output", str(tmp_path / "merged.scip"), "--project", indexed] + args += ["--known-project", "tsconfig.app.json", "--known-project", "tsconfig.node.json"] + args += ["--failed-project", failed, "--paths", str(candidates), "--failed-paths", str(out)] + assert _MOD.main([*args, str(part)]) == 0 + return out.read_text() + + +def test_a_failing_sibling_tsconfig_fails_only_the_files_no_sibling_indexed( + tmp_path: Path, +) -> None: + """Sibling tsconfigs share the scope '.': a file is failed only when the failed + sibling is among its owners and no sibling that indexed holds its document.""" + app_failed = _failed_paths( + tmp_path, "tsconfig.node.json", "tsconfig.app.json", ["vite.config.ts"] + ) + assert app_failed == "src/main.ts\nsrc/App.tsx\n" + node_failed = _failed_paths( + tmp_path, "tsconfig.app.json", "tsconfig.node.json", ["src/main.ts", "src/App.tsx"] + ) + assert node_failed == "vite.config.ts\n" From f91022545f74b01a9017b1dfa461a559017d9fb9 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:32:45 +0000 Subject: [PATCH 31/81] Read the failed-files list the way the merge writes it The merge writes `--failed-paths` with `surrogateescape`, so a git name that is not UTF-8 keeps its raw bytes; the converter read the list strictly and aborted. It now reads it with `surrogateescape` and drops such a name: no document or stored row carries it, and the delta is strict JSON. `--changed-files` and `--deleted-files` are read as before. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 13 ++++++++++++- tests/unit/test_scip_to_delta_skip.py | 13 +++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index db91864b3f9..72227a1220a 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1528,6 +1528,17 @@ def _path_list(path: str | None) -> list[str]: return [ln.strip() for ln in Path(path).read_text().splitlines() if ln.strip()] +def _failed_path_list(path: str | None) -> list[str]: + """`--failed-files` as the merge writes it: git's raw bytes for a name that is + not UTF-8. Such a name is dropped: no document or stored row carries it, and + the delta is strict JSON, so listing it would fail the whole delta.""" + if not path: + return [] + text = Path(path).read_text(encoding="utf-8", errors="surrogateescape") + names = (ln.strip() for ln in text.splitlines()) + return [n for n in names if n and not any("\udc80" <= ch <= "\udcff" for ch in n)] + + def _summary(counts: dict) -> str: return ( f"delta: {counts['files']} files, {counts['symbols']} symbols, {counts['edges']} edges " @@ -1618,7 +1629,7 @@ def main() -> int: exclude_generated=bool(args.exclude_generated), path_prefix=prefix, stop_on_failed_document=bool(args.stop_on_failed_document), - failed=_path_list(args.failed_files), + failed=_failed_path_list(args.failed_files), ) if args.dry_run: diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 68a2955f740..c3d6d108b7b 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -197,6 +197,19 @@ def test_failed_files_are_listed_as_skipped(tmp_path: Path) -> None: assert window["skipped_files"] == ["pkg/b.ts"] +def test_a_failed_file_whose_name_is_not_utf8_does_not_stop_the_run(tmp_path: Path) -> None: + """The merge writes git's raw bytes for such a name. No document or stored row carries + it and the delta is strict JSON, so it is dropped; the other failed files are listed.""" + index = _index_with(tmp_path, "g") + failed = tmp_path / "failed.txt" + failed.write_bytes(b"pkg/b.ts\npkg/caf\xe9.ts\n") + out = tmp_path / "delta.json" + proc = _run(index, out, "--failed-files", str(failed)) + assert proc.returncode == 0, proc.stderr + delta = json.loads(out.read_text()) + assert delta["skipped_files"] == ["pkg/b.ts"] + + def _ts_index(tmp_path: Path, *, with_b: bool) -> tuple[Path, Path]: """pkg/a/`a.ts` defines run(), which calls the arrow-function constant `helper` of pkg/b/`b.ts`. Without b's document the index cannot say `helper` is a function.""" From f1205719c6b6a2730e2a5ba99d11d7d1fcb69a3c Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:52:53 +0000 Subject: [PATCH 32/81] The record reader applies the protobuf parser's tag and length bounds _top_level_records refused only field number 0. A field number of 2**29 or more, at the top level or in a group tag, is refused by the parser but was skipped here, so a part carrying one merged and converted with exit 0. Tags and length prefixes are now read as the parser reads them: a varint of at most five bytes that fits in 32 bits, which bounds the field number to 1..2**29 - 1. Value varints keep the ten-byte limit. The reserved range 19000..19999 and redundant trailing zero bytes inside the five-byte limit are accepted, as the parser accepts them. Lengths of 2**63 and above were already refused and are pinned. Behaviour was compared with the upb parser, the installed default. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 43 +++++++++------ tests/unit/test_scip_merge_indexes.py | 77 +++++++++++++++++++++++++++ tests/unit/test_scip_to_delta_cli.py | 65 ++++++++++++++++++++++ 3 files changed, 170 insertions(+), 15 deletions(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 23c3da6d4fd..2fb24da5009 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -808,12 +808,17 @@ def _top_level_records(data: bytes): Every other field is skipped the way the protobuf parser skips it, and anything the parser refuses is refused here with a ValueError: a record, - fixed-width value, varint or tag that runs past the end, a varint longer - than ten bytes, field number 0, an unbalanced group, and wire types 6 and 7. + fixed-width value, varint or tag that runs past the end, a value varint + longer than ten bytes, a tag or length varint longer than five bytes or + beyond 32 bits, a field number outside 1..2**29 - 1, an unbalanced group, + and wire types 6 and 7. Field numbers in the reserved range 19000..19999 + and redundant trailing zero bytes inside the five-byte limit are accepted, + as the parser accepts them. """ end, max_depth = len(data), 100 # the parser's own group nesting limit + max_field = (1 << 29) - 1 - def varint(p: int) -> tuple[int, int]: + def varint(p: int, max_bytes: int = 10) -> tuple[int, int]: shift = result = 0 start = p while True: @@ -825,8 +830,22 @@ def varint(p: int) -> tuple[int, int]: if not b & 0x80: return result, p shift += 7 - if shift >= 70: - raise ValueError(f"varint at {start} is longer than 10 bytes") + if shift >= 7 * max_bytes: + raise ValueError(f"varint at {start} is longer than {max_bytes} bytes") + + def word32(p: int) -> tuple[int, int]: + """A tag or a length: the parser reads it as a 32-bit varint.""" + value, after = varint(p, 5) + if value >> 32: + raise ValueError(f"varint at {p} does not fit in 32 bits") + return value, after + + def tag_at(p: int) -> tuple[int, int, int]: + tag, after = word32(p) + field = tag >> 3 + if not 1 <= field <= max_field: + raise ValueError(f"field number {field} at {p} is outside 1..{max_field}") + return field, tag & 7, after def span(p: int, size: int) -> int: if p + size > end: @@ -842,7 +861,7 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: if wire == 5: return span(p, 4) if wire == 2: - length, p = varint(p) + length, p = word32(p) return span(p, length) if wire == 3: if depth >= max_depth: @@ -850,10 +869,7 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: while True: if p >= end: raise ValueError(f"group {field} at {p} is not closed before the end") - tag, p = varint(p) - inner, inner_wire = tag >> 3, tag & 7 - if inner == 0: - raise ValueError(f"field number 0 at {p}") + inner, inner_wire, p = tag_at(p) if inner_wire == 4: if inner != field: raise ValueError(f"group {field} is closed by group {inner} at {p}") @@ -863,12 +879,9 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: pos = 0 while pos < end: - tag, pos = varint(pos) - field, wire = tag >> 3, tag & 7 - if field == 0: - raise ValueError(f"field number 0 at {pos}") + field, wire, pos = tag_at(pos) if wire == 2: # length-delimited - length, pos = varint(pos) + length, pos = word32(pos) stop = span(pos, length) payload = data[pos:stop] pos = stop diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 6dfe301c4a5..80cb38a47d7 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -455,6 +455,65 @@ def test_the_reader_names_the_offset_of_a_record_that_runs_past_the_end() -> Non "wire type 7": bytes([0x4F]), "unknown record with a long length": bytes([0x4A, 0x05, 0x01]), } + + +def _varint(n: int) -> bytes: + out = bytearray() + while True: + low, n = n & 0x7F, n >> 7 + out.append(low | (0x80 if n else 0)) + if not n: + return bytes(out) + + +def _tag(field: int, wire: int) -> bytes: + return _varint(field << 3 | wire) + + +_MAX_FIELD = (1 << 29) - 1 + +# More bytes the protobuf parser refuses: field numbers outside 1..2**29 - 1 (also in +# group tags), tags and lengths longer than five bytes or beyond 32 bits, huge lengths. +_REFUSED_TAILS.update( + { + "field number 2**29": _tag(_MAX_FIELD + 1, 2) + b"\x00", + "field number 2**29 on a varint": _tag(_MAX_FIELD + 1, 0) + b"\x01", + "field number 2**32": _tag(1 << 32, 2) + b"\x00", + "group with field number 2**29": _tag(_MAX_FIELD + 1, 3) + _tag(_MAX_FIELD + 1, 4), + "group holding field number 2**29": ( + _tag(9, 3) + _tag(_MAX_FIELD + 1, 0) + b"\x01" + _tag(9, 4) + ), + "tag of six bytes": b"\xc8\x80\x80\x80\x80\x00\x01", + "tag of ten bytes": b"\xc8" + b"\x80" * 8 + b"\x00\x01", + "tag of five bytes beyond 32 bits": b"\xc8\xff\xff\xff\x1f\x01", + "length of six bytes": _tag(9, 2) + b"\x80" * 5 + b"\x00", + "length of ten bytes": _tag(9, 2) + b"\x80" * 9 + b"\x00", + "length of five bytes beyond 32 bits": _tag(9, 2) + b"\x80\x80\x80\x80\x10", + "length 2**63": _tag(9, 2) + _varint(1 << 63), + "length 2**64 - 1": _tag(9, 2) + _varint((1 << 64) - 1), + "group tag of six bytes inside a group": ( + _tag(9, 3) + b"\xc8\x80\x80\x80\x80\x00\x01" + _tag(9, 4) + ), + } +) + +# Bytes the parser accepts and skips: the reserved range 19000..19999, the largest +# field number, and redundant trailing zero bytes within five bytes. +_ACCEPTED_TAILS = { + "largest field number": _tag(_MAX_FIELD, 2) + b"\x00", + "largest field number on a varint": _tag(_MAX_FIELD, 0) + b"\x01", + "group with the largest field number": _tag(_MAX_FIELD, 3) + _tag(_MAX_FIELD, 4), + "reserved field 19000": _tag(19000, 2) + b"\x00", + "reserved field 19999 on a varint": _tag(19999, 0) + b"\x01", + "group holding a reserved field": _tag(9, 3) + _tag(19500, 0) + b"\x01" + _tag(9, 4), + "tag with one redundant zero byte": b"\xc8\x00\x01", + "tag padded to five bytes": b"\xc8\x80\x80\x80\x00\x01", + "end group tag padded": _tag(9, 3) + b"\xcc\x00", + "length padded to five bytes": _tag(9, 2) + b"\x81\x80\x80\x80\x00" + b"x", + "length with one redundant zero byte": _tag(9, 2) + b"\x81\x00" + b"x", +} + + _REFUSED = pytest.mark.parametrize("how", list(_REFUSED_TAILS)) @@ -496,3 +555,21 @@ def test_merge_accepts_a_part_with_a_balanced_unknown_group(tmp_path: Path) -> N _MOD.merge_indexes([part], out) merged = _scip_pb2().Index.FromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] + + +@pytest.mark.parametrize("how", list(_ACCEPTED_TAILS)) +def test_the_reader_accepts_what_the_protobuf_parser_accepts(how: str) -> None: + raw = _index_with_docs(["packages/app/src/a.ts"], ["a"]) + _ACCEPTED_TAILS[how] + _scip_pb2().Index.FromString(raw) # the case is one the parser accepts + assert [f for f, _ in _MOD._top_level_records(raw)][:2] == [1, 2] + + +@pytest.mark.parametrize("how", list(_ACCEPTED_TAILS)) +def test_merge_keeps_a_part_the_protobuf_parser_accepts(tmp_path: Path, how: str) -> None: + part = tmp_path / "part.scip" + part.write_bytes(_index_with_docs(["packages/app/src/a.ts"], ["a"]) + _ACCEPTED_TAILS[how]) + _scip_pb2().Index.FromString(part.read_bytes()) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index 96539d99089..cbdd0d5fe8d 100644 --- a/tests/unit/test_scip_to_delta_cli.py +++ b/tests/unit/test_scip_to_delta_cli.py @@ -389,6 +389,63 @@ def test_a_record_that_runs_past_the_end_of_the_index_fails_the_run(tmp_path: Pa } +def _varint(n: int) -> bytes: + out = bytearray() + while True: + low, n = n & 0x7F, n >> 7 + out.append(low | (0x80 if n else 0)) + if not n: + return bytes(out) + + +def _tag(field: int, wire: int) -> bytes: + return _varint(field << 3 | wire) + + +_MAX_FIELD = (1 << 29) - 1 + +# More bytes the protobuf parser refuses: field numbers outside 1..2**29 - 1 (also in +# group tags), tags and lengths longer than five bytes or beyond 32 bits, huge lengths. +_REFUSED_TAILS.update( + { + "field number 2**29": _tag(_MAX_FIELD + 1, 2) + b"\x00", + "field number 2**29 on a varint": _tag(_MAX_FIELD + 1, 0) + b"\x01", + "field number 2**32": _tag(1 << 32, 2) + b"\x00", + "group with field number 2**29": _tag(_MAX_FIELD + 1, 3) + _tag(_MAX_FIELD + 1, 4), + "group holding field number 2**29": ( + _tag(9, 3) + _tag(_MAX_FIELD + 1, 0) + b"\x01" + _tag(9, 4) + ), + "tag of six bytes": b"\xc8\x80\x80\x80\x80\x00\x01", + "tag of ten bytes": b"\xc8" + b"\x80" * 8 + b"\x00\x01", + "tag of five bytes beyond 32 bits": b"\xc8\xff\xff\xff\x1f\x01", + "length of six bytes": _tag(9, 2) + b"\x80" * 5 + b"\x00", + "length of ten bytes": _tag(9, 2) + b"\x80" * 9 + b"\x00", + "length of five bytes beyond 32 bits": _tag(9, 2) + b"\x80\x80\x80\x80\x10", + "length 2**63": _tag(9, 2) + _varint(1 << 63), + "length 2**64 - 1": _tag(9, 2) + _varint((1 << 64) - 1), + "group tag of six bytes inside a group": ( + _tag(9, 3) + b"\xc8\x80\x80\x80\x80\x00\x01" + _tag(9, 4) + ), + } +) + +# Bytes the parser accepts and skips: the reserved range 19000..19999, the largest +# field number, and redundant trailing zero bytes within five bytes. +_ACCEPTED_TAILS = { + "largest field number": _tag(_MAX_FIELD, 2) + b"\x00", + "largest field number on a varint": _tag(_MAX_FIELD, 0) + b"\x01", + "group with the largest field number": _tag(_MAX_FIELD, 3) + _tag(_MAX_FIELD, 4), + "reserved field 19000": _tag(19000, 2) + b"\x00", + "reserved field 19999 on a varint": _tag(19999, 0) + b"\x01", + "group holding a reserved field": _tag(9, 3) + _tag(19500, 0) + b"\x01" + _tag(9, 4), + "tag with one redundant zero byte": b"\xc8\x00\x01", + "tag padded to five bytes": b"\xc8\x80\x80\x80\x00\x01", + "end group tag padded": _tag(9, 3) + b"\xcc\x00", + "length padded to five bytes": _tag(9, 2) + b"\x81\x80\x80\x80\x00" + b"x", + "length with one redundant zero byte": _tag(9, 2) + b"\x81\x00" + b"x", +} + + def _convert_raw(tmp_path: Path, raw: bytes) -> subprocess.CompletedProcess[str]: index = tmp_path / "damaged.scip" index.write_bytes(raw) @@ -419,3 +476,11 @@ def test_the_converter_skips_a_balanced_unknown_group(tmp_path: Path) -> None: _pb().Index.FromString(raw) proc = _convert_raw(tmp_path, raw) assert proc.returncode == 0, proc.stderr + + +@pytest.mark.parametrize("how", list(_ACCEPTED_TAILS)) +def test_the_converter_accepts_what_the_protobuf_parser_accepts(tmp_path: Path, how: str) -> None: + raw = _index(tmp_path).read_bytes() + _ACCEPTED_TAILS[how] + _pb().Index.FromString(raw) + proc = _convert_raw(tmp_path, raw) + assert proc.returncode == 0, proc.stderr From e6286e3bc3b7f88cf34bebd98e30b4ac2ae00158 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 02:53:48 +0000 Subject: [PATCH 33/81] Read every harness path list the way git writes it The harness passes a changed or deleted name that is not UTF-8 as raw bytes, as the merge does for the failed list, and `_path_list` read it strictly: a bad name in a failed member's window stopped the healthy member's delta. One reader now serves all three lists with `surrogateescape` and drops such a name: no document or stored row carries it, and the delta is strict JSON. Dropping a name from a changed or deleted list never sends it, so #1959's wire decision holds. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 13 ++---- .../test_run_typescript_delta_umbrella.py | 40 ++++++++++++++++++- tests/unit/test_scip_to_delta_skip.py | 26 ++++++++++++ 3 files changed, 69 insertions(+), 10 deletions(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 72227a1220a..5c5c64d2eeb 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1523,14 +1523,9 @@ def _strip_prefix(path: str, prefix: str) -> str: def _path_list(path: str | None) -> list[str]: - if not path: - return [] - return [ln.strip() for ln in Path(path).read_text().splitlines() if ln.strip()] - - -def _failed_path_list(path: str | None) -> list[str]: - """`--failed-files` as the merge writes it: git's raw bytes for a name that is - not UTF-8. Such a name is dropped: no document or stored row carries it, and + """A newline list of paths as the harness writes it (`--changed-files`, + `--deleted-files`) or the merge does (`--failed-files`): git's raw bytes for a name + that is not UTF-8. Such a name is dropped: no document or stored row carries it, and the delta is strict JSON, so listing it would fail the whole delta.""" if not path: return [] @@ -1629,7 +1624,7 @@ def main() -> int: exclude_generated=bool(args.exclude_generated), path_prefix=prefix, stop_on_failed_document=bool(args.stop_on_failed_document), - failed=_failed_path_list(args.failed_files), + failed=_path_list(args.failed_files), ) if args.dry_run: diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 1c329f3b3bd..b54affa9f9d 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -32,7 +32,20 @@ _FAKE_PYTHON = """#!/usr/bin/env bash # Forward discover/filter/merge to the real helpers; stub only the converter. case "${1-}" in - *scip_ts_projects.py|*scip_merge_indexes.py) exec "$REAL_PYTHON" "$@" ;; + *scip_to_delta.py) [[ -n "${REAL_CONVERT:-}" ]] && exec "$REAL_PYTHON" "$@" ;; + *scip_ts_projects.py) + # REAL_CONVERT runs the real converter; the window filter is not what it tests, so + # `filter` keeps every member and `has-config` finds no config change. + if [[ -n "${REAL_CONVERT:-}" && "${2-}" == filter ]]; then + shift + while [[ "$1" != -- ]]; do shift; done + shift + printf '%s\\n' "$@" + exit 0 + fi + [[ -n "${REAL_CONVERT:-}" && "${2-}" == has-config ]] && exit 1 + exec "$REAL_PYTHON" "$@" ;; + *scip_merge_indexes.py) exec "$REAL_PYTHON" "$@" ;; esac { printf 'convert' @@ -197,6 +210,31 @@ def test_a_failing_member_in_a_delta_lists_every_file_it_owns(tmp_path: Path) -> assert "--changed-files" in _convert_args(log) +def test_a_failed_members_non_utf8_file_in_the_window_does_not_stop_the_delta( + tmp_path: Path, +) -> None: + """Incremental pass, real converter: packages/lib fails, and the window holds one of + its files whose name is not UTF-8. git prints the name as raw bytes into the changed + and failed lists; the healthy member's delta still converts, and the name is dropped.""" + repo = _repo(tmp_path) + base = _git(repo, "rev-parse", "HEAD") + bad = Path(os.fsdecode(b"packages/lib/src/caf\xe9.ts")) + try: + (repo / bad).write_text("export const c = 1;\n") + except OSError: + pytest.skip("the filesystem refuses a name that is not UTF-8") + (repo / "packages/lib/src/b.ts").write_text("export const b = 2;\n") + (repo / "packages/app/src/a.ts").write_text("export const a = 2;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "window") + head = _git(repo, "rev-parse", "HEAD") + env = {"FAIL_TARGET": "packages/lib", "REAL_CONVERT": "1"} + proc, _ = _run_status(tmp_path, repo, base, head, env) + assert proc.returncode == 0, proc.stderr + delta = json.loads((tmp_path / "delta.json").read_text()) + assert delta["skipped_files"] == ["packages/lib/src/b.ts"] + + @pytest.mark.parametrize("rc", [134, 137]) def test_a_member_killed_by_a_signal_fails_the_pass(tmp_path: Path, rc: int) -> None: """A V8 heap abort (134) or a SIGKILL (137) says nothing about the member's diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index c3d6d108b7b..2f5b69ad09c 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -210,6 +210,32 @@ def test_a_failed_file_whose_name_is_not_utf8_does_not_stop_the_run(tmp_path: Pa assert delta["skipped_files"] == ["pkg/b.ts"] +def test_a_changed_or_deleted_name_that_is_not_utf8_does_not_stop_the_run( + tmp_path: Path, +) -> None: + """The harness writes git's raw bytes into `--changed-files` and `--deleted-files` + too. Such a name is dropped, as in the failed list: no document or stored row carries + it and the delta is strict JSON. The other names are kept.""" + index = _index_with(tmp_path, "g") + changed = tmp_path / "changed.txt" + changed.write_bytes(b"src/a.cpp\nsrc/caf\xe9.cpp\n") + deleted = tmp_path / "deleted.txt" + deleted.write_bytes(b"src/gone.cpp\nsrc/old\xe9.cpp\n") + out = tmp_path / "delta.json" + proc = subprocess.run( + [sys.executable, str(_CONVERTER), "--index", str(index), "--commit", "h" * 40] + + ["--base", "b" * 40, "--source-root", "", "--dry-run", str(out)] + + ["--changed-files", str(changed), "--deleted-files", str(deleted)], + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, proc.stderr + delta = json.loads(out.read_text()) + assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] + assert delta["deleted_files"] == ["src/gone.cpp"] + + def _ts_index(tmp_path: Path, *, with_b: bool) -> tuple[Path, Path]: """pkg/a/`a.ts` defines run(), which calls the arrow-function constant `helper` of pkg/b/`b.ts`. Without b's document the index cannot say `helper` is a function.""" From e55d0a656363299ecb42abfc003564287b00d8a2 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 03:05:58 +0000 Subject: [PATCH 34/81] Read a skipped document's effect on callers and seeds as stale The constructor scan reads every document. When it skips one, that document may declare a type's only constructor, so a converted factory call would lose its edge and the apply would retire the old one. Such a caller is now skipped too: it keeps its rows and is marked stale. code.callers and code.callees read staleness only for the paths of edges they return. A seed in a skipped file with no edge, such as a function whose first call came in the skipped revision, read as exact. The seed's own path is now read too, when the compiler tier covers it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 2 +- scripts/scip_harness/README.md | 5 +- scripts/scip_harness/scip_to_delta.py | 33 ++++++-- server/code/api/models_symbol.py | 3 +- server/code/app/symbol/coverage.py | 15 ++-- server/code/app/symbol/graph.py | 16 ++-- server/code/domain/index/epistemic.py | 4 +- .../integration/test_code_scip_stale_mark.py | 42 ++++++++++ tests/unit/test_scip_to_delta_skip.py | 78 +++++++++++++++++++ 9 files changed, 178 insertions(+), 20 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 0a1d6464b22..b7cb284bc5e 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1373,7 +1373,7 @@ the output to read. | compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | | a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | | compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | -| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window (callers and impact name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | +| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window, and so is a window file with a factory call, whose constructor may be in the skipped document (`code.callers` and `code.callees` name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | | a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | | GitHub rate limit | the pass ends, cursor unmoved | the next pass | | branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 0591ea2e486..870306b6cbf 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -39,7 +39,10 @@ A document the converter cannot parse or convert (a string that is not UTF-8, say) is skipped: it is named once on stderr (`scip_to_delta: warning: skipped document …`) and counted in the summary line. It is listed in the delta's `skipped_files` when it is one of the files the delta converts (a window's -own, or any in a full run). The rest of the index converts. In a run over +own, or any in a full run). The rest of the index converts. The constructor +scan reads every document, so after it skips one, a converted file with a factory +call (`std::make_shared`) is skipped too: the skipped document may declare +`T`'s only constructor, and without it the call would have no edge. In a run over every document (no `--changed-files`), a failed document whose path cannot be read (one that is not UTF-8, say) fails the run: the server would read its file as gone. The server keeps diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 46a81e271b8..596f48ba1d0 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -729,6 +729,11 @@ def _ctor_overloads(data, scip_pb2, skips: _Skips) -> dict[str, list[str]]: return {k: sorted(v) for k, v in out.items()} +class _OverloadsIncomplete(Exception): + """A factory call in a run whose constructor scan skipped a document: the skipped + document may declare the type's only constructor, so the call's edge is unknown.""" + + class _SourceLines: """Lines of the checkout's files, read on demand — the factory test needs the text before the type token on its line. `None` for a file the root @@ -857,10 +862,12 @@ def __init__(self, stop: bool = False, whole: bool = False) -> None: self.stop, self.whole = stop, whole self.labels: set[str] = set() self.paths: set[str] = set() + self.failures = 0 # every skip, repeats included: a pass can tell it missed one def add(self, path: str, err: Exception, index: int) -> None: if self.stop: raise err + self.failures += 1 if self.whole and not path: raise ValueError(f"document {index} failed and its path cannot be read") from err # a document whose path cannot be read is told apart by its place in the index @@ -993,12 +1000,14 @@ def __init__( exclude_generated: bool, *, is_python: bool = False, + ctors_complete: bool = True, ) -> None: self.src = src self.is_ts = is_ts self.is_cxx = is_cxx self.is_python = is_python self.ctors = ctors + self.ctors_complete = ctors_complete self.ancestors = ancestors self.exclude_generated = exclude_generated self.factory_edges = 0 @@ -1042,11 +1051,21 @@ def _prepare( ctors: dict[str, list[str]] = {} # constructor calls through factories are a C++ form (`std::make_shared`) is_cxx = scheme == CXX_SCHEME + complete = True # only the C++ scan's own skips count, not another pass's if src.available and is_cxx: + failed = skips.failures ctors = _ctor_overloads(data, scip_pb2, skips) + complete = skips.failures == failed ancestors = _implementation_targets(data, scip_pb2, skips) return _Run( - src, is_ts, is_cxx, ctors, ancestors, exclude_generated, is_python=scheme == "scip-python" + src, + is_ts, + is_cxx, + ctors, + ancestors, + exclude_generated, + is_python=scheme == "scip-python", + ctors_complete=complete, ) @@ -1061,11 +1080,11 @@ def _edge(kind: str, encl: tuple[str, str], to_q: str, to_sig: str, line: int) - } -def _factory_ends(doc, lines: list[str] | None, ctors: dict[str, list[str]]) -> list: +def _factory_ends(doc, lines: list[str] | None, wanted: bool) -> list: """(0-based line, end col) of every factory call in the document, sorted, for a type argument that sits on a later line than its factory.""" out: list[tuple[int, int]] = [] - if lines is None or not ctors: + if lines is None or not wanted: return out for occ in doc.occurrences: parsed = _parse_symbol(occ.symbol) @@ -1109,7 +1128,7 @@ def _convert_document(doc, run: _Run) -> dict | None: type_refs: list[tuple[int, str]] = [] # TypeScript only factory_refs: list[tuple[int, str]] = [] # (line, class qname) under a factory seen_defs: set[str] = set() - factory_ends = _factory_ends(doc, lines, ctors) + factory_ends = _factory_ends(doc, lines, bool(ctors) or not run.ctors_complete) for occ in doc.occurrences: parsed = _parse_symbol(occ.symbol) if parsed is None: @@ -1120,7 +1139,7 @@ def _convert_document(doc, run: _Run) -> dict | None: kind == "class" and not occ.symbol_roles & 0x1 and occ.symbol.rstrip().endswith("#") - and qname in ctors + and (qname in ctors or not run.ctors_complete) ): if _factory_type_ref(lines, occ.range): # `std::make_shared(...)`: the type token is the only trace @@ -1172,6 +1191,10 @@ def _convert_document(doc, run: _Run) -> dict | None: # unit is a `uses_type` edge (the compiler resolved it) type_refs.append((line, occ.symbol)) + if factory_refs and not run.ctors_complete: + # converted without the type's constructors, the call would have no edge and the + # apply would retire the one the file had; skipped, the file keeps its rows, marked + raise _OverloadsIncomplete("a factory call, and the constructor scan skipped a document") fn_defs.sort() # innermost-first when spans exist: sort widest-first per start so a # later (narrower) containing span overwrites a wider one diff --git a/server/code/api/models_symbol.py b/server/code/api/models_symbol.py index f76fad5e533..3c974318b8f 100644 --- a/server/code/api/models_symbol.py +++ b/server/code/api/models_symbol.py @@ -524,7 +524,8 @@ def _drop_unrequested_candidates( # treesitter_only_files, external_calls, ctor_edges_absent (a # constructor seed with no edge in an index that predates constructor # calls through factories), scip_stale_files (a compiler-tier edge - # served from a file changed since that tier last ran, or one it skipped), + # served from a file changed since that tier last ran, or one it skipped, or a seed + # in such a file), # truncated (the walk stopped short of the graph)}. epistemic: str = "lower_bound" # Why `epistemic` is `lower_bound`, from the set above; empty when it is `exact`. diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index b23f69e410f..813a0071c71 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -76,11 +76,16 @@ async def _scip_coverage( return covered -async def _scip_stale(repo: CodeRepo, org: str, ns: str, edges: list[Any]) -> set[str]: - """Served compiler-tier edge paths the compiler tier has not seen since they - changed. Fail-open to UNPROVEN: a failed read counts every one of them stale, so - the answer can only fall to a lower bound, never claim exact.""" - paths = list(dict.fromkeys(e.path for e in edges if e.tier == "scip")) +async def _scip_stale( + repo: CodeRepo, org: str, ns: str, edges: list[Any], seed_paths: list[str] +) -> set[str]: + """Served compiler-tier edge paths, and seed paths, the compiler tier has not seen + since they changed. The seed's own path counts with no edge served from it: a seed + that gained its first call (or its first caller in its file) in a revision the tier + skipped has none. Fail-open to UNPROVEN: a failed read counts every one of them + stale, so the answer can only fall to a lower bound, never claim exact.""" + edge_paths = (e.path for e in edges if e.tier == "scip") + paths = list(dict.fromkeys([*edge_paths, *(p for p in seed_paths if p)])) if not paths: return set() try: diff --git a/server/code/app/symbol/graph.py b/server/code/app/symbol/graph.py index 0581ddcd6ef..fe0226a880b 100644 --- a/server/code/app/symbol/graph.py +++ b/server/code/app/symbol/graph.py @@ -387,7 +387,8 @@ async def _floor_reads( walk's blind spot: sites named like the seed for callers, the seed's own declined call sites for callees.""" coverage = _scip_coverage(repo, org, ns, seed_paths, seeds) - stale = _scip_stale(repo, org, ns, edges_out) + stale = _scip_stale(repo, org, ns, edges_out, seed_paths) + dispatch_missing = False if direction == "callers": declined, scip_paths, dispatch_missing, stale_paths = await asyncio.gather( _declined_safe(repo, org, ns, seeds), @@ -395,11 +396,14 @@ async def _floor_reads( _dispatch_missing(repo, org, ns, seeds, dispatch_rows, attempted=dispatch_attempted), stale, ) - return declined, scip_paths, dispatch_missing, stale_paths - declined, scip_paths, stale_paths = await asyncio.gather( - _declined_outgoing_safe(repo, org, ns, seeds), coverage, stale - ) - return declined, scip_paths, False, stale_paths + else: + declined, scip_paths, stale_paths = await asyncio.gather( + _declined_outgoing_safe(repo, org, ns, seeds), coverage, stale + ) + # a seed path the compiler tier does not cover is `treesitter_only_files` already + served = {e.path for e in edges_out if e.tier == "scip"} + stale_paths = {p for p in stale_paths if p in served or p in scip_paths} + return declined, scip_paths, dispatch_missing, stale_paths def _not_found(input: CodeCallersInput, overlay: Any) -> str: diff --git a/server/code/domain/index/epistemic.py b/server/code/domain/index/epistemic.py index 1eef63297ab..43810b120c3 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -26,7 +26,9 @@ the fast tier rewrote after the compiler tier's last run, or whose document that run skipped: its line and caller come - from content that tier never saw + from content that tier never saw; or a + seed in such a file, whose own calls + and callers may be missing truncated the walk stopped short of the graph (a node cap, a hop read cut at its row limit, a page): the answer lists part of it diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 1d86bcf0a66..02b68e87fbc 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -366,3 +366,45 @@ async def no_marks(*a: Any) -> None: await apply_delta(repo, org, ns, ScipDelta(commit=second, files=[_other()]), tier="clang") await repo.set_state(org, ns, "scip_commit", second) assert await _read(repo, org, ns) == (set(), set(), True) + + +@pytest.mark.asyncio +async def test_a_seed_in_a_skipped_file_with_no_edges_is_not_exact( + ch_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """The compiler tier covers `BAD`, where `caller` calls nothing and nothing calls + `callee`. The next revision adds `caller`'s first call, to `callee`, and the delta + skips the document. No edge comes back in either direction, so the seed's own path + has to say the answer may be missing what the tier never saw.""" + from server.code.api.models_symbol import CodeCallersInput + from server.code.app.symbol import handle_code_callees, handle_code_callers + from server.settings import settings + + org, ns = unique_org("scip-stale-seed"), "code-stale-seed" + monkeypatch.setattr(settings, "code_org", org) + monkeypatch.setattr(settings, "code_namespace", ns) + repo = await _repo(ch_client, org, ns, [BAD]) + symbols = [ + ScipSymbol(qualified_name="caller", line_start=1, line_end=3), + ScipSymbol(qualified_name="callee", line_start=5, line_end=7), + ] + await apply_delta( + repo, + org, + ns, + ScipDelta(commit="a" * 40, files=[ScipFile(path=BAD, symbols=symbols)]), + tier="clang", + ) + await repo.set_state(org, ns, "scip_commit", "a" * 40) + + def ask(name: str) -> CodeCallersInput: + return CodeCallersInput(org=org, namespace=ns, name=name, include_ambiguous=False) + + for out in (await handle_code_callees(ask("caller")), await handle_code_callers(ask("callee"))): + assert not out.edges and (out.epistemic, out.causes) == ("exact", []) + + await _skip(repo, org, ns) + for out in (await handle_code_callees(ask("caller")), await handle_code_callers(ask("callee"))): + assert not out.edges + assert (out.epistemic, out.causes) == ("lower_bound", ["scip_stale_files"]) + assert BAD in (out.note or "") diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 90ba3cc315e..8e3e543e794 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -209,3 +209,81 @@ def convert_document(doc, run): assert delta["skipped_files"] == ["src/a.cpp"] assert delta["stats"]["factory_ctor_edges"] == 0 assert "features" not in delta + + +def _occurrences(index, path: str, occs: list[tuple[str, list[int], int]]) -> None: + doc = index.documents.add() + doc.relative_path = path + for symbol, rng, role in occs: + occ = doc.occurrences.add() + occ.symbol, occ.symbol_roles = symbol, role + occ.range.extend(rng) + + +def _overload_index(tmp_path: Path, *, bad: bool) -> tuple[Path, Path]: + """(index, checkout): src/a.cpp constructs Foo through `make_shared` as in + `_factory_index`, src/ok.cpp defines a function, and Foo's only constructor is + declared in src/foo.h, a document that fails to decode when `bad`.""" + pb = _pb() + head, defn = "cxx . . $", pb.SymbolRole.Definition + col = _FACTORY_SRC.splitlines()[1].index("Foo") + index = pb.Index() + _occurrences( + index, + "src/a.cpp", + [ + (f"{head} DB/use(aa).", [0, 5, 8], defn), + (f"{head} std/make_shared(bb).", [1, 16, 27], 0), + (f"{head} DB/Foo#", [1, col, col + 3], 0), + ], + ) + _occurrences(index, "src/ok.cpp", [(f"{head} DB/ok(ee).", [0, 5, 7], defn)]) + _occurrences( + index, + "src/foo.h", + [ + (f"{head} DB/Foo#", [0, 7, 10], defn), + # a constructor declared in the class body is a reference-role occurrence + (f"{head} DB/Foo#Foo(cc).", [1, 2, 5], 0), + (f"{head} DB/{_MARK.decode()}(dd).", [2, 5, 8], defn), + ], + ) + raw = index.SerializeToString() + assert raw.count(_MARK) == 1 + if bad: + raw = raw.replace(_MARK, b"\xff\xfe" + _MARK[2:]) + out = tmp_path / ("bad.scip" if bad else "good.scip") + out.write_bytes(raw) + root = tmp_path / "checkout" + (root / "src").mkdir(parents=True, exist_ok=True) + (root / "src" / "a.cpp").write_text(_FACTORY_SRC) + return out, root + + +def test_a_factory_caller_keeps_its_rows_when_the_overload_scan_misses_a_document( + tmp_path: Path, +) -> None: + """Foo's only constructor is in src/foo.h, outside the window, and that document fails + to decode. Converted without it, src/a.cpp would lose its constructor edge and the + apply would retire the old one with neither file marked. The caller is listed in + `skipped_files` instead: the server keeps its rows and marks it stale. A window file + with no factory call converts as before, and so does the caller when the scan reads + every document.""" + conv = _converter() + window = {"src/a.cpp", "src/ok.cpp"} + index, root = _overload_index(tmp_path, bad=False) + whole = conv.convert(str(index), window, [], "h" * 40, "b" * 40, source_root=str(root)) + caller = next(f for f in whole["files"] if f["path"] == "src/a.cpp") + assert "DB::Foo::Foo" in [e["to_qualified_name"] for e in caller["edges"]] + assert whole["skipped_files"] == [] + + index, root = _overload_index(tmp_path, bad=True) + delta = conv.convert(str(index), window, [], "h" * 40, "b" * 40, source_root=str(root)) + assert [f["path"] for f in delta["files"]] == ["src/ok.cpp"] + assert delta["skipped_files"] == ["src/a.cpp"] + assert delta["stats"]["skipped_failed"] == 2 + assert delta["delta_version"] == 2 + # a full run lists the caller beside the document that failed + full = conv.convert(str(index), None, [], "h" * 40, "", source_root=str(root), full=True) + assert full["skipped_files"] == ["src/a.cpp", "src/foo.h"] + assert "features" not in full From 7ef1199ed9a72129b148c9f24dc93edfe1b836e0 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 04:51:27 +0000 Subject: [PATCH 35/81] Run the member-isolation regression through the real window filter With #1963 merged in, scip_ts_projects.py reads the changed-file list as git writes it, so the incremental harness test no longer needs to stub `filter` and `has-config`. The non-UTF-8 member name now passes through both the real filter and the real converter. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- tests/unit/test_run_typescript_delta_umbrella.py | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index e57ed27974c..14ca70c741f 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -33,18 +33,7 @@ # Forward discover/filter/merge to the real helpers; stub only the converter. case "${1-}" in *scip_to_delta.py) [[ -n "${REAL_CONVERT:-}" ]] && exec "$REAL_PYTHON" "$@" ;; - *scip_ts_projects.py) - # REAL_CONVERT runs the real converter; the window filter is not what it tests, so - # `filter` keeps every member and `has-config` finds no config change. - if [[ -n "${REAL_CONVERT:-}" && "${2-}" == filter ]]; then - shift - while [[ "$1" != -- ]]; do shift; done - shift - printf '%s\\n' "$@" - exit 0 - fi - [[ -n "${REAL_CONVERT:-}" && "${2-}" == has-config ]] && exit 1 - exec "$REAL_PYTHON" "$@" ;; + *scip_ts_projects.py) exec "$REAL_PYTHON" "$@" ;; *scip_merge_indexes.py) exec "$REAL_PYTHON" "$@" ;; esac { @@ -215,7 +204,8 @@ def test_a_failed_members_non_utf8_file_in_the_window_does_not_stop_the_delta( ) -> None: """Incremental pass, real converter: packages/lib fails, and the window holds one of its files whose name is not UTF-8. git prints the name as raw bytes into the changed - and failed lists; the healthy member's delta still converts, and the name is dropped.""" + and failed lists; the real window filter and the real converter both read it, the + healthy member's delta still converts, and the name is dropped.""" repo = _repo(tmp_path) base = _git(repo, "rev-parse", "HEAD") bad = Path(os.fsdecode(b"packages/lib/src/caf\xe9.ts")) From 0267d571370f7675ce71eaf098473d47a1db07a8 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:05:35 +0000 Subject: [PATCH 36/81] The record reader keeps the last value of a singular field _document_path returned the first relative_path record in a document. The protobuf parser keeps the last value of a singular field, so a document carrying pkg/first.ts then pkg/second.ts is pkg/second.ts, and the merge treated it as pkg/first.ts and dropped a separate pkg/first.ts document as its duplicate. The converter shares the reader and ordered, filtered and deduplicated by the wrong path. _document_path now returns the last relative_path. Metadata is the other singular field read from raw records: the parser merges repeated metadata records, but _project_root used the first and the merge copied only the last. _project_root now merges every metadata record before the first document, and the merge copies every metadata record of the first part. Document, symbol and occurrence fields are parsed by the protobuf runtime and need no change. Each reader is compared with the parser on the same bytes. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 11 +-- scripts/scip_harness/scip_to_delta.py | 27 +++--- tests/unit/test_scip_merge_indexes.py | 99 ++++++++++++++++++++++ 3 files changed, 120 insertions(+), 17 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index b30eab0aaef..f12f4b6c1c7 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -9,7 +9,8 @@ project references. Sibling tsconfigs in the same directory share a scope, so each keeps the documents it emitted and a path present in more than one of those indexes keeps the last copy. Metadata is taken from -the first non-empty input. External +the first non-empty input, every metadata record in it, as the parser +merges them. External symbols are concatenated. An all-empty input list, or only empty files, writes a zero-byte output so the converter treats it as an empty index. @@ -116,7 +117,7 @@ def merge_indexes( if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") owners = known_projects if known_projects is not None else (projects or []) - metadata = None + metadata: list[Any] = [] documents: dict[str, Any] = {} external_symbols: list[Any] = [] has_payload = False @@ -128,7 +129,7 @@ def merge_indexes( try: for field, payload in _top_level_records(data): if field == _METADATA and not has_payload: - metadata = payload + metadata.append(payload) elif field == _DOCUMENT: rel = _document_path(payload) if project is None or _keeps(project, rel, owners): @@ -145,8 +146,8 @@ def merge_indexes( try: with open(tmp, "wb") as out: if has_payload: - if metadata is not None: - _write_record(out, _METADATA, metadata) + for payload in metadata: + _write_record(out, _METADATA, payload) for payload in documents.values(): _write_record(out, _DOCUMENT, payload) for payload in external_symbols: diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 2fb24da5009..559175615d4 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -892,11 +892,13 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: def _document_path(payload) -> str: """A serialized Document's relative_path (field 1), read without parsing - its occurrences.""" + its occurrences. A singular field written more than once takes its last + value, as the protobuf parser takes it.""" + path = b"" for field, value in _top_level_records(payload): if field == 1: - return bytes(value).decode("utf-8", "replace") - return "" + path = bytes(value) + return path.decode("utf-8", "replace") def _stream_documents(data, scip_pb2, *, paths: set[str] | None = None, ordered: bool = False): @@ -939,18 +941,19 @@ def _index_scheme(data: bytes, scip_pb2) -> str: def _project_root(data: bytes, scip_pb2) -> Path | None: """The checkout the index was produced from (Index.metadata.project_root, - a file:// URI), or None when the metadata record is absent.""" + a file:// URI), or None when the metadata record is absent. Metadata + records before the first document merge into one message, as the protobuf + parser merges a repeated singular message.""" + md = scip_pb2.Metadata() for field, payload in _top_level_records(data): if field == 1: - md = scip_pb2.Metadata() - md.ParseFromString(payload) - root = str(md.project_root or "") - if root.startswith("file://"): - root = root[len("file://") :] - return Path(root) if root else None - if field == 2: + md.MergeFromString(payload) + elif field == 2: break # metadata precedes documents; do not scan the whole index - return None + root = str(md.project_root or "") + if root.startswith("file://"): + root = root[len("file://") :] + return Path(root) if root else None # The parser tier's generated-file rule, harness-side: Go's generated-file header diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 80cb38a47d7..bf2897bf7c6 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -573,3 +573,102 @@ def test_merge_keeps_a_part_the_protobuf_parser_accepts(tmp_path: Path, how: str _MOD.merge_indexes([part], out) merged = _scip_pb2().Index.FromString(out.read_bytes()) assert [d.relative_path for d in merged.documents] == ["packages/app/src/a.ts"] + + +def _record(field: int, payload: bytes, wire: int = 2) -> bytes: + return _tag(field, wire) + (_varint(len(payload)) if wire == 2 else b"") + payload + + +def _path_record(*paths: str) -> bytes: + """One document record whose relative_path (field 1) is written once per path.""" + return _record(2, b"".join(_record(1, p.encode()) for p in paths)) + + +_REPEATED_PATH_DOCS = { + "two paths then the first again": [("pkg/first.ts", "pkg/second.ts"), ("pkg/first.ts",)], + "two paths, the second alone": [("pkg/first.ts", "pkg/second.ts"), ("pkg/second.ts",)], + "three paths": [("a.ts", "b.ts", "c.ts")], +} + + +@pytest.mark.parametrize("how", list(_REPEATED_PATH_DOCS)) +def test_merge_keys_a_document_by_the_last_relative_path_the_parser_keeps( + tmp_path: Path, how: str +) -> None: + """A singular field written twice takes its last value, as the parser takes it.""" + raw = b"".join(_path_record(*paths) for paths in _REPEATED_PATH_DOCS[how]) + parsed = _scip_pb2().Index.FromString(raw) + part = tmp_path / "part.scip" + part.write_bytes(raw) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + expected = {d.relative_path: d for d in parsed.documents} # last copy of a path wins + assert {d.relative_path for d in merged.documents} == set(expected) + assert len(merged.documents) == len(expected) + + +def test_merge_keeps_both_documents_of_the_reviewers_pair(tmp_path: Path) -> None: + """One document carrying first.ts then second.ts is second.ts; a separate + first.ts is another file. The merge keeps both.""" + raw = _path_record("pkg/first.ts", "pkg/second.ts") + _path_record("pkg/first.ts") + assert [d.relative_path for d in _scip_pb2().Index.FromString(raw).documents] == [ + "pkg/second.ts", + "pkg/first.ts", + ] + part = tmp_path / "part.scip" + part.write_bytes(raw) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + merged = _scip_pb2().Index.FromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == ["pkg/second.ts", "pkg/first.ts"] + + +_DOCUMENT_PATH_PAYLOADS = { + "no path": b"", + "one path": _record(1, b"a.ts"), + "last of two": _record(1, b"a.ts") + _record(1, b"b.ts"), + "last of three around another field": ( + _record(1, b"a.ts") + _record(5, b"text") + _record(1, b"b.ts") + _record(1, b"c.ts") + ), + "an empty last path": _record(1, b"a.ts") + _record(1, b""), + "a varint on field 1 is not the path": _record(1, b"a.ts") + _record(1, b"\x05", wire=0), + "a varint on field 1 alone": _record(1, b"\x05", wire=0), +} + + +@pytest.mark.parametrize("how", list(_DOCUMENT_PATH_PAYLOADS)) +def test_document_path_is_what_the_protobuf_parser_reads(how: str) -> None: + payload = _DOCUMENT_PATH_PAYLOADS[how] + doc = _scip_pb2().Document.FromString(payload) + assert _MOD._document_path(payload) == doc.relative_path + + +_REPEATED_METADATA = { + "project_root twice": _record(1, _record(3, b"file:///a")) + + _record(1, _record(3, b"file:///b")), + "the later record sets other fields": ( + _record(1, _record(3, b"file:///a")) + _record(1, _record(1, b"\x01", wire=0)) + ), + "tool info then project_root": ( + _record(1, _record(2, _record(1, b"scip-typescript"))) + + _record(1, _record(3, b"file:///c")) + ), +} + + +@pytest.mark.parametrize("how", list(_REPEATED_METADATA)) +def test_the_converter_and_merge_read_repeated_metadata_as_the_parser_does( + tmp_path: Path, how: str +) -> None: + raw = _REPEATED_METADATA[how] + _path_record("a.ts") + parsed = _scip_pb2().Index.FromString(raw) + root = parsed.metadata.project_root + assert _MOD._converter._project_root(raw, _scip_pb2()) == ( + Path(root.removeprefix("file://")) if root else None + ) + part = tmp_path / "part.scip" + part.write_bytes(raw) + out = tmp_path / "merged.scip" + _MOD.merge_indexes([part], out) + assert _scip_pb2().Index.FromString(out.read_bytes()).metadata == parsed.metadata From 817ed0c83ececccf901fd90650366a414da0a6a7 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:15:25 +0000 Subject: [PATCH 37/81] Read any stale mark as a gap in an incoming answer A skipped document can add the first call to a covered function from a file that is neither a seed path nor the path of a returned edge. code.callers read no mark for that file, so the empty answer stayed exact. An incoming answer now reads the namespace's marks once per query, and any mark makes it a lower bound with scip_stale_files. The callers note names up to three marked files. code.impact, the code.test_gate causes, the grep neighbours, the PR pack's callers line and the code.symbol uses block follow the same rule. Outgoing answers keep the seed-path rule. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/features/code-index/overview.md | 6 ++- server/code/api/models_symbol.py | 5 +- server/code/app/index/packs.py | 3 ++ server/code/app/symbol/coverage.py | 29 ++++++++++++ server/code/app/symbol/gate.py | 7 +-- server/code/app/symbol/graph.py | 16 ++++--- server/code/app/symbol/impact.py | 7 +-- server/code/app/symbol/neighbours.py | 7 +-- server/code/app/symbol_uses.py | 12 +++-- server/code/domain/index/epistemic.py | 5 +- server/code/store/index/symbols.py | 10 ++-- .../integration/test_code_scip_stale_mark.py | 46 +++++++++++++++++++ tests/unit/test_code_callers_member_fold.py | 3 ++ tests/unit/test_code_ctor_call_edges.py | 9 ++-- tests/unit/test_code_epistemic_envelope.py | 3 ++ tests/unit/test_code_grep_neighbours.py | 16 ++++++- tests/unit/test_code_registration_edges.py | 6 ++- tests/unit/test_code_symbol_uses_context.py | 8 ++++ tests/unit/test_code_test_gate.py | 8 ++++ 19 files changed, 170 insertions(+), 36 deletions(-) diff --git a/docs/features/code-index/overview.md b/docs/features/code-index/overview.md index 7aa7c1d1918..781934bfd77 100644 --- a/docs/features/code-index/overview.md +++ b/docs/features/code-index/overview.md @@ -298,8 +298,10 @@ generated from the same schemas. The first three are answers; no fallback grep is needed. - **`epistemic`.** `code.callers` and `code.impact` answer `exact` when the compiler - tier covers every seed file, no call site named like a seed was declined, and no - override seed lacks its base. Otherwise `lower_bound`, with `causes`: + tier covers every seed file, no call site named like a seed was declined, no + override seed lacks its base, and no file in the namespace is marked stale because the + compiler tier skipped its document (it may hold a caller no edge shows). Otherwise + `lower_bound`, with `causes`: `unresolved_calls`, `ambiguous_calls`, `dispatch_seeds_missing`, `treesitter_only_files`, `external_calls`, `ctor_edges_absent`, `scip_stale_files`, `truncated`. History answers are always `lower_bound`. No static index sees dispatch diff --git a/server/code/api/models_symbol.py b/server/code/api/models_symbol.py index 3c974318b8f..3d7be411c89 100644 --- a/server/code/api/models_symbol.py +++ b/server/code/api/models_symbol.py @@ -525,7 +525,7 @@ def _drop_unrequested_candidates( # constructor seed with no edge in an index that predates constructor # calls through factories), scip_stale_files (a compiler-tier edge # served from a file changed since that tier last ran, or one it skipped, or a seed - # in such a file), + # in such a file; for callers, any file the namespace holds marked skipped), # truncated (the walk stopped short of the graph)}. epistemic: str = "lower_bound" # Why `epistemic` is `lower_bound`, from the set above; empty when it is `exact`. @@ -655,7 +655,8 @@ def _drop_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: # why, from {unresolved_calls, ambiguous_calls, dispatch_seeds_missing, # treesitter_only_files, external_calls, ctor_edges_absent (a # constructor seed with no edge in an index that predates constructor - # calls through factories), truncated (the walk or its page stopped short + # calls through factories), scip_stale_files (a file the namespace holds + # marked skipped may hold a caller), truncated (the walk or its page stopped short # of the graph)}. epistemic: str = "lower_bound" # Why `epistemic` is `lower_bound`, from the set above; empty when it is `exact`. diff --git a/server/code/app/index/packs.py b/server/code/app/index/packs.py index 46079be97f0..df4a5c4c8b1 100644 --- a/server/code/app/index/packs.py +++ b/server/code/app/index/packs.py @@ -319,11 +319,14 @@ async def _envelope_line( remaining = [p for p in paths if p and p not in covered] if remaining: covered |= await repo.scip_covered_paths(org, ns, remaining) + # a file marked stale may hold a caller no edge shows + marked = await repo.scip_stale_marks(org, ns) env = envelope( unresolved=unresolved, ambiguous=ambiguous, seed_paths=paths, scip_paths=covered, + scip_stale=bool(marked), ) except Exception: # noqa: BLE001 — a pack line degrades to absence return "" diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index 813a0071c71..96d1ea5a6eb 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -5,6 +5,7 @@ from __future__ import annotations +import asyncio import logging from typing import Any @@ -95,6 +96,34 @@ async def _scip_stale( return set(paths) +# Stands for the namespace's marks when their read failed: the answer falls to a lower +# bound, and the note says the marks were not read. +MARKS_UNREAD = "(stale marks unread)" + + +async def _marked_stale(repo: CodeRepo, org: str, ns: str) -> set[str]: + """Files any compiler tier holds marked stale in the namespace: a delta skipped their + document, so each may hold a call no edge shows, to a seed neither it nor any served + edge path names. An incoming answer (callers, an impact radius, the tests linked + through callers) is not exact while one is. One read of the namespace's mark rows + per query, never cached: a delta may mark a file at any time. Fail-open to UNPROVEN: + a failed read counts as a mark.""" + try: + return await repo.scip_stale_marks(org, ns) + except Exception as e: # noqa: BLE001 — a freshness read must not fail the answer + logger.debug("scip stale-marks read skipped: %s", e) + return {MARKS_UNREAD} + + +async def _coverage_and_marks( + repo: CodeRepo, org: str, ns: str, paths: list[str], rows: list[dict[str, Any]] +) -> tuple[set[str], set[str]]: + """(`_scip_coverage`, `_marked_stale`) for an incoming answer, read together.""" + return await asyncio.gather( + _scip_coverage(repo, org, ns, paths, rows), _marked_stale(repo, org, ns) + ) + + def _graph_paths(paths: list[str], rows: list[dict[str, Any]]) -> tuple[list[str], list[str]]: """(paths with a symbol row, graphed-language paths without one). Test files are leaves of the call graph and a .md or .sql defines nothing diff --git a/server/code/app/symbol/gate.py b/server/code/app/symbol/gate.py index 8b4c2d89fca..2302637e269 100644 --- a/server/code/app/symbol/gate.py +++ b/server/code/app/symbol/gate.py @@ -16,9 +16,9 @@ ) from server.code.app.spans import code_span, set_code_span_attributes, span_attrs from server.code.app.symbol.coverage import ( + _coverage_and_marks, _declined_safe, _graph_paths, - _scip_coverage, _unindexed_paths, ) from server.code.app.symbol.diff import ( @@ -72,7 +72,7 @@ async def handle_code_test_gate(input: CodeTestGateInput) -> CodeTestGateOutput: ( links, (unresolved_n, ambiguous_n), - scip_paths, + (scip_paths, marked), unindexed, ) = await asyncio.gather( link_tests( @@ -86,7 +86,7 @@ async def handle_code_test_gate(input: CodeTestGateInput) -> CodeTestGateOutput: neighbors=settings.code_test_neighbor_rows, ), _declined_safe(repo, org, ns, touched), - _scip_coverage(repo, org, ns, known_paths, symbol_rows), + _coverage_and_marks(repo, org, ns, known_paths, symbol_rows), _unindexed_paths(repo, org, ns, bare_paths), ) impacted = links.impacted @@ -104,6 +104,7 @@ async def handle_code_test_gate(input: CodeTestGateInput) -> CodeTestGateOutput: seed_paths=[*known_paths, *sorted(unindexed)], scip_paths=scip_paths, unindexed_paths=unindexed, + scip_stale=bool(marked), truncated=links.capped, ) # The graph is never proof that no test runs a definition: the answer is `measured` diff --git a/server/code/app/symbol/graph.py b/server/code/app/symbol/graph.py index fe0226a880b..91e40290ca3 100644 --- a/server/code/app/symbol/graph.py +++ b/server/code/app/symbol/graph.py @@ -36,6 +36,7 @@ _declined_safe, _env_fields, _has_ctor_seed, + _marked_stale, _scip_coverage, _scip_stale, ) @@ -385,16 +386,19 @@ async def _floor_reads( """((unresolved, ambiguous), scip-covered seed paths, dispatch seeds missing, stale paths), gathered so a cancelled call takes every read down. The declined count is the walk's blind spot: sites named like the seed for callers, the seed's own declined call - sites for callees.""" + sites for callees. A callers answer also counts every file the namespace holds + marked stale: it may hold the seed's first caller, which no edge or seed path names.""" coverage = _scip_coverage(repo, org, ns, seed_paths, seeds) stale = _scip_stale(repo, org, ns, edges_out, seed_paths) dispatch_missing = False + marked: set[str] = set() if direction == "callers": - declined, scip_paths, dispatch_missing, stale_paths = await asyncio.gather( + declined, scip_paths, dispatch_missing, stale_paths, marked = await asyncio.gather( _declined_safe(repo, org, ns, seeds), coverage, _dispatch_missing(repo, org, ns, seeds, dispatch_rows, attempted=dispatch_attempted), stale, + _marked_stale(repo, org, ns), ) else: declined, scip_paths, stale_paths = await asyncio.gather( @@ -402,7 +406,7 @@ async def _floor_reads( ) # a seed path the compiler tier does not cover is `treesitter_only_files` already served = {e.path for e in edges_out if e.tier == "scip"} - stale_paths = {p for p in stale_paths if p in served or p in scip_paths} + stale_paths = {p for p in stale_paths if p in served or p in scip_paths} | marked return declined, scip_paths, dispatch_missing, stale_paths @@ -489,7 +493,7 @@ def _stale_note(stale_paths: set[str]) -> str: if not stale_paths: return "" return ( - f"compiler-tier edges from {len(stale_paths)} file(s) changed since that tier " - f"last ran or skipped by it ({', '.join(sorted(stale_paths)[:3])}): their lines " - "may be stale" + f"{len(stale_paths)} file(s) changed since the compiler tier last ran or skipped " + f"by it ({', '.join(sorted(stale_paths)[:3])}): edges from them may be stale, and " + "calls in them missing" ) diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index ec6f8c7781a..1b4939419ca 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -23,10 +23,10 @@ from server.code.app.index.symbol_forms import resolved_by_of from server.code.app.spans import code_span, set_code_span_attributes, span_attrs from server.code.app.symbol.coverage import ( + _coverage_and_marks, _declined_safe, _env_fields, _graph_paths, - _scip_coverage, _unindexed_paths, ) from server.code.app.symbol.diff import ( @@ -263,7 +263,7 @@ async def handle_code_impact(input: CodeImpactInput) -> CodeImpactOutput: ( (impacted, capped), (unresolved_n, ambiguous_n), - scip_paths, + (scip_paths, marked), unindexed, dispatch_missing, (linked_rows, links), @@ -279,7 +279,7 @@ async def handle_code_impact(input: CodeImpactInput) -> CodeImpactOutput: overlay=overlay, ), _declined_safe(repo, org, ns, seeds), - _scip_coverage(repo, org, ns, known_paths, symbol_rows if diff_shaped else seeds), + _coverage_and_marks(repo, org, ns, known_paths, symbol_rows if diff_shaped else seeds), _unindexed_paths(repo, org, ns, bare_paths), _dispatch_missing(repo, org, ns, seeds, dispatch_rows, attempted=True) if not diff_shaped @@ -325,6 +325,7 @@ async def handle_code_impact(input: CodeImpactInput) -> CodeImpactOutput: scip_paths=scip_paths, unindexed_paths=unindexed, dispatch_missing=dispatch_missing, + scip_stale=bool(marked), truncated=truncated, ) # An empty radius is a verdict, not an abstain. Seeds that resolved and a walk that diff --git a/server/code/app/symbol/neighbours.py b/server/code/app/symbol/neighbours.py index 942f1a970f1..c31bd77aec5 100644 --- a/server/code/app/symbol/neighbours.py +++ b/server/code/app/symbol/neighbours.py @@ -13,7 +13,7 @@ from server.code.app.own_callees import own_callees from server.code.app.spans import code_span, span_attrs -from server.code.app.symbol.coverage import _scip_coverage +from server.code.app.symbol.coverage import _coverage_and_marks from server.code.domain.index.epistemic import classify from server.code.store.index import CodeRepo from server.code.store.index import prefer_scip_edges as _prefer_scip_edges @@ -229,13 +229,13 @@ async def citing_docs() -> list[dict[str, Any]]: return [r for r in rows if is_doc_path(str(r.get("path") or ""))] with code_span("enclosing.neighbours", results=len(anchors), depth=k) as sp: - callers_read, (callees, _), docs, tmap, misses, scip_paths = await asyncio.gather( + callers_read, (callees, _), docs, tmap, misses, (scip_paths, marked) = await asyncio.gather( _soft(edges("callers"), None), _soft(edges("callees"), ([], set())), _soft(citing_docs(), []), _soft(repo.test_map_for(org, ns, paths, limit=len(paths) * k * 2), []), _soft(repo.call_misses_for_names(org, ns, names), {}), - _scip_coverage(repo, org, ns, paths, anchors), + _coverage_and_marks(repo, org, ns, paths, anchors), ) # a failed callers read: no anchor's callers are known callers, callers_cut = callers_read if callers_read is not None else ([], set(anchor_name)) @@ -282,6 +282,7 @@ def fold( ambiguous=int(m.get("ambiguous", 0)), seed_paths=[path], scip_paths=scip_paths, + scip_stale=bool(marked), truncated=len(callers_of) > k or aid in callers_cut, ) entry = { diff --git a/server/code/app/symbol_uses.py b/server/code/app/symbol_uses.py index 5776f01e4a0..17664eaa0af 100644 --- a/server/code/app/symbol_uses.py +++ b/server/code/app/symbol_uses.py @@ -228,9 +228,11 @@ def build_block( seeds: list[dict[str, Any]], *, floor: float, + stale: bool = False, ) -> dict[str, Any]: """The compact block from the two reads' rows. Pure; the tests hold it - to a stub repo.""" + to a stub repo. `stale`: the namespace holds a file marked stale, which may hold a + caller no edge shows.""" live = prefer_scip_edges(edges) edge_sites = {(str(e["path"]), int(e["line"])) for e in live} sites = [ @@ -259,7 +261,7 @@ def build_block( "files": len({s["path"] for s in sites}), "top": top, "truncated": len(sites) > len(top), - "epistemic": "exact" if compiler_seed and declined == 0 else "lower_bound", + "epistemic": "exact" if compiler_seed and declined == 0 and not stale else "lower_bound", } @@ -284,6 +286,7 @@ async def uses_brief( handed on so the definitions' `fan_in` field does not read the table twice. Never raises: a read that did not answer yields the noted block.""" from server.code.app import fan_in as code_fan_in + from server.code.app.symbol.coverage import _marked_stale ids = [str(r.get("symbol_id") or "") for r in rows if r.get("symbol_id")] stats: dict[str, dict[str, Any]] = {} @@ -306,9 +309,10 @@ async def uses_brief( return mention_block(lines, truncated=truncated), stats names = bare_names(rows) try: - edges, misses = await asyncio.gather( + edges, misses, marked = await asyncio.gather( repo.edges_for_symbols(org, ns, ids, direction="callers", limit=READ_CAP), repo.live_call_misses_for_names(org, ns, names, limit=READ_CAP) if names else _none(), + _marked_stale(repo, org, ns), ) except Exception as e: # noqa: BLE001 — additive, never fatal logger.debug("code.symbol uses leg failed: %s", e) @@ -316,7 +320,7 @@ async def uses_brief( if len(edges) >= READ_CAP or len(misses) >= READ_CAP: return hub_block(_count_floor(edges, misses, rows)), stats floor = float(settings.code_callers_candidate_min_confidence) - return build_block(edges, misses, rows, floor=floor), stats + return build_block(edges, misses, rows, floor=floor, stale=bool(marked)), stats async def _none() -> list[dict[str, Any]]: diff --git a/server/code/domain/index/epistemic.py b/server/code/domain/index/epistemic.py index 43810b120c3..5286636c3ed 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -28,7 +28,10 @@ run skipped: its line and caller come from content that tier never saw; or a seed in such a file, whose own calls - and callers may be missing + and callers may be missing; for an + incoming answer, any file the + namespace holds marked skipped, which + may hold a caller no edge shows truncated the walk stopped short of the graph (a node cap, a hop read cut at its row limit, a page): the answer lists part of it diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 0db81af3f9a..dab964b3468 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -590,11 +590,11 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str # the query names the FRESH paths; every other asked path is stale return set(asked) - {str(r["path"]) for r in rows} - async def scip_stale_marks(self, org: str, ns: str, tier: str) -> set[str]: - """The paths `tier` holds marked stale (`SCIP_STALE_PREFIX`): its last delta for - each skipped the file's document, and no apply of the file by this build has - completed since (`_marks_in_force`).""" - prefix = f"{SCIP_STALE_PREFIX}{tier}:" + async def scip_stale_marks(self, org: str, ns: str, tier: str | None = None) -> set[str]: + """The paths `tier` (every tier when None) holds marked stale + (`SCIP_STALE_PREFIX`): its last delta for each skipped the file's document, and no + apply of the file by this build has completed since (`_marks_in_force`).""" + prefix = f"{SCIP_STALE_PREFIX}{tier}:" if tier else SCIP_STALE_PREFIX rows = await self._ch.query_all( _marks_in_force("startsWith(state_key, {mark:String})"), {"org": org, "ns": ns, "mark": prefix}, diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 02b68e87fbc..d1f08b11c87 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -408,3 +408,49 @@ def ask(name: str) -> CodeCallersInput: assert not out.edges assert (out.epistemic, out.causes) == ("lower_bound", ["scip_stale_files"]) assert BAD in (out.note or "") + + +@pytest.mark.asyncio +async def test_a_first_caller_in_another_skipped_file_is_not_exact( + ch_client: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + """The compiler tier covers `callee` in `OTHER` and `caller` in `BAD`, and nothing + calls `callee`. The next revision adds `caller`'s call to `callee`, and the delta + skips `BAD`'s document. The seed's own file is not marked and no edge names `BAD`, + so only the namespace's marks can say an incoming answer may miss a caller.""" + from server.code.api.models_symbol import CodeCallersInput, CodeImpactInput + from server.code.app.symbol import handle_code_callers, handle_code_impact + from server.settings import settings + + org, ns = unique_org("scip-stale-caller"), "code-stale-caller" + monkeypatch.setattr(settings, "code_org", org) + monkeypatch.setattr(settings, "code_namespace", ns) + repo = await _repo(ch_client, org, ns, [OTHER, BAD]) + files = [ + ScipFile(path=OTHER, symbols=[ScipSymbol(qualified_name="callee", line_start=1)]), + ScipFile(path=BAD, symbols=[ScipSymbol(qualified_name="caller", line_start=1)]), + ] + await apply_delta(repo, org, ns, ScipDelta(commit="a" * 40, files=files), tier="clang") + await repo.set_state(org, ns, "scip_commit", "a" * 40) + + async def answers() -> list[tuple[str, list[str]]]: + callers = await handle_code_callers( + CodeCallersInput(org=org, namespace=ns, name="callee", include_ambiguous=False) + ) + impact = await handle_code_impact(CodeImpactInput(org=org, namespace=ns, name="callee")) + assert not callers.edges and not impact.impacted_symbols + if callers.epistemic != "exact": + assert BAD in (callers.note or "") + return [(callers.epistemic, callers.causes), (impact.epistemic, impact.causes)] + + assert await answers() == [("exact", [])] * 2 + + await _skip(repo, org, ns) + assert await repo.scip_stale_paths(org, ns, [OTHER]) == set() + assert await answers() == [("lower_bound", ["scip_stale_files"])] * 2 + + await apply_delta( + repo, org, ns, ScipDelta(commit="c" * 40, files=[ScipFile(path=BAD)]), tier="clang" + ) + await repo.set_state(org, ns, "scip_commit", "c" * 40) + assert await answers() == [("exact", [])] * 2 diff --git a/tests/unit/test_code_callers_member_fold.py b/tests/unit/test_code_callers_member_fold.py index 1a371cf37ca..859eeb0d3ad 100644 --- a/tests/unit/test_code_callers_member_fold.py +++ b/tests/unit/test_code_callers_member_fold.py @@ -73,6 +73,9 @@ class _FakeRepo: + async def scip_stale_marks(self, org, ns, tier=None): + return set() + def __init__(self, seed: dict[str, Any]) -> None: self.seed = seed self.member_calls: list[list[str]] = [] diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index dfd3f0fae9d..0a1341b5f43 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -608,8 +608,8 @@ async def scip_covered_paths(self, org, ns, paths): async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} - async def scip_stale_marks(self, org, ns, tier): - return set(self.stale_marks) if tier == "clang" else set() + async def scip_stale_marks(self, org, ns, tier=None): + return set(self.stale_marks) if tier in ("clang", None) else set() async def all_state(self, org, ns): self.state_reads += 1 @@ -708,7 +708,8 @@ async def test_a_skipped_file_withdraws_the_claim_a_clean_full_run_made(intel) - ) ) assert out.edges == [] and out.epistemic == "lower_bound" - assert out.causes == [ep.CAUSE_CTOR] + # and the marked file may hold any caller, not only a factory call + assert out.causes == [ep.CAUSE_CTOR, ep.CAUSE_STALE] async def test_a_mark_written_after_the_probe_is_cached_withdraws_exact(intel) -> None: @@ -732,7 +733,7 @@ async def callers() -> Any: assert (await callers()).epistemic == "exact" repo.stale_marks = {"src/new.cpp"} out = await callers() - assert out.epistemic == "lower_bound" and out.causes == [ep.CAUSE_CTOR] + assert out.epistemic == "lower_bound" and out.causes == [ep.CAUSE_CTOR, ep.CAUSE_STALE] repo.stale_marks = set() assert (await callers()).epistemic == "exact" assert repo.state_reads == 1 # all three answers went through the one cached probe diff --git a/tests/unit/test_code_epistemic_envelope.py b/tests/unit/test_code_epistemic_envelope.py index c9606e1b819..afc546a70f7 100644 --- a/tests/unit/test_code_epistemic_envelope.py +++ b/tests/unit/test_code_epistemic_envelope.py @@ -168,6 +168,9 @@ async def scip_covered_paths(self, org, ns, paths): async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} + async def scip_stale_marks(self, org, ns, tier=None): + return set() + indexed = {"src/A.cpp", "src/Constants.h"} # in code_files; Constants.h has no symbols async def live_paths_present(self, org, ns, paths): diff --git a/tests/unit/test_code_grep_neighbours.py b/tests/unit/test_code_grep_neighbours.py index eeaff93eecc..59c95189c17 100644 --- a/tests/unit/test_code_grep_neighbours.py +++ b/tests/unit/test_code_grep_neighbours.py @@ -236,6 +236,9 @@ async def scip_covered_paths(self, org, ns, paths): async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} + async def scip_stale_marks(self, org, ns, tier=None): + return set() + @pytest.fixture(autouse=True) def _intel_on(monkeypatch): @@ -323,7 +326,9 @@ def test_neighbours_need_matches_mode() -> None: # ---- the envelope covers the callers list that is shown ------------------------ -def _entry(callers: list[str], *, k: int = 2, fail: bool = False) -> dict[str, Any]: +def _entry( + callers: list[str], *, k: int = 2, fail: bool = False, marked: frozenset[str] = frozenset() +) -> dict[str, Any]: """The block's entry for one compiler-indexed anchor with no declined call site: its envelope is `exact` when the callers shown are the callers the index holds.""" from server.code.app.symbol.neighbours import _attach_enclosing_neighbours @@ -338,6 +343,9 @@ def _entry(callers: list[str], *, k: int = 2, fail: bool = False) -> dict[str, A } class _EdgeRepo: + async def scip_stale_marks(self, org, ns, tier=None): + return set(marked) + async def edges_for_symbols(self, org, ns, ids, *, direction, edge_kinds=None, **kw): if direction != "callers" or edge_kinds != ["calls"]: return [] @@ -390,6 +398,12 @@ def test_a_callers_read_that_filled_its_row_cap_is_a_lower_bound() -> None: assert entry["epistemic"] == "lower_bound" and entry["causes"] == ["truncated"] +def test_a_file_marked_stale_anywhere_makes_the_callers_a_lower_bound() -> None: + # the compiler tier skipped another file's document: it may hold a caller of DB::f + entry = _entry(["DB::a"], marked=frozenset({"src/Skipped.cpp"})) + assert entry["epistemic"] == "lower_bound" and entry["causes"] == ["scip_stale_files"] + + def test_a_failed_callers_read_is_a_lower_bound() -> None: entry = _entry([], fail=True) assert entry["callers"] == [] diff --git a/tests/unit/test_code_registration_edges.py b/tests/unit/test_code_registration_edges.py index 73f936e85e8..06c74455792 100644 --- a/tests/unit/test_code_registration_edges.py +++ b/tests/unit/test_code_registration_edges.py @@ -386,7 +386,7 @@ async def top_reviewers(self, *a, **k): @pytest.fixture def repo(monkeypatch): - from server.code.app.symbol import graph, impact + from server.code.app.symbol import coverage, graph, impact r = _Repo() for m in (graph, impact): @@ -396,8 +396,10 @@ def repo(monkeypatch): monkeypatch.setattr(m, "schedule_code_trace", lambda **k: None) monkeypatch.setattr(m, "_dispatch_seeds", _none_rows) monkeypatch.setattr(m, "_declined_safe", _zero_pair) - monkeypatch.setattr(m, "_scip_coverage", _empty_set) monkeypatch.setattr(m, "_dispatch_missing", _false) + # graph reads coverage by its own name; impact through `_coverage_and_marks` + monkeypatch.setattr(graph, "_scip_coverage", _empty_set) + monkeypatch.setattr(coverage, "_scip_coverage", _empty_set) monkeypatch.setattr(graph, "_candidate_block", _none) # the walk stays on resolved edges: dispatch widening is not this file's subject monkeypatch.setattr(graph, "_widening", lambda _inp: (False, 0.2)) diff --git a/tests/unit/test_code_symbol_uses_context.py b/tests/unit/test_code_symbol_uses_context.py index 4b90bbf5d52..6a5a74be566 100644 --- a/tests/unit/test_code_symbol_uses_context.py +++ b/tests/unit/test_code_symbol_uses_context.py @@ -188,6 +188,9 @@ class _FakeRepo: + async def scip_stale_marks(self, org, ns, tier=None): + return set(getattr(self, "marks", set())) + def __init__( self, defs: list[dict[str, Any]], @@ -358,6 +361,11 @@ def test_exact_only_when_every_seed_file_is_compiler_indexed(): covered = [ONE[0], {**ONE[1], "path": "src/Foo.cpp", "start_line": 10}] out = _run(_FakeRepo(covered, misses=[]), name="DB::Foo::bar") assert out.uses["epistemic"] == "exact" and out.uses["count"] == 3 + # a file the compiler tier skipped, anywhere in the namespace, may hold a caller + repo = _FakeRepo(covered, misses=[]) + repo.marks = {"src/Skipped.cpp"} + out = _run(repo, name="DB::Foo::bar") + assert out.uses["epistemic"] == "lower_bound" and out.uses["count"] == 3 def test_a_hub_floor_counts_a_site_both_tiers_saw_once(): diff --git a/tests/unit/test_code_test_gate.py b/tests/unit/test_code_test_gate.py index a4a2c31beda..57bf3a7402c 100644 --- a/tests/unit/test_code_test_gate.py +++ b/tests/unit/test_code_test_gate.py @@ -524,6 +524,9 @@ def _edge(frm: str, to: str, fq: str, path: str, kind: str = "calls") -> dict[st class _Repo: + async def scip_stale_marks(self, org, ns, tier=None): + return set(getattr(self, "marks", set())) + def __init__(self) -> None: self.symbols = [ _sym("sA", "DB::A::f", "src/A.cpp", 10, 20), @@ -960,6 +963,11 @@ async def test_a_cut_coverage_read_is_a_cause_and_a_test_only_change_has_none(in out = await _gate(intel, repo, diff=_one_line("pkg/w.py", 46)) assert out.causes == ["truncated"] assert [t["why"] for t in out.tests].count("coverage") == 2 + # a file the compiler tier skipped may hold a caller the static links miss + repo.marks = {"pkg/skipped.py"} + out = await _gate(intel, repo, diff=_one_line("pkg/w.py", 46)) + assert out.causes == ["scip_stale_files", "truncated"] + repo.marks = set() # a change of test files only touches no source definition: never `measured`, no cause out = await _gate(intel, repo, files=["tests/test_w.py"]) From 1c0d2ba179922465a349c2ee20f68af70c474ef6 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:25:59 +0000 Subject: [PATCH 38/81] Pin the ten-byte value varint the record reader accepts A value varint of ten bytes is accepted whatever its tenth byte holds. The protobuf parser (upb, and the pure-Python backend) accepts it, so a part with such a trailing unknown varint parses whole and merges the same way. Tag and length varints are bounded at five bytes and refused beyond, as the parser refuses them. The reader already matches, so this adds tests only: a value varint ending in 0x00, 0x01, 0x02 or 0x7f, at top level and inside a group, is accepted by the reader and the merge, each compared with the parser. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- tests/unit/test_scip_merge_indexes.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index bf2897bf7c6..eb18da4d165 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -513,6 +513,15 @@ def _tag(field: int, wire: int) -> bytes: "length with one redundant zero byte": _tag(9, 2) + b"\x81\x00" + b"x", } +# A value varint of ten bytes is accepted whatever its tenth byte holds (upb and the +# pure-Python backend agree); an eleventh byte is refused above. +for _last in (0x00, 0x01, 0x02, 0x7F): + _ten = b"\xff" * 9 + bytes([_last]) + _ACCEPTED_TAILS[f"value varint of ten bytes ending 0x{_last:02x}"] = _tag(9, 0) + _ten + _ACCEPTED_TAILS[f"group value varint of ten bytes ending 0x{_last:02x}"] = ( + _tag(9, 3) + _tag(9, 0) + _ten + _tag(9, 4) + ) + _REFUSED = pytest.mark.parametrize("how", list(_REFUSED_TAILS)) From 2488a8b317cbaac5c1f5b28428c500e7bd54b05b Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 05:30:48 +0000 Subject: [PATCH 39/81] Let the Go worker's apply stand-ins take the tier #1704 passes the producer's tier to apply_delta, and main's Go worker tests added since define stand-ins without the keyword. They fail with a TypeError the pass reports as a failing tier. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- tests/unit/test_code_scip_go_delta_worker.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index f9ed978e8c9..33c35fd7182 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -757,7 +757,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return "".join(f"done {m}\n" for m in modules) - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=0) @@ -813,7 +813,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return "".join(f"done {m}\n" for m in modules) - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=0) @@ -885,7 +885,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): log += _WINDOW_LOGS[window] if m == "lib" else "done svc\n" return log - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=0) @@ -1050,7 +1050,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): log += line return log - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=0) @@ -1166,7 +1166,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return log[0] if "lib" in modules else "done svc\n" - async def fake_apply(repo, org, ns, delta): + async def fake_apply(repo, org, ns, delta, **_): from server.code.app.index.scip_delta import ScipApplyStats return ScipApplyStats(files=0) From 226a92c4a638f6f0a985950d33bdeafd6e5163b1 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:08:06 +0000 Subject: [PATCH 40/81] Test the PR pack's callers line and name unread stale marks in the note A unit test drives the pack's callers line with one stale mark in the namespace and expects a lower bound, and an exact line with none. The callers note no longer counts the unread-marks placeholder as a file: it names the files it knows and says the stale marks could not be read. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/code/app/symbol/graph.py | 19 ++++--- tests/unit/test_code_stale_marks_note.py | 67 ++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 7 deletions(-) create mode 100644 tests/unit/test_code_stale_marks_note.py diff --git a/server/code/app/symbol/graph.py b/server/code/app/symbol/graph.py index 91e40290ca3..808ed1cf1e7 100644 --- a/server/code/app/symbol/graph.py +++ b/server/code/app/symbol/graph.py @@ -31,6 +31,7 @@ ) from server.code.app.symbol.coverage import ( _CTOR_NOTE, + MARKS_UNREAD, _ctor_edges_absent, _declined_outgoing_safe, _declined_safe, @@ -490,10 +491,14 @@ def _declined_note(unresolved_n: int, ambiguous_n: int) -> str: def _stale_note(stale_paths: set[str]) -> str: - if not stale_paths: - return "" - return ( - f"{len(stale_paths)} file(s) changed since the compiler tier last ran or skipped " - f"by it ({', '.join(sorted(stale_paths)[:3])}): edges from them may be stale, and " - "calls in them missing" - ) + files = stale_paths - {MARKS_UNREAD} + parts = [] + if files: + parts.append( + f"{len(files)} file(s) changed since the compiler tier last ran or skipped " + f"by it ({', '.join(sorted(files)[:3])}): edges from them may be stale, and " + "calls in them missing" + ) + if MARKS_UNREAD in stale_paths: + parts.append("the stale marks could not be read") + return "; ".join(parts) diff --git a/tests/unit/test_code_stale_marks_note.py b/tests/unit/test_code_stale_marks_note.py new file mode 100644 index 00000000000..6a6a0f1e84a --- /dev/null +++ b/tests/unit/test_code_stale_marks_note.py @@ -0,0 +1,67 @@ +"""A stale mark in the namespace lowers the PR pack's callers line, and the callers note +names the marks it could not read instead of counting the placeholder as a file.""" + +from __future__ import annotations + +from typing import Any + +from server.code.app.index.packs import _envelope_line +from server.code.app.symbol.coverage import MARKS_UNREAD +from server.code.app.symbol.graph import _stale_note + + +class _Repo: + """The three store reads the pack line makes.""" + + def __init__(self, marks: set[str] | Exception) -> None: + self._marks = marks + + async def call_misses_for_names(self, org: str, ns: str, names: list[str]) -> dict[str, Any]: + return {} + + async def scip_covered_paths(self, org: str, ns: str, paths: list[str]) -> set[str]: + return set(paths) + + async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + if isinstance(self._marks, Exception): + raise self._marks + return self._marks + + +_CHANGED = [{"name": "f", "path": "src/a.cpp", "tier": "scip"}] + + +async def test_pack_callers_line_reads_exact_with_no_mark() -> None: + line = await _envelope_line(_Repo(set()), "o", "n", _CHANGED) # type: ignore[arg-type] + assert line == "callers below are exact" + + +async def test_pack_callers_line_is_a_lower_bound_with_one_stale_mark() -> None: + line = await _envelope_line(_Repo({"src/bad.cpp"}), "o", "n", _CHANGED) # type: ignore[arg-type] + assert line == "callers below are lower_bound (scip_stale_files)" + + +async def test_pack_callers_line_is_absent_when_the_marks_read_fails() -> None: + line = await _envelope_line(_Repo(RuntimeError("down")), "o", "n", _CHANGED) # type: ignore[arg-type] + assert line == "" + + +def test_stale_note_counts_and_names_files() -> None: + note = _stale_note({"src/b.cpp", "src/a.cpp"}) + assert note.startswith("2 file(s) changed since the compiler tier last ran or skipped by it") + assert "(src/a.cpp, src/b.cpp)" in note + assert "could not be read" not in note + + +def test_stale_note_says_the_marks_could_not_be_read() -> None: + note = _stale_note({MARKS_UNREAD}) + assert note == "the stale marks could not be read" + assert "file(s)" not in note and MARKS_UNREAD not in note + + +def test_stale_note_does_not_count_the_placeholder_as_a_file() -> None: + note = _stale_note({MARKS_UNREAD, "src/a.cpp"}) + assert note.startswith("1 file(s) changed") + assert "(src/a.cpp)" in note + assert MARKS_UNREAD not in note + assert note.endswith("the stale marks could not be read") From 65c7ec4d1e368491193058c749659695d65eb5ae Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:41:41 +0000 Subject: [PATCH 41/81] Format the failure-model table in code-index-operations.md with Prettier The table padding after the main merge did not match Prettier 3.9.9, which the format check runs. No text changes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 28 ++++++++++++------------ 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 34af9e3f305..b9ac9aada53 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1405,21 +1405,21 @@ the output to read. ## Failure model -| Failure | Behaviour | Recovery | -| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `git fetch` fails | watermark unmoved; the entry's `fetch` tier records the error, its kind and fix (`tier_health`) | the next pass (supervisor backoff) | -| crash mid-commit | the commit is re-run | idempotent upserts | -| a file fails to parse | chunks without symbols, `code_files.index_error` set (a parse past `code_parse_timeout_s` or `code_parse_memory_mb` included, and one that could not run in its process) | `code.index_errors` lists them; fixed by the next change or a repair (raising either limit re-reads none) | -| every file fails to parse with `LookupError` "... is loaded from outside the interpreter's site-packages" | chunks without symbols for every file: tree-sitter or a grammar is installed where the parse process does not see it | install the tree-sitter packages into the server interpreter's own environment, not through `PYTHONPATH` or the user site | -| embedding provider down | chunks stored without vectors; lexical search still serves | `code_embed_recovery` | -| compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | -| a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | -| compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | +| Failure | Behaviour | Recovery | +| ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `git fetch` fails | watermark unmoved; the entry's `fetch` tier records the error, its kind and fix (`tier_health`) | the next pass (supervisor backoff) | +| crash mid-commit | the commit is re-run | idempotent upserts | +| a file fails to parse | chunks without symbols, `code_files.index_error` set (a parse past `code_parse_timeout_s` or `code_parse_memory_mb` included, and one that could not run in its process) | `code.index_errors` lists them; fixed by the next change or a repair (raising either limit re-reads none) | +| every file fails to parse with `LookupError` "... is loaded from outside the interpreter's site-packages" | chunks without symbols for every file: tree-sitter or a grammar is installed where the parse process does not see it | install the tree-sitter packages into the server interpreter's own environment, not through `PYTHONPATH` or the user site | +| embedding provider down | chunks stored without vectors; lexical search still serves | `code_embed_recovery` | +| compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | +| a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | +| compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | | a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window, and so is a window file with a factory call, whose constructor may be in the skipped document (`code.callers` and `code.callees` name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | -| a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | -| GitHub rate limit | the pass ends, cursor unmoved | the next pass | -| branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | -| weekly graph stats fail | last week's ranks keep serving | the next weekly pass | +| a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | +| GitHub rate limit | the pass ends, cursor unmoved | the next pass | +| branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | +| weekly graph stats fail | last week's ranks keep serving | the next weekly pass | The code index's gauges (`loom.code.index_lag_commits`, `loom.code.stale_files`, `loom.code.tier_lag_seconds`, `loom.code.embed_backlog`, `loom.code.files_errored`) are From c3ed4e4c23271f673d8015845ae8bb09c139a6aa Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:48:06 +0000 Subject: [PATCH 42/81] Key merged documents by their raw path bytes The merge keyed documents by the relative_path decoded with replacement, so two paths that differ only by a malformed byte and a literal U+FFFD collapsed to one key and the later document replaced the earlier one. Reversing the inputs dropped the other document. The merge now keys on the raw path bytes (the last value of field 1) and decodes the path only to ask which project owns it. Ownership is unchanged: both names decode to the same text, so both get the same answer. scip_to_delta gains _document_path_bytes; _document_path decodes it as before. The new test merges a document named with a 0xff byte and one named with U+FFFD, in both input orders, with and without a project; both survive. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 18 +++++++++----- scripts/scip_harness/scip_to_delta.py | 15 ++++++++---- tests/unit/test_scip_merge_indexes.py | 28 ++++++++++++++++++++++ 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index f12f4b6c1c7..20d959a218a 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -15,9 +15,10 @@ writes a zero-byte output so the converter treats it as an empty index. The merge reads only the top-level records and each document's -relative_path, and copies the records it keeps byte for byte. Nothing is -decoded, so a document python-protobuf would refuse (a string field that -is not UTF-8) reaches the converter, which decides what to do with it. A +relative_path, and copies the records it keeps byte for byte. Documents +are told apart by the raw path bytes; the path is decoded only to ask which +project owns it. A document python-protobuf would refuse (a string field +that is not UTF-8) reaches the converter, which decides what to do with it. A record, fixed-width value, varint, tag or group that the protobuf parser would refuse is corrupt: the merge stops and names the part, as the whole-index parse used to. @@ -51,6 +52,7 @@ def _load_harness_module(name: str) -> Any: _read_index = _converter._read_index _top_level_records = _converter._top_level_records _document_path = _converter._document_path +_document_path_bytes = _converter._document_path_bytes _METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 @@ -118,7 +120,7 @@ def merge_indexes( raise SystemExit("--project count must match the number of indexes") owners = known_projects if known_projects is not None else (projects or []) metadata: list[Any] = [] - documents: dict[str, Any] = {} + documents: dict[bytes, Any] = {} external_symbols: list[Any] = [] has_payload = False for i, path in enumerate(paths): @@ -131,9 +133,13 @@ def merge_indexes( if field == _METADATA and not has_payload: metadata.append(payload) elif field == _DOCUMENT: - rel = _document_path(payload) + # Key on the raw bytes: two names that differ only by a + # malformed byte and a literal U+FFFD decode alike but are + # two documents. Ownership reads the decoded text. + raw = _document_path_bytes(payload) + rel = raw.decode("utf-8", "replace") if project is None or _keeps(project, rel, owners): - documents[rel] = payload + documents[raw] = payload elif field == _EXTERNAL_SYMBOL: external_symbols.append(payload) except ValueError as e: diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 559175615d4..f40b12aa1e4 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -890,15 +890,20 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: pos = skip(pos, wire, field, 0) -def _document_path(payload) -> str: - """A serialized Document's relative_path (field 1), read without parsing - its occurrences. A singular field written more than once takes its last - value, as the protobuf parser takes it.""" +def _document_path_bytes(payload: bytes | memoryview) -> bytes: + """A serialized Document's relative_path (field 1) as the raw bytes, read + without parsing its occurrences. A singular field written more than once + takes its last value, as the protobuf parser takes it.""" path = b"" for field, value in _top_level_records(payload): if field == 1: path = bytes(value) - return path.decode("utf-8", "replace") + return path + + +def _document_path(payload) -> str: + """The relative_path as text; a malformed byte reads as U+FFFD.""" + return _document_path_bytes(payload).decode("utf-8", "replace") def _stream_documents(data, scip_pb2, *, paths: set[str] | None = None, ordered: bool = False): diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index eb18da4d165..0ad7ed43c3d 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -633,6 +633,34 @@ def test_merge_keeps_both_documents_of_the_reviewers_pair(tmp_path: Path) -> Non assert [d.relative_path for d in merged.documents] == ["pkg/second.ts", "pkg/first.ts"] +@pytest.mark.parametrize("reverse", [False, True], ids=["malformed first", "literal first"]) +@pytest.mark.parametrize("projects", [None, ["pkg"]], ids=["no project", "owned by pkg"]) +def test_merge_keeps_paths_that_differ_only_by_a_malformed_byte( + tmp_path: Path, reverse: bool, projects: list[str] | None +) -> None: + """A path with a stray 0xff byte decodes to the same text as one with a + literal U+FFFD. They are two documents; the merge keeps both, in either + input order. Ownership still reads the decoded text, which is the same + for both.""" + malformed = _record(2, _record(1, b"pkg/a\xff.ts")) + literal = _record(2, _record(1, "pkg/a\ufffd.ts".encode())) + inputs = [literal, malformed] if reverse else [malformed, literal] + parts = [] + for i, raw in enumerate(inputs): + part = tmp_path / f"part{i}.scip" + part.write_bytes(raw) + parts.append(part) + out = tmp_path / "merged.scip" + _MOD.merge_indexes( + parts, + out, + projects=None if projects is None else projects * len(parts), + known_projects=projects, + ) + kept = [bytes(p) for field, p in _MOD._top_level_records(out.read_bytes()) if field == 2] + assert kept == [raw[2:] for raw in inputs] # a two-byte record header, then the payload + + _DOCUMENT_PATH_PAYLOADS = { "no path": b"", "one path": _record(1, b"a.ts"), From d958be34067ff24df5615b8d2d662f89867e90a5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:49:08 +0000 Subject: [PATCH 43/81] Type the raw path reader as bytes mypy on the two modules stays at its baseline of 54 errors. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index f40b12aa1e4..a8cccb76df6 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -890,7 +890,7 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: pos = skip(pos, wire, field, 0) -def _document_path_bytes(payload: bytes | memoryview) -> bytes: +def _document_path_bytes(payload: bytes) -> bytes: """A serialized Document's relative_path (field 1) as the raw bytes, read without parsing its occurrences. A singular field written more than once takes its last value, as the protobuf parser takes it.""" From a0f86605ef309b082c1ba035f2512186563ca049 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 06:53:23 +0000 Subject: [PATCH 44/81] Read the stale marks of an incoming answer with a bound An incoming answer (callers, impact, grep neighbours, the PR pack line, the symbol uses block, test_gate) fetched every active stale path of the namespace into Python, though it needs only whether any is marked and a few names for the note. A full pass can mark a whole source tree. Add scip_stale_sample: the marks read stops at a LIMIT (three, as the note names), and a cleared mark, an empty row, is still not returned. The pack line and the constructor-coverage probe ask for one. The answer stays a lower bound whenever a mark exists, and a failed read still counts as one. The note no longer counts files, since a sample cannot. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/code/app/index/packs.py | 2 +- server/code/app/symbol/coverage.py | 11 +-- server/code/app/symbol/graph.py | 6 +- server/code/store/index/symbols.py | 17 +++++ .../integration/test_code_scip_stale_mark.py | 22 ++++++ tests/unit/test_code_callers_member_fold.py | 2 +- tests/unit/test_code_coverage_tiers.py | 2 +- tests/unit/test_code_ctor_call_edges.py | 4 +- tests/unit/test_code_epistemic_envelope.py | 2 +- tests/unit/test_code_grep_neighbours.py | 4 +- tests/unit/test_code_stale_marks_bounded.py | 74 +++++++++++++++++++ tests/unit/test_code_stale_marks_note.py | 8 +- tests/unit/test_code_symbol_uses_context.py | 2 +- tests/unit/test_code_test_gate.py | 2 +- 14 files changed, 137 insertions(+), 21 deletions(-) create mode 100644 tests/unit/test_code_stale_marks_bounded.py diff --git a/server/code/app/index/packs.py b/server/code/app/index/packs.py index df4a5c4c8b1..069da24e565 100644 --- a/server/code/app/index/packs.py +++ b/server/code/app/index/packs.py @@ -320,7 +320,7 @@ async def _envelope_line( if remaining: covered |= await repo.scip_covered_paths(org, ns, remaining) # a file marked stale may hold a caller no edge shows - marked = await repo.scip_stale_marks(org, ns) + marked = await repo.scip_stale_sample(org, ns, limit=1) env = envelope( unresolved=unresolved, ambiguous=ambiguous, diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index 96d1ea5a6eb..c33ce495750 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -105,11 +105,12 @@ async def _marked_stale(repo: CodeRepo, org: str, ns: str) -> set[str]: """Files any compiler tier holds marked stale in the namespace: a delta skipped their document, so each may hold a call no edge shows, to a seed neither it nor any served edge path names. An incoming answer (callers, an impact radius, the tests linked - through callers) is not exact while one is. One read of the namespace's mark rows - per query, never cached: a delta may mark a file at any time. Fail-open to UNPROVEN: - a failed read counts as a mark.""" + through callers) is not exact while one is. One bounded read per query (a sample of + the marked files, enough to say whether any is and to name a few), never cached: a + delta may mark a file at any time. Fail-open to UNPROVEN: a failed read counts as + a mark.""" try: - return await repo.scip_stale_marks(org, ns) + return await repo.scip_stale_sample(org, ns) except Exception as e: # noqa: BLE001 — a freshness read must not fail the answer logger.debug("scip stale-marks read skipped: %s", e) return {MARKS_UNREAD} @@ -192,7 +193,7 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, if not scip_bit: return False, ts_ok try: - marked = await repo.scip_stale_marks(org, ns, "clang") + marked = await repo.scip_stale_sample(org, ns, "clang", limit=1) except Exception as e: # noqa: BLE001 — fail closed: an error can only lower an answer logger.debug("scip stale-marks read skipped: %s", e) return False, ts_ok diff --git a/server/code/app/symbol/graph.py b/server/code/app/symbol/graph.py index 808ed1cf1e7..70b0c0e7825 100644 --- a/server/code/app/symbol/graph.py +++ b/server/code/app/symbol/graph.py @@ -495,9 +495,9 @@ def _stale_note(stale_paths: set[str]) -> str: parts = [] if files: parts.append( - f"{len(files)} file(s) changed since the compiler tier last ran or skipped " - f"by it ({', '.join(sorted(files)[:3])}): edges from them may be stale, and " - "calls in them missing" + "file(s) changed since the compiler tier last ran or skipped " + f"by it ({', '.join(sorted(files)[:3])}{', ...' if len(files) > 3 else ''}): " + "edges from them may be stale, and calls in them missing" ) if MARKS_UNREAD in stale_paths: parts.append("the stale marks could not be read") diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index dab964b3468..6b69534ac46 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -28,6 +28,9 @@ NameCandidates = dict[str, list[tuple[str, str, str]]] +# How many marked paths one bounded read returns: the callers note names three. +STALE_SAMPLE = 3 + def _marks_in_force(keys: str) -> str: """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches @@ -601,6 +604,20 @@ async def scip_stale_marks(self, org: str, ns: str, tier: str | None = None) -> ) return {str(r["path"]) for r in rows} + async def scip_stale_sample( + self, org: str, ns: str, tier: str | None = None, *, limit: int = STALE_SAMPLE + ) -> set[str]: + """Up to `limit` of the paths `scip_stale_marks` would return, in one read the + store stops at `limit`: the answer to "is any file marked stale" (a non-empty set) + and the files a note can name, without fetching every mark of a namespace a full + pass marked whole. An emptied mark is no row here either (`_marks_in_force`).""" + prefix = f"{SCIP_STALE_PREFIX}{tier}:" if tier else SCIP_STALE_PREFIX + rows = await self._ch.query_all( + _marks_in_force("startsWith(state_key, {mark:String})") + " LIMIT {limit:UInt32}", + {"org": org, "ns": ns, "mark": prefix, "limit": limit}, + ) + return {str(r["path"]) for r in rows} + async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: one namespace-wide distinct read, taken once per full compiler run so diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index d1f08b11c87..947de209ab1 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -454,3 +454,25 @@ async def answers() -> list[tuple[str, list[str]]]: ) await repo.set_state(org, ns, "scip_commit", "c" * 40) assert await answers() == [("exact", [])] * 2 + + +@pytest.mark.asyncio +async def test_the_bounded_mark_read_stops_at_its_limit_and_skips_a_cleared_mark( + ch_client: Any, +) -> None: + org, ns = unique_org("scip-stale-sample"), "code-stale-sample" + repo = await _repo(ch_client, org, ns, []) + marked = [f"src/m{i}.cpp" for i in range(6)] + await repo.set_states(org, ns, {f"scip_stale:clang:{p}": "a" * 40 for p in marked}) + assert await repo.scip_stale_marks(org, ns) == set(marked) + + sample = await repo.scip_stale_sample(org, ns) + assert len(sample) == 3 and sample <= set(marked) + assert len(await repo.scip_stale_sample(org, ns, "clang", limit=1)) == 1 + assert await repo.scip_stale_sample(org, ns, "python") == set() + + # a cleared mark is an empty row: no bounded read returns it, whatever its place + await repo.set_states(org, ns, {f"scip_stale:clang:{p}": "" for p in marked[:5]}) + assert await repo.scip_stale_sample(org, ns) == {marked[5]} + await repo.set_states(org, ns, {f"scip_stale:clang:{marked[5]}": ""}) + assert await repo.scip_stale_sample(org, ns) == set() diff --git a/tests/unit/test_code_callers_member_fold.py b/tests/unit/test_code_callers_member_fold.py index 859eeb0d3ad..9e3195e6e5e 100644 --- a/tests/unit/test_code_callers_member_fold.py +++ b/tests/unit/test_code_callers_member_fold.py @@ -73,7 +73,7 @@ class _FakeRepo: - async def scip_stale_marks(self, org, ns, tier=None): + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): return set() def __init__(self, seed: dict[str, Any]) -> None: diff --git a/tests/unit/test_code_coverage_tiers.py b/tests/unit/test_code_coverage_tiers.py index bb8eda6d81a..e271cd0dffd 100644 --- a/tests/unit/test_code_coverage_tiers.py +++ b/tests/unit/test_code_coverage_tiers.py @@ -908,7 +908,7 @@ async def edges_for_symbols(self, *a, **k): async def call_guards_for_callers(self, *a, **k): return {} - async def scip_stale_marks(self, org, ns, tier=None): + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): return set() def __getattr__(self, name): diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 0a1341b5f43..c5d205ef6f3 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -608,8 +608,8 @@ async def scip_covered_paths(self, org, ns, paths): async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} - async def scip_stale_marks(self, org, ns, tier=None): - return set(self.stale_marks) if tier in ("clang", None) else set() + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): + return set(sorted(self.stale_marks)[:limit]) if tier in ("clang", None) else set() async def all_state(self, org, ns): self.state_reads += 1 diff --git a/tests/unit/test_code_epistemic_envelope.py b/tests/unit/test_code_epistemic_envelope.py index afc546a70f7..08b9f57176d 100644 --- a/tests/unit/test_code_epistemic_envelope.py +++ b/tests/unit/test_code_epistemic_envelope.py @@ -168,7 +168,7 @@ async def scip_covered_paths(self, org, ns, paths): async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} - async def scip_stale_marks(self, org, ns, tier=None): + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): return set() indexed = {"src/A.cpp", "src/Constants.h"} # in code_files; Constants.h has no symbols diff --git a/tests/unit/test_code_grep_neighbours.py b/tests/unit/test_code_grep_neighbours.py index 59c95189c17..f9b87df9a6d 100644 --- a/tests/unit/test_code_grep_neighbours.py +++ b/tests/unit/test_code_grep_neighbours.py @@ -236,7 +236,7 @@ async def scip_covered_paths(self, org, ns, paths): async def scip_stale_paths(self, org, ns, paths): return {p for p in paths if p in getattr(self, "stale_paths", set())} - async def scip_stale_marks(self, org, ns, tier=None): + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): return set() @@ -343,7 +343,7 @@ def _entry( } class _EdgeRepo: - async def scip_stale_marks(self, org, ns, tier=None): + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): return set(marked) async def edges_for_symbols(self, org, ns, ids, *, direction, edge_kinds=None, **kw): diff --git a/tests/unit/test_code_stale_marks_bounded.py b/tests/unit/test_code_stale_marks_bounded.py new file mode 100644 index 00000000000..e3af97c489f --- /dev/null +++ b/tests/unit/test_code_stale_marks_bounded.py @@ -0,0 +1,74 @@ +"""An incoming answer reads the namespace's stale marks with a bound: a pass that marked a +whole source tree costs one capped read, not a fetch of every marked path, and the +answer is still a lower bound.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from server.code.app.index.packs import _envelope_line +from server.code.app.symbol.coverage import MARKS_UNREAD, _marked_stale +from server.code.store.index import CodeRepo + +_MARKED_WHOLE = 5000 + + +class _CH: + """Answers the marks read as ClickHouse would: every mark of a namespace a full pass + marked, cut at the query's own LIMIT when it has one.""" + + def __init__(self, *, fail: bool = False) -> None: + self.fail = fail + self.reads: list[tuple[str, dict[str, Any]]] = [] + + async def query_all( + self, sql: str, params: dict[str, Any] | None = None + ) -> list[dict[str, Any]]: + self.reads.append((sql, dict(params or {}))) + if self.fail: + raise RuntimeError("down") + rows = [{"path": f"src/f{i:05d}.cpp"} for i in range(_MARKED_WHOLE)] + if "LIMIT {limit:UInt32}" in sql: + return rows[: int((params or {})["limit"])] + return rows + + +class _PackRepo(CodeRepo): + async def call_misses_for_names(self, org: str, ns: str, names: list[str]) -> dict[str, Any]: + return {} + + async def scip_covered_paths(self, org: str, ns: str, paths: list[str]) -> set[str]: + return set(paths) + + +def _assert_bounded(ch: _CH) -> None: + assert ch.reads + for sql, params in ch.reads: + assert "LIMIT {limit:UInt32}" in sql + assert params["limit"] <= 3 + + +@pytest.mark.asyncio +async def test_a_namespace_marked_whole_is_read_with_a_limit() -> None: + ch = _CH() + marked = await _marked_stale(CodeRepo(ch), "o", "n") # type: ignore[arg-type] + _assert_bounded(ch) + assert 0 < len(marked) <= 3 + assert MARKS_UNREAD not in marked + + +@pytest.mark.asyncio +async def test_the_pack_line_stays_a_lower_bound_over_a_bounded_read() -> None: + ch = _CH() + changed = [{"name": "f", "path": "src/a.cpp", "tier": "scip"}] + line = await _envelope_line(_PackRepo(ch), "o", "n", changed) # type: ignore[arg-type] + _assert_bounded(ch) + assert line == "callers below are lower_bound (scip_stale_files)" + + +@pytest.mark.asyncio +async def test_a_failed_read_still_counts_as_a_mark() -> None: + ch = _CH(fail=True) + assert await _marked_stale(CodeRepo(ch), "o", "n") == {MARKS_UNREAD} # type: ignore[arg-type] diff --git a/tests/unit/test_code_stale_marks_note.py b/tests/unit/test_code_stale_marks_note.py index 6a6a0f1e84a..99ce26e1aaf 100644 --- a/tests/unit/test_code_stale_marks_note.py +++ b/tests/unit/test_code_stale_marks_note.py @@ -22,7 +22,9 @@ async def call_misses_for_names(self, org: str, ns: str, names: list[str]) -> di async def scip_covered_paths(self, org: str, ns: str, paths: list[str]) -> set[str]: return set(paths) - async def scip_stale_marks(self, org: str, ns: str) -> set[str]: + async def scip_stale_sample( + self, org: str, ns: str, tier: str | None = None, *, limit: int = 3 + ) -> set[str]: if isinstance(self._marks, Exception): raise self._marks return self._marks @@ -48,7 +50,7 @@ async def test_pack_callers_line_is_absent_when_the_marks_read_fails() -> None: def test_stale_note_counts_and_names_files() -> None: note = _stale_note({"src/b.cpp", "src/a.cpp"}) - assert note.startswith("2 file(s) changed since the compiler tier last ran or skipped by it") + assert note.startswith("file(s) changed since the compiler tier last ran or skipped by it") assert "(src/a.cpp, src/b.cpp)" in note assert "could not be read" not in note @@ -61,7 +63,7 @@ def test_stale_note_says_the_marks_could_not_be_read() -> None: def test_stale_note_does_not_count_the_placeholder_as_a_file() -> None: note = _stale_note({MARKS_UNREAD, "src/a.cpp"}) - assert note.startswith("1 file(s) changed") + assert note.startswith("file(s) changed") assert "(src/a.cpp)" in note assert MARKS_UNREAD not in note assert note.endswith("the stale marks could not be read") diff --git a/tests/unit/test_code_symbol_uses_context.py b/tests/unit/test_code_symbol_uses_context.py index 6a5a74be566..1bdc7fe553e 100644 --- a/tests/unit/test_code_symbol_uses_context.py +++ b/tests/unit/test_code_symbol_uses_context.py @@ -188,7 +188,7 @@ class _FakeRepo: - async def scip_stale_marks(self, org, ns, tier=None): + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): return set(getattr(self, "marks", set())) def __init__( diff --git a/tests/unit/test_code_test_gate.py b/tests/unit/test_code_test_gate.py index 57bf3a7402c..4453e212141 100644 --- a/tests/unit/test_code_test_gate.py +++ b/tests/unit/test_code_test_gate.py @@ -524,7 +524,7 @@ def _edge(frm: str, to: str, fq: str, path: str, kind: str = "calls") -> dict[st class _Repo: - async def scip_stale_marks(self, org, ns, tier=None): + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): return set(getattr(self, "marks", set())) def __init__(self) -> None: From 4f34de0f1185717054474051ed600db25df0f2ba Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 07:35:48 +0000 Subject: [PATCH 45/81] Return the merge's kept paths as text The merge keys its documents on raw bytes, so a caller that matches the kept set against member paths (text) would never find a path in it. merge_indexes now returns the kept paths decoded with "replace", the same text ownership reads, and deduplication still runs on the bytes. The unused `_document_path` alias is gone; the one test that read the converter's function through it names the converter. Assisted-by: Claude Code:claude-sonnet-5-5 Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 5 +++-- tests/unit/test_scip_merge_indexes.py | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 20d959a218a..485c01142ba 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -51,7 +51,6 @@ def _load_harness_module(name: str) -> Any: _converter = _load_harness_module("scip_to_delta") _read_index = _converter._read_index _top_level_records = _converter._top_level_records -_document_path = _converter._document_path _document_path_bytes = _converter._document_path_bytes _METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 @@ -115,7 +114,8 @@ def merge_indexes( output: Path, projects: list[str] | None = None, known_projects: list[str] | None = None, -) -> None: +) -> set[str]: + """Write the merged index; return the paths whose document it holds, as text.""" if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") owners = known_projects if known_projects is not None else (projects or []) @@ -162,6 +162,7 @@ def merge_indexes( except BaseException: tmp.unlink(missing_ok=True) raise + return {raw.decode("utf-8", "replace") for raw in documents} def main(argv: list[str] | None = None) -> int: diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 0ad7ed43c3d..360416d6ff4 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -678,7 +678,7 @@ def test_merge_keeps_paths_that_differ_only_by_a_malformed_byte( def test_document_path_is_what_the_protobuf_parser_reads(how: str) -> None: payload = _DOCUMENT_PATH_PAYLOADS[how] doc = _scip_pb2().Document.FromString(payload) - assert _MOD._document_path(payload) == doc.relative_path + assert _MOD._converter._document_path(payload) == doc.relative_path _REPEATED_METADATA = { @@ -709,3 +709,16 @@ def test_the_converter_and_merge_read_repeated_metadata_as_the_parser_does( out = tmp_path / "merged.scip" _MOD.merge_indexes([part], out) assert _scip_pb2().Index.FromString(out.read_bytes()).metadata == parsed.metadata + + +def test_merge_returns_the_kept_paths_as_text(tmp_path: Path) -> None: + """The paths a caller matches against its own member paths are text, while the + merge keys its documents on raw bytes: a stray 0xff byte reads as U+FFFD.""" + plain = tmp_path / "plain.scip" + plain.write_bytes(_index_with_docs(["pkg/a.ts"])) + odd = tmp_path / "odd.scip" + odd.write_bytes(_record(2, _record(1, b"pkg/b\xff.ts"))) + out = tmp_path / "merged.scip" + kept = _MOD.merge_indexes([plain, odd], out) + assert kept == {"pkg/a.ts", "pkg/b\ufffd.ts"} + assert all(isinstance(path, str) for path in kept) From 82521da9f77210978ce4f719c08072a77a2db5a0 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 07:42:25 +0000 Subject: [PATCH 46/81] Read one more stale mark than the callers note names The note names three marked files and adds ", ..." when more than three paths were collected, but the bounded read stopped at three, so a namespace with more marks read the same as one with exactly three. The read now returns up to four marks (STALE_SAMPLE, STALE_SHOWN + 1), the note still names three, and the ellipsis shows only when a fourth was read. The bounded-read tests assert the new cap and the note tests cover three and four files. Assisted-by: Claude Code:claude-sonnet-5-5 Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/code/app/symbol/graph.py | 4 +++- server/code/store/index/symbols.py | 6 ++++-- tests/integration/test_code_scip_stale_mark.py | 2 +- tests/unit/test_code_stale_marks_bounded.py | 6 ++++-- tests/unit/test_code_stale_marks_note.py | 7 +++++++ 5 files changed, 19 insertions(+), 6 deletions(-) diff --git a/server/code/app/symbol/graph.py b/server/code/app/symbol/graph.py index 70b0c0e7825..3dee57b03d8 100644 --- a/server/code/app/symbol/graph.py +++ b/server/code/app/symbol/graph.py @@ -51,6 +51,7 @@ from server.code.app.symbol.resolve import _resolve_symbols, _seed_ids_of from server.code.domain.index.epistemic import envelope as _envelope from server.code.store.index import CodeRepo +from server.code.store.index.symbols import STALE_SHOWN from server.core.errors import NotFoundError from server.settings import settings @@ -496,7 +497,8 @@ def _stale_note(stale_paths: set[str]) -> str: if files: parts.append( "file(s) changed since the compiler tier last ran or skipped " - f"by it ({', '.join(sorted(files)[:3])}{', ...' if len(files) > 3 else ''}): " + f"by it ({', '.join(sorted(files)[:STALE_SHOWN])}" + f"{', ...' if len(files) > STALE_SHOWN else ''}): " "edges from them may be stale, and calls in them missing" ) if MARKS_UNREAD in stale_paths: diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 6b69534ac46..d6c879ffe87 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -28,8 +28,10 @@ NameCandidates = dict[str, list[tuple[str, str, str]]] -# How many marked paths one bounded read returns: the callers note names three. -STALE_SAMPLE = 3 +# The callers note names three marked paths; a bounded read returns one more, so the +# note can tell whether there are others. +STALE_SHOWN = 3 +STALE_SAMPLE = STALE_SHOWN + 1 def _marks_in_force(keys: str) -> str: diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 947de209ab1..d5cd8107d97 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -467,7 +467,7 @@ async def test_the_bounded_mark_read_stops_at_its_limit_and_skips_a_cleared_mark assert await repo.scip_stale_marks(org, ns) == set(marked) sample = await repo.scip_stale_sample(org, ns) - assert len(sample) == 3 and sample <= set(marked) + assert len(sample) == 4 and sample <= set(marked) assert len(await repo.scip_stale_sample(org, ns, "clang", limit=1)) == 1 assert await repo.scip_stale_sample(org, ns, "python") == set() diff --git a/tests/unit/test_code_stale_marks_bounded.py b/tests/unit/test_code_stale_marks_bounded.py index e3af97c489f..439d458a9d7 100644 --- a/tests/unit/test_code_stale_marks_bounded.py +++ b/tests/unit/test_code_stale_marks_bounded.py @@ -11,6 +11,7 @@ from server.code.app.index.packs import _envelope_line from server.code.app.symbol.coverage import MARKS_UNREAD, _marked_stale from server.code.store.index import CodeRepo +from server.code.store.index.symbols import STALE_SAMPLE, STALE_SHOWN _MARKED_WHOLE = 5000 @@ -47,7 +48,7 @@ def _assert_bounded(ch: _CH) -> None: assert ch.reads for sql, params in ch.reads: assert "LIMIT {limit:UInt32}" in sql - assert params["limit"] <= 3 + assert params["limit"] <= STALE_SAMPLE @pytest.mark.asyncio @@ -55,7 +56,8 @@ async def test_a_namespace_marked_whole_is_read_with_a_limit() -> None: ch = _CH() marked = await _marked_stale(CodeRepo(ch), "o", "n") # type: ignore[arg-type] _assert_bounded(ch) - assert 0 < len(marked) <= 3 + # one more than the note names, so the note can tell that there are more + assert len(marked) == STALE_SAMPLE == STALE_SHOWN + 1 == 4 assert MARKS_UNREAD not in marked diff --git a/tests/unit/test_code_stale_marks_note.py b/tests/unit/test_code_stale_marks_note.py index 99ce26e1aaf..03f9bd1b154 100644 --- a/tests/unit/test_code_stale_marks_note.py +++ b/tests/unit/test_code_stale_marks_note.py @@ -67,3 +67,10 @@ def test_stale_note_does_not_count_the_placeholder_as_a_file() -> None: assert "(src/a.cpp)" in note assert MARKS_UNREAD not in note assert note.endswith("the stale marks could not be read") + + +def test_stale_note_marks_that_there_are_more_files_only_when_a_fourth_is_sampled() -> None: + three = _stale_note({"src/a.cpp", "src/b.cpp", "src/c.cpp"}) + assert "(src/a.cpp, src/b.cpp, src/c.cpp)" in three and "..." not in three + four = _stale_note({"src/a.cpp", "src/b.cpp", "src/c.cpp", "src/d.cpp"}) + assert "(src/a.cpp, src/b.cpp, src/c.cpp, ...)" in four From e35389c1c06848fb953d5b111c3af2f40046c8dd Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 08:00:54 +0000 Subject: [PATCH 47/81] Read a skipped TypeScript document's callers as stale A TypeScript document that fails to decode defines nothing, so the kind of an arrow-function constant in it is unknown. `_ts_needs_failed_kind` looked only at `--failed-files`, so a caller of that constant converted without its `calls` edge and the apply tombstoned the edge with no stale mark on the caller. The check now also takes the skipped documents' paths: such a caller keeps its rows and is marked stale, as it already is for a failed member. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 20 ++++++++++----- tests/unit/test_scip_to_delta_skip.py | 37 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index fc962ed2f6b..36b6cda52c0 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -292,8 +292,9 @@ def _ts_symbol_file(symbol: str) -> str | None: return None -def _ts_needs_failed_kind(doc: Any, failed: set[str]) -> bool: - """`doc` refers to a term defined in one of the `failed` files whose kind the index +def _ts_needs_failed_kind(doc: Any, failed: set[str], skipped: set[str]) -> bool: + """`doc` refers to a term defined in one of the `failed` files (their indexer + failed) or `skipped` ones (their document did not decode) whose kind the index does not hold. A term's kind decides whether a reference is a `calls` edge, and only its definition gives it (`_ts_prepass`).""" if _TS is None: @@ -302,7 +303,10 @@ def _ts_needs_failed_kind(doc: Any, failed: set[str]) -> bool: symbol = occ.symbol if occ.symbol_roles & 0x1 or not symbol.endswith(".") or symbol.endswith(")."): continue - if symbol not in _TS.def_kinds and _ts_symbol_file(symbol) in failed: + if symbol in _TS.def_kinds: + continue + file = _ts_symbol_file(symbol) + if file in failed or file in skipped: return True return False @@ -1368,10 +1372,12 @@ def _files(self, data, scip_pb2, changed: set[str] | None): for i, doc in _indexed_documents(data, scip_pb2, self._skips, changed, True): if changed is not None and doc.relative_path not in changed: continue - if self._failed and _ts_needs_failed_kind(doc, self._failed): - # Converted, it would lose the `calls` edges into the failed files that a - # complete index writes: its rows stay instead, marked stale. - failure = ValueError("refers to a definition in a file whose indexer failed") + if (self._failed or self._skips.paths) and _ts_needs_failed_kind( + doc, self._failed, self._skips.paths + ): + # Converted, it would lose the `calls` edges into the failed or skipped + # files that a complete index writes: its rows stay instead, marked stale. + failure = ValueError("refers to a definition in a file the index lacks") self._skips.add(doc.relative_path, failure, i) continue try: diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 832008090d7..ca5dd429871 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -293,6 +293,43 @@ def test_a_document_that_calls_into_a_failed_member_is_skipped_too(tmp_path: Pat assert plain["files"][0]["edges"] == [] +def _ts_index_with_undecodable_b(tmp_path: Path) -> tuple[Path, Path]: + """`_ts_index` with b's document in the index, but one string of it not UTF-8: it is + skipped at parse time and defines nothing, so `helper`'s kind is unknown.""" + index, root = _ts_index(tmp_path, with_b=True) + pb = _pb() + parsed = pb.Index() + parsed.ParseFromString(index.read_bytes()) + b = next(d for d in parsed.documents if d.relative_path == "pkg/b/b.ts") + b.occurrences.add( + range=[0, 0, 1], symbol="scip-typescript npm fx 0.0.0 pkg/b/`b.ts`/" + _MARK.decode() + ) + raw = parsed.SerializeToString() + assert raw.count(_MARK) == 1 + index.write_bytes(raw.replace(_MARK, b"\xff\xfe" + _MARK[2:])) + return index, root + + +def test_a_document_that_calls_into_a_skipped_document_is_skipped_too(tmp_path: Path) -> None: + """b's document fails to decode, so `helper` is in no `def_kinds`. Converted anyway, + pkg/a/a.ts would lose its `calls` edge to it with no stale mark on a.ts, and the + apply would tombstone the edge. It keeps its rows instead, marked stale, as for a + failed member's files; the window or the whole run, the same.""" + conv = _converter() + index, root = _ts_index_with_undecodable_b(tmp_path) + window = {"pkg/a/a.ts", "pkg/b/b.ts"} + delta = conv.convert(str(index), window, [], "h" * 40, "b" * 40, source_root=str(root)) + assert delta["files"] == [] + assert delta["skipped_files"] == ["pkg/a/a.ts", "pkg/b/b.ts"] + assert delta["delta_version"] == 2 + full = conv.convert(str(index), None, [], "h" * 40, "", source_root=str(root), full=True) + assert full["files"] == [] + assert full["skipped_files"] == ["pkg/a/a.ts", "pkg/b/b.ts"] + # a window of the skipped document alone lists it and nothing else + alone = conv.convert(str(index), {"pkg/b/b.ts"}, [], "h" * 40, "b" * 40, source_root=str(root)) + assert alone["skipped_files"] == ["pkg/b/b.ts"] + + def test_failed_files_are_warned_about_and_counted(tmp_path: Path, capsys) -> None: """A failed member's files are named on stderr in the skipped-document format the server logs, and counted in `skipped_failed`; a window only its own.""" From 60417d589320ce8f4683499a187217e3f54b86e2 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 08:51:03 +0000 Subject: [PATCH 48/81] Claim constructor calls only when the constructor scan read every document A full C++ run claimed ctor_calls whenever none of its listed files was skipped. The harness passes --changed-files with --full, so a document the constructor scan could not read outside that list was never listed, and the run still claimed every factory constructor call of the namespace. tail now also requires the scan to have read every document of the index. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 10 ++++++---- tests/unit/test_scip_to_delta_skip.py | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 596f48ba1d0..06fa0d11545 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -29,8 +29,9 @@ source line under that reference (from `--source-root`, default the index's project_root) and emits a `calls` edge to every known constructor overload of T — 1.0 for a single constructor, 0.8 each for several. A `--full` -conversion with source claims the `ctor_calls` feature, which the server -records per namespace so the read side stops labelling a constructor's +conversion with source claims the `ctor_calls` feature when its constructor +scan read every document of the index and it skipped none of its files. The +server records it per namespace so the read side stops labelling a constructor's empty answer `ctor_edges_absent`. The type argument may sit on the line after the factory (`std::make_shared<\n T>(...)`): the test then runs from the factory occurrence's end to the token. @@ -1350,8 +1351,9 @@ def tail(self) -> dict: "skipped_failed": len(self._skips.labels), }, } - # a skipped document may hold a factory call: an incomplete run makes no claim - if self._claims_ctor_calls and not skipped: + # a skipped document may hold a factory call, and a constructor scan that missed + # a document, inside the window or not, may miss an overload: neither claims + if self._claims_ctor_calls and self._run.ctors_complete and not skipped: out["features"] = [CTOR_CALLS_FEATURE] # 2 lists skipped files: a server that applies version 1 only refuses it instead of # applying it without their stale marks. Last, since a document that fails to diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 8e3e543e794..2d27c293c6a 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -287,3 +287,26 @@ def test_a_factory_caller_keeps_its_rows_when_the_overload_scan_misses_a_documen full = conv.convert(str(index), None, [], "h" * 40, "", source_root=str(root), full=True) assert full["skipped_files"] == ["src/a.cpp", "src/foo.h"] assert "features" not in full + + +def test_a_full_run_whose_constructor_scan_skipped_a_document_outside_its_files_makes_no_claim( + tmp_path: Path, +) -> None: + """The C++ `--full` harness passes `--changed-files`, so a document the constructor + scan could not read can sit outside the files the delta lists. src/foo.h fails to + decode and the run converts only src/ok.cpp: nothing is listed as skipped, yet the + scan behind the claim missed a document, so the run does not claim `ctor_calls`.""" + conv = _converter() + index, root = _overload_index(tmp_path, bad=True) + delta = conv.convert( + str(index), {"src/ok.cpp"}, [], "h" * 40, "", source_root=str(root), full=True + ) + assert [f["path"] for f in delta["files"]] == ["src/ok.cpp"] + assert delta["skipped_files"] == [] and delta["stats"]["skipped_failed"] == 1 + assert "features" not in delta + # the same window over an index the scan reads whole claims it + index, root = _overload_index(tmp_path, bad=False) + whole = conv.convert( + str(index), {"src/ok.cpp"}, [], "h" * 40, "", source_root=str(root), full=True + ) + assert whole["features"] == ["ctor_calls"] From cdc76feb675900c97e30a5df776be3b71424ff93 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 08:55:54 +0000 Subject: [PATCH 49/81] Write the merged index through a unique temporary file An input named .tmp was truncated when the merge opened its temporary output, and removed on an error. Create the temporary beside the output with exclusive creation under a fresh name, then replace the output once the write succeeds. Assisted-by: Claude Code Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 9 ++++++--- tests/unit/test_scip_merge_indexes.py | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 485c01142ba..bd3f7cf12ea 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -29,6 +29,7 @@ import argparse import importlib.util import os +import tempfile from pathlib import Path from typing import Any, BinaryIO @@ -147,10 +148,12 @@ def merge_indexes( has_payload = True # The parts stay mapped while the output is written, so write beside the # output and swap it in; truncating an input that is also the output would - # pull the mapped pages away. - tmp = output.with_name(output.name + ".tmp") + # pull the mapped pages away. The temporary is created exclusively under a + # fresh name, so it can never be one of the inputs. + fd, tmp_name = tempfile.mkstemp(dir=output.parent, prefix=output.name + ".", suffix=".tmp") + tmp = Path(tmp_name) try: - with open(tmp, "wb") as out: + with os.fdopen(fd, "wb") as out: if has_payload: for payload in metadata: _write_record(out, _METADATA, payload) diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 360416d6ff4..a28a229e618 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -722,3 +722,25 @@ def test_merge_returns_the_kept_paths_as_text(tmp_path: Path) -> None: kept = _MOD.merge_indexes([plain, odd], out) assert kept == {"pkg/a.ts", "pkg/b\ufffd.ts"} assert all(isinstance(path, str) for path in kept) + + +def test_merge_does_not_truncate_an_input_named_like_the_temporary(tmp_path: Path) -> None: + first = tmp_path / "result.scip.tmp" + second = tmp_path / "second.scip" + first.write_bytes(_index_with_docs(["packages/app/src/a.ts"])) + second.write_bytes(_index_with_docs(["packages/lib/src/b.ts"])) + before = first.read_bytes() + out = tmp_path / "result.scip" + _MOD.merge_indexes([first, second], out) + assert first.read_bytes() == before + merged = _scip_pb2().Index() + merged.ParseFromString(out.read_bytes()) + assert [d.relative_path for d in merged.documents] == [ + "packages/app/src/a.ts", + "packages/lib/src/b.ts", + ] + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "result.scip", + "result.scip.tmp", + "second.scip", + ] From c3ae722479fe8435d2766bb9b45a0654ee6dc4a5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 11:00:21 +0000 Subject: [PATCH 50/81] Retire a stale mark once a later apply of the file is published The previous build writes no marks, so its refresh of a marked file left the mark counting until this build applied the file again. For Python, TypeScript and Go that wait had no bound when the file never changed. Every compiler-tier pass now runs retire_published_marks for each entry before its own work. A mark is emptied when the file holds a compiler-tier row written after the mark and the tier's watermark holds another blob of the file than the mark's commit. A Go tier that owes a module retry, and a mirror that cannot answer, keep their marks. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 32 ++++-- server/code/app/index/compiler_tier.py | 24 +++- server/code/app/index/gitrepo.py | 19 ++++ server/code/app/index/scip_delta.py | 46 ++++++++ server/code/store/index/symbols.py | 53 +++++++-- .../integration/test_code_scip_stale_mark.py | 107 +++++++++++++++++- 6 files changed, 257 insertions(+), 24 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 375d9c990aa..ffaeaf84d2c 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1028,18 +1028,26 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline would move the watermark back). A compiler-tier worker applies the delta its own build's harness wrote. In `tests/unit/test_code_scip_skipped_documents.py`, a converted upload with a skipped document fails under a worker that applies version 1 - only and applies with its mark under N's. Only N's apply of a marked file empties its - mark, once every round of that apply has landed. N-1 neither reads nor empties a - mark. A round writes its symbols and its edges in separate inserts, so N-1's rows of - the file and its watermark writes cannot show that its apply of the file completed, - and N keeps counting the mark: after N-1 refreshes the file, and after an N-1 retry - whose edge insert failed followed by an N-1 watermark write over a window with no - change, the file reads stale and constructor coverage incomplete until N applies the - file again, by a delta that changes it or, for C++, by N's weekly full run. The - Python, TypeScript and Go tiers have no weekly full run, so for them the wait has no - upper bound: only a delta that changes the file ends it, and a file that never - changes reads stale until it does. A rollback and a roll forward do the same. A - marked file that N-1 deletes is never applied by N again, so N's next apply of the + only and applies with its mark under N's. N-1 neither reads nor empties a mark. A + round writes its symbols and its edges in separate inserts, so N-1's rows of the file + alone cannot show that its apply of the file completed, and a read keeps counting the + mark: after N-1 refreshes the file, and after an N-1 retry whose edge insert failed + followed by an N-1 watermark write over a window with no change, the file reads stale + and constructor coverage incomplete. N empties the mark when it applies the file, + once every round of that apply has landed, or in its worker's next pass of the tier, + which runs for every entry the tier owns, current or not, once N-1's apply is + published (`retire_published_marks` in `server/code/app/index/scip_delta.py`): the + file holds a compiler-tier row written after the mark, and the tier's watermark holds + another blob of the file than the mark's commit in the entry's mirror. Each build + moves a watermark only after a whole apply of the window from the one before, and + N-1 fails a run on a document it cannot read, so that watermark is a completed apply + of the file's current content. A file that never changes again therefore reads fresh + after one pass of N. A watermark written over a window with no change of the file + still holds the mark's blob, so the failed retry above keeps its mark until N applies + the file. The Go tier keeps its marks while it owes a module retry + (`scip_commit_go_retry`), since its watermark passed a module that did not build, and + a mirror that cannot answer keeps every mark. A rollback and a roll forward do the + same. A marked file that N-1 deletes is never applied by N again, so N's next apply of the tier empties its mark when the entry's mirror holds the delta's commit and the commit has no blob at that path; a mirror that cannot be read, or lacks the commit, keeps the mark. diff --git a/server/code/app/index/compiler_tier.py b/server/code/app/index/compiler_tier.py index 005c73ed02f..d430c8d2cf7 100644 --- a/server/code/app/index/compiler_tier.py +++ b/server/code/app/index/compiler_tier.py @@ -102,7 +102,9 @@ async def run_tier[R: TierResult]( `health_tier` record (default: `producer`; `tier_health.record`): a failure, or a success unless `run_repo` returned False (it attempted nothing: the entry was not due) or added a skip. An entry the tier does not own drops its record - (`tier_health.forget`).""" + (`tier_health.forget`). Before `run_repo`, even for an entry already current, the + stale marks an earlier apply has since published are emptied + (`retire_published_marks`).""" from server.code.domain.index.repos import configured_repos from server.code.store.index import CodeRepo @@ -114,7 +116,8 @@ async def run_entry(repo: CodeRepo, cfg: RepoConfig) -> None: # The watermark reset is one of the entry's writes: under its lock too. skips = len(result.skipped) try: - ran = await run_repo(repo, cfg, result) is not False # False: leave the record + # False: leave the record + ran = await _attempt(repo, cfg, result, run_repo, producer, watermark) except BaseUnknown as e: # Not a failure to report: the next run indexes in full. await restart_full(repo, cfg, watermark, e, result.errors) @@ -166,6 +169,23 @@ async def run_entry(repo: CodeRepo, cfg: RepoConfig) -> None: return result +async def _attempt[R: TierResult]( + repo: CodeRepo, + cfg: RepoConfig, + result: R, + run_repo: Callable[[CodeRepo, RepoConfig, R], Awaitable[bool | None]], + producer: str, + watermark: str, +) -> bool: + """One entry's work, once the tier's stale marks an earlier apply has since + published are emptied (`retire_published_marks`): False when `run_repo` attempted + nothing.""" + from server.code.app.index.scip_delta import retire_published_marks + + await retire_published_marks(repo, cfg.org, cfg.namespace, producer, watermark) + return await run_repo(repo, cfg, result) is not False + + async def _gc_checkout(cfg: RepoConfig, producer: str) -> None: import asyncio diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index 58d4a59f369..4dda5599eb4 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -1344,3 +1344,22 @@ async def blob_paths_at( raise GitError(f"git cat-file answered {len(lines)} lines for {len(wanted)} paths") return set() return {path for path, kind in zip(wanted, lines, strict=True) if kind == "blob"} + + +async def blob_ids(git_dir: str, pairs: list[tuple[str, str]]) -> list[str]: + """The blob id of each `(revision, path)`, in order, with no blob reads: "" where the + revision holds no blob at the path or the mirror lacks the revision. One `cat-file + --batch-check`; a reply short of the request raises GitError.""" + if not pairs: + return [] + if any("\n" in path or "\r" in path for _, path in pairs): + raise GitError("a path with a line break cannot be asked of cat-file") + payload = "".join(f"{_rev(rev)}:{path}\n" for rev, path in pairs).encode() + out = await _git( + git_dir, "cat-file", "--batch-check=%(objecttype) %(objectname)", stdin=payload + ) + lines = out.splitlines() + if len(lines) != len(pairs): + raise GitError(f"git cat-file answered {len(lines)} lines for {len(pairs)} paths") + # a missing object reads `: missing`, never `blob ` + return [line[5:] if line.startswith("blob ") else "" for line in lines] diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 14802dde2f3..9b24eccb0a5 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -347,6 +347,52 @@ async def _mark_stale( await repo.set_states(org, ns, rows) +async def retire_published_marks( + repo: Any, org: str, ns: str, tier: str, watermark: str +) -> set[str]: + """Empty `tier`'s marks whose file an apply has published since the mark, and return + their paths. The previous build writes no marks, so its refresh of a marked file + leaves the mark counting; this is how such a mark ends when the file never changes + again. A file is published when it holds a compiler-tier row written after the mark + and the tier's `watermark` holds another blob of it than the mark's commit. A build + moves the watermark only after a whole apply of the window from the one before, and + the previous build fails a run on a document it cannot read, so that watermark is a + completed apply of the file's current content. A tier that owes a retry + (`_retry`: a Go module that did not build, whose files the watermark + passed) keeps its marks, as does a read that fails.""" + try: + published = await _published(repo, org, ns, tier, watermark) + except Exception: # noqa: BLE001 — a failed read can only keep a mark + return set() + if published: + check_held() + await repo.set_states( + org, ns, {f"{SCIP_STALE_PREFIX}{tier}:{p}": "" for p in sorted(published)} + ) + return published + + +async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> set[str]: + """The marked paths `retire_published_marks` empties.""" + written = await repo.scip_marks_rewritten(org, ns, tier) + target = str(await repo.get_state(org, ns, watermark) or "") if written else "" + if not target or await repo.get_state(org, ns, f"{watermark}_retry"): + return set() + from server.code.app.index import gitrepo + from server.code.domain.index.repos import repo_for_namespace + + cfg = repo_for_namespace(org, ns) + if cfg is None or not cfg.git_dir or not await gitrepo.has_commit(cfg.git_dir, target): + return set() + paths = sorted(p for p, at in written.items() if at != target) + blobs = await gitrepo.blob_ids( + cfg.git_dir, [(written[p], p) for p in paths] + [(target, p) for p in paths] + ) + marked, now = blobs[: len(paths)], blobs[len(paths) :] + # no blob at the mark's commit: a commit the mirror lacks, which proves nothing + return {p for p, was, is_ in zip(paths, marked, now, strict=True) if was and was != is_} + + async def _apply_files( repo: Any, org: str, ns: str, commit: str, files: list[ScipFile], stats: ScipApplyStats ) -> None: diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index d6c879ffe87..459d67d66a1 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -36,10 +36,11 @@ def _marks_in_force(keys: str) -> str: """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches - `keys`. Only an apply that writes marks empties one (`_mark_stale`), once every round - of it has landed. A round writes its symbols and its edges in separate inserts, so - the rows and the watermark write of a build that predates the marks cannot show that - its apply of the file completed: they leave the mark counting.""" + `keys`. Only a build that writes marks empties one: its apply of the file, once every + round of it has landed (`_mark_stale`), or its worker's pass once a later apply of + the file is published (`retire_published_marks`). A round writes its symbols and its + edges in separate inserts, so the rows of a build that predates the marks cannot + show alone that its apply of the file completed: a read leaves the mark counting.""" return f""" -- `scip_stale::`; a path may hold ':' itself SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path @@ -565,8 +566,8 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left - the rows of its earlier state, until this build applies the file again - (`_marks_in_force`).""" + the rows of its earlier state, until this build applies the file again or finds + a later apply of it published (`_marks_in_force`).""" if not paths: return set() asked = list(dict.fromkeys(paths))[:200] @@ -597,8 +598,9 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str async def scip_stale_marks(self, org: str, ns: str, tier: str | None = None) -> set[str]: """The paths `tier` (every tier when None) holds marked stale - (`SCIP_STALE_PREFIX`): its last delta for each skipped the file's document, and no - apply of the file by this build has completed since (`_marks_in_force`).""" + (`SCIP_STALE_PREFIX`): its last delta for each skipped the file's document, and + this build has neither completed an apply of the file since nor found a later + apply of it published (`_marks_in_force`).""" prefix = f"{SCIP_STALE_PREFIX}{tier}:" if tier else SCIP_STALE_PREFIX rows = await self._ch.query_all( _marks_in_force("startsWith(state_key, {mark:String})"), @@ -620,6 +622,41 @@ async def scip_stale_sample( ) return {str(r["path"]) for r in rows} + async def scip_marks_rewritten(self, org: str, ns: str, tier: str) -> dict[str, str]: + """`tier`'s marks in force whose file holds a compiler-tier symbol or edge row + written after the mark, each path with the commit its mark holds: the marked files + an apply has written since, by either build (`retire_published_marks`).""" + rows = await self._ch.query_all( + """ + WITH marks AS ( + -- `scip_stale::`; a path may hold ':' itself + SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path, + state_value AS mark_commit, version AS marked + FROM loom.code_index_state FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND startsWith(state_key, {mark:String}) AND state_value != '' + ), + written AS ( + SELECT path, max(version) AS rewritten + FROM ( + SELECT path, version FROM loom.code_symbols + WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' + AND path IN (SELECT path FROM marks) + UNION ALL + SELECT path, version FROM loom.code_edges + WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' + AND path IN (SELECT path FROM marks) + ) + GROUP BY path + ) + SELECT marks.path AS path, marks.mark_commit AS mark_commit + FROM marks INNER JOIN written ON written.path = marks.path + WHERE written.rewritten > marks.marked + """, + {"org": org, "ns": ns, "mark": f"{SCIP_STALE_PREFIX}{tier}:"}, + ) + return {str(r["path"]): str(r["mark_commit"]) for r in rows} + async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: one namespace-wide distinct read, taken once per full compiler run so diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index d5cd8107d97..9e6256ba2eb 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -1,6 +1,7 @@ """A file whose compiler-tier document a delta skipped reads as stale, although the tier's watermark moved past the file's last change, until a later delta of this build -applies it. The marks stay out of the whole-namespace state reads.""" +applies it or a pass of this build's worker finds a later apply of it published. The +marks stay out of the whole-namespace state reads.""" from __future__ import annotations @@ -10,10 +11,11 @@ from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any +from unittest.mock import AsyncMock import pytest -from server.code.app.index import scip_delta, scip_full +from server.code.app.index import compiler_tier, scip_delta, scip_full from server.code.app.index.scip_delta import ( ScipDelta, ScipEdge, @@ -24,7 +26,9 @@ from server.code.app.symbol.coverage import _ctor_edge_coverage from server.code.store.index import CodeRepo from server.code.workers import scip_delta as delta_worker +from server.code.workers import scip_py_delta from server.core.ch import get_client +from server.workers import pass_context from tests.integration._resources import unique_org from tests.unit.code_fixtures import repo_config @@ -476,3 +480,102 @@ async def test_the_bounded_mark_read_stops_at_its_limit_and_skips_a_cleared_mark assert await repo.scip_stale_sample(org, ns) == {marked[5]} await repo.set_states(org, ns, {f"scip_stale:clang:{marked[5]}": ""}) assert await repo.scip_stale_sample(org, ns) == set() + + +PY_BAD = "src/bad.py" +PY_OTHER = "src/other.py" + + +def _py_mirror(tmp_path: Path) -> tuple[str, str, str]: + """A git dir whose first commit holds `PY_BAD` and `PY_OTHER` and whose second + changes `PY_BAD` alone: (git dir, first commit, second commit).""" + work = tmp_path / "py-mirror" + (work / "src").mkdir(parents=True) + + def git(*args: str) -> str: + done = subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], + cwd=work, + check=True, + capture_output=True, + text=True, + ) + return done.stdout.strip() + + git("init", "-q") + (work / PY_BAD).write_text("x = 1\n") + (work / PY_OTHER).write_text("y = 1\n") + git("add", ".") + git("commit", "-q", "-m", "one") + first = git("rev-parse", "HEAD") + (work / PY_BAD).write_text("x = 2\n") + git("commit", "-q", "-am", "two") + return str(work / ".git"), first, git("rev-parse", "HEAD") + + +def _py_file(path: str) -> ScipFile: + return ScipFile( + path=path, + symbols=[ScipSymbol(qualified_name=f"{path}:f", line_start=1)], + edges=[ScipEdge(from_qualified_name=f"{path}:f", to_qualified_name="g", line=1)], + ) + + +async def _python_pass(cfg: Any, monkeypatch: pytest.MonkeyPatch) -> None: + """One pass of this build's Python worker over an entry with nothing to index.""" + + async def current(*a: Any) -> bool: + return False + + async def no_gc(*a: Any) -> None: + return None + + monkeypatch.setattr("server.code.domain.index.repos.configured_repos", lambda: [cfg]) + monkeypatch.setattr(compiler_tier, "worker_owns", AsyncMock(return_value=True)) + monkeypatch.setattr(compiler_tier, "_gc_checkout", no_gc) + monkeypatch.setattr(scip_py_delta, "_run_repo", current) + pass_context.begin("code_scip_py_delta") + try: + result = await scip_py_delta.run_pass() + finally: + pass_context.clear() + assert result.repos_checked == 1 and not result.errors and not result.skipped + + +@pytest.mark.asyncio +async def test_a_pass_of_this_build_retires_a_mark_the_previous_build_published( + ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Rollout order on a tier with no weekly full run: this build marks two skipped + Python files. The previous build applies the next commit, which changes `PY_BAD`, + and moves the watermark; `PY_BAD` never changes again. An apply whose edge insert + fails also writes `PY_OTHER`'s symbols, and `PY_OTHER` is the same at both commits. + The next pass of this build's Python worker, with nothing to index, empties the mark + of `PY_BAD`, which the watermark holds published, and keeps the other.""" + org, ns = unique_org("scip-stale-retire"), "code-stale-retire" + git_dir, first, second = _py_mirror(tmp_path) + cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) + monkeypatch.setattr("server.code.domain.index.repos.repo_for_namespace", lambda o, n: cfg) + repo = await _repo(ch_client, org, ns, [PY_BAD, PY_OTHER]) + skip = ScipDelta(commit=first, skipped_files=[PY_BAD, PY_OTHER]) + await apply_delta(repo, org, ns, skip, tier="python") + await repo.set_state(org, ns, "scip_commit_py", first) + + async def no_marks(*a: Any) -> None: + return None + + with monkeypatch.context() as previous_build: + previous_build.setattr(scip_delta, "_mark_stale", no_marks) + refresh = ScipDelta(commit=second, files=[_py_file(PY_BAD)]) + await apply_delta(repo, org, ns, refresh, tier="python") + _fail_edges(repo, previous_build) + with pytest.raises(ConnectionError): + failed = ScipDelta(commit=second, files=[_py_file(PY_OTHER)]) + await apply_delta(repo, org, ns, failed, tier="python") + assert (await repo.live_symbols_for_paths(org, ns, [PY_OTHER], "scip")).get(PY_OTHER) + await repo.set_state(org, ns, "scip_commit_py", second) + assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD, PY_OTHER} + + await _python_pass(cfg, monkeypatch) + assert await repo.scip_stale_marks(org, ns, "python") == {PY_OTHER} + assert await repo.scip_stale_paths(org, ns, [PY_BAD, PY_OTHER]) == {PY_OTHER} From b792baa8bbf84258d86053753fbde5ddad9f35cd Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 11:27:42 +0000 Subject: [PATCH 51/81] Scope the stale-mark recovery to the entries a tier worker runs The pass that retires a published mark runs only for an entry whose tier this build's worker owns and whose mirror holds the commits. A namespace fed by uploads alone, applied by code_scip_apply, has no mirror to prove the refresh with and keeps its mark until this build applies the file. Rule 69 and the docstrings of the pass, the mark reads and the integration test said otherwise. Say so, and drop the claim that a file that never changes again reads fresh in every namespace. Also name the two limits of the proof: a Go module that could not be fetched is passed without a retry, and a mirror that lacks one mark's commit keeps only that mark, while one that lacks the watermark's commit keeps all. Text only. Assisted-by: Claude Code:claude-sonnet-5-5 Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 41 +++++++++++-------- server/code/app/index/scip_delta.py | 20 +++++---- server/code/store/index/symbols.py | 20 +++++---- .../integration/test_code_scip_stale_mark.py | 5 ++- 4 files changed, 49 insertions(+), 37 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index ffaeaf84d2c..0c83eda4bc3 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1033,24 +1033,29 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline alone cannot show that its apply of the file completed, and a read keeps counting the mark: after N-1 refreshes the file, and after an N-1 retry whose edge insert failed followed by an N-1 watermark write over a window with no change, the file reads stale - and constructor coverage incomplete. N empties the mark when it applies the file, - once every round of that apply has landed, or in its worker's next pass of the tier, - which runs for every entry the tier owns, current or not, once N-1's apply is - published (`retire_published_marks` in `server/code/app/index/scip_delta.py`): the - file holds a compiler-tier row written after the mark, and the tier's watermark holds - another blob of the file than the mark's commit in the entry's mirror. Each build - moves a watermark only after a whole apply of the window from the one before, and - N-1 fails a run on a document it cannot read, so that watermark is a completed apply - of the file's current content. A file that never changes again therefore reads fresh - after one pass of N. A watermark written over a window with no change of the file - still holds the mark's blob, so the failed retry above keeps its mark until N applies - the file. The Go tier keeps its marks while it owes a module retry - (`scip_commit_go_retry`), since its watermark passed a module that did not build, and - a mirror that cannot answer keeps every mark. A rollback and a roll forward do the - same. A marked file that N-1 deletes is never applied by N again, so N's next apply of the - tier empties its mark when the entry's mirror holds the delta's commit and the - commit has no blob at that path; a mirror that cannot be read, or lacks the commit, - keeps the mark. + and constructor coverage incomplete. N empties the mark when it applies the file, once + every round of that apply has landed. For an entry whose tier this build's worker runs + and whose mirror holds both commits, its next pass of the tier also empties the mark, + current entry or not, once N-1's apply is published (`retire_published_marks` in + `server/code/app/index/scip_delta.py`): the file holds a compiler-tier row written after + the mark, and the tier's watermark holds another blob of the file than the mark's commit + in the entry's mirror. The Python, TypeScript and C++ tiers move a watermark only after + a whole apply of the window from the one before, and N-1 fails a run on a document it + cannot read, so that watermark is a completed apply of the file's current content, and + for such an entry a file that never changes again reads fresh after one pass of N. A + namespace whose compiler tier arrives by upload alone has no mirror to prove the refresh + with: `code_scip_apply` (`server/code/workers/scip_apply.py`) writes its marks and moves + its watermark but never runs the pass, so that namespace keeps the mark until N applies + the file. A watermark written over a window with no change of the file still holds the + mark's blob, so the failed retry above keeps its mark until N applies the file. The Go + tier keeps its marks while it owes a module retry (`scip_commit_go_retry`); a module it + could not fetch is passed without one, so only a partly failed apply before it could + empty a mark wrongly. A mirror that lacks the watermark's commit, or a read that fails, + keeps every mark; one that lacks a mark's commit keeps that mark. A rollback and a roll + forward do the same. A marked file that N-1 deletes is never applied by N again, so N's + next apply of the tier empties its mark when the entry's mirror holds the delta's commit + and the commit has no blob at that path; a mirror that cannot be read, or lacks the + commit, keeps the mark. `tests/integration/test_code_scip_stale_mark.py` applies these orders. A kept delta file (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI applies a retained version-2 file as version 1, so a skipped file's partial entry diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 9b24eccb0a5..7552fc94fe9 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -351,15 +351,19 @@ async def retire_published_marks( repo: Any, org: str, ns: str, tier: str, watermark: str ) -> set[str]: """Empty `tier`'s marks whose file an apply has published since the mark, and return - their paths. The previous build writes no marks, so its refresh of a marked file - leaves the mark counting; this is how such a mark ends when the file never changes - again. A file is published when it holds a compiler-tier row written after the mark - and the tier's `watermark` holds another blob of it than the mark's commit. A build - moves the watermark only after a whole apply of the window from the one before, and - the previous build fails a run on a document it cannot read, so that watermark is a + their paths. The previous build writes no marks, so its refresh of a marked file leaves + the mark counting; for an entry whose tier this build's worker runs, this is how such a + mark ends when the file never changes again. `code_scip_apply` never calls it, so a + namespace fed by uploads alone keeps the mark until this build applies the file. A file is + published when it holds a compiler-tier row written after the mark and the tier's + `watermark` holds another blob of it than the mark's commit. The Python, TypeScript and + C++ tiers move the watermark only after a whole apply of the window from the one before, + and the previous build fails a run on a document it cannot read, so that watermark is a completed apply of the file's current content. A tier that owes a retry - (`_retry`: a Go module that did not build, whose files the watermark - passed) keeps its marks, as does a read that fails.""" + (`_retry`: a Go module that did not build, whose files the watermark passed) + keeps its marks, as does a read that fails; a Go module that could not be fetched is + passed without a retry. A mirror that lacks the watermark's commit keeps every mark, one + that lacks a mark's commit that mark.""" try: published = await _published(repo, org, ns, tier, watermark) except Exception: # noqa: BLE001 — a failed read can only keep a mark diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 459d67d66a1..94caca5382f 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -37,10 +37,11 @@ def _marks_in_force(keys: str) -> str: """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches `keys`. Only a build that writes marks empties one: its apply of the file, once every - round of it has landed (`_mark_stale`), or its worker's pass once a later apply of - the file is published (`retire_published_marks`). A round writes its symbols and its - edges in separate inserts, so the rows of a build that predates the marks cannot - show alone that its apply of the file completed: a read leaves the mark counting.""" + round of it has landed (`_mark_stale`), or, for an entry whose tier its worker runs, that + worker's pass once a later apply of the file is published (`retire_published_marks`); a + namespace fed by uploads alone has no such pass. A round writes its symbols and its edges + in separate inserts, so the rows of a build that predates the marks cannot show alone that + its apply of the file completed: a read leaves the mark counting.""" return f""" -- `scip_stale::`; a path may hold ':' itself SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path @@ -566,8 +567,9 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str writes a file row when the file's bytes change, so a row newer than the watermark is content the compiler tier has not seen; a deleted or unknown file is a tree the compiler tier's rows no longer describe; a skipped document left - the rows of its earlier state, until this build applies the file again or finds - a later apply of it published (`_marks_in_force`).""" + the rows of its earlier state, until this build applies the file again or, for an + entry whose tier its worker runs, that worker's pass finds a later apply of it + published (`_marks_in_force`).""" if not paths: return set() asked = list(dict.fromkeys(paths))[:200] @@ -598,9 +600,9 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str async def scip_stale_marks(self, org: str, ns: str, tier: str | None = None) -> set[str]: """The paths `tier` (every tier when None) holds marked stale - (`SCIP_STALE_PREFIX`): its last delta for each skipped the file's document, and - this build has neither completed an apply of the file since nor found a later - apply of it published (`_marks_in_force`).""" + (`SCIP_STALE_PREFIX`): its last delta for each skipped the file's document, and this + build has neither completed an apply of the file since nor, for an entry whose tier + its worker runs, found a later apply of it published (`_marks_in_force`).""" prefix = f"{SCIP_STALE_PREFIX}{tier}:" if tier else SCIP_STALE_PREFIX rows = await self._ch.query_all( _marks_in_force("startsWith(state_key, {mark:String})"), diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 9e6256ba2eb..bf07740eebd 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -1,7 +1,8 @@ """A file whose compiler-tier document a delta skipped reads as stale, although the tier's watermark moved past the file's last change, until a later delta of this build -applies it or a pass of this build's worker finds a later apply of it published. The -marks stay out of the whole-namespace state reads.""" +applies it or, for an entry whose tier this build's worker runs, a pass of that worker +finds a later apply of it published. The marks stay out of the whole-namespace state +reads.""" from __future__ import annotations From b914189708c486e637ad0e39bc5dc167ae97f217 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 13:05:25 +0000 Subject: [PATCH 52/81] Retire a published mark by its blob, and keep it past a failed upload The recovery pass asked for a compiler-tier row of the marked file written after the mark. An apply of the previous build that changes a function body alone rewrites no row of the file, so its refresh kept the mark although the watermark had moved past the change. The Python, TypeScript and C++ workers move the watermark only after a whole apply of the window, so a watermark that holds another blob of the file than the mark's commit is enough on its own. An upload batch whose apply fails is recorded failed and leaves the watermark; a later batch moves it without applying the failed batch's files. The pass now keeps every mark older than the namespace's newest failed batch, so such a file stays stale until this build applies it. The Go worker passes a module it could not fetch without a retry, so a Go mark still needs a row of the file written after it. Signed-off-by: Kaloyan Naumov Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- docs/architecture/rolling-upgrades.md | 34 ++--- server/code/app/index/scip_delta.py | 24 ++-- server/code/store/index/symbols.py | 28 +++-- .../integration/test_code_scip_stale_mark.py | 118 +++++++++++++++++- 4 files changed, 167 insertions(+), 37 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 0c83eda4bc3..626f494adff 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1037,21 +1037,27 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline every round of that apply has landed. For an entry whose tier this build's worker runs and whose mirror holds both commits, its next pass of the tier also empties the mark, current entry or not, once N-1's apply is published (`retire_published_marks` in - `server/code/app/index/scip_delta.py`): the file holds a compiler-tier row written after - the mark, and the tier's watermark holds another blob of the file than the mark's commit - in the entry's mirror. The Python, TypeScript and C++ tiers move a watermark only after - a whole apply of the window from the one before, and N-1 fails a run on a document it - cannot read, so that watermark is a completed apply of the file's current content, and - for such an entry a file that never changes again reads fresh after one pass of N. A - namespace whose compiler tier arrives by upload alone has no mirror to prove the refresh - with: `code_scip_apply` (`server/code/workers/scip_apply.py`) writes its marks and moves - its watermark but never runs the pass, so that namespace keeps the mark until N applies - the file. A watermark written over a window with no change of the file still holds the + `server/code/app/index/scip_delta.py`): the tier's watermark holds another blob of the + file than the mark's commit in the entry's mirror. The Python, TypeScript and C++ + workers move a watermark only after a whole apply of the window from the one before, + and N-1 fails a run on a document it cannot read, so that watermark is a completed apply + of the file's current content, whether or not the apply rewrote a row of the file (a + change to a function body alone rewrites none). For such an entry a file that never + changes again reads fresh after one pass of N. An upload batch whose apply fails is + recorded `failed` and leaves the watermark, and a later batch moves it without applying + the failed one's files, so the pass keeps every mark older than the namespace's newest + failed batch until N applies the file; batch records expire after 30 days. A namespace + whose compiler tier arrives by upload alone has no mirror to prove the refresh with: + `code_scip_apply` (`server/code/workers/scip_apply.py`) writes its marks and moves its + watermark but never runs the pass, so that namespace keeps the mark until N applies the + file. A watermark written over a window with no change of the file still holds the mark's blob, so the failed retry above keeps its mark until N applies the file. The Go - tier keeps its marks while it owes a module retry (`scip_commit_go_retry`); a module it - could not fetch is passed without one, so only a partly failed apply before it could - empty a mark wrongly. A mirror that lacks the watermark's commit, or a read that fails, - keeps every mark; one that lacks a mark's commit keeps that mark. A rollback and a roll + worker passes a module it could not fetch without a retry, so for the Go tier the pass + also needs a compiler-tier row of the file written after the mark, and an N-1 refresh + that rewrites no row keeps the mark until N applies the file. The Go tier keeps its + marks while it owes a module retry (`scip_commit_go_retry`). A mirror that lacks the + watermark's commit, or a read that fails, keeps every mark; one that lacks a mark's + commit keeps that mark. A rollback and a roll forward do the same. A marked file that N-1 deletes is never applied by N again, so N's next apply of the tier empties its mark when the entry's mirror holds the delta's commit and the commit has no blob at that path; a mirror that cannot be read, or lacks the diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 7552fc94fe9..b635b23b020 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -355,15 +355,19 @@ async def retire_published_marks( the mark counting; for an entry whose tier this build's worker runs, this is how such a mark ends when the file never changes again. `code_scip_apply` never calls it, so a namespace fed by uploads alone keeps the mark until this build applies the file. A file is - published when it holds a compiler-tier row written after the mark and the tier's - `watermark` holds another blob of it than the mark's commit. The Python, TypeScript and - C++ tiers move the watermark only after a whole apply of the window from the one before, - and the previous build fails a run on a document it cannot read, so that watermark is a - completed apply of the file's current content. A tier that owes a retry - (`_retry`: a Go module that did not build, whose files the watermark passed) - keeps its marks, as does a read that fails; a Go module that could not be fetched is - passed without a retry. A mirror that lacks the watermark's commit keeps every mark, one - that lacks a mark's commit that mark.""" + published when the tier's `watermark` holds another blob of it than the mark's commit. + The Python, TypeScript and C++ workers move the watermark only after a whole apply of + the window from the one before, and the previous build fails a run on a document it + cannot read, so that watermark is a completed apply of the file's current content, + whether or not the apply rewrote a row of the file (a change to a function body alone + rewrites none). An upload batch whose apply fails leaves the watermark to the next + batch, which does not apply the failed one's files, so a mark older than a failed batch + of the namespace is kept (`scip_marks_retirable`). The Go worker passes a module it + could not fetch without a retry, so a Go mark also needs a compiler-tier row of the file + written after it. A tier that owes a retry (`_retry`: a Go module that did not + build, whose files the watermark passed) keeps its marks, as does a read that fails. A + mirror that lacks the watermark's commit keeps every mark, one that lacks a mark's commit + that mark.""" try: published = await _published(repo, org, ns, tier, watermark) except Exception: # noqa: BLE001 — a failed read can only keep a mark @@ -378,7 +382,7 @@ async def retire_published_marks( async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> set[str]: """The marked paths `retire_published_marks` empties.""" - written = await repo.scip_marks_rewritten(org, ns, tier) + written = await repo.scip_marks_retirable(org, ns, tier, rewritten=tier == "go") target = str(await repo.get_state(org, ns, watermark) or "") if written else "" if not target or await repo.get_state(org, ns, f"{watermark}_retry"): return set() diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 94caca5382f..da6a7295d36 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -624,10 +624,13 @@ async def scip_stale_sample( ) return {str(r["path"]) for r in rows} - async def scip_marks_rewritten(self, org: str, ns: str, tier: str) -> dict[str, str]: - """`tier`'s marks in force whose file holds a compiler-tier symbol or edge row - written after the mark, each path with the commit its mark holds: the marked files - an apply has written since, by either build (`retire_published_marks`).""" + async def scip_marks_retirable( + self, org: str, ns: str, tier: str, *, rewritten: bool + ) -> dict[str, str]: + """`tier`'s marks in force written after the namespace's newest failed upload batch + (`code_scip_apply`), each path with the commit its mark holds; with `rewritten`, only + those whose file holds a compiler-tier symbol or edge row written after the mark + (`retire_published_marks`).""" rows = await self._ch.query_all( """ WITH marks AS ( @@ -650,12 +653,23 @@ async def scip_marks_rewritten(self, org: str, ns: str, tier: str) -> dict[str, AND path IN (SELECT path FROM marks) ) GROUP BY path + ), + failed AS ( + -- 0 when no batch failed; a batch retried and applied since is no row here + SELECT max(version) AS at FROM loom.code_scip_batches FINAL + WHERE org = {org:String} AND namespace = {ns:String} AND status = 'failed' ) SELECT marks.path AS path, marks.mark_commit AS mark_commit - FROM marks INNER JOIN written ON written.path = marks.path - WHERE written.rewritten > marks.marked + FROM marks LEFT JOIN written ON written.path = marks.path + WHERE marks.marked > (SELECT at FROM failed) + AND ({rewritten:UInt8} = 0 OR written.rewritten > marks.marked) """, - {"org": org, "ns": ns, "mark": f"{SCIP_STALE_PREFIX}{tier}:"}, + { + "org": org, + "ns": ns, + "mark": f"{SCIP_STALE_PREFIX}{tier}:", + "rewritten": int(rewritten), + }, ) return {str(r["path"]): str(r["mark_commit"]) for r in rows} diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index bf07740eebd..0f6217de91c 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -9,6 +9,7 @@ import asyncio import json import subprocess +import uuid from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any @@ -26,8 +27,8 @@ ) from server.code.app.symbol.coverage import _ctor_edge_coverage from server.code.store.index import CodeRepo +from server.code.workers import scip_apply, scip_py_delta from server.code.workers import scip_delta as delta_worker -from server.code.workers import scip_py_delta from server.core.ch import get_client from server.workers import pass_context from tests.integration._resources import unique_org @@ -487,9 +488,9 @@ async def test_the_bounded_mark_read_stops_at_its_limit_and_skips_a_cleared_mark PY_OTHER = "src/other.py" -def _py_mirror(tmp_path: Path) -> tuple[str, str, str]: - """A git dir whose first commit holds `PY_BAD` and `PY_OTHER` and whose second - changes `PY_BAD` alone: (git dir, first commit, second commit).""" +def _py_mirror(tmp_path: Path) -> tuple[str, list[str]]: + """A git dir whose first commit holds `PY_BAD` and `PY_OTHER`, whose second changes + `PY_BAD` alone and whose third `PY_OTHER` alone: (git dir, the three commits).""" work = tmp_path / "py-mirror" (work / "src").mkdir(parents=True) @@ -511,7 +512,10 @@ def git(*args: str) -> str: first = git("rev-parse", "HEAD") (work / PY_BAD).write_text("x = 2\n") git("commit", "-q", "-am", "two") - return str(work / ".git"), first, git("rev-parse", "HEAD") + second = git("rev-parse", "HEAD") + (work / PY_OTHER).write_text("y = 2\n") + git("commit", "-q", "-am", "three") + return str(work / ".git"), [first, second, git("rev-parse", "HEAD")] def _py_file(path: str) -> ScipFile: @@ -554,7 +558,7 @@ async def test_a_pass_of_this_build_retires_a_mark_the_previous_build_published( The next pass of this build's Python worker, with nothing to index, empties the mark of `PY_BAD`, which the watermark holds published, and keeps the other.""" org, ns = unique_org("scip-stale-retire"), "code-stale-retire" - git_dir, first, second = _py_mirror(tmp_path) + git_dir, (first, second, _) = _py_mirror(tmp_path) cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) monkeypatch.setattr("server.code.domain.index.repos.repo_for_namespace", lambda o, n: cfg) repo = await _repo(ch_client, org, ns, [PY_BAD, PY_OTHER]) @@ -580,3 +584,105 @@ async def no_marks(*a: Any) -> None: await _python_pass(cfg, monkeypatch) assert await repo.scip_stale_marks(org, ns, "python") == {PY_OTHER} assert await repo.scip_stale_paths(org, ns, [PY_BAD, PY_OTHER]) == {PY_OTHER} + + +@pytest.mark.asyncio +async def test_a_pass_retires_a_mark_the_previous_build_published_without_rewriting_a_row( + ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """This build applies `PY_BAD`, then a delta of the same commit skips it. The + previous build applies the next commit, which changes a function body alone: the + file's symbols and edges are the rows it already holds, so the apply rewrites none, + and it moves the watermark. The next pass of this build's Python worker empties the + mark.""" + org, ns = unique_org("scip-stale-body"), "code-stale-body" + git_dir, (first, second, _) = _py_mirror(tmp_path) + cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) + monkeypatch.setattr("server.code.domain.index.repos.repo_for_namespace", lambda o, n: cfg) + repo = await _repo(ch_client, org, ns, [PY_BAD]) + await apply_delta( + repo, org, ns, ScipDelta(commit=first, files=[_py_file(PY_BAD)]), tier="python" + ) + await apply_delta(repo, org, ns, ScipDelta(commit=first, skipped_files=[PY_BAD]), tier="python") + await repo.set_state(org, ns, "scip_commit_py", first) + symbols = await repo.live_symbols_for_paths(org, ns, [PY_BAD], "scip") + edges = await repo.live_edges_for_paths(org, ns, [PY_BAD], "scip") + + async def no_marks(*a: Any) -> None: + return None + + with monkeypatch.context() as previous_build: + previous_build.setattr(scip_delta, "_mark_stale", no_marks) + body = ScipDelta(commit=second, files=[_py_file(PY_BAD)]) + await apply_delta(repo, org, ns, body, tier="python") + await repo.set_state(org, ns, "scip_commit_py", second) + assert await repo.live_symbols_for_paths(org, ns, [PY_BAD], "scip") == symbols + assert await repo.live_edges_for_paths(org, ns, [PY_BAD], "scip") == edges + assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD} + + await _python_pass(cfg, monkeypatch) + assert await repo.scip_stale_marks(org, ns, "python") == set() + assert await repo.scip_stale_paths(org, ns, [PY_BAD]) == set() + + +async def _upload(org: str, ns: str, base: str, delta: ScipDelta) -> None: + """One complete upload batch of `delta` from the Python producer.""" + repo, batch_id = CodeRepo(), str(uuid.uuid4()) + await repo.insert_scip_part(org, ns, batch_id, 0, delta.model_dump_json(), "") + await repo.upsert_scip_batch( + org, + ns, + batch_id, + commit_sha=delta.commit, + base_sha=base, + total_parts=1, + producer="scip-python", + ) + + +async def _apply_uploads() -> scip_apply.CodeScipApplyResult: + pass_context.begin("code_scip_apply") + try: + return await scip_apply.run_pass() + finally: + pass_context.clear() + + +@pytest.mark.asyncio +async def test_a_failed_upload_keeps_the_mark_past_a_later_batch_that_moves_the_watermark( + ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """An upload marks `PY_BAD` skipped. The next batch changes `PY_BAD`; its symbols + land and its edge insert fails, so `code_scip_apply` records it failed and leaves the + watermark. A later batch changes `PY_OTHER` alone and moves the watermark past the + change of `PY_BAD`, whose apply never completed: a pass of this build's Python worker + keeps the mark.""" + org, ns = unique_org("scip-stale-upload"), "code-stale-upload" + git_dir, (first, second, third) = _py_mirror(tmp_path) + cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) + monkeypatch.setattr("server.code.domain.index.repos.repo_for_namespace", lambda o, n: cfg) + repo = await _repo(ch_client, org, ns, [PY_BAD, PY_OTHER]) + await _upload(org, ns, "", ScipDelta(delta_version=2, commit=first, skipped_files=[PY_BAD])) + assert (await _apply_uploads()).batches_applied == 1 + assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD} + + await _upload(org, ns, first, ScipDelta(commit=second, files=[_py_file(PY_BAD)])) + insert_rows = CodeRepo.insert_rows + + async def edges_fail(self: CodeRepo, table: str, rows: list[dict[str, Any]]) -> None: + if table == "code_edges": + raise ConnectionError("edge insert failed") + await insert_rows(self, table, rows) + + with monkeypatch.context() as failing: + failing.setattr(CodeRepo, "insert_rows", edges_fail) + assert (await _apply_uploads()).batches_failed == 1 + assert (await repo.live_symbols_for_paths(org, ns, [PY_BAD], "scip")).get(PY_BAD) + assert await repo.get_state(org, ns, "scip_commit_py") == first + + await _upload(org, ns, second, ScipDelta(commit=third, files=[_py_file(PY_OTHER)])) + assert (await _apply_uploads()).batches_applied == 1 + assert await repo.get_state(org, ns, "scip_commit_py") == third + + await _python_pass(cfg, monkeypatch) + assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD} From 9b914b35e846073f793e134531bb09dee6d2ddd9 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 08:23:34 +0000 Subject: [PATCH 53/81] A path whose bytes are not UTF-8 keeps its key: the window lists every path and a deletion retires its rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `_document_path` decodes with `replace` again. Its only job is a key: ordering and pairing documents (`_stream_documents`) and naming a skip. Returning "" for every undecodable path collapsed a bad byte under `src/` and the same byte under `lib/` onto one key, where U+FFFD keeps them distinct, and it is the one string the store keys a document by. `git_paths` emits git's `-z` output, raw and NUL-separated, and no longer drops a path git still C-quotes (a name holding a tab, newline, quote or backslash). The second list is a `--diff-filter=D` list: a dropped path never reached `deleted.txt`, never became `deleted_files`, and the server — which reads a file the delta does not name as gone — never retired the rows of a file that vanished. `_path_list` (scip_to_delta) and `_read_lines` (scip_ts_projects) split on NUL only, decode with `replace`, and strip nothing, so a deletion names exactly the key the store holds. `scip_ts_projects` matches its member directories through the same `_key`, and prints the argv path back unchanged. The C++ and Go runners' shell consumers read the lists with `grep -z`, `sort -zu`, `read -d ''` and `path_count`, so no list is converted to newlines. Pinned by tests/unit/test_scip_path_encoding.py on a real git fixture: one file's path bytes go from UTF-8 to invalid and back across two commits; the old path is the delta's `deleted_files`, the new one is the `replace` key, and every path git reported is in a list. A full run now names an undecodable path by its replace key instead of failing; it still fails for a failed document with no path at all, which cannot be named. --- scripts/scip_harness/lib.sh | 33 ++- scripts/scip_harness/run_delta.sh | 36 ++-- scripts/scip_harness/run_go_monorepo_delta.sh | 7 +- scripts/scip_harness/scip_to_delta.py | 25 ++- scripts/scip_harness/scip_ts_projects.py | 24 ++- tests/unit/test_scip_path_encoding.py | 201 ++++++++++++++++++ tests/unit/test_scip_to_delta_cli.py | 3 +- tests/unit/test_scip_to_delta_skip.py | 38 +++- tests/unit/test_scip_ts_projects.py | 4 +- 9 files changed, 307 insertions(+), 64 deletions(-) create mode 100644 tests/unit/test_scip_path_encoding.py diff --git a/scripts/scip_harness/lib.sh b/scripts/scip_harness/lib.sh index 84408ea12f9..892a15133b3 100644 --- a/scripts/scip_harness/lib.sh +++ b/scripts/scip_harness/lib.sh @@ -52,35 +52,34 @@ require_base() { fi } -# git_paths : `git ` printing one path per line exactly as -# the tree names it (core.quotePath off, so a non-ASCII name is not C-quoted). -# A name git must still quote (a tab, newline, quote or backslash in it) cannot -# be carried by a line-per-path list; it is dropped with a warning instead of -# being passed on as a path that names nothing. +# git_paths : `git ` printing each path NUL-separated exactly as +# the tree names it (core.quotePath off, so a non-ASCII name is not C-quoted). NUL +# ends every name, so one holding a tab, a newline, a quote or a backslash is carried +# whole: a list never drops a path, and a deletion always names the row the store +# holds. Callers pass -z; the Python readers decode each name as UTF-8 with `replace`. git_paths() { - git -c core.quotePath=false "$@" | while IFS= read -r p; do - if [[ "$p" == \"* ]]; then - echo "scip harness: skipping a path git cannot print unquoted: $p" >&2 - else - printf '%s\n' "$p" - fi - done - return "${PIPESTATUS[0]}" + git -c core.quotePath=false "$@" +} + +# path_count : the number of NUL-terminated names a git_paths list holds. +path_count() { + grep -zc '' "$1" 2>/dev/null || true } # window_files [pathspec...]: the window's files in the # current directory's repository, as /changed.txt (everything but # deletions: what the index is read for) and /deleted.txt (deletions -# and a rename's old path: what the delta tombstones). Renames are split, so -# no old path hides inside a rename. Fails when git cannot diff the window. +# and a rename's old path: what the delta tombstones). Both are NUL-separated and +# hold every path git reported. Renames are split, so no old path hides inside a +# rename. Fails when git cannot diff the window. window_files() { local out=$1 base=$2 head=$3 shift 3 : >"$out/changed.txt" : >"$out/deleted.txt" - git_paths diff --name-only --no-renames --diff-filter=d --end-of-options "$base" "$head" -- "$@" \ + git_paths diff --name-only -z --no-renames --diff-filter=d --end-of-options "$base" "$head" -- "$@" \ >"$out/changed.txt" \ - && git_paths diff --name-only --no-renames --diff-filter=D --end-of-options "$base" "$head" -- "$@" \ + && git_paths diff --name-only -z --no-renames --diff-filter=D --end-of-options "$base" "$head" -- "$@" \ >"$out/deleted.txt" } diff --git a/scripts/scip_harness/run_delta.sh b/scripts/scip_harness/run_delta.sh index 6ad773314c0..8d8948dc1e1 100755 --- a/scripts/scip_harness/run_delta.sh +++ b/scripts/scip_harness/run_delta.sh @@ -101,54 +101,56 @@ if [[ "$BASE" == "--full" ]]; then reconfigure "full index" echo ">> full-index mode: whole compile_commands.json" cp build/compile_commands.json "$WORK/compdb.json" - git_paths ls-files 'src/*' 'base/*' 'programs/*' >"$WORK/changed.txt" + git_paths ls-files -z 'src/*' 'base/*' 'programs/*' >"$WORK/changed.txt" : >"$WORK/deleted.txt" else require_base "$BASE" window_files "$WORK" "$BASE" "$HEAD_SHA" # a window that adds a translation unit or edits the build changes what the # compile database must list - git_paths diff --name-only --no-renames --diff-filter=A --end-of-options "$BASE" "$HEAD_SHA" \ + git_paths diff --name-only -z --no-renames --diff-filter=A --end-of-options "$BASE" "$HEAD_SHA" \ >"$WORK/added.txt" - if grep -qE '\.(cpp|cc|cxx)$' "$WORK/added.txt" \ - || grep -qE '(^|/)CMakeLists\.txt$|\.cmake$' "$WORK/changed.txt" "$WORK/deleted.txt"; then + if grep -qzE '\.(cpp|cc|cxx)$' "$WORK/added.txt" \ + || grep -qzE '(^|/)CMakeLists\.txt$|\.cmake$' "$WORK/changed.txt" "$WORK/deleted.txt"; then reconfigure "the window adds a translation unit or edits the build" fi - grep -E '\.(cpp|cc|cxx)$' "$WORK/changed.txt" >"$WORK/tus.txt" || true + grep -zE '\.(cpp|cc|cxx)$' "$WORK/changed.txt" >"$WORK/tus.txt" || true # headers: every TU that includes them (text search on the checkout) # `|| true`: a window with no header changes is normal — under # pipefail a matchless grep otherwise kills the whole harness with a silent # "exit 1" whenever a merge window touches only .cpp files. - { grep -E '\.(h|hpp|inl|ipp)$' "$WORK/changed.txt" || true; } | while read -r hdr; do - base_hdr=$(basename "$hdr") - git_paths grep -l -F -e "$base_hdr" -- 'src/*.cpp' 'programs/*.cpp' 'base/*.cpp' || true - done | sort -u >>"$WORK/tus.txt" - sort -u "$WORK/tus.txt" -o "$WORK/tus.txt" + { grep -zE '\.(h|hpp|inl|ipp)$' "$WORK/changed.txt" || true; } \ + | while IFS= read -r -d '' hdr; do + base_hdr=$(basename "$hdr") + git_paths grep -lz -F -e "$base_hdr" -- 'src/*.cpp' 'programs/*.cpp' 'base/*.cpp' || true + done | sort -zu >>"$WORK/tus.txt" + sort -zu "$WORK/tus.txt" -o "$WORK/tus.txt" - N_TUS=$(wc -l <"$WORK/tus.txt") + N_TUS=$(path_count "$WORK/tus.txt") if ((N_TUS > MAX_TUS)); then echo ">> $N_TUS TUs exceed cap $MAX_TUS — degrading to changed .cpp only" >&2 - { grep -E '\.(cpp|cc|cxx)$' "$WORK/changed.txt" || true; } | sort -u >"$WORK/tus.txt" + { grep -zE '\.(cpp|cc|cxx)$' "$WORK/changed.txt" || true; } | sort -zu >"$WORK/tus.txt" echo ">> skipped header-driven TUs are healed by the next --full run" >&2 fi if [[ ! -s "$WORK/tus.txt" && ! -s "$WORK/deleted.txt" ]]; then echo ">> no C++ TUs changed — nothing to index" exit 0 fi - echo ">> $(wc -l <"$WORK/tus.txt") TUs to index" + echo ">> $(path_count "$WORK/tus.txt") TUs to index" # the delta carries the window's files and every TU re-read for them: an # includer of a changed header gets its edges refreshed too - sort -u "$WORK/changed.txt" "$WORK/tus.txt" -o "$WORK/changed.txt" + sort -zu "$WORK/changed.txt" "$WORK/tus.txt" -o "$WORK/changed.txt" # compile_commands.json carries ABSOLUTE paths; git paths are relative — # match on suffix (an exact match gave an empty compdb, and scip-clang # crashes on a <4-byte input file). N_COMPDB=$( "$PYTHON" - "$WORK/tus.txt" build/compile_commands.json "$WORK/compdb.json" <<'PYEOF' -import json, sys -want = tuple("/" + ln.strip() for ln in open(sys.argv[1]) if ln.strip()) +import json, os, sys +# the lists are NUL-separated and a name need not be UTF-8: compare the bytes +want = tuple(b"/" + name for name in open(sys.argv[1], "rb").read().split(b"\0") if name) with open(sys.argv[2]) as fh: - keep = [e for e in json.load(fh) if want and e["file"].endswith(want)] + keep = [e for e in json.load(fh) if want and os.fsencode(e["file"]).endswith(want)] with open(sys.argv[3], "w") as fh: json.dump(keep, fh) print(len(keep)) diff --git a/scripts/scip_harness/run_go_monorepo_delta.sh b/scripts/scip_harness/run_go_monorepo_delta.sh index 93505426186..95600809803 100755 --- a/scripts/scip_harness/run_go_monorepo_delta.sh +++ b/scripts/scip_harness/run_go_monorepo_delta.sh @@ -58,7 +58,8 @@ fi if [[ -n "${MODULES:-}" ]]; then mapfile -t DIRS <<<"$MODULES" else - mapfile -t DIRS < <(cd "$CHECKOUT" && git_paths ls-files -- '**/go.mod' 'go.mod' | while IFS= read -r m; do dirname -- "$m"; done | sort -u) + mapfile -t -d '' DIRS < <(cd "$CHECKOUT" && git_paths ls-files -z -- '**/go.mod' 'go.mod' \ + | while IFS= read -r -d '' m; do printf '%s\0' "$(dirname -- "$m")"; done | sort -zu) fi run_module() { @@ -68,7 +69,7 @@ run_module() { work=$(mktemp -d) trap 'rm -rf "$work"' RETURN local n - n=$(cd "$CHECKOUT/$dir" && git_paths ls-files -- '*.go' ':!:*/vendor/*' | wc -l) + n=$(cd "$CHECKOUT/$dir" && git_paths ls-files -z -- '*.go' ':!:*/vendor/*' | grep -zc '') if ((n < MIN_GO_FILES)); then echo "skip $dir ($n go files)" return 0 @@ -113,4 +114,4 @@ run_module() { } export -f run_module git_paths window_files convert_delta export CHECKOUT SCIP_GO PYTHON HARNESS_DIR HEAD_SHA BASE LOOM_BASE_URL ORG NS MIN_GO_FILES DELTA_OUT_DIR LOOM_API_KEY EXCLUDE_GENERATED -printf '%s\n' "${DIRS[@]}" | xargs -P "$JOBS" -I{} bash -c 'run_module "$@"' _ {} +printf '%s\0' "${DIRS[@]}" | xargs -0 -P "$JOBS" -I{} bash -c 'run_module "$@"' _ {} diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 785d0b2e970..0d8f8d3daf2 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -904,13 +904,13 @@ def _document_path_bytes(payload: bytes) -> bytes: def _document_path(payload) -> str: - """A serialized Document's relative_path (field 1) as text, its last value as the - protobuf parser takes it; "" when it is not UTF-8, which a run reads as a path it - cannot read.""" - try: - return _document_path_bytes(payload).decode("utf-8") - except (IndexError, ValueError): # UnicodeDecodeError is a ValueError - return "" + """The relative_path as text; a malformed byte reads as U+FFFD. + + This string is the key a document is ordered and paired by and the name a skip is + reported under, so it must stay distinct per path: an undecodable path decodes with + `replace` (the one decode policy of the harness, and the key the store holds), where + "" would collapse every such path onto one shared key.""" + return _document_path_bytes(payload).decode("utf-8", "replace") class _Skips: @@ -918,8 +918,8 @@ class _Skips: is not UTF-8, say) or one that fails to convert. Each is named once on stderr, the delta lists the named ones (`skipped_files`: the server keeps their rows and marks them stale) and counts all of them. With `stop` the failure fails the run instead. - So does one whose path cannot be read in a run over every document (`whole`): the - server reads a file such a delta does not name as gone and retires its rows.""" + So does one with no path at all in a run over every document (`whole`): the server + reads a file such a delta does not name as gone and retires its rows.""" def __init__(self, stop: bool = False, whole: bool = False) -> None: self.stop, self.whole = stop, whole @@ -1558,9 +1558,14 @@ def _strip_prefix(path: str, prefix: str) -> str: def _path_list(path: str | None) -> list[str]: + """A `git_paths` list: NUL-separated names, each decoded as UTF-8 with `replace` — + the policy `_document_path` keys a document by, so a deleted path names the row the + store holds even when its bytes are not UTF-8. A name may hold a newline, so the + list is split on NUL only, and nothing is stripped off its ends.""" if not path: return [] - return [ln.strip() for ln in Path(path).read_text().splitlines() if ln.strip()] + raw = Path(path).read_bytes() + return [name.decode("utf-8", "replace") for name in raw.split(b"\0") if name] def _summary(counts: dict) -> str: diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index 8c44ab47f0e..1000b60cd92 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -266,15 +266,19 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> return [] if any(is_shared_change(path) for path in changed_paths): return list(projects) + keys = {project: _key(project) for project in projects} selected = [ project for project in projects - if any(project_owns(project, path) and is_index_trigger(path) for path in changed_paths) + if any( + project_owns(keys[project], path) and is_index_trigger(path) for path in changed_paths + ) ] unowned_ts = [ path for path in changed_paths - if is_typescript_path(path) and not any(project_owns(project, path) for project in projects) + if is_typescript_path(path) + and not any(project_owns(keys[project], path) for project in projects) ] if unowned_ts and (selected or any(is_project_config_change(path) for path in changed_paths)): # The converter reads definition kinds from the members it is given, so a @@ -284,14 +288,20 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> return selected +def _key(path: str) -> str: + """A path as the store keys it: its bytes decoded as UTF-8 with `replace`, which is + what `scip_to_delta.py` keys a document by. A valid name is unchanged; a member + directory whose own name is not UTF-8 still matches the list entry for its files.""" + return path.encode("utf-8", "surrogateescape").decode("utf-8", "replace") + + def _read_lines(path: Path | None) -> list[str]: + """A `git_paths` list: NUL-separated names, each decoded as UTF-8 with `replace` + (the delta's one key), so a window entry names the document the store holds. A name + may hold a newline, so the list is split on NUL only and nothing is stripped.""" if path is None or not path.is_file(): return [] - # git_paths prints a name as the tree stores it, which need not be UTF-8. - # Decode it as argv is decoded, so it compares equal to a member path - # passed on the command line and is printed back unchanged. - text = os.fsdecode(path.read_bytes()) - return [line.strip() for line in text.splitlines() if line.strip()] + return [name.decode("utf-8", "replace") for name in path.read_bytes().split(b"\0") if name] def main(argv: list[str] | None = None) -> int: diff --git a/tests/unit/test_scip_path_encoding.py b/tests/unit/test_scip_path_encoding.py new file mode 100644 index 00000000000..6a2c03738db --- /dev/null +++ b/tests/unit/test_scip_path_encoding.py @@ -0,0 +1,201 @@ +"""A path whose bytes are not UTF-8 survives the window: `git_paths` lists every path +git reported, NUL-separated and undropped, the readers decode each one as UTF-8 with +`replace` — the key the store holds — and a file whose path bytes change between two +commits is retired under the old key. A real git repository; no ClickHouse. +""" + +from __future__ import annotations + +import importlib.util +import os +import subprocess +import sys +from pathlib import Path + +from tests.unit.test_scip_to_delta_cli import _CONVERTER, _add_doc, _fn, _pb + +_HARNESS = _CONVERTER.parent +_LIB = _HARNESS / "lib.sh" +_TS_PROJECTS = _HARNESS / "scip_ts_projects.py" + +_VALID = "src/café.ts" # UTF-8: 63 61 66 c3 a9 2e 74 73 +_VALID_BYTES = b"src/caf\xc3\xa9.ts" +_INVALID = b"src/caf\xe9.ts" # c3 a9 replaced by the single byte e9: not UTF-8 +_KEY = "src/caf\ufffd.ts" # what `replace` decoding makes of _INVALID + + +def _git(cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True + ).stdout.strip() + + +def _commit(repo: Path, msg: str) -> str: + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", msg) + return _git(repo, "rev-parse", "HEAD") + + +def _repo_at(tmp_path: Path, name: bytes) -> tuple[Path, str]: + """A repository whose one commit holds a file at `name` (raw bytes).""" + repo = tmp_path / "repo" + (repo / "src").mkdir(parents=True) + with open(os.fsencode(repo) + b"/" + name, "wb") as fh: + fh.write(b"export const a = 1;\n") + _git(tmp_path, "init", "-q", str(repo)) + return repo, _commit(repo, "init") + + +def _move(repo: Path, old: bytes, new: bytes) -> None: + os.rename(os.fsencode(repo) + b"/" + old, os.fsencode(repo) + b"/" + new) + + +def _split(path: Path) -> list[bytes]: + return [name for name in path.read_bytes().split(b"\0") if name] + + +def _window(repo: Path, base: str, head: str, out: Path) -> tuple[list[bytes], list[bytes]]: + """`window_files` over a real repository: the two lists as raw names.""" + out.mkdir(parents=True) + script = ( + "set -euo pipefail\n" + f'cd "{repo}"\n' + f'source "{_LIB}"\n' + f'window_files "{out}" "{base}" "{head}" "*.ts"\n' + ) + env = {**os.environ, "PYTHON": sys.executable} + proc = subprocess.run(["bash", "-c", script], capture_output=True, text=True, env=env) + assert proc.returncode == 0, proc.stderr + return _split(out / "changed.txt"), _split(out / "deleted.txt") + + +def _gits_own(repo: Path, base: str, head: str, diff_filter: str) -> list[bytes]: + """git's own list for the same window, NUL-separated: what nothing may be missing from.""" + raw = subprocess.run( + [ + "git", + "-C", + str(repo), + "-c", + "core.quotePath=false", + "diff", + "--name-only", + "-z", + "--no-renames", + f"--diff-filter={diff_filter}", + "--end-of-options", + base, + head, + "--", + ], + check=True, + capture_output=True, + ).stdout + return [name for name in raw.split(b"\0") if name] + + +def _converter(): + spec = importlib.util.spec_from_file_location("scip_to_delta_encoding", _CONVERTER) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _ts_projects(): + spec = importlib.util.spec_from_file_location("scip_ts_projects_encoding", _TS_PROJECTS) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _index(tmp_path: Path) -> Path: + """An index holding src/café.ts and a document whose path is the raw _INVALID bytes + (`src/cafX.ts` is the same length as _INVALID, so every length prefix still holds + and python-protobuf refuses the path).""" + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///nonexistent-checkout" + _add_doc(index, _VALID, [(_fn("f", "aa"), 0)], []) + _add_doc(index, "src/cafX.ts", [(_fn("g", "bb"), 0)], []) + raw = index.SerializeToString() + assert raw.count(b"src/cafX.ts") == 1 + path = tmp_path / "index.scip" + path.write_bytes(raw.replace(b"src/cafX.ts", _INVALID)) + return path + + +def test_a_path_that_stops_being_utf8_is_retired_under_its_old_key(tmp_path: Path) -> None: + """The window lists the new raw path and the old one, nothing dropped; the old path + is the delta's `deleted_files` (the server retires those rows), and the new one is + keyed by the `replace` decoding, the same key the store holds for it.""" + repo, base = _repo_at(tmp_path, _VALID_BYTES) + _move(repo, _VALID_BYTES, _INVALID) + head = _commit(repo, "rename the file to a name whose bytes are not UTF-8") + + changed, deleted = _window(repo, base, head, tmp_path / "work") + assert changed == _gits_own(repo, base, head, "d") == [_INVALID] + assert deleted == _gits_own(repo, base, head, "D") == [_VALID_BYTES] + assert [name.decode("utf-8", "replace") for name in deleted] == [_VALID] + assert [name.decode("utf-8", "replace") for name in changed] == [_KEY] + + conv = _converter() + assert conv._path_list(str(tmp_path / "work" / "deleted.txt")) == [_VALID] + assert conv._path_list(str(tmp_path / "work" / "changed.txt")) == [_KEY] + assert _ts_projects()._read_lines(tmp_path / "work" / "changed.txt") == [_KEY] + + delta = conv.convert(str(_index(tmp_path)), {_KEY}, [_VALID], "h" * 40, base, source_root="") + assert delta["deleted_files"] == [_VALID] + assert delta["files"] == [] and delta["skipped_files"] == [_KEY] + assert delta["stats"]["skipped_failed"] == 1 + + +def test_the_reverse_change_retires_the_replace_key(tmp_path: Path) -> None: + """A path that becomes UTF-8 again: the deleted entry is the `replace` key the old + document was indexed under, so the rows it names are the rows that exist.""" + repo, base = _repo_at(tmp_path, _INVALID) + _move(repo, _INVALID, _VALID_BYTES) + head = _commit(repo, "rename the file to a UTF-8 name") + + changed, deleted = _window(repo, base, head, tmp_path / "work") + assert changed == [_VALID_BYTES] + assert deleted == [_INVALID] == _gits_own(repo, base, head, "D") + conv = _converter() + assert conv._path_list(str(tmp_path / "work" / "deleted.txt")) == [_KEY] + delta = conv.convert(str(_index(tmp_path)), {_VALID}, [_KEY], "h" * 40, base, source_root="") + assert delta["deleted_files"] == [_KEY] + assert [f["path"] for f in delta["files"]] == [_VALID] + + +def test_two_undecodable_paths_keep_distinct_keys(tmp_path: Path) -> None: + """The key orders and pairs documents: `replace` keeps `src/…` and `lib/…` apart, + where "" put every undecodable path on one shared key.""" + pb = _pb() + conv = _converter() + keys = [] + for directory in (b"src/", b"lib/"): + mark = directory + b"paX.ts" + doc = pb.Document() + doc.relative_path = mark.decode() + payload = doc.SerializeToString().replace(mark, directory + b"pa\xff.ts") + keys.append(conv._document_path(payload)) + assert keys == ["src/pa\ufffd.ts", "lib/pa\ufffd.ts"] + assert keys[0] != keys[1] + + +def test_a_deleted_path_holding_a_newline_is_still_listed(tmp_path: Path) -> None: + """git C-quotes a name holding a newline; a list that drops the quoted line loses + the deletion, and the server keeps the rows of a file that vanished. The NUL list + carries the name whole, and it decodes to the key the store holds.""" + repo, base = _repo_at(tmp_path, _VALID_BYTES) + _move(repo, _VALID_BYTES, b"src/we\nird.ts") + head = _commit(repo, "rename the file to a name holding a newline") + + changed, deleted = _window(repo, base, head, tmp_path / "work") + assert changed == [b"src/we\nird.ts"] + assert deleted == [_VALID_BYTES] + delta = _converter().convert( + str(_index(tmp_path)), {"src/we\nird.ts"}, [_VALID], "h" * 40, base, source_root="" + ) + assert delta["deleted_files"] == [_VALID] diff --git a/tests/unit/test_scip_to_delta_cli.py b/tests/unit/test_scip_to_delta_cli.py index cbdd0d5fe8d..5bc007ab440 100644 --- a/tests/unit/test_scip_to_delta_cli.py +++ b/tests/unit/test_scip_to_delta_cli.py @@ -61,8 +61,9 @@ def _index(tmp_path: Path, name: str = "index.scip") -> Path: def _lines(tmp_path: Path, name: str, paths: list[str]) -> Path: + """A window list as `git_paths` writes it: NUL-separated raw names.""" p = tmp_path / name - p.write_text("".join(f"{x}\n" for x in paths)) + p.write_bytes(b"".join(x.encode() + b"\0" for x in paths)) return p diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index 2d27c293c6a..e939f1f8121 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -122,24 +122,48 @@ def test_the_server_logs_the_converters_warning_line() -> None: assert _converter().SKIPPED_WARNING == SKIPPED_WARNING -def test_a_run_over_every_document_fails_on_one_whose_path_cannot_be_read( +def test_a_full_run_names_a_document_whose_path_is_not_utf8_by_its_replace_key( tmp_path: Path, ) -> None: - """The server reads a file a full run's delta does not name as gone: a failed document - whose path cannot be recovered (here not UTF-8) fails the run, and no delta is written. - A window, which names its own files, counts it and converts.""" + """A path that is not UTF-8 still has a key: `replace` decoding, the one the store + holds. A failed document is listed under it, so the server marks that one file; "" + would have collapsed every such path onto one shared key, unnameable even to the + skip list.""" index = _bad_utf8_index(tmp_path) raw = index.read_bytes() assert raw.count(b"src/bad.cpp") == 1 index.write_bytes(raw.replace(b"src/bad.cpp", b"src/\xffad.cpp")) out = tmp_path / "delta.json" proc = _run(index, out) + assert proc.returncode == 0, proc.stderr + delta = json.loads(out.read_text()) + assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] + assert delta["skipped_files"] == ["src/\ufffdad.cpp"] + assert delta["stats"]["skipped_failed"] == 1 + assert "warning: skipped document 'src/\ufffdad.cpp'" in proc.stderr, proc.stderr + window = _converter().convert(str(index), {"src/a.cpp"}, [], "h" * 40, "b" * 40, source_root="") + assert [f["path"] for f in window["files"]] == ["src/a.cpp"] + assert window["skipped_files"] == [] and window["stats"]["skipped_failed"] == 1 + + +def test_a_full_run_fails_on_a_failed_document_with_no_path_at_all(tmp_path: Path) -> None: + """The server reads a file a full run's delta does not name as gone. A document that + fails and carries no path cannot be named, so the run fails rather than retire rows + it cannot name.""" + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///nonexistent-checkout" + _add_doc(index, "src/a.cpp", [(_fn("f", "aa"), 0)], []) + _add_doc(index, "", [(_fn(_MARK.decode(), "bb"), 0)], []) + raw = index.SerializeToString() + assert raw.count(_MARK) == 1 + path = tmp_path / "nopath.scip" + path.write_bytes(raw.replace(_MARK, b"\xff\xfe" + _MARK[2:])) + out = tmp_path / "delta.json" + proc = _run(path, out) assert proc.returncode != 0 assert "document 1 failed and its path cannot be read" in proc.stderr, proc.stderr assert not out.exists() - delta = _converter().convert(str(index), {"src/a.cpp"}, [], "h" * 40, "b" * 40, source_root="") - assert [f["path"] for f in delta["files"]] == ["src/a.cpp"] - assert delta["skipped_files"] == [] and delta["stats"]["skipped_failed"] == 1 def test_a_document_that_fails_to_convert_is_skipped_and_listed( diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index 9948d605281..cab623e6fa7 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -226,7 +226,7 @@ def test_delta_selects_a_root_tsconfig_for_a_root_source_change() -> None: def test_filter_reads_and_prints_names_that_are_not_utf8(tmp_path: Path) -> None: """Window lists carry raw git names; a member path is printed back byte for byte.""" changed = tmp_path / "changed.txt" - changed.write_bytes(b"packages/caf\xe9/src/a.ts\npackages/lib/caf\xe9.md\n") + changed.write_bytes(b"packages/caf\xe9/src/a.ts\0packages/lib/caf\xe9.md\0") # A UTF-8 locale other than C gives stdout the strict error handler; # pin it so the test does not depend on the host's locale. env = {**os.environ, "PYTHONIOENCODING": "utf-8:strict"} @@ -247,7 +247,7 @@ def test_filter_reads_and_prints_names_that_are_not_utf8(tmp_path: Path) -> None capture_output=True, ) assert out.stdout == b"packages/caf\xe9\n" - changed.write_bytes(b"caf\xe9.md\npackage.json\n") + changed.write_bytes(b"caf\xe9.md\0package.json\0") for cmd in (b"has-config", b"has-shared"): argv = [sys.executable, os.fsencode(_SCRIPT), cmd, b"--changed-file-list"] rc = subprocess.run([*argv, os.fsencode(changed)], env=env, capture_output=True) From 7932246ddd10ba5959be20af23a828e5eab0e168 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 09:07:33 +0000 Subject: [PATCH 54/81] Retire a stale mark only on the file's own record of an apply at the watermark MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `retire_published_marks` read two absences as proof. A mark was retirable when no `code_scip_batches` row of the namespace was `failed` and newer than it, so a partial apply that published a file's symbols and raised on its edge insert still cleared the mark once a later batch moved the watermark past the file, and `code_scip_batches` expires a record 30 days after it is created, after which every mark in a namespace was retirable. A mark now retires on positive evidence only: a compiler-tier symbol or edge row of the file stamped (`indexed_commit`) with the tier's watermark commit, which is an apply's own record that it wrote the file there, plus another blob of the file than the mark's. Every apply stamps its rows that way — this build's and the previous build's, an upload's and a worker's alike — and a partial apply cannot produce the stamp at the commit the watermark moves to: it stamps the commit it failed at, writes no watermark, and what follows leaves the file's rows there. A skipped file, a Go module its worker could not fetch, and a file whose apply rewrote no row carry no row at the watermark's commit, so their marks stay until this build applies the file. The pass reads `code_scip_batches` for nothing. The Go tier also retires no mark while `tier_health:go` notes a dependency this host cannot fetch (state `unavailable`), the module its worker passes without a retry. Rule 70 of `docs/architecture/rolling-upgrades.md` states the evidence, that it does not expire, and that a mark without it stays until the file is applied again. The tests read the tables' own definitions through clickhouse-local: a mark whose apply failed its edge insert, a mark whose namespace holds no batch row, and a Go mark under an unfetchable-dependency note survive, and the same file applied with its edges empties its mark. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 40 +-- server/code/app/index/scip_delta.py | 50 +++- server/code/store/index/symbols.py | 27 +- .../integration/test_code_scip_stale_mark.py | 20 +- tests/unit/test_code_scip_mark_retirement.py | 275 ++++++++++++++++++ 5 files changed, 354 insertions(+), 58 deletions(-) create mode 100644 tests/unit/test_code_scip_mark_retirement.py diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 7cdf4dc822a..d20e820bb19 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1049,30 +1049,32 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline only and applies with its mark under N's. N-1 neither reads nor empties a mark. A round writes its symbols and its edges in separate inserts, so N-1's rows of the file alone cannot show that its apply of the file completed, and a read keeps counting the - mark: after N-1 refreshes the file, and after an N-1 retry whose edge insert failed - followed by an N-1 watermark write over a window with no change, the file reads stale - and constructor coverage incomplete. N empties the mark when it applies the file, once - every round of that apply has landed. For an entry whose tier this build's worker runs - and whose mirror holds both commits, its next pass of the tier also empties the mark, - current entry or not, once N-1's apply is published (`retire_published_marks` in - `server/code/app/index/scip_delta.py`): the tier's watermark holds another blob of the - file than the mark's commit in the entry's mirror. The Python, TypeScript and C++ - workers move a watermark only after a whole apply of the window from the one before, - and N-1 fails a run on a document it cannot read, so that watermark is a completed apply - of the file's current content, whether or not the apply rewrote a row of the file (a - change to a function body alone rewrites none). For such an entry a file that never - changes again reads fresh after one pass of N. An upload batch whose apply fails is - recorded `failed` and leaves the watermark, and a later batch moves it without applying - the failed one's files, so the pass keeps every mark older than the namespace's newest - failed batch until N applies the file; batch records expire after 30 days. A namespace + mark: after an N-1 retry whose edge insert failed, followed by an N-1 watermark write + over a window that does not carry the file, it reads stale and constructor coverage + incomplete. N empties the mark when it applies the file, once every round of that apply + has landed. Its next pass of the tier also empties a mark whose file a completed apply + published (`retire_published_marks` in `server/code/app/index/scip_delta.py`), on the + file's own record and nothing else: a compiler-tier symbol or edge row of the file + stamped (`indexed_commit`) with the tier's watermark commit. Every apply stamps its rows + that way — N's and N-1's, an upload's and a worker's alike — so a file the previous build + applied after the mark carries that commit and another blob than the mark's, and the + mark goes. A partial apply cannot carry it: an apply whose edge insert raises stamps the + commit it was applying, writes no watermark, and the commit the next batch moves the + watermark to leaves the file's rows at the failed one. A file an apply skipped, and a + file of a Go module its worker could not fetch, carry no row at the watermark's commit + at all, so their marks stay; so does the mark of a file whose apply rewrote no row (a + function body alone changed), because no row of it carries the new commit, and it ends + when N applies the file. The pass reads `code_scip_batches` for nothing: that table + expires a record 30 days after it is created, so a row's absence there is evidence of + nothing, and what an apply did is in the rows it wrote, which do not expire. A namespace whose compiler tier arrives by upload alone has no mirror to prove the refresh with: `code_scip_apply` (`server/code/workers/scip_apply.py`) writes its marks and moves its watermark but never runs the pass, so that namespace keeps the mark until N applies the file. A watermark written over a window with no change of the file still holds the mark's blob, so the failed retry above keeps its mark until N applies the file. The Go - worker passes a module it could not fetch without a retry, so for the Go tier the pass - also needs a compiler-tier row of the file written after the mark, and an N-1 refresh - that rewrites no row keeps the mark until N applies the file. The Go tier keeps its + worker passes a module it could not fetch without a retry, so while `tier_health:go` + notes that dependency (state `unavailable`) the pass retires no Go mark, and a Go mark + also needs a compiler-tier row of the file written after the mark. The Go tier keeps its marks while it owes a module retry (`scip_commit_go_retry`). A mirror that lacks the watermark's commit, or a read that fails, keeps every mark; one that lacks a mark's commit keeps that mark. A rollback and a roll diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 3e146526a3c..8d3d4393c81 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -355,19 +355,20 @@ async def retire_published_marks( the mark counting; for an entry whose tier this build's worker runs, this is how such a mark ends when the file never changes again. `code_scip_apply` never calls it, so a namespace fed by uploads alone keeps the mark until this build applies the file. A file is - published when the tier's `watermark` holds another blob of it than the mark's commit. - The Python, TypeScript and C++ workers move the watermark only after a whole apply of - the window from the one before, and the previous build fails a run on a document it - cannot read, so that watermark is a completed apply of the file's current content, - whether or not the apply rewrote a row of the file (a change to a function body alone - rewrites none). An upload batch whose apply fails leaves the watermark to the next - batch, which does not apply the failed one's files, so a mark older than a failed batch - of the namespace is kept (`scip_marks_retirable`). The Go worker passes a module it - could not fetch without a retry, so a Go mark also needs a compiler-tier row of the file - written after it. A tier that owes a retry (`_retry`: a Go module that did not - build, whose files the watermark passed) keeps its marks, as does a read that fails. A - mirror that lacks the watermark's commit keeps every mark, one that lacks a mark's commit - that mark.""" + published only on positive evidence: the tier's `watermark` holds another blob of it than + the mark's commit, and the file holds a compiler-tier symbol or edge row stamped with + that commit, which is an apply's own record that it wrote the file there. Both builds + stamp every apply that way, an upload's and a worker's alike, and an apply that did not + reach the file writes no such row; a file an apply skipped or left unbuilt has none at + the watermark's commit, so its mark stays. Nothing is inferred from a batch's absence: a + `code_scip_batches` record expires 30 days on, and no row there is evidence of anything. + A tier that owes a retry (`_retry`: a Go module that did not build, whose + files the watermark passed) keeps its marks, as does a read that fails. The Go tier also + keeps them while its durable record notes a dependency this host cannot fetch + (`tier_health:go`, state `unavailable`), since the worker passes such a module without a + retry, and a Go mark needs a compiler-tier row of the file written after it. A mirror + that lacks the watermark's commit keeps every mark, one that lacks a mark's commit that + mark.""" try: published = await _published(repo, org, ns, tier, watermark) except Exception: # noqa: BLE001 — a failed read can only keep a mark @@ -380,12 +381,29 @@ async def retire_published_marks( return published +async def _dependency_unavailable(repo: Any, org: str, ns: str) -> bool: + """Whether the Go tier's durable record notes a module dependency this host cannot + fetch (`tier_health:go`, state `unavailable`). The worker passes such a module without + a retry, so no apply of the files in it can be taken as published.""" + from server.code.domain.index import tier_health + + raw = str(await repo.get_state(org, ns, tier_health.state_key("go")) or "") + record = tier_health.parse("go", raw) + return record is not None and record.state == "unavailable" + + async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> set[str]: - """The marked paths `retire_published_marks` empties.""" - written = await repo.scip_marks_retirable(org, ns, tier, rewritten=tier == "go") - target = str(await repo.get_state(org, ns, watermark) or "") if written else "" + """The marked paths `retire_published_marks` empties: the file's own rows carry the + watermark's commit (`scip_marks_retirable`), and its blob differs from the mark's.""" + target = str(await repo.get_state(org, ns, watermark) or "") if not target or await repo.get_state(org, ns, f"{watermark}_retry"): return set() + # A module the Go worker passed cannot have been applied, whatever the watermark says. + if tier == "go" and await _dependency_unavailable(repo, org, ns): + return set() + written = await repo.scip_marks_retirable(org, ns, tier, commit=target, rewritten=tier == "go") + if not written: + return set() from server.code.app.index import gitrepo from server.code.domain.index.repos import repo_for_namespace diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index da6a7295d36..ad2719d24c2 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -625,12 +625,14 @@ async def scip_stale_sample( return {str(r["path"]) for r in rows} async def scip_marks_retirable( - self, org: str, ns: str, tier: str, *, rewritten: bool + self, org: str, ns: str, tier: str, *, commit: str, rewritten: bool ) -> dict[str, str]: - """`tier`'s marks in force written after the namespace's newest failed upload batch - (`code_scip_apply`), each path with the commit its mark holds; with `rewritten`, only - those whose file holds a compiler-tier symbol or edge row written after the mark - (`retire_published_marks`).""" + """`tier`'s marks in force whose file holds a compiler-tier symbol or edge row + stamped with `commit` — an apply's own record that it wrote this file at that commit + — each path with the commit its mark holds; with `rewritten`, only those whose file + also holds a row written after the mark (`retire_published_marks`). What an apply did + not write is not evidence, and `code_scip_batches` expires: nothing here reads the + absence of a `failed` row as a sign that a file was published.""" rows = await self._ch.query_all( """ WITH marks AS ( @@ -642,32 +644,29 @@ async def scip_marks_retirable( AND startsWith(state_key, {mark:String}) AND state_value != '' ), written AS ( - SELECT path, max(version) AS rewritten + SELECT path, max(version) AS rewritten, + countIf(indexed_commit = {commit:String}) AS stamped FROM ( - SELECT path, version FROM loom.code_symbols + SELECT path, indexed_commit, version FROM loom.code_symbols WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' AND path IN (SELECT path FROM marks) UNION ALL - SELECT path, version FROM loom.code_edges + SELECT path, indexed_commit, version FROM loom.code_edges WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' AND path IN (SELECT path FROM marks) ) GROUP BY path - ), - failed AS ( - -- 0 when no batch failed; a batch retried and applied since is no row here - SELECT max(version) AS at FROM loom.code_scip_batches FINAL - WHERE org = {org:String} AND namespace = {ns:String} AND status = 'failed' ) SELECT marks.path AS path, marks.mark_commit AS mark_commit FROM marks LEFT JOIN written ON written.path = marks.path - WHERE marks.marked > (SELECT at FROM failed) + WHERE written.stamped > 0 AND ({rewritten:UInt8} = 0 OR written.rewritten > marks.marked) """, { "org": org, "ns": ns, "mark": f"{SCIP_STALE_PREFIX}{tier}:", + "commit": commit, "rewritten": int(rewritten), }, ) diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 0f6217de91c..44be871f357 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -1,8 +1,8 @@ """A file whose compiler-tier document a delta skipped reads as stale, although the tier's watermark moved past the file's last change, until a later delta of this build -applies it or, for an entry whose tier this build's worker runs, a pass of that worker -finds a later apply of it published. The marks stay out of the whole-namespace state -reads.""" +applies it or a pass finds the file's own rows stamped with the watermark's commit — an +apply's record that it wrote the file there (`retire_published_marks`). The marks stay out +of the whole-namespace state reads.""" from __future__ import annotations @@ -556,7 +556,8 @@ async def test_a_pass_of_this_build_retires_a_mark_the_previous_build_published( and moves the watermark; `PY_BAD` never changes again. An apply whose edge insert fails also writes `PY_OTHER`'s symbols, and `PY_OTHER` is the same at both commits. The next pass of this build's Python worker, with nothing to index, empties the mark - of `PY_BAD`, which the watermark holds published, and keeps the other.""" + of `PY_BAD`, whose rows the apply stamped with the watermark's commit, and keeps the + other, whose blob did not move.""" org, ns = unique_org("scip-stale-retire"), "code-stale-retire" git_dir, (first, second, _) = _py_mirror(tmp_path) cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) @@ -587,14 +588,15 @@ async def no_marks(*a: Any) -> None: @pytest.mark.asyncio -async def test_a_pass_retires_a_mark_the_previous_build_published_without_rewriting_a_row( +async def test_a_mark_whose_apply_rewrote_no_row_keeps_itself( ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """This build applies `PY_BAD`, then a delta of the same commit skips it. The previous build applies the next commit, which changes a function body alone: the file's symbols and edges are the rows it already holds, so the apply rewrites none, - and it moves the watermark. The next pass of this build's Python worker empties the - mark.""" + and it moves the watermark. The next pass of this build's Python worker keeps the + mark: no row of the file carries the new commit, so nothing records that an apply + published it there, and the mark ends when this build applies the file.""" org, ns = unique_org("scip-stale-body"), "code-stale-body" git_dir, (first, second, _) = _py_mirror(tmp_path) cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) @@ -621,8 +623,8 @@ async def no_marks(*a: Any) -> None: assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD} await _python_pass(cfg, monkeypatch) - assert await repo.scip_stale_marks(org, ns, "python") == set() - assert await repo.scip_stale_paths(org, ns, [PY_BAD]) == set() + assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD} + assert await repo.scip_stale_paths(org, ns, [PY_BAD]) == {PY_BAD} async def _upload(org: str, ns: str, base: str, delta: ScipDelta) -> None: diff --git a/tests/unit/test_code_scip_mark_retirement.py b/tests/unit/test_code_scip_mark_retirement.py new file mode 100644 index 00000000000..80beb31c251 --- /dev/null +++ b/tests/unit/test_code_scip_mark_retirement.py @@ -0,0 +1,275 @@ +"""A stale mark retires only on positive evidence that an apply of the file finished. + +`retire_published_marks` used to read the absence of a `failed` batch row as proof that +nothing had failed, so a partial apply — symbols in, the edge insert raised, a later batch +moving the watermark past that file — and a namespace whose batch records aged out both +emptied the mark. Both read the same now: the file must hold a compiler-tier row stamped +with the watermark's commit, an apply's own record that it wrote the file there, or every +mark stays. Real SQL on clickhouse-local: the rows below are the tables' own definitions, +and a retirement's write is its payload (the store insert needs a server this suite has +not). +""" + +from __future__ import annotations + +import asyncio +import json +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.code.app.index import gitrepo +from server.code.app.index.scip_delta import retire_published_marks +from server.code.domain.index import repos +from server.code.store.index import CodeRepo +from tests.unit import clickhouse_local + +ORG, NS = "o", "n" +C0 = "a" * 40 +C1 = "b" * 40 +C2 = "c" * 40 +BATCH = "6f1e2b7c-0000-4000-8000-000000000001" +PATH = "src/a.cc" +DDL = ( + clickhouse_local.ddl("code_index_state"), + clickhouse_local.ddl("code_symbols"), + clickhouse_local.ddl("code_edges"), + clickhouse_local.ddl("code_scip_batches"), +) + + +def _lit(value: Any) -> str: + if value is None: + return "NULL" + if isinstance(value, int): + return str(value) + return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'" + + +def _insert(table: str, rows: list[dict[str, Any]]) -> str: + cols = list(rows[0]) + values = ", ".join("(" + ", ".join(_lit(r[c]) for c in cols) + ")" for r in rows) + return f"INSERT INTO loom.{table} ({', '.join(cols)}) VALUES {values}" + + +def _mark(tier: str, commit: str, *, path: str = PATH, version: int = 1500) -> dict[str, Any]: + return { + "org": ORG, + "namespace": NS, + "state_key": f"scip_stale:{tier}:{path}", + "state_value": commit, + "detail": "", + "version": version, + } + + +def _watermark(key: str, commit: str, *, detail: str = "", version: int = 2000) -> dict[str, Any]: + return { + "org": ORG, + "namespace": NS, + "state_key": key, + "state_value": commit, + "detail": detail, + "version": version, + } + + +def _batch(status: str, *, commit: str = C1, version: int = 1200) -> dict[str, Any]: + return { + "org": ORG, + "namespace": NS, + "batch_id": BATCH, + "commit_sha": commit, + "status": status, + "producer": "clang", + "version": version, + } + + +def _symbol(*, stamped: str = "", path: str = PATH, version: int = 3000) -> dict[str, Any]: + return { + "org": ORG, + "namespace": NS, + "tier": "scip", + "qualified_name": f"f::{path}", + "symbol_id": f"s::{path}", + "path": path, + "indexed_commit": stamped, + "version": version, + } + + +def _edge(*, stamped: str = "", path: str = PATH, version: int = 3000) -> dict[str, Any]: + return { + "org": ORG, + "namespace": NS, + "tier": "scip", + "edge_kind": "calls", + "to_symbol_id": "s::callee", + "from_symbol_id": f"s::{path}", + "path": path, + "indexed_commit": stamped, + "version": version, + } + + +def _health(tier: str, state: str) -> dict[str, Any]: + record = { + "state": state, + "kind": "dependency_unavailable" if state == "unavailable" else "", + "error": "", + "fix": "", + "failing_since": "", + "last_failed_at": "", + "failed_passes": 0, + "last_ok_at": "", + } + return { + "org": ORG, + "namespace": NS, + "state_key": f"tier_health:{tier}", + "state_value": json.dumps(record), + "detail": "", + "version": 2100, + } + + +class _Local: + """clickhouse-local for the reads; the state writes recorded, since the store's insert + needs a server. What a retirement writes is its payload.""" + + def __init__(self, *setup: str) -> None: + self.local = clickhouse_local.LocalCH(*setup) + self.writes: list[tuple[str, list[dict[str, Any]]]] = [] + + async def query_all(self, sql: str, params: dict[str, Any] | None = None, **kw: Any) -> Any: + return await self.local.query_all(sql, params, **kw) + + async def query_one(self, sql: str, params: dict[str, Any] | None = None, **kw: Any) -> Any: + return await self.local.query_one(sql, params, **kw) + + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + self.writes.append((table, rows)) + + +def _ch(*rows: tuple[str, dict[str, Any]]) -> _Local: + by_table: dict[str, list[dict[str, Any]]] = {} + for table, row in rows: + by_table.setdefault(table, []).append(row) + return _Local(*DDL, *(_insert(table, rs) for table, rs in by_table.items())) + + +def _mirror(monkeypatch: pytest.MonkeyPatch, blobs: dict[tuple[str, str], bytes]) -> None: + """A mirror holding `blobs` at `(commit, path)`, its commits all present.""" + + async def has_commit(_git_dir: str, _commit: str) -> bool: + return True + + async def blob_ids(_git_dir: str, pairs: list[tuple[str, str]]) -> list[bytes | None]: + return [blobs.get((commit, path)) for commit, path in pairs] + + monkeypatch.setattr(gitrepo, "has_commit", has_commit) + monkeypatch.setattr(gitrepo, "blob_ids", blob_ids) + monkeypatch.setattr( + repos, "repo_for_namespace", lambda org, ns: SimpleNamespace(git_dir="/mirror") + ) + + +def _retire(ch: _Local, tier: str = "clang", watermark: str = "scip_commit") -> set[str]: + return asyncio.run(retire_published_marks(CodeRepo(ch), ORG, NS, tier, watermark)) + + +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_partial_apply_that_published_symbols_keeps_the_mark( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The apply wrote the file's symbols stamped `C1`, its edge insert raised, and a later + # batch moved the watermark to `C2`: no row of the file carries `C2`, so no record says + # the file's apply finished, however new its symbols are. + ch = _ch( + ("code_index_state", _mark("clang", C0)), + ("code_scip_batches", _batch("failed", commit=C1)), + ("code_symbols", _symbol(stamped=C1)), + ("code_index_state", _watermark("scip_commit", C2, detail=BATCH)), + ) + _mirror(monkeypatch, {(C0, PATH): b"old", (C2, PATH): b"new"}) + + assert _retire(ch) == set() + assert ch.writes == [] + + +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_the_reapply_with_edges_empties_the_mark(monkeypatch: pytest.MonkeyPatch) -> None: + # The same file applied again, every round in and stamped with the commit that moved + # the watermark: the mark goes. + ch = _ch( + ("code_index_state", _mark("clang", C0)), + ("code_scip_batches", _batch("applied", commit=C2)), + ("code_symbols", _symbol(stamped=C2)), + ("code_edges", _edge(stamped=C2)), + ("code_index_state", _watermark("scip_commit", C2, detail=BATCH)), + ) + _mirror(monkeypatch, {(C0, PATH): b"old", (C2, PATH): b"new"}) + + assert _retire(ch) == {PATH} + ((table, rows),) = ch.writes + assert table == "loom.code_index_state" + assert [(r["state_key"], r["state_value"]) for r in rows] == [(f"scip_stale:clang:{PATH}", "")] + + +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_mark_with_no_row_at_the_watermarks_commit_keeps_itself( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The namespace holds no batch row at all (they expired, or a worker applied) and the + # file's rows were stamped at the mark's commit: the absence of a failure is no record + # that the file was published, so the mark stays. + ch = _ch( + ("code_index_state", _mark("clang", C0)), + ("code_symbols", _symbol(stamped=C0)), + ("code_edges", _edge(stamped=C0)), + ("code_index_state", _watermark("scip_commit", C1)), + ) + _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) + + assert _retire(ch) == set() + assert ch.writes == [] + + +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_stamp_at_the_watermarks_commit_is_the_evidence_a_mark_needs() -> None: + repo = CodeRepo( + _ch( + ("code_index_state", _mark("clang", C0)), + ("code_symbols", _symbol(stamped=C1)), + ) + ) + assert asyncio.run(repo.scip_marks_retirable(ORG, NS, "clang", commit=C1, rewritten=False)) == { + PATH: C0 + } + assert ( + asyncio.run(repo.scip_marks_retirable(ORG, NS, "clang", commit=C2, rewritten=False)) == {} + ) + + +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_the_go_tier_retires_no_mark_while_its_record_notes_an_unfetched_dependency( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The worker passed a module it could not fetch, so a mark in it was applied by no + # one, whatever the watermark says; the same rows with the note cleared retire. + rows = ( + ("code_index_state", _mark("go", C0)), + ("code_scip_batches", _batch("applied", commit=C1)), + ("code_symbols", _symbol(stamped=C1)), + ("code_index_state", _watermark("scip_commit_go", C1, detail=BATCH)), + ) + _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) + + noted = _ch(*rows, ("code_index_state", _health("go", "unavailable"))) + assert _retire(noted, "go", "scip_commit_go") == set() + assert noted.writes == [] + + cleared = _ch(*rows, ("code_index_state", _health("go", "ok"))) + assert _retire(cleared, "go", "scip_commit_go") == {PATH} From 13cc9a70fb69c8a31d9692d6b1cd697f7e8b509c Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 09:47:14 +0000 Subject: [PATCH 55/81] Retire a stale mark only when both of the file's inserts carry the watermark MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `scip_marks_retirable` retired on a row of either table stamped with the tier's watermark commit, so a symbol row alone satisfied it. An apply whose edge insert raised leaves the file's symbols stamped at the commit it was applying, and a same-commit part or retry — a second batch that moves the watermark onto that commit — made that symbol row the watermark's, so the mark went with nothing showing the file's edges were published. The evidence is now both of an apply's inserts: a symbol row of the file stamped with the watermark commit and, when the store holds any compiler-tier edge row of the file, an edge row stamped with that same commit. Whether a file has edges is read from the rows it holds, so a file the tier writes no edge of still retires on its symbol row alone. The blob difference and the Go `rewritten` gate stand. Rule 70 said a partial apply cannot carry the evidence, which held for the batch that failed and not for the commit it failed at once a later batch moved the watermark there; it now states both inserts, that same-commit path, and the Go freeze the note imposes — every Go mark of the entry, because the record names no faithful set of modules to scope it by. The integration test that gave the old reason for a state its sibling retires now states what empties a mark. Two of that file's harness stubs still returned the pre-masking two-tuple and failed at the parent commit; they return the printed output too. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 41 ++++++----- server/code/app/index/scip_delta.py | 31 +++++--- server/code/store/index/symbols.py | 62 ++++++++++------ .../integration/test_code_scip_stale_mark.py | 22 +++--- tests/unit/test_code_scip_mark_retirement.py | 72 +++++++++++++++++-- 5 files changed, 167 insertions(+), 61 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index d20e820bb19..229af26ef92 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1054,27 +1054,36 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline incomplete. N empties the mark when it applies the file, once every round of that apply has landed. Its next pass of the tier also empties a mark whose file a completed apply published (`retire_published_marks` in `server/code/app/index/scip_delta.py`), on the - file's own record and nothing else: a compiler-tier symbol or edge row of the file - stamped (`indexed_commit`) with the tier's watermark commit. Every apply stamps its rows - that way — N's and N-1's, an upload's and a worker's alike — so a file the previous build - applied after the mark carries that commit and another blob than the mark's, and the - mark goes. A partial apply cannot carry it: an apply whose edge insert raises stamps the - commit it was applying, writes no watermark, and the commit the next batch moves the - watermark to leaves the file's rows at the failed one. A file an apply skipped, and a - file of a Go module its worker could not fetch, carry no row at the watermark's commit - at all, so their marks stay; so does the mark of a file whose apply rewrote no row (a - function body alone changed), because no row of it carries the new commit, and it ends - when N applies the file. The pass reads `code_scip_batches` for nothing: that table - expires a record 30 days after it is created, so a row's absence there is evidence of - nothing, and what an apply did is in the rows it wrote, which do not expire. A namespace - whose compiler tier arrives by upload alone has no mirror to prove the refresh with: + file's own record and nothing else: a compiler-tier symbol row of the file stamped + (`indexed_commit`) with the tier's watermark commit and, where the store holds a + compiler-tier edge row of the file, an edge row of it stamped with that same commit. + Every apply stamps its rows that way — N's and N-1's, an upload's and a worker's alike — + so a file the previous build applied after the mark carries that commit in both of the + apply's inserts, and another blob than the mark's, and the mark goes. One insert is no + record of the other: an apply whose edge insert raised leaves the file's symbol row + stamped at the commit it was applying, and a part or retry at that same commit — a second + batch that moves the watermark onto it — makes that symbol row the watermark's, so the + edge row is what shows both inserts landed. A file the tier writes no edge of is not + asked for one, and a file whose edges an apply left unchanged carries no edge row at the + new commit and keeps its mark. A file an apply skipped, and a file of a Go module its + worker could not fetch, carry no row at the watermark's commit at all, so their marks + stay; so does the mark of a file whose apply rewrote no row (a function body alone + changed), because no row of it carries the new commit, and it ends when N applies the + file. The pass reads `code_scip_batches` for nothing: that table expires a record 30 days + after it is created, so a row's absence there is evidence of nothing, and what an apply + did is in the rows it wrote, which do not expire. A namespace whose compiler tier arrives + by upload alone has no mirror to prove the refresh with: `code_scip_apply` (`server/code/workers/scip_apply.py`) writes its marks and moves its watermark but never runs the pass, so that namespace keeps the mark until N applies the file. A watermark written over a window with no change of the file still holds the mark's blob, so the failed retry above keeps its mark until N applies the file. The Go worker passes a module it could not fetch without a retry, so while `tier_health:go` - notes that dependency (state `unavailable`) the pass retires no Go mark, and a Go mark - also needs a compiler-tier row of the file written after the mark. The Go tier keeps its + notes that dependency (state `unavailable`) the pass retires no Go mark of the entry — + every mark, not only the unbuilt module's files, because that record keeps the module + lines as printed and masked, clipped to their tail, and names no faithful set of modules + to scope the freeze by — so a mark elsewhere in the entry ends when the note clears or + when N applies the file. A Go mark also needs a compiler-tier row of the file written + after the mark. The Go tier keeps its marks while it owes a module retry (`scip_commit_go_retry`). A mirror that lacks the watermark's commit, or a read that fails, keeps every mark; one that lacks a mark's commit keeps that mark. A rollback and a roll diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 8d3d4393c81..7c6b3c9e4fa 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -356,19 +356,25 @@ async def retire_published_marks( mark ends when the file never changes again. `code_scip_apply` never calls it, so a namespace fed by uploads alone keeps the mark until this build applies the file. A file is published only on positive evidence: the tier's `watermark` holds another blob of it than - the mark's commit, and the file holds a compiler-tier symbol or edge row stamped with - that commit, which is an apply's own record that it wrote the file there. Both builds - stamp every apply that way, an upload's and a worker's alike, and an apply that did not - reach the file writes no such row; a file an apply skipped or left unbuilt has none at - the watermark's commit, so its mark stays. Nothing is inferred from a batch's absence: a - `code_scip_batches` record expires 30 days on, and no row there is evidence of anything. + the mark's commit, and the file's own rows record both of an apply's inserts at that + commit — a symbol row of it stamped with the commit, and, when the store holds any edge + row of the file, an edge row stamped with the same commit. Both builds stamp every apply + that way, an upload's and a worker's alike, and an apply that did not reach the file + writes no such row; a file an apply skipped or left unbuilt has none at the watermark's + commit, so its mark stays. One insert is not the other's record: an apply whose edge + insert raised leaves the file's symbol row stamped at the commit it was applying, and a + same-commit part or retry that moves the watermark to that commit makes the symbols + alone look like a finished apply, so the edge row is required where the file has edges. + Nothing is inferred from a batch's absence: a `code_scip_batches` record expires 30 days + on, and no row there is evidence of anything. A tier that owes a retry (`_retry`: a Go module that did not build, whose files the watermark passed) keeps its marks, as does a read that fails. The Go tier also keeps them while its durable record notes a dependency this host cannot fetch (`tier_health:go`, state `unavailable`), since the worker passes such a module without a - retry, and a Go mark needs a compiler-tier row of the file written after it. A mirror - that lacks the watermark's commit keeps every mark, one that lacks a mark's commit that - mark.""" + retry, and a Go mark needs a compiler-tier row of the file written after it — every Go + mark of the entry, not only the unbuilt module's files, because the note keeps no + faithful set of the modules it names. A mirror that lacks the watermark's commit keeps + every mark, one that lacks a mark's commit that mark.""" try: published = await _published(repo, org, ns, tier, watermark) except Exception: # noqa: BLE001 — a failed read can only keep a mark @@ -384,7 +390,9 @@ async def retire_published_marks( async def _dependency_unavailable(repo: Any, org: str, ns: str) -> bool: """Whether the Go tier's durable record notes a module dependency this host cannot fetch (`tier_health:go`, state `unavailable`). The worker passes such a module without - a retry, so no apply of the files in it can be taken as published.""" + a retry, so no apply of the files in it can be taken as published; the record keeps the + module lines as printed and masked, clipped to their tail, so the pass keeps every Go + mark of the entry rather than guess which files the note names.""" from server.code.domain.index import tier_health raw = str(await repo.get_state(org, ns, tier_health.state_key("go")) or "") @@ -394,7 +402,8 @@ async def _dependency_unavailable(repo: Any, org: str, ns: str) -> bool: async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> set[str]: """The marked paths `retire_published_marks` empties: the file's own rows carry the - watermark's commit (`scip_marks_retirable`), and its blob differs from the mark's.""" + watermark's commit in both of an apply's inserts (`scip_marks_retirable`), and its blob + differs from the mark's.""" target = str(await repo.get_state(org, ns, watermark) or "") if not target or await repo.get_state(org, ns, f"{watermark}_retry"): return set() diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index ad2719d24c2..ae2f49e19d0 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -627,12 +627,20 @@ async def scip_stale_sample( async def scip_marks_retirable( self, org: str, ns: str, tier: str, *, commit: str, rewritten: bool ) -> dict[str, str]: - """`tier`'s marks in force whose file holds a compiler-tier symbol or edge row - stamped with `commit` — an apply's own record that it wrote this file at that commit - — each path with the commit its mark holds; with `rewritten`, only those whose file - also holds a row written after the mark (`retire_published_marks`). What an apply did - not write is not evidence, and `code_scip_batches` expires: nothing here reads the - absence of a `failed` row as a sign that a file was published.""" + """`tier`'s marks in force whose file an apply published at `commit`, each path with + the commit its mark holds; with `rewritten`, only those whose file also holds a row + written after the mark (`retire_published_marks`). + + The evidence is the file's own record of both of an apply's inserts: a symbol row of + it stamped with `commit` and, when the store holds any edge row of the file at all, + an edge row of it stamped with that same commit. A file the tier writes no edge of is + not made to grow one — whether it has edges is read from the rows it holds. A file it + does write edges of keeps its mark while only one of the two inserts carries the + commit, which is what a partial apply leaves: its symbol insert lands stamped at the + commit, and a same-commit part or retry that moves the watermark to that commit makes + the symbol row alone look like a finished apply. What an apply did not write is not + evidence, and `code_scip_batches` expires: nothing here reads the absence of a + `failed` row as a sign that a file was published.""" rows = await self._ch.query_all( """ WITH marks AS ( @@ -643,24 +651,36 @@ async def scip_marks_retirable( WHERE org = {org:String} AND namespace = {ns:String} AND startsWith(state_key, {mark:String}) AND state_value != '' ), - written AS ( - SELECT path, max(version) AS rewritten, - countIf(indexed_commit = {commit:String}) AS stamped - FROM ( - SELECT path, indexed_commit, version FROM loom.code_symbols - WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' - AND path IN (SELECT path FROM marks) - UNION ALL - SELECT path, indexed_commit, version FROM loom.code_edges - WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' - AND path IN (SELECT path FROM marks) - ) + symbols_written AS ( + SELECT path, countIf(indexed_commit = {commit:String}) AS stamped, + max(version) AS rewritten + FROM loom.code_symbols + WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' + AND path IN (SELECT path FROM marks) + GROUP BY path + ), + -- `held`: the file holds an edge row of this tier at all, at any version of it + -- (a tombstone too: the apply that wrote it wrote the file's edges) + edges_written AS ( + SELECT path, count() AS held, + countIf(indexed_commit = {commit:String}) AS stamped, + max(version) AS rewritten + FROM loom.code_edges + WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' + AND path IN (SELECT path FROM marks) GROUP BY path ) SELECT marks.path AS path, marks.mark_commit AS mark_commit - FROM marks LEFT JOIN written ON written.path = marks.path - WHERE written.stamped > 0 - AND ({rewritten:UInt8} = 0 OR written.rewritten > marks.marked) + FROM marks + LEFT JOIN symbols_written AS symbols ON symbols.path = marks.path + LEFT JOIN edges_written AS edges ON edges.path = marks.path + WHERE ifNull(symbols.stamped, 0) > 0 + AND (ifNull(edges.held, 0) = 0 OR ifNull(edges.stamped, 0) > 0) + AND ( + {rewritten:UInt8} = 0 + OR greatest(ifNull(symbols.rewritten, 0), ifNull(edges.rewritten, 0)) + > marks.marked + ) """, { "org": org, diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 44be871f357..32240c51dea 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -18,6 +18,7 @@ import pytest from server.code.app.index import compiler_tier, scip_delta, scip_full +from server.code.app.index.output_mask import Unmasked from server.code.app.index.scip_delta import ( ScipDelta, ScipEdge, @@ -142,13 +143,16 @@ async def test_a_skipped_document_is_stale_until_a_delta_applies_it(ch_client: A @pytest.mark.asyncio -async def test_a_refresh_by_the_previous_build_keeps_the_mark_until_this_build_applies_the_file( +async def test_a_refresh_by_the_previous_build_keeps_the_mark_until_this_build_writes( ch_client: Any, monkeypatch: pytest.MonkeyPatch ) -> None: """Rollout or rollback order: this build marks a skipped file, then the previous - build, which writes no marks, applies the file and moves the watermark. Its rows - cannot show that both inserts landed, so the mark still counts. Once this build is - back and applies the file, the mark is emptied; a later skip marks it again.""" + build, which writes no marks, applies the file and moves the watermark. Its rows are + a record that both of its inserts landed, and a read still counts the mark because a + read is no retirement: only a write of this build empties a mark — its own apply of + the file, or the pass of its tier's worker (`retire_published_marks`) — and the + previous build writes neither. Once this build is back and applies the file, the mark + is emptied; a later skip marks it again.""" org, ns = unique_org("scip-stale-rollout"), "code-stale-rollout" repo = await _repo(ch_client, org, ns, [BAD]) await _skip(repo, org, ns) @@ -248,7 +252,7 @@ async def harness(checkout: Path, scip_clang: Path, delta_path: Path, **kw: Any) files = [f.model_dump() for f in (_retry(), _other())] body = json.dumps({"delta_version": 1, "commit": "c" * 40, "files": files}) await asyncio.to_thread(delta_path.write_text, body) - return 0, "" + return 0, "", Unmasked(b"") with monkeypatch.context() as full_run: full_run.setattr(scip_full, "move_checkout", no_move) @@ -288,8 +292,8 @@ async def test_a_window_with_nothing_to_apply_keeps_the_mark( async def no_git(*a: Any, **kw: Any) -> None: return None - async def no_delta(*a: Any, **kw: Any) -> tuple[int, str]: - return 0, "" # the harness writes no delta when no C++ file changed + async def no_delta(*a: Any, **kw: Any) -> tuple[int, str, Unmasked]: + return 0, "", Unmasked(b"") # the harness writes no delta when no C++ file changed monkeypatch.setattr( delta_worker, @@ -556,8 +560,8 @@ async def test_a_pass_of_this_build_retires_a_mark_the_previous_build_published( and moves the watermark; `PY_BAD` never changes again. An apply whose edge insert fails also writes `PY_OTHER`'s symbols, and `PY_OTHER` is the same at both commits. The next pass of this build's Python worker, with nothing to index, empties the mark - of `PY_BAD`, whose rows the apply stamped with the watermark's commit, and keeps the - other, whose blob did not move.""" + of `PY_BAD`, both of whose inserts the apply stamped with the watermark's commit, and + keeps the other, whose blob did not move.""" org, ns = unique_org("scip-stale-retire"), "code-stale-retire" git_dir, (first, second, _) = _py_mirror(tmp_path) cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) diff --git a/tests/unit/test_code_scip_mark_retirement.py b/tests/unit/test_code_scip_mark_retirement.py index 80beb31c251..9b5d8c2503f 100644 --- a/tests/unit/test_code_scip_mark_retirement.py +++ b/tests/unit/test_code_scip_mark_retirement.py @@ -3,9 +3,10 @@ `retire_published_marks` used to read the absence of a `failed` batch row as proof that nothing had failed, so a partial apply — symbols in, the edge insert raised, a later batch moving the watermark past that file — and a namespace whose batch records aged out both -emptied the mark. Both read the same now: the file must hold a compiler-tier row stamped -with the watermark's commit, an apply's own record that it wrote the file there, or every -mark stays. Real SQL on clickhouse-local: the rows below are the tables' own definitions, +emptied the mark. Both read the same now: the file must hold a compiler-tier symbol row +stamped with the watermark's commit, and, when the store holds any compiler-tier edge row +of it, an edge row stamped with that same commit — an apply's own record that both of its +inserts wrote the file there — or every mark stays. Real SQL on clickhouse-local: the rows below are the tables' own definitions, and a retirement's write is its payload (the store insert needs a server this suite has not). """ @@ -218,6 +219,66 @@ def test_the_reapply_with_edges_empties_the_mark(monkeypatch: pytest.MonkeyPatch assert [(r["state_key"], r["state_value"]) for r in rows] == [(f"scip_stale:clang:{PATH}", "")] +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_symbol_stamp_alone_keeps_the_mark_of_a_file_that_holds_edges( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A symbol row of the file stamped `C1` and the watermark at `C1` — a same-commit part + # or retry moved it there — while the file's edges still carry the mark's commit. The + # symbol insert landing is no record that the edge insert of that apply landed: the + # mark stays, and the file's edges are what the next apply has to stamp. + ch = _ch( + ("code_index_state", _mark("clang", C0)), + ("code_symbols", _symbol(stamped=C1)), + ("code_edges", _edge(stamped=C0)), + ("code_index_state", _watermark("scip_commit", C1)), + ) + _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) + + assert ( + asyncio.run(CodeRepo(ch).scip_marks_retirable(ORG, NS, "clang", commit=C1, rewritten=False)) + == {} + ) + assert _retire(ch) == set() + assert ch.writes == [] + + +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_an_edge_stamp_alone_keeps_the_mark_too(monkeypatch: pytest.MonkeyPatch) -> None: + # The mirror of the case above: a round publishes the file's edges and its symbol insert + # raises, so the symbols carry the mark's commit and the edges the watermark's. Neither + # insert stands for the other, so this mark stays too. + ch = _ch( + ("code_index_state", _mark("clang", C0)), + ("code_symbols", _symbol(stamped=C0)), + ("code_edges", _edge(stamped=C1)), + ("code_index_state", _watermark("scip_commit", C1)), + ) + _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) + + assert _retire(ch) == set() + assert ch.writes == [] + + +@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") +def test_a_parser_tier_edge_of_the_file_is_no_edge_of_the_compiler_tier( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The file holds an edge every indexed file has — the parser tier's — and the compiler + # tier wrote none of it (a header of declarations). Whether the file has edges is read + # from the compiler tier's rows: its apply had no edge to write, so its symbol row at the + # watermark is the whole record the file can carry and the mark goes. + ch = _ch( + ("code_index_state", _mark("clang", C0)), + ("code_symbols", _symbol(stamped=C1)), + ("code_edges", _edge(stamped=C0) | {"tier": "treesitter"}), + ("code_index_state", _watermark("scip_commit", C1)), + ) + _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) + + assert _retire(ch) == {PATH} + + @pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") def test_a_mark_with_no_row_at_the_watermarks_commit_keeps_itself( monkeypatch: pytest.MonkeyPatch, @@ -238,7 +299,10 @@ def test_a_mark_with_no_row_at_the_watermarks_commit_keeps_itself( @pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_a_stamp_at_the_watermarks_commit_is_the_evidence_a_mark_needs() -> None: +def test_a_file_with_no_edges_needs_only_its_symbol_stamp() -> None: + # A file the compiler tier writes no edge of (a header of declarations, a file of + # constants): its apply's edge insert had nothing to write, so its symbol row at the + # watermark is the whole record the file can carry, and it is enough. repo = CodeRepo( _ch( ("code_index_state", _mark("clang", C0)), From d81b67e37fbfb3c48944155d011f0d59203f57ef Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 10:57:01 +0000 Subject: [PATCH 56/81] A mark retires on the apply's own record, and the Go freeze names modules MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pass read a count of the file's rows: a symbol row stamped at the watermark's commit and, where the store held any edge row of the file, an edge row stamped with it. An apply that rewrites a symbol row and leaves the edge set unchanged writes no edge row at all, so `held > 0, stamped = 0` — a finished apply — is the shape a failed edge insert leaves, which is the one state the mark exists to catch; `held` was a count with no FINAL and no tombstone filter, so a file whose edges were legitimately removed was held for good; and neither aggregation took FINAL, so a superseded version could answer for the live one. Now each round writes one state row per marked file it carried — `scip_applied::` holding the commit — last of the round's writes, after its symbol insert and its edge insert and in the same coroutine, so the row exists only for a round that raised neither. It is written for a file the round rewrote no row of too, which is what a function body alone does. `retire_published_marks` reads that row and nothing else: FINAL, non-empty, the watermark's commit, and newer than the mark. A mark and the record that answers it are written and emptied in one insert, so no retirement joins a record to a mark it was not written for. The Go worker writes the modules it could not fetch to `scip_unavailable:go` before it moves the watermark, and the pass gates those modules' files and a retried module's own: one unbuilt module no longer holds every Go mark of the entry, and the masked health note is not read for it. A build that writes no record — the previous release — no longer retires a mark: its refresh of a marked file leaves the mark counting, and the mark ends when this build applies the file. tests/unit/test_code_scip_mark_retirement.py applies every case on clickhouse-local, and tests/integration/test_code_scip_stale_mark.py against a server. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 74 +- server/code/app/index/scip_delta.py | 214 ++++-- server/code/domain/index/state.py | 18 +- server/code/store/index/base.py | 55 +- server/code/store/index/symbols.py | 109 +-- server/code/workers/scip_go_delta.py | 55 +- .../integration/test_code_scip_stale_mark.py | 23 +- tests/unit/test_code_delta_stream.py | 2 +- tests/unit/test_code_repos_batched_state.py | 2 + tests/unit/test_code_scip_mark_retirement.py | 632 +++++++++++------- .../unit/test_code_scip_skipped_documents.py | 9 +- tests/unit/test_code_scip_ts_delta_worker.py | 2 +- 12 files changed, 774 insertions(+), 421 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 229af26ef92..8bcc40a5835 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1047,29 +1047,39 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline build's harness wrote. In `tests/unit/test_code_scip_skipped_documents.py`, a converted upload with a skipped document fails under a worker that applies version 1 only and applies with its mark under N's. N-1 neither reads nor empties a mark. A - round writes its symbols and its edges in separate inserts, so N-1's rows of the file - alone cannot show that its apply of the file completed, and a read keeps counting the - mark: after an N-1 retry whose edge insert failed, followed by an N-1 watermark write - over a window that does not carry the file, it reads stale and constructor coverage - incomplete. N empties the mark when it applies the file, once every round of that apply - has landed. Its next pass of the tier also empties a mark whose file a completed apply - published (`retire_published_marks` in `server/code/app/index/scip_delta.py`), on the - file's own record and nothing else: a compiler-tier symbol row of the file stamped - (`indexed_commit`) with the tier's watermark commit and, where the store holds a - compiler-tier edge row of the file, an edge row of it stamped with that same commit. - Every apply stamps its rows that way — N's and N-1's, an upload's and a worker's alike — - so a file the previous build applied after the mark carries that commit in both of the - apply's inserts, and another blob than the mark's, and the mark goes. One insert is no - record of the other: an apply whose edge insert raised leaves the file's symbol row - stamped at the commit it was applying, and a part or retry at that same commit — a second - batch that moves the watermark onto it — makes that symbol row the watermark's, so the - edge row is what shows both inserts landed. A file the tier writes no edge of is not - asked for one, and a file whose edges an apply left unchanged carries no edge row at the - new commit and keeps its mark. A file an apply skipped, and a file of a Go module its - worker could not fetch, carry no row at the watermark's commit at all, so their marks - stay; so does the mark of a file whose apply rewrote no row (a function body alone - changed), because no row of it carries the new commit, and it ends when N applies the - file. The pass reads `code_scip_batches` for nothing: that table expires a record 30 days + round writes its symbols and its edges in separate inserts, and an apply that rewrites a + symbol row while leaving the edge set unchanged writes no edge row at all (`_apply_round` + skips an empty edge insert, `_diff_edges` restamps no row it keeps), so N-1's rows of the + file alone cannot show that its apply of the file completed: what a finished apply of an + unchanged file leaves and what an edge insert that raised leaves are the same rows. A read + keeps counting the mark: after an N-1 retry whose edge insert failed, followed by an N-1 + watermark write over a window that does not carry the file, it reads stale and + constructor coverage incomplete. + + So the apply leaves its own record and N retires on that alone. At the end of every round + — after the round's symbol insert and its edge insert, in the same coroutine — N writes + one state row per marked file the round carried, `scip_applied::` holding the + commit (`SCIP_APPLIED_PREFIX`, `_record_applied` in + `server/code/app/index/scip_delta.py`). The row exists only for a round whose inserts both + returned; an insert that raised leaves none. It is written for a file the round rewrote no + row of too — a function body alone — because the record states that the apply reached the + file, and a count of the file's rows cannot. N empties the mark when it applies the file, + once every round of that apply has landed, and empties the record in the same insert + (`_mark_stale`): a mark and the record that answers it are written and emptied together, + so no retirement joins a record to a mark it was not written for. It is one narrow row per + marked file a round carried, not a row a file of the index, and nothing else writes it. + + N's next pass of the tier also empties a mark whose file a completed apply published + (`retire_published_marks`), on that record and nothing else: `scip_applied` for the file's + tier and path, read `FINAL`, non-empty, holding the tier's watermark commit, and written + after the mark (`version` past the mark's). A superseded version of either row answers + nothing. A file the previous build applied holds no record — N-1 writes none — so its mark + ends when N applies the file, not on N-1's rows: the predicate this replaced retired it on + stamps that could not tell a finished apply from a failed insert, and a mark kept a pass + too long reads stale, where one retired on a partial apply hides the failure the mark + exists for. `tests/unit/test_code_scip_mark_retirement.py` applies every case. + + The pass reads `code_scip_batches` for nothing: that table expires a record 30 days after it is created, so a row's absence there is evidence of nothing, and what an apply did is in the rows it wrote, which do not expire. A namespace whose compiler tier arrives by upload alone has no mirror to prove the refresh with: @@ -1077,14 +1087,16 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline watermark but never runs the pass, so that namespace keeps the mark until N applies the file. A watermark written over a window with no change of the file still holds the mark's blob, so the failed retry above keeps its mark until N applies the file. The Go - worker passes a module it could not fetch without a retry, so while `tier_health:go` - notes that dependency (state `unavailable`) the pass retires no Go mark of the entry — - every mark, not only the unbuilt module's files, because that record keeps the module - lines as printed and masked, clipped to their tail, and names no faithful set of modules - to scope the freeze by — so a mark elsewhere in the entry ends when the note clears or - when N applies the file. A Go mark also needs a compiler-tier row of the file written - after the mark. The Go tier keeps its - marks while it owes a module retry (`scip_commit_go_retry`). A mirror that lacks the + worker passes a module it could not fetch without a retry and without a delta, so it + writes the modules it left unbuilt to `scip_unavailable:go` — a JSON list of their dirs, + unmasked, from the split the harness output already gives it (`_build`'s `unfetched`) — + before it moves the watermark, and the pass keeps the marks of those modules' files and no + others: a module that owes a retry (`scip_commit_go_retry`) is gated the same way, by its + own dir, and both rows name modules rather than the entry. The health record's note is not + read for this: it keeps the module lines as printed and masked, clipped to their tail, and + names no faithful set of modules to scope a freeze by. A Go file outside those modules + ends on its record like any other tier's, so one broken module no longer holds an entry's + every Go mark. A mirror that lacks the watermark's commit, or a read that fails, keeps every mark; one that lacks a mark's commit keeps that mark. A rollback and a roll forward do the same. A marked file that N-1 deletes is never applied by N again, so N's diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 7c6b3c9e4fa..851be0f2688 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -25,7 +25,11 @@ from server.code.app.index.entry_lock import check_held from server.code.domain.extract.treesitter import symbol_id -from server.code.domain.index.state import SCIP_STALE_PREFIX +from server.code.domain.index.state import ( + SCIP_APPLIED_PREFIX, + SCIP_STALE_PREFIX, + SCIP_UNAVAILABLE_PREFIX, +) from server.code.store.index import CodeRepo, build_row from server.workers import pass_context @@ -268,7 +272,13 @@ def keep(path: str) -> bool: rounds = delta.rounds(APPLY_ROUND_FILES, keep) reading = False refreshed: set[str] = set() + marked: set[str] = set() try: + # The tier's marks, read once: the rounds record the apply of a marked file + # (`_record_applied`), and `_mark_stale` empties the mark and the record of the + # files this delta applied. Both read the same set, so a record cannot outlive its + # mark. A read that fails here aborts the apply with the rounds' file released. + marked = await repo.scip_stale_marks(org, ns, tier) while True: reading = True batch = await asyncio.to_thread(next, rounds, None) @@ -280,7 +290,7 @@ def keep(path: str) -> bool: if not batch: continue refreshed.update(f.path for f in batch) - await _apply_files(repo, org, ns, delta.commit, batch, stats) + await _apply_files(repo, org, ns, delta.commit, batch, stats, tier=tier, marked=marked) del batch # freed before the next round is read finally: # a failed apply releases the read's file now; a read cancelled while it runs in @@ -289,7 +299,7 @@ def keep(path: str) -> bool: rounds.close() # a skipped file the entry would not keep is never marked: nothing would clear it skipped = {p for p in delta.skipped_files if not out_of_scope(p) and not refused(p)} - await _mark_stale(repo, org, ns, tier, delta.commit, skipped, refreshed) + await _mark_stale(repo, org, ns, tier, delta.commit, skipped, refreshed, marked) if FEATURE_CTOR_CALLS in delta.features: check_held() await repo.set_state( @@ -330,18 +340,24 @@ async def _mark_stale( commit: str, skipped: set[str], refreshed: set[str], + marked: set[str], ) -> None: - """One write of `tier`'s rows only (`SCIP_STALE_PREFIX`): each skipped file marked at - `commit`, and the mark of each file this delta applied or deleted emptied, as is the - mark of a file with no blob at `commit` (one the previous build deleted, which no - apply of this build names again). Another tier's marks are never read or written, so - tiers applying side by side keep both.""" + """One write of `tier`'s rows only (`SCIP_STALE_PREFIX`, `SCIP_APPLIED_PREFIX`): each + skipped file marked at `commit`, and the mark of each file this delta applied or + deleted emptied, as is the mark of a file with no blob at `commit` (one the previous + build deleted, which no apply of this build names again) and the applied record of + each of those. A mark and the record that answers it end in the same insert, so no + retirement reads a record against a mark it was not written for. `marked` is the + tier's marks read once by the caller (`apply_delta`), before the rounds ran. Another + tier's marks are never read or written, so tiers applying side by side keep both.""" refreshed -= skipped prefix = f"{SCIP_STALE_PREFIX}{tier}:" - marked = await repo.scip_stale_marks(org, ns, tier) + applied = f"{SCIP_APPLIED_PREFIX}{tier}:" gone = await _gone_at(org, ns, commit, marked - refreshed - skipped) + cleared = sorted((marked & refreshed) | gone) rows = {prefix + p: commit for p in sorted(skipped)} - rows.update({prefix + p: "" for p in sorted((marked & refreshed) | gone)}) + rows.update({prefix + p: "" for p in cleared}) + rows.update({applied + p: "" for p in cleared}) if rows: check_held() await repo.set_states(org, ns, rows) @@ -350,67 +366,99 @@ async def _mark_stale( async def retire_published_marks( repo: Any, org: str, ns: str, tier: str, watermark: str ) -> set[str]: - """Empty `tier`'s marks whose file an apply has published since the mark, and return - their paths. The previous build writes no marks, so its refresh of a marked file leaves - the mark counting; for an entry whose tier this build's worker runs, this is how such a - mark ends when the file never changes again. `code_scip_apply` never calls it, so a - namespace fed by uploads alone keeps the mark until this build applies the file. A file is - published only on positive evidence: the tier's `watermark` holds another blob of it than - the mark's commit, and the file's own rows record both of an apply's inserts at that - commit — a symbol row of it stamped with the commit, and, when the store holds any edge - row of the file, an edge row stamped with the same commit. Both builds stamp every apply - that way, an upload's and a worker's alike, and an apply that did not reach the file - writes no such row; a file an apply skipped or left unbuilt has none at the watermark's - commit, so its mark stays. One insert is not the other's record: an apply whose edge - insert raised leaves the file's symbol row stamped at the commit it was applying, and a - same-commit part or retry that moves the watermark to that commit makes the symbols - alone look like a finished apply, so the edge row is required where the file has edges. - Nothing is inferred from a batch's absence: a `code_scip_batches` record expires 30 days - on, and no row there is evidence of anything. - A tier that owes a retry (`_retry`: a Go module that did not build, whose - files the watermark passed) keeps its marks, as does a read that fails. The Go tier also - keeps them while its durable record notes a dependency this host cannot fetch - (`tier_health:go`, state `unavailable`), since the worker passes such a module without a - retry, and a Go mark needs a compiler-tier row of the file written after it — every Go - mark of the entry, not only the unbuilt module's files, because the note keeps no - faithful set of the modules it names. A mirror that lacks the watermark's commit keeps - every mark, one that lacks a mark's commit that mark.""" + """Empty `tier`'s marks whose file an apply of this build has published since the + mark, and return their paths. + + A published file is one thing: the apply's own record, `scip_applied::` + holding the watermark's commit, written after both of the apply's inserts of the file + (`apply_delta`, `_record_applied`) and newer than the mark. Nothing here counts the + file's rows: an apply that rewrites a symbol row and leaves the edge set unchanged + writes no edge row at all (`_apply_round` skips an empty edge insert, `_diff_edges` + restamps no row it keeps), so `held > 0, stamped = 0` is the same shape a failed edge + insert leaves, and a count cannot tell them apart. The record can, and it is the only + thing asked for one file — one row per marked file the round carried, joined to the + mark by path and ordered by version, so a superseded version of either answers + nothing. + + The tier's `watermark` must also hold another blob of the file than the mark's commit: + a file that did not change is not republished, and its mark is a statement about the + file as it stands. A mark whose commit is the watermark's is that same file. + + A build that writes no marks writes no record: its refresh of a marked file leaves the + mark counting, and the mark ends when this build applies the file (`_mark_stale`) or, + for an entry whose tier this build's worker runs, here. `code_scip_apply` never calls + this, so a namespace fed by uploads alone keeps the mark until this build applies the + file. Nothing is inferred from a batch's absence: a `code_scip_batches` record expires + 30 days on, and no row there is evidence of anything. + + A tier that owes a retry (`_retry`: the modules that did not build, whose + files the watermark passed) keeps the marks of those modules' files only, as does the + Go tier while its last pass lists a module it could not fetch + (`scip_unavailable:go`, written by `scip_go_delta._run_repo`): no apply covered those + files, so no record of them names the watermark. Every other module's files retire on + their record — the freeze names modules, not the entry. A read that fails keeps every + mark, and so does a mirror that lacks the watermark's commit, or a mark's commit. + """ try: published = await _published(repo, org, ns, tier, watermark) except Exception: # noqa: BLE001 — a failed read can only keep a mark return set() if published: check_held() - await repo.set_states( - org, ns, {f"{SCIP_STALE_PREFIX}{tier}:{p}": "" for p in sorted(published)} - ) + await repo.clear_scip_marks(org, ns, tier, sorted(published)) return published -async def _dependency_unavailable(repo: Any, org: str, ns: str) -> bool: - """Whether the Go tier's durable record notes a module dependency this host cannot - fetch (`tier_health:go`, state `unavailable`). The worker passes such a module without - a retry, so no apply of the files in it can be taken as published; the record keeps the - module lines as printed and masked, clipped to their tail, so the pass keeps every Go - mark of the entry rather than guess which files the note names.""" - from server.code.domain.index import tier_health +def _module_dirs(raw: str, *, mapping: bool) -> set[str]: + """The module directories a JSON state row names: the keys of `_retry`'s + map (dir -> base), or the items of `scip_unavailable`'s list. A row that is empty or + not of that shape names none: a sheet of text from another build is not a list of + modules, and reading it as one would freeze nothing.""" + if not raw: + return set() + try: + parsed = json.loads(raw) + except ValueError: + return set() + if mapping: + if not isinstance(parsed, dict): + return set() + return {str(d) for d in parsed} + if not isinstance(parsed, list): + return set() + return {str(d) for d in parsed if isinstance(d, str)} + + +def _under_module(path: str, dirs: set[str]) -> bool: + """Whether `path` is one of `dirs`' files. The root module (".", "" or "/") holds + every path of the entry.""" + for d in dirs: + d = d.strip("/") + if d in ("", ".") or path == d or path.startswith(d + "/"): + return True + return False + - raw = str(await repo.get_state(org, ns, tier_health.state_key("go")) or "") - record = tier_health.parse("go", raw) - return record is not None and record.state == "unavailable" +async def _unbuilt_modules(repo: Any, org: str, ns: str, tier: str, watermark: str) -> set[str]: + """The module directories whose files the watermark passed without an apply this + build made: those that owe a retry (`_retry`) and, for the Go tier, those + its last pass could not fetch (`scip_unavailable:go`). Both rows name modules, so the + freeze they justify is the modules' — an entry with one broken module still retires + every other module's marks.""" + owed = str(await repo.get_state(org, ns, f"{watermark}_retry") or "") + unfetched = str(await repo.get_state(org, ns, f"{SCIP_UNAVAILABLE_PREFIX}{tier}") or "") + return _module_dirs(owed, mapping=True) | _module_dirs(unfetched, mapping=False) async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> set[str]: - """The marked paths `retire_published_marks` empties: the file's own rows carry the - watermark's commit in both of an apply's inserts (`scip_marks_retirable`), and its blob - differs from the mark's.""" + """The marked paths `retire_published_marks` empties: the apply's own record of the + file holds the watermark's commit (`scip_marks_retirable`), its blob differs from the + mark's, and its module is not one the watermark passed unbuilt (`_unbuilt_modules`).""" target = str(await repo.get_state(org, ns, watermark) or "") - if not target or await repo.get_state(org, ns, f"{watermark}_retry"): + if not target: return set() - # A module the Go worker passed cannot have been applied, whatever the watermark says. - if tier == "go" and await _dependency_unavailable(repo, org, ns): - return set() - written = await repo.scip_marks_retirable(org, ns, tier, commit=target, rewritten=tier == "go") + gated = await _unbuilt_modules(repo, org, ns, tier, watermark) + written = await repo.scip_marks_retirable(org, ns, tier, commit=target) if not written: return set() from server.code.app.index import gitrepo @@ -419,7 +467,9 @@ async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> cfg = repo_for_namespace(org, ns) if cfg is None or not cfg.git_dir or not await gitrepo.has_commit(cfg.git_dir, target): return set() - paths = sorted(p for p, at in written.items() if at != target) + paths = sorted(p for p, at in written.items() if at != target and not _under_module(p, gated)) + if not paths: + return set() blobs = await gitrepo.blob_ids( cfg.git_dir, [(written[p], p) for p in paths] + [(target, p) for p in paths] ) @@ -428,19 +478,42 @@ async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> return {p for p, was, is_ in zip(paths, marked, now, strict=True) if was and was != is_} +async def _record_applied( + repo: Any, org: str, ns: str, tier: str, commit: str, paths: list[str] +) -> None: + """The round's last write: `scip_applied::` = `commit` for each of the + round's marked files. It runs after both of the round's inserts, in this coroutine, so + its presence is the record that neither raised — an insert that raised leaves none and + the mark stays (`retire_published_marks`). A file the round rewrote no row of is + recorded too: its apply did reach it, and that is exactly what the count of its rows + cannot say.""" + if not paths: + return + check_held() + await repo.record_scip_applied(org, ns, tier, commit, paths) + + async def _apply_files( - repo: Any, org: str, ns: str, commit: str, files: list[ScipFile], stats: ScipApplyStats + repo: Any, + org: str, + ns: str, + commit: str, + files: list[ScipFile], + stats: ScipApplyStats, + *, + tier: str, + marked: set[str], ) -> None: """One round of files: one read and insert per table where the store has the round reads, else file by file.""" # A pass that lost its workers' lease writes no further round. pass_context.check_stop() if _has_round_reads(repo): - await _apply_round(repo, org, ns, commit, files, stats) + await _apply_round(repo, org, ns, commit, files, stats, tier=tier, marked=marked) return for f in files: pass_context.check_stop() - await _apply_file(repo, org, ns, commit, f, stats) + await _apply_file(repo, org, ns, commit, f, stats, tier=tier, marked=marked) stats.files += 1 @@ -457,9 +530,13 @@ async def _apply_round( commit: str, files: list[ScipFile], stats: ScipApplyStats, + *, + tier: str, + marked: set[str], ) -> None: - """One round: the three reads once for every path, the per-file - key-diff unchanged, the rows of the round in one insert per table.""" + """One round: the four reads once for every path, the per-file + key-diff unchanged, the rows of the round in one insert per table, and last the + round's record of the marked files it carried (`_record_applied`).""" paths = sorted({f.path for f in files}) symbols = await repo.live_symbols_for_paths(org, ns, paths, "scip") edges = await repo.live_edges_for_paths(org, ns, paths, "scip") @@ -490,6 +567,7 @@ async def _apply_round( await _publish(repo, "code_symbols", sink.symbols) if sink.edges: await _publish(repo, "code_edges", sink.edges) + await _record_applied(repo, org, ns, tier, commit, sorted(p for p in paths if p in marked)) def _symbol_metadata(symbol: ScipSymbol) -> dict[str, Any]: @@ -516,10 +594,13 @@ async def _apply_file( spans: list[tuple[str, int, int]] | None = None, fn_symbol_spans: list[tuple[int, int]] | None = None, sink: _RoundSink | None = None, + tier: str = "", + marked: set[str] | None = None, ) -> None: - """One file's key-diff. Alone it reads its own live rows and inserts; - inside a round (`_apply_round`) the live rows and chunk spans come in - and the rows go to `sink` for the round's insert.""" + """One file's key-diff. Alone it reads its own live rows, inserts, and last records + the apply of a marked file (`_record_applied`); inside a round (`_apply_round`) the + live rows and chunk spans come in, the rows go to `sink` for the round's insert, and + the round records the file.""" # ---- symbols --------------------------------------------------------- if existing is None: existing = await repo.live_symbols_for_path(org, ns, f.path, "scip") @@ -588,6 +669,9 @@ async def _apply_file( sink.edges.extend(edge_rows) else: await _publish(repo, "code_edges", edge_rows) + await _record_applied( + repo, org, ns, tier, commit, [f.path] if f.path in (marked or ()) else [] + ) async def _diff_edges( diff --git a/server/code/domain/index/state.py b/server/code/domain/index/state.py index 47a9c64ce6e..5b42f545f6e 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -29,9 +29,25 @@ class StateEntry(TypedDict, total=False): # holds that delta's commit, under the tier that applied it whatever the path's suffix, # until a later delta of that tier applies or deletes the file and empties it once the # whole apply has landed. A build that writes no marks never empties one, and neither -# its rows of the file nor its watermark write retire it. +# its rows of the file nor its watermark write retire it: the rows of an apply are two +# inserts, and a file an apply of it rewrote no row of leaves the same rows as an apply +# whose second insert raised. # `scip_stale_paths` reads these rows by key; the whole-namespace reads leave them out. SCIP_STALE_PREFIX = "scip_stale:" +# An apply's own record that it published a marked file at a commit: +# `scip_applied::` holds the commit, written after both of the apply's +# inserts of that file (its symbols, its edges) so the row's presence is the record that +# both landed — an insert that raised leaves none. `retire_published_marks` reads it, and +# only it: what an apply wrote about a file is a count of rows, and a count cannot tell +# an unchanged file, whose apply writes no row, from an insert that failed. +# It lives as long as the mark it answers: the apply that empties a mark clears its +# record too. The whole-namespace reads leave these rows out. +SCIP_APPLIED_PREFIX = "scip_applied:" +# The module directories a tier's last pass could not build (its go harness could not +# fetch them, so no delta of theirs reached the watermark): `scip_unavailable:` +# holds them as a JSON list, and a mark of a file inside one is not retired — no apply +# covered that file. +SCIP_UNAVAILABLE_PREFIX = "scip_unavailable:" # A failed clone's reasons, as the mirror job writes them into the bootstrap stage's # `{"reason": ...}` detail; `code.repos` and `code.index_status` show only these, and # `CLONE_FAILED` for a reason in no shape the job writes. diff --git a/server/code/store/index/base.py b/server/code/store/index/base.py index abe1c680036..f30b4ae29bf 100644 --- a/server/code/store/index/base.py +++ b/server/code/store/index/base.py @@ -7,7 +7,12 @@ from typing import Any -from server.code.domain.index.state import SCIP_STALE_PREFIX, IndexState, StateEntry +from server.code.domain.index.state import ( + SCIP_APPLIED_PREFIX, + SCIP_STALE_PREFIX, + IndexState, + StateEntry, +) from server.code.store.index.rows import ( _TABLE_COLS, VERSION_INVARIANT_COLS, @@ -133,9 +138,10 @@ async def all_state(self, org: str, ns: str) -> IndexState: FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND NOT startsWith(state_key, {stale:String}) + AND NOT startsWith(state_key, {applied:String}) ORDER BY state_key """, - {"org": org, "ns": ns, "stale": SCIP_STALE_PREFIX}, + {"org": org, "ns": ns, "stale": SCIP_STALE_PREFIX, "applied": SCIP_APPLIED_PREFIX}, ) return { str(r["state_key"]): StateEntry( @@ -158,9 +164,14 @@ async def all_state_many( FROM loom.code_index_state FINAL WHERE (org, namespace) IN {pairs:Array(Tuple(String, String))} AND NOT startsWith(state_key, {stale:String}) + AND NOT startsWith(state_key, {applied:String}) ORDER BY org, namespace, state_key """, - {"pairs": [(str(o), str(n)) for o, n in pairs], "stale": SCIP_STALE_PREFIX}, + { + "pairs": [(str(o), str(n)) for o, n in pairs], + "stale": SCIP_STALE_PREFIX, + "applied": SCIP_APPLIED_PREFIX, + }, ) out: dict[tuple[str, str], IndexState] = {(str(o), str(n)): {} for o, n in pairs} for r in rows: @@ -203,6 +214,44 @@ async def set_states(self, org: str, ns: str, values: dict[str, str], detail: st ], ) + async def set_states_batch( + self, org: str, ns: str, values: dict[str, str], detail: str = "" + ) -> None: + """Several state rows of one namespace in one insert at one version, past every one + of their keys' newest rows: one read for the batch instead of one a key + (`set_states`). The floor is the batch's highest key, so it passes each key's own + newest row — the only thing a write needs — and a round of per-file records costs + one read rather than one a file. Empty values writes nothing. + """ + if not values: + return + row = await self._ch.query_one( + """ + SELECT greatest(toUInt64(toUnixTimestamp64Nano(now64(9))), max(version) + 1) AS v + FROM loom.code_index_state + WHERE org = {org:String} AND namespace = {ns:String} + AND state_key IN {keys:Array(String)} + """, + {"org": org, "ns": ns, "keys": sorted(values)}, + ) + version = int(row["v"]) if row else 1 + now = _now() + await self._ch.insert( + "loom.code_index_state", + [ + { + "org": org, + "namespace": ns, + "state_key": key, + "state_value": value, + "detail": detail, + "updated_at": now, + "version": version, + } + for key, value in values.items() + ], + ) + async def rewrite_state( self, org: str, ns: str, key: str, value: str, detail: str = "" ) -> None: diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index ae2f49e19d0..cdf1c613fe0 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -10,7 +10,7 @@ from clickhouse_connect.driver.binding import format_bind_value from server.code.domain.index.compiler_tiers import TIERS -from server.code.domain.index.state import SCIP_STALE_PREFIX +from server.code.domain.index.state import SCIP_APPLIED_PREFIX, SCIP_STALE_PREFIX from server.code.domain.index.test_gate import TEST_PATH_PATTERN from server.code.store.index.base import CodeRepoBase from server.code.store.index.sql import _batched, _hex, like_contains @@ -38,10 +38,12 @@ def _marks_in_force(keys: str) -> str: """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches `keys`. Only a build that writes marks empties one: its apply of the file, once every round of it has landed (`_mark_stale`), or, for an entry whose tier its worker runs, that - worker's pass once a later apply of the file is published (`retire_published_marks`); a - namespace fed by uploads alone has no such pass. A round writes its symbols and its edges - in separate inserts, so the rows of a build that predates the marks cannot show alone that - its apply of the file completed: a read leaves the mark counting.""" + worker's pass once the apply's own record of the file names the watermark's commit + (`retire_published_marks`, `scip_marks_retirable`); a namespace fed by uploads alone has + no such pass. A build that predates the marks writes no record, and its rows of the file + cannot stand in for one — an apply of it that rewrote no row of a file leaves what a + failed insert leaves — so its apply leaves the mark counting, and the mark ends when this + build applies the file.""" return f""" -- `scip_stale::`; a path may hold ':' itself SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path @@ -625,22 +627,28 @@ async def scip_stale_sample( return {str(r["path"]) for r in rows} async def scip_marks_retirable( - self, org: str, ns: str, tier: str, *, commit: str, rewritten: bool + self, org: str, ns: str, tier: str, *, commit: str ) -> dict[str, str]: - """`tier`'s marks in force whose file an apply published at `commit`, each path with - the commit its mark holds; with `rewritten`, only those whose file also holds a row - written after the mark (`retire_published_marks`). + """`tier`'s marks in force whose file an apply of this build published at `commit`, + each path with the commit its mark holds (`retire_published_marks`). - The evidence is the file's own record of both of an apply's inserts: a symbol row of - it stamped with `commit` and, when the store holds any edge row of the file at all, - an edge row of it stamped with that same commit. A file the tier writes no edge of is - not made to grow one — whether it has edges is read from the rows it holds. A file it - does write edges of keeps its mark while only one of the two inserts carries the - commit, which is what a partial apply leaves: its symbol insert lands stamped at the - commit, and a same-commit part or retry that moves the watermark to that commit makes - the symbol row alone look like a finished apply. What an apply did not write is not - evidence, and `code_scip_batches` expires: nothing here reads the absence of a - `failed` row as a sign that a file was published.""" + The evidence is the apply's own record, `scip_applied::` + (`SCIP_APPLIED_PREFIX`): `apply_delta` writes it after both of its inserts of the + file, so the row exists only for an apply that raised neither. A count of the + file's rows cannot stand in for it — an apply that rewrites a symbol row and + leaves the edge set unchanged writes no edge row at all (`_apply_round` skips an + empty edge insert, `_diff_edges` restamps no row it keeps), which is the same + shape a failed edge insert leaves — and neither can the watermark alone. + + The record must also be newer than the mark, `applied_at > marked`: a file an + earlier apply of the same commit published, then a delta skipped, holds a record + of the commit that says nothing about the skip. Both reads are `FINAL` and skip + emptied rows, so a superseded version of either row cannot answer. + + A file the previous build applied holds no record — that build writes none — so + its mark ends when this build applies the file (`_mark_stale`), not on the + previous build's rows (`_marks_in_force`). + """ rows = await self._ch.query_all( """ WITH marks AS ( @@ -651,47 +659,54 @@ async def scip_marks_retirable( WHERE org = {org:String} AND namespace = {ns:String} AND startsWith(state_key, {mark:String}) AND state_value != '' ), - symbols_written AS ( - SELECT path, countIf(indexed_commit = {commit:String}) AS stamped, - max(version) AS rewritten - FROM loom.code_symbols - WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' - AND path IN (SELECT path FROM marks) - GROUP BY path - ), - -- `held`: the file holds an edge row of this tier at all, at any version of it - -- (a tombstone too: the apply that wrote it wrote the file's edges) - edges_written AS ( - SELECT path, count() AS held, - countIf(indexed_commit = {commit:String}) AS stamped, - max(version) AS rewritten - FROM loom.code_edges - WHERE org = {org:String} AND namespace = {ns:String} AND tier = 'scip' - AND path IN (SELECT path FROM marks) - GROUP BY path + applied AS ( + -- `scip_applied::`: the apply's record that both of its + -- inserts of the file landed, at the commit it names + SELECT arrayStringConcat(arraySlice(splitByChar(':', state_key), 3), ':') AS path, + state_value AS applied_commit, version AS applied_at + FROM loom.code_index_state FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND startsWith(state_key, {applied:String}) AND state_value != '' ) SELECT marks.path AS path, marks.mark_commit AS mark_commit FROM marks - LEFT JOIN symbols_written AS symbols ON symbols.path = marks.path - LEFT JOIN edges_written AS edges ON edges.path = marks.path - WHERE ifNull(symbols.stamped, 0) > 0 - AND (ifNull(edges.held, 0) = 0 OR ifNull(edges.stamped, 0) > 0) - AND ( - {rewritten:UInt8} = 0 - OR greatest(ifNull(symbols.rewritten, 0), ifNull(edges.rewritten, 0)) - > marks.marked - ) + INNER JOIN applied ON applied.path = marks.path + WHERE applied.applied_commit = {commit:String} + AND applied.applied_at > marks.marked """, { "org": org, "ns": ns, "mark": f"{SCIP_STALE_PREFIX}{tier}:", + "applied": f"{SCIP_APPLIED_PREFIX}{tier}:", "commit": commit, - "rewritten": int(rewritten), }, ) return {str(r["path"]): str(r["mark_commit"]) for r in rows} + async def record_scip_applied( + self, org: str, ns: str, tier: str, commit: str, paths: list[str] + ) -> None: + """One insert: `scip_applied::` = `commit` for every path of a round + whose two inserts an apply has finished (`apply_delta` writes it last), so the + row's presence is that apply's record that neither raised. One narrow row per + marked file the round carried — a file with no mark is not written for, since no + reader asks about it — and one version for the batch, past every key's newest + row (`set_states_batch`).""" + await self.set_states_batch( + org, + ns, + {f"{SCIP_APPLIED_PREFIX}{tier}:{p}": commit for p in paths}, + ) + + async def clear_scip_marks(self, org: str, ns: str, tier: str, paths: list[str]) -> None: + """Empty the mark of each path of `tier`, and its applied record with it: a mark + and the record that answers it live and end together, so no later read joins a + record to a mark it was not written for. One insert for both families.""" + values = {f"{SCIP_STALE_PREFIX}{tier}:{p}": "" for p in paths} + values.update({f"{SCIP_APPLIED_PREFIX}{tier}:{p}": "" for p in paths}) + await self.set_states_batch(org, ns, values) + async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: one namespace-wide distinct read, taken once per full compiler run so diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index 4a460269346..5a18cf15a63 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -79,6 +79,7 @@ from server.code.app.index.output_mask import Unmasked from server.code.app.index.sandbox import tool_mounts from server.code.app.index.tier_health import error_text, note_unavailable +from server.code.domain.index.state import SCIP_UNAVAILABLE_PREFIX from server.code.domain.index.tier_health import ( REFUSAL_HELD, ) @@ -98,6 +99,11 @@ WATERMARK = "scip_commit_go" # module dir -> the base of the window it failed in ("" for a full run), as JSON RETRY = f"{WATERMARK}_retry" +# The modules the last pass could not fetch (`scip_unavailable:go`): a JSON list of their +# dirs. The worker passes such a module without a retry and without a delta, so no apply +# covered its files; `retire_published_marks` gates those modules' files and no others, +# where a note in the health record (`tier_health:go`, masked lines) cannot say which. +GATE = f"{SCIP_UNAVAILABLE_PREFIX}{PRODUCER}" _MODULE_FILES = ("go.mod", "go.sum") @@ -283,6 +289,34 @@ async def _known_retry( return kept +@dataclass(frozen=True) +class _Gate: + """The modules a pass left unbuilt at the watermark it wrote: `dirs` are the modules it + passed without an apply (a dependency this host could not fetch), `attempted` every + module it ran. A module keeps its gate until a pass attempts it again.""" + + dirs: frozenset[str] = frozenset() + attempted: frozenset[str] = frozenset() + + +async def _gate_dirs(repo: CodeRepo, cfg: RepoConfig) -> set[str]: + """The modules the last pass could not fetch, from the gate key (none when it holds + no list: a pass that built everything writes an empty one).""" + raw = await repo.get_state(cfg.org, cfg.namespace, GATE) + try: + listed = json.loads(raw) if raw else [] + except ValueError: + return set() + return {str(d) for d in listed if isinstance(d, str)} if isinstance(listed, list) else set() + + +async def _write_gate(repo: CodeRepo, cfg: RepoConfig, built: _Gate) -> None: + """Write the gate before the watermark: a module a pass could not fetch keeps its gate + until a pass attempts it, and one it built loses it whatever an earlier pass wrote.""" + keep = await _gate_dirs(repo, cfg) - built.attempted + await repo.set_state(cfg.org, cfg.namespace, GATE, json.dumps(sorted(keep | built.dirs))) + + async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResult) -> bool: """False when `run_tier` must keep the tier's record: the pass built nothing while a module failure or an `unavailable` note stands, it just noted one, or a held run's @@ -337,7 +371,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) return not await _kept_when_nothing_built(repo, cfg) - broken, unreachable, held, still_failing, applied = await _build( + broken, unreachable, held, still_failing, applied, gate = await _build( repo, cfg, checkout, runs, target, shape, result ) result.modules_skipped.extend(f"{cfg.namespace}: {line}" for line in broken + unreachable) @@ -345,6 +379,7 @@ async def _run_repo(repo: CodeRepo, cfg: RepoConfig, result: CodeScipGoDeltaResu if still_failing or retry: value = json.dumps(still_failing, sort_keys=True) if still_failing else "" await repo.set_state(cfg.org, cfg.namespace, RETRY, value) + await _write_gate(repo, cfg, gate) await repo.set_state(cfg.org, cfg.namespace, WATERMARK, target) result.deltas_applied += 1 logger.info( @@ -410,12 +445,13 @@ async def _build( target: str, shape: dict[str, object], result: CodeScipGoDeltaResult, -) -> tuple[list[str], list[str], list[str], dict[str, str], int]: +) -> tuple[list[str], list[str], list[str], dict[str, str], int, _Gate]: """Run the harness once per base in `runs` and apply each module's delta. Returns the module failure lines (masked) that fail the tier, those whose dependency cannot be fetched here, a line per module of a held run (`refusal_held`), the modules to - run again with the base each ran from (their dirs as printed), and the number of - deltas applied.""" + run again with the base each ran from (their dirs as printed), the number of deltas + applied, and which modules this pass left unbuilt (`_Gate`) — the unmasked split the + harness output gives, which is what the retirement gate is written from.""" from server.code.app.index.scip_delta import apply_delta failed: list[str] = [] @@ -423,6 +459,7 @@ async def _build( held: list[str] = [] still_failing: dict[str, str] = {} unfetched: dict[str, str] = {} + attempted: set[str] = set() applied = 0 for base, modules in sorted(runs.items()): if modules and await refusal_held(repo, cfg, WATERMARK, base, target, result, shape): @@ -448,6 +485,7 @@ async def _build( # The retry map keys the next pass's builds: only a module this run selected # enters it, whatever the output names. selected = {d or "." for d in expected} + attempted |= selected broken_dirs, unreachable_dirs = log.module_dirs() still_failing.update((m, base) for m in broken_dirs if m in selected) unfetched.update((m, base) for m in unreachable_dirs if m in selected) @@ -475,7 +513,14 @@ async def _build( # with it, so a retry that builds it alone cannot clear their note. if held or failed: still_failing.update(unfetched) - return sorted(failed), sorted(unreachable_lines), held, still_failing, applied + return ( + sorted(failed), + sorted(unreachable_lines), + held, + still_failing, + applied, + _Gate(frozenset(unfetched), frozenset(attempted)), + ) def _bin_dirs() -> list[str]: diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 32240c51dea..9317d22139f 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -560,8 +560,8 @@ async def test_a_pass_of_this_build_retires_a_mark_the_previous_build_published( and moves the watermark; `PY_BAD` never changes again. An apply whose edge insert fails also writes `PY_OTHER`'s symbols, and `PY_OTHER` is the same at both commits. The next pass of this build's Python worker, with nothing to index, empties the mark - of `PY_BAD`, both of whose inserts the apply stamped with the watermark's commit, and - keeps the other, whose blob did not move.""" + of `PY_BAD`, whose apply recorded it at the watermark's commit, and keeps the other, + whose blob did not move.""" org, ns = unique_org("scip-stale-retire"), "code-stale-retire" git_dir, (first, second, _) = _py_mirror(tmp_path) cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) @@ -592,15 +592,16 @@ async def no_marks(*a: Any) -> None: @pytest.mark.asyncio -async def test_a_mark_whose_apply_rewrote_no_row_keeps_itself( +async def test_a_mark_whose_apply_rewrote_no_row_is_retired( ch_client: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: - """This build applies `PY_BAD`, then a delta of the same commit skips it. The - previous build applies the next commit, which changes a function body alone: the - file's symbols and edges are the rows it already holds, so the apply rewrites none, - and it moves the watermark. The next pass of this build's Python worker keeps the - mark: no row of the file carries the new commit, so nothing records that an apply - published it there, and the mark ends when this build applies the file.""" + """This build applies `PY_BAD`, then a delta of the same commit skips it. The next + apply changes a function body alone: the file's symbols and edges are the rows it + already holds, so it rewrites none, and it moves the watermark. No row of the file + carries the new commit — a count of rows is the shape an insert that raised leaves, + so it cannot say the apply finished — and the apply's own record does: the next pass + of this build's Python worker empties the mark. The predicate this replaces kept it + for good, which is the mark no later apply of the file was going to end.""" org, ns = unique_org("scip-stale-body"), "code-stale-body" git_dir, (first, second, _) = _py_mirror(tmp_path) cfg = repo_config(org=org, namespace=ns, git_dir=git_dir) @@ -627,8 +628,8 @@ async def no_marks(*a: Any) -> None: assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD} await _python_pass(cfg, monkeypatch) - assert await repo.scip_stale_marks(org, ns, "python") == {PY_BAD} - assert await repo.scip_stale_paths(org, ns, [PY_BAD]) == {PY_BAD} + assert await repo.scip_stale_marks(org, ns, "python") == set() + assert await repo.scip_stale_paths(org, ns, [PY_BAD]) == set() async def _upload(org: str, ns: str, base: str, delta: ScipDelta) -> None: diff --git a/tests/unit/test_code_delta_stream.py b/tests/unit/test_code_delta_stream.py index 3d37da1265a..0c4fa8873f5 100644 --- a/tests/unit/test_code_delta_stream.py +++ b/tests/unit/test_code_delta_stream.py @@ -365,7 +365,7 @@ async def test_a_failed_apply_releases_the_file( _write(path, 30) delta = open_delta(path) - async def failing(*a: Any) -> None: + async def failing(*a: Any, **_: Any) -> None: raise RuntimeError("clickhouse down") monkeypatch.setattr(scip_delta, "_apply_files", failing) diff --git a/tests/unit/test_code_repos_batched_state.py b/tests/unit/test_code_repos_batched_state.py index 4a984a9570d..a5dbdc0031a 100644 --- a/tests/unit/test_code_repos_batched_state.py +++ b/tests/unit/test_code_repos_batched_state.py @@ -70,6 +70,8 @@ async def test_all_state_many_reads_every_namespace_in_one_statement() -> None: assert ch.params[0] == { "pairs": [("o", "a"), ("o", "b"), ("o", "empty")], "stale": "scip_stale:", + # a round's per-file apply records are not entry state + "applied": "scip_applied:", } assert out[("o", "a")]["git_head"]["value"] == "aaa" assert out[("o", "a")]["table_counts"]["detail"] == "aaa||" diff --git a/tests/unit/test_code_scip_mark_retirement.py b/tests/unit/test_code_scip_mark_retirement.py index 9b5d8c2503f..fc13bb95107 100644 --- a/tests/unit/test_code_scip_mark_retirement.py +++ b/tests/unit/test_code_scip_mark_retirement.py @@ -1,339 +1,463 @@ -"""A stale mark retires only on positive evidence that an apply of the file finished. - -`retire_published_marks` used to read the absence of a `failed` batch row as proof that -nothing had failed, so a partial apply — symbols in, the edge insert raised, a later batch -moving the watermark past that file — and a namespace whose batch records aged out both -emptied the mark. Both read the same now: the file must hold a compiler-tier symbol row -stamped with the watermark's commit, and, when the store holds any compiler-tier edge row -of it, an edge row stamped with that same commit — an apply's own record that both of its -inserts wrote the file there — or every mark stays. Real SQL on clickhouse-local: the rows below are the tables' own definitions, -and a retirement's write is its payload (the store insert needs a server this suite has -not). +"""A stale mark retires on the apply's own record that it published the file, and on +nothing else. + +`retire_published_marks` used to read the file's rows: a compiler-tier symbol row stamped +with the watermark's commit, and — when the store held any edge row of the file — an edge +row stamped with that same commit. A count of rows cannot say that an apply finished. An +apply that rewrites a symbol row and leaves the edge set unchanged writes no edge row at +all (`_apply_round` skips an empty edge insert, `_diff_edges` restamps no row it keeps), +so `held > 0, stamped = 0` — a whole apply — is the shape a failed edge insert leaves, +which is the one state the mark exists to catch. `held` was `count()` with no `FINAL` and +no tombstone filter and `tombstone_of` copies the old `indexed_commit`, so a file whose +edges were legitimately removed was held to the strict limb forever; neither aggregation +carried `FINAL`, so a superseded symbol version could answer for the live one. + +Now the apply writes one row per marked file it carried, last of the round's writes — +`scip_applied::` = the commit — so its presence is the record that both +inserts of the round landed. The predicate reads that row: `FINAL`, non-empty, naming the +watermark's commit, and newer than the mark. Real SQL on clickhouse-local, and the writes +are real too: a kept database holds what `apply_delta` inserted, so each case is an apply +and then a retirement over the rows it left. """ from __future__ import annotations -import asyncio import json from types import SimpleNamespace from typing import Any import pytest -from server.code.app.index import gitrepo -from server.code.app.index.scip_delta import retire_published_marks +from server.code.app.index import gitrepo, scip_delta +from server.code.app.index.scip_delta import ( + ScipDelta, + ScipEdge, + ScipFile, + ScipSymbol, + apply_delta, + retire_published_marks, +) from server.code.domain.index import repos from server.code.store.index import CodeRepo from tests.unit import clickhouse_local +pytestmark = pytest.mark.skipif( + clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed" +) + ORG, NS = "o", "n" C0 = "a" * 40 C1 = "b" * 40 C2 = "c" * 40 -BATCH = "6f1e2b7c-0000-4000-8000-000000000001" +C3 = "d" * 40 PATH = "src/a.cc" DDL = ( + "SET enable_quantized_codec = 1", + clickhouse_local.ddl("code_chunks"), clickhouse_local.ddl("code_index_state"), clickhouse_local.ddl("code_symbols"), clickhouse_local.ddl("code_edges"), - clickhouse_local.ddl("code_scip_batches"), ) -def _lit(value: Any) -> str: - if value is None: - return "NULL" - if isinstance(value, int): - return str(value) - return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'" +def _world(tmp_path: Any, monkeypatch: pytest.MonkeyPatch, blobs: dict[tuple[str, str], bytes]): + """A kept database with the tables an apply writes and a retirement reads, the repo + over it, and a mirror holding `blobs` at `(commit, path)` whose commits all exist.""" + ch = clickhouse_local.KeptCH(tmp_path / "ch", *DDL) + async def has_commit(_git_dir: str, _commit: str) -> bool: + return True -def _insert(table: str, rows: list[dict[str, Any]]) -> str: - cols = list(rows[0]) - values = ", ".join("(" + ", ".join(_lit(r[c]) for c in cols) + ")" for r in rows) - return f"INSERT INTO loom.{table} ({', '.join(cols)}) VALUES {values}" + async def blob_ids(_git_dir: str, pairs: list[tuple[str, str]]) -> list[bytes | None]: + return [blobs.get((commit, path)) for commit, path in pairs] + async def blob_paths_at(_git_dir: str, commit: str, paths: Any) -> set[str]: + return {p for p in paths if (commit, p) in blobs} -def _mark(tier: str, commit: str, *, path: str = PATH, version: int = 1500) -> dict[str, Any]: - return { - "org": ORG, - "namespace": NS, - "state_key": f"scip_stale:{tier}:{path}", - "state_value": commit, - "detail": "", - "version": version, - } + monkeypatch.setattr(gitrepo, "has_commit", has_commit) + monkeypatch.setattr(gitrepo, "blob_ids", blob_ids) + monkeypatch.setattr(gitrepo, "blob_paths_at", blob_paths_at) + monkeypatch.setattr( + repos, "repo_for_namespace", lambda org, ns: SimpleNamespace(git_dir="/mirror") + ) + return ch, CodeRepo(ch) + + +def _file( + commit: str, *, path: str = PATH, doc: str = "", edges: int = 1, edge_line: int = 2 +) -> ScipFile: + return ScipFile( + path=path, + symbols=[ScipSymbol(qualified_name="a::f", line_start=1, line_end=3, doc=doc)], + edges=[ + ScipEdge( + from_qualified_name="a::f", + to_qualified_name=f"a::callee{i}", + line=edge_line, + ) + for i in range(edges) + ], + ) -def _watermark(key: str, commit: str, *, detail: str = "", version: int = 2000) -> dict[str, Any]: - return { - "org": ORG, - "namespace": NS, - "state_key": key, - "state_value": commit, - "detail": detail, - "version": version, - } +def _previous_build(monkeypatch: pytest.MonkeyPatch) -> None: + """The previous build's apply: it writes rows and moves the watermark, and writes no + marks (it knows none), so the mark a newer build left survives it.""" + async def no_marks(*a: Any) -> None: + return None -def _batch(status: str, *, commit: str = C1, version: int = 1200) -> dict[str, Any]: - return { - "org": ORG, - "namespace": NS, - "batch_id": BATCH, - "commit_sha": commit, - "status": status, - "producer": "clang", - "version": version, - } + monkeypatch.setattr(scip_delta, "_mark_stale", no_marks) -def _symbol(*, stamped: str = "", path: str = PATH, version: int = 3000) -> dict[str, Any]: - return { - "org": ORG, - "namespace": NS, - "tier": "scip", - "qualified_name": f"f::{path}", - "symbol_id": f"s::{path}", - "path": path, - "indexed_commit": stamped, - "version": version, - } +async def _apply( + repo: CodeRepo, + delta: ScipDelta, + *, + tier: str = "clang", + watermark: str | None = None, + previous: bool = False, +) -> None: + """One apply, and the tier's watermark after it. `previous` runs it as the previous + build does: rows and watermark, no marks (`_previous_build`).""" + with pytest.MonkeyPatch.context() as ctx: + if previous: + _previous_build(ctx) + await apply_delta(repo, ORG, NS, delta, tier=tier) + if watermark is not None: + await repo.set_state(ORG, NS, watermark, delta.commit) -def _edge(*, stamped: str = "", path: str = PATH, version: int = 3000) -> dict[str, Any]: - return { - "org": ORG, - "namespace": NS, - "tier": "scip", - "edge_kind": "calls", - "to_symbol_id": "s::callee", - "from_symbol_id": f"s::{path}", - "path": path, - "indexed_commit": stamped, - "version": version, - } +async def _retire( + repo: CodeRepo, *, tier: str = "clang", watermark: str = "scip_commit" +) -> set[str]: + return await retire_published_marks(repo, ORG, NS, tier, watermark) -def _health(tier: str, state: str) -> dict[str, Any]: - record = { - "state": state, - "kind": "dependency_unavailable" if state == "unavailable" else "", - "error": "", - "fix": "", - "failing_since": "", - "last_failed_at": "", - "failed_passes": 0, - "last_ok_at": "", - } +def _state(*rows: dict[str, Any]) -> list[dict[str, Any]]: + return list(rows) + + +def _row(key: str, value: str, *, version: int) -> dict[str, Any]: return { "org": ORG, "namespace": NS, - "state_key": f"tier_health:{tier}", - "state_value": json.dumps(record), + "state_key": key, + "state_value": value, "detail": "", - "version": 2100, + "version": version, } -class _Local: - """clickhouse-local for the reads; the state writes recorded, since the store's insert - needs a server. What a retirement writes is its payload.""" +# ---------------------------------------------------------------- red-then-green +# (a) a doc-only apply retires its mark - def __init__(self, *setup: str) -> None: - self.local = clickhouse_local.LocalCH(*setup) - self.writes: list[tuple[str, list[dict[str, Any]]]] = [] - async def query_all(self, sql: str, params: dict[str, Any] | None = None, **kw: Any) -> Any: - return await self.local.query_all(sql, params, **kw) +async def test_a_doc_only_apply_retires_its_mark(monkeypatch: pytest.MonkeyPatch, tmp_path: Any): + """The file holds one edge; the apply rewrites one symbol row (its doc comment) and + leaves the edge set alone, so it writes no edge row. At the old predicate that is + `held = 1, stamped = 0` — the shape of an edge insert that raised — and the mark is + kept for good. The apply's record says both inserts landed, and the mark goes.""" + _, repo = _world( + tmp_path, monkeypatch, {(C1, PATH): b"one", (C2, PATH): b"two", (C3, PATH): b"three"} + ) + await _apply(repo, ScipDelta(commit=C1, files=[_file(C1)])) + await _apply(repo, ScipDelta(commit=C2, skipped_files=[PATH]), watermark="scip_commit") + assert await repo.scip_stale_marks(ORG, NS, "clang") == {PATH} + + await _apply( + repo, + ScipDelta(commit=C3, files=[_file(C3, doc="changed")]), + watermark="scip_commit", + previous=True, + ) + live = await repo.live_edges_for_paths(ORG, NS, [PATH], "scip") + assert len(live[PATH]) == 1 # the edge is still there, restamped by nobody + assert [r["indexed_commit"] for r in live[PATH]] == [C1] - async def query_one(self, sql: str, params: dict[str, Any] | None = None, **kw: Any) -> Any: - return await self.local.query_one(sql, params, **kw) + assert await _retire(repo) == {PATH} + assert await repo.scip_stale_marks(ORG, NS, "clang") == set() + assert await repo.get_state(ORG, NS, f"scip_applied:clang:{PATH}") == "" - async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: - self.writes.append((table, rows)) +# (b) an apply that leaves the edge set unchanged retires -def _ch(*rows: tuple[str, dict[str, Any]]) -> _Local: - by_table: dict[str, list[dict[str, Any]]] = {} - for table, row in rows: - by_table.setdefault(table, []).append(row) - return _Local(*DDL, *(_insert(table, rs) for table, rs in by_table.items())) +async def test_an_apply_that_rewrites_no_row_retires_its_mark( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +): + """The same file, byte for byte: the apply writes no row of either table — nothing + changed, which is what a function body alone does — and the old predicate has no + stamp to read at all. The record is written whatever the diff wrote.""" + ch, repo = _world( + tmp_path, monkeypatch, {(C1, PATH): b"one", (C2, PATH): b"two", (C3, PATH): b"three"} + ) + await _apply(repo, ScipDelta(commit=C1, files=[_file(C1)])) + await _apply(repo, ScipDelta(commit=C2, skipped_files=[PATH]), watermark="scip_commit") + before = ( + await repo.live_symbols_for_paths(ORG, NS, [PATH], "scip"), + await repo.live_edges_for_paths(ORG, NS, [PATH], "scip"), + ) + await _apply( + repo, + ScipDelta(commit=C3, files=[_file(C3)]), + watermark="scip_commit", + previous=True, + ) + after = ( + await repo.live_symbols_for_paths(ORG, NS, [PATH], "scip"), + await repo.live_edges_for_paths(ORG, NS, [PATH], "scip"), + ) + assert after == before # no row of the file carries C3 -def _mirror(monkeypatch: pytest.MonkeyPatch, blobs: dict[tuple[str, str], bytes]) -> None: - """A mirror holding `blobs` at `(commit, path)`, its commits all present.""" + assert await _retire(repo) == {PATH} + assert await repo.get_state(ORG, NS, f"scip_applied:clang:{PATH}") == "" - async def has_commit(_git_dir: str, _commit: str) -> bool: - return True - async def blob_ids(_git_dir: str, pairs: list[tuple[str, str]]) -> list[bytes | None]: - return [blobs.get((commit, path)) for commit, path in pairs] +# (c) a file whose edges are all tombstoned is not held - monkeypatch.setattr(gitrepo, "has_commit", has_commit) - monkeypatch.setattr(gitrepo, "blob_ids", blob_ids) - monkeypatch.setattr( - repos, "repo_for_namespace", lambda org, ns: SimpleNamespace(git_dir="/mirror") + +async def test_a_file_whose_edges_are_all_tombstoned_is_not_held( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +): + """The apply drops both edges: its tombstones copy the old `indexed_commit`, so at the + old predicate `count()` sees two rows and `stamped` sees none — `held` meant "ever had + an edge". The file holds no live edge now, and its apply's record says the insert of + the empty set landed.""" + ch, repo = _world( + tmp_path, monkeypatch, {(C1, PATH): b"one", (C2, PATH): b"two", (C3, PATH): b"three"} + ) + await _apply(repo, ScipDelta(commit=C1, files=[_file(C1, edges=2)])) + await _apply(repo, ScipDelta(commit=C2, skipped_files=[PATH]), watermark="scip_commit") + await _apply( + repo, + ScipDelta(commit=C3, files=[_file(C3, doc="changed", edges=0)]), + watermark="scip_commit", + previous=True, ) + live = await repo.live_edges_for_paths(ORG, NS, [PATH], "scip") + assert live.get(PATH, []) == [] + every = await ch.query_all( + "SELECT count() AS n, countIf(indexed_commit = {c:String}) AS at_c3 " + "FROM loom.code_edges WHERE org = {o:String} AND namespace = {n:String}", + {"c": C3, "o": ORG, "n": NS}, + ) + # four rows: two live at C1 and the two tombstones that replaced them, each copying + # the commit it tombstones — so a count of rows at C3 is none, and `held` was 4 + assert every == [{"n": 4, "at_c3": 0}] + assert await _retire(repo) == {PATH} -def _retire(ch: _Local, tier: str = "clang", watermark: str = "scip_commit") -> set[str]: - return asyncio.run(retire_published_marks(CodeRepo(ch), ORG, NS, tier, watermark)) +# (d) a superseded version does not answer -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_a_partial_apply_that_published_symbols_keeps_the_mark( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # The apply wrote the file's symbols stamped `C1`, its edge insert raised, and a later - # batch moved the watermark to `C2`: no row of the file carries `C2`, so no record says - # the file's apply finished, however new its symbols are. - ch = _ch( - ("code_index_state", _mark("clang", C0)), - ("code_scip_batches", _batch("failed", commit=C1)), - ("code_symbols", _symbol(stamped=C1)), - ("code_index_state", _watermark("scip_commit", C2, detail=BATCH)), + +async def test_a_superseded_record_version_does_not_retire( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +): + """An apply of the watermark's commit wrote the record, and a later apply emptied it + (the mark it answered was replaced). The superseded row still names the commit, and a + read that does not take `FINAL` joins it: the mark goes on a record that is no longer + live. `FINAL` reads the emptied row and the mark stays.""" + ch, repo = _world( + tmp_path, + monkeypatch, + {(C1, PATH): b"old", (C2, PATH): b"new"}, + ) + await ch.insert( + "loom.code_index_state", + _state( + _row(f"scip_stale:clang:{PATH}", C1, version=1500), + _row(f"scip_applied:clang:{PATH}", C2, version=3000), + _row(f"scip_applied:clang:{PATH}", "", version=3100), + _row("scip_commit", C2, version=2000), + ), + ) + # the rows the old predicate read: both of the apply's inserts stamped, so it retires + await ch.insert( + "loom.code_symbols", + [ + { + "org": ORG, + "namespace": NS, + "tier": "scip", + "qualified_name": f"f::{PATH}", + "symbol_id": f"s::{PATH}", + "path": PATH, + "indexed_commit": C2, + "version": 3200, + } + ], ) - _mirror(monkeypatch, {(C0, PATH): b"old", (C2, PATH): b"new"}) - - assert _retire(ch) == set() - assert ch.writes == [] - - -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_the_reapply_with_edges_empties_the_mark(monkeypatch: pytest.MonkeyPatch) -> None: - # The same file applied again, every round in and stamped with the commit that moved - # the watermark: the mark goes. - ch = _ch( - ("code_index_state", _mark("clang", C0)), - ("code_scip_batches", _batch("applied", commit=C2)), - ("code_symbols", _symbol(stamped=C2)), - ("code_edges", _edge(stamped=C2)), - ("code_index_state", _watermark("scip_commit", C2, detail=BATCH)), + await ch.insert( + "loom.code_edges", + [ + { + "org": ORG, + "namespace": NS, + "tier": "scip", + "edge_kind": "calls", + "to_symbol_id": "s::callee", + "from_symbol_id": f"s::{PATH}", + "path": PATH, + "indexed_commit": C2, + "version": 3200, + } + ], ) - _mirror(monkeypatch, {(C0, PATH): b"old", (C2, PATH): b"new"}) - assert _retire(ch) == {PATH} - ((table, rows),) = ch.writes - assert table == "loom.code_index_state" - assert [(r["state_key"], r["state_value"]) for r in rows] == [(f"scip_stale:clang:{PATH}", "")] + assert await _retire(repo) == set() + assert await repo.scip_stale_marks(ORG, NS, "clang") == {PATH} -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_a_symbol_stamp_alone_keeps_the_mark_of_a_file_that_holds_edges( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # A symbol row of the file stamped `C1` and the watermark at `C1` — a same-commit part - # or retry moved it there — while the file's edges still carry the mark's commit. The - # symbol insert landing is no record that the edge insert of that apply landed: the - # mark stays, and the file's edges are what the next apply has to stamp. - ch = _ch( - ("code_index_state", _mark("clang", C0)), - ("code_symbols", _symbol(stamped=C1)), - ("code_edges", _edge(stamped=C0)), - ("code_index_state", _watermark("scip_commit", C1)), +# (e) the Go freeze names modules + + +async def test_a_go_file_outside_an_unfetched_module_retires( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +): + """`mod_a` is a module this host cannot fetch; `mod_b` built. The health record notes + the entry unavailable, its text masked and clipped — the old read froze every Go mark + of the entry on it. The gate key names `mod_a`, so only its files keep their marks.""" + ch, repo = _world( + tmp_path, + monkeypatch, + { + (C1, "mod_a/x.go"): b"old", + (C2, "mod_a/x.go"): b"new", + (C1, "mod_b/y.go"): b"old", + (C2, "mod_b/y.go"): b"new", + }, + ) + await ch.insert( + "loom.code_index_state", + _state( + _row("scip_stale:go:mod_a/x.go", C1, version=1500), + _row("scip_stale:go:mod_b/y.go", C1, version=1500), + _row("scip_applied:go:mod_a/x.go", C2, version=3000), + _row("scip_applied:go:mod_b/y.go", C2, version=3000), + _row("scip_commit_go", C2, version=2000), + _row("scip_unavailable:go", json.dumps(["mod_a"]), version=2500), + _row( + "tier_health:go", + json.dumps( + { + "state": "unavailable", + "kind": "dependency_unavailable", + "error": "mod_a: cannot fetch …", + "fix": "", + "failing_since": "", + "last_failed_at": "", + "failed_passes": 0, + "last_ok_at": "", + } + ), + version=2100, + ), + ), ) - _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) - assert ( - asyncio.run(CodeRepo(ch).scip_marks_retirable(ORG, NS, "clang", commit=C1, rewritten=False)) - == {} + assert await _retire(repo, tier="go", watermark="scip_commit_go") == {"mod_b/y.go"} + assert await repo.scip_stale_marks(ORG, NS, "go") == {"mod_a/x.go"} + + +async def test_a_retried_module_freezes_only_its_own_files( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +): + """A module that failed to build is in the retry map: its files keep their marks, and + the entry's other modules' files retire on their records. One module's retry is no + reason to keep every mark of the entry.""" + ch, repo = _world( + tmp_path, + monkeypatch, + { + (C1, "mod_a/x.go"): b"old", + (C2, "mod_a/x.go"): b"new", + (C1, "mod_b/y.go"): b"old", + (C2, "mod_b/y.go"): b"new", + }, ) - assert _retire(ch) == set() - assert ch.writes == [] - - -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_an_edge_stamp_alone_keeps_the_mark_too(monkeypatch: pytest.MonkeyPatch) -> None: - # The mirror of the case above: a round publishes the file's edges and its symbol insert - # raises, so the symbols carry the mark's commit and the edges the watermark's. Neither - # insert stands for the other, so this mark stays too. - ch = _ch( - ("code_index_state", _mark("clang", C0)), - ("code_symbols", _symbol(stamped=C0)), - ("code_edges", _edge(stamped=C1)), - ("code_index_state", _watermark("scip_commit", C1)), + await ch.insert( + "loom.code_index_state", + _state( + _row("scip_stale:go:mod_a/x.go", C1, version=1500), + _row("scip_stale:go:mod_b/y.go", C1, version=1500), + _row("scip_applied:go:mod_a/x.go", C2, version=3000), + _row("scip_applied:go:mod_b/y.go", C2, version=3000), + _row("scip_commit_go", C2, version=2000), + _row("scip_commit_go_retry", json.dumps({"mod_a": ""}), version=2400), + ), ) - _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) - assert _retire(ch) == set() - assert ch.writes == [] + assert await _retire(repo, tier="go", watermark="scip_commit_go") == {"mod_b/y.go"} -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_a_parser_tier_edge_of_the_file_is_no_edge_of_the_compiler_tier( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # The file holds an edge every indexed file has — the parser tier's — and the compiler - # tier wrote none of it (a header of declarations). Whether the file has edges is read - # from the compiler tier's rows: its apply had no edge to write, so its symbol row at the - # watermark is the whole record the file can carry and the mark goes. - ch = _ch( - ("code_index_state", _mark("clang", C0)), - ("code_symbols", _symbol(stamped=C1)), - ("code_edges", _edge(stamped=C0) | {"tier": "treesitter"}), - ("code_index_state", _watermark("scip_commit", C1)), +# the guarantee the record exists for +async def test_an_edge_insert_that_raised_leaves_no_record( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +): + """The round's symbol insert lands and its edge insert raises. The record is written + after both, so the raise leaves none, and the mark stays however new the symbol row + is — the state a count of rows cannot tell from an unchanged file.""" + ch, repo = _world( + tmp_path, monkeypatch, {(C1, PATH): b"old", (C2, PATH): b"two", (C3, PATH): b"new"} ) - _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) + await _apply(repo, ScipDelta(commit=C1, files=[_file(C1)])) + await _apply(repo, ScipDelta(commit=C2, skipped_files=[PATH])) + + insert_rows = CodeRepo.insert_rows + + async def edges_fail(self: CodeRepo, table: str, rows: list[dict[str, Any]]) -> None: + if table == "code_edges": + raise ConnectionError("edge insert failed") + await insert_rows(self, table, rows) + + monkeypatch.setattr(CodeRepo, "insert_rows", edges_fail) + with pytest.raises(ConnectionError): + # a moved edge line: the round does write an edge row, and the insert of it raises + await apply_delta( + repo, + ORG, + NS, + ScipDelta(commit=C3, files=[_file(C3, doc="new", edge_line=3)]), + tier="clang", + ) + monkeypatch.undo() - assert _retire(ch) == {PATH} + symbols = await repo.live_symbols_for_paths(ORG, NS, [PATH], "scip") + assert [r["indexed_commit"] for r in symbols[PATH]] == [C3] # the symbol insert landed + assert await repo.get_state(ORG, NS, f"scip_applied:clang:{PATH}") == "" + await repo.set_state(ORG, NS, "scip_commit", C3) + assert await _retire(repo) == set() + assert await repo.scip_stale_marks(ORG, NS, "clang") == {PATH} -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_a_mark_with_no_row_at_the_watermarks_commit_keeps_itself( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # The namespace holds no batch row at all (they expired, or a worker applied) and the - # file's rows were stamped at the mark's commit: the absence of a failure is no record - # that the file was published, so the mark stays. - ch = _ch( - ("code_index_state", _mark("clang", C0)), - ("code_symbols", _symbol(stamped=C0)), - ("code_edges", _edge(stamped=C0)), - ("code_index_state", _watermark("scip_commit", C1)), - ) - _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) - assert _retire(ch) == set() - assert ch.writes == [] +async def test_the_record_is_the_rounds_last_write(monkeypatch: pytest.MonkeyPatch, tmp_path: Any): + """`scip_applied` is inserted after the round's symbols and its edges, in the same + coroutine: an insert of either that raised aborts before it.""" + ch, repo = _world(tmp_path, monkeypatch, {(C1, PATH): b"old", (C2, PATH): b"two"}) + await _apply(repo, ScipDelta(commit=C1, skipped_files=[PATH])) + order: list[str] = [] + insert_rows = CodeRepo.insert_rows + insert = ch.insert -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_a_file_with_no_edges_needs_only_its_symbol_stamp() -> None: - # A file the compiler tier writes no edge of (a header of declarations, a file of - # constants): its apply's edge insert had nothing to write, so its symbol row at the - # watermark is the whole record the file can carry, and it is enough. - repo = CodeRepo( - _ch( - ("code_index_state", _mark("clang", C0)), - ("code_symbols", _symbol(stamped=C1)), - ) - ) - assert asyncio.run(repo.scip_marks_retirable(ORG, NS, "clang", commit=C1, rewritten=False)) == { - PATH: C0 - } - assert ( - asyncio.run(repo.scip_marks_retirable(ORG, NS, "clang", commit=C2, rewritten=False)) == {} - ) - + async def record_insert_rows(self: CodeRepo, table: str, rows: list[dict[str, Any]]) -> None: + order.append(table) + await insert_rows(self, table, rows) -@pytest.mark.skipif(clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed") -def test_the_go_tier_retires_no_mark_while_its_record_notes_an_unfetched_dependency( - monkeypatch: pytest.MonkeyPatch, -) -> None: - # The worker passed a module it could not fetch, so a mark in it was applied by no - # one, whatever the watermark says; the same rows with the note cleared retire. - rows = ( - ("code_index_state", _mark("go", C0)), - ("code_scip_batches", _batch("applied", commit=C1)), - ("code_symbols", _symbol(stamped=C1)), - ("code_index_state", _watermark("scip_commit_go", C1, detail=BATCH)), - ) - _mirror(monkeypatch, {(C0, PATH): b"old", (C1, PATH): b"new"}) + async def record_insert(table: str, rows: list[dict[str, Any]], *a: Any, **kw: Any) -> None: + # the record is the non-empty row; `_mark_stale`'s clearing of it comes after + if table == "loom.code_index_state" and any( + str(r.get("state_key", "")).startswith("scip_applied:") and r.get("state_value") + for r in rows + ): + order.append("scip_applied") + await insert(table, rows, *a, **kw) - noted = _ch(*rows, ("code_index_state", _health("go", "unavailable"))) - assert _retire(noted, "go", "scip_commit_go") == set() - assert noted.writes == [] + monkeypatch.setattr(CodeRepo, "insert_rows", record_insert_rows) + monkeypatch.setattr(ch, "insert", record_insert) + await _apply(repo, ScipDelta(commit=C1, files=[_file(C1)])) - cleared = _ch(*rows, ("code_index_state", _health("go", "ok"))) - assert _retire(cleared, "go", "scip_commit_go") == {PATH} + assert order == ["code_symbols", "code_edges", "scip_applied"] diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index d813c698c4b..aa212bd05e0 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -72,8 +72,9 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( monkeypatch: pytest.MonkeyPatch, ) -> None: """Each skipped file the entry keeps is marked under the applying tier, whatever its - suffix, and the mark of each file this delta applies or deletes is emptied. An - out-of-scope or refused path is never marked: no delta would clear it.""" + suffix, and the mark of each file this delta applies or deletes is emptied, with the + applied record that answered it — one insert for both, so no record outlives its + mark. An out-of-scope or refused path is never marked: no delta would clear it.""" monkeypatch.setattr(scip_delta, "_apply_files", AsyncMock()) monkeypatch.setattr(scip_delta, "_indexable_prefixes", lambda *a: ("src/",)) monkeypatch.setattr( @@ -98,6 +99,8 @@ async def test_one_apply_marks_and_clears_its_tiers_files_in_one_insert( "scip_stale:clang:src/k.cu": "c" * 40, "scip_stale:clang:src/a.cpp": "", "scip_stale:clang:src/gone.cpp": "", + "scip_applied:clang:src/a.cpp": "", + "scip_applied:clang:src/gone.cpp": "", }, ) @@ -131,6 +134,8 @@ async def test_a_skipped_path_that_files_or_deleted_files_name_keeps_its_rows_an "scip_stale:clang:src/lost.cpp": "c" * 40, "scip_stale:clang:src/b.cpp": "", "scip_stale:clang:src/gone.cpp": "", + "scip_applied:clang:src/b.cpp": "", + "scip_applied:clang:src/gone.cpp": "", }, ) diff --git a/tests/unit/test_code_scip_ts_delta_worker.py b/tests/unit/test_code_scip_ts_delta_worker.py index 4155c9d03dd..c8ad4cb58f6 100644 --- a/tests/unit/test_code_scip_ts_delta_worker.py +++ b/tests/unit/test_code_scip_ts_delta_worker.py @@ -292,7 +292,7 @@ async def fake_harness(co, base, head, delta_path, projects=(), **_): applied: list[tuple[str, bool]] = [] - async def fake_apply_files(repo, org, ns, commit, files, stats): + async def fake_apply_files(repo, org, ns, commit, files, stats, **_: Any): applied.extend((f.path, f.deleted) for f in files) monkeypatch.setattr(w, "git", fake_git) From b5ff7baf6876ed9ee02ad5cb0844001dc766f076 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 11:23:08 +0000 Subject: [PATCH 57/81] The coverage the retirement review asked for, and one record write MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The construction was accepted; what guarded it was not. Four gaps, closed by tests that fail when the thing they name is flipped, and one duplicate that let the record's paths be chosen in two places. The Go gate (`scip_unavailable:go`) had no test: nothing named the key, so the wrong dirs or a fetched module keeping its gate would have passed. Three tests now drive real passes: a pass over three modules with two unfetched writes both dirs and not the built one, and the next pass, which attempts one of them, rebases the gate as `previous - attempted`; a module fetched again leaves the gate empty; and the row the pass writes is read back by `_unbuilt_modules`, so the unfetched module's files are held and a file outside every dir the gate names is not. Mutating the gate to name `attempted` fails all three (`assert ['lib', 'mod_a', 'mod_b'] == ['mod_a', 'mod_b']`). `applied_at > marked` was asserted only with the record newer than the mark. The same two rows with the versions swapped — a mark written after an apply of the same commit — are now parametrized: the mark-newer case is kept, the record-newer case retires. Flipping `>` to `<` fails both. `_record_applied` chose nothing before: `_apply_round` filtered `paths` through `marked` and `_apply_file`'s `sink is None` fallback wrote its own conditional. Both pass their paths and the marked set to one helper, which picks the record's files; the fallback needs no difference, so it has none. The test that asserted `["code_symbols", "code_edges", "scip_applied"]` read a call order. It now reads the row back: live under FINAL, holding the apply's commit, newer than the mark, and the mark it retires on the next pass. The order stays pinned by the keep-guard, which fails when the record is written before the inserts: the edge insert raises and a record of a round that never landed is left (`assert 'dddd…' == ''`). The operations table still promised that "the next delta that converts the file clears the mark". An N-1 delta neither reads nor empties a mark, so it now says the delta that carries the file without skipping it empties the mark and N-1 neither reads nor empties one (rule 70). Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 2 +- server/code/app/index/scip_delta.py | 24 ++--- tests/unit/test_code_scip_go_delta_worker.py | 92 +++++++++++++++++++ tests/unit/test_code_scip_mark_retirement.py | 93 ++++++++++++++------ 4 files changed, 173 insertions(+), 38 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 58a83b8ee38..0fdb56b2439 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1465,7 +1465,7 @@ the output to read. | compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | | a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | | compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | -| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window, and so is a window file with a factory call, whose constructor may be in the skipped document (`code.callers` and `code.callees` name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that converts the file clears the mark | +| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window, and so is a window file with a factory call, whose constructor may be in the skipped document (`code.callers` and `code.callees` name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that carries the file without skipping it empties the mark, and N-1 neither reads nor empties one (rule 70) | | a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | | GitHub rate limit | the pass ends, cursor unmoved | the next pass | | branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 851be0f2688..b085f26c50f 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -479,18 +479,20 @@ async def _published(repo: Any, org: str, ns: str, tier: str, watermark: str) -> async def _record_applied( - repo: Any, org: str, ns: str, tier: str, commit: str, paths: list[str] + repo: Any, org: str, ns: str, tier: str, commit: str, paths: list[str], marked: set[str] ) -> None: """The round's last write: `scip_applied::` = `commit` for each of the - round's marked files. It runs after both of the round's inserts, in this coroutine, so - its presence is the record that neither raised — an insert that raised leaves none and - the mark stays (`retire_published_marks`). A file the round rewrote no row of is - recorded too: its apply did reach it, and that is exactly what the count of its rows - cannot say.""" - if not paths: + round's `paths` that is `marked` — the one place the record's paths are chosen, for a + round and for a file applied alone. It runs after both of the round's inserts, in this + coroutine, so its presence is the record that neither raised — an insert that raised + leaves none and the mark stays (`retire_published_marks`). A file the round rewrote no + row of is recorded too: its apply did reach it, and that is exactly what the count of + its rows cannot say.""" + owed = sorted(p for p in paths if p in marked) + if not owed: return check_held() - await repo.record_scip_applied(org, ns, tier, commit, paths) + await repo.record_scip_applied(org, ns, tier, commit, owed) async def _apply_files( @@ -567,7 +569,7 @@ async def _apply_round( await _publish(repo, "code_symbols", sink.symbols) if sink.edges: await _publish(repo, "code_edges", sink.edges) - await _record_applied(repo, org, ns, tier, commit, sorted(p for p in paths if p in marked)) + await _record_applied(repo, org, ns, tier, commit, paths, marked) def _symbol_metadata(symbol: ScipSymbol) -> dict[str, Any]: @@ -669,9 +671,7 @@ async def _apply_file( sink.edges.extend(edge_rows) else: await _publish(repo, "code_edges", edge_rows) - await _record_applied( - repo, org, ns, tier, commit, [f.path] if f.path in (marked or ()) else [] - ) + await _record_applied(repo, org, ns, tier, commit, [f.path], marked or set()) async def _diff_edges( diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index 840908eaf53..0a30604e95d 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -14,6 +14,7 @@ import pytest +from server.code.app.index import scip_delta as sd from server.code.app.index.output_mask import Unmasked from server.code.workers import scip_go_delta as w from tests.unit.code_fixtures import repo_config @@ -1368,3 +1369,94 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): with p1, p2: await w.run_pass() assert calls == [("a" * 40, "b" * 40, ["."])] + + +# ---------------------------------------------------------------- the fetch gate +# `scip_unavailable:go` names the modules a pass could not fetch; the retirement holds +# those modules' files and no others, and rebases the list each pass. + +GATE_KEY = "scip_unavailable:go" + + +def _gate(state: dict[str, str]) -> list[str]: + return json.loads(state.get(GATE_KEY, "[]")) + + +def _unreachable(module: str) -> str: + """The harness line for a module whose dependency this host cannot fetch.""" + return f"{_PRIVATE.replace('svc', module)}\n" + + +def _gate_host(monkeypatch, tmp_path: Path, state: dict[str, str], logs: dict[str, str]): + """A pass over `lib`, `mod_a`, `mod_b` that returns `logs[m]` for each module it runs, + writing no delta. The host is set up once; every pass reads the same state.""" + _host(monkeypatch, tmp_path) + + async def fake_harness(co, base, head, out_dir, modules, cfg): + ran = modules or ["lib", "mod_a", "mod_b"] + return Unmasked("".join(logs[m] for m in ran).encode()) + + monkeypatch.setattr(w, "git", AsyncMock()) + monkeypatch.setattr(w, "_run_harness", fake_harness) + monkeypatch.setattr(w, "_module_dirs", AsyncMock(return_value=["lib", "mod_a", "mod_b"])) + monkeypatch.setattr(w, "_changed_paths", AsyncMock(return_value=[])) + return _stateful_repo(state) + + +@pytest.mark.asyncio +async def test_a_pass_that_cannot_fetch_two_modules_writes_both_and_the_next_rebases_it( + monkeypatch, tmp_path: Path +) -> None: + """`lib` builds; `mod_a` and `mod_b` cannot be fetched. The gate names the two + unfetched dirs and not the built one. The next pass attempts `mod_a` only, and fetches + it: the gate is rebased as `previous - attempted`, so only `mod_b` is left.""" + state = {"git_head": "b" * 40, "scip_commit_go": ""} + logs = {"lib": "done lib\n", "mod_a": _unreachable("mod_a"), "mod_b": _unreachable("mod_b")} + repo = _gate_host(monkeypatch, tmp_path, state, logs) + p1, p2 = _patched(repo, [_Cfg()]) + with p1, p2: + await w.run_pass() + assert _gate(state) == ["mod_a", "mod_b"] # the unfetched dirs, not the built one + + logs["mod_a"] = "done mod_a\n" # the next window touches mod_a only, and it fetches + state["git_head"] = "c" * 40 + monkeypatch.setattr(w, "_changed_paths", AsyncMock(return_value=["mod_a/x.go"])) + with p1, p2: + await w.run_pass() + assert _gate(state) == ["mod_b"] # `previous - attempted`, not `previous + unfetched` + + +@pytest.mark.asyncio +async def test_a_module_fetched_again_loses_its_gate(monkeypatch, tmp_path: Path) -> None: + """A module the last pass could not fetch, fetched in this one, leaves the gate: the + pass attempted it, so nothing is left for the gate to hold.""" + state = { + "git_head": "b" * 40, + "scip_commit_go": "a" * 40, + GATE_KEY: json.dumps(["mod_a"]), + } + logs = {"lib": "done lib\n", "mod_a": "done mod_a\n", "mod_b": "done mod_b\n"} + repo = _gate_host(monkeypatch, tmp_path, state, logs) + monkeypatch.setattr(w, "_changed_paths", AsyncMock(return_value=["mod_a/x.go"])) + p1, p2 = _patched(repo, [_Cfg()]) + with p1, p2: + await w.run_pass() + assert _gate(state) == [] + + +@pytest.mark.asyncio +async def test_the_gate_a_pass_writes_is_the_one_retirement_gates(monkeypatch, tmp_path: Path): + """What the pass writes is read by `retire_published_marks`: the unfetched module's + files are held, and a file outside every dir the gate names retires.""" + state = {"git_head": "b" * 40, "scip_commit_go": ""} + logs = {"lib": "done lib\n", "mod_a": _unreachable("mod_a"), "mod_b": "done mod_b\n"} + repo = _gate_host(monkeypatch, tmp_path, state, logs) + p1, p2 = _patched(repo, [_Cfg()]) + with p1, p2: + await w.run_pass() + + gated = await sd._unbuilt_modules(repo, "org", "code-go", "go", "scip_commit_go") + assert gated == {"mod_a"} + assert sd._under_module("mod_a/x.go", gated) # gated: no apply covered it + assert not sd._under_module("lib/y.go", gated) # retires on its record + assert not sd._under_module("mod_b/z.go", gated) # built, so it retires too diff --git a/tests/unit/test_code_scip_mark_retirement.py b/tests/unit/test_code_scip_mark_retirement.py index fc13bb95107..f30de89d08f 100644 --- a/tests/unit/test_code_scip_mark_retirement.py +++ b/tests/unit/test_code_scip_mark_retirement.py @@ -310,6 +310,39 @@ async def test_a_superseded_record_version_does_not_retire( assert await repo.scip_stale_marks(ORG, NS, "clang") == {PATH} +# (d') the record must be newer than the mark, not merely name the same commit + + +@pytest.mark.parametrize( + ("mark_version", "record_version", "retires"), + [(2500, 3000, True), (3000, 2500, False)], + ids=["record-newer", "mark-newer"], +) +async def test_only_a_record_written_after_the_mark_answers_it( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Any, + mark_version: int, + record_version: int, + retires: bool, +) -> None: + """The same two rows, one version flipped: the mark is at C1, the record names the + watermark's C2, and the blobs differ, so `applied_at > marked` alone decides. A record + older than the mark is an apply of C2 that ran before a delta skipped the file at C1: + it says nothing about the skip, and the mark stays.""" + ch, repo = _world(tmp_path, monkeypatch, {(C1, PATH): b"old", (C2, PATH): b"new"}) + await ch.insert( + "loom.code_index_state", + _state( + _row(f"scip_stale:clang:{PATH}", C1, version=mark_version), + _row(f"scip_applied:clang:{PATH}", C2, version=record_version), + _row("scip_commit", C2, version=2000), + ), + ) + + assert await _retire(repo) == ({PATH} if retires else set()) + assert await repo.scip_stale_marks(ORG, NS, "clang") == (set() if retires else {PATH}) + + # (e) the Go freeze names modules @@ -433,31 +466,41 @@ async def edges_fail(self: CodeRepo, table: str, rows: list[dict[str, Any]]) -> assert await repo.scip_stale_marks(ORG, NS, "clang") == {PATH} -async def test_the_record_is_the_rounds_last_write(monkeypatch: pytest.MonkeyPatch, tmp_path: Any): - """`scip_applied` is inserted after the round's symbols and its edges, in the same - coroutine: an insert of either that raised aborts before it.""" - ch, repo = _world(tmp_path, monkeypatch, {(C1, PATH): b"old", (C2, PATH): b"two"}) +async def test_the_round_leaves_a_record_the_next_pass_retires_on( + monkeypatch: pytest.MonkeyPatch, tmp_path: Any +): + """The row the round writes, read back rather than inferred from a call order: a live + `scip_applied:clang:` holding the apply's commit, newer than the mark it answers, + and the mark it retires on the next pass. That the write follows both of the round's + inserts is what `test_an_edge_insert_that_raised_leaves_no_record` pins, by making the + second one raise: a write before it would record a round that never landed.""" + ch, repo = _world(tmp_path, monkeypatch, {(C1, PATH): b"old", (C2, PATH): b"new"}) await _apply(repo, ScipDelta(commit=C1, skipped_files=[PATH])) + assert await repo.scip_stale_marks(ORG, NS, "clang") == {PATH} + # the previous build applies the file: rows and watermark, no marks it knows of + await _apply( + repo, ScipDelta(commit=C2, files=[_file(C2)]), watermark="scip_commit", previous=True + ) - order: list[str] = [] - insert_rows = CodeRepo.insert_rows - insert = ch.insert - - async def record_insert_rows(self: CodeRepo, table: str, rows: list[dict[str, Any]]) -> None: - order.append(table) - await insert_rows(self, table, rows) - - async def record_insert(table: str, rows: list[dict[str, Any]], *a: Any, **kw: Any) -> None: - # the record is the non-empty row; `_mark_stale`'s clearing of it comes after - if table == "loom.code_index_state" and any( - str(r.get("state_key", "")).startswith("scip_applied:") and r.get("state_value") - for r in rows - ): - order.append("scip_applied") - await insert(table, rows, *a, **kw) - - monkeypatch.setattr(CodeRepo, "insert_rows", record_insert_rows) - monkeypatch.setattr(ch, "insert", record_insert) - await _apply(repo, ScipDelta(commit=C1, files=[_file(C1)])) + def row(rows: list[dict[str, Any]]) -> dict[str, Any]: + assert len(rows) == 1, rows + return rows[0] - assert order == ["code_symbols", "code_edges", "scip_applied"] + record = row( + await ch.query_all( + "SELECT state_value AS value, version AS at FROM loom.code_index_state FINAL " + "WHERE org = {o:String} AND namespace = {n:String} AND state_key = {k:String}", + {"o": ORG, "n": NS, "k": f"scip_applied:clang:{PATH}"}, + ) + ) + mark = row( + await ch.query_all( + "SELECT version AS at FROM loom.code_index_state FINAL " + "WHERE org = {o:String} AND namespace = {n:String} AND state_key = {k:String}", + {"o": ORG, "n": NS, "k": f"scip_stale:clang:{PATH}"}, + ) + ) + assert record["value"] == C2 # live, and naming the apply's own commit + assert record["at"] > mark["at"] # written after the mark it answers + assert await _retire(repo) == {PATH} + assert await repo.get_state(ORG, NS, f"scip_applied:clang:{PATH}") == "" From 5ca63b4940dd682f67aa263d2f6a9a48987739f8 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 14:12:12 +0000 Subject: [PATCH 58/81] A gone mark is asked of the tree, not only of git's byte lookup A mark is keyed by the `replace` decoding of its path, and `git cat-file` answers by bytes: for a name that is not UTF-8 the stored spelling (`src/caf\ufffd.cc`) matches nothing, so a marked file the tree still holds read as deleted and its mark was retired with the record that answered it. `_gone_at` now asks the tree, whose names decode to the same keys, about every path the byte-exact lookup did not find. A path holding a line break, which `cat-file` cannot take at all, is answered the same way, so deleting such a file retires its mark instead of keeping it for good. The `replace` decoding stays the one policy for keys: the tree's names are read through it, so key and tree agree by construction. Signed-off-by: Kaloyan Naumov --- docs/architecture/rolling-upgrades.md | 6 +- server/code/app/index/scip_delta.py | 17 ++- tests/unit/test_scip_gone_at_bytes.py | 160 ++++++++++++++++++++++++++ 3 files changed, 175 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_scip_gone_at_bytes.py diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 06368beb273..643c75b9995 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1113,8 +1113,10 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline commit keeps that mark. A rollback and a roll forward do the same. A marked file that N-1 deletes is never applied by N again, so N's next apply of the tier empties its mark when the entry's mirror holds the delta's commit - and the commit has no blob at that path; a mirror that cannot be read, or lacks the - commit, keeps the mark. + and the commit holds no file at that path, its names read as the keys the store writes + them by — so a name that is not UTF-8 matches its `replace` spelling and an existing + file is never read as gone; a mirror that cannot be read, or lacks the commit, keeps + the mark. `tests/integration/test_code_scip_stale_mark.py` applies these orders. A kept delta file (`scip-full --apply-delta`) is read by the CLI that applies it: N-1's CLI applies a retained version-2 file as version 1, so a skipped file's partial entry diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 939d2c268b0..4f276ce80df 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -324,7 +324,9 @@ def keep(path: str) -> bool: async def _gone_at(org: str, ns: str, commit: str, paths: set[str]) -> set[str]: """The marked `paths` with no file at `commit` in the entry's mirror. Empty when the mirror cannot say (no entry, no mirror, a commit it lacks, a failed or short read), - so a failed read keeps every mark.""" + so a failed read keeps every mark. A mark is keyed by the `replace` decoding of its + path, which no byte-exact lookup can match when the name is not UTF-8, so a path + `cat-file` does not find is asked of the tree, whose names decode to the same keys.""" if not paths or not commit: return set() try: @@ -335,7 +337,10 @@ async def _gone_at(org: str, ns: str, commit: str, paths: set[str]) -> set[str]: if cfg is None or not cfg.git_dir or not await gitrepo.has_commit(cfg.git_dir, commit): return set() asked = {p for p in paths if "\n" not in p and "\r" not in p} - return asked - await gitrepo.blob_paths_at(cfg.git_dir, commit, asked) + missing = set(paths) - await gitrepo.blob_paths_at(cfg.git_dir, commit, asked) + if not missing: + return set() + return missing - set(await gitrepo.ls_tree(cfg.git_dir, commit)) except Exception: # noqa: BLE001 — a failed read can only keep a mark return set() @@ -352,10 +357,10 @@ async def _mark_stale( ) -> None: """One write of `tier`'s rows only (`SCIP_STALE_PREFIX`, `SCIP_APPLIED_PREFIX`): each skipped file marked at `commit`, and the mark of each file this delta applied or - deleted emptied, as is the mark of a file with no blob at `commit` (one the previous - build deleted, which no apply of this build names again) and the applied record of - each of those. A mark and the record that answers it end in the same insert, so no - retirement reads a record against a mark it was not written for. `marked` is the + deleted emptied, as is the mark of a file the commit holds no file at (one the + previous build deleted, which no apply of this build names again) and the applied + record of each of those. A mark and the record that answers it end in the same insert, + so no retirement reads a record against a mark it was not written for. `marked` is the tier's marks read once by the caller (`apply_delta`), before the rounds ran. Another tier's marks are never read or written, so tiers applying side by side keep both.""" refreshed -= skipped diff --git a/tests/unit/test_scip_gone_at_bytes.py b/tests/unit/test_scip_gone_at_bytes.py new file mode 100644 index 00000000000..dfe12cd5353 --- /dev/null +++ b/tests/unit/test_scip_gone_at_bytes.py @@ -0,0 +1,160 @@ +"""A mark lives under the key the store spells its path with, and a name that is not +UTF-8 is spelled with `replace` (`src/caf\ufffd.cc`). `git cat-file` answers by bytes, so +that spelling matches nothing and a gone check that trusts it alone retires the mark of a +file the tree still holds. + +The gone check (`_gone_at`) reads the tree's names decoded the same way before it calls a +marked path gone. Real git; clickhouse-local holds the state rows. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from server.code.app.index.scip_delta import ScipDelta, ScipEdge, ScipFile, ScipSymbol, apply_delta +from server.code.domain.index import repos +from server.code.store.index import CodeRepo +from tests.unit import clickhouse_local + +pytestmark = pytest.mark.skipif( + clickhouse_local.CLICKHOUSE is None, reason="clickhouse binary not installed" +) + +ORG, NS = "o", "n" +RAW = b"src/caf\xe9.cc" # c3 a9 replaced by the single byte e9: not UTF-8 +KEY = "src/caf\ufffd.cc" # what `replace` decoding makes of RAW, and the key the store holds +OTHER = "src/other.cc" +LATE = "src/late.cc" +NEWLINE = "src/we\nird.cc" +DDL = ( + "SET enable_quantized_codec = 1", + clickhouse_local.ddl("code_chunks"), + clickhouse_local.ddl("code_index_state"), + clickhouse_local.ddl("code_symbols"), + clickhouse_local.ddl("code_edges"), +) + + +def _git(cwd: Path, *args: str) -> str: + done = subprocess.run( + ["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True + ) + return done.stdout.strip() + + +def _commit(work: Path, msg: str) -> str: + _git(work, "add", "-A") + _git(work, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", msg) + return _git(work, "rev-parse", "HEAD") + + +def _write(work: Path, name: bytes, text: bytes) -> None: + with open(os.fsencode(work) + b"/" + name, "wb") as fh: + fh.write(text) + + +def _mirror(tmp_path: Path) -> Path: + """A repository whose first commit holds a file named in bytes that are not UTF-8 + and a plain one.""" + work = tmp_path / "mirror" + (work / "src").mkdir(parents=True) + _write(work, RAW, b"int x;\n") + _write(work, OTHER.encode(), b"int y;\n") + _write(work, LATE.encode(), b"int z;\n") + _git(work, "init", "-q") + return work + + +def _file(commit: str, path: str = OTHER) -> ScipFile: + return ScipFile( + path=path, + symbols=[ScipSymbol(qualified_name="a::f", line_start=1, line_end=3, doc=commit)], + edges=[ + ScipEdge(from_qualified_name="a::f", to_qualified_name="a::g", line=2), + ], + ) + + +def _world(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, work: Path) -> CodeRepo: + monkeypatch.setattr( + repos, "repo_for_namespace", lambda org, ns: SimpleNamespace(git_dir=str(work / ".git")) + ) + return CodeRepo(clickhouse_local.KeptCH(tmp_path / "ch", *DDL)) + + +async def _marks(repo: CodeRepo) -> set[str]: + return await repo.scip_stale_marks(ORG, NS, "clang") + + +async def test_a_file_whose_name_is_not_utf8_is_not_gone_while_the_tree_holds_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The skip marks `KEY` at the first commit. The next commit changes only `OTHER`, so + no apply names `KEY` again and the mark is asked about: `cat-file` cannot match + `src/caf\ufffd.cc`, the tree's own name decodes back to it, and the mark stays. A + commit that deletes the file retires it.""" + work = _mirror(tmp_path) + first = _commit(work, "one") + repo = _world(tmp_path, monkeypatch, work) + await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[KEY]), tier="clang") + assert await _marks(repo) == {KEY} + + _write(work, OTHER.encode(), b"int y = 2;\n") + second = _commit(work, "touch other only") + await apply_delta(repo, ORG, NS, ScipDelta(commit=second, files=[_file(second)]), tier="clang") + assert await _marks(repo) == {KEY} + + os.unlink(os.fsencode(work) + b"/" + RAW) + third = _commit(work, "delete the file") + await apply_delta(repo, ORG, NS, ScipDelta(commit=third, files=[_file(third)]), tier="clang") + assert await _marks(repo) == set() + + +async def test_a_file_that_is_gone_still_retires_and_a_failed_read_keeps_the_mark( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The ordinary path: a UTF-8 name `cat-file` does not find is gone, and a commit the + mirror lacks keeps every mark — the tree read must not turn a failed read into one.""" + work = _mirror(tmp_path) + first = _commit(work, "one") + repo = _world(tmp_path, monkeypatch, work) + await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[OTHER]), tier="clang") + assert await _marks(repo) == {OTHER} + + _write(work, OTHER.encode(), b"int y = 3;\n") + second = _commit(work, "touch other") + await apply_delta(repo, ORG, NS, ScipDelta(commit=second, files=[_file(second)]), tier="clang") + assert await _marks(repo) == set() + + await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[OTHER]), tier="clang") + await apply_delta( + repo, + ORG, + NS, + ScipDelta(commit="f" * 40, files=[_file("f" * 40, LATE)]), + tier="clang", + ) + assert await _marks(repo) == {OTHER} + + +async def test_a_marked_path_holding_a_newline_is_answered_by_the_tree_too( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """`cat-file` cannot take a name holding a line break, so the gone check could only + keep that mark for good. The tree carries the name whole, and a delete retires it.""" + work = _mirror(tmp_path) + _write(work, NEWLINE.encode(), b"int w;\n") + first = _commit(work, "one") + repo = _world(tmp_path, monkeypatch, work) + await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[NEWLINE]), tier="clang") + assert await _marks(repo) == {NEWLINE} + + os.unlink(os.fsencode(work) + b"/" + NEWLINE.encode()) + second = _commit(work, "delete it") + await apply_delta(repo, ORG, NS, ScipDelta(commit=second, files=[_file(second)]), tier="clang") + assert await _marks(repo) == set() From dd0c138ac94bbb76ed5117122af77612a5bc8289 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 15:07:59 +0000 Subject: [PATCH 59/81] scip_merge_indexes: the merge duplicated _keeps, _encode_varint and _write_record The merge resolution in scripts/scip_harness/scip_merge_indexes.py kept both parents' copy of three helpers: each parent had one, and the merged file defined _keeps, _encode_varint and _write_record twice. The second copy is deleted, so each function is defined once before merge_indexes. No behaviour changes: the two copies were byte-identical, and the later definition shadowed the earlier one. Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 32 ---------------------- 1 file changed, 32 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index 8bfcc3184eb..7cbb203c090 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -148,38 +148,6 @@ def _write_record(out: BinaryIO, field: int, payload: Any) -> None: out.write(payload) -def _keeps(project: str, relpath: str, owners: list[str]) -> bool: - # Keep documents this member owns. Documents followed through - # TypeScript project references into another package are - # dropped even when that package is not in this merge, so a - # subset rebuild cannot overwrite the other package's rows. - # owners is the full discovered set: a root-level tsconfig owns - # every path, so ownership still prefers a longer member that - # was not indexed in this run. - if not project_owns(project, relpath): - return False - owner = _preferred_owner(owners, relpath) - # Compare scopes, not raw project strings: a generated member - # target is dir/tsconfig.scip.json, while --known-project still - # names dir. - return owner is None or project_scope(owner) == project_scope(project) - - -def _encode_varint(value: int) -> bytes: - out = bytearray() - while value > 0x7F: - out.append(value & 0x7F | 0x80) - value >>= 7 - out.append(value) - return bytes(out) - - -def _write_record(out: BinaryIO, field: int, payload: Any) -> None: - out.write(_encode_varint(field << 3 | 2)) # wire type 2, length-delimited - out.write(_encode_varint(len(payload))) - out.write(payload) - - def merge_indexes( paths: list[Path], output: Path, From b4b868e489fc9ef470792676c676d0027f10a6ef Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 17:17:16 +0000 Subject: [PATCH 60/81] A failed member is matched by its whole name, not as a word in another The failed-member list joined names with spaces and matched each name against that string, so a member whose name is a token of another (`app` beside `packages/my app`) read as already listed. Its `--failed-project` never reached the merge and its files never reached `--failed-paths` / `--failed-files`, so a full pass could retire the compiler rows of a member whose indexer failed, the opposite of the member isolation this branch adds. The surviving-member list used the same delimiter and is fixed with it. Both are newline-delimited now, so only an equal name is a duplicate. `test_a_failed_member_whose_name_is_a_token_of_another_is_not_skipped` runs a full pass where `packages/my app` and `app` both fail and `packages/lib` converts. Before, the converter received `["packages/my app/src/a.ts"]`; now it receives both `app/src/a.ts` and `packages/my app/src/a.ts`. Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/run_typescript_delta.sh | 18 +++--- .../test_run_typescript_delta_umbrella.py | 58 +++++++++++++++++++ 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 122555414c8..d889afd6c9a 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -259,16 +259,16 @@ JSONEOF done # A member survives when one run its merge reads from succeeded. The partial # output of a failed run is not merged, so a killed process cannot write rows. - local surviving=" " + local surviving=$'\n' for i in "${!pair_run[@]}"; do if [[ "${run_ok[${pair_run[i]}]:-0}" == 1 ]]; then - case " $surviving " in - *" ${pair_member[i]} "*) ;; - *) surviving="$surviving${pair_member[i]} " ;; + case "$surviving" in + *$'\n'"${pair_member[i]}"$'\n'*) ;; + *) surviving="$surviving${pair_member[i]}"$'\n' ;; esac fi done - if [[ -z "${surviving// /}" ]]; then + if [[ -z "${surviving//$'\n'/}" ]]; then echo ">> every member failed — no delta" >&2 exit 1 fi @@ -284,16 +284,16 @@ JSONEOF # own as skipped (`DeltaStream.tail`) and needs the rest to know which # references lost their definition. git_paths ls-files -- "${TS_GLOBS[@]}" >"$WORK/candidates.txt" - local failed_members=" " + local failed_members=$'\n' for i in "${!pair_run[@]}"; do case " ${failed_runs[*]} " in *" ${pair_run[i]} "*) ;; *) continue ;; esac - case " $failed_members " in - *" ${pair_member[i]} "*) continue ;; + case "$failed_members" in + *$'\n'"${pair_member[i]}"$'\n'*) continue ;; esac - failed_members="$failed_members${pair_member[i]} " + failed_members="$failed_members${pair_member[i]}"$'\n' merge_args+=(--failed-project "${pair_member[i]}") done merge_args+=(--paths "$WORK/candidates.txt" --failed-paths "$WORK/failed.txt") diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 8aa632c242f..e51bf7fad4e 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -534,6 +534,64 @@ def test_member_path_with_a_space_survives_full_and_delta_passes(tmp_path: Path) assert _targets(_runs(log)) == ["packages/my app"] +def test_a_failed_member_whose_name_is_a_token_of_another_is_not_skipped( + tmp_path: Path, +) -> None: + """`app` is a word inside `packages/my app`, not the same member. + + Both indexers fail. The failed-member list must hold both names, so the + converter receives both members' files: a spaced name read as a token of + another would drop `app`'s paths, and a full pass could retire the + compiler rows of a member whose indexer failed. + """ + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + { + "files": [], + "references": [ + {"path": "packages/my app"}, + {"path": "app"}, + {"path": "packages/lib"}, + ], + } + ), + "packages/my app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/my app/src/a.ts": "export const a = 1;\n", + "app/tsconfig.json": json.dumps({"include": ["src"]}), + "app/src/a.ts": "export const a = 1;\n", + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + writer = tmp_path / "scip_writer.py" + writer.write_text(_SCIP_WRITER) + # Both names hold "app", so both indexers fail; packages/lib still converts. + proc, log = _run_status( + tmp_path, + repo, + "--full", + head, + { + "BROKEN_PROJECT": "app", + "INDEXED": str(tmp_path / "indexed"), + "MERGED": str(tmp_path / "merged.scip"), + "SCIP_VENDOR": str(_SCRIPT.parent / "vendor"), + "SCIP_WRITER": str(writer), + }, + scip=_FAKE_SCIP_INDEXING, + ) + assert proc.returncode == 0, proc.stderr + assert _failed(log) == ["app/src/a.ts", "packages/my app/src/a.ts"] + + def test_full_pass_starts_one_indexer_process_per_member(tmp_path: Path) -> None: """A full pass must not hand every member to one scip-typescript process. From 1d0d36331d33c54857efd49c71e0225e1edddae7 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 17:29:41 +0000 Subject: [PATCH 61/81] A gitlink is not a file, and a document's own damage stays its own Three findings from the review of #1704. The tree read behind `_gone_at` kept every name `ls-tree -r` printed, and the `--name-only` listing prints a submodule entry like a file: a source file replaced by a gitlink kept its stale mark for good, because no document at that path can ever clear it. Both tree listings now read the record's type and answer blobs only, the answer `blob_ids_at` already gave the same path. `ls_tree` and `ls_tree_blobs` feed the ingest, the backfill's retirement and the reconcile as well, so a gitlink path reads absent there too: the same verdict the mark takes. Two test fixtures built their commits by writing a name that is not UTF-8 to disk, which macOS refuses (EIO from APFS), so the tests failed before git ran. Those entries are now built in the index with `git update-index --cacheinfo` and never touch the filesystem; a commit stages its plain paths explicitly, because `git add -A` reads an index-only entry as a deletion. `tests/unit/ test_scip_path_encoding.py` had the second fixture: its two-commit rename is now an index-level move, so the same tests read real git trees with no such name on disk. A new test pins a gitlink at a marked path as gone. `scip_to_delta`'s path read raised on a document truncated inside itself, before the window could select it or the skip handler could name it: a document outside the window failed the run. The read keeps the path its records carried ahead of the damage and the document's own parse fails per document, named; a document whose own name cannot be read still fails the run, since no window can say whether it was selected. Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_to_delta.py | 42 +++++++-- server/code/app/index/gitrepo.py | 33 ++++--- server/code/app/index/scip_delta.py | 4 +- tests/unit/test_gitrepo_unusual_paths.py | 23 +++++ tests/unit/test_scip_gone_at_bytes.py | 108 ++++++++++++++++++----- tests/unit/test_scip_path_encoding.py | 48 ++++++++-- tests/unit/test_scip_to_delta_skip.py | 68 ++++++++++++++ 7 files changed, 272 insertions(+), 54 deletions(-) diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 711293edea6..203d766b949 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -919,15 +919,30 @@ def skip(p: int, wire: int, field: int, depth: int) -> int: pos = skip(pos, wire, field, 0) +def _read_document_path(payload: bytes) -> tuple[bytes, ValueError | None]: + """A serialized Document's relative_path (field 1) as the raw bytes, with the failure + of a record the read could not finish (a document truncated inside itself), if any. + + The path field is numbered before the occurrences in every writer, so the records + ahead of the damage still name the document, and a name is all this asks for: the + document's own parse reports the damage per document, where `skips` names it. A read + that raised here would fail a window over a document it never converts.""" + path = b"" + try: + for field, value in _top_level_records(payload): + if field == 1: + path = bytes(value) + except ValueError as e: + return path, e + return path, None + + def _document_path_bytes(payload: bytes) -> bytes: """A serialized Document's relative_path (field 1) as the raw bytes, read without parsing its occurrences. A singular field written more than once - takes its last value, as the protobuf parser takes it.""" - path = b"" - for field, value in _top_level_records(payload): - if field == 1: - path = bytes(value) - return path + takes its last value, as the protobuf parser takes it, and a truncated tail + keeps the name the records before it carried.""" + return _read_document_path(payload)[0] def _document_path(payload) -> str: @@ -990,11 +1005,20 @@ def _indexed_documents(data, scip_pb2, skips: _Skips, paths: set[str] | None, or the documents with those relative paths; `ordered` yields them sorted by path (index order among equal paths), so the delta does not depend on the order a parallel indexer wrote its documents in. A document that does - not parse is skipped (`skips`); an index whose records cannot be read to the - end raises.""" + not parse is skipped (`skips`), named under the path its own records carry + before the damage; an index whose records cannot be read to the end raises.""" records = enumerate(payload for field, payload in _top_level_records(data) if field == 2) if paths is not None or ordered: - keyed = [(_document_path(payload), i, payload) for i, payload in records] + keyed: list[tuple[str, int, bytes]] = [] + for i, payload in records: + raw, failure = _read_document_path(payload) + if failure is not None and not raw: + # nothing names this document, so a window cannot say whether it was + # selected: converting without it could leave the rows it was asked to + # refresh unmarked, and it cannot be listed as skipped. Fails, as a whole + # run fails for any document it cannot name (`_Skips.add`). + raise ValueError(f"document {i}'s path cannot be read: {failure}") from failure + keyed.append((raw.decode("utf-8", "replace"), i, payload)) if paths is not None: keyed = [k for k in keyed if k[0] in paths] if ordered: diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index 5ee926e25c9..c0adefbd1ea 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -1284,10 +1284,24 @@ def blob_sha(data: bytes) -> str: return h.hexdigest() +def _tree_blobs(out: str) -> dict[str, str]: + """path -> object id for the blob records of a `-z` `ls-tree -r`: ` + \t`, whose path `-z` leaves verbatim. A record of another type is + left out: a gitlink is a submodule's pointer, not a file any read here can read, + and `blob_ids_at` leaves the same path out of its map.""" + blobs: dict[str, str] = {} + for record in nul_fields(out): + meta, _, path = record.partition("\t") + fields = meta.split() + if len(fields) == 3 and fields[1] == "blob" and path: + blobs[path] = fields[2] + return blobs + + async def ls_tree_blobs(git_dir: str, sha: str) -> dict[str, str]: """path -> blob sha for every blob at a commit: one `git ls-tree -r`, metadata only (no blob is read). ~30k paths in well under a second on - the ClickHouse mirror.""" + the ClickHouse mirror. A path holding a gitlink is not a blob and is absent.""" out = await _git( git_dir, "ls-tree", @@ -1297,30 +1311,23 @@ async def ls_tree_blobs(git_dir: str, sha: str) -> dict[str, str]: _rev(sha), timeout_s=settings.code_git_fetch_timeout_s, ) - # ` \t`: the default record, whose path -z leaves - # verbatim (a --format %(path) is still quoted) - blobs: dict[str, str] = {} - for record in nul_fields(out): - meta, _, path = record.partition("\t") - fields = meta.split() - if len(fields) == 3 and path: - blobs[path] = fields[2] - return blobs + return _tree_blobs(out) async def ls_tree(git_dir: str, sha: str, prefixes: tuple[str, ...] = ()) -> list[str]: - """All blob paths at a commit, optionally filtered to path prefixes.""" + """The blob paths at a commit, optionally filtered to path prefixes. A path holding a + gitlink is not a file at that commit and is left out, the answer `blob_ids_at` gives + it: a name alone cannot tell a submodule's pointer from a source file.""" out = await _git( git_dir, "ls-tree", "-r", "-z", - "--name-only", "--end-of-options", _rev(sha), timeout_s=settings.code_git_fetch_timeout_s, ) - paths = nul_fields(out) + paths = list(_tree_blobs(out)) if prefixes: paths = [p for p in paths if p.startswith(prefixes)] return paths diff --git a/server/code/app/index/scip_delta.py b/server/code/app/index/scip_delta.py index 4f276ce80df..5d4f4faffca 100644 --- a/server/code/app/index/scip_delta.py +++ b/server/code/app/index/scip_delta.py @@ -326,7 +326,9 @@ async def _gone_at(org: str, ns: str, commit: str, paths: set[str]) -> set[str]: mirror cannot say (no entry, no mirror, a commit it lacks, a failed or short read), so a failed read keeps every mark. A mark is keyed by the `replace` decoding of its path, which no byte-exact lookup can match when the name is not UTF-8, so a path - `cat-file` does not find is asked of the tree, whose names decode to the same keys.""" + `cat-file` does not find is asked of the tree, whose names decode to the same keys. + The tree answers its blobs only: a path holding a gitlink is not a source file, and a + mark kept there outlives every read that could answer it.""" if not paths or not commit: return set() try: diff --git a/tests/unit/test_gitrepo_unusual_paths.py b/tests/unit/test_gitrepo_unusual_paths.py index aea6efbe6fc..e1a5637c724 100644 --- a/tests/unit/test_gitrepo_unusual_paths.py +++ b/tests/unit/test_gitrepo_unusual_paths.py @@ -80,6 +80,29 @@ def test_ls_tree_lists_exactly_the_tree(repo: tuple[Path, str, str]) -> None: assert asyncio.run(gitrepo.ls_tree(git_dir, head, ("docs/",))) == [UNUSUAL["cjk"]] +def test_a_gitlink_is_not_one_of_the_listed_paths(tmp_path: Path) -> None: + """A submodule's entry names a path and holds no file: `ls-tree -r` lists it under the + entry's type, and a listing that keeps it hands the ingest, the backfill's retirement + and the gone check a path no blob read can open. Both listings answer blobs only.""" + wt = tmp_path / "w" + wt.mkdir() + _git(wt, "init", "-q", "-b", "main") + _git(wt, "config", "user.email", "t@example.invalid") + _git(wt, "config", "user.name", "t") + (wt / "a.py").write_text("a = 1\n") + _git(wt, "add", ".") + _git(wt, "commit", "-q", "-m", "a file") + first = _git(wt, "rev-parse", "HEAD") + (wt / "a.py").unlink() + _git(wt, "update-index", "--add", "--cacheinfo", f"160000,{first},a.py") + _git(wt, "commit", "-q", "-m", "the file is a gitlink") + head = _git(wt, "rev-parse", "HEAD") + assert "160000 commit" in _git(wt, "ls-tree", "-r", head) + git_dir = str(wt / ".git") + assert asyncio.run(gitrepo.ls_tree(git_dir, head)) == [] + assert asyncio.run(gitrepo.ls_tree_blobs(git_dir, head)) == {} + + def test_the_diff_readers_name_the_real_paths_and_split_a_rename( repo: tuple[Path, str, str], ) -> None: diff --git a/tests/unit/test_scip_gone_at_bytes.py b/tests/unit/test_scip_gone_at_bytes.py index dfe12cd5353..4bf68852054 100644 --- a/tests/unit/test_scip_gone_at_bytes.py +++ b/tests/unit/test_scip_gone_at_bytes.py @@ -4,12 +4,17 @@ file the tree still holds. The gone check (`_gone_at`) reads the tree's names decoded the same way before it calls a -marked path gone. Real git; clickhouse-local holds the state rows. +marked path gone — and only the tree's blobs: a path that holds a gitlink is no more a +source file than a path that holds nothing, and its mark retires the way a deletion's +does, where keeping it would leave the rows stale with no document able to clear them. + +A name that is not UTF-8 cannot be created on macOS (`open` fails with EIO — APFS refuses +the bytes), so that entry is built in the index with `git update-index --cacheinfo` and +never touches the filesystem. Real git; clickhouse-local holds the state rows. """ from __future__ import annotations -import os import subprocess from pathlib import Path from types import SimpleNamespace @@ -31,6 +36,7 @@ OTHER = "src/other.cc" LATE = "src/late.cc" NEWLINE = "src/we\nird.cc" +LINKED = "src/gone.cc" # a path a commit holds as a gitlink (mode 160000) DDL = ( "SET enable_quantized_codec = 1", clickhouse_local.ddl("code_chunks"), @@ -40,32 +46,59 @@ ) -def _git(cwd: Path, *args: str) -> str: +def _git(work: Path, *args: str) -> str: done = subprocess.run( - ["git", "-C", str(cwd), *args], check=True, capture_output=True, text=True + ["git", "-C", str(work), *args], check=True, capture_output=True, text=True ) return done.stdout.strip() -def _commit(work: Path, msg: str) -> str: - _git(work, "add", "-A") - _git(work, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", msg) - return _git(work, "rev-parse", "HEAD") +def _git_raw(work: Path, *args: bytes) -> None: + """A git command whose arguments carry a path as bytes: a name that is not UTF-8 + never passes through a `str`, and never through the filesystem.""" + done = subprocess.run(["git", "-C", str(work).encode(), *args], capture_output=True) + assert done.returncode == 0, done.stderr + + +def _tree(work: Path, rev: str) -> bytes: + """The commit's listing as git writes it: `-z` leaves every name verbatim.""" + done = subprocess.run( + ["git", "-C", str(work), "ls-tree", "-r", "-z", rev], capture_output=True, check=True + ) + return done.stdout + + +def _stage(work: Path, path: bytes, content: bytes) -> None: + """`path` holds `content` in the index, with no file of that name on disk.""" + blob = subprocess.run( + ["git", "-C", str(work), "hash-object", "-w", "--stdin"], + input=content, + capture_output=True, + check=True, + ).stdout.strip() + _git_raw(work, b"update-index", b"--add", b"--cacheinfo", b"100644," + blob + b"," + path) -def _write(work: Path, name: bytes, text: bytes) -> None: - with open(os.fsencode(work) + b"/" + name, "wb") as fh: - fh.write(text) +def _stage_link(work: Path, path: str, target: str) -> None: + """`path` is a submodule entry (mode 160000) in the index.""" + _git(work, "update-index", "--add", "--cacheinfo", f"160000,{target},{path}") + + +def _commit(work: Path, msg: str, *paths: str) -> str: + """Stage `paths` (`-A` over the whole tree by default) and commit the index as it + stands: an entry the index holds and the worktree does not must survive the commit.""" + _git(work, "add", "-A", "--", *(paths or (".",))) + _git(work, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", msg) + return _git(work, "rev-parse", "HEAD") def _mirror(tmp_path: Path) -> Path: - """A repository whose first commit holds a file named in bytes that are not UTF-8 - and a plain one.""" + """A repository holding two plain source files. A name that is not UTF-8 is staged in + the index by the one test that needs it (`_stage`).""" work = tmp_path / "mirror" (work / "src").mkdir(parents=True) - _write(work, RAW, b"int x;\n") - _write(work, OTHER.encode(), b"int y;\n") - _write(work, LATE.encode(), b"int z;\n") + (work / OTHER).write_text("int y;\n") + (work / LATE).write_text("int z;\n") _git(work, "init", "-q") return work @@ -98,19 +131,24 @@ async def test_a_file_whose_name_is_not_utf8_is_not_gone_while_the_tree_holds_it no apply names `KEY` again and the mark is asked about: `cat-file` cannot match `src/caf\ufffd.cc`, the tree's own name decodes back to it, and the mark stays. A commit that deletes the file retires it.""" + assert KEY == RAW.decode("utf-8", "replace") work = _mirror(tmp_path) - first = _commit(work, "one") + _stage(work, RAW, b"int x;\n") + first = _commit(work, "one", OTHER, LATE) + assert RAW in _tree(work, first) repo = _world(tmp_path, monkeypatch, work) await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[KEY]), tier="clang") assert await _marks(repo) == {KEY} - _write(work, OTHER.encode(), b"int y = 2;\n") - second = _commit(work, "touch other only") + (work / OTHER).write_text("int y = 2;\n") + second = _commit(work, "touch other only", OTHER) + assert RAW in _tree(work, second) await apply_delta(repo, ORG, NS, ScipDelta(commit=second, files=[_file(second)]), tier="clang") assert await _marks(repo) == {KEY} - os.unlink(os.fsencode(work) + b"/" + RAW) - third = _commit(work, "delete the file") + _git_raw(work, b"update-index", b"--force-remove", b"--", RAW) + third = _commit(work, "delete the file", OTHER) + assert RAW not in _tree(work, third) await apply_delta(repo, ORG, NS, ScipDelta(commit=third, files=[_file(third)]), tier="clang") assert await _marks(repo) == set() @@ -126,7 +164,7 @@ async def test_a_file_that_is_gone_still_retires_and_a_failed_read_keeps_the_mar await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[OTHER]), tier="clang") assert await _marks(repo) == {OTHER} - _write(work, OTHER.encode(), b"int y = 3;\n") + (work / OTHER).write_text("int y = 3;\n") second = _commit(work, "touch other") await apply_delta(repo, ORG, NS, ScipDelta(commit=second, files=[_file(second)]), tier="clang") assert await _marks(repo) == set() @@ -148,13 +186,35 @@ async def test_a_marked_path_holding_a_newline_is_answered_by_the_tree_too( """`cat-file` cannot take a name holding a line break, so the gone check could only keep that mark for good. The tree carries the name whole, and a delete retires it.""" work = _mirror(tmp_path) - _write(work, NEWLINE.encode(), b"int w;\n") + (work / NEWLINE).write_text("int w;\n") first = _commit(work, "one") repo = _world(tmp_path, monkeypatch, work) await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[NEWLINE]), tier="clang") assert await _marks(repo) == {NEWLINE} - os.unlink(os.fsencode(work) + b"/" + NEWLINE.encode()) + (work / NEWLINE).unlink() second = _commit(work, "delete it") await apply_delta(repo, ORG, NS, ScipDelta(commit=second, files=[_file(second)]), tier="clang") assert await _marks(repo) == set() + + +async def test_a_gitlink_at_a_marked_path_is_gone( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A source file replaced by a submodule entry is not a file at that path: `cat-file` + answers the marked key missing and `ls-tree -r` lists the path under the entry's type, + so a tree read that keeps every name keeps this mark too. The tree read answers blobs + only, and the mark retires as a deletion's does — no document can ever clear it.""" + work = _mirror(tmp_path) + (work / LINKED).write_text("int g;\n") + first = _commit(work, "one") + repo = _world(tmp_path, monkeypatch, work) + await apply_delta(repo, ORG, NS, ScipDelta(commit=first, skipped_files=[LINKED]), tier="clang") + assert await _marks(repo) == {LINKED} + + (work / LINKED).unlink() + _stage_link(work, LINKED, first) + second = _commit(work, "src/gone.cc is a gitlink", OTHER, LATE) + assert b"160000 commit" in _tree(work, second) + await apply_delta(repo, ORG, NS, ScipDelta(commit=second, files=[_file(second)]), tier="clang") + assert await _marks(repo) == set() diff --git a/tests/unit/test_scip_path_encoding.py b/tests/unit/test_scip_path_encoding.py index 6a2c03738db..b2e24893f76 100644 --- a/tests/unit/test_scip_path_encoding.py +++ b/tests/unit/test_scip_path_encoding.py @@ -31,23 +31,57 @@ def _git(cwd: Path, *args: str) -> str: def _commit(repo: Path, msg: str) -> str: - _git(repo, "add", "-A") _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", msg) return _git(repo, "rev-parse", "HEAD") +def _put(repo: Path, path: bytes, blob: bytes) -> None: + """`path` holds `blob` in the index, with no file of that name on disk: macOS cannot + create a name that is not UTF-8 (EIO), and git reads the entry either way.""" + done = subprocess.run( + [ + "git", + "-C", + os.fsencode(repo), + b"update-index", + b"--add", + b"--cacheinfo", + b"100644," + blob + b"," + path, + ], + capture_output=True, + ) + assert done.returncode == 0, done.stderr + + def _repo_at(tmp_path: Path, name: bytes) -> tuple[Path, str]: - """A repository whose one commit holds a file at `name` (raw bytes).""" + """A repository whose one commit holds a file at `name` (raw bytes), built in the + index: no name in these tests ever reaches the filesystem.""" repo = tmp_path / "repo" - (repo / "src").mkdir(parents=True) - with open(os.fsencode(repo) + b"/" + name, "wb") as fh: - fh.write(b"export const a = 1;\n") - _git(tmp_path, "init", "-q", str(repo)) + repo.mkdir() + subprocess.run(["git", "init", "-q", str(repo)], check=True, capture_output=True) + blob = subprocess.run( + ["git", "-C", str(repo), "hash-object", "-w", "--stdin"], + input=b"export const a = 1;\n", + capture_output=True, + check=True, + ).stdout.strip() + _put(repo, name, blob) return repo, _commit(repo, "init") def _move(repo: Path, old: bytes, new: bytes) -> None: - os.rename(os.fsencode(repo) + b"/" + old, os.fsencode(repo) + b"/" + new) + """The same blob moves to `new` in the index; the two commits differ by that path.""" + blob = subprocess.run( + ["git", "-C", os.fsencode(repo), b"rev-parse", b"HEAD:" + old], + capture_output=True, + check=True, + ).stdout.strip() + done = subprocess.run( + ["git", "-C", os.fsencode(repo), b"update-index", b"--force-remove", b"--", old], + capture_output=True, + ) + assert done.returncode == 0, done.stderr + _put(repo, new, blob) def _split(path: Path) -> list[bytes]: diff --git a/tests/unit/test_scip_to_delta_skip.py b/tests/unit/test_scip_to_delta_skip.py index e939f1f8121..1fb6c827d47 100644 --- a/tests/unit/test_scip_to_delta_skip.py +++ b/tests/unit/test_scip_to_delta_skip.py @@ -334,3 +334,71 @@ def test_a_full_run_whose_constructor_scan_skipped_a_document_outside_its_files_ str(index), {"src/ok.cpp"}, [], "h" * 40, "", source_root=str(root), full=True ) assert whole["features"] == ["ctor_calls"] + + +def _varint(n: int) -> bytes: + out = bytearray() + while True: + out.append((n & 0x7F) | (0x80 if n >> 7 else 0)) + n >>= 7 + if not n: + return bytes(out) + + +def _index_with_a_truncated_document(tmp_path: Path) -> Path: + """`ok.py` converts; `bad.py` names itself and then carries an occurrence that declares + more bytes than the document holds. The index's own framing is intact — the damage is + inside one document — so the window's path read meets it before either selection or the + per-document handler does.""" + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///nonexistent-checkout" + _add_doc(index, "ok.py", [(_fn("f", "aa"), 0)], []) + bad = b"\x0a" + _varint(len("bad.py")) + b"bad.py" + b"\x22" + _varint(64) + b"\x0a\x01x" + out = tmp_path / "index.scip" + out.write_bytes(index.SerializeToString() + b"\x12" + _varint(len(bad)) + bad) + return out + + +def test_a_malformed_document_outside_the_window_does_not_fail_the_run(tmp_path: Path) -> None: + """The window names only `ok.py`. Reading the documents' paths to select the window + meets `bad.py`'s truncation first, and a document the run was never going to convert + must not fail it: the path read reports what it read and the window converts.""" + conv = _converter() + delta = conv.convert( + str(_index_with_a_truncated_document(tmp_path)), {"ok.py"}, [], "h" * 40, "" + ) + assert [f["path"] for f in delta["files"]] == ["ok.py"] + assert delta["skipped_files"] == [] + + +def test_a_malformed_document_in_a_full_run_is_skipped_under_its_path(tmp_path: Path) -> None: + """With no window the document is converted, refused, and named under the path read + before the damage — the skip handler asks for that path, so it must not raise.""" + conv = _converter() + delta = conv.convert( + str(_index_with_a_truncated_document(tmp_path)), None, [], "h" * 40, "", full=True + ) + assert [f["path"] for f in delta["files"]] == ["ok.py"] + assert delta["skipped_files"] == ["bad.py"] + assert delta["stats"]["skipped_failed"] == 1 + + +def test_a_document_whose_own_name_cannot_be_read_fails_the_run(tmp_path: Path) -> None: + """`bad.py`'s path field is truncated, so nothing names the document and a window + cannot say whether it was selected. Converting without it could leave rows the run was + asked to refresh unmarked, and it cannot be listed as skipped: the run fails.""" + + def index_bytes() -> bytes: + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///nonexistent-checkout" + _add_doc(index, "ok.py", [(_fn("f", "aa"), 0)], []) + nameless = b"\x0a" + _varint(64) + b"bad.py" + return index.SerializeToString() + b"\x12" + _varint(len(nameless)) + nameless + + index = tmp_path / "index.scip" + index.write_bytes(index_bytes()) + conv = _converter() + with pytest.raises(ValueError, match="path cannot be read"): + conv.convert(str(index), {"ok.py"}, [], "h" * 40, "") From 249760a2b10c731c68aace5a45923250706acbd2 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 18:33:24 +0000 Subject: [PATCH 62/81] The path-scoped read guard knows the two state-only writers `record_scip_applied` and `clear_scip_marks` take `paths` but write `code_index_state` rows keyed by path; they read no table, so the ingest round buffer's flush rule does not apply. The guard flagged them as unreviewed reads. They join `_PATH_PARAM_REVIEWED` with the reason. Signed-off-by: Kaloyan Naumov --- tests/unit/test_code_ingest_round_models.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unit/test_code_ingest_round_models.py b/tests/unit/test_code_ingest_round_models.py index 58731e8b03e..1d409cf14ba 100644 --- a/tests/unit/test_code_ingest_round_models.py +++ b/tests/unit/test_code_ingest_round_models.py @@ -348,6 +348,8 @@ async def run() -> None: "pr_history_in_window": "PR tables, never written by the ingest", "prs_overlapping_paths": "PR tables, never written by the ingest", "prs_touching_in_window": "PR tables, never written by the ingest", + "record_scip_applied": "writes code_index_state rows keyed by path; reads no table", + "clear_scip_marks": "writes code_index_state rows keyed by path; reads no table", } From 1b07f07f014273e8a80c184b1389749bb12876f5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 19:45:51 +0000 Subject: [PATCH 63/81] Decode a project's own name and its documents' paths as one key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two findings from the review of #1704, both a project directory whose name holds a byte that is not UTF-8. `scip_to_delta.py` read the module's directory from argv, where Python hands back a lone surrogate for that byte, and every window name as the `replace` decoding of git's bytes. The two never compared equal: a deleted file under the module carried the prefix twice (`caf\udce9/caf\ufffd/gone.ts`) and named no row, and the module's own changed document was not the changed one. `_path_text` is now the one decode — bytes, or a `str` re-encoded with `surrogateescape` — used for the document path, the window lists, the directory as the delta keys it, and the Go scope name; the checkout's own name still opens the source reads. The merge compared the plan's member name — argv text, surrogate-escaped — with a document's `replace`-decoded path, so a selected member whose directory is not UTF-8 owned nothing: the merge wrote an index without its documents and the converter could not mark the member's document stale. `owner_key` (was `_key`, the same decode) is applied to both sides; the plan still hands the raw name to the indexer runs, which open the checkout. Both sides of each comparison now decode through one function, so two paths that differ only by a malformed byte stay distinct, as the earlier key ruling requires. Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/scip_merge_indexes.py | 13 ++- scripts/scip_harness/scip_to_delta.py | 44 ++++++--- scripts/scip_harness/scip_ts_projects.py | 9 +- tests/unit/test_scip_path_encoding.py | 101 +++++++++++++++++++++ 4 files changed, 148 insertions(+), 19 deletions(-) diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index ecbc1272702..c4fa2487534 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -17,7 +17,9 @@ The merge reads only the top-level records and each document's relative_path, and copies the records it keeps byte for byte. Documents are told apart by the raw path bytes; the path is decoded only to ask which -project owns it. A document python-protobuf would refuse (a string field +project owns it, and the member's own name is decoded the same way +(`owner_key`, `replace`) so a member whose directory is not UTF-8 owns its +documents. A document python-protobuf would refuse (a string field that is not UTF-8) reaches the converter, which decides what to do with it. A record, fixed-width value, varint, tag or group that the protobuf parser would refuse is corrupt: the merge stops and names the part, as the whole-index parse @@ -50,6 +52,7 @@ def _load_harness_module(name: str) -> Any: project_owns = _ts_projects.project_owns project_scope = _ts_projects.project_scope scope_specificity = _ts_projects.scope_specificity +owner_key = _ts_projects.owner_key _converter = _load_harness_module("scip_to_delta") _read_index = _converter._read_index _top_level_records = _converter._top_level_records @@ -111,7 +114,11 @@ def merge_indexes( """Write the merged index; return the paths whose document it holds, as text.""" if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") - owners = known_projects if known_projects is not None else (projects or []) + # The plan names a member as argv text, where a directory whose name is not UTF-8 + # arrives surrogate-escaped; a document's path is the `replace` decoding of its raw + # bytes. Ownership compares the two, so both sides are the one key (`owner_key`). + owner_source = known_projects if known_projects is not None else (projects or []) + owners = [owner_key(project) for project in owner_source] metadata: list[Any] = [] documents: dict[bytes, Any] = {} external_symbols: list[Any] = [] @@ -120,7 +127,7 @@ def merge_indexes( data = _read_index(str(path)) if path.is_file() else b"" if not data: continue - project = projects[i] if projects is not None else None + project = owner_key(projects[i]) if projects is not None else None try: for field, payload in _top_level_records(data): if field == _METADATA and not has_payload: diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 203d766b949..755a3f31f7b 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -148,6 +148,8 @@ def __init__( ) -> None: self.root = source_root self.prefix = path_prefix.strip("/") + # the directory as the store names a path; the reads below open it by its own + self.key = _path_text(self.prefix) self._clauses: dict[str, str] = {} # scip-go's own kind per definition symbol # (SymbolInformation.kind: Struct, Interface, Field, Method, @@ -215,13 +217,13 @@ def scope(self, module: str, pkg_path: str) -> str | None: # root): the directory is the real one, the clause the package's # clause plus `_test` — the fast tier's `cht.cht_test` rel = pkg_path[len(module) :].strip("/")[: -len("_test")].rstrip("/") - directory = "/".join(p for p in (self.prefix, rel) if p) + directory = "/".join(p for p in (self.key, rel) if p) base_path = pkg_path[: -len("_test")] return f"{self.dir_scope(directory)}.{self.clause(rel, base_path)}_test" if not (pkg_path == module or pkg_path.startswith(module + "/")): return None rel = pkg_path[len(module) :].strip("/") - directory = "/".join(p for p in (self.prefix, rel) if p) + directory = "/".join(p for p in (self.key, rel) if p) return f"{self.dir_scope(directory)}.{self.clause(rel, pkg_path)}" @@ -945,6 +947,18 @@ def _document_path_bytes(payload: bytes) -> bytes: return _read_document_path(payload)[0] +def _path_text(path: str | bytes) -> str: + """One logical path as the store holds it: its bytes decoded as UTF-8 with + `replace`, the one decode policy of the harness. `bytes` is the raw name a git + list carries; a `str` is a name Python already decoded — argv, a directory + listing — whose undecodable bytes came back as lone surrogates + (`surrogateescape`), which this turns into the same replacement character. So a + path is one key on both sides of a comparison, and two paths that differ only by + a malformed byte stay distinct.""" + raw = path if isinstance(path, bytes) else path.encode("utf-8", "surrogateescape") + return raw.decode("utf-8", "replace") + + def _document_path(payload) -> str: """The relative_path as text; a malformed byte reads as U+FFFD. @@ -952,7 +966,7 @@ def _document_path(payload) -> str: reported under, so it must stay distinct per path: an undecodable path decodes with `replace` (the one decode policy of the harness, and the key the store holds), where "" would collapse every such path onto one shared key.""" - return _document_path_bytes(payload).decode("utf-8", "replace") + return _path_text(_document_path_bytes(payload)) class _Skips: @@ -1430,7 +1444,9 @@ def __init__( data, scip_pb2, source_root, exclude_generated, path_prefix, self._skips ) self._deleted = sorted(set(deleted)) - self._prefix = path_prefix + # the emitted paths are the store's keys, so the module's directory is decoded + # as a window's names are; `_prepare` keeps the checkout's own name to read by + self._prefix = _path_text(path_prefix.strip("/")) # A FULL index converted with its source claims the feature: the # server records that this namespace's compiler tier carries # constructor calls through factories, and code.callers stops @@ -1614,7 +1630,8 @@ def upload( def _strip_prefix(path: str, prefix: str) -> str: """A repository-relative changed path as the module-relative one the index - knows; a path outside the module is left as is (it matches nothing).""" + knows; a path outside the module is left as is (it matches nothing). Both are + the store's keys (`_path_text`), so an undecodable directory strips too.""" return path[len(prefix) + 1 :] if path.startswith(prefix + "/") else path @@ -1629,8 +1646,8 @@ def _path_list(path: str | None) -> list[str]: return [] raw = Path(path).read_bytes() if b"\0" in raw: - return [name.decode("utf-8", "replace") for name in raw.split(b"\0") if name] - text = raw.decode("utf-8", "replace") + return [_path_text(name) for name in raw.split(b"\0") if name] + text = _path_text(raw) return [line.strip() for line in text.splitlines() if line.strip()] @@ -1700,14 +1717,17 @@ def main() -> int: return 2 prefix = args.path_prefix.strip("/") + # The directory as the delta keys a path: a window's names are the `replace` + # decoding of git's bytes, and argv's may hold a lone surrogate. `prefix` itself + # stays the checkout's name, which is what the source reads open. + prefix_key = _path_text(prefix) changed = None if args.changed_files: - changed = { - _strip_prefix(c, prefix) if prefix else c for c in _path_list(args.changed_files) - } + names = _path_list(args.changed_files) + changed = {_strip_prefix(name, prefix_key) if prefix_key else name for name in names} deleted = _path_list(args.deleted_files) - if prefix: - deleted = [f"{prefix}/{_strip_prefix(d, prefix)}" for d in deleted] + if prefix_key: + deleted = [f"{prefix_key}/{_strip_prefix(d, prefix_key)}" for d in deleted] stream = DeltaStream( args.index, changed, diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index b928960db02..7862ae5092f 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -501,7 +501,7 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> return [] if any(is_shared_change(path) for path in changed_paths): return list(projects) - keys = {project: _key(project) for project in projects} + keys = {project: owner_key(project) for project in projects} selected = [ project for project in projects @@ -523,10 +523,11 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> return selected -def _key(path: str) -> str: +def owner_key(path: str) -> str: """A path as the store keys it: its bytes decoded as UTF-8 with `replace`, which is - what `scip_to_delta.py` keys a document by. A valid name is unchanged; a member - directory whose own name is not UTF-8 still matches the list entry for its files.""" + what `scip_to_delta.py` keys a document by (`_path_text`). A valid name is unchanged; + a member directory whose own name is not UTF-8 still matches the list entry for its + files, and stays distinct from another such name that replaces to the same text.""" return path.encode("utf-8", "surrogateescape").decode("utf-8", "replace") diff --git a/tests/unit/test_scip_path_encoding.py b/tests/unit/test_scip_path_encoding.py index b2e24893f76..c13c6ce8141 100644 --- a/tests/unit/test_scip_path_encoding.py +++ b/tests/unit/test_scip_path_encoding.py @@ -7,6 +7,7 @@ from __future__ import annotations import importlib.util +import json import os import subprocess import sys @@ -17,12 +18,20 @@ _HARNESS = _CONVERTER.parent _LIB = _HARNESS / "lib.sh" _TS_PROJECTS = _HARNESS / "scip_ts_projects.py" +_MERGE = _HARNESS / "scip_merge_indexes.py" _VALID = "src/café.ts" # UTF-8: 63 61 66 c3 a9 2e 74 73 _VALID_BYTES = b"src/caf\xc3\xa9.ts" _INVALID = b"src/caf\xe9.ts" # c3 a9 replaced by the single byte e9: not UTF-8 _KEY = "src/caf\ufffd.ts" # what `replace` decoding makes of _INVALID +# A project directory whose own name is not UTF-8: the harness names it as argv text +# (a lone surrogate, from the surrogate escape Python decodes those bytes with), a +# document path inside it as `replace`-decoded text. One key, `caf\ufffd`. +_BAD_DIR = b"caf\xe9" +_BAD_DIR_KEY = "caf\ufffd" +_BAD_DIR_ARG = _BAD_DIR.decode("utf-8", "surrogateescape") + def _git(cwd: Path, *args: str) -> str: return subprocess.run( @@ -144,6 +153,14 @@ def _ts_projects(): return mod +def _merge(): + spec = importlib.util.spec_from_file_location("scip_merge_indexes_encoding", _MERGE) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + def _index(tmp_path: Path) -> Path: """An index holding src/café.ts and a document whose path is the raw _INVALID bytes (`src/cafX.ts` is the same length as _INVALID, so every length prefix still holds @@ -233,3 +250,87 @@ def test_a_deleted_path_holding_a_newline_is_still_listed(tmp_path: Path) -> Non str(_index(tmp_path)), {"src/we\nird.ts"}, [_VALID], "h" * 40, base, source_root="" ) assert delta["deleted_files"] == [_VALID] + + +def _module_index(tmp_path: Path, names: list[str]) -> Path: + """An index of a module below the repository root: its document paths are + module-relative, and `--path-prefix` puts the module's directory back.""" + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///nonexistent-checkout" + for i, name in enumerate(names): + _add_doc(index, name, [(_fn(f"f{i}", "aa"), 0)], []) + path = tmp_path / "module.scip" + path.write_bytes(index.SerializeToString()) + return path + + +def _convert_bytes(tmp_path: Path, index: Path, *extra: bytes) -> dict: + """`scip_to_delta.py` over a window whose names are raw bytes: the module's + directory arrives as argv (which Python decodes with `surrogateescape`), the lists + as the NUL file git wrote.""" + out = tmp_path / "delta.json" + proc = subprocess.run( + [ + os.fsencode(sys.executable), + os.fsencode(_CONVERTER), + b"--index", + os.fsencode(index), + b"--commit", + b"h" * 40, + b"--source-root", + b"", + *extra, + b"--dry-run", + os.fsencode(out), + ], + capture_output=True, + ) + assert proc.returncode == 0, proc.stderr.decode("utf-8", "replace") + return json.loads(out.read_text()) + + +def test_a_deleted_file_under_an_undecodable_project_keeps_the_projects_key( + tmp_path: Path, +) -> None: + """The module's directory reaches the script as argv text holding a lone surrogate, + the window's names as `replace`-decoded text. Both are the same repository path only + after one decode: otherwise a deleted file under it carries the prefix twice and + names no row, and the module's own document is not the changed one.""" + changed = tmp_path / "changed.bin" + changed.write_bytes(_BAD_DIR + b"/a.ts\0") + deleted = tmp_path / "deleted.bin" + deleted.write_bytes(_BAD_DIR + b"/gone.ts\0") + + delta = _convert_bytes( + tmp_path, + _module_index(tmp_path, ["a.ts", "gone.ts"]), + b"--path-prefix", + _BAD_DIR, + b"--changed-files", + os.fsencode(changed), + b"--deleted-files", + os.fsencode(deleted), + ) + assert [f["path"] for f in delta["files"]] == [_BAD_DIR_KEY + "/a.ts"] + assert delta["deleted_files"] == [_BAD_DIR_KEY + "/gone.ts"] + + +def test_merge_keeps_a_document_of_a_member_whose_directory_is_not_utf8( + tmp_path: Path, +) -> None: + """The plan names the member as argv text (a surrogate escape), the merged document's + path as `replace`-decoded text; ownership compares the two. A member whose own name + is not UTF-8 owns its documents only after one decode — without it the merge is + empty and the converter cannot mark the member's document stale.""" + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///repo" + _add_doc(index, "cafX/a.ts", [(_fn("f", "aa"), 0)], []) + part = tmp_path / "app.scip" + # `cafX` is the same length as _BAD_DIR, so every length prefix still holds + part.write_bytes(index.SerializeToString().replace(b"cafX/", _BAD_DIR + b"/")) + + out = tmp_path / "merged.scip" + _merge().merge_indexes([part], out, projects=[_BAD_DIR_ARG]) + assert _BAD_DIR + b"/a.ts" in out.read_bytes() From 0225eda988683e1737f6f23bd7ca435d731e673c Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 20:16:11 +0000 Subject: [PATCH 64/81] A failed member's file with a tab in its name keeps its skip record MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `git ls-files` C-quotes a tracked name holding a tab or a newline unless `-z` is given, and the quoted line names no path. The merger read those lines as literal paths, so a failed member's file with a tab in its name matched no candidate, `--failed-paths` did not list it, and a full run's delta carried neither a conversion nor a skip record for it: the file fell out in silence, its rows neither refreshed nor marked stale. `git ls-files -z` in the shell, NUL-separated candidates into `scip_merge_indexes.py`, NUL-separated `--failed-paths` out, and a note in the harness README. The converter's `_path_list` already splits on NUL when present and falls back to lines, so the C++/Python/Go windows are untouched — their window lists already carried `-z`, and this was the one list still shaped by lines. Pinned: a tab-named file of a failed member is listed as failed, and a full pass carries the same file in `skipped_files` through the real converter. Second, no behaviour change: a mark at a path holding no blob at the delta's commit — a deletion, a tree, a gitlink — retires, because `_gone_at` answers the tree's blobs only and no convertible document can ever refresh rows at a path that holds none. Pinned without the store in `test_a_mark_at_a_gitlink_retires_and_a_blob_keeps_its_mark`; the clickhouse twin in `test_scip_gone_at_bytes.py` stays as it was. Refs #1973 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/README.md | 3 +- scripts/scip_harness/run_typescript_delta.sh | 6 +- scripts/scip_harness/scip_merge_indexes.py | 21 ++++--- scripts/scip_harness/scip_to_delta.py | 3 +- .../unit/test_code_scip_skipped_documents.py | 55 +++++++++++++++++++ .../test_run_typescript_delta_umbrella.py | 46 +++++++++++++++- tests/unit/test_scip_merge_indexes.py | 33 +++++++++-- 7 files changed, 149 insertions(+), 18 deletions(-) diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 40d3dea3f7c..517be06a21c 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -56,7 +56,8 @@ records cannot be read to the end fails the run either way. `run_typescript_delta.sh` treats a member whose scip-typescript exits with an error the same way: the other members' parts are merged, and the files the -failed member owns go to the converter as `--failed-files`. Those in the +failed member owns go to the converter as `--failed-files`, NUL-separated so a +name holding a tab or a newline arrives as the one path it is. Those in the delta are warned about, counted and listed in `skipped_files`; a converted file that refers to a constant defined in one of them is skipped too. The pass fails instead with `SCIP_STOP_ON_FAILED_DOCUMENT=1`, when a member is diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index d215f24326e..63fa8a5ce43 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -292,7 +292,11 @@ JSONEOF # Every file a failed run's members own: the converter lists only the delta's # own as skipped (`DeltaStream.tail`) and needs the rest to know which # references lost their definition. - git_paths ls-files -- "${TS_GLOBS[@]}" >"$WORK/candidates.txt" + # `-z`: a name holding a tab or a newline is C-quoted on a line list, and a + # quoted line names no path, so the file would lose its skip record. NUL-separated, + # the raw bytes reach the merge, which writes the failed list back NUL-separated + # for the converter. + git_paths ls-files -z -- "${TS_GLOBS[@]}" >"$WORK/candidates.txt" local failed_members=$'\n' for i in "${!pair_run[@]}"; do case " ${failed_runs[*]} " in diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index c751791fd5b..9c85b286a8e 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -223,7 +223,9 @@ def main(argv: list[str] | None = None) -> int: help="a member whose indexer failed; with --paths, the paths it owns are " "written to --failed-paths", ) - parser.add_argument("--paths", type=Path, help="newline list of candidate paths") + parser.add_argument( + "--paths", type=Path, help="candidate paths, NUL-separated (`git ls-files -z`)" + ) parser.add_argument("--failed-paths", type=Path, help="where the failed members' paths go") parser.add_argument("indexes", nargs="+", type=Path) args = parser.parse_args(argv) @@ -231,15 +233,16 @@ def main(argv: list[str] | None = None) -> int: known = args.known_project or None kept = merge_indexes(args.indexes, args.output, projects, known) if args.failed_paths is not None: - # git prints a name that is not UTF-8 as its raw bytes - text = ( - args.paths.read_text(encoding="utf-8", errors="surrogateescape") if args.paths else "" - ) - lines = text.splitlines() - candidates = [line for line in lines if line] + # git prints a name that is not UTF-8 as its raw bytes. The candidate list is + # NUL-separated (`git ls-files -z`): a name holding a tab or a newline rides it + # as the one path it is, where a line list carries a C-quoted line that names + # nothing and the file would lose its skip record. + text = args.paths.read_bytes().decode("utf-8", "surrogateescape") if args.paths else "" + candidates = [part for part in text.split("\0") if part] failed = owned_by(candidates, args.failed_project, known or args.failed_project, kept) - args.failed_paths.write_text( - "".join(f"{path}\n" for path in failed), encoding="utf-8", errors="surrogateescape" + # NUL-separated too: the converter reads it as the same raw bytes. + args.failed_paths.write_bytes( + b"".join(f"{path}\0".encode("utf-8", "surrogateescape") for path in failed) ) return 0 diff --git a/scripts/scip_harness/scip_to_delta.py b/scripts/scip_harness/scip_to_delta.py index 71883446ad9..6865993b3ea 100644 --- a/scripts/scip_harness/scip_to_delta.py +++ b/scripts/scip_harness/scip_to_delta.py @@ -1744,7 +1744,8 @@ def main() -> int: ) ap.add_argument( "--failed-files", - help="newline list of files whose indexer run failed (a TypeScript member, say): " + help="NUL-separated list of files whose indexer run failed (a TypeScript member, " + "say): " "listed as skipped, so the server keeps their rows and marks them stale", ) ap.add_argument( diff --git a/tests/unit/test_code_scip_skipped_documents.py b/tests/unit/test_code_scip_skipped_documents.py index aa212bd05e0..cf1da542b88 100644 --- a/tests/unit/test_code_scip_skipped_documents.py +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -7,7 +7,10 @@ import asyncio import logging +import os +import subprocess from pathlib import Path +from types import SimpleNamespace from unittest.mock import AsyncMock import pytest @@ -271,3 +274,55 @@ def test_an_upload_applies_for_the_tier_whose_watermark_it_moves() -> None: "typescript", "go", ] + + +def _mirror_holding_a_gitlink(tmp_path: Path) -> tuple[str, str]: + """A mirror whose commit holds `vendor/lib` as a gitlink (mode 160000, no blob) and + `src/a.cpp` as a blob. A gitlink is one tree entry naming a commit, so no submodule + is checked out and the object store still holds it.""" + work = tmp_path / "work" + (work / "src").mkdir(parents=True) + env = { + **os.environ, + "GIT_AUTHOR_NAME": "t", + "GIT_AUTHOR_EMAIL": "t@t", + "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@t", + } + + def run(*args: str) -> str: + done = subprocess.run( + ["git", *args], cwd=work, check=True, capture_output=True, text=True, env=env + ) + return done.stdout.strip() + + run("init", "-q") + (work / "src" / "a.cpp").write_text("int a;\n") + run("add", "-A") + run("commit", "-qm", "one") + first = run("rev-parse", "HEAD") + run("read-tree", "HEAD") + run("update-index", "--add", "--cacheinfo", f"160000,{first},vendor/lib") + tree = run("write-tree") + commit = run("commit-tree", tree, "-p", first, "-m", "gitlink") + assert run("ls-tree", "-r", commit, "vendor/lib").startswith("160000 commit ") + return str(work / ".git"), commit + + +@pytest.mark.asyncio +async def test_a_mark_at_a_gitlink_retires_and_a_blob_keeps_its_mark( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A mark retires at a path that holds no blob at the delta's commit: a gitlink is a + tree entry with no document to convert, so no later delta can ever refresh its rows + (#1704's decision, pinned here without the store). A path that still holds a blob + keeps its mark, and a commit the mirror lacks proves nothing, so it keeps every mark. + """ + git_dir, commit = _mirror_holding_a_gitlink(tmp_path) + monkeypatch.setattr( + "server.code.domain.index.repos.repo_for_namespace", + lambda org, ns: SimpleNamespace(git_dir=git_dir), + ) + paths = {"vendor/lib", "src/a.cpp"} + assert await scip_delta._gone_at("o", "n", commit, paths) == {"vendor/lib"} + assert await scip_delta._gone_at("o", "n", "f" * 40, paths) == set() diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 7a34c1c62c8..cec1387025d 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -54,7 +54,15 @@ args=("$@") for ((i = 0; i < ${#args[@]}; i++)); do if [[ "${args[i]}" == --failed-files ]]; then - while IFS= read -r p; do printf 'failed\\t%s\\n' "$p" >>"$CALLS"; done <"${args[i + 1]}" + f="${args[i + 1]}" + # A name holding a tab or a newline rides the list NUL-separated, one entry, as + # the merge writes it; a plain list stays newline-separated. Read either shape, + # as the converter's `_path_list` reads it. + if [[ $(wc -c <"$f") -ne $(tr -d '\\000' <"$f" | wc -c) ]]; then + while IFS= read -r -d '' p; do printf 'failed\\t%s\\n' "$p" >>"$CALLS"; done <"$f" + else + while IFS= read -r p; do printf 'failed\\t%s\\n' "$p" >>"$CALLS"; done <"$f" + fi fi done while [[ $# -gt 0 ]]; do @@ -319,6 +327,42 @@ def test_a_failing_member_leaves_the_others_and_lists_its_files(tmp_path: Path) assert "--full" in _convert_args(log) +def test_a_failed_members_file_with_a_tab_in_its_name_is_listed_as_failed( + tmp_path: Path, +) -> None: + """git C-quotes a name holding a tab on a line list, and the quoted line names + no path; `ls-files -z` carries the raw bytes to the merge, so the failed member's + file still reaches the converter and keeps its rows, marked stale.""" + repo = _repo(tmp_path) + (repo / "packages/lib/src/a\tb.ts").write_text("export const ab = 1;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "tab") + head = _git(repo, "rev-parse", "HEAD") + proc, log = _run_status(tmp_path, repo, "--full", head, {"FAIL_TARGET": "packages/lib"}) + assert proc.returncode == 0, proc.stderr + assert _failed(log) == ["packages/lib/src/a\tb.ts", "packages/lib/src/b.ts"] + + +def test_a_full_pass_lists_a_failed_file_whose_name_holds_a_tab(tmp_path: Path) -> None: + """The skip record survives the whole way: `ls-files -z` names the file, the + merge writes the failed list NUL-separated, and the real converter lists the file + as skipped, so the server keeps its rows and marks them stale.""" + repo = _repo(tmp_path) + (repo / "packages/lib/src/a\tb.ts").write_text("export const ab = 1;\n") + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "tab") + head = _git(repo, "rev-parse", "HEAD") + proc, _ = _run_status( + tmp_path, repo, "--full", head, {"FAIL_TARGET": "packages/lib", "REAL_CONVERT": "1"} + ) + assert proc.returncode == 0, proc.stderr + delta = json.loads((tmp_path / "delta.json").read_text()) + assert delta["skipped_files"] == [ + "packages/lib/src/a\tb.ts", + "packages/lib/src/b.ts", + ] + + def test_a_failing_member_in_a_delta_lists_every_file_it_owns(tmp_path: Path) -> None: """The converter lists only the window's files as skipped; it needs the rest to know which references in the window lost their definition.""" diff --git a/tests/unit/test_scip_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index 25eeb41a92e..56318e9a6a0 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -342,18 +342,19 @@ def test_a_failed_member_owns_the_paths_the_merge_would_take_from_it() -> None: assert _MOD.owned_by(paths, ["tsconfig.repo.json"], known) == ["eslint.config.mjs", "x/y.ts"] -def _failed_paths(tmp_path: Path, indexed: str, failed: str, docs: list[str]) -> str: +def _failed_paths(tmp_path: Path, indexed: str, failed: str, docs: list[str]) -> list[str]: """Root `tsconfig.app.json` and `tsconfig.node.json`, one indexed, one failed.""" part = tmp_path / "part.scip" part.write_bytes(_index_with_docs(docs)) candidates = tmp_path / "candidates.txt" - candidates.write_text("src/main.ts\nsrc/App.tsx\nvite.config.ts\n") + # NUL-separated, as `git ls-files -z` writes it. + candidates.write_bytes(b"src/main.ts\0src/App.tsx\0vite.config.ts\0") out = tmp_path / "failed.txt" args = ["--output", str(tmp_path / "merged.scip"), "--project", indexed] args += ["--known-project", "tsconfig.app.json", "--known-project", "tsconfig.node.json"] args += ["--failed-project", failed, "--paths", str(candidates), "--failed-paths", str(out)] assert _MOD.main([*args, str(part)]) == 0 - return out.read_text() + return [part for part in out.read_bytes().decode("utf-8").split("\0") if part] def test_a_failing_sibling_tsconfig_fails_only_the_files_no_sibling_indexed( @@ -364,11 +365,33 @@ def test_a_failing_sibling_tsconfig_fails_only_the_files_no_sibling_indexed( app_failed = _failed_paths( tmp_path, "tsconfig.node.json", "tsconfig.app.json", ["vite.config.ts"] ) - assert app_failed == "src/main.ts\nsrc/App.tsx\n" + assert app_failed == ["src/main.ts", "src/App.tsx"] node_failed = _failed_paths( tmp_path, "tsconfig.app.json", "tsconfig.node.json", ["src/main.ts", "src/App.tsx"] ) - assert node_failed == "vite.config.ts\n" + assert node_failed == ["vite.config.ts"] + + +def test_a_failed_path_with_a_tab_in_its_name_is_written_back_intact( + tmp_path: Path, +) -> None: + """A candidate list is NUL-separated, so a name holding a tab rides it as the one + path it is instead of a C-quoted line naming nothing; the failed list comes back + NUL-separated too, and the converter reads that name as skipped.""" + part = tmp_path / "part.scip" + part.write_bytes(_index_with_docs(["vite.config.ts"])) + candidates = tmp_path / "candidates.txt" + candidates.write_bytes(b"src/main.ts\0src/a\tb.ts\0vite.config.ts\0") + out = tmp_path / "failed.txt" + args = ["--output", str(tmp_path / "merged.scip"), "--project", "tsconfig.node.json"] + args += ["--known-project", "tsconfig.app.json", "--known-project", "tsconfig.node.json"] + args += ["--failed-project", "tsconfig.app.json", "--paths", str(candidates)] + args += ["--failed-paths", str(out)] + assert _MOD.main([*args, str(part)]) == 0 + assert [p for p in out.read_bytes().decode("utf-8").split("\0") if p] == [ + "src/main.ts", + "src/a\tb.ts", + ] def test_merge_copies_a_document_whose_strings_are_not_utf8(tmp_path: Path) -> None: From 29d0998029b5fd25f718813b51f419ecb8d6e1fa Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 01:43:40 +0000 Subject: [PATCH 65/81] Each bound list in a staleness read stays inside one ClickHouse form field MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 200-path round of 192-byte paths bound its marks — four a path, 800 strings — as one HTTP form field of 171,000 bytes, past `http_max_field_value_size` (128 KiB by default). clickhouse-connect sends every parameter longer than 4 KiB as such a field, so ClickHouse refused the statement, and the staleness answer it carries fell open to "every asked path is stale" for every walk of that size. The path list alone rendered 39,200 bytes. `scip_stale_paths` now reads the asked paths in groups where both of the statement's list parameters render within `FIELD_BYTES`: the paths, and each path's mark under every tier. The two are cut together — a mark bound apart from its path reads that path fresh in the statement that lacks it. Its sibling `scip_covered_paths` is cut the same way; at 340-byte paths a 200-path round rendered 68,800 bytes, past the 64 KiB the statement is written to. `server/core/ch_params.py` gains `chunks_multi`, which takes a value's width per list parameter, and `rendered_width`; `chunks` is the one-parameter case. Both reads answer every path they are given: the `[:200]` truncations are gone, and a path past that bound read fresh before this change. tests/analyzer/shapes.txt is regenerated for the state read that now excludes both `scip_stale:` and `scip_applied:`. Signed-off-by: Kaloyan Naumov --- server/code/store/index/symbols.py | 102 ++++++++++------- server/core/ch_params.py | 42 +++++-- tests/analyzer/shapes.txt | 2 +- .../unit/test_code_scip_stale_field_bound.py | 105 ++++++++++++++++++ 4 files changed, 201 insertions(+), 50 deletions(-) create mode 100644 tests/unit/test_code_scip_stale_field_bound.py diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 0b248a7935f..aaaa098490e 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -5,6 +5,7 @@ from __future__ import annotations +from collections.abc import Iterator from typing import Any from clickhouse_connect.driver.binding import format_bind_value @@ -24,7 +25,7 @@ demote_noise_paths, return_type_from_signature, ) -from server.core.ch_params import FIELD_BYTES, chunks +from server.core.ch_params import FIELD_BYTES, chunks, chunks_multi, rendered_width NameCandidates = dict[str, list[tuple[str, str, str]]] @@ -53,6 +54,21 @@ def _marks_in_force(keys: str) -> str: """ +def _stale_read_groups(paths: list[str]) -> Iterator[list[str]]: + """`paths` grouped so one statement's two list parameters each render within + `FIELD_BYTES`: the paths, and every path's mark under each tier. The marks list is + the larger — four marks a path, each prefixed — and it is the one a round of long + paths pushes past the field's bound. Both are cut together because a mark answers + for its own path: a mark bound in another statement reads that path fresh here.""" + return chunks_multi( + paths, + widths=lambda p: ( + rendered_width(p), + sum(rendered_width(f"{SCIP_STALE_PREFIX}{t.producer}:{p}") for t in TIERS), + ), + ) + + def _concat_key_parts(refs: list[str]) -> str: """Keep each concatenation small even for a name spanning thousands of fields.""" while len(refs) > 1: @@ -566,20 +582,25 @@ async def scip_covered_paths(self, org: str, ns: str, paths: list[str]) -> set[s keyed by batch with no path column and a seven-day TTL, so they cannot say which files the tier covers now. `tier` leads the sort key after the identity and the path - bloom filter prunes the rest; plain WHERE.""" + bloom filter prunes the rest; plain WHERE. The paths travel in lists that each + fit one HTTP form field (`chunks`), so a round of long paths is read in parts + rather than refused whole.""" if not paths: return set() - rows = await self._ch.query_all( - """ - SELECT DISTINCT path - FROM loom.code_symbols FINAL - WHERE org = {org:String} AND namespace = {ns:String} - AND tier = 'scip' AND path IN {paths:Array(String)} - AND tombstoned_at IS NULL - """, - {"org": org, "ns": ns, "paths": paths[:200]}, - ) - return {str(r["path"]) for r in rows} + covered: set[str] = set() + for part in chunks(list(dict.fromkeys(paths))): + rows = await self._ch.query_all( + """ + SELECT DISTINCT path + FROM loom.code_symbols FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND tier = 'scip' AND path IN {paths:Array(String)} + AND tombstoned_at IS NULL + """, + {"org": org, "ns": ns, "paths": part}, + ) + covered |= {str(r["path"]) for r in rows} + return covered async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str]: """Paths a compiler-tier edge may not be read from as current: the fast tier @@ -592,34 +613,39 @@ async def scip_stale_paths(self, org: str, ns: str, paths: list[str]) -> set[str is a tree the compiler tier's rows no longer describe; a skipped document left the rows of its earlier state, until this build applies the file again or, for an entry whose tier its worker runs, that worker's pass finds a later apply of it - published (`_marks_in_force`).""" + published (`_marks_in_force`). Both lists travel in statements that each fit one + HTTP form field, `paths` and its four marks a path cut together + (`_stale_read_groups`).""" if not paths: return set() - asked = list(dict.fromkeys(paths))[:200] - # the asked paths' marks under every tier: point keys, never the whole prefix - marks = [f"{SCIP_STALE_PREFIX}{t.producer}:{p}" for t in TIERS for p in asked] - rows = await self._ch.query_all( - """ - WITH - (SELECT maxIf(updated_at, state_key = 'scip_commit') - FROM loom.code_index_state FINAL - WHERE org = {org:String} AND namespace = {ns:String}) AS t_scip, - (SELECT maxIf(updated_at, state_key = 'scip_commit_py') - FROM loom.code_index_state FINAL - WHERE org = {org:String} AND namespace = {ns:String}) AS t_py - SELECT path - FROM loom.code_files FINAL - WHERE org = {org:String} AND namespace = {ns:String} - AND path IN {paths:Array(String)} AND tombstoned_at IS NULL - AND created_at <= if(endsWith(path, '.py') AND t_py > toDateTime(0), t_py, t_scip) - AND path NOT IN (""" - + _marks_in_force("state_key IN {marks:Array(String)}") - + """) - """, - {"org": org, "ns": ns, "paths": asked, "marks": marks}, - ) + asked = list(dict.fromkeys(paths)) + fresh: set[str] = set() + for group in _stale_read_groups(asked): + # the group's marks under every tier: point keys, never the whole prefix + marks = [f"{SCIP_STALE_PREFIX}{t.producer}:{p}" for t in TIERS for p in group] + rows = await self._ch.query_all( + """ + WITH + (SELECT maxIf(updated_at, state_key = 'scip_commit') + FROM loom.code_index_state FINAL + WHERE org = {org:String} AND namespace = {ns:String}) AS t_scip, + (SELECT maxIf(updated_at, state_key = 'scip_commit_py') + FROM loom.code_index_state FINAL + WHERE org = {org:String} AND namespace = {ns:String}) AS t_py + SELECT path + FROM loom.code_files FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND path IN {paths:Array(String)} AND tombstoned_at IS NULL + AND created_at <= if(endsWith(path, '.py') AND t_py > toDateTime(0), t_py, t_scip) + AND path NOT IN (""" + + _marks_in_force("state_key IN {marks:Array(String)}") + + """) + """, + {"org": org, "ns": ns, "paths": group, "marks": marks}, + ) + fresh |= {str(r["path"]) for r in rows} # the query names the FRESH paths; every other asked path is stale - return set(asked) - {str(r["path"]) for r in rows} + return set(asked) - fresh async def scip_stale_marks(self, org: str, ns: str, tier: str | None = None) -> set[str]: """The paths `tier` (every tier when None) holds marked stale diff --git a/server/core/ch_params.py b/server/core/ch_params.py index 533c26ead51..bdb93ec1bfd 100644 --- a/server/core/ch_params.py +++ b/server/core/ch_params.py @@ -9,7 +9,7 @@ from __future__ import annotations -from collections.abc import Iterator, Sequence +from collections.abc import Callable, Iterator, Sequence from clickhouse_connect.driver.binding import format_bind_value @@ -18,24 +18,44 @@ FIELD_BYTES = 64 * 1024 # not a setting: follows ClickHouse's default field limit -def chunks[T](values: Sequence[T], *, limit: int = FIELD_BYTES) -> Iterator[list[T]]: - """`values` in order, in lists whose rendered parameter (`[v1, v2, ...]`) is at - most `limit` bytes of UTF-8; a value longer than `limit` on its own is a chunk - alone.""" +def rendered_width(value: object) -> int: + """The bytes `value` adds to a bound list parameter: its rendering, and the `, ` + that separates it from its neighbour. Bytes, as the field is measured: a CJK + character is three of them.""" + return len(format_bind_value(value, top_level=False).encode()) + 2 + + +def chunks_multi[T]( + values: Sequence[T], *, widths: Callable[[T], Sequence[int]], limit: int = FIELD_BYTES +) -> Iterator[list[T]]: + """`values` in order, in lists where the rendering of EVERY parameter they feed is + at most `limit` bytes. `widths(value)` gives, in the order the statement binds its + parameters, the bytes the value adds to each (see `rendered_width`); the brackets + count once a list is opened. A value wider than `limit` on one parameter is a chunk + alone — no cut of the list makes it fit — so it meets the bound's error itself + instead of taking a neighbour with it.""" chunk: list[T] = [] - size = 2 # the brackets + sizes: list[int] = [] for value in values: - # Bytes, as the field is measured: a CJK character is three of them. - width = len(format_bind_value(value, top_level=False).encode()) + 2 # and its ", " - if chunk and size + width > limit: + added = list(widths(value)) + if sizes and any(s + a > limit for s, a in zip(sizes, added, strict=True)): yield chunk - chunk, size = [], 2 + chunk, sizes = [], [] + if not sizes: + sizes = [2] * len(added) # the brackets chunk.append(value) - size += width + sizes = [s + a for s, a in zip(sizes, added, strict=True)] if chunk: yield chunk +def chunks[T](values: Sequence[T], *, limit: int = FIELD_BYTES) -> Iterator[list[T]]: + """`values` in order, in lists whose rendered parameter (`[v1, v2, ...]`) is at + most `limit` bytes of UTF-8; a value longer than `limit` on its own is a chunk + alone.""" + return chunks_multi(values, widths=lambda value: (rendered_width(value),), limit=limit) + + def fitting[T](values: Sequence[T], *, limit: int = FIELD_BYTES) -> list[T]: """The leading values of `values` that one parameter of at most `limit` bytes carries (all of them when they fit).""" diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index dc2305d6699..b3d5fc73661 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -1787,7 +1787,6 @@ c6c8bd9f5afd SELECT operation, sumMerge(cost_usd_state) AS cost_usd, sumMerge(to c6cde2e02fad ALTER TABLE loom.conversations DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? c6d2cd622bdf SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g c6e9dc907dc7 SELECT value FROM loom.oauth_signin_state WHERE claim_key = {k:String} -c7139b45f19a SELECT state_key, state_value, detail, updated_at FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND NOT startsWith(state_key, {stale:String}) ORDER BY state_key c71b88136b17 SELECT count() AS n FROM loom.learnings_supporters WHERE org = {org:String} AND user_id = {uid:String} AND ? c72e7e6dceb9 SELECT count() AS n FROM loom.working_memory FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String} c764a0b2a60f SELECT src_path, test_path, max(confidence) AS confidence FROM loom.code_test_map FINAL WHERE org = {org:String} AND namespace = {ns:String} AND src_path IN {paths:Array(String)} AND tombstoned_at IS @@ -2251,6 +2250,7 @@ f51e0ce42dcd SELECT count() OVER () AS total, memory_key, toString(memory_id) AS f52e30d82733 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g f5ddaf977ab5 SELECT state_key, state_value AS value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state_key IN {keys:Array(String)} f60a04215196 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user +f60eaaa910c4 SELECT state_key, state_value, detail, updated_at FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND NOT startsWith(state_key, {stale:String}) AND NOT startsWith f617d9867707 SELECT count() AS n FROM loom.memory_code_links WHERE org = {org:String} AND namespace IN {ns:Array(String)} f62c0f3f47ea DELETE FROM loom.code_answers WHERE (org = {org:String} AND (namespace IN {ns:Array(String)} OR memory_namespace IN {ns:Array(String)})) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:Stri f646cb42e8e3 ALTER TABLE loom.derived_facts DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? diff --git a/tests/unit/test_code_scip_stale_field_bound.py b/tests/unit/test_code_scip_stale_field_bound.py new file mode 100644 index 00000000000..f78331eff8c --- /dev/null +++ b/tests/unit/test_code_scip_stale_field_bound.py @@ -0,0 +1,105 @@ +"""A staleness read for a round of long paths stays inside one ClickHouse form field. + +`scip_stale_paths` binds the asked paths and, per path, a mark under each of the four +tiers: 800 strings for a 200-path round. ClickHouse refuses a bound HTTP form field over +`http_max_field_value_size` (128 KiB by default), and the driver sends every parameter +longer than 4 KiB as such a field, so an unbounded read fails the whole statement — and +what answers it falls open to "every asked path is stale" for every walk of that size. + +Measured on the round below, before the split: the path list renders 39,200 bytes and +the mark list 171,000. +""" + +from __future__ import annotations + +from typing import Any + +import pytest +from clickhouse_connect.driver.binding import format_bind_value + +from server.code.domain.index.compiler_tiers import TIERS +from server.code.store.index import CodeRepo + +# The server's refusal, and the budget the statement is written to: half of it, for the +# driver's quoting and a server configured lower (server/core/ch_params.py). +SERVER_FIELD_LIMIT = 128 * 1024 +FIELD_BUDGET = 64 * 1024 +ROUND = 200 +PATH_BYTES = 192 + + +def _path(i: int, width: int = PATH_BYTES) -> str: + """A distinct path of exactly `width` bytes.""" + head, tail = f"src/mod{i:04d}/", f"{i:04d}" + return head + "d" * (width - len(head) - len(tail)) + tail + + +class _FieldBoundCH: + """A ClickHouse that refuses a bound parameter past its field limit, as the HTTP + interface does, and reports which of the paths a statement asked about are fresh.""" + + def __init__(self, fresh: set[str]) -> None: + self.fresh = fresh + self.reads: list[dict[str, Any]] = [] + + async def query_all( + self, sql: str, params: dict[str, Any] | None = None + ) -> list[dict[str, Any]]: + params = dict(params or {}) + self.reads.append(params) + for name, value in params.items(): + size = len(format_bind_value(value).encode()) + if size > SERVER_FIELD_LIMIT: + raise RuntimeError(f"Field value too long: {name} renders {size} bytes") + asked = {str(p) for p in params.get("paths", [])} + return [{"path": p} for p in sorted(asked & self.fresh)] + + +def _fields(ch: _FieldBoundCH) -> list[dict[str, Any]]: + assert ch.reads, "the read issued no statement" + return ch.reads + + +@pytest.mark.asyncio +async def test_a_round_of_long_paths_never_renders_a_field_past_the_bound() -> None: + paths = [_path(i) for i in range(ROUND)] + assert len(set(paths)) == ROUND + assert all(len(p.encode()) == PATH_BYTES for p in paths) + fresh = set(paths[::7]) + ch = _FieldBoundCH(fresh) + + stale = await CodeRepo(ch).scip_stale_paths("o", "n", paths) # type: ignore[arg-type] + + assert stale == set(paths) - fresh, "every asked path is answered, fresh or stale" + seen: set[str] = set() + for params in _fields(ch): + for name, value in params.items(): + assert len(format_bind_value(value).encode()) <= FIELD_BUDGET, name + asked = {str(p) for p in params["paths"]} + # The two lists are one statement's: a path's mark cannot be bound apart from + # the path, or this statement reads it fresh. + assert {str(m) for m in params["marks"]} == { + f"scip_stale:{t.producer}:{p}" for t in TIERS for p in asked + } + seen |= asked + assert seen == set(paths) + assert len(ch.reads) > 1, "one field cannot carry the round" + + +@pytest.mark.asyncio +async def test_a_covered_paths_round_never_renders_a_field_past_the_bound() -> None: + # 340 bytes a path: the round still fits the server's field, and passes the budget + # the coverage read is written to only when the list is cut. + paths = [_path(i, 340) for i in range(ROUND)] + assert all(len(p.encode()) == 340 for p in paths) + ch = _FieldBoundCH(set(paths[::5])) + + covered = await CodeRepo(ch).scip_covered_paths("o", "n", paths) # type: ignore[arg-type] + + assert covered == set(paths[::5]) + seen: set[str] = set() + for params in _fields(ch): + for name, value in params.items(): + assert len(format_bind_value(value).encode()) <= FIELD_BUDGET, name + seen |= {str(p) for p in params["paths"]} + assert seen == set(paths) From a36342706f94095da51de94edeab2349b5da4d86 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 01:54:28 +0000 Subject: [PATCH 66/81] A member's run that drops a sibling reference keeps its own failure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A member whose tsconfig references a sibling member generates a config without the reference, so its run indexes that member's documents alone — but `own` was 0 for it (it did not run alone before), and the pass read every `own` 0 failure as a shared project's: `exit $rc`, discarding every other member's work. The PR's own case, since project references are the shape of a TypeScript monorepo: a healthy app and a lib that references it, the lib's generated config exits 1, the app's delta was thrown away. The plan now answers two questions instead of one. `own` still says whether an empty run is a failure (a member that ran alone before); `exclusive` says the run is a member's own project whose pairs name that member alone, and only `exclusive` decides whether a failure is that member's or the pass's. The empty check moves out of the shared branch, keyed on `own` alone, so an exclusive run reads its empty the way a shared one did. Red: tests/unit/test_run_typescript_delta_umbrella.py::test_a_members_run_that_drops_a_sibling_reference_keeps_its_own_failure — ">> scip-typescript failed on packages/lib/.scip-norefs.*.tsconfig.json (exit 1)", the pass exits 1, no convert. Green: exit 0, packages/app's index merged and converted, packages/lib/src/b.ts in the failed list. `plan` on the same tree: `index 1 packages/lib/.scip-norefs.*.tsconfig.json 0 1`. --- scripts/scip_harness/run_typescript_delta.sh | 37 ++++++---- scripts/scip_harness/scip_ts_projects.py | 33 +++++++-- .../test_run_typescript_delta_umbrella.py | 69 +++++++++++++++++++ tests/unit/test_scip_ts_projects.py | 37 +++++++++- 4 files changed, 153 insertions(+), 23 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 63fa8a5ce43..a1dc0f2238f 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -209,22 +209,26 @@ JSONEOF # # A member whose indexer fails leaves the others: the files it would have given # the merge go to the converter as failed, so the server keeps their rows and - # marks them stale. A shared project of the closures is not one member's to - # lose, so its failure fails the pass. With SCIP_STOP_ON_FAILED_DOCUMENT=1, a - # member killed by a signal, or a pass whose every member failed, the pass - # fails too. - local plan kind run own arg i runs=() owns=() parts=() merge_args=() known_args=() t rc + # marks them stale. A member whose tsconfig references a sibling is no + # exception: its run drops that reference into a generated config, so it reads + # no sibling's document and the sibling's delta does not need its output. A + # shared project of the closures — one no member owns, or one more than one + # member's merge reads — is not one member's to lose, so its failure fails the + # pass. With SCIP_STOP_ON_FAILED_DOCUMENT=1, a member killed by a signal, or a + # pass whose every member failed, the pass fails too. + local plan kind run own excl arg i runs=() owns=() exclusive=() parts=() merge_args=() known_args=() t rc local -a pair_run=() pair_member=() failed_runs=() run_ok=() for t in "${ALL_PROJECTS[@]}"; do known_args+=(--known-project "$t") done plan=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" plan "$CHECKOUT" "${known_args[@]}" -- "${targets[@]}") - while IFS=$'\t' read -r kind run arg own; do + while IFS=$'\t' read -r kind run arg own excl; do case "$kind" in config) on_exit "rm -f $(printf %q "$run")" ;; index) runs[run]=$arg owns[run]=$own + exclusive[run]=$excl ;; merge) # One merge input per (run, member) pair: the merge keeps the documents @@ -245,15 +249,18 @@ JSONEOF continue fi # A referenced project that matches no file was harmless inside a member's - # process; alone it is an empty part, which the merge reads as empty. - if [[ "${owns[run]}" == 0 ]]; then - if indexed_no_file "$run" "$rc"; then - echo ">> ${runs[run]} indexed no file — read as empty" >&2 - run_ok[run]=1 - continue - fi - # An internal project of the closures: its documents are the input of more - # than one member's merge, so a failure here is not one member's to lose. + # process; alone it is an empty part, which the merge reads as empty. Which + # members use the run says nothing about this: a member's own run that drops + # its references can be empty the same way. + if [[ "${owns[run]}" == 0 ]] && indexed_no_file "$run" "$rc"; then + echo ">> ${runs[run]} indexed no file — read as empty" >&2 + run_ok[run]=1 + continue + fi + # A project no member owns, or one more than one member's merge reads: its + # documents are another member's input too, so its failure is not one + # member's to lose. + if [[ "${exclusive[run]}" == 0 ]]; then echo ">> scip-typescript failed on ${runs[run]} (exit $rc)" >&2 exit "$rc" fi diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index b928960db02..7bd104bdd6c 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -211,12 +211,18 @@ def _expand_references(checkout: Path, tsconfig: Path, data: dict, seen: set[Pat class ProjectRun(NamedTuple): """One scip-typescript process over the project of `config`, named by `target`. With `drop_references` the process gets instead a generated config - that extends `config` without its references, which `write_plan` creates.""" + that extends `config` without its references, which `write_plan` creates. + + `own` says the member ran alone in a single process before, so an empty run + is still a failure; it is one question. `exclusive` says the run is a + member's own project that no other member's merge reads, so a failure takes + only that member's rows: another question, asked of the merge's pairs.""" target: str config: Path drop_references: bool = False own: bool = False + exclusive: bool = False def _indexer_config(checkout: Path, root: str) -> Path: @@ -334,6 +340,11 @@ def plan_project_runs( left with no pair does not run. `known` is the full member set the merge assigns ownership over (default: the targets). + A run is `exclusive` when it is a member's own project and the pairs name + that member alone. A member whose tsconfig references a sibling still runs + alone: the generated config drops the reference, and the sibling's documents + belong to the sibling's own run, so a failure here is that member's. + `references` is the one tsconfig field `extends` does not inherit, so the generated config indexes the same files with the same options. A project outside the checkout, or a jsconfig.json (scip-typescript adds compiler @@ -343,6 +354,7 @@ def plan_project_runs( known = targets if known is None else known member_of = {_indexer_config(checkout, target): target for target in targets} runs: list[ProjectRun] = [] + own_config: list[bool] = [] run_of: dict[Path, int] = {} merge: list[tuple[int, str]] = [] for target in targets: @@ -356,7 +368,16 @@ def plan_project_runs( run = _project_run(checkout, target_of_run, config, has_references) # Only a member without references ran alone before: an empty one failed then too. runs.append(run._replace(own=config in member_of and not run.drop_references)) + own_config.append(config in member_of) merge.append((run_of[config], target)) + readers: dict[int, set[str]] = {} + for index, member in merge: + readers.setdefault(index, set()).add(member) + # A member's own project read by its own merge alone is nobody else's to lose. + for index, own_project in enumerate(own_config): + runs[index] = runs[index]._replace( + exclusive=own_project and len(readers.get(index, ())) == 1 + ) return runs, merge @@ -396,9 +417,11 @@ def _write_without_references(config: Path) -> Path: def write_plan(checkout: Path, targets: list[str], known: list[str] | None = None) -> list[str]: """Write the generated configs and return the plan as tab-separated lines: - `config ` for each file written, `index ` for each run - (own is 1 for a member that ran alone before, whose empty run still fails the - pass) and `merge ` in merge order.""" + `config ` for each file written, `index ` + for each run (own is 1 for a member that ran alone before, whose empty run still + fails the pass; exclusive is 1 for a member's own project no other member's merge + reads, whose failure is that member's alone) and `merge ` in merge + order.""" checkout = Path(os.path.abspath(checkout)) runs, merge = plan_project_runs(checkout, targets, known) lines: list[str] = [] @@ -412,7 +435,7 @@ def write_plan(checkout: Path, targets: list[str], known: list[str] | None = Non written.append(generated) lines.append(f"config\t{generated}") target = str(generated.relative_to(checkout)) - index.append(f"index\t{i}\t{target}\t{int(run.own)}") + index.append(f"index\t{i}\t{target}\t{int(run.own)}\t{int(run.exclusive)}") except BaseException: # The caller learns of a config only from the returned plan: remove those written so far. for path in written: diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index cec1387025d..fb632263949 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -1222,6 +1222,75 @@ def test_a_referenced_project_whose_tsconfig_fails_to_load_fails_the_pass( assert "convert" not in (tmp_path / "calls").read_text() +def _sibling_repo(tmp_path: Path) -> Path: + """`lib` references `app`, the sibling the umbrella also names. `lib`'s run + drops that reference, so its process reads no document of `app`'s.""" + repo = tmp_path / "repo" + files = { + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": "packages/lib"}]} + ), + "packages/app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/app/src/a.ts": "export const a = 1;\n", + "packages/lib/tsconfig.json": json.dumps( + {"include": ["src"], "references": [{"path": "../app"}]} + ), + "packages/lib/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return repo + + +def test_a_members_run_that_drops_a_sibling_reference_keeps_its_own_failure( + tmp_path: Path, +) -> None: + """`lib` references `app`, and its generated config drops that reference: the + process reads `lib`'s documents alone, so no other member's delta needs them. + Its config fails to load and the run exits 1 — `lib`'s failure, not the pass's: + `app`'s index is merged and converted, and `lib`'s files go to the converter as + failed, so the server keeps their rows and marks them stale.""" + repo = _sibling_repo(tmp_path) + head = _git(repo, "rev-parse", "HEAD") + vendor = _SCRIPT.parent / "vendor" + writer = tmp_path / "scip_writer.py" + writer.write_text(_SCIP_WRITER) + indexed = tmp_path / "indexed" + merged = tmp_path / "merged.scip" + proc, log = _run_status( + tmp_path, + repo, + "--full", + head, + scip=_FAKE_SCIP_INDEXING, + extra_env={ + "BROKEN_PROJECT": "packages/lib", + "INDEXED": str(indexed), + "MERGED": str(merged), + "SCIP_VENDOR": str(vendor), + "SCIP_WRITER": str(writer), + }, + ) + assert proc.returncode == 0, proc.stderr + assert indexed.read_text().splitlines() == ["packages/app/tsconfig.json"] + assert _failed(log) == ["packages/lib/src/b.ts"] + assert "--full" in _convert_args(log) + import sys + + sys.path.insert(0, str(vendor)) + import scip_pb2 + + index = scip_pb2.Index() + index.ParseFromString(merged.read_bytes()) + assert {doc.relative_path for doc in index.documents} == {"packages/app/indexed.ts"} + assert _git(repo, "status", "--porcelain", "--ignored") == "" + + def test_a_tracked_file_with_the_generated_config_name_is_left_as_it_is( tmp_path: Path, ) -> None: diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index fcb7892f9c3..a940aeae596 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -352,13 +352,42 @@ def test_plan_keeps_a_reference_whose_files_may_leave_its_directory(tmp_path: Pa assert merge == [(0, "packages/app"), (1, "packages/app"), (2, "packages/app")] +def test_plan_keeps_a_members_run_alone_when_its_tsconfig_references_a_sibling( + tmp_path: Path, +) -> None: + """`lib` references `app`, the sibling member the umbrella also names. `lib`'s + run drops that reference and indexes `lib`'s documents alone, so no other + member's merge reads it: its failure is `lib`'s, though its empty part is still + the empty of a run that did not run alone (`own` 0).""" + _write( + tmp_path, + "tsconfig.json", + json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": "packages/lib"}]} + ), + ) + _write(tmp_path, "packages/app/tsconfig.json", json.dumps({"include": ["src"]})) + _write( + tmp_path, + "packages/lib/tsconfig.json", + json.dumps({"include": ["src"], "references": [{"path": "../app"}]}), + ) + targets = ["packages/app", "packages/lib"] + runs, merge = plan_project_runs(tmp_path, targets) + assert [(run.drop_references, run.own, run.exclusive) for run in runs] == [ + (False, True, True), + (True, False, True), + ] + assert merge == [(0, "packages/app"), (1, "packages/lib")] + + def test_plan_without_references_runs_the_members_as_they_are(tmp_path: Path) -> None: for name in ("app", "lib"): _write(tmp_path, f"packages/{name}/tsconfig.json", json.dumps({"include": ["src"]})) targets = ["packages/app", "packages/lib"] assert write_plan(tmp_path, targets) == [ - "index\t0\tpackages/app\t1", - "index\t1\tpackages/lib\t1", + "index\t0\tpackages/app\t1\t1", + "index\t1\tpackages/lib\t1\t1", "merge\t0\tpackages/app", "merge\t1\tpackages/lib", ] @@ -377,7 +406,9 @@ def test_plan_writes_a_config_that_extends_the_project_without_its_references( build = next(path for path in generated if path.name.endswith(".tsconfig.build.json")) assert build.parent == tmp_path / "packages/a" assert json.loads(build.read_text()) == {"extends": "./tsconfig.build.json"} - assert f"index\t0\t{build.relative_to(tmp_path)}\t0" in lines + # `a`'s build config is read by both of `a`'s members' merges, so neither + # member's failure may take it. + assert f"index\t0\t{build.relative_to(tmp_path)}\t0\t0" in lines assert len(generated) == 2 # a's build and spec configs; b has no references From 4879af475b6fb0140903d9309aee00bf7bf5a5d4 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 01:54:53 +0000 Subject: [PATCH 67/81] handle_code_impact stays under the line ratchet after the merge The merge put `scip_stale=bool(marked)` into `handle_code_impact` and took the function to 201 lines, past the 200 the ratchet allows for a function with no baseline entry (`function_length_gate`: "1 function(s) over 200 lines (baseline 0)"). `server/code/app/symbol/impact.py` at upstream main is 200 and clean, so the regression is the union, not either side. The co-change gap block (its precision-floor note, the nested import and the call) moves into `_co_change_gaps`, which is what the ratchet asks for. No behaviour change: same call, same floor, same rows. --- server/code/app/symbol/impact.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index f8e457e628e..9d283f9f098 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -438,14 +438,7 @@ async def handle_code_impact(input: CodeImpactInput) -> CodeImpactOutput: ) if diff_shaped: - # "You changed these files; these often change WITH them and are absent from this - # change." Same precision floor as the PR pack (support >= 4 of the PRs considered, - # confidence >= 15%, at most 5): a looser floor (2-of-50, up to 15 leads) measured - # 25% precision and a PR reviewer agent chased every lead (+63% cost, findings - # unchanged); this floor measures ~36%. - from server.code.app.index.packs import render_co_change_gaps - - co_change_missing = render_co_change_gaps(co_changed, list(seed_paths)) + co_change_missing = _co_change_gaps(co_changed, seed_paths) impacted_sorted, paged = _page_by_hop( impacted, per_hop_limit=input.per_hop_limit, offset=input.offset @@ -556,6 +549,22 @@ async def handle_code_impact(input: CodeImpactInput) -> CodeImpactOutput: return out +def _co_change_gaps( + co_changed: list[dict[str, Any]], seed_paths: list[str] +) -> list[dict[str, Any]]: + """The files that often change WITH the files a change touches and leaves out. + + "You changed these files; these often change WITH them and are absent from this + change." Same precision floor as the PR pack (support >= 4 of the PRs considered, + confidence >= 15%, at most 5): a looser floor (2-of-50, up to 15 leads) measured + 25% precision and a PR reviewer agent chased every lead (+63% cost, findings + unchanged); this floor measures ~36%. + """ + from server.code.app.index.packs import render_co_change_gaps + + return render_co_change_gaps(co_changed, list(seed_paths)) + + async def _symbol_seeds( repo: CodeRepo, org: str, ns: str, input: CodeImpactInput ) -> tuple[list[dict[str, Any]], list[str], list[str], list[dict[str, Any]], int]: From 6da687d78cf9165b560ff281a26ab8593577677c Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 02:22:48 +0000 Subject: [PATCH 68/81] docs/reference/status.md: the merge's settings count Both sides added a boolean setting, so the generated `boolean` count in `docs/reference/status.md` moves from 56 to 57. `scripts/codegen/docs_reference.py` regenerated it; no other page changed. --- docs/reference/status.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/status.md b/docs/reference/status.md index fb49a80c05e..e34c5144990 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -89,7 +89,7 @@ default is `off`) are not listed here. -56 boolean settings load false. +57 boolean settings load false. | Setting | Meaning | | --- | --- | From e383334275c86e2a5e6b3adb849f8d12e8f16519 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 08:18:29 +0000 Subject: [PATCH 69/81] The header loop body indents under the pipeline shfmt holds it in 9b914b35e left the `while IFS= read -r -d ''` body at eight spaces, where every other block in the harness sits at its own depth. `shfmt -w` moves the three lines; no byte of the NUL-delimited path handling changes. --- scripts/scip_harness/run_delta.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/scip_harness/run_delta.sh b/scripts/scip_harness/run_delta.sh index 8d8948dc1e1..2b6c4d71c6c 100755 --- a/scripts/scip_harness/run_delta.sh +++ b/scripts/scip_harness/run_delta.sh @@ -122,9 +122,9 @@ else # "exit 1" whenever a merge window touches only .cpp files. { grep -zE '\.(h|hpp|inl|ipp)$' "$WORK/changed.txt" || true; } \ | while IFS= read -r -d '' hdr; do - base_hdr=$(basename "$hdr") - git_paths grep -lz -F -e "$base_hdr" -- 'src/*.cpp' 'programs/*.cpp' 'base/*.cpp' || true - done | sort -zu >>"$WORK/tus.txt" + base_hdr=$(basename "$hdr") + git_paths grep -lz -F -e "$base_hdr" -- 'src/*.cpp' 'programs/*.cpp' 'base/*.cpp' || true + done | sort -zu >>"$WORK/tus.txt" sort -zu "$WORK/tus.txt" -o "$WORK/tus.txt" N_TUS=$(path_count "$WORK/tus.txt") From 56fc521a7545cb1eb9748fb45c42e85b933ff19b Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 08:18:29 +0000 Subject: [PATCH 70/81] The header loop body indents under the pipeline shfmt holds it in 9b914b35e left the `while IFS= read -r -d ''` body at eight spaces, where every other block in the harness sits at its own depth. `shfmt -w` moves the three lines; no byte of the NUL-delimited path handling changes. --- scripts/scip_harness/run_delta.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/scip_harness/run_delta.sh b/scripts/scip_harness/run_delta.sh index 8d8948dc1e1..2b6c4d71c6c 100755 --- a/scripts/scip_harness/run_delta.sh +++ b/scripts/scip_harness/run_delta.sh @@ -122,9 +122,9 @@ else # "exit 1" whenever a merge window touches only .cpp files. { grep -zE '\.(h|hpp|inl|ipp)$' "$WORK/changed.txt" || true; } \ | while IFS= read -r -d '' hdr; do - base_hdr=$(basename "$hdr") - git_paths grep -lz -F -e "$base_hdr" -- 'src/*.cpp' 'programs/*.cpp' 'base/*.cpp' || true - done | sort -zu >>"$WORK/tus.txt" + base_hdr=$(basename "$hdr") + git_paths grep -lz -F -e "$base_hdr" -- 'src/*.cpp' 'programs/*.cpp' 'base/*.cpp' || true + done | sort -zu >>"$WORK/tus.txt" sort -zu "$WORK/tus.txt" -o "$WORK/tus.txt" N_TUS=$(path_count "$WORK/tus.txt") From efa1108a489d01efe78cac68420deeb735d0e28a Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 09:33:33 +0000 Subject: [PATCH 71/81] handle_code_impact stays under the line ratchet: the co-change gaps move out The 201st line was the precision-floor note above the co-change call, so function_length_gate read the function as a regression past the 200 the ratchet allows and asked for a split. The shape that pays it already exists: #1973 landed `_co_change_gaps` for this same function on wip/ts-retire-r37 (4879af475). The note becomes the helper docstring, the nested import and the call move with it, and the call site keeps its `if diff_shaped:` guard. Both functions are identical in the two trees, so nothing is second-guessed here. No behaviour change: same call, same floor, same rows. --- server/code/app/symbol/impact.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index a4902d06981..d922aadd521 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -439,14 +439,7 @@ async def handle_code_impact(input: CodeImpactInput) -> CodeImpactOutput: ) if diff_shaped: - # "You changed these files; these often change WITH them and are absent from this - # change." Same precision floor as the PR pack (support >= 4 of the PRs considered, - # confidence >= 15%, at most 5): a looser floor (2-of-50, up to 15 leads) measured - # 25% precision and a PR reviewer agent chased every lead (+63% cost, findings - # unchanged); this floor measures ~36%. - from server.code.app.index.packs import render_co_change_gaps - - co_change_missing = render_co_change_gaps(co_changed, list(seed_paths)) + co_change_missing = _co_change_gaps(co_changed, seed_paths) impacted_sorted, paged = _page_by_hop( impacted, per_hop_limit=input.per_hop_limit, offset=input.offset @@ -557,6 +550,22 @@ async def handle_code_impact(input: CodeImpactInput) -> CodeImpactOutput: return out +def _co_change_gaps( + co_changed: list[dict[str, Any]], seed_paths: list[str] +) -> list[dict[str, Any]]: + """The files that often change WITH the files a change touches and leaves out. + + "You changed these files; these often change WITH them and are absent from this + change." Same precision floor as the PR pack (support >= 4 of the PRs considered, + confidence >= 15%, at most 5): a looser floor (2-of-50, up to 15 leads) measured + 25% precision and a PR reviewer agent chased every lead (+63% cost, findings + unchanged); this floor measures ~36%. + """ + from server.code.app.index.packs import render_co_change_gaps + + return render_co_change_gaps(co_changed, list(seed_paths)) + + async def _symbol_seeds( repo: CodeRepo, org: str, ns: str, input: CodeImpactInput ) -> tuple[list[dict[str, Any]], list[str], list[str], list[dict[str, Any]], int]: From 18a8cdb436812147327f6be3fd56ac1b04222d72 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 21:44:39 +0000 Subject: [PATCH 72/81] The stale-mark clear is cut under the bound field, merge ownership compares raw paths, and a Go module directory keeps a trailing newline A round of 200 334-byte paths rendered the clear as one 141 KB keys field, past the servers 128 KiB: the worker stopped before indexing. The clear and the applied record now go in as many statements as one bound list carries, each paths mark and record together. The merge compares project ownership on the raw path bytes (surrogateescape), so two member directories that replace-decode alike stay two owners. The Go harness cuts a go.mod name with a parameter expansion, since dirname in a command substitution drops a trailing newline and the module was skipped. Item numbers after main read-receipts rule are renumbered, status.md regenerated. --- docs/architecture/rolling-upgrades.md | 1 + docs/reference/status.md | 2 +- scripts/scip_harness/run_go_monorepo_delta.sh | 10 ++- scripts/scip_harness/scip_merge_indexes.py | 28 ++++---- server/code/store/index/symbols.py | 55 ++++++++++++--- .../unit/test_code_scip_stale_field_bound.py | 70 +++++++++++++++++++ tests/unit/test_scip_harness_windows.py | 30 ++++++++ tests/unit/test_scip_path_encoding.py | 30 ++++++++ 8 files changed, 201 insertions(+), 25 deletions(-) diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index a1321c62780..2bf2b64b776 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1123,6 +1123,7 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline replaces its rows and no stale mark is written. Apply a kept file with the CLI of the build that wrote it, during a rollout or a rollback. N's reader refuses a version it does not apply. No gate holds the rollout. + 72. **A `/help` address** (N drops the dashboard's docs view and opens docs on the docs site): an N-1 tab pushed `/help?page=#` entries, and after the ReloadBar's reload on N, Back or Forward onto one reaches N in the same document. N diff --git a/docs/reference/status.md b/docs/reference/status.md index e8c9dc28c65..a275c9b5aef 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -89,7 +89,7 @@ default is `off`) are not listed here. -56 boolean settings load false. +57 boolean settings load false. | Setting | Meaning | | --- | --- | diff --git a/scripts/scip_harness/run_go_monorepo_delta.sh b/scripts/scip_harness/run_go_monorepo_delta.sh index 95600809803..f0c31597eb9 100755 --- a/scripts/scip_harness/run_go_monorepo_delta.sh +++ b/scripts/scip_harness/run_go_monorepo_delta.sh @@ -58,8 +58,16 @@ fi if [[ -n "${MODULES:-}" ]]; then mapfile -t DIRS <<<"$MODULES" else + # The name is cut with a parameter expansion, not `dirname` in a command + # substitution: that drops a trailing newline, and a module directory may end in + # one, so the run would probe a directory that does not exist and skip the module. mapfile -t -d '' DIRS < <(cd "$CHECKOUT" && git_paths ls-files -z -- '**/go.mod' 'go.mod' \ - | while IFS= read -r -d '' m; do printf '%s\0' "$(dirname -- "$m")"; done | sort -zu) + | while IFS= read -r -d '' m; do + case $m in + */*) printf '%s\0' "${m%/*}" ;; + *) printf '%s\0' . ;; + esac + done | sort -zu) fi run_module() { diff --git a/scripts/scip_harness/scip_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index c4fa2487534..fcc34181ca5 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -16,10 +16,12 @@ The merge reads only the top-level records and each document's relative_path, and copies the records it keeps byte for byte. Documents -are told apart by the raw path bytes; the path is decoded only to ask which -project owns it, and the member's own name is decoded the same way -(`owner_key`, `replace`) so a member whose directory is not UTF-8 owns its -documents. A document python-protobuf would refuse (a string field +are told apart by the raw path bytes, and ownership compares those bytes: +the member's own name arrives as argv text, which Python decodes with +`surrogateescape`, and a document's raw bytes decode to the same spelling +under `surrogateescape`, so a member whose directory is not UTF-8 owns its +documents and two directories that differ by one undecodable byte stay two +owners. A document python-protobuf would refuse (a string field that is not UTF-8) reaches the converter, which decides what to do with it. A record, fixed-width value, varint, tag or group that the protobuf parser would refuse is corrupt: the merge stops and names the part, as the whole-index parse @@ -52,7 +54,6 @@ def _load_harness_module(name: str) -> Any: project_owns = _ts_projects.project_owns project_scope = _ts_projects.project_scope scope_specificity = _ts_projects.scope_specificity -owner_key = _ts_projects.owner_key _converter = _load_harness_module("scip_to_delta") _read_index = _converter._read_index _top_level_records = _converter._top_level_records @@ -115,10 +116,12 @@ def merge_indexes( if projects is not None and len(projects) != len(paths): raise SystemExit("--project count must match the number of indexes") # The plan names a member as argv text, where a directory whose name is not UTF-8 - # arrives surrogate-escaped; a document's path is the `replace` decoding of its raw - # bytes. Ownership compares the two, so both sides are the one key (`owner_key`). - owner_source = known_projects if known_projects is not None else (projects or []) - owners = [owner_key(project) for project in owner_source] + # arrives surrogate-escaped; a document's raw bytes decoded with `surrogateescape` + # are the same spelling. Ownership compares the two in that key, so two members that + # differ by one undecodable byte stay two owners — `owner_key` folds both to one + # U+FFFD text, and a member selected alone would then keep, or lose, the other's + # documents with its own. The returned set is the store's key, `replace`-decoded. + owners = list(known_projects if known_projects is not None else (projects or [])) metadata: list[Any] = [] documents: dict[bytes, Any] = {} external_symbols: list[Any] = [] @@ -127,7 +130,7 @@ def merge_indexes( data = _read_index(str(path)) if path.is_file() else b"" if not data: continue - project = owner_key(projects[i]) if projects is not None else None + project = projects[i] if projects is not None else None try: for field, payload in _top_level_records(data): if field == _METADATA and not has_payload: @@ -135,9 +138,10 @@ def merge_indexes( elif field == _DOCUMENT: # Key on the raw bytes: two names that differ only by a # malformed byte and a literal U+FFFD decode alike but are - # two documents. Ownership reads the decoded text. + # two documents. Ownership reads the same raw bytes, in the + # spelling a member's argv name holds (`surrogateescape`). raw = _document_path_bytes(payload) - rel = raw.decode("utf-8", "replace") + rel = raw.decode("utf-8", "surrogateescape") if project is None or _keeps(project, rel, owners): documents[raw] = payload elif field == _EXTERNAL_SYMBOL: diff --git a/server/code/store/index/symbols.py b/server/code/store/index/symbols.py index 6748605c838..5c7e38ff8e1 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -37,6 +37,12 @@ STALE_SAMPLE = STALE_SHOWN + 1 +def _state_key(prefix: str, tier: str, path: str) -> str: + """`:`: the state key a path's mark or applied record lives at, + spelled once so the write's width and the key it inserts are the same string.""" + return f"{prefix}{tier}:{path}" + + def _marks_in_force(keys: str) -> str: """The paths of the non-empty `SCIP_STALE_PREFIX` rows whose `state_key` matches `keys`. Only a build that writes marks empties one: its apply of the file, once every @@ -71,6 +77,21 @@ def _stale_read_groups(paths: list[str]) -> Iterator[list[str]]: ) +def _write_groups(paths: list[str], prefixes: tuple[str, ...], tier: str) -> Iterator[list[str]]: + """`paths` grouped so one `set_states_batch` statement binds within `FIELD_BYTES`. + `set_states_batch` binds every key it writes as one `Array(String)` parameter, and a + round's paths are unbounded — 200 of 334 bytes is a 66.8 KB field on one family, + 133.6 KB on a clear's two — so a statement that binds them all is a form field past + the server's bound, and the failed clear stops the worker before it indexes. + `prefixes` names the key families a path writes (a clear writes its mark and its + applied record together; a record writes one), and a path's families stay in one + statement, since a second statement takes its own version.""" + return chunks_multi( + paths, + widths=lambda p: (sum(rendered_width(_state_key(prefix, tier, p)) for prefix in prefixes),), + ) + + def _concat_key_parts(refs: list[str]) -> str: """Keep each concatenation small even for a name spanning thousands of fields.""" while len(refs) > 1: @@ -744,21 +765,33 @@ async def record_scip_applied( whose two inserts an apply has finished (`apply_delta` writes it last), so the row's presence is that apply's record that neither raised. One narrow row per marked file the round carried — a file with no mark is not written for, since no - reader asks about it — and one version for the batch, past every key's newest - row (`set_states_batch`).""" - await self.set_states_batch( - org, - ns, - {f"{SCIP_APPLIED_PREFIX}{tier}:{p}": commit for p in paths}, - ) + reader asks about it — and one version for each statement's batch, past every + key's newest row (`set_states_batch`). A round's paths are unbounded, so they go + in as many statements as the bound field carries (`_write_groups`).""" + for group in _write_groups(list(dict.fromkeys(paths)), (SCIP_APPLIED_PREFIX,), tier): + await self.set_states_batch( + org, + ns, + {_state_key(SCIP_APPLIED_PREFIX, tier, p): commit for p in group}, + ) async def clear_scip_marks(self, org: str, ns: str, tier: str, paths: list[str]) -> None: """Empty the mark of each path of `tier`, and its applied record with it: a mark and the record that answers it live and end together, so no later read joins a - record to a mark it was not written for. One insert for both families.""" - values = {f"{SCIP_STALE_PREFIX}{tier}:{p}": "" for p in paths} - values.update({f"{SCIP_APPLIED_PREFIX}{tier}:{p}": "" for p in paths}) - await self.set_states_batch(org, ns, values) + record to a mark it was not written for. One insert for both families, in as many + statements as the bound field carries: a round's paths are unbounded, and the + statement that binds them all is a form field past the server's 128 KiB — the + clear fails, and the worker stops before it indexes the round. A path's two keys + are counted and written together, so no path's mark and record take two + versions.""" + for group in _write_groups( + list(dict.fromkeys(paths)), (SCIP_STALE_PREFIX, SCIP_APPLIED_PREFIX), tier + ): + values: dict[str, str] = {} + for p in group: + values[_state_key(SCIP_STALE_PREFIX, tier, p)] = "" + values[_state_key(SCIP_APPLIED_PREFIX, tier, p)] = "" + await self.set_states_batch(org, ns, values) async def live_scip_paths(self, org: str, ns: str) -> set[str]: """Every path holding a live compiler-tier symbol row: diff --git a/tests/unit/test_code_scip_stale_field_bound.py b/tests/unit/test_code_scip_stale_field_bound.py index f78331eff8c..f6e7ae34c41 100644 --- a/tests/unit/test_code_scip_stale_field_bound.py +++ b/tests/unit/test_code_scip_stale_field_bound.py @@ -103,3 +103,73 @@ async def test_a_covered_paths_round_never_renders_a_field_past_the_bound() -> N assert len(format_bind_value(value).encode()) <= FIELD_BUDGET, name seen |= {str(p) for p in params["paths"]} assert seen == set(paths) + + +class _FieldBoundWriteCH: + """A ClickHouse that refuses a bound parameter past its field limit, as the HTTP + interface does, and keeps what a write inserted. `set_states_batch` binds its keys + as one `Array(String)` field, so a clear or a record of a round of long paths is + the statement the bound catches.""" + + def __init__(self) -> None: + self.writes: list[dict[str, Any]] = [] + self.inserts: list[list[dict[str, Any]]] = [] + + async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> dict[str, Any]: + params = dict(params or {}) + self.writes.append(params) + for name, value in params.items(): + size = len(format_bind_value(value).encode()) + if size > SERVER_FIELD_LIMIT: + raise RuntimeError(f"Field value too long: {name} renders {size} bytes") + return {"v": 1} + + async def insert(self, table: str, rows: list[dict[str, Any]], **kwargs: Any) -> None: + self.inserts.append([dict(row) for row in rows]) + + +def _write_fields(ch: _FieldBoundWriteCH) -> list[dict[str, Any]]: + assert ch.writes, "the write issued no statement" + for params in ch.writes: + for name, value in params.items(): + assert len(format_bind_value(value).encode()) <= FIELD_BUDGET, name + return ch.writes + + +@pytest.mark.asyncio +async def test_a_clear_of_a_round_of_long_paths_never_renders_a_field_past_the_bound() -> None: + """`clear_scip_marks` empties a mark and its applied record: two keys a path, so a + 200-path round of 334-byte paths renders 140 KB in one field — past the server's, + which fails the statement and stops the worker before it indexes the round.""" + paths = [_path(i, 334) for i in range(ROUND)] + assert all(len(p.encode()) == 334 for p in paths) + ch = _FieldBoundWriteCH() + + await CodeRepo(ch).clear_scip_marks("o", "n", "go", paths) # type: ignore[arg-type] + + assert len(_write_fields(ch)) > 1, "one field cannot carry the round's clear" + cleared = 0 + for rows in ch.inserts: + keys = {str(row["state_key"]) for row in rows} + marks = {key.split(":", 2)[2] for key in keys if key.startswith("scip_stale:go:")} + applied = {key.split(":", 2)[2] for key in keys if key.startswith("scip_applied:go:")} + # A mark and the record that answers it end together: one statement, never two. + assert marks == applied, "a path's mark and applied record clear in one insert" + assert all(row["state_value"] == "" for row in rows) + cleared += len(marks) + assert cleared == ROUND + + +@pytest.mark.asyncio +async def test_a_record_of_a_round_of_long_paths_never_renders_a_field_past_the_bound() -> None: + """`record_scip_applied` binds one key a path: 200 paths of 334 bytes render 70 KB, + past the 64 KiB budget the write is held to, though under the server's limit.""" + paths = [_path(i, 334) for i in range(ROUND)] + ch = _FieldBoundWriteCH() + + await CodeRepo(ch).record_scip_applied("o", "n", "go", "c" * 40, paths) # type: ignore[arg-type] + + assert len(_write_fields(ch)) > 1, "one field cannot carry the round's record" + recorded = [str(row["state_key"]) for rows in ch.inserts for row in rows] + assert sorted(recorded) == sorted(f"scip_applied:go:{p}" for p in paths) + assert {str(row["state_value"]) for rows in ch.inserts for row in rows} == {"c" * 40} diff --git a/tests/unit/test_scip_harness_windows.py b/tests/unit/test_scip_harness_windows.py index d7df9bc72a7..12d5603fa76 100644 --- a/tests/unit/test_scip_harness_windows.py +++ b/tests/unit/test_scip_harness_windows.py @@ -523,6 +523,36 @@ def test_a_window_without_cpp_changes_writes_no_delta(tmp_path: Path) -> None: assert w.run(head, []) is None and w.compdbs == [] +def test_a_module_directory_ending_in_a_newline_is_still_indexed(tmp_path: Path) -> None: + """`git_paths ls-files` names each `go.mod` verbatim, and a module directory may end + in a newline. The discovery strips the file name with a parameter expansion: a + command substitution such as `$(dirname ...)` drops the trailing newline, so the run + probes a directory that does not exist, skips the module and advances its index + without that module's rows.""" + w = _Window(tmp_path, "go") + module = "line\n" + (w.repo / module).mkdir() + (w.repo / module / "go.mod").write_text("module example.com/line\n") + (w.repo / module / "x.go").write_text("package line\n") + w.base = _commit(w.repo, "add a module directory ending in a newline") + (w.repo / module / "x.go").write_text("package line\n\nvar X = 1\n") + head = _commit(w.repo, "edit its one file") + + _write_index(w.index, ["x.go"]) + subprocess.run( + ["bash", str(w.script), str(w.repo), w.base, head], + env=w.env, + check=True, + capture_output=True, + text=True, + ) + + out = tmp_path / "out" / f"{module}.json" + assert out.exists(), "the module under a name ending in a newline was skipped" + delta = json.loads(out.read_text()) + assert [f["path"] for f in delta["files"]] == [f"{module}/x.go"] + + _UNKNOWN_BASE = "0123456789abcdef0123456789abcdef01234567" diff --git a/tests/unit/test_scip_path_encoding.py b/tests/unit/test_scip_path_encoding.py index c13c6ce8141..68a35cd21b0 100644 --- a/tests/unit/test_scip_path_encoding.py +++ b/tests/unit/test_scip_path_encoding.py @@ -31,6 +31,10 @@ _BAD_DIR = b"caf\xe9" _BAD_DIR_KEY = "caf\ufffd" _BAD_DIR_ARG = _BAD_DIR.decode("utf-8", "surrogateescape") +# A second member directory that is also not UTF-8 and decodes with `replace` to the +# same text as _BAD_DIR: the two are one ownership key under `replace`, two under +# `surrogateescape`. +_BAD_DIR_SIBLING = b"caf\xe8" def _git(cwd: Path, *args: str) -> str: @@ -334,3 +338,29 @@ def test_merge_keeps_a_document_of_a_member_whose_directory_is_not_utf8( out = tmp_path / "merged.scip" _merge().merge_indexes([part], out, projects=[_BAD_DIR_ARG]) assert _BAD_DIR + b"/a.ts" in out.read_bytes() + + +def test_a_member_keeps_only_the_documents_of_its_own_raw_name(tmp_path: Path) -> None: + """Two member directories whose names are not UTF-8, differing in the one byte that + `replace` folds to the same U+FFFD: the merge compares raw paths, so a member selected + alone does not take the other's document — which would advance this member's index + while the other's rows stayed, or drop its own and leave the index empty.""" + pb = _pb() + index = pb.Index() + index.metadata.project_root = "file:///repo" + _add_doc(index, "cafX/a.ts", [(_fn("f", "aa"), 0)], []) + _add_doc(index, "cafY/b.ts", [(_fn("g", "bb"), 0)], []) + part = tmp_path / "app.scip" + # `cafX` and `cafY` are each the same length as _BAD_DIR, so every length prefix holds + part.write_bytes( + index.SerializeToString() + .replace(b"cafX/", _BAD_DIR + b"/") + .replace(b"cafY/", _BAD_DIR_SIBLING + b"/") + ) + + out = tmp_path / "merged.scip" + kept = _merge().merge_indexes([part], out, projects=[_BAD_DIR_ARG]) + + assert _BAD_DIR + b"/a.ts" in out.read_bytes() + assert _BAD_DIR_SIBLING not in out.read_bytes() + assert kept == {_BAD_DIR_KEY + "/a.ts"} From 4c3103c8f12c6200de99dfbf0a4622d107f9cdb5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 21:49:02 +0000 Subject: [PATCH 73/81] The plan and the member lists are NUL-delimited fields A member directory is a path: it may hold a space, a tab or a newline, and none of them is a field break. The plan was tab-separated, so `packages/lib` was read as target `packages/li` with a stray `b` in the own field; the indexer ran a directory git does not hold, the pass exited successfully with no skip record for the member, and the worker retired the compiler rows that member's files held. discover and filter printed one path per line, which cuts a directory whose name holds a newline. `write_plan` returns records of fields and `main` writes every field NUL-terminated; discover and filter print one NUL-terminated name per record. The harness reads the plan with `read -r -d ''` per field (a record cut short stops the pass rather than indexing a truncated target) and the lists with `mapfile -t -d ''`. Tests: `test_a_member_directory_holding_a_tab_is_indexed_whole` (red: the indexer ran `packages/li`; green: the run's target is the whole directory), through the real script with a stub indexer. `test_filter_reads_and_prints_names_that_are_not_utf8` and the `write_plan` cases follow the record shape. --- scripts/scip_harness/run_typescript_delta.sh | 58 ++++++++++++++----- scripts/scip_harness/scip_ts_projects.py | 43 +++++++++----- .../test_run_typescript_delta_umbrella.py | 40 +++++++++++++ tests/unit/test_scip_ts_projects.py | 19 +++--- 4 files changed, 122 insertions(+), 38 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 88d0b95d9e3..763c6a944b8 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -49,12 +49,14 @@ if [[ -n "${SCIP_TS_PROJECTS:-}" ]]; then read -r -a PROJECTS <<<"$SCIP_TS_PROJECTS" WORKSPACES="" # every target below has a tsconfig; inference would write one into the tree SCIP_TS_PATHS=0 # the dist-export rewrite is for an unbuilt workspace, not named projects -elif discovered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT") && [[ -n "$discovered" ]]; then +elif "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" discover "$CHECKOUT" >"$WORK/discovered" \ + && [[ -s "$WORK/discovered" ]]; then # umbrella root tsconfig: index member projects instead of loading the root. - # One path per line (a member directory may contain a space). SCIP_TS_PATHS - # stays as configured: the rewrite lands in the config each member is indexed - # through, and in an unbuilt workspace it resolves imports between members. - mapfile -t PROJECTS <<<"$discovered" + # One NUL-terminated path per record (a member directory may contain a space, a tab + # or a newline, and none of them is a record break). SCIP_TS_PATHS stays as + # configured: the rewrite lands in the config each member is indexed through, and in + # an unbuilt workspace it resolves imports between members. + mapfile -t -d '' PROJECTS <"$WORK/discovered" WORKSPACES="" fi # Ownership uses the full discovered set even when a delta indexes a subset, @@ -132,6 +134,17 @@ paths_rewrite() { on_exit '"$PYTHON" "$HARNESS_DIR/scip_ts_paths.py" '"$(printf '%q ' "${args[@]}")"'--restore >/dev/null 2>&1' } +# plan_field VAR WHAT: the next NUL-terminated field of the plan, read from this +# function's stdin. The plan's fields are paths, so nothing splits on whitespace: a +# member directory may hold a space, a tab or a newline. A plan cut mid-record is not a +# plan to index against, so it stops the pass instead of indexing a truncated target. +plan_field() { + IFS= read -r -d '' "$1" || { + echo ">> plan ends inside $2" >&2 + exit 1 + } +} + # index_workspace: scip-typescript over the checkout into $WORK/index.scip. # Everything it writes into the tree (the tsconfig paths, a named project's # tsconfig.scip.json and package.json stub) is undone on exit. @@ -246,16 +259,28 @@ JSONEOF # member's merge reads — is not one member's to lose, so its failure fails the # pass. With SCIP_STOP_ON_FAILED_DOCUMENT=1, a member killed by a signal, or a # pass whose every member failed, the pass fails too. - local plan kind run own excl arg i runs=() owns=() exclusive=() parts=() merge_args=() known_args=() t rc + local kind run own excl arg i runs=() owns=() exclusive=() parts=() merge_args=() known_args=() t rc local -a pair_run=() pair_member=() failed_runs=() run_ok=() for t in "${ALL_PROJECTS[@]}"; do known_args+=(--known-project "$t") done - plan=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" plan "$CHECKOUT" "${known_args[@]}" -- "${targets[@]}") - while IFS=$'\t' read -r kind run arg own excl; do + # The plan is a file of NUL-terminated fields, read here field by field: a member + # directory is a path, and a tab in it is a byte of the name. A tab-separated plan cut + # `packages/lib` at the tab, the indexer ran `packages/li`, and the delta left + # without a skip record for the member whose rows the worker then retired. + "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" plan "$CHECKOUT" "${known_args[@]}" \ + -- "${targets[@]}" >"$WORK/plan" || exit $? + while IFS= read -r -d '' kind; do case "$kind" in - config) on_exit "rm -f $(printf %q "$run")" ;; + config) + plan_field run "a config record" + on_exit "rm -f $(printf %q "$run")" + ;; index) + plan_field run "an index record" + plan_field arg "an index record" + plan_field own "an index record" + plan_field excl "an index record" runs[run]=$arg owns[run]=$own exclusive[run]=$excl @@ -263,11 +288,17 @@ JSONEOF merge) # One merge input per (run, member) pair: the merge keeps the documents # that member's own process would have indexed from that run. + plan_field run "a merge record" + plan_field arg "a merge record" pair_run+=("$run") pair_member+=("$arg") ;; + *) + echo ">> unknown plan record: $kind" >&2 + exit 1 + ;; esac - done <<<"$plan" + done <"$WORK/plan" for run in "${!runs[@]}"; do rc=0 NODE_OPTIONS="--max-old-space-size=$NODE_HEAP_MB" \ @@ -369,9 +400,10 @@ if [[ "$BASE" != "--full" ]]; then filter_args=() [[ -s "$WORK/project-window/changed.txt" ]] && filter_args+=(--changed-file-list "$WORK/project-window/changed.txt") [[ -s "$WORK/project-window/deleted.txt" ]] && filter_args+=(--deleted-file-list "$WORK/project-window/deleted.txt") - filtered=$("$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" -- "${PROJECTS[@]}") - if [[ -n "$filtered" ]]; then - mapfile -t PROJECTS <<<"$filtered" + "$PYTHON" "$HARNESS_DIR/scip_ts_projects.py" filter "${filter_args[@]}" \ + -- "${PROJECTS[@]}" >"$WORK/filtered" + if [[ -s "$WORK/filtered" ]]; then + mapfile -t -d '' PROJECTS <"$WORK/filtered" else # An empty filter is a real empty selection (e.g. an unowned # package.json or TypeScript file). Do not keep the full member set. diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index 7bd104bdd6c..2206ef26d58 100755 --- a/scripts/scip_harness/scip_ts_projects.py +++ b/scripts/scip_harness/scip_ts_projects.py @@ -415,17 +415,23 @@ def _write_without_references(config: Path) -> Path: return Path(name) -def write_plan(checkout: Path, targets: list[str], known: list[str] | None = None) -> list[str]: - """Write the generated configs and return the plan as tab-separated lines: - `config ` for each file written, `index ` +def write_plan( + checkout: Path, targets: list[str], known: list[str] | None = None +) -> list[tuple[str, ...]]: + """Write the generated configs and return the plan as records of fields: + `("config", path)` for each file written, `("index", run, target, own, exclusive)` for each run (own is 1 for a member that ran alone before, whose empty run still fails the pass; exclusive is 1 for a member's own project no other member's merge - reads, whose failure is that member's alone) and `merge ` in merge - order.""" + reads, whose failure is that member's alone) and `("merge", run, member)` in merge + order. + + A field is a path — a member directory or a generated config — so the caller writes + them NUL-terminated: a tab or a newline in a directory's name is a byte of the path, + not a field break, and a tab-separated plan cut `packages/lib` at the tab.""" checkout = Path(os.path.abspath(checkout)) runs, merge = plan_project_runs(checkout, targets, known) - lines: list[str] = [] - index: list[str] = [] + records: list[tuple[str, ...]] = [] + index: list[tuple[str, ...]] = [] written: list[Path] = [] try: for i, run in enumerate(runs): @@ -433,17 +439,17 @@ def write_plan(checkout: Path, targets: list[str], known: list[str] | None = Non if run.drop_references: generated = _write_without_references(run.config) written.append(generated) - lines.append(f"config\t{generated}") + records.append(("config", str(generated))) target = str(generated.relative_to(checkout)) - index.append(f"index\t{i}\t{target}\t{int(run.own)}\t{int(run.exclusive)}") + index.append(("index", str(i), target, str(int(run.own)), str(int(run.exclusive)))) except BaseException: # The caller learns of a config only from the returned plan: remove those written so far. for path in written: path.unlink(missing_ok=True) raise - lines.extend(index) - lines.extend(f"merge\t{i}\t{member}" for i, member in merge) - return lines + records.extend(index) + records.extend(("merge", str(i), member) for i, member in merge) + return records def posix_path(path: str) -> str: @@ -605,7 +611,11 @@ def main(argv: list[str] | None = None) -> int: if args.cmd == "discover": projects = discover_umbrella_projects(args.checkout) elif args.cmd == "plan": - projects = write_plan(args.checkout, list(args.targets), args.known_project or None) + # The plan's fields are NUL-terminated: see `write_plan`. + for record in write_plan(args.checkout, list(args.targets), args.known_project or None): + for field in record: + sys.stdout.buffer.write(os.fsencode(field) + b"\0") + return 0 elif args.cmd == "has-shared": changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) return 0 if any(is_shared_change(path) for path in changed) else 1 @@ -615,10 +625,11 @@ def main(argv: list[str] | None = None) -> int: else: changed = _read_lines(args.changed_file_list) + _read_lines(args.deleted_file_list) projects = select_projects_for_delta(list(args.projects), changed) - # One path per line so a member whose path contains a space is not split - # by the shell when it loads the list. + # One NUL-terminated path per record: a member directory is a path, so a space, a + # tab or a newline in it is a byte of the name, not a record break. The shell loads + # the list with `mapfile -t -d ''`. for project in projects: - sys.stdout.buffer.write(os.fsencode(project) + b"\n") + sys.stdout.buffer.write(os.fsencode(project) + b"\0") return 0 diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index fb632263949..6b1f52bf911 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -1308,3 +1308,43 @@ def test_a_tracked_file_with_the_generated_config_name_is_left_as_it_is( "packages/app/tools/indexed.ts", "packages/lib/indexed.ts", } + + +def _plan_targets(log: str) -> list[str]: + """Each indexer run's target, read from its raw line: `run\tindex\t\t--output\t`. + + `_targets` splits the line on tabs, which is what the harness's own reader must not do + to a path; this reader takes everything between the record kind and `--output` whole. + """ + return [m.group(1) for m in re.finditer(r"^run\tindex\t(.*)\t--output\t", log, re.M)] + + +def test_a_member_directory_holding_a_tab_is_indexed_whole(tmp_path: Path) -> None: + """The plan's fields are NUL-separated, so a member directory with a tab in its name + reaches the indexer as one target and its rows land. + + Read as tab-separated fields, `packages/lib` is cut at the tab: the indexer runs + `packages/li`, the delta exits successfully and carries no skip record for the member, + and the worker retires the compiler rows the member held. + """ + repo = tmp_path / "repo" + member = "packages/li\tb" + files = { + "tsconfig.json": json.dumps( + {"files": [], "references": [{"path": "packages/app"}, {"path": member}]} + ), + "packages/app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/app/src/a.ts": "export const a = 1;\n", + f"{member}/tsconfig.json": json.dumps({"include": ["src"]}), + f"{member}/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + log = _run(tmp_path, repo, "--full", head) + assert _plan_targets(log) == ["packages/app", member] diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index a940aeae596..7e7132ba744 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -250,7 +250,8 @@ def test_filter_reads_and_prints_names_that_are_not_utf8(tmp_path: Path) -> None check=True, capture_output=True, ) - assert out.stdout == b"packages/caf\xe9\n" + # NUL-terminated: a member name may hold any byte but NUL, a newline included. + assert out.stdout == b"packages/caf\xe9\0" changed.write_bytes(b"caf\xe9.md\0package.json\0") for cmd in (b"has-config", b"has-shared"): argv = [sys.executable, os.fsencode(_SCRIPT), cmd, b"--changed-file-list"] @@ -386,10 +387,10 @@ def test_plan_without_references_runs_the_members_as_they_are(tmp_path: Path) -> _write(tmp_path, f"packages/{name}/tsconfig.json", json.dumps({"include": ["src"]})) targets = ["packages/app", "packages/lib"] assert write_plan(tmp_path, targets) == [ - "index\t0\tpackages/app\t1\t1", - "index\t1\tpackages/lib\t1\t1", - "merge\t0\tpackages/app", - "merge\t1\tpackages/lib", + ("index", "0", "packages/app", "1", "1"), + ("index", "1", "packages/lib", "1", "1"), + ("merge", "0", "packages/app"), + ("merge", "1", "packages/lib"), ] assert sorted(p.name for p in (tmp_path / "packages/app").iterdir()) == ["tsconfig.json"] @@ -398,17 +399,17 @@ def test_plan_writes_a_config_that_extends_the_project_without_its_references( tmp_path: Path, ) -> None: targets = _closure_tree(tmp_path) - lines = write_plan(tmp_path, targets) + records = write_plan(tmp_path, targets) generated = sorted(tmp_path.glob("packages/*/.scip-norefs.*")) - assert sorted(line for line in lines if line.startswith("config")) == sorted( - f"config\t{path}" for path in generated + assert sorted(r for r in records if r[0] == "config") == sorted( + ("config", str(path)) for path in generated ) build = next(path for path in generated if path.name.endswith(".tsconfig.build.json")) assert build.parent == tmp_path / "packages/a" assert json.loads(build.read_text()) == {"extends": "./tsconfig.build.json"} # `a`'s build config is read by both of `a`'s members' merges, so neither # member's failure may take it. - assert f"index\t0\t{build.relative_to(tmp_path)}\t0\t0" in lines + assert ("index", "0", str(build.relative_to(tmp_path)), "0", "0") in records assert len(generated) == 2 # a's build and spec configs; b has no references From 550c65eb85f4a34586acb52ffa1ac01d1451bd39 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 21:49:04 +0000 Subject: [PATCH 74/81] A Go module directory keeps every byte and reaches the harness whole `$(dirname -- "$m")` strips the trailing newlines of a module directory, so a tracked directory whose name ends in a newline was `cd`-ed as a missing path: the module was skipped, and the worker advanced the watermark with no delta for it. `${m%/*}` keeps the name; a module at the checkout root has no separator and stays `.`. The selected-module list could not carry such a directory either: `_harness_env` joined it with newlines into `MODULES`. It now writes the list beside the deltas, NUL-separated, and sets `MODULES_FILE`; the harness reads that file first (`MODULES` stays for a human at a terminal). Tests: `test_a_module_directory_ending_in_a_newline_is_indexed` (red: scip-go never ran in `svc/e\n`, the pass skipped it; green: it runs, and the delta lands) and `test_selected_modules_reach_the_harness_nul_separated` (red: `MODULES_FILE` unread, the harness discovered every module; green: only the selected two), through the real script with stub scip-go/go/converter. `_harness_env`'s test asserts the file's bytes. --- scripts/scip_harness/README.md | 5 +- scripts/scip_harness/run_go_monorepo_delta.sh | 28 +++- server/code/workers/scip_go_delta.py | 8 +- tests/unit/test_code_scip_go_delta_worker.py | 12 +- .../test_run_go_monorepo_delta_modules.py | 130 ++++++++++++++++++ 5 files changed, 171 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_run_go_monorepo_delta_modules.py diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index ed42c45e2bc..9ccf34a46e7 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -115,8 +115,9 @@ their files but make no namespace-wide claim — run `--full` once to make it. ## Go `run_go_monorepo_delta.sh` runs [scip-go](https://github.com/scip-code/scip-go) -once per `go.mod` directory (or the `MODULES` list a merge touched) and converts -each through the same `scip_to_delta.py`. scip-go's symbols +once per `go.mod` directory (or the `MODULES_FILE` list a merge touched, NUL-separated +so a module directory ending in a newline survives) and converts each through the same +`scip_to_delta.py`. scip-go's symbols (`scip-go gomod /#|().`) parse through the generic descriptor grammar, no scheme branch: `/::` functions, `class` structs, `calls` / `inherits` / `overrides` edges. The diff --git a/scripts/scip_harness/run_go_monorepo_delta.sh b/scripts/scip_harness/run_go_monorepo_delta.sh index 95600809803..c9ecef0ae86 100755 --- a/scripts/scip_harness/run_go_monorepo_delta.sh +++ b/scripts/scip_harness/run_go_monorepo_delta.sh @@ -11,9 +11,12 @@ # (per module, only the Go files the window # changed or deleted; a module with none is skipped) # -# Env: LOOM_API_KEY (writer; upload mode), SCIP_GO, PYTHON, GOFLAGS, MODULES (a -# newline list of module dirs to run instead of every go.mod; e.g. the ones a -# merge touched), MIN_GO_FILES (skip modules with fewer .go files; default 1), +# Env: LOOM_API_KEY (writer; upload mode), SCIP_GO, PYTHON, GOFLAGS, MODULES_FILE +# (a NUL-separated list of module dirs to run instead of every go.mod; e.g. the ones +# a merge touched — the worker writes it, because a module directory is a path and a +# newline-joined variable cannot carry one that ends in a newline), MODULES (the same +# list newline-separated, for a human at a terminal), MIN_GO_FILES (skip modules with +# fewer .go files; default 1), # JOBS (parallel scip-go runs; default 2 — budget ~4 GB RAM each: the Go compiler # runs inside scip-go), EXCLUDE_GENERATED (default 1: drop generated documents). A module whose # `go mod download` fails is logged and skipped, never fatal to the run. @@ -55,11 +58,26 @@ if [[ -n "$BASE" && "$BASE" != "--full" ]]; then require_base "$BASE" "$CHECKOUT" fi -if [[ -n "${MODULES:-}" ]]; then +# A module directory is a path: it may end in a newline, and `$(dirname ...)` would +# strip it, so the `cd` would miss and the module would be skipped while the worker +# advanced the watermark without its delta. `${m%/*}` keeps every byte; a module at the +# checkout root has no separator and is `.`, as dirname spells it. +if [[ -n "${MODULES_FILE:-}" ]]; then + [[ -r "$MODULES_FILE" ]] || { + echo "MODULES_FILE is not readable: $MODULES_FILE" >&2 + exit 2 + } + mapfile -t -d '' DIRS <"$MODULES_FILE" +elif [[ -n "${MODULES:-}" ]]; then mapfile -t DIRS <<<"$MODULES" else mapfile -t -d '' DIRS < <(cd "$CHECKOUT" && git_paths ls-files -z -- '**/go.mod' 'go.mod' \ - | while IFS= read -r -d '' m; do printf '%s\0' "$(dirname -- "$m")"; done | sort -zu) + | while IFS= read -r -d '' m; do + case "$m" in + */*) printf '%s\0' "${m%/*}" ;; + *) printf '%s\0' . ;; + esac + done | sort -zu) fi run_module() { diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index 5a18cf15a63..6180849d021 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -581,7 +581,13 @@ def _harness_env(out_dir: Path, modules: list[str], cfg: RepoConfig) -> dict[str env["GOPRIVATE"] = settings.code_scip_go_private env["GONOSUMDB"] = settings.code_scip_go_private if modules: - env["MODULES"] = "\n".join(modules) + # A module directory is a path: one whose name ends in a newline cannot ride a + # newline-joined variable (the harness would read a truncated `cd` and skip the + # module while the watermark advanced). The list goes beside the deltas, + # NUL-separated, so the harness reads every byte of it. + modules_file = out_dir / "modules" + modules_file.write_bytes(b"".join(os.fsencode(m) + b"\0" for m in modules)) + env["MODULES_FILE"] = str(modules_file) return env diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index 0a30604e95d..fe5f4c33668 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -294,16 +294,20 @@ async def run(cfg: Any) -> Any: assert state["scip_commit_go"] == "b" * 40 -def test_harness_env_carries_the_entrys_generated_rule_and_the_modules(monkeypatch, tmp_path): +def test_harness_env_carries_the_entrys_generated_rule_and_the_module_list(monkeypatch, tmp_path): + """The selected modules go in a NUL-separated file, not a newline-joined variable: a + module directory is a path, and one ending in a newline would be cut by the join.""" monkeypatch.setenv("PATH", "/usr/local/go/bin:/host/go/bin:/usr/bin") monkeypatch.setattr(w.settings, "code_scip_go_bin_dir", str(tmp_path)) monkeypatch.setattr(w.settings, "code_scip_go_private", "go.example.com") - env = w._harness_env(tmp_path, ["svc", "lib"], _Cfg()) - assert env["MODULES"] == "svc\nlib" and env["EXCLUDE_GENERATED"] == "1" + env = w._harness_env(tmp_path, ["svc", "svc/e\n"], _Cfg()) + assert "MODULES" not in env + assert Path(env["MODULES_FILE"]).read_bytes() == b"svc\0svc/e\n\0" + assert env["EXCLUDE_GENERATED"] == "1" assert env["GOPRIVATE"] == "go.example.com" and env["GOFLAGS"] == "-mod=mod" assert env["PATH"].startswith(str(tmp_path)) assert "/usr/local/go/bin" in env["PATH"] and "/host/go/bin" in env["PATH"] - assert "MODULES" not in w._harness_env(tmp_path, [], _Cfg()) + assert "MODULES_FILE" not in w._harness_env(tmp_path, [], _Cfg()) def test_harness_env_carries_no_credential_into_module_downloads(monkeypatch, tmp_path): diff --git a/tests/unit/test_run_go_monorepo_delta_modules.py b/tests/unit/test_run_go_monorepo_delta_modules.py new file mode 100644 index 00000000000..d10f8c51faf --- /dev/null +++ b/tests/unit/test_run_go_monorepo_delta_modules.py @@ -0,0 +1,130 @@ +"""run_go_monorepo_delta.sh enumerates module directories losslessly. + +A directory whose name ends in a newline is a module like any other: `$(dirname ...)` +drops that newline, the module's `cd` misses, and the worker advances the watermark with +no delta for it. The selected modules reach the harness NUL-separated for the same +reason: a newline-joined variable cannot carry such a directory. go, scip-go and the +converter are stubs; git runs for real. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +_SCRIPT = ( + Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_go_monorepo_delta.sh" +) + +_FAKE_GO = """#!/usr/bin/env bash +exit 0 +""" + +_FAKE_SCIP_GO = """#!/usr/bin/env bash +# The directory the indexer ran in, NUL-separated: a module name may hold any byte. +printf '%s\\0' "$PWD" >>"$INDEXED" +while [[ $# -gt 0 ]]; do [[ "$1" == --output ]] && : >"$2"; shift; done +""" + +_FAKE_PYTHON = """#!/usr/bin/env bash +# The converter's last argument is the delta it writes. +printf '{}\\n' >"${!#}" +""" + + +def _git(cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", *args], cwd=cwd, check=True, capture_output=True, text=True + ).stdout.strip() + + +def _repo(tmp_path: Path, members: list[str]) -> Path: + repo = tmp_path / "repo" + for member in members: + root = repo / member if member else repo + root.mkdir(parents=True, exist_ok=True) + (root / "go.mod").write_text("module example.com/x\n\ngo 1.22\n") + (root / "main.go").write_text("package main\n\nfunc main() {}\n") + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return repo + + +def _run( + tmp_path: Path, repo: Path, extra_env: dict[str, str] | None = None +) -> tuple[subprocess.CompletedProcess[str], Path]: + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + for name, body in ( + ("go", _FAKE_GO), + ("scip-go", _FAKE_SCIP_GO), + ("python", _FAKE_PYTHON), + ): + dest = bin_dir / name + dest.write_text(body) + dest.chmod(0o755) + indexed = tmp_path / "indexed" + indexed.unlink(missing_ok=True) + out_dir = tmp_path / "deltas" + env = { + **os.environ, + "PATH": f"{bin_dir}:{os.environ['PATH']}", + "INDEXED": str(indexed), + "DELTA_OUT_DIR": str(out_dir), + "PYTHON": str(bin_dir / "python"), + "SCIP_GO": str(bin_dir / "scip-go"), + "MIN_GO_FILES": "1", + "JOBS": "1", + **(extra_env or {}), + } + env.pop("MODULES", None) + env.pop("MODULES_FILE", None) + env.update(extra_env or {}) + proc = subprocess.run( + ["bash", str(_SCRIPT), str(repo), "--full", _git(repo, "rev-parse", "HEAD")], + env=env, + check=False, + capture_output=True, + text=True, + ) + return proc, indexed + + +def _indexed_dirs(indexed: Path, repo: Path) -> list[str]: + """The directories scip-go ran in, relative to the checkout: a module the harness + never reached is one this list lacks, and a name cut at a newline names a directory + git does not hold.""" + if not indexed.exists(): + return [] + dirs = [] + for raw in indexed.read_bytes().split(b"\0"): + if not raw: + continue + dirs.append(os.path.relpath(os.fsdecode(raw), str(repo))) + return sorted(dirs) + + +def test_a_module_directory_ending_in_a_newline_is_indexed(tmp_path: Path) -> None: + """`${m%/*}` keeps the newline `$(dirname ...)` strips: the module is indexed, not + skipped, and the pass writes its delta.""" + weird = "svc/e\n" + repo = _repo(tmp_path, ["", "svc/api", weird]) + proc, indexed = _run(tmp_path, repo) + assert proc.returncode == 0, proc.stderr + assert _indexed_dirs(indexed, repo) == [".", "svc/api", weird] + assert (tmp_path / "deltas" / "svc__e\n.json").exists() + + +def test_selected_modules_reach_the_harness_nul_separated(tmp_path: Path) -> None: + """The worker's list arrives in a NUL-separated file: a newline-joined `MODULES` + cannot carry a directory that ends in a newline, so the harness reads none of the + module and the worker advances the watermark without its delta.""" + weird = "svc/e\n" + repo = _repo(tmp_path, ["", "svc/api", weird]) + modules = tmp_path / "selected" + modules.write_bytes(b"svc/api\0" + weird.encode() + b"\0") + proc, indexed = _run(tmp_path, repo, {"MODULES_FILE": str(modules)}) + assert proc.returncode == 0, proc.stderr + assert _indexed_dirs(indexed, repo) == ["svc/api", weird] From a13504466b02e964c4ce9e9d27fe5b0b16ee8714 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 21:49:07 +0000 Subject: [PATCH 75/81] The operations doc points at rule 76 for the skipped-document delta The merge that took upstream main's rules 73-75 renumbered this branch's rule to 76; the pointer in the code-index operations table still said 73. --- docs/operations/code-index-operations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 71f3a29db3d..2cc8310e347 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1477,7 +1477,7 @@ the output to read. | compiler-tier apply fails | batch `failed` with the error | `loom code scip-retry ` | | a compiler-tier pass fails or hangs | the harness's timeout ends a hang, and the pass deadline (that timeout plus headroom for the git steps and the apply) cancels anything else; the entry lock is freed; a failure the pass reports (the harness's own timeout included) is recorded with its kind and fix in `tier_health` | the next pass; `workers.status` names the timeout | | compiler-tier window base unknown (history rewritten, pruned mirror) | every `scripts/scip_harness/` tier exits 3, never an empty delta; the Python, TypeScript and Go workers clear the tier's watermark | the next run is a full index for that tier (`code_scip_full` for C/C++) | -| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window, and so is a window file with a factory call, whose constructor may be in the skipped document (`code.callers` and `code.callees` name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that carries the file without skipping it empties the mark, and N-1 neither reads nor empties one (rule 73) | +| a compiler-tier document fails to parse or convert (a string that is not UTF-8, say) | the converter skips it with a warning, which the worker logs, and converts the rest; the file keeps its compiler rows; a delta marks it stale if that file is in its window, and so is a window file with a factory call, whose constructor may be in the skipped document (`code.callers` and `code.callees` name it in `scip_stale_files`), and a full run does not retire them; with `LOOM_CODE_SCIP_STOP_ON_FAILED_DOCUMENT=true` the pass fails instead | the next delta that carries the file without skipping it empties the mark, and N-1 neither reads nor empties one (rule 76) | | a compiler-tier delta is a link, not a regular file, or oversize, or the Go harness writes more deltas than modules | the delta is refused (`FileRefused`, or `Go harness wrote more deltas than its N module(s)`) and the entry's pass fails; the watermark stays; a `FileRefused` delta holds the tier (no harness runs) until an input of its run changes (above), extra deltas rerun every pass | oversize: raise `LOOM_CODE_SCIP_DELTA_FILE_MAX_MB` and `LOOM_CODE_SCIP_DELTA_MAX_NODES` (they bound work and the path text kept); for a file entry over the round budget raise `LOOM_CODE_SCIP_DELTA_ROUND_MAX_NODES`, within the worker's memory; a file entry over the fixed character cap is named, and no setting changes that cap: the file it indexes is what to split; a link, a non-regular file or extra deltas keep the failure until the repository changes or the entry is removed | | GitHub rate limit | the pass ends, cursor unmoved | the next pass | | branch force-pushed (watermark no longer an ancestor) | watermark reset to the new head, logged | `loom code backfill` to re-derive | From c00d8e05e61c35671c1eca2d60ec2e09c287d20b Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 21:56:02 +0000 Subject: [PATCH 76/81] A stale-marks read that lowers an answer says so, and the SCIP pass's reads are listed `_marked_stale` and `_ctor_edge_coverage` serve a smaller answer on a failed marks read (the answer falls to a lower bound, the ctor claim drops) and recorded nothing: the inventory test found four unnoted broad handlers in the SCIP paths on this head. Both now call `degradations.partial("code_index", "scip_stale_marks_unread", caller_text(e))` beside the note they already returned. `_gone_at` and `retire_published_marks` are reads of the apply pass with no response path, so they join `degraded_unnoted.txt` as `logged_only_nonanswer` with that reason. `test_degraded_unnoted.py` passes (was 4 missing entries); the ctor/mark-retirement suites are unchanged and green. --- server/code/app/symbol/coverage.py | 2 ++ tests/unit/degraded_unnoted.txt | 2 ++ 2 files changed, 4 insertions(+) diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index 65d5b5fe0fe..aa5f208a5ad 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -120,6 +120,7 @@ async def _marked_stale(repo: CodeRepo, org: str, ns: str) -> set[str]: return await repo.scip_stale_sample(org, ns) except Exception as e: # noqa: BLE001 — a freshness read must not fail the answer logger.debug("scip stale-marks read skipped: %s", e) + degradations.partial("code_index", "scip_stale_marks_unread", caller_text(e)) return {MARKS_UNREAD} @@ -206,6 +207,7 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, marked = await repo.scip_stale_sample(org, ns, "clang", limit=1) except Exception as e: # noqa: BLE001 — fail closed: an error can only lower an answer logger.debug("scip stale-marks read skipped: %s", e) + degradations.partial("code_index", "scip_stale_marks_unread", caller_text(e)) return False, ts_ok return not marked, ts_ok diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 605a72dfff8..4dd11a0c96a 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -80,6 +80,8 @@ server/code/app/index/scip_delta.py::_declaration_line_test::1 server/code/app/index/scip_delta.py::_declaration_line_test::2 logged_only_nonanswer # the SCIP apply's edge filter, a worker pass server/code/app/index/scip_delta.py::_indexable_prefixes::1 logged_only_nonanswer # the SCIP apply's repo entry, a worker pass server/code/app/index/scip_delta.py::_path_refusal::1 logged_only_nonanswer # the SCIP apply's repo entry, a worker pass +server/code/app/index/scip_delta.py::_gone_at::1 logged_only_nonanswer # the SCIP apply's pass, a mark kept +server/code/app/index/scip_delta.py::retire_published_marks::1 logged_only_nonanswer # the SCIP apply's pass, a mark kept server/code/app/index/tier_health.py::forget::1 write # dropping a tier-health record of a tier the entry no longer runs server/code/app/index/tier_health.py::note_unavailable::1 write # a tier-health record write; the pass it describes is whole server/code/app/index/tier_health.py::record::1 write # a tier-health record write; the ingest or CLI pass it describes is whole From 03570a96a4928b4eb17242a692ce9208b844ad9a Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Fri, 4 Dec 2026 23:11:57 +0000 Subject: [PATCH 77/81] The selected Go modules reach the harness NUL-separated, so a module directory ending in a newline keeps its delta The harness cut a `go.mod` name with `${m%/*}` already, but `_harness_env` still joined the selected modules with newlines. A module directory whose name ends in one arrived as a path that does not exist: its `cd` missed, the run skipped the module, and the worker advanced the watermark without its delta. The list now goes beside the deltas, NUL-separated, in `out_dir/modules`, and the harness reads `MODULES_FILE` first with `mapfile -t -d ''` (`MODULES` stays for a human at a terminal). The shape is #1973's (`wip/ts-member-r39`, `550c65eb8`), ported rather than reinvented; the discovery cut and the script's other lines are unchanged. Tests: `test_selected_modules_reach_the_harness_nul_separated` (red at `18a8cdb43`: `MODULES_FILE` unread, so the harness discovered all three modules and the list was `['.', 'svc/api', 'svc/e\n']` instead of `['svc/api', 'svc/e\n']`; green: only the selected two run, and scip-go runs in `svc/e\n`), `test_a_module_directory_ending_in_a_newline_is_indexed`, and `_harness_env`'s test, which asserts the file's bytes `svc\0svc/e\n\0`. --- scripts/scip_harness/README.md | 5 +- scripts/scip_harness/run_go_monorepo_delta.sh | 26 ++-- server/code/workers/scip_go_delta.py | 8 +- tests/unit/test_code_scip_go_delta_worker.py | 12 +- .../test_run_go_monorepo_delta_modules.py | 130 ++++++++++++++++++ 5 files changed, 166 insertions(+), 15 deletions(-) create mode 100644 tests/unit/test_run_go_monorepo_delta_modules.py diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 7d0de306426..15da10bd8cc 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -105,8 +105,9 @@ their files but make no namespace-wide claim — run `--full` once to make it. ## Go `run_go_monorepo_delta.sh` runs [scip-go](https://github.com/scip-code/scip-go) -once per `go.mod` directory (or the `MODULES` list a merge touched) and converts -each through the same `scip_to_delta.py`. scip-go's symbols +once per `go.mod` directory (or the `MODULES_FILE` list a merge touched, NUL-separated +so a module directory ending in a newline survives) and converts each through the same +`scip_to_delta.py`. scip-go's symbols (`scip-go gomod /#|().`) parse through the generic descriptor grammar, no scheme branch: `/::` functions, `class` structs, `calls` / `inherits` / `overrides` edges. The diff --git a/scripts/scip_harness/run_go_monorepo_delta.sh b/scripts/scip_harness/run_go_monorepo_delta.sh index f0c31597eb9..c9ecef0ae86 100755 --- a/scripts/scip_harness/run_go_monorepo_delta.sh +++ b/scripts/scip_harness/run_go_monorepo_delta.sh @@ -11,9 +11,12 @@ # (per module, only the Go files the window # changed or deleted; a module with none is skipped) # -# Env: LOOM_API_KEY (writer; upload mode), SCIP_GO, PYTHON, GOFLAGS, MODULES (a -# newline list of module dirs to run instead of every go.mod; e.g. the ones a -# merge touched), MIN_GO_FILES (skip modules with fewer .go files; default 1), +# Env: LOOM_API_KEY (writer; upload mode), SCIP_GO, PYTHON, GOFLAGS, MODULES_FILE +# (a NUL-separated list of module dirs to run instead of every go.mod; e.g. the ones +# a merge touched — the worker writes it, because a module directory is a path and a +# newline-joined variable cannot carry one that ends in a newline), MODULES (the same +# list newline-separated, for a human at a terminal), MIN_GO_FILES (skip modules with +# fewer .go files; default 1), # JOBS (parallel scip-go runs; default 2 — budget ~4 GB RAM each: the Go compiler # runs inside scip-go), EXCLUDE_GENERATED (default 1: drop generated documents). A module whose # `go mod download` fails is logged and skipped, never fatal to the run. @@ -55,15 +58,22 @@ if [[ -n "$BASE" && "$BASE" != "--full" ]]; then require_base "$BASE" "$CHECKOUT" fi -if [[ -n "${MODULES:-}" ]]; then +# A module directory is a path: it may end in a newline, and `$(dirname ...)` would +# strip it, so the `cd` would miss and the module would be skipped while the worker +# advanced the watermark without its delta. `${m%/*}` keeps every byte; a module at the +# checkout root has no separator and is `.`, as dirname spells it. +if [[ -n "${MODULES_FILE:-}" ]]; then + [[ -r "$MODULES_FILE" ]] || { + echo "MODULES_FILE is not readable: $MODULES_FILE" >&2 + exit 2 + } + mapfile -t -d '' DIRS <"$MODULES_FILE" +elif [[ -n "${MODULES:-}" ]]; then mapfile -t DIRS <<<"$MODULES" else - # The name is cut with a parameter expansion, not `dirname` in a command - # substitution: that drops a trailing newline, and a module directory may end in - # one, so the run would probe a directory that does not exist and skip the module. mapfile -t -d '' DIRS < <(cd "$CHECKOUT" && git_paths ls-files -z -- '**/go.mod' 'go.mod' \ | while IFS= read -r -d '' m; do - case $m in + case "$m" in */*) printf '%s\0' "${m%/*}" ;; *) printf '%s\0' . ;; esac diff --git a/server/code/workers/scip_go_delta.py b/server/code/workers/scip_go_delta.py index 5a18cf15a63..6180849d021 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -581,7 +581,13 @@ def _harness_env(out_dir: Path, modules: list[str], cfg: RepoConfig) -> dict[str env["GOPRIVATE"] = settings.code_scip_go_private env["GONOSUMDB"] = settings.code_scip_go_private if modules: - env["MODULES"] = "\n".join(modules) + # A module directory is a path: one whose name ends in a newline cannot ride a + # newline-joined variable (the harness would read a truncated `cd` and skip the + # module while the watermark advanced). The list goes beside the deltas, + # NUL-separated, so the harness reads every byte of it. + modules_file = out_dir / "modules" + modules_file.write_bytes(b"".join(os.fsencode(m) + b"\0" for m in modules)) + env["MODULES_FILE"] = str(modules_file) return env diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index 0a30604e95d..fe5f4c33668 100644 --- a/tests/unit/test_code_scip_go_delta_worker.py +++ b/tests/unit/test_code_scip_go_delta_worker.py @@ -294,16 +294,20 @@ async def run(cfg: Any) -> Any: assert state["scip_commit_go"] == "b" * 40 -def test_harness_env_carries_the_entrys_generated_rule_and_the_modules(monkeypatch, tmp_path): +def test_harness_env_carries_the_entrys_generated_rule_and_the_module_list(monkeypatch, tmp_path): + """The selected modules go in a NUL-separated file, not a newline-joined variable: a + module directory is a path, and one ending in a newline would be cut by the join.""" monkeypatch.setenv("PATH", "/usr/local/go/bin:/host/go/bin:/usr/bin") monkeypatch.setattr(w.settings, "code_scip_go_bin_dir", str(tmp_path)) monkeypatch.setattr(w.settings, "code_scip_go_private", "go.example.com") - env = w._harness_env(tmp_path, ["svc", "lib"], _Cfg()) - assert env["MODULES"] == "svc\nlib" and env["EXCLUDE_GENERATED"] == "1" + env = w._harness_env(tmp_path, ["svc", "svc/e\n"], _Cfg()) + assert "MODULES" not in env + assert Path(env["MODULES_FILE"]).read_bytes() == b"svc\0svc/e\n\0" + assert env["EXCLUDE_GENERATED"] == "1" assert env["GOPRIVATE"] == "go.example.com" and env["GOFLAGS"] == "-mod=mod" assert env["PATH"].startswith(str(tmp_path)) assert "/usr/local/go/bin" in env["PATH"] and "/host/go/bin" in env["PATH"] - assert "MODULES" not in w._harness_env(tmp_path, [], _Cfg()) + assert "MODULES_FILE" not in w._harness_env(tmp_path, [], _Cfg()) def test_harness_env_carries_no_credential_into_module_downloads(monkeypatch, tmp_path): diff --git a/tests/unit/test_run_go_monorepo_delta_modules.py b/tests/unit/test_run_go_monorepo_delta_modules.py new file mode 100644 index 00000000000..d10f8c51faf --- /dev/null +++ b/tests/unit/test_run_go_monorepo_delta_modules.py @@ -0,0 +1,130 @@ +"""run_go_monorepo_delta.sh enumerates module directories losslessly. + +A directory whose name ends in a newline is a module like any other: `$(dirname ...)` +drops that newline, the module's `cd` misses, and the worker advances the watermark with +no delta for it. The selected modules reach the harness NUL-separated for the same +reason: a newline-joined variable cannot carry such a directory. go, scip-go and the +converter are stubs; git runs for real. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +_SCRIPT = ( + Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_go_monorepo_delta.sh" +) + +_FAKE_GO = """#!/usr/bin/env bash +exit 0 +""" + +_FAKE_SCIP_GO = """#!/usr/bin/env bash +# The directory the indexer ran in, NUL-separated: a module name may hold any byte. +printf '%s\\0' "$PWD" >>"$INDEXED" +while [[ $# -gt 0 ]]; do [[ "$1" == --output ]] && : >"$2"; shift; done +""" + +_FAKE_PYTHON = """#!/usr/bin/env bash +# The converter's last argument is the delta it writes. +printf '{}\\n' >"${!#}" +""" + + +def _git(cwd: Path, *args: str) -> str: + return subprocess.run( + ["git", *args], cwd=cwd, check=True, capture_output=True, text=True + ).stdout.strip() + + +def _repo(tmp_path: Path, members: list[str]) -> Path: + repo = tmp_path / "repo" + for member in members: + root = repo / member if member else repo + root.mkdir(parents=True, exist_ok=True) + (root / "go.mod").write_text("module example.com/x\n\ngo 1.22\n") + (root / "main.go").write_text("package main\n\nfunc main() {}\n") + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + return repo + + +def _run( + tmp_path: Path, repo: Path, extra_env: dict[str, str] | None = None +) -> tuple[subprocess.CompletedProcess[str], Path]: + bin_dir = tmp_path / "bin" + bin_dir.mkdir(exist_ok=True) + for name, body in ( + ("go", _FAKE_GO), + ("scip-go", _FAKE_SCIP_GO), + ("python", _FAKE_PYTHON), + ): + dest = bin_dir / name + dest.write_text(body) + dest.chmod(0o755) + indexed = tmp_path / "indexed" + indexed.unlink(missing_ok=True) + out_dir = tmp_path / "deltas" + env = { + **os.environ, + "PATH": f"{bin_dir}:{os.environ['PATH']}", + "INDEXED": str(indexed), + "DELTA_OUT_DIR": str(out_dir), + "PYTHON": str(bin_dir / "python"), + "SCIP_GO": str(bin_dir / "scip-go"), + "MIN_GO_FILES": "1", + "JOBS": "1", + **(extra_env or {}), + } + env.pop("MODULES", None) + env.pop("MODULES_FILE", None) + env.update(extra_env or {}) + proc = subprocess.run( + ["bash", str(_SCRIPT), str(repo), "--full", _git(repo, "rev-parse", "HEAD")], + env=env, + check=False, + capture_output=True, + text=True, + ) + return proc, indexed + + +def _indexed_dirs(indexed: Path, repo: Path) -> list[str]: + """The directories scip-go ran in, relative to the checkout: a module the harness + never reached is one this list lacks, and a name cut at a newline names a directory + git does not hold.""" + if not indexed.exists(): + return [] + dirs = [] + for raw in indexed.read_bytes().split(b"\0"): + if not raw: + continue + dirs.append(os.path.relpath(os.fsdecode(raw), str(repo))) + return sorted(dirs) + + +def test_a_module_directory_ending_in_a_newline_is_indexed(tmp_path: Path) -> None: + """`${m%/*}` keeps the newline `$(dirname ...)` strips: the module is indexed, not + skipped, and the pass writes its delta.""" + weird = "svc/e\n" + repo = _repo(tmp_path, ["", "svc/api", weird]) + proc, indexed = _run(tmp_path, repo) + assert proc.returncode == 0, proc.stderr + assert _indexed_dirs(indexed, repo) == [".", "svc/api", weird] + assert (tmp_path / "deltas" / "svc__e\n.json").exists() + + +def test_selected_modules_reach_the_harness_nul_separated(tmp_path: Path) -> None: + """The worker's list arrives in a NUL-separated file: a newline-joined `MODULES` + cannot carry a directory that ends in a newline, so the harness reads none of the + module and the worker advances the watermark without its delta.""" + weird = "svc/e\n" + repo = _repo(tmp_path, ["", "svc/api", weird]) + modules = tmp_path / "selected" + modules.write_bytes(b"svc/api\0" + weird.encode() + b"\0") + proc, indexed = _run(tmp_path, repo, {"MODULES_FILE": str(modules)}) + assert proc.returncode == 0, proc.stderr + assert _indexed_dirs(indexed, repo) == ["svc/api", weird] From 19e2b981a30905f33a1b256dc31cce068a9ad854 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 5 Dec 2026 01:57:14 +0000 Subject: [PATCH 78/81] A failed TypeScript member is told apart by its whole path The harness collected the failed members in a newline-separated string and skipped a member whose name appeared in it as a line. A member whose path holds a newline (`packages/long` + newline + `packages/lib`) contains the line `packages/lib`, so when both members failed the shorter one was never passed to the merge, and its rows could be retired as if it had not failed. The seen-set is now an associative array keyed by the whole member path. The members still reach the merge as separate arguments, so no byte of a path is altered. Test: test_a_failed_member_is_not_conflated_with_a_line_of_another_members_name (red: only the longer member's file was listed as failed). Assisted-by: Claude Code:claude-sonnet-5-5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/run_typescript_delta.sh | 10 ++-- .../test_run_typescript_delta_umbrella.py | 60 ++++++++++++++++++- 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/scripts/scip_harness/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 763c6a944b8..7dfd68adada 100755 --- a/scripts/scip_harness/run_typescript_delta.sh +++ b/scripts/scip_harness/run_typescript_delta.sh @@ -365,16 +365,16 @@ JSONEOF # the raw bytes reach the merge, which writes the failed list back NUL-separated # for the converter. git_paths ls-files -z -- "${TS_GLOBS[@]}" >"$WORK/candidates.txt" - local failed_members=$'\n' + # Keyed by the whole member: a newline-separated string cannot tell a member from + # a line of another member's name. + local -A failed_members=() for i in "${!pair_run[@]}"; do case " ${failed_runs[*]} " in *" ${pair_run[i]} "*) ;; *) continue ;; esac - case "$failed_members" in - *$'\n'"${pair_member[i]}"$'\n'*) continue ;; - esac - failed_members="$failed_members${pair_member[i]}"$'\n' + [[ -n "${failed_members["${pair_member[i]}"]:-}" ]] && continue + failed_members["${pair_member[i]}"]=1 merge_args+=(--failed-project "${pair_member[i]}") done merge_args+=(--paths "$WORK/candidates.txt" --failed-paths "$WORK/failed.txt") diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 6b1f52bf911..6b33a1bf9d0 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -59,7 +59,7 @@ # the merge writes it; a plain list stays newline-separated. Read either shape, # as the converter's `_path_list` reads it. if [[ $(wc -c <"$f") -ne $(tr -d '\\000' <"$f" | wc -c) ]]; then - while IFS= read -r -d '' p; do printf 'failed\\t%s\\n' "$p" >>"$CALLS"; done <"$f" + while IFS= read -r -d '' p; do printf 'failed\\t%s\\n' "${p//$'\\n'/\\\\n}" >>"$CALLS"; done <"$f" else while IFS= read -r p; do printf 'failed\\t%s\\n' "$p" >>"$CALLS"; done <"$f" fi @@ -640,6 +640,64 @@ def test_a_failed_member_whose_name_is_a_token_of_another_is_not_skipped( assert _failed(log) == ["app/src/a.ts", "packages/my app/src/a.ts"] +def test_a_failed_member_is_not_conflated_with_a_line_of_another_members_name( + tmp_path: Path, +) -> None: + """`packages/long\\npackages/lib` holds a line that is the member `packages/lib`. + + Both indexers fail. Each is its own member: the failed list carries the files of + both, so the shorter member's rows are not retired as if it had not failed. + """ + repo = tmp_path / "repo" + long_member = "packages/long\npackages/lib" + files = { + "tsconfig.json": json.dumps( + { + "files": [], + "references": [ + {"path": "packages/app"}, + {"path": long_member}, + {"path": "packages/lib"}, + ], + } + ), + "packages/app/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/app/src/a.ts": "export const a = 1;\n", + f"{long_member}/tsconfig.json": json.dumps({"include": ["src"]}), + f"{long_member}/src/a.ts": "export const a = 1;\n", + "packages/lib/tsconfig.json": json.dumps({"include": ["src"]}), + "packages/lib/src/b.ts": "export const b = 1;\n", + } + for rel, text in files.items(): + path = repo / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "add", "-A") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init") + head = _git(repo, "rev-parse", "HEAD") + writer = tmp_path / "scip_writer.py" + writer.write_text(_SCIP_WRITER) + # Both names hold "packages/lib", so both indexers fail; packages/app still converts. + proc, log = _run_status( + tmp_path, + repo, + "--full", + head, + { + "BROKEN_PROJECT": "packages/lib", + "INDEXED": str(tmp_path / "indexed"), + "MERGED": str(tmp_path / "merged.scip"), + "SCIP_VENDOR": str(_SCRIPT.parent / "vendor"), + "SCIP_WRITER": str(writer), + }, + scip=_FAKE_SCIP_INDEXING, + ) + assert proc.returncode == 0, proc.stderr + # The stub prints a newline in a name as a backslash and an n, so one entry stays on one line. + assert _failed(log) == ["packages/lib/src/b.ts", "packages/long\\npackages/lib/src/a.ts"] + + def test_full_pass_starts_one_indexer_process_per_member(tmp_path: Path) -> None: """A full pass must not hand every member to one scip-typescript process. From 41352d58b473dcec24a5984c296c1fe258a6c948 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 5 Dec 2026 01:59:16 +0000 Subject: [PATCH 79/81] A Go module that fails to build is named whole in the harness output, whatever its directory holds The harness printed a failed module as one `skip : ... failed: ...` line, so a directory ending in a newline broke it in two: the worker read neither a failed module nor a retry for it, and the healthy delta advanced the watermark. The harness now writes a backslash, a newline and a carriage return in the directory as `\\`, `\n` and `\r`, and `failed_dir` reads them back, so the module is recorded, shown and retried under its real name. Assisted-by: Claude Code:claude-sonnet-5-5 Signed-off-by: Kaloyan Naumov --- scripts/scip_harness/run_go_monorepo_delta.sh | 15 ++++++++--- server/code/domain/index/tier_health.py | 10 +++++-- .../test_run_go_monorepo_delta_modules.py | 26 +++++++++++++++++++ 3 files changed, 46 insertions(+), 5 deletions(-) diff --git a/scripts/scip_harness/run_go_monorepo_delta.sh b/scripts/scip_harness/run_go_monorepo_delta.sh index c9ecef0ae86..cb3fd80da34 100755 --- a/scripts/scip_harness/run_go_monorepo_delta.sh +++ b/scripts/scip_harness/run_go_monorepo_delta.sh @@ -80,6 +80,15 @@ else done | sort -zu) fi +# A module's failure line is one line the worker reads the directory back from: a +# backslash, a newline or a carriage return in the directory is written as `\\`, `\n` or +# `\r`, so a name that ends in a newline is named whole, not cut where the line breaks. +line_safe() { + local s=${1//\\/\\\\} + s=${s//$'\n'/\\n} + printf '%s' "${s//$'\r'/\\r}" +} + run_module() { # an xargs child: without these a failed conversion would pass as `tail`'s exit set -o pipefail @@ -117,10 +126,10 @@ run_module() { if ((window)) && [[ ! -s "$work/changed.txt" ]]; then : >"$work/index.scip" # only deletions: an empty Index, no scip-go run elif ! (cd "$CHECKOUT/$dir" && go mod download >"$work/download.log" 2>&1); then - echo "skip $dir: go mod download failed: $(tail -1 "$work/download.log")" >&2 + echo "skip $(line_safe "$dir"): go mod download failed: $(tail -1 "$work/download.log")" >&2 return 0 elif ! (cd "$CHECKOUT/$dir" && "$SCIP_GO" --output "$work/index.scip" >"$work/scip-go.log" 2>&1); then - echo "skip $dir: scip-go failed: $(tail -1 "$work/scip-go.log")" >&2 + echo "skip $(line_safe "$dir"): scip-go failed: $(tail -1 "$work/scip-go.log")" >&2 return 0 fi if [[ -n "${DELTA_OUT_DIR:-}" ]]; then @@ -130,6 +139,6 @@ run_module() { fi echo "done $dir" } -export -f run_module git_paths window_files convert_delta +export -f run_module line_safe git_paths window_files convert_delta export CHECKOUT SCIP_GO PYTHON HARNESS_DIR HEAD_SHA BASE LOOM_BASE_URL ORG NS MIN_GO_FILES DELTA_OUT_DIR LOOM_API_KEY EXCLUDE_GENERATED printf '%s\0' "${DIRS[@]}" | xargs -0 -P "$JOBS" -I{} bash -c 'run_module "$@"' _ {} diff --git a/server/code/domain/index/tier_health.py b/server/code/domain/index/tier_health.py index ab228922039..0de85a9186f 100644 --- a/server/code/domain/index/tier_health.py +++ b/server/code/domain/index/tier_health.py @@ -327,12 +327,18 @@ def is_module_line(line: str) -> bool: _FAILED_DIR = re.compile(r"(.*?): (?:go mod download|scip-go) failed") +_LINE_ESCAPE = re.compile(r"\\(.)") +_UNESCAPED = {"n": "\n", "r": "\r", "\\": "\\"} def failed_dir(line: str) -> str: - """The module dir of a module line without `skip `: `: go mod download failed: ...`.""" + """The module dir of a module line without `skip `: `: go mod download failed: ...`. + The harness writes a backslash, a newline and a carriage return in the dir as `\\\\`, + `\\n` and `\\r` (`line_safe`), so the line is one line; they are read back here.""" found = _FAILED_DIR.match(line) - return found.group(1) if found else line + if not found: + return line + return _LINE_ESCAPE.sub(lambda m: _UNESCAPED.get(m.group(1), m.group(0)), found.group(1)) def module_failures(text: str) -> list[str]: diff --git a/tests/unit/test_run_go_monorepo_delta_modules.py b/tests/unit/test_run_go_monorepo_delta_modules.py index d10f8c51faf..953468807c6 100644 --- a/tests/unit/test_run_go_monorepo_delta_modules.py +++ b/tests/unit/test_run_go_monorepo_delta_modules.py @@ -13,11 +13,20 @@ import subprocess from pathlib import Path +import pytest + +from server.code.app.index.output_mask import Unmasked + _SCRIPT = ( Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "run_go_monorepo_delta.sh" ) _FAKE_GO = """#!/usr/bin/env bash +# `go mod download` fails in the directory GO_FAILS_AT names, when one is set. +if [[ -n "${GO_FAILS_AT:-}" && "$PWD" == *"$GO_FAILS_AT" ]]; then + echo "dial tcp: connection refused" + exit 1 +fi exit 0 """ @@ -128,3 +137,20 @@ def test_selected_modules_reach_the_harness_nul_separated(tmp_path: Path) -> Non proc, indexed = _run(tmp_path, repo, {"MODULES_FILE": str(modules)}) assert proc.returncode == 0, proc.stderr assert _indexed_dirs(indexed, repo) == ["svc/api", weird] + + +@pytest.mark.parametrize("weird", ["svc/e\n", "svc/b\\n", "svc/c\r\\"]) +def test_a_failed_module_directory_is_named_whole(tmp_path: Path, weird: str) -> None: + """The failure line is one line whatever the directory holds: the worker reads the + module from it to record the failure and keep its retry, and a name cut at a + newline is none of the run's modules, so the watermark would advance past it. A + backslash is written as one too, so `b\\n` and a newline stay two modules.""" + repo = _repo(tmp_path, ["svc/api", weird]) + proc, _ = _run(tmp_path, repo, {"GO_FAILS_AT": weird.rsplit("/", 1)[1]}) + assert proc.returncode == 0, proc.stderr + printed = Unmasked((proc.stdout + proc.stderr).encode()) + broken, unreachable = printed.module_dirs() + assert (broken, unreachable) == ([weird], []) + shown_broken, _ = printed.module_failures() + assert len(shown_broken) == 1 + assert "connection refused" in shown_broken[0] From f5b3de236e2c1473e6db072f4075be6e438157ba Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 5 Dec 2026 02:11:33 +0000 Subject: [PATCH 80/81] The boolean-settings count in status.md follows the merged settings Regenerated with scripts/codegen/docs_reference.py after the merge of main and #1704: the count of boolean settings that load false is 58. Assisted-by: Claude Code:claude-sonnet-5-5 Signed-off-by: Kaloyan Naumov --- docs/reference/status.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/status.md b/docs/reference/status.md index d63b20d2958..e51a92a87db 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -89,7 +89,7 @@ default is `off`) are not listed here. -57 boolean settings load false. +58 boolean settings load false. | Setting | Meaning | | --- | --- | From 4cfab6603dcdebb0234b390e2edc019a202a4c56 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 5 Dec 2026 02:14:56 +0000 Subject: [PATCH 81/81] The stale-mark integration test stubs the submodule sync main added `_run_repo` now syncs submodule URLs through the compiler tier's own `git` (#2080), which the test's temporary checkout cannot run, so test_a_window_with_nothing_to_apply_keeps_the_mark failed before it reached the window. The test stubs `update_submodules` beside `git`. Assisted-by: Claude Code:claude-sonnet-5-5 Signed-off-by: Kaloyan Naumov --- tests/integration/test_code_scip_stale_mark.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/integration/test_code_scip_stale_mark.py b/tests/integration/test_code_scip_stale_mark.py index 9317d22139f..f0d7018ccbb 100644 --- a/tests/integration/test_code_scip_stale_mark.py +++ b/tests/integration/test_code_scip_stale_mark.py @@ -301,6 +301,9 @@ async def no_delta(*a: Any, **kw: Any) -> tuple[int, str, Unmasked]: lambda cfg: (tmp_path, str(tmp_path / "scip-clang"), tmp_path, None), ) monkeypatch.setattr(delta_worker, "git", no_git) + # The pass syncs submodule URLs through the compiler tier's own `git`, which this + # checkout (a temporary directory, not a repository) cannot run. + monkeypatch.setattr(delta_worker, "update_submodules", no_git) monkeypatch.setattr(delta_worker, "run_harness", no_delta) result = delta_worker.CodeScipDeltaResult() await delta_worker._run_repo(repo, repo_config(org=org, namespace=ns), result)