Skip to content

fix(tests): keep the test suite and the developer's environment apart - #3758

Merged
KuSh merged 1 commit into
rtk-ai:developfrom
KuSh:fix/test-db-isolation
Oct 1, 2026
Merged

KuSh merged 1 commit into
rtk-ai:developfrom
KuSh:fix/test-db-isolation

Conversation

@KuSh

@KuSh KuSh commented Aug 29, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

cargo test and 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, which rtk gain then 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_salt on 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:

$ sqlite3 ~/.local/share/rtk/history.db "PRAGMA integrity_check;"
*** in database main ***
Tree 2 page 8287 cell 449: 2nd reference to page 5617
wrong # of entries in index idx_pf_timestamp

after which rtk gain and the tracking tests fail with database disk image is malformed until it is repaired by hand (.recover cost 57 of 55828 rows). Global-init tests go further: they uninstall the contributor's legacy rtk hook from ~/.claude/hooks and write CLAUDE.md/RTK.md into an exported CLAUDE_CONFIG_DIR.

The suite takes its results from the contributor's machine. Deny rules in ~/.claude/settings.json or the checkout's .claude/settings.local.json, an exported RTK_NO_TOML=1, RTK_TEE=0 or CLAUDE_CONFIG_DIR, a ~/.gitconfig that signs commits or excludes files through its init template, GIT_DIR/GIT_INDEX_FILE exported by a git hook, a global.json or .ignore above TMPDIR: each of these fails tests that pass elsewhere.

Under all of them at once, with a French locale as well, cargo test --all -- --include-ignored on develop (77a0c68) fails 126 tests. It deletes the legacy hook script, its hash, the Cursor hook and the OpenCode plugin. It writes CLAUDE.md and RTK.md into the exported Claude directory, 110 KB into the exported tracking database, the recall store, a tee log, an audit log, a telemetry salt and a filters.toml. It also stages a file into the repository GIT_DIR names 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 (through dirs), the working directory, a project root found by walking up, relative project paths (CLAUDE.md, .rtk/filters.toml, composer.json), and path variables such as CLAUDE_CONFIG_DIR. In a test build every answer lies in the process's scratch directory:

  • under a root a test can make its own (test_isolation::with_root, and with_agent_dir for the agent-init tests, which keeps the home apart from the agent's directory so code ignoring the variable is caught);
  • in the directory the test entered with 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;
  • with upward searches (.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 exported RTK_NO_TOML or COMPOSER_BIN_DIR cannot 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, and GIT_CEILING_DIRECTORIES at 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_command and its tests/ twin common::rtk_command clear every inherited RTK_* 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_command spawned target/debug/rtk without the data redirect, so the tests it served wrote to the contributor's data. There is now one rtk_command, one temp_git_repo and one git isolation, and .claude/rules/cli-testing.md points 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 static and removed by an atexit handler. 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.

  • One refuses a test that names the rtk binary (CARGO_BIN_EXE_rtk, Command::new("rtk"), a target/debug path) outside the two constructors.
  • One refuses dirs::, a direct environment read, or a working-directory read in non-test code outside user_dirs/user_env, with four exemptions that must each still match one read.
  • One checks that every variable rtk reads is pinned or cleared for a child.

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-ignored under the hostile setup failed files written or deleted outside the scratch directory
develop (77a0c68) 126 12, plus the foreign repository's index and hooks
this branch 0 0

Also on this commit:

  • cargo fmt --all --check, cargo clippy --all-targets (zero warnings), and cargo test --all -- --include-ignored pass in a fresh checkout.
  • The suite passes with TMPDIR inside a git repository.
  • 40 runs of hooks:: core:: cmds::git at 32 threads had no failures.
  • The cfg(windows) paths compile (cargo check --target x86_64-pc-windows-gnu --all-targets).
  • semgrep with the CI invocation (--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_last and trusted_filters.json untouched.

Limits

Related issues

🤖 Generated with Claude Code

@KuSh

KuSh commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Needs a rebase before merging: a new integration test is landing that this branch's guard will reject.

#3519 is approved and adds tests/diff_byte_accuracy_test.rs, which spawns the binary via CARGO_BIN_EXE_rtk and does not set RTK_DB_PATH. Merging it into this branch locally and running the guard:

---- core::db_isolation_tests::tests_that_spawn_rtk_isolate_the_database stdout ----
these files spawn the rtk binary without setting RTK_DB_PATH, so the child writes to
the user's real ~/.local/share/rtk/history.db — ...
  tests/diff_byte_accuracy_test.rs

So the rebase needs to convert that file to common::rtk_command() alongside the eight it already covers, or the suite fails on first merge. Worth noting the guard did its job here — it caught the new file automatically, which is the whole point of scanning sources rather than listing them.

Second one to fold in while rebasing: #3781 adds tests/diff_exit_code_test.rs, which sets RTK_DB_PATH inline on the Command. The guard passes it, since it only requires the string to appear in the file, but it should use the shared helper too — otherwise the one convention this PR establishes has an exception in the same release.

Neither is a change to the approach here, just coverage that moved while this was open.

@KuSh
KuSh force-pushed the fix/test-db-isolation branch from e12bb5d to 2104ef7 Compare September 2, 2026 22:25
@KuSh KuSh changed the title fix(tracking): keep the test suite off the user's real database fix(tests): stop spawned rtk children writing to the real tracking database Sep 2, 2026
@KuSh
KuSh force-pushed the fix/test-db-isolation branch 7 times, most recently from 16d7f14 to 15af639 Compare September 4, 2026 07:35
@KuSh KuSh changed the title fix(tests): stop spawned rtk children writing to the real tracking database fix(tests): stop the test suite writing to the developer's own rtk data Sep 4, 2026
@KuSh
KuSh force-pushed the fix/test-db-isolation branch 7 times, most recently from b2068b5 to 3fa3ad4 Compare September 4, 2026 22:01
@KuSh
KuSh force-pushed the fix/test-db-isolation branch from 3fa3ad4 to 99bfe04 Compare September 9, 2026 11:34
@KuSh
KuSh force-pushed the fix/test-db-isolation branch from 99bfe04 to e6e066c Compare September 17, 2026 22:42
@bharvey42

Copy link
Copy Markdown

Reviewed this on Windows 11 (stable-x86_64-pc-windows-gnu), since #3228 was closed in its favour and the leak I measured there was Windows-side. Short version: the isolation works — it closes the leak completely on this machine, including the spawned-child path. Three things I hit that you may not see on Linux/macOS.

It works

Method: PR head (e6e066c) vs its own parent (5e0f92c), counting rows in the real ~/AppData/Local/rtk/history.db before/after cargo test --all. This machine runs other Claude sessions against the same database, so a raw total is meaningless here — I filtered on the project_path column and counted only rows attributable to the worktree under test.

rows written to the real history.db
base 5e0f92c 56
PR head 0

The base rows are the fixtures, unmistakable: find /definitely/missing/xyz -mtime +0, find . -name secret.txt, git stash show, git worktree list, find <temp>\.tmpKrq4GF -name '*.txt', cat <temp>\.tmp9SKZ6a.rs. By filter: 33 rtk read, 15 rtk find, 4 rtk git stash/status/worktree, 2 rtk json, 2 rtk diff. On the PR head, zero — and .device_salt, .hook_warn_last and trusted_filters.json were all untouched too. --no-fail-fast, so the integration targets that spawn the binary actually ran.

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 develop (find_cmd::run_from_args_propagates_find_exit_status, core::stream::test_read_lines_lossy_preserves_lines_after_invalid_utf8, hooks::hook_cmd::test_claude_pipeline_rewrites_only_safe_final_stage). No regressions.

1. Windows CI is red, and it is a class rather than a single error

test (windows-latest) currently fails with:

error: unused import: `Command`
 --> tests\read_window_bytes_test.rs:3:20
error: could not compile `rtk` (test "read_window_bytes_test")

I reproduced that byte-for-byte locally. Cause: the PR moves the other four tests in that file onto common::rtk_command(), and the only remaining user of Command is rewritten_head_spellings_match_native_on_non_utf8_files, which is #[cfg(unix)]. On Windows the import is genuinely unused, and [lints.rust] warnings = "deny" makes it fatal.

Fixing only that uncovers the next one, which is the more general shape:

error: function `rtk_command` is never used        --> tests\common\mod.rs:19:8
error: function `redirect_rtk_data` is never used  --> src\core\test_isolation\scratch.rs:25:8
error: function `scratch_dir` is never used        --> src\core\test_isolation\scratch.rs:39:8
error: function `remove_at_exit` is never used     --> src\core\test_isolation\scratch.rs:60:4
error: could not compile `rtk` (test "dotnet_double_dash_test")

Of the 20 integration targets that now carry mod common;, about a dozen have their sole rtk_command() call inside a #[cfg(unix)] test — dotnet_double_dash, copilot_selfheal, gh_pr_checks_failure, grep_context, hook_warning_scope, native_test_expression, search_compress, search_error, search_faithful, search_stdin, signal_flush, stderr_only_failure. Each compiles common (and scratch.rs through it) with nothing using it, so each is a separate -D dead-code failure surfacing one at a time.

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

telemetry_cmd.rs is not in this PR, and run_forget still resolves the database itself rather than through constants::data_dir():

// 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 — trust.rs:51, hook_check.rs:140, tee_file.rs:111, telemetry.rs:222, telemetry.rs:552, tracking.rs:1562 — which is what makes this one stand out. Nothing reaches it today (TelemetrySubcommand::Forget has no test), so it is latent rather than a live leak. But it is the one path that removes the developer's database instead of appending to it, and tests_that_spawn_rtk_isolate_their_data scans for CARGO_BIN_EXE_rtk, so it would not catch a future in-process test for telemetry forget.

Since the guard test is already a source scan, it could cover this shape cheaply: reject dirs::data_local_dir() anywhere under src/ except constants.rs. That turns "remember to use data_dir()" into something the suite enforces.

3. On Windows the scratch directories are never reclaimed

remove_at_exit is #[cfg(unix)], and tempfile's guard is dropped by .keep(), so nothing removes the directory on Windows. It is per test binary, not per run — a single cargo test --all --no-fail-fast here went from 2 to 11 rtk-test-* directories under %TEMP%, each with its own rtk/history.db. The doc comment says as much, so I assume this is known; flagging the magnitude since it accrues every run on every Windows contributor's machine, and %TEMP% is not cleared as reliably as /tmp.

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 semgrep security scan is red (2 findings on the changed files); I did not dig into which rules.

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.

@KuSh
KuSh force-pushed the fix/test-db-isolation branch from e6e066c to 11d9684 Compare September 20, 2026 16:20
@KuSh

KuSh commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thank you @bharvey42! The project_path filter to get an attributable count on a machine that runs rtk concurrently is a better measurement than the one I had, and it is the half I could not do from Linux at all. Both compile fixes were exactly right; I have pushed them along with the rest.

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;

tests/common/mod.rs now carries #![allow(dead_code)] with the reason above it, since every integration target compiles the module separately and uses only the part it needs.

I also set up a cross-check so this class stops reaching CI: cargo check --target x86_64-pc-windows-gnu --all-targets in a container, a couple of seconds once warm. It reproduced both of your errors byte-for-byte before the fix and is clean after. Running it against the rebased branch turned up two more files that had landed on develop since my branch point and spawn the binary directly — tests/trae_hook_test.rs and tests/windows_child_quoting_test.rs — so those are converted too.

2. telemetry_cmd.rs. Converted, and I took the enforcement suggestion: there is now a second scan rejecting dirs::data_local_dir() anywhere under src/ outside constants.rs. It found one more caller while I was at it — core/retriever.rs, added to develop after my branch point, which had grown its own hand-rolled cfg(test) redirect into the temp root. It now goes through data_dir() like everything else, which also gets it the scratch cleanup.

Worth being precise about scope, since the two overlap but are not the same: this makes run_forget resolve through data_dir(), so it is test-isolated and consistent with its siblings. It does not make it honour RTK_DB_PATH or config.tracking.database_path — that is #2956, and still open.

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 rtk-test-* directories at creation, which suits Windows precisely because it refuses to delete a file with an open handle, so a live run's directory would be skipped and the rest reclaimed. I have deliberately not implemented it: that safety argument rests on file-locking semantics I can only type-check from Linux, not exercise, and this PR has already had one round where something I could not test turned out to behave differently than I assumed. If you have the machine and the inclination it would be a good standalone change; equally happy to leave it sitting on the issue.

semgrep. Two findings, both mine: unsafe-block on the libc::atexit call and dynamic-command-execution on Command::new(bin) in rtk_command. Suppressed with justifications in the repo's existing // nosemgrep: style. I reproduced the CI job locally with the same --baseline-commit --error invocation to confirm it comes back zero rather than assuming the suppressions landed — the first attempt did not, because I had split the justification across two lines and only the immediately preceding line counts.

The branch is rebased onto current develop (it had gone conflicting), which took one conflict in hook_warning_scope_test.rs where develop's newer isolating_env helper supersedes what I had inline — I took develop's, it pins XDG_CONFIG_HOME too.

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.

@KuSh
KuSh force-pushed the fix/test-db-isolation branch from 11d9684 to 18709cd Compare September 28, 2026 01:06

@aeppling aeppling left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@KuSh
KuSh force-pushed the fix/test-db-isolation branch from 18709cd to 3a13647 Compare September 30, 2026 17:44
@KuSh KuSh changed the title fix(tests): stop the test suite writing to the developer's own rtk data fix(tests): keep the test suite and the developer's environment apart Sep 30, 2026
@KuSh

KuSh commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator Author

@aeppling thank you, both reproduced with your commands, and both are fixed on the new head (3a13647).

1. filters.toml on a fresh machine. I did not pin HOME in with_claude_dir_override: swapping HOME process-wide reaches every test running beside it, and in a loop that failed about one run in six (17.5%), through concurrent tests that spawn tooling reading HOME, cargo's rustup shim among them. The redirect sits in the resolver instead. core::user_dirs is now the one place that asks dirs (data, config, home), with the cfg(test) redirect in it, and the scan refuses any dirs:: use elsewhere, config_dir included as you suggested. generate_global_filters_template writes through user_dirs::config().

2. hook-audit.log with RTK_HOOK_AUDIT=1. Also fixed here. audit_log_inner resolves through user_dirs::home(), and in a test build RTK_HOOK_AUDIT is only what a test sets itself, so an exported one is not read. The audit test now calls audit_log under its own root and reads the line back.

Your two repros on 3a13647: no filters.toml and no hook-audit.log under the fake HOME.

Following the same class in the other direction widened the PR. Tests also took their results from the contributor's machine: deny rules in ~/.claude or the checkout's settings.local.json, exported RTK_*, CLAUDE_CONFIG_DIR or GIT_DIR, ~/.gitconfig, a global.json above TMPDIR. The description has the design and the numbers. Under all of those at once, develop fails 126 tests and writes or deletes 12 files outside the scratch directory; this branch fails none and touches none. It is rebased on develop after #3826, whose test_support helpers now live in test_isolation.

Production behaviour is unchanged: every redirect is behind cfg(test).

@KuSh
KuSh requested a review from aeppling September 30, 2026 20:05
`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]>
@KuSh
KuSh force-pushed the fix/test-db-isolation branch from 3a13647 to e0d99ab Compare September 30, 2026 22:05

@aeppling aeppling left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @KuSh thanks for addressing the review , lgtm

@KuSh
KuSh merged commit 4c8a255 into rtk-ai:develop Oct 1, 2026
12 checks passed
@KuSh
KuSh deleted the fix/test-db-isolation branch October 1, 2026 09:27
@rtk-release-bot rtk-release-bot Bot mentioned this pull request Oct 1, 2026
aeppling pushed a commit that referenced this pull request Oct 5, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants