Keep Tests from Leaking Rotator Daemons¶
A launch command (amplihack claude, amplihack launch,
amplihack profile run) can start the profile rotator in the background with
amplihack profile rotate watch --spawned. That process is detached with
setsid, so it outlives the test that launched it. Before #1690, test runs
left these daemons behind: they ran from target*/debug/amplihack, their
parent was PID 1, and their HOME was a temp directory the test had already
deleted.
This guide explains the three stops that keep tests from starting a real rotator, how to run the leak check, and what to do when it fails. It is for contributors who write tests. Users' autostart is unchanged; see Start the rotator automatically.
Contents¶
- The three stops
- Write a test that starts the binary
- Run the leak check
- When the leak check fails
- Test a real daemon on purpose
- Tie a started rotator to the test
- Limits
The three stops¶
| Stop | Where | What it does | Covers |
|---|---|---|---|
| A | tests/support/isolated_amplihack.rs |
isolated(..) sets AMPLIHACK_ROTATE_AUTOSTART=0 next to AMPLIHACK_TEST_HOME_GUARD=1. |
Every test that starts the binary through isolated(..) and keeps its environment. |
| B | autostart::run() in crates/amplihack-cli/src/commands/profile/rotate/autostart.rs |
The first check: if AMPLIHACK_TEST_HOME_GUARD is set and not empty, return Outcome::Skipped("test"). |
Fixtures that call env_clear() after isolated(..) and set the guard again, which drops stop A. |
| C | autostart_on_launch in the same file |
Test builds (#[cfg(test)]) use a spawner that always refuses. Other builds use daemon::spawn. |
In-crate unit tests, which never set the guard. |
Stop B comes before every other autostart check. A skipped launch reads no
setting, creates no file or directory, takes no lock and prints nothing to
stdout or stderr. It cannot skip the checks and still spawn: the only result
is Skipped("test").
Stop B is not a user setting. Only the test harness sets
AMPLIHACK_TEST_HOME_GUARD (see the
environment variable reference). Under
the guard, rotate status can still print autostart: on (default), because
the status text describes the setting, not the test harness.
Stop C is compiled only into test builds. Release and debug binaries use the real spawner, so a user's launch starts the rotator exactly as before.
Write a test that starts the binary¶
Start the binary through isolated(..). It clears the environment and gives
the child a temp HOME, the home guard and the autostart opt-out. In
crates/amplihack-cli/tests/, main.rs already includes the helper with
#[path = "../../../tests/support/isolated_amplihack.rs"]:
use crate::isolated_amplihack::isolated;
let mut cmd = isolated(env!("CARGO_BIN_EXE_amplihack"));
cmd.args(["profile", "rotate", "status"]);
let out = cmd.output().unwrap();
assert!(out.status.success());
crates/amplihack-cli/tests/issue_1690_isolated_autostart.rs checks that
isolated(..) sets both variables:
| Variable | Value |
|---|---|
AMPLIHACK_TEST_HOME_GUARD |
1 |
AMPLIHACK_ROTATE_AUTOSTART (ROTATE_AUTOSTART_ENV) |
0 |
A test that needs its own HOME sets it again after isolated(..); the
guard and the opt-out stay. If your fixture calls env_clear() after
isolated(..), set the guard again afterwards. Stop B then still holds even
though stop A is gone:
use crate::isolated_amplihack::{isolated, HOME_GUARD_ENV};
let tmp = tempfile::tempdir().unwrap();
let mut cmd = isolated(env!("CARGO_BIN_EXE_amplihack"));
cmd.env_clear()
.env("PATH", std::env::var_os("PATH").unwrap())
.env("TMPDIR", std::env::temp_dir())
.env("HOME", tmp.path().join("home"))
.env(HOME_GUARD_ENV, "1");
Keep TMPDIR as well. The home guard accepts only a HOME under the child's
temp dir, so if your TMPDIR is not /tmp and the child loses it, the guard
rejects the test's HOME.
A fixture that calls env_clear() and does not set the guard again has no
stop. Only the leak check catches it.
Run the leak check¶
scripts/check-leaked-rotators.sh lists rotator daemons that a test run left
behind. Run it after the test suite:
On a clean run:
A process counts as a leak only when all of these hold:
- It belongs to the current user.
- Its argv contains
profile,rotate,watchand--spawnedas separate entries. - Its executable is under a
target*/directory, under$CARGO_TARGET_DIR, or under this repo'starget/. Those last two are resolved through symlinks first, so atarget/that links to, say,/d0/cargo-targets/<name>/still counts. A(deleted)suffix on/proc/<pid>/exeis ignored; if the link cannot be read, argv[0] is used. - Its
HOMEis under$TMPDIRor/tmp. ATMPDIRof/or a relative one is ignored, so only/tmpcounts then.
Your own rotator (~/.local/bin/amplihack, HOME=/home/<you>) never matches,
and the script never sends a signal to any process.
| Exit | Meaning |
|---|---|
| 0 | No leaked rotator, or not Linux (no /proc; prints a note). |
| 1 | At least one leaked rotator. One line each is printed. |
| 2 | /proc exists but the scan could not read its own entry or saw no processes. |
CI runs the check in the test job after both nextest steps and
cargo test --doc, as No leaked rotator daemons (issue #1690), with
if: always() so it also runs after a failing test. The check job runs the
self-test tests/issue_1690_leaked_rotator_check.sh. That script starts a
decoy process that looks like a leaked rotator, checks that the detector
exits 1 and names its pid, then kills only the decoy and checks for exit 0:
When the leak check fails¶
Each leak prints one line:
leaked rotator: pid=48213 exe=/home/dev/amplihack-rs/target/debug/amplihack HOME=/tmp/.tmpQ3x9aB/home AMPLIHACK_CLAUDE_PROFILE_ROOT=/tmp/.tmpQ3x9aB/profiles
The output holds only those four fields. Control characters are removed and each value is cut to about 256 bytes, because CI logs are public and a full environment can hold tokens.
To find the test that started it:
- Start from the
AMPLIHACK_CLAUDE_PROFILE_ROOTin the leak line. If that directory still exists, read itsrotate.err:
An autostart: started pid 48213 exe … line with the leaked pid confirms
that a launch autostarted it. The profile names under that root, and the
files the fixture wrote there, tell you which fixture built it. If the
file has no autostart: line, the daemon came from an explicit
profile rotate start. That test must stop it itself; see the
issue_1592_daemon tests.
2. If the root is gone, narrow the search. A launch can only autostart when
auto-switch is on for a profile root and the guard is missing. So the
culprit is a test file that calls .env_clear(), turns on auto-switch or
sets a profile root, and never sets the guard again:
grep -rlE '\.env_clear\(\)' --include='*.rs' crates bins tests \
| xargs -r grep -lE 'AMPLIHACK_ROTATE_AUTOSTART|auto_switch|auto-switch|AMPLIHACK_CLAUDE_PROFILE_ROOT' \
| xargs -r grep -LE 'AMPLIHACK_TEST_HOME_GUARD|HOME_GUARD_ENV'
On a clean tree this prints nothing. A plain env_clear() search is not
useful, because most of its matches clear the environment for git, sh
or bash, and those can never start a rotator. If the narrow search
prints a file, that file is the place to look. If it prints nothing, the
fixture writes its config in a way the pattern does not match: check the
fixtures that changed in the failing commit.
3. Fix the fixture by setting the guard again after env_clear(), or by using
isolated(..) unchanged.
To stop a leaked daemon on your machine, check the pid again first. PIDs are
reused, so make sure it is still a rotate watch --spawned process running a
test-build binary with a temp HOME, then kill that pid alone:
pid=48213
tr '\0' ' ' < "/proc/$pid/cmdline"; echo # must contain: profile rotate watch --spawned
readlink "/proc/$pid/exe" # must be a test build (see above)
tr '\0' '\n' < "/proc/$pid/environ" | grep -E '^HOME=' # must be under $TMPDIR or /tmp
kill "$pid"
If any of the three checks does not match, the pid now belongs to another process. Do not kill it.
Do not use pkill -f 'rotate watch'. It also matches your real rotator.
Test a real daemon on purpose¶
The explicit amplihack profile rotate start path has no test stop. Stop B
covers autostart only. The issue_1592_daemon tests need a real daemon: they
start it with --interval 1 and stop it themselves. If such a test fails
before it stops its daemon, the fixture's lifetime pipe stops it; see the
next section. If the daemon still outlives the run, the leak check reports
it. That is intended.
A test that needs a real autostart must remove both stops on purpose, with
cmd.env_remove("AMPLIHACK_TEST_HOME_GUARD") and
cmd.env_remove("AMPLIHACK_ROTATE_AUTOSTART") (removing only the guard still
leaves autostart off through stop A), and must stop the daemon it starts. No test does this today.
Tie a started rotator to the test¶
A rotator started with profile rotate start from the profile_rotate
fixture ends when the test process ends, even if the test is killed with
SIGKILL or cargo test is cancelled. The fixture does this for you; the
mechanism is described in
How a Test's Rotator Ends with Its Test.
Use Fixture::new() and build commands with cmd(..) or
cmd_no_root_env(..). Both go through the private base(..), which arms
every command:
use crate::support::profile_rotate::Fixture;
let fx = Fixture::new();
let out = fx
.cmd(&["profile", "rotate", "start", "--interval", "1", "--hold", "0"])
.output()
.unwrap();
assert!(out.status.success());
// Stop the rotator here as existing tests do. If the test is killed
// before it can, the closed pipe stops the watcher instead.
Existing tests still stop the rotator themselves; the pipe is the backstop
for a test that is killed. Do not rely on Drop for routine cleanup: if
arming breaks, Drop waits on the pidfd with poll(-1) and the test hangs.
Dropping the fixture after a stop finds no pid file and returns at once.
A test that needs the rotator to outlive the test process uses an unarmed fixture, and must stop the rotator itself:
Keep these rules when you change the fixture or write your own command:
- Keep
AMPLIHACK_TEST_HOME_GUARD=1. Without it the watcher ignores the pipe. - Do not rename
AMPLIHACK_TEST_ROTATOR_LIFETIME_FDto anAMPLIHACK_ROTATE*name.daemon::spawnremoves those, and a source-scan test fails. - Do not pass the write end to a child, duplicate it or clear its
FD_CLOEXEC. A child holding it keeps the watcher alive after the test. - Do not clear
FD_CLOEXECon the read end in the test process. Clear it only in the child'spre_exec, asbase(..)does.
Drop waits with no timeout. If a test hangs in Fixture::drop, the watcher
did not exit when the pipe closed: check that watch() still calls
lifetime::arm and that the child received both variables.
Limits¶
- A fixture that runs
env_clear()and never sets the guard again bypasses stops A and B. Only the leak check catches it. - Only an empty or unset guard lets autostart run. Any other value, even
one that is not valid UTF-8, skips it. The harness always sets
1. - The lifetime pipe covers only commands built by the
profile_rotatefixture'scmd(..)andcmd_no_root_env(..). A rotator started any other way, or fromFixture::unarmed(), can still leak if the test is killed. - The leak check misses a daemon whose
HOMEis outside$TMPDIRand/tmp. Test homes are alwaystempfiledirectories. - On a developer machine the leak check can report a daemon from another worktree's test run that is still in progress. CI runners start clean.
Related¶
- How a Test's Rotator Ends with Its Test - The lifetime pipe, its arming rules and why other options were rejected
- Rotate Claude Logins - What the rotator does and when a launch starts it
amplihack profilereference -rotate start,rotate watchandrotate autostart- AMPLIHACK_* environment variables -
AMPLIHACK_TEST_HOME_GUARDandAMPLIHACK_ROTATE_AUTOSTART - Developing amplihack - Build and test setup
- Keep Tests out of the Real Profile Root - Why
isolated(..)removesAMPLIHACK_CLAUDE_PROFILE_ROOT, and the real-root guard