diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index a92799eae1e..f04c189d25d 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -439,12 +439,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), one process per project of their reference closures, each project once; a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a TypeScript file no project contains changed beside one that selects a project; a window whose only changes are TypeScript files outside every project indexes none. 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), one process per project of their reference closures, each project once; a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a TypeScript file no project contains changed beside one that selects a project; a window whose only changes are TypeScript files outside every project indexes none. A member 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/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index cedd771115c..e25b0ba3d3c 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -1229,6 +1229,82 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline `tests/unit/test_context_pack_other_namespaces.py` checks N's side, and the mixed-version gate does not check this rule. +80. **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. N-1 neither reads nor empties a mark. A + 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: + `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 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 + next apply of the tier empties its mark when the entry's mirror holds the delta's commit + 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 + 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 `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/docs/features/code-index/overview.md b/docs/features/code-index/overview.md index 822e37fed05..d6ec53dfc8b 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/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index fb5f49aa400..919a3b9be54 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1469,20 +1469,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; 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 80) | +| 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/operations/upgrades.md b/docs/operations/upgrades.md index 6bf989121e7..141b54c03f7 100644 --- a/docs/operations/upgrades.md +++ b/docs/operations/upgrades.md @@ -381,7 +381,7 @@ upgrade does not make older writers participate in those fences know the label columns and its census does not count them, so it verifies clean while a user erasure leaves the user's principal and run on the labels the newer build stamped in `loom.memory_usage_events`, and a namespace erasure leaves the namespace's events - ([rolling upgrades](../architecture/rolling-upgrades.md), rule 72). As in step 10, a + ([rolling upgrades](../architecture/rolling-upgrades.md), rule 73). As in step 10, a user erasure requested again also erases what the user wrote since. This counts the labels one user's principal is still on, for each spelling the erasure covers, where ``, `` and `` are `human:`, @@ -398,7 +398,7 @@ upgrade does not make older writers participate in those fences 20. Moving to a build whose SCIM user delete erases the user's worker sources: once the newer build serves every replica, send again each delete an older replica answered - 409 ([rolling upgrades](../architecture/rolling-upgrades.md), rule 73). The older + 409 ([rolling upgrades](../architecture/rolling-upgrades.md), rule 74). The older build answers it for a user who owns worker sources and finishes none of the user's source erasure, and the 409 is not retryable, so a provider does not send it again. Send `DELETE /scim/v2/Users/` again with the SCIM token for every delete the @@ -442,7 +442,7 @@ fed; request again each one run without `purge` once the newer build serves, as 10; a purge it completed is not found again (rule 37). An erasure the previous build runs leaves the user's principal and run on the usage labels, or the namespace's usage events; run it again once the newer build serves, as in -step 19 (rule 72). +step 19 (rule 73). Before rolling back to a build without read receipts, turn `read_receipts_enabled` off for the deployment (`loom settings set read_receipts_enabled false`, which every replica applies within `LOOM_RUNTIME_OVERRIDES_REFRESH_SECONDS` and which wins over a replica's @@ -452,7 +452,7 @@ environment) and run table above its `max_table_size_to_drop`, 50 GB by default), then run it again once the first replica of the previous build serves, for the rows written in between: that build's erasure has no step for the table -([read receipts](../architecture/read-receipts.md#rolling-upgrades), rule 75). Once the +([read receipts](../architecture/read-receipts.md#rolling-upgrades), rule 76). Once the newer build serves alone again, `loom settings reset read_receipts_enabled` turns receipts back on. Do not roll back past the build that adds the document bucket while any catalog row diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 365899f80c0..c5bd6b51d38 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -465,6 +465,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 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 c8347b7d415..d9a3b515e9c 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -91,7 +91,7 @@ default is `off`) are not listed here. -57 boolean settings load false. +58 boolean settings load false. | Setting | Meaning | | --- | --- | @@ -111,6 +111,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 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_SEARCH_REPORT_PROSE` | Search an issue body (a question past code_search_query_max_tokens) by its prose, without the code blocks, indented code and form lines it pastes, when the prose is itself past that cap and asks for… | | `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. | diff --git a/loom.example.yaml b/loom.example.yaml index 3f3d18080cd..3510b31399f 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -1557,6 +1557,10 @@ 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 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 # 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 513b8c2faff..2737b3b638c 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -2006,6 +2006,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 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, "type": "boolean", diff --git a/scripts/scip_harness/README.md b/scripts/scip_harness/README.md index 263ecf9bcc7..9ccf34a46e7 100644 --- a/scripts/scip_harness/README.md +++ b/scripts/scip_harness/README.md @@ -35,6 +35,35 @@ 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 …`) 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 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 +that file's compiler rows and marks them stale until a later delta converts +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 +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`, 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 +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 @@ -75,17 +104,20 @@ 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. +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 `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/lib.sh b/scripts/scip_harness/lib.sh index 356fb19c44d..892a15133b3 100644 --- a/scripts/scip_harness/lib.sh +++ b/scripts/scip_harness/lib.sh @@ -52,43 +52,46 @@ 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" } # 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_delta.sh b/scripts/scip_harness/run_delta.sh index 6ad773314c0..2b6c4d71c6c 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 623653c7b92..368c0bd52ed 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,20 +58,57 @@ 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 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 + case "$m" in + */*) printf '%s\0' "${m%/*}" ;; + *) printf '%s\0' . ;; + esac + done | sort -zu) fi +# A module directory is written to the harness output as a token that holds only +# `A-Za-z0-9._/+@~-` and `%XX` bytes: a space, a colon, a quote, a newline or any other byte +# in the name is `%` and two hex digits. No directory can then spell a line break or part +# of the `: ... failed` framing, and the worker reads the bytes back exactly. +dir_token() { + local LC_ALL=C s=$1 out='' c i + for ((i = 0; i < ${#s}; i++)); do + c=${s:i:1} + case $c in + [A-Za-z0-9._/+@~-]) out+=$c ;; + *) + printf -v c '%%%02X' "'$c" + out+=$c + ;; + esac + done + printf '%s' "$out" +} + 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 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)" + echo "skip $(dir_token "$dir") ($n go files)" return 0 fi local prefix=$dir @@ -88,7 +128,7 @@ run_module() { # prefix), so the delta tombstones what the window removed (cd "$CHECKOUT" && window_files "$work" "$BASE" "$HEAD_SHA" "${prefix:+$prefix/}*.go") if [[ ! -s "$work/changed.txt" && ! -s "$work/deleted.txt" ]]; then - echo "skip $dir (no Go change in window)" + echo "skip $(dir_token "$dir") (no Go change in window)" return 0 fi args+=(--base "$BASE" --changed-files "$work/changed.txt" --deleted-files "$work/deleted.txt") @@ -96,19 +136,19 @@ 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 $(dir_token "$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 $(dir_token "$dir"): scip-go failed: $(tail -1 "$work/scip-go.log")" >&2 return 0 fi 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[@]}" | tail -1 || return 1 else - convert_delta "${args[@]}" | tail -1 + convert_delta "${args[@]}" | tail -1 || return 1 fi - echo "done $dir" + echo "done $(dir_token "$dir")" } -export -f run_module git_paths window_files convert_delta +export -f run_module dir_token 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/run_typescript_delta.sh b/scripts/scip_harness/run_typescript_delta.sh index 929349ccae1..7dfd68adada 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. @@ -236,42 +249,137 @@ JSONEOF # through a generated config without them, and gives the merge each run once # per member whose process would have indexed it, in that order. A project # whose documents the merge would drop for every such member does not run. - local plan kind run own arg runs=() owns=() parts=() merge_args=() known_args=() t rc + # + # 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 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 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 + # 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 ;; merge) - merge_args+=(--project "$arg") - parts+=("$WORK/index.part.$run.scip") + # 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" \ "$SCIP_TYPESCRIPT" index "${ws[@]}" "${runs[run]}" --output "$WORK/index.part.$run.scip" \ >"$WORK/index.part.$run.log" 2>"$WORK/index.part.$run.err" || rc=$? cat "$WORK/index.part.$run.log" "$WORK/index.part.$run.err" >&2 + if [[ $rc -eq 0 ]]; then + run_ok[run]=1 + 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. Any - # other failure, a killed process included, fails the pass with its status. - if [[ $rc -ne 0 ]]; then - if [[ "${owns[run]}" == 0 ]] && indexed_no_file "$run" "$rc"; then - echo ">> ${runs[run]} indexed no file — read as empty" >&2 - else - echo ">> scip-typescript failed on ${runs[run]} (exit $rc)" >&2 - exit "$rc" - fi + # 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 + echo ">> ${runs[run]} 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 run. 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_runs+=("$run") + 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=$'\n' + for i in "${!pair_run[@]}"; do + if [[ "${run_ok[${pair_run[i]}]:-0}" == 1 ]]; then + case "$surviving" in + *$'\n'"${pair_member[i]}"$'\n'*) ;; + *) surviving="$surviving${pair_member[i]}"$'\n' ;; + esac fi done + if [[ -z "${surviving//$'\n'/}" ]]; then + echo ">> every member failed — no delta" >&2 + exit 1 + fi + for i in "${!pair_run[@]}"; do + case " ${failed_runs[*]} " in + *" ${pair_run[i]} "*) continue ;; + esac + merge_args+=(--project "${pair_member[i]}") + parts+=("$WORK/index.part.${pair_run[i]}.scip") + done + if [[ ${#failed_runs[@]} -gt 0 ]]; then + # 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. + # `-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" + # 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 + [[ -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") + CONVERT_ARGS+=(--failed-files "$WORK/failed.txt") + fi # Always merge so a member's run that followed project references also # drops documents it does not own. "$PYTHON" "$HARNESS_DIR/scip_merge_indexes.py" --output "$WORK/index.scip" \ @@ -292,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_merge_indexes.py b/scripts/scip_harness/scip_merge_indexes.py index ecbc1272702..eea948c3776 100644 --- a/scripts/scip_harness/scip_merge_indexes.py +++ b/scripts/scip_harness/scip_merge_indexes.py @@ -16,8 +16,14 @@ 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 +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. The paths it returns as kept are those raw bytes, and `owned_by` compares a +candidate by its raw bytes, so a path no part indexed stays failed even when another +path decodes to the same replacement text. 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 @@ -49,6 +55,7 @@ def _load_harness_module(name: str) -> Any: _ts_projects = _load_harness_module("scip_ts_projects") project_owns = _ts_projects.project_owns project_scope = _ts_projects.project_scope +posix_path = _ts_projects.posix_path scope_specificity = _ts_projects.scope_specificity _converter = _load_harness_module("scip_to_delta") _read_index = _converter._read_index @@ -58,16 +65,54 @@ def _load_harness_module(name: str) -> Any: _METADATA, _DOCUMENT, _EXTERNAL_SYMBOL = 1, 2, 3 -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] + 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[bytes] | frozenset[bytes] = 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`, the raw paths `merge_indexes` returns). A path is compared as its raw bytes, + the one spelling both sides hold. 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: + if path.encode("utf-8", "surrogateescape") 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 def _keeps(project: str, relpath: str, owners: list[str]) -> bool: @@ -107,11 +152,19 @@ def merge_indexes( output: Path, projects: list[str] | None = None, known_projects: list[str] | None = None, -) -> set[str]: - """Write the merged index; return the paths whose document it holds, as text.""" +) -> set[bytes]: + """Write the merged index; return the raw 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") - 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 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 holds those raw bytes: a caller that + # compares a path decodes it under `surrogateescape` or encodes it back, and no + # second decoding (the store's `replace` key) sits between the two sides. + owners = list(known_projects if known_projects is not None else (projects or [])) metadata: list[Any] = [] documents: dict[bytes, Any] = {} external_symbols: list[Any] = [] @@ -128,9 +181,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: @@ -157,7 +211,7 @@ def merge_indexes( except BaseException: tmp.unlink(missing_ok=True) raise - return {raw.decode("utf-8", "replace") for raw in documents} + return set(documents) def main(argv: list[str] | None = None) -> int: @@ -178,11 +232,34 @@ 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="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) projects = args.project or None known = args.known_project or None - merge_indexes(args.indexes, args.output, projects, known) + 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. 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) + # 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 475687ddcd3..51aa68461ef 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. @@ -49,6 +50,7 @@ import time import uuid from pathlib import Path +from typing import Any _HERE = Path(__file__).resolve().parent _VENDOR = _HERE / "vendor" @@ -147,6 +149,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, @@ -214,13 +218,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)}" @@ -271,6 +275,45 @@ 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], 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: + 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 in _TS.def_kinds: + continue + file = _ts_symbol_file(symbol) + if file in failed or file in skipped: + 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 @@ -413,11 +456,11 @@ def _held_edges(held: list[tuple[str, int, str]], enclosing) -> list[dict]: return out -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) @@ -455,7 +498,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 @@ -470,7 +513,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 @@ -479,12 +522,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) @@ -594,12 +637,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 @@ -739,7 +782,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 @@ -747,11 +790,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]): @@ -760,6 +799,11 @@ def _ctor_overloads(records, scip_pb2) -> 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 @@ -917,51 +961,140 @@ 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 _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.""" - return _document_path_bytes(payload).decode("utf-8", "replace") + """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 _path_text(_document_path_bytes(payload)) + + +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. + 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 + 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 + 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 +): + """`_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 _stream_documents(data, scip_pb2, *, paths: set[str] | None = None, ordered: bool = False): - """Yield scip.Document messages by streaming the Index's top-level +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 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`), 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), payload) for 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 = [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) - yield doc + 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 i, 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] @@ -1036,12 +1169,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 @@ -1049,7 +1184,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 @@ -1060,7 +1200,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 = ( @@ -1069,22 +1209,32 @@ 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 + complete = True # only the C++ scan's own skips count, not another pass's if src.available and is_cxx: - ctors = _ctor_overloads(_top_level_records(data), scip_pb2) - ancestors = _implementation_targets(data, scip_pb2) + 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, ) @@ -1099,11 +1249,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) @@ -1148,7 +1298,7 @@ def _convert_document(doc, run: _Run) -> dict | None: held_refs: list[tuple[str, int, str]] = [] # TypeScript only: (edge kind, line, symbol) 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: @@ -1159,7 +1309,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 @@ -1216,6 +1366,10 @@ def _convert_document(doc, run: _Run) -> dict | None: edge_kind = "uses_type" if _ts_typeof_ref(lines, occ.range) else "calls" held_refs.append((edge_kind, 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 @@ -1302,10 +1456,11 @@ 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 stats and the features, complete once `files` is - exhausted.""" + 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__( self, @@ -1319,12 +1474,28 @@ def __init__( full: bool = False, 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._run = _prepare(data, scip_pb2, source_root, exclude_generated, path_prefix) + self._skips = _Skips(stop_on_failed_document, whole=changed is None) + # 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 ()) + 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 + ) 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 @@ -1335,14 +1506,26 @@ 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): - for doc in _stream_documents(data, scip_pb2, 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 - entry = _convert_document(doc, self._run) + 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: + 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, i) + continue if entry is None: continue if self._prefix: @@ -1350,15 +1533,29 @@ 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, + "skipped_files": skipped, "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: + # 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 + # convert is known only once `files` is written. + out["delta_version"] = 2 if skipped else 1 return out @@ -1373,6 +1570,8 @@ def convert( full: bool = False, 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). @@ -1393,6 +1592,8 @@ def convert( full=full, 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()} @@ -1488,14 +1689,25 @@ 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 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 a list + that holds a NUL is split on NUL only and nothing is stripped off its ends; a list + with no NUL is a newline list (`git diff --name-only` without `-z`), which cannot + name such a file, and is split on its lines.""" if not path: return [] - return [ln.strip() for ln in Path(path).read_text().splitlines() if ln.strip()] + raw = Path(path).read_bytes() + if b"\0" in raw: + 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()] def _summary(counts: dict) -> str: @@ -1503,6 +1715,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']})" ) @@ -1540,6 +1753,18 @@ 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( + "--failed-files", + 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( "--source-root", default=None, @@ -1557,14 +1782,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, @@ -1575,6 +1803,8 @@ 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), + failed=_path_list(args.failed_files), ) if args.dry_run: diff --git a/scripts/scip_harness/scip_ts_projects.py b/scripts/scip_harness/scip_ts_projects.py index 92b2875d837..5bc25e1c8b8 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 @@ -394,15 +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 ` 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.""" +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", 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): @@ -410,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)}") + 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: @@ -501,15 +530,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: owner_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 @@ -519,14 +552,21 @@ def select_projects_for_delta(projects: list[str], changed_paths: list[str]) -> return selected +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 (`_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") + + 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: @@ -572,7 +612,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 @@ -582,10 +626,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/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/api/models_symbol.py b/server/code/api/models_symbol.py index f0a5f1e5961..caf1b186f72 100644 --- a/server/code/api/models_symbol.py +++ b/server/code/api/models_symbol.py @@ -558,8 +558,9 @@ 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, or a seed + # 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`. causes: list[str] = Field(default_factory=list) @@ -692,7 +693,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), unmapped_changes (diff shape: a changed source line sits in # no function, such as module-level code, a class body, a file with no # definition, or a line the diff adds with no new side read or in a function the diff --git a/server/code/app/index/compiler_tier.py b/server/code/app/index/compiler_tier.py index 1f9834339b6..940a4ff1d59 100644 --- a/server/code/app/index/compiler_tier.py +++ b/server/code/app/index/compiler_tier.py @@ -44,6 +44,11 @@ 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; 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): # the window cannot be diffed, and only a full index can bring the tier back. @@ -99,7 +104,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 @@ -111,7 +118,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) @@ -163,6 +171,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 @@ -604,12 +629,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: @@ -868,13 +894,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`; 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" 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], @@ -884,4 +913,10 @@ 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"), done.printed() + out = done.stdout.decode("utf-8", "replace") + 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, done.printed() diff --git a/server/code/app/index/delta_file.py b/server/code/app/index/delta_file.py index 4716763a8f7..db99994c6c5 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 @@ -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]] = { @@ -348,11 +350,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 @@ -361,9 +365,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: @@ -390,11 +394,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")) @@ -409,9 +414,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) @@ -470,4 +479,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/gitrepo.py b/server/code/app/index/gitrepo.py index f67e39363de..8e050251a9a 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -1309,10 +1309,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", @@ -1322,38 +1336,61 @@ 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 -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.""" - return set((await blob_ids_at(git_dir, (sha,), paths))[sha]) +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 path the + batch input cannot name (a line break, `./`, `../`) holds no blob, as one git + cannot resolve does. `strict` raises GitError where the read itself fails — a reply + short of the request, or a clone git cannot read — for a caller that treats a + missing path as proof the file is gone.""" + try: + return set((await blob_ids_at(git_dir, (sha,), paths))[sha]) + except GitError: + if strict: + raise + return set() + + +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] async def blob_ids_at( diff --git a/server/code/app/index/packs.py b/server/code/app/index/packs.py index 46079be97f0..069da24e565 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_sample(org, ns, limit=1) 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/index/scip_delta.py b/server/code/app/index/scip_delta.py index 891acdbdcee..5d4f4faffca 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,10 +25,18 @@ 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_APPLIED_PREFIX, + SCIP_STALE_PREFIX, + SCIP_UNAVAILABLE_PREFIX, +) from server.code.store.index import CodeRepo, build_row 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): @@ -89,6 +98,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 ) @@ -106,6 +117,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]]: ... @@ -233,18 +245,25 @@ 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`).""" stats = ScipApplyStats() + skipped_paths = set(delta.skipped_files) 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 @@ -254,24 +273,41 @@ 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 + 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) reading = False if batch is None: break - await _apply_files(repo, org, ns, delta.commit, batch, stats) + # 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, 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 # its thread keeps it until that read returns and the rounds are collected if not reading: 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, marked) if FEATURE_CTOR_CALLS in delta.features: check_held() await repo.set_state( @@ -285,8 +321,205 @@ 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. 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. + 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: + 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} + 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() + + +async def _mark_stale( + repo: Any, + org: str, + ns: str, + tier: str, + commit: str, + skipped: set[str], + refreshed: set[str], + marked: set[str], +) -> 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 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 + prefix = f"{SCIP_STALE_PREFIX}{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 cleared}) + rows.update({applied + p: "" for p in cleared}) + if rows: + check_held() + 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 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.clear_scip_marks(org, ns, tier, sorted(published)) + return published + + +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 + + +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 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: + return set() + 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 + 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 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] + ) + 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 _record_applied( + 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 `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, owed) + + 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.""" @@ -294,11 +527,11 @@ async def _apply_files( pass_context.check_stop() await _settle_held_edges(repo, org, ns, files, stats) 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 @@ -337,9 +570,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") @@ -370,6 +607,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, paths, marked) def _symbol_metadata(symbol: ScipSymbol) -> dict[str, Any]: @@ -396,10 +634,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") @@ -468,6 +709,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], marked or set()) async def _diff_edges( diff --git a/server/code/app/index/scip_full.py b/server/code/app/index/scip_full.py index ec6404e2e99..716d9a14626 100644 --- a/server/code/app/index/scip_full.py +++ b/server/code/app/index/scip_full.py @@ -190,7 +190,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/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index ab4c4cced7b..455295e1609 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 @@ -82,11 +83,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: @@ -97,6 +103,36 @@ async def _scip_stale(repo: CodeRepo, org: str, ns: str, edges: list[Any]) -> se 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 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_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} + + +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 @@ -157,13 +193,33 @@ 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 - (`scip_ctor_calls`); 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, named - in `degraded` on every answer that serves it. The read is every request's, so it runs - outside a best-effort block.""" + 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 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; a failed state read says no to both and is named in + `degraded` on every answer that serves it.""" + scip_bit, ts_ok = await _ctor_state(repo, org, ns) + if not scip_bit: + return False, ts_ok + try: + 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 + + +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, + named in `degraded` on every answer that serves it. The read is every request's, so it + runs outside a best-effort block.""" hit = _CTOR_CACHE.get((org, ns)) if hit is None: ttl: float | None = None diff --git a/server/code/app/symbol/gate.py b/server/code/app/symbol/gate.py index 8a9dd5929c0..3cbc2793923 100644 --- a/server/code/app/symbol/gate.py +++ b/server/code/app/symbol/gate.py @@ -20,9 +20,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 ( @@ -88,7 +88,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( @@ -102,7 +102,7 @@ async def handle_code_test_gate(input: CodeTestGateInput) -> CodeTestGateOutput: neighbors=near_rows + over, ), _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), ) span_attrs(sp, results=len(links.impacted)) @@ -133,6 +133,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 or cut, ) # 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 0c8047461ca..3dee57b03d8 100644 --- a/server/code/app/symbol/graph.py +++ b/server/code/app/symbol/graph.py @@ -31,11 +31,13 @@ ) from server.code.app.symbol.coverage import ( _CTOR_NOTE, + MARKS_UNREAD, _ctor_edges_absent, _declined_outgoing_safe, _declined_safe, _env_fields, _has_ctor_seed, + _marked_stale, _scip_coverage, _scip_stale, ) @@ -49,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 @@ -385,21 +388,28 @@ 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) + 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), ) - 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} | marked + return declined, scip_paths, dispatch_missing, stale_paths def _not_found(input: CodeCallersInput, overlay: Any) -> str: @@ -482,9 +492,15 @@ 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"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" - ) + files = stale_paths - {MARKS_UNREAD} + parts = [] + if files: + parts.append( + "file(s) changed since the compiler tier last ran or skipped " + 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: + parts.append("the stale marks could not be read") + return "; ".join(parts) diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index 5b97486bc36..d922aadd521 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 ( @@ -398,7 +398,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), @@ -414,7 +414,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 @@ -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 @@ -460,6 +453,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, ) if unplaced: @@ -556,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]: diff --git a/server/code/app/symbol/neighbours.py b/server/code/app/symbol/neighbours.py index 7bbe79d693e..dafee3c3b7a 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 @@ -231,13 +231,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)) @@ -284,6 +284,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 689a9a684cb..a28bb9f5243 100644 --- a/server/code/app/symbol_uses.py +++ b/server/code/app/symbol_uses.py @@ -229,9 +229,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 = [ @@ -260,7 +262,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", } @@ -285,6 +287,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]] = {} @@ -309,9 +312,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 degradations.partial("code_index", "uses_leg_dropped", e) @@ -320,7 +324,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 0ad04b03e78..0d82c5a55b6 100644 --- a/server/code/domain/index/epistemic.py +++ b/server/code/domain/index/epistemic.py @@ -24,8 +24,14 @@ 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 - from content that tier never saw + tier's last run, or whose document that + 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; 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 @@ -50,8 +56,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..5b42f545f6e 100644 --- a/server/code/domain/index/state.py +++ b/server/code/domain/index/state.py @@ -24,6 +24,30 @@ class StateEntry(TypedDict, total=False): # The state key of an entry's bootstrap stage, whose detail is JSON. STAGE_KEY = "bootstrap_stage" +# 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 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: 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/domain/index/tier_health.py b/server/code/domain/index/tier_health.py index ab228922039..684cdd54edb 100644 --- a/server/code/domain/index/tier_health.py +++ b/server/code/domain/index/tier_health.py @@ -12,6 +12,7 @@ import json import re +import urllib.parse from dataclasses import asdict, dataclass from datetime import UTC, datetime @@ -326,13 +327,19 @@ def is_module_line(line: str) -> bool: return line.startswith("skip ") and bool(_MODULE_FAILED.search(line)) -_FAILED_DIR = re.compile(r"(.*?): (?:go mod download|scip-go) failed") +_FAILED_DIR = re.compile(r"([^\s:]*): (?:go mod download|scip-go) failed") 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 the dir as a token of `A-Za-z0-9._/+@~-` and `%XX` bytes + (`dir_token`), so it holds no space, colon or line break to end the dir early; the + bytes are decoded as the worker lists modules (`_module_dirs`: UTF-8, `replace`), so + the name equals the retry map's key.""" found = _FAILED_DIR.match(line) - return found.group(1) if found else line + if not found: + return line + return urllib.parse.unquote_to_bytes(found.group(1)).decode("utf-8", "replace") def module_failures(text: str) -> list[str]: diff --git a/server/code/store/index/base.py b/server/code/store/index/base.py index 1ae7463556d..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 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, @@ -132,9 +137,11 @@ 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}) + AND NOT startsWith(state_key, {applied:String}) ORDER BY state_key """, - {"org": org, "ns": ns}, + {"org": org, "ns": ns, "stale": SCIP_STALE_PREFIX, "applied": SCIP_APPLIED_PREFIX}, ) return { str(r["state_key"]): StateEntry( @@ -156,9 +163,15 @@ 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}) + AND NOT startsWith(state_key, {applied: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, + "applied": SCIP_APPLIED_PREFIX, + }, ) out: dict[tuple[str, str], IndexState] = {(str(o), str(n)): {} for o, n in pairs} for r in rows: @@ -168,15 +181,61 @@ async def all_state_many( return out async def set_state(self, org: str, ns: str, key: str, value: str, detail: str = "") -> None: - """Write the `key` row at a version past that key's newest row, on ClickHouse's - clock (`next_version`). Workers on several hosts write one namespace's state, and - a row written on a clock behind its key's newest would neither move - `state_generation` nor, under FINAL, replace that row. The floor is the key's - alone: a previous build still writes on its own clock, and another key's row - ahead of it must not put this build's rows past that build's next write.""" - version = await next_version( - self._ch, "loom.code_index_state", {"org": org, "namespace": ns, "state_key": key} + 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, each at a version past that + key's newest row, on ClickHouse's clock (`next_version`). Workers on several hosts + write one namespace's state, and a row written on a clock behind its key's newest + would neither move `state_generation` nor, under FINAL, replace that row. The floor + is the key's alone: a previous build still writes on its own clock, and another + key's row ahead of it must not put this build's rows past that build's next write. + """ + now = _now() + versions = { + key: await next_version( + self._ch, "loom.code_index_state", {"org": org, "namespace": ns, "state_key": key} + ) + for key in values + } + await self._ch.insert( + "loom.code_index_state", + [ + { + "org": org, + "namespace": ns, + "state_key": key, + "state_value": value, + "detail": detail, + "updated_at": now, + "version": versions[key], + } + for key, value in values.items() + ], ) + + 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", [ @@ -186,9 +245,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(), + "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 ff4fe61a126..5c7e38ff8e1 100644 --- a/server/code/store/index/symbols.py +++ b/server/code/store/index/symbols.py @@ -5,10 +5,13 @@ from __future__ import annotations +from collections.abc import Iterator from typing import Any 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_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 @@ -22,12 +25,72 @@ 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]]] # The kinds `functions_for_paths` reads unless asked for others. FUNCTION_KINDS: tuple[str, ...] = ("function", "method", "fixture") +# 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 _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 + round of it has landed (`_mark_stale`), or, for an entry whose tier its worker runs, that + 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 + FROM loom.code_index_state FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND {keys} AND state_value != '' + """ + + +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 _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.""" @@ -546,51 +609,189 @@ 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 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 (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 + 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`). 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] + 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) - 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 + (`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})"), + {"org": org, "ns": ns, "mark": prefix}, + ) + 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 scip_marks_retirable( + self, org: str, ns: str, tier: str, *, commit: str + ) -> dict[str, str]: + """`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 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 - (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) + 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 != '' + ), + 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 + INNER JOIN applied ON applied.path = marks.path + WHERE applied.applied_commit = {commit:String} + AND applied.applied_at > marks.marked """, - {"org": org, "ns": ns, "paths": asked}, + { + "org": org, + "ns": ns, + "mark": f"{SCIP_STALE_PREFIX}{tier}:", + "applied": f"{SCIP_APPLIED_PREFIX}{tier}:", + "commit": commit, + }, ) - # the query names the FRESH paths; every other asked path is stale - return set(asked) - {str(r["path"]) for r in rows} + 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 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, 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/server/code/workers/scip_apply.py b/server/code/workers/scip_apply.py index 34feccb961f..1060793e671 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: @@ -62,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() @@ -89,9 +98,11 @@ 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) + 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 064f67923af..4850f21c17f 100644 --- a/server/code/workers/scip_delta.py +++ b/server/code/workers/scip_delta.py @@ -170,7 +170,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 8cdf5c9a565..768eea0ebca 100644 --- a/server/code/workers/scip_go_delta.py +++ b/server/code/workers/scip_go_delta.py @@ -80,6 +80,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, ) @@ -99,6 +100,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") @@ -284,6 +290,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 @@ -350,7 +384,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) @@ -358,6 +392,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( @@ -423,12 +458,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] = [] @@ -436,6 +472,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): @@ -461,6 +498,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) @@ -474,7 +512,7 @@ async def _build( paths = await asyncio.to_thread(_deltas, out_dir, len(expected)) for path in paths: delta = await open_tier_delta(repo, cfg, WATERMARK, base, 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( @@ -488,7 +526,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]: @@ -549,7 +594,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/server/code/workers/scip_py_delta.py b/server/code/workers/scip_py_delta.py index ee7498de2e3..efe863edec5 100644 --- a/server/code/workers/scip_py_delta.py +++ b/server/code/workers/scip_py_delta.py @@ -136,7 +136,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 af0a5b34b83..6adc031ea0f 100644 --- a/server/code/workers/scip_ts_delta.py +++ b/server/code/workers/scip_ts_delta.py @@ -179,7 +179,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/server/core/ch_params.py b/server/core/ch_params.py index 05bbb6249af..206b3993f81 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/server/settings/catalog.py b/server/settings/catalog.py index d433d8d2bd0..d65263d4c6f 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1340,6 +1340,9 @@ 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 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 # that hit the TU cap). One entry per pass, under its entry lock. diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 59bb6a26c59..b323dfd4fcb 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -2060,7 +2060,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 dae7125bf66f 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, -- The content hash, for the read receipt of a hit this @@ -2332,6 +2331,7 @@ f51e0ce42dcd SELECT count() OVER () AS total, memory_key, toString(memory_id) AS 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)} f5ffc57e48b2 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, -- The content hash, for the read receipt of a hit this 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/integration/test_code_plane.py b/tests/integration/test_code_plane.py index 94a1c230f6d..95a8518bcf9 100644 --- a/tests/integration/test_code_plane.py +++ b/tests/integration/test_code_plane.py @@ -338,7 +338,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") @@ -348,7 +348,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 @@ -1397,7 +1397,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/integration/test_code_scip_held_edges_live_ch.py b/tests/integration/test_code_scip_held_edges_live_ch.py index 24e613e0d0c..656c5405154 100644 --- a/tests/integration/test_code_scip_held_edges_live_ch.py +++ b/tests/integration/test_code_scip_held_edges_live_ch.py @@ -67,8 +67,11 @@ async def _members(repo: CodeRepo, org: str, ns: str) -> None: {"path": "b/src/gone.ts", "symbols": [_symbol(_TOMB, "function", 1)]}, ] ), + tier="typescript", + ) + await apply_delta( + repo, org, ns, _delta([{"path": "b/src/gone.ts", "deleted": True}]), tier="typescript" ) - await apply_delta(repo, org, ns, _delta([{"path": "b/src/gone.ts", "deleted": True}])) async def test_the_store_reads_each_key_s_compiler_tier_kind(env: Any) -> None: @@ -100,6 +103,7 @@ async def test_a_held_edge_is_written_only_into_a_stored_function(env: Any) -> N } ] ), + tier="typescript", ) assert stats.edges_dropped_unresolved == 3 rows = await repo.live_edges_for_path(org, ns, _A_PATH, "scip") 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..2da4f909ad3 --- /dev/null +++ b/tests/integration/test_code_scip_stale_mark.py @@ -0,0 +1,697 @@ +"""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 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 + +import asyncio +import json +import subprocess +import uuid +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 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, + ScipFile, + ScipSymbol, + apply_delta, +) +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.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 + +BAD = "src/bad.cpp" +OTHER = "src/a.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", + [[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_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]), + 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)]) + + +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 + + 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() + + 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} + 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=BAD)]), tier="clang" + ) + 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_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 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) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + await _previous_build_apply(repo, org, ns, "c" * 40, monkeypatch) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + 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="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( + 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 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) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + await _failed_retry(repo, org, ns, monkeypatch) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + await _previous_build_apply(repo, org, ns, "c" * 40, monkeypatch) + assert await _read(repo, org, ns) == ({BAD}, {BAD}, False) + + +@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 + 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) + + 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, "", Unmasked(b"") + + 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, Unmasked]: + return 0, "", Unmasked(b"") # 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), + ) + # The pass moves the checkout through the compiler tier's own `git`, which this + # checkout (a temporary directory, not a repository) cannot run. + monkeypatch.setattr(delta_worker, "move_checkout", 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) + + +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) + + +@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 "") + + +@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 + + +@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) == 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() + + # 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() + + +PY_BAD = "src/bad.py" +PY_OTHER = "src/other.py" + + +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) + + 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") + 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: + 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`, 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) + 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} + + +@pytest.mark.asyncio +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 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) + 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} diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 3f66e6664c7..92f2b3b9b10 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 diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index d95269d1501..9c17416d4cf 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -353,6 +353,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_callers_member_fold.py b/tests/unit/test_code_callers_member_fold.py index 1a371cf37ca..9e3195e6e5e 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_sample(self, org, ns, tier=None, *, limit=3): + 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_coverage_tiers.py b/tests/unit/test_code_coverage_tiers.py index d0ef12a178b..e271cd0dffd 100644 --- a/tests/unit/test_code_coverage_tiers.py +++ b/tests/unit/test_code_coverage_tiers.py @@ -908,6 +908,9 @@ async def edges_for_symbols(self, *a, **k): async def call_guards_for_callers(self, *a, **k): return {} + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): + return set() + def __getattr__(self, name): async def _none(*a, **k): return [] if name != "class_of_method" else None diff --git a/tests/unit/test_code_ctor_call_edges.py b/tests/unit/test_code_ctor_call_edges.py index 8e9ecf07106..c5d205ef6f3 100644 --- a/tests/unit/test_code_ctor_call_edges.py +++ b/tests/unit/test_code_ctor_call_edges.py @@ -351,12 +351,12 @@ 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, "_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, 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 == [] @@ -582,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) @@ -604,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_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 return {k: {"value": v, "detail": "", "updated_at": None} for k, v in self._state.items()} @@ -684,6 +691,54 @@ 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" + # 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: + 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, 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 + + 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 diff --git a/tests/unit/test_code_ctor_edges_remainder.py b/tests/unit/test_code_ctor_edges_remainder.py index d97c0c44871..38c9a977dd7 100644 --- a/tests/unit/test_code_ctor_edges_remainder.py +++ b/tests/unit/test_code_ctor_edges_remainder.py @@ -496,12 +496,12 @@ 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, "_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 bb2b377424e..0c4fa8873f5 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 @@ -362,12 +365,12 @@ 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) 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 not _delta_is_open(path) @@ -394,7 +397,7 @@ def slow(text: str, index: int) -> Any: return real(text, index) monkeypatch.setattr(delta_file, "_entry", slow) - 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): @@ -677,3 +680,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_epistemic_envelope.py b/tests/unit/test_code_epistemic_envelope.py index 1fe70d1e574..0c53046eb48 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_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 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..f9b87df9a6d 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_sample(self, org, ns, tier=None, *, limit=3): + 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_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): 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_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", } 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_repos_batched_state.py b/tests/unit/test_code_repos_batched_state.py index 09382adef06..a5dbdc0031a 100644 --- a/tests/unit/test_code_repos_batched_state.py +++ b/tests/unit/test_code_repos_batched_state.py @@ -67,7 +67,12 @@ 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:", + # 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||" assert out[("o", "b")] == {"git_head": {"value": "bbb", "detail": "", "updated_at": "t"}} diff --git a/tests/unit/test_code_scip_go_delta_paths.py b/tests/unit/test_code_scip_go_delta_paths.py index 4a7b7724658..98cb23c29d5 100644 --- a/tests/unit/test_code_scip_go_delta_paths.py +++ b/tests/unit/test_code_scip_go_delta_paths.py @@ -7,6 +7,7 @@ from __future__ import annotations import asyncio +import os import subprocess from pathlib import Path @@ -57,6 +58,23 @@ def test_module_dirs_name_every_go_mod_verbatim(checkout: tuple[Path, str, str]) assert asyncio.run(w._module_dirs(co)) == ["", "svc/api", "svc/café", "tools/my tool"] +def test_a_failed_non_utf8_module_dir_is_spelled_as_the_worker_lists_it( + checkout: tuple[Path, str, str], +) -> None: + """The retry map keeps only keys the worker's own module listing spells, so the dir + a failure line names must be spelled the same way for a directory that is not UTF-8.""" + from server.code.domain.index.tier_health import failed_dir + + co, _base, _head = checkout + odd = co / os.fsdecode(b"svc/n\xff") + odd.mkdir(parents=True) + (odd / "go.mod").write_text("module m\n") + _git(co, "add", "-A") + _git(co, "commit", "-q", "-m", "odd") + named = failed_dir("svc/n%FF: go mod download failed: x") + assert named in asyncio.run(w._module_dirs(co)) + + def test_the_window_names_its_changed_paths_verbatim(checkout: tuple[Path, str, str]) -> None: co, base, head = checkout changed = asyncio.run(w._changed_paths(co, base, head)) diff --git a/tests/unit/test_code_scip_go_delta_worker.py b/tests/unit/test_code_scip_go_delta_worker.py index 21cd8892df7..b7ab04c19af 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 @@ -155,7 +156,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 @@ -264,7 +265,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return Unmasked(b"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) @@ -299,16 +300,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): @@ -778,7 +783,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return Unmasked("".join(f"done {m}\n" for m in modules).encode()) - 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) @@ -834,7 +839,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return Unmasked("".join(f"done {m}\n" for m in modules).encode()) - 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) @@ -906,7 +911,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): log += _WINDOW_LOGS[window] if m == "lib" else "done svc\n" return Unmasked(log.encode()) - 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) @@ -1072,7 +1077,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): log += line return Unmasked(log.encode()) - 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) @@ -1188,7 +1193,7 @@ async def fake_harness(co, base, head, out_dir, modules, cfg): ) return Unmasked((log[0] if "lib" in modules else "done svc\n").encode()) - 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) @@ -1376,3 +1381,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 new file mode 100644 index 00000000000..b9919f0e056 --- /dev/null +++ b/tests/unit/test_code_scip_mark_retirement.py @@ -0,0 +1,506 @@ +"""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 json +from types import SimpleNamespace +from typing import Any + +import pytest + +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 +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"), +) + + +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 + + 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} + + 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 _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 + + monkeypatch.setattr(scip_delta, "_mark_stale", no_marks) + + +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) + + +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 _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": key, + "state_value": value, + "detail": "", + "version": version, + } + + +# ---------------------------------------------------------------- red-then-green +# (a) a doc-only apply retires its mark + + +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] + + 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}") == "" + + +# (b) an apply that leaves the edge set unchanged retires + + +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 + + assert await _retire(repo) == {PATH} + assert await repo.get_state(ORG, NS, f"scip_applied:clang:{PATH}") == "" + + +# (c) a file whose edges are all tombstoned is not held + + +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} + + +# (d) a superseded version does not answer + + +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, + } + ], + ) + 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, + } + ], + ) + + assert await _retire(repo) == set() + 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 + + +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, + ), + ), + ) + + 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", + }, + ) + 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), + ), + ) + + assert await _retire(repo, tier="go", watermark="scip_commit_go") == {"mod_b/y.go"} + + +# 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"} + ) + 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) + + with monkeypatch.context() as failing: + failing.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", + ) + + 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} + + +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 + ) + + def row(rows: list[dict[str, Any]]) -> dict[str, Any]: + assert len(rows) == 1, rows + return rows[0] + + 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}") == "" diff --git a/tests/unit/test_code_scip_py_delta_worker.py b/tests/unit/test_code_scip_py_delta_worker.py index 24bd79e6a4a..e062da03241 100644 --- a/tests/unit/test_code_scip_py_delta_worker.py +++ b/tests/unit/test_code_scip_py_delta_worker.py @@ -124,7 +124,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 @@ -195,7 +195,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) @@ -250,7 +250,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 new file mode 100644 index 00000000000..cf1da542b88 --- /dev/null +++ b/tests/unit/test_code_scip_skipped_documents.py @@ -0,0 +1,328 @@ +"""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 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 asyncio +import logging +import os +import subprocess +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from server.code.app.index import compiler_tier, sandbox, scip_delta +from server.code.app.index.output_mask import Unmasked +from server.code.app.index.scip_delta import ScipDelta, ScipFile + + +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): + 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, Unmasked]: + 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_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.""" + 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): + rc, text, printed = await _harness(tmp_path) + # the masked text is what the caller logs; the printed form is opaque by design + assert (rc, text) == (0, out) + assert isinstance(printed, Unmasked) + 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 +@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_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, 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( + 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"} + delta = ScipDelta( + commit="c" * 40, + files=[ScipFile(path="src/a.cpp")], + deleted_files=["src/gone.cpp"], + skipped_files=["src/bad.cpp", "src/k.cu", "contrib/x.cpp", "src/conf.env.h"], + ) + 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_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": "", + "scip_applied:clang:src/a.cpp": "", + "scip_applied:clang:src/gone.cpp": "", + }, + ) + + +@pytest.mark.asyncio +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. 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", "src/gone.cpp"} + delta = ScipDelta( + commit="c" * 40, + files=[ScipFile(path="src/both.cpp"), ScipFile(path="src/b.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", "src/gone.cpp"] + repo.set_states.assert_awaited_once_with( + "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": "", + "scip_applied:clang:src/b.cpp": "", + "scip_applied:clang:src/gone.cpp": "", + }, + ) + + +@pytest.mark.asyncio +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 = {"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, + } + + +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_delta, "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 + + assert [tier_for(p) for p in ("scip_harness@ci", "scip-python", "scip-typescript", "go")] == [ + "clang", + "python", + "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_code_scip_stale_field_bound.py b/tests/unit/test_code_scip_stale_field_bound.py new file mode 100644 index 00000000000..f6e7ae34c41 --- /dev/null +++ b/tests/unit/test_code_scip_stale_field_bound.py @@ -0,0 +1,175 @@ +"""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) + + +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_code_scip_ts_delta_worker.py b/tests/unit/test_code_scip_ts_delta_worker.py index 0a6e9cc294a..faa12061178 100644 --- a/tests/unit/test_code_scip_ts_delta_worker.py +++ b/tests/unit/test_code_scip_ts_delta_worker.py @@ -149,7 +149,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 @@ -268,6 +268,56 @@ async def test_dependency_failure_does_not_run_indexer_or_advance_watermark(monk 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 under the + TypeScript tier; 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, **_: Any): + 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_states.assert_awaited_once_with( + "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) + + def test_harness_env_passes_only_the_named_variables(monkeypatch, tmp_path: Path): monkeypatch.setenv("NPM_TOKEN", "t0k") monkeypatch.setenv("OTHER_TOKEN", "nope") 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..439d458a9d7 --- /dev/null +++ b/tests/unit/test_code_stale_marks_bounded.py @@ -0,0 +1,76 @@ +"""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 +from server.code.store.index.symbols import STALE_SAMPLE, STALE_SHOWN + +_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"] <= STALE_SAMPLE + + +@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) + # 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 + + +@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 new file mode 100644 index 00000000000..03f9bd1b154 --- /dev/null +++ b/tests/unit/test_code_stale_marks_note.py @@ -0,0 +1,76 @@ +"""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_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 + + +_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("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("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") + + +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 diff --git a/tests/unit/test_code_symbol_uses_context.py b/tests/unit/test_code_symbol_uses_context.py index 4b90bbf5d52..1bdc7fe553e 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_sample(self, org, ns, tier=None, *, limit=3): + 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 2ecc9859431..e098fab6b1b 100644 --- a/tests/unit/test_code_test_gate.py +++ b/tests/unit/test_code_test_gate.py @@ -591,6 +591,9 @@ def _edge(frm: str, to: str, fq: str, path: str, kind: str = "calls") -> dict[st class _Repo: + async def scip_stale_sample(self, org, ns, tier=None, *, limit=3): + return set(getattr(self, "marks", set())) + def __init__(self) -> None: self.symbols = [ _sym("sA", "DB::A::f", "src/A.cpp", 10, 20), @@ -1053,6 +1056,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"]) diff --git a/tests/unit/test_code_tier_health.py b/tests/unit/test_code_tier_health.py index 07d1c9101b8..7932694e489 100644 --- a/tests/unit/test_code_tier_health.py +++ b/tests/unit/test_code_tier_health.py @@ -837,7 +837,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() 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_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_run_go_monorepo_delta_modules.py b/tests/unit/test_run_go_monorepo_delta_modules.py new file mode 100644 index 00000000000..6bc485145c7 --- /dev/null +++ b/tests/unit/test_run_go_monorepo_delta_modules.py @@ -0,0 +1,188 @@ +"""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 + +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 +""" + +_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, + errors="surrogateescape", + ) + 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] + + +# Every shape a directory can take against the failure line's own framing: a line break, +# the escape character, the text the worker splits the line at, a name the retry +# classifier reads, and a byte that is not UTF-8. +_FAILING_DIRS = [ + "svc/e\n", + "svc/b\\n", + "svc/c\r\\", + "services/a: scip-go failed/b", + "svc/d: go mod download failed", + "svc/h: 410 gone", + 'svc/q"uote', + "svc/sp ace", + "svc/p%41", + os.fsdecode(b"svc/n\xff"), +] + + +@pytest.mark.parametrize("weird", _FAILING_DIRS) +def test_a_failed_module_directory_is_named_whole(tmp_path: Path, weird: str) -> None: + """The failure line names the module's directory whatever bytes it holds: the worker + reads it back to record the failure and keep the retry, and a name cut anywhere is + none of the run's modules, so the watermark would advance past it. The directory is + written as a token that cannot hold the line's own delimiter or a line break.""" + repo = _repo(tmp_path, ["svc/api", weird]) + proc, _ = _run(tmp_path, repo, {"GO_FAILS_AT": weird.split("/", 1)[1]}) + assert proc.returncode == 0, proc.stderr + printed = Unmasked(os.fsencode(proc.stdout + proc.stderr)) + broken, unreachable = printed.module_dirs() + # spelled as the worker lists modules (UTF-8, `replace`): the retry map's key + spelled = os.fsencode(weird).decode("utf-8", "replace") + assert (broken, unreachable) == ([spelled], []) + shown_broken, shown_unreachable = printed.module_failures() + assert len(shown_broken) == 1 and not shown_unreachable + assert "connection refused" in shown_broken[0] + + +def test_a_directory_cannot_forge_a_failure_line_in_the_other_lines(tmp_path: Path) -> None: + """A module that built is named in `done `: a directory holding a line break and + a failure line must not read as a second module's failure.""" + weird = "svc/g\nskip bad: scip-go failed: forged" + repo = _repo(tmp_path, ["svc/api", weird]) + proc, _ = _run(tmp_path, repo) + assert proc.returncode == 0, proc.stderr + printed = Unmasked(os.fsencode(proc.stdout + proc.stderr)) + assert printed.module_failures() == ([], []) + assert printed.module_dirs() == ([], []) diff --git a/tests/unit/test_run_typescript_delta_umbrella.py b/tests/unit/test_run_typescript_delta_umbrella.py index 0eb37a48dbd..6b33a1bf9d0 100644 --- a/tests/unit/test_run_typescript_delta_umbrella.py +++ b/tests/unit/test_run_typescript_delta_umbrella.py @@ -32,6 +32,10 @@ [[ -f "$c" ]] && printf '%s\\t%s\\n' "$c" "$(tr -d '\\n' <"$c")" >>"$CALLS.tsconfig" done fi + if [[ -n "${FAIL_TARGET:-}" && "$a" == "$FAIL_TARGET" ]]; then + echo "error TS5023: Unknown compiler option" >&2 + exit "${FAIL_RC:-1}" + fi done while [[ $# -gt 0 ]]; do [[ "$1" == "--output" ]] && : >"$2"; shift; done """ @@ -40,12 +44,27 @@ # Forward discover/filter/merge/paths to the real helpers; stub only the converter. case "${1-}" in *scip_ts_projects.py|*scip_merge_indexes.py|*scip_ts_paths.py) exec "$REAL_PYTHON" "$@" ;; + *scip_to_delta.py) [[ -n "${REAL_CONVERT:-}" ]] && exec "$REAL_PYTHON" "$@" ;; esac { printf 'convert' 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 + 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//$'\\n'/\\\\n}" >>"$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 [[ "$1" == "--dry-run" ]] && echo '{}' >"$2" [[ "$1" == "--index" && -n "${MERGED-}" ]] && cp "$2" "$MERGED" @@ -148,9 +167,25 @@ def _run( repo: Path, base: str, head: str, - scip: str = _FAKE_SCIP, extra_env: dict[str, str] | None = None, + scip: str = _FAKE_SCIP, ) -> str: + proc, log = _run_status(tmp_path, repo, base, head, extra_env, scip=scip) + if proc.returncode != 0: + raise subprocess.CalledProcessError( + proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr + ) + return log + + +def _run_status( + tmp_path: Path, + repo: Path, + base: str, + head: str, + extra_env: dict[str, str] | None = None, + scip: str = _FAKE_SCIP, +) -> tuple[subprocess.CompletedProcess[str], str]: bin_dir = tmp_path / "bin" bin_dir.mkdir(exist_ok=True) calls = tmp_path / "calls" @@ -174,15 +209,17 @@ def _run( } # Don't leak a parent SCIP_TS_PROJECTS into the test. env.pop("SCIP_TS_PROJECTS", None) + env.pop("SCIP_STOP_ON_FAILED_DOCUMENT", None) env.pop("SCIP_TS_PATHS", None) - subprocess.run( + 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]]: @@ -272,6 +309,151 @@ 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_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.""" + 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", "packages/lib/src/c.ts"] + 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 real window filter and the real converter both read it, the + healthy member's delta still converts, and the name is kept under its `replace` key, + the one the store holds.""" + 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", + "packages/lib/src/caf\ufffd.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 + 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) + 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') @@ -400,6 +582,122 @@ 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_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. @@ -982,6 +1280,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: @@ -999,3 +1366,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_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 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_ctor_scan_window.py b/tests/unit/test_scip_ctor_scan_window.py new file mode 100644 index 00000000000..6af070bd735 --- /dev/null +++ b/tests/unit/test_scip_ctor_scan_window.py @@ -0,0 +1,47 @@ +"""A full C++ run claims `ctor_calls` only when its constructor scan read every document +of the index. The harness passes `--changed-files` with `--full`, so a document the scan +cannot read can sit outside the files the delta lists; nothing is then listed as skipped, +and the claim must still be withheld (the scan-completeness check is the converter's, +`_Run.ctors_complete`).""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +from tests.unit.test_scip_to_delta_cli import _CONVERTER +from tests.unit.test_scip_to_delta_skip import _overload_index + + +def _features(tmp_path: Path, *, bad: bool) -> tuple[list[str], dict]: + """The `--full` run over src/ok.cpp only, as the harness invokes the converter.""" + index, root = _overload_index(tmp_path, bad=bad) + window = tmp_path / "changed.txt" + window.write_text("src/ok.cpp\n") + out = tmp_path / ("bad.json" if bad else "good.json") + cmd = [sys.executable, str(_CONVERTER), "--index", str(index), "--commit", "h" * 40] + cmd += ["--source-root", str(root), "--full", "--changed-files", str(window)] + cmd += ["--dry-run", str(out)] + proc = subprocess.run(cmd, capture_output=True, text=True, check=False) + assert proc.returncode == 0, proc.stderr + delta = json.loads(out.read_text()) + return delta.get("features", []), delta + + +def test_an_undecodable_header_outside_the_window_withholds_the_ctor_claim( + tmp_path: Path, +) -> None: + """src/foo.h, which holds Foo's constructor, fails to decode and the window holds + only src/ok.cpp: the delta lists no skipped file, yet the scan behind the claim + missed a document, so there is no `ctor_calls`.""" + features, delta = _features(tmp_path, bad=True) + assert [f["path"] for f in delta["files"]] == ["src/ok.cpp"] + assert delta["skipped_files"] == [] + assert features == [] + + +def test_the_same_window_over_a_whole_index_claims_ctor_calls(tmp_path: Path) -> None: + features, _ = _features(tmp_path, bad=False) + assert features == ["ctor_calls"] diff --git a/tests/unit/test_scip_entry_lock.py b/tests/unit/test_scip_entry_lock.py index aeb093e4ac0..5f31334f592 100644 --- a/tests/unit/test_scip_entry_lock.py +++ b/tests/unit/test_scip_entry_lock.py @@ -574,6 +574,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 @@ -600,7 +603,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 @@ -615,7 +618,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_gone_at_bytes.py b/tests/unit/test_scip_gone_at_bytes.py new file mode 100644 index 00000000000..4bf68852054 --- /dev/null +++ b/tests/unit/test_scip_gone_at_bytes.py @@ -0,0 +1,220 @@ +"""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 — 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 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" +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"), + clickhouse_local.ddl("code_index_state"), + clickhouse_local.ddl("code_symbols"), + clickhouse_local.ddl("code_edges"), +) + + +def _git(work: Path, *args: str) -> str: + done = subprocess.run( + ["git", "-C", str(work), *args], check=True, capture_output=True, text=True + ) + return done.stdout.strip() + + +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 _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 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) + (work / OTHER).write_text("int y;\n") + (work / LATE).write_text("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.""" + assert KEY == RAW.decode("utf-8", "replace") + work = _mirror(tmp_path) + _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} + + (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} + + _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() + + +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} + + (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() + + 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) + (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} + + (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_harness_windows.py b/tests/unit/test_scip_harness_windows.py index c0a9b9fe652..12d5603fa76 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) @@ -498,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_merge_indexes.py b/tests/unit/test_scip_merge_indexes.py index a28a229e618..d1cc1a385c4 100644 --- a/tests/unit/test_scip_merge_indexes.py +++ b/tests/unit/test_scip_merge_indexes.py @@ -332,6 +332,93 @@ def test_merge_prefers_a_one_character_member_over_a_root_tsconfig(tmp_path: Pat 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"] + + +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" + # 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 [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( + 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", "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"] + + +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_a_path_a_sibling_indexed_is_not_failed_in_any_spelling(tmp_path: Path) -> None: + """A path is one key: its raw bytes, on the merge's side and the candidate list's. A + sibling indexed `src/caf<0xff>.ts`, whose name is not UTF-8; the failed sibling does + not list it. Three paths nobody indexed stay failed: one that differs by another + malformed byte, one holding a literal U+FFFD (both decode, under `replace`, to the + indexed path's text), and a plain one.""" + part = tmp_path / "part.scip" + part.write_bytes(_record(2, _record(1, b"src/caf\xff.ts"))) + candidates = tmp_path / "candidates.txt" + candidates.write_bytes( + b"src/caf\xff.ts\0src/caf\xfe.ts\0" + "src/caf\ufffd.ts".encode() + b"\0src/main.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().split(b"\0") if p] == [ + b"src/caf\xfe.ts", + "src/caf\ufffd.ts".encode(), + b"src/main.ts", + ] + + 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.""" @@ -711,17 +798,16 @@ def test_the_converter_and_merge_read_repeated_metadata_as_the_parser_does( 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.""" +def test_merge_returns_the_kept_paths_as_raw_bytes(tmp_path: Path) -> None: + """The merge keys its documents on raw bytes and returns that key, so a caller + compares a path in one spelling: a stray 0xff byte stays 0xff.""" 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) + assert kept == {b"pkg/a.ts", b"pkg/b\xff.ts"} def test_merge_does_not_truncate_an_input_named_like_the_temporary(tmp_path: Path) -> None: diff --git a/tests/unit/test_scip_path_encoding.py b/tests/unit/test_scip_path_encoding.py new file mode 100644 index 00000000000..7f6080ccbf3 --- /dev/null +++ b/tests/unit/test_scip_path_encoding.py @@ -0,0 +1,366 @@ +"""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 json +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" +_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") +# 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: + 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, "-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), built in the + index: no name in these tests ever reaches the filesystem.""" + repo = tmp_path / "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: + """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]: + 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 _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 + 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] + + +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() + + +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 + b"/a.ts"} 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_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 new file mode 100644 index 00000000000..79551f5d87f --- /dev/null +++ b/tests/unit/test_scip_to_delta_skip.py @@ -0,0 +1,608 @@ +"""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, + _FACTORY_SRC, + _add_doc, + _factory_index, + _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 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 + + +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_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_full_run_names_a_document_whose_path_is_not_utf8_by_its_replace_key( + tmp_path: Path, +) -> None: + """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() + + +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 + + +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_failed_file_whose_name_is_not_utf8_keeps_its_replace_key(tmp_path: Path) -> None: + """The merge writes git's raw bytes for such a name. It decodes with `replace`, the + key the store holds, so the one file is marked under the name the store knows; the + other failed files are listed too.""" + 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", "pkg/caf\ufffd.ts"] + + +def test_a_changed_or_deleted_name_that_is_not_utf8_keeps_its_replace_key( + tmp_path: Path, +) -> None: + """The harness writes git's raw bytes into `--changed-files` and `--deleted-files` + too. A name decodes with `replace`, the key the store holds, so a deleted one names + the row to drop instead of being dropped as a name. 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", "src/old\ufffd.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.""" + 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 _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.""" + 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.""" + 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 + 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 + + +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 + + +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"] + + +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, "") diff --git a/tests/unit/test_scip_ts_kind_prepass.py b/tests/unit/test_scip_ts_kind_prepass.py index 6981652e846..363f15916d7 100644 --- a/tests/unit/test_scip_ts_kind_prepass.py +++ b/tests/unit/test_scip_ts_kind_prepass.py @@ -199,12 +199,17 @@ 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 _applied(delta: dict[str, Any], kinds: dict[str, str]) -> tuple[_Repo, sd.ScipApplyStats]: repo = _Repo(kinds) with patch("server.code.domain.index.repos.repo_for_namespace", return_value=_Cfg()): stats = asyncio.run( - sd.apply_delta(repo, "o", "n", sd.ScipDelta.model_validate(delta)) # type: ignore[arg-type] + sd.apply_delta( # type: ignore[arg-type] + repo, "o", "n", sd.ScipDelta.model_validate(delta), tier="typescript" + ) ) return repo, stats diff --git a/tests/unit/test_scip_ts_merge_to_converter.py b/tests/unit/test_scip_ts_merge_to_converter.py new file mode 100644 index 00000000000..2bf30aeb831 --- /dev/null +++ b/tests/unit/test_scip_ts_merge_to_converter.py @@ -0,0 +1,43 @@ +"""A TypeScript member index with a document the protobuf parser refuses goes through +the member merge and then the converter: the merge copies the document, the converter +skips it and lists it, and the rest of the run converts (run_typescript_delta.sh runs +the two in this order for a member that indexed).""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +from tests.unit.test_scip_to_delta_skip import _MARK, _converter, _ts_index_with_undecodable_b + +_MERGE = Path(__file__).resolve().parents[2] / "scripts" / "scip_harness" / "scip_merge_indexes.py" + + +def _merge_module(): + spec = importlib.util.spec_from_file_location("scip_merge_indexes_to_converter", _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 test_a_document_the_parser_refuses_survives_the_member_merge_and_is_skipped_by_the_converter( + tmp_path: Path, +) -> None: + """pkg/b's document holds one string that is not UTF-8. The merge keeps it, so the + converter can skip it by name and keep the rows of pkg/a/a.ts, which calls into it; + a merge that parsed the part would raise `DecodeError` before the converter ran.""" + part, root = _ts_index_with_undecodable_b(tmp_path) + merged = tmp_path / "merged.scip" + _merge_module().merge_indexes([part], merged, projects=["pkg"], known_projects=["pkg"]) + assert b"\xff\xfe" + _MARK[2:] in merged.read_bytes() + delta = _converter().convert( + str(merged), + {"pkg/a/a.ts", "pkg/b/b.ts"}, + [], + "h" * 40, + "b" * 40, + source_root=str(root), + ) + assert delta["files"] == [] + assert delta["skipped_files"] == ["pkg/a/a.ts", "pkg/b/b.ts"] diff --git a/tests/unit/test_scip_ts_projects.py b/tests/unit/test_scip_ts_projects.py index 134c4a4662c..7e7132ba744 100644 --- a/tests/unit/test_scip_ts_projects.py +++ b/tests/unit/test_scip_ts_projects.py @@ -230,7 +230,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"} @@ -250,8 +250,9 @@ 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" - changed.write_bytes(b"caf\xe9.md\npackage.json\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"] rc = subprocess.run([*argv, os.fsencode(changed)], env=env, capture_output=True) @@ -352,15 +353,44 @@ 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", - "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"] @@ -369,15 +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"} - 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 ("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 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