Repository navigation
fix(tests): keep the test suite and the developer's environment apart - #3758
Conversation
|
Needs a rebase before merging: a new integration test is landing that this branch's guard will reject. #3519 is approved and adds So the rebase needs to convert that file to Second one to fold in while rebasing: #3781 adds Neither is a change to the approach here, just coverage that moved while this was open. |
e12bb5d to
2104ef7
Compare
16d7f14 to
15af639
Compare
b2068b5 to
3fa3ad4
Compare
3fa3ad4 to
99bfe04
Compare
99bfe04 to
e6e066c
Compare
|
Reviewed this on Windows 11 ( It worksMethod: PR head (e6e066c) vs its own parent (5e0f92c), counting rows in the real
The base rows are the fixtures, unmistakable: 3678 passed / 3 failed (the base run: 3676 / 3 — the +2 are this PR’s own guard tests), the 3 being the Windows-only failures that reproduce identically on pristine 1. Windows CI is red, and it is a class rather than a single error
I reproduced that byte-for-byte locally. Cause: the PR moves the other four tests in that file onto Fixing only that uncovers the next one, which is the more general shape: Of the 20 integration targets that now carry Two edits made the whole suite compile here: // tests/read_window_bytes_test.rs
use std::process::{Output, Stdio};
#[cfg(unix)]
use std::process::Command;// tests/common/mod.rs — each integration target compiles this separately
// and uses only the part it needs.
#![allow(dead_code)]The numbers above are from a tree with exactly those two edits applied and nothing else. 2. One call site the sweep missed — and it deletes
// src/core/telemetry_cmd.rs:220
let db_path = dirs::data_local_dir()
.unwrap_or_else(|| std::path::PathBuf::from("."))
.join(super::constants::RTK_DATA_DIR)
.join(super::constants::HISTORY_DB);
if db_path.exists() {
match std::fs::remove_file(&db_path) { ... }
}Every sibling got converted — Since the guard test is already a source scan, it could cover this shape cheaply: reject 3. On Windows the scratch directories are never reclaimed
Not a blocker for what the PR sets out to do — just the last thing standing between this and "the suite leaves nothing behind". Also worth noting Happy to re-run any of this, or to push the two compile fixes as a PR against your branch if that is easier than carrying them here. |
e6e066c to
11d9684
Compare
|
Thank you @bharvey42! The 1. Windows CI. Fixed as you described, and your framing as a class rather than a single error is what made it worth fixing properly: // tests/read_window_bytes_test.rs
use std::process::{Output, Stdio};
#[cfg(unix)]
use std::process::Command;
I also set up a cross-check so this class stops reaching CI: 2. Worth being precise about scope, since the two overlap but are not the same: this makes 3. Windows scratch directories. Recorded on #3874 with your measurement, rather than guessed at here. Your 2 → 11 figure is the useful part: the doc comment says the behaviour is known, but not that it accrues per test binary per run. I sketched a shape there — sweep sibling semgrep. Two findings, both mine: The branch is rebased onto current On the offer to push a PR against the branch: genuinely appreciated, and no need this time since the fixes are small and now in. If you would rather review the Windows-side work as its own change in future, that suits me fine too — you have the machine and I do not, and that has been the binding constraint on this PR throughout. |
11d9684 to
18709cd
Compare
aeppling
left a comment
There was a problem hiding this comment.
Two residual write paths the isolation misses. Both predate this branch; requesting changes for #1 only, since it sits inside this PR's own verification claim and the fix is one line.
1. A fresh machine gets ~/.config/rtk/filters.toml created by cargo test.
test_global_default_mode_creates_artifacts runs run_default_mode in-process, which calls generate_global_filters_template. That writes through raw dirs::config_dir(), and with_claude_dir_override only overrides CLAUDE_CONFIG_DIR, so the template lands in the real config dir. The writer skips when the file exists, which is why any machine that has run rtk init (including the ones this PR was verified on) measures clean. This is the same class as the .device_salt minting fixed here, and it contradicts the verification claim that ~/.config/rtk is unchanged across a run.
Repro:
FH=$(mktemp -d)
HOME=$FH cargo test --bin rtk test_global_default_mode_creates_artifacts
find $FH -name filters.toml
Fix: pin HOME and XDG_CONFIG_HOME in with_claude_dir_override (its sibling with_missing_claude_dir_override already pins HOME). Extending the RESOLVERS scan to dirs::config_dir() would keep the class caught.
2. With RTK_HOOK_AUDIT=1 exported, hook tests write the real ~/.local/share/rtk/hook-audit.log.
run_antigravity_inner and run_gemini_inner_impl call audit_log inside the tested function, and audit_log_inner resolves via raw dirs::home_dir() plus a hardcoded .local/share/rtk, bypassing constants::data_dir(). Default runs are clean (verified: 0 writes without the var), so this is fine print rather than a defect, same category as the Windows gap on #3874. Fine as a follow-up.
Repro:
FH=$(mktemp -d)
HOME=$FH RTK_HOOK_AUDIT=1 cargo test --bin rtk hook_cmd::tests
wc -l $FH/.local/share/rtk/hook-audit.log # 34 lines
Everything the PR converts checks out on my side: fmt/clippy/test all green on the branch head, and a full cargo test --all with before/after inspection left the real DB, tee spool, salt, markers and trust store untouched.
18709cd to
3a13647
Compare
|
@aeppling thank you, both reproduced with your commands, and both are fixed on the new head (3a13647). 1. 2. Your two repros on 3a13647: no Following the same class in the other direction widened the PR. Tests also took their results from the contributor's machine: deny rules in Production behaviour is unchanged: every redirect is behind |
`cargo test` wrote into the contributor's own files (tracking database, tee spool, telemetry salt, agent hooks and settings) and took its results from their machine: agent settings, exported RTK_* and agent variables, git configuration and repository variables, files above TMPDIR. A test build now resolves every user location through `core::user_dirs` and reads the environment only through `core::user_env`, both answering from a per-process scratch directory and per-thread values a test sets. Spawned rtk children get the same redirect through the environment, and every git the suite runs is isolated from the developer's configuration and repositories. rtk-ai#3826's helpers move into `test_isolation`, so there is one `rtk_command`. Scans refuse a test that names the rtk binary outside the two constructors, and a direct `dirs::`, environment or working-directory read outside `user_dirs`/`user_env`. Production behaviour is unchanged; every redirect sits behind cfg(test). Co-Authored-By: Claude Opus 5.5 <[email protected]>
3a13647 to
e0d99ab
Compare
Resolves the test-import conflict in src/main.rs by keeping develop's test_isolation import and dropping clap::Parser, which this branch no longer needs. The help fuzz now spawns through common::rtk_command() rather than naming CARGO_BIN_EXE_rtk, so the child writes to the test's scratch data directory instead of the contributor's own. core::test_isolation fails the suite on a spawn that skips it (#3758), which is what turned the merged branch red.
Problem
cargo testand the contributor's machine do not stay apart, in either direction.The suite writes to the contributor's files. It inserts rows into
~/.local/share/rtk/history.db, whichrtk gainthen counts as real usage; fills the tee spool, rotated after every write, so a run evicts the raw output kept there for recovery; mints the telemetry.device_salton a machine that never ran rtk; and spends the once-a-day hook warning. Several rtk children writing one database concurrently corrupted a 35 MB one outright:after which
rtk gainand the tracking tests fail withdatabase disk image is malformeduntil it is repaired by hand (.recovercost 57 of 55828 rows). Global-init tests go further: they uninstall the contributor's legacy rtk hook from~/.claude/hooksand writeCLAUDE.md/RTK.mdinto an exportedCLAUDE_CONFIG_DIR.The suite takes its results from the contributor's machine. Deny rules in
~/.claude/settings.jsonor the checkout's.claude/settings.local.json, an exportedRTK_NO_TOML=1,RTK_TEE=0orCLAUDE_CONFIG_DIR, a~/.gitconfigthat signs commits or excludes files through its init template,GIT_DIR/GIT_INDEX_FILEexported by a git hook, aglobal.jsonor.ignoreaboveTMPDIR: each of these fails tests that pass elsewhere.Under all of them at once, with a French locale as well,
cargo test --all -- --include-ignoredon develop (77a0c68) fails 126 tests. It deletes the legacy hook script, its hash, the Cursor hook and the OpenCode plugin. It writesCLAUDE.mdandRTK.mdinto the exported Claude directory, 110 KB into the exported tracking database, the recall store, a tee log, an audit log, a telemetry salt and afilters.toml. It also stages a file into the repositoryGIT_DIRnames and installs a hook in it.Fix
A test build no longer reads the user's locations or environment, and every process the suite spawns is isolated the same way. Production behaviour is unchanged: every redirect sits behind
cfg(test).core::user_dirs— the one place that resolves a location. rtk's data and config directories and the home (throughdirs), the working directory, a project root found by walking up, relative project paths (CLAUDE.md,.rtk/filters.toml,composer.json), and path variables such asCLAUDE_CONFIG_DIR. In a test build every answer lies in the process's scratch directory:test_isolation::with_root, andwith_agent_dirfor the agent-init tests, which keeps the home apart from the agent's directory so code ignoring the variable is caught);test_isolation::enter, recorded per thread. The process's own working directory never moves, so tests that enter a directory run in parallel instead of queueing on a lock;.claude,global.json,Directory.Build.props) stopping at the scratch directory.core::user_env— the one reader of environment variables. In a test build it answers only what the calling test set, per thread. An exportedRTK_NO_TOMLorCOMPOSER_BIN_DIRcannot change a result, and tests running in parallel cannot see each other's values.Git. rtk's own git commands in a test build, git spawned by tests, and rtk children all run git with no global or system configuration, no inherited
GIT_*variable, an empty init template, andGIT_CEILING_DIRECTORIESat the temporary directory.Process-wide caches that would hold whichever test's configuration was read first are loaded per call in a test build:
cached_config, the TOML registry's user and project filters, the Composer bin directories.Spawned children. A child is built without
cfg(test), so the environment is its only channel.test_isolation::rtk_commandand itstests/twincommon::rtk_commandclear every inheritedRTK_*variable and the agent, CI and Composer variables rtk reads. They point the child's data, config and home at the scratch root, start it in an empty project directory rather than the checkout, and isolate its git. The locale is left to each test, so a child's output and a native tool it is compared with share one.#3826's helpers now live in
test_isolation.test_support::rtk_commandspawnedtarget/debug/rtkwithout the data redirect, so the tests it served wrote to the contributor's data. There is now onertk_command, onetemp_git_repoand one git isolation, and.claude/rules/cli-testing.mdpoints at them.The scratch directory is a directory of its own, because rtk chmods its database's parent to 0700. It is held in a
staticand removed by anatexithandler. A run killed by a signal, or any non-Unix platform, leaves it in place.Scans keep it from drifting. Each asserts that the files it exempts were visited, so a run that cannot see the sources fails rather than passes.
CARGO_BIN_EXE_rtk,Command::new("rtk"), atarget/debugpath) outside the two constructors.dirs::, a direct environment read, or a working-directory read in non-test code outsideuser_dirs/user_env, with four exemptions that must each still match one read.Verification
The same hostile run as above, on this branch: 0 failures out of 4085, and the planted files, the exported database and the foreign repository are byte-identical afterwards.
cargo test --all -- --include-ignoredunder the hostile setupAlso on this commit:
cargo fmt --all --check,cargo clippy --all-targets(zero warnings), andcargo test --all -- --include-ignoredpass in a fresh checkout.TMPDIRinside a git repository.hooks:: core:: cmds::gitat 32 threads had no failures.cfg(windows)paths compile (cargo check --target x86_64-pc-windows-gnu --all-targets).--baseline-commit,--error) reports zero findings.The data-directory redirect was independently reproduced on Windows 11 by @bharvey42 in this review: 56 rows written by the base commit, 0 by the branch, with
.device_salt,.hook_warn_lastandtrusted_filters.jsonuntouched.Limits
TMPDIRunder the home, which is the Windows default, it can read settings above it.dirsresolves known folders through the shell API, so a child there is redirected only through the variables rtk reads itself (Windows: spawned rtk children cannot be redirected away from the real data dir (test isolation gap from #3758) #3874).rtk hook auditstill readsHOMEdirectly; moving it touser_dirs::homewould change where it looks on Windows, which is hook-audit log path uses Linux /tmp on Windows, doesn't honor XDG_DATA_HOME #1681.Related issues
.device_saltto the user's data dir #2106 — telemetry tests write a real.device_saltto the user's data dir — is fixed here:salt_file_path()resolves throughuser_dirs::data. Left without a closing keyword so the maintainer decides whether it closes on merge.🤖 Generated with Claude Code