Repository navigation
test(guards): fail when a source scan guards nothing - #3878
Conversation
The walks swallow read errors, so a missing scan root passed as a clean result; and the path allowlists are matched by string, so a rename leaves an exemption armed at the abandoned path for whatever file lands there next. Both walks now return the number of .rs files reached and each test asserts it is nonzero, and a new test pins that every allowlist entry still names a real file.
worktrunk-bot
left a comment
There was a problem hiding this comment.
Self-review. The mechanism is right, and allowlisted_paths_still_exist is the half with teeth — a path allowlist that stops matching anything is an armed exemption, not dead clutter. Two gaps, both of which I'm applying in a follow-up commit rather than leaving for a maintainer, since this PR is bot-authored.
version_build.rs has the identical hole and this PR doesn't cover it. vergen_env_vars_are_read_optionally walks src/ with the same let Ok(entries) = fs::read_dir(dir) else { return }; and then asserts violations.is_empty(), so a missing or relocated scan root passes it having read nothing — exactly the shape this PR pins. It matters more there than here: that guard is what stands between a bare env!("VERGEN_…") and another #3123, where cargo install worktrunk failed to compile off the crates.io archive. The other two source-scanning guards already carry floors — packaged_assets.rs's !assets.is_empty() and snapshot_formatting_guard.rs's seen > 500 — so as written this PR leaves version_build.rs as the only one without.
scanned > 0 is weaker than the precedent it follows. for_each_snapshot in snapshot_formatting_guard.rs asserts seen > 500 over its ~1200-file corpus for this same reason, under the same "would pass vacuously" comment. src/ holds 205 .rs files and the new docstring already says a real run "reaches hundreds of files", so a substantial floor is there for the taking — and it catches the partial walk the docstring itself names ("relocated src/"), which > 0 cannot: a workspace split that leaves a stub src/ behind clears zero while the guard inspects almost nothing.
Left alone deliberately, for a maintainer's call: four guard tests now hand-roll a near-identical recursive walk (output_system_guard, version_build, packaged_assets, and snapshot_formatting_guard's .snap variant), and this PR adds counting to two of them. A single counted walker in tests/common/ would make the floor structural instead of something each new guard has to remember — but it touches four files and is a separate concern from this one.
Verification of the follow-up commit
MIN_SCANNED_FILES = 100 in both files; src/ currently walks to 205, so the headroom is ~2x.
Injected fault — pointing the vergen scan at src-does-not-exist, which passed silently before:
thread '...::version_build::vergen_env_vars_are_read_optionally' panicked at tests/integration_tests/version_build.rs:46:5:
scanned only 0 .rs files under /home/runner/work/worktrunk/worktrunk/src-does-not-exist — the guard passed without inspecting the crate.
The walk swallows read errors, so this is a missing or unreadable scan root, not a clean result.
Unmodified tree:
test integration_tests::output_system_guard::allowlisted_paths_still_exist ... ok
test integration_tests::output_system_guard::check_no_unexpected_stdout_writes ... ok
test integration_tests::output_system_guard::check_stderr_macros_come_from_styling ... ok
test integration_tests::version_build::vergen_env_vars_are_read_optionally ... ok
Also clean: cargo fmt --check, cargo clippy --test integration --all-features.
The nightly-sweep change gave output_system_guard's two walks a
scanned-file floor, but left vergen_env_vars_are_read_optionally with the
identical hole: it walks src/ with the same read-error-swallowing recursion
and then asserts violations.is_empty(), so a missing or relocated scan root
passes it having read nothing. That guard is what stands between a bare
env!("VERGEN_…") and another #3123, and it was the last source-scanning
guard without a floor (packaged_assets and snapshot_formatting_guard both
already carry one).
Raise the floor itself from > 0 to MIN_SCANNED_FILES (100, against src/'s
205 .rs files), matching snapshot_formatting_guard's seen > 500. Zero only
catches a scan root that vanished outright; the docstring's other named
case — a relocated src/ — is partial, and a workspace split leaving a stub
behind clears > 0 while the guard inspects almost nothing.
|
Two changes here, and they're worth separating: Keep the allowlist test. Both lists are matched by path string, so a rename leaves a dead entry armed at the old path — and The floor is a different matter. The root cause it works around is that the walks discard the error: let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};Rather than measuring how much the walk reached, let that error surface: let entries = fs::read_dir(dir)
.unwrap_or_else(|e| panic!("scan root {} unreadable: {e}", dir.display()));One line per walk instead of a returned count threaded through three recursive functions, no
|
Replace the scanned-file floor with a panic at the point the walk discards the error, and extend the treatment to the two guards that carried a count-based floor of their own.
worktrunk-bot
left a comment
There was a problem hiding this comment.
Self-review of the two commits since the last round. The requested direction is applied: the floors are gone from all four guards, MIN_SCANNED_FILES with them, and each of the five walks surfaces its read_dir error instead. All 20 allowlist entries resolve today, src/remove_dir.rs included, so allowlisted_paths_still_exist is green on the current tree.
One residual, raised as a decision rather than pushed as a commit. The walks now surface the error at the directory level, but the same swallow sits one level down, inside the very functions this diff touches:
check_fileinoutput_system_guard.rs—match fs::read_to_string(path) { … Err(_) => return }, in both the stdout scan and the stderr scancheck_fileinversion_build.rs—let Ok(contents) = fs::read_to_string(path) else { return; };scan_fileinpackaged_assets.rs— the samelet Ok(…) elseform
A .rs file the walk reaches but can't read is skipped in silence, so the guard reports clean for content it never inspected. That is the shape the PR names, scoped to one file rather than the whole tree. visit_snap_files in snapshot_formatting_guard.rs already treats it as fatal (fs::read_to_string(&path).unwrap()), so as it stands the four guards now disagree about the file-level case while agreeing about the directory-level one. entries.flatten() is the same class again — it drops a mid-iteration DirEntry error in all five walks.
I stopped short of applying it because the last round's point was that this change should stay one line per walk, and pushing the treatment downward is a scope call worth making explicitly rather than assuming. If you want it, it's four one-line edits and I'll push them in a follow-up commit; if the file-level case is too remote to be worth the lines, the inconsistency with snapshot_formatting_guard.rs is the thing to settle, in whichever direction.
|
Applied in Net effect on the two commits you were reading: Verified by repointing each of the five scan roots at a nonexistent directory — all five now fail, all five passed silently before: Checks are green on that head, |
…violation (#3888) `check_stderr_macros_come_from_styling` tells a contributor to write `worktrunk::styling::eprintln!(…)`. That path resolves in the binary's modules and nowhere else, so pasted into a library module it produces code that cannot compile — and the guard can't catch that, because its scan only checks the call is prefixed with `styling::`, which both forms satisfy. The compiler is what fails, one CI round later. The messages now name both paths, from one `STYLING_PATH_BY_CRATE` const the stdout guard shares. `check_no_unexpected_stdout_writes` carried the same single-path instruction and gets the same treatment; the module docstring and the `STD_STDERR_ALLOWED_PATHS` doc follow. The `writing-user-outputs` skill is the other place the guidance lives, and it also named only `worktrunk::styling` — one paragraph there now states the split and that the guards accept either form, so the compiler is the only thing that tells you the path is wrong for the file. This came out of #3884, where the guard fired on `src/git/repository/mod.rs`, the fix was applied literally, and `test (linux)` and `test (macos)` both went red on it. <details><summary>Verification</summary> `src/lib.rs` declares `cache`, `command_log`, `config`, `copy`, `docs`, `git`, `path`, `priority`, `progress`, `remove_dir`, `shell`, `shell_exec`, `signal_forwarder`, `styling`, `sync`, `trace`, `utils`, `testing`. `src/main.rs` declares `cli`, `commands`, `completion`, `diagnostic`, `display`, `help`, `invocation`, `llm`, `log_files`, `logging`, `md_help`, `output`, `pager`, `summary`. Both trees are under `src/`, and both guards scan all of it. Each message was read by tripping its guard from a library module (a temporary `eprintln!`/`println!` in `src/priority.rs`, reverted): ``` stderr writes that resolve to std's macro instead of anstream's: src/priority.rs:250: eprintln!("probe"); std's `eprint!`/`eprintln!` keep ANSI escapes when stderr is redirected, so a file mixing them with anstream's emits color on some lines of a log and not others. Import the macro from `styling`, or qualify the call as `styling::eprintln!(…)`. Spell the path for the crate the file belongs to: `worktrunk::styling` in the binary's modules (the ones `src/main.rs` declares), `crate::styling` in the library's (the ones `src/lib.rs` declares). Or add the file to STD_STDERR_ALLOWED_PATHS with a comment explaining why std's macro is the right one there. ``` `cargo test --test integration -- output_system_guard` 5 passed, `cargo fmt --check` and `cargo clippy --tests --features shell-integration-tests` clean. #3878 also touches `tests/integration_tests/output_system_guard.rs` and is green and merge-ready, so this went to its own branch rather than folding in — the two edit different hunks and whichever merges second may want a trivial rebase. </details> Co-authored-by: worktrunk-bot <[email protected]>
…'t cover (#3911) #3878 changed each source-scan walk's `fs::read_dir` from a silent `return` into a panic, which is the right call — a directory the walk can't read contributed no violations, so an unreadable or relocated `src/` read as a clean crate. On the strength of that it also dropped two guards as duplicates of what the panic now gives. Neither is one: the panic catches a directory that can't be read, and both of them catch a walk that read everything and found nothing. **`packaged_assets.rs`** lost `assert!(!assets.is_empty())`. The other way discovery comes back empty is every file reading fine and the `include_str!` / `include_bytes!` / `#[template]` matching in `scan_file` recognizing none of them. Nothing downstream notices, because the comparison against `cargo package --list` and the `flake.nix` filter iterates `assets` — an empty set checks nothing and the test passes green while the guard standing between a bare `include_str!` and another #3123 has stopped guarding. **`snapshot_formatting_guard.rs`** lost `assert!(seen > 500)` from `for_each_snapshot`. That walk's roots are `src`, `tests` and `docs`, and all three exist, so the `read_dir` panic in `visit_snap_files` only fires when one of them can't be read. If the corpus moves out from under those roots while they still read fine, the walk succeeds, yields zero `.snap` files, and all three callers assert absence over nothing. The comment left in `visit_snap_files` claimed the panic covered exactly that case; it didn't, and now says which of the two failures each mechanism is for. The count is restored **per root** rather than in aggregate. `tests` holds 1,088 of today's 1,156 snapshots, so relocating just that root leaves 68 behind — a layout change moves one root and leaves the others, which is the realistic shape and the one an aggregate non-empty check survives. Counting inside the loop has no threshold in it and names the root that came back empty. That makes each root load-bearing, `docs` included at 4 files: a root that legitimately stops holding snapshots belongs out of the list rather than exempted from it. **Two swallows survived in both files.** `scan_file` still had `let Ok(contents) = fs::read_to_string(path) else { return };` — a subset of `src/*.rs` failing to read silently drops whatever those files embed while the rest keep `assets` non-empty, so the restored assert wouldn't have caught it. And both walks iterated `entries.flatten()`, which drops a per-entry `io::Error` (a file removed mid-walk, a failing `stat`), so the file it would have led to reached neither panic. Both now surface. `visit_snap_files` also read each snapshot with a bare `unwrap()` whose message named no file, leaving you to guess which of 1,156 it was; it names the path now, like the others. Each walk's two directory panics say which read failed. "This directory can't be read" and "this directory reads fine but one entry in it can't" would otherwise print the same line naming the same path, and the second is the one where the obvious next step — open the directory, find it fine — sends you back to the start. ## Test plan The 14 tests across the four guard files #3878 touched all pass. The corpus assert is a tripwire for a state the tree isn't in, so it was exercised directly, twice: <details><summary>Bug-back checks on the corpus assert</summary> **Whole corpus gone** — roots flipped from `["src", "tests", "docs"]` to `[".github"]`, which exists, reads fine, and holds no snapshots: ``` exit=101 count-assert fired: True read_dir panic fired instead: False ``` The `read_dir` panic *not* firing is the point: it confirms the two mechanisms cover different failures rather than one being a duplicate of the other. **One root relocated** — `tests` alone swapped for `.github`, leaving `src`'s 64 and `docs`' 4 in place: ``` exit=101 per-root assert fired and named the root: True .github/ holds no .snap files — the corpus has moved, so these assertions are now passing over whatever is left of it ``` 68 snapshots still walk here, so an aggregate non-empty check passes and this is the case it can't see. Both edits were reverted after the runs. </details> The panics on the read paths aren't exercised. A `.rs` file under `src/` that isn't readable UTF-8 wouldn't compile, so the crate never reaches the test; they're fail-fast for the reachable causes — a permissions change, a file removed mid-walk — rather than live guards. > _This was written by Claude Code on behalf of max-sixty_
Nightly sweep finding. The guard tests that scan
src/have two ways to pass while guarding nothing: their directory walks discard theread_direrror, andoutput_system_guard's two path allowlists are matched by string, so a rename leaves the exemption armed at the abandoned path. This lets the read error surface at every source-scanning walk, and adds a test that every allowlist entry still names a real file.The stale-allowlist half
STDOUT_ALLOWED_PATHSandSTD_STDERR_ALLOWED_PATHSexempt a path, and an entry exempts the whole file. When a file is renamed, nothing fails — the entry just stops matching anything. It stays armed, so a new file later occupying that path inherits a stdout permission nobody granted it, and the guard stays green while it writes.src/help.rsis the shape of the risk: a plausible name for a future refactor to reuse, currently exempt because--help-pageand--versionare genuinely the command's answer.git log --diff-filter=R -- src/shows renames are routine here, so this is a rot-prevention pin rather than a fix for present drift — all 20 entries resolve today. It converts the rename into a failing test at the moment it happens, while the reviewer still knows whether the exemption should move with the file or go.The vacuous-pass half
Every source-scanning guard walks with
Err(_) => return, so a missing or unreadable scan root produces zero violations and the test reports success having read nothing. Rather than measure how much of the tree the walk reached, the walk now lets the error out:That is one line per walk, and the failure names the actual io error instead of a file count. It covers all five walks, including the two that carried a count-based floor of their own and would otherwise have set the convention:
snapshot_formatting_guard.rs'sseen > 500andpackaged_assets.rs's!assets.is_empty()are both removed in favour of the same treatment.version_build.rsmatters most of the five: that guard is what stands between a bareenv!("VERGEN_…")and another #3123, wherecargo install worktrunkfailed to compile off the crates.io archive.Verification
Each of the five walks was confirmed to panic on an injected fault (its scan root repointed at a nonexistent directory) and to pass on the real tree.
Injected-fault runs
Each panics naming the directory and the error:
All five passed silently before this change. Unmodified tree:
Also clean:
cargo fmt --check,cargo clippy --test integration --all-features.