Repository navigation
🤖 tests: TLA+ model of background processes + failing repros - #5464
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9af02d4d3d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review |
Add formal/background-processes/ (5 TLA+ modules, 22 configs, check.sh with an EXPECT table) and src/node/services/backgroundProcessesFormalRepro.test.ts: five repros wrapped in expectReproFailure (each passes only while it fails at its target assertion) plus four passing controls. Add the model's filter to .github/workflows/formal.yml. No production code changes. --- _Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high`_
03e2fc6 to
4647fa3
Compare
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
… during removal and archive (coder#5473) ## Summary Archive now stops this backend's own background processes before it stops the runtime or deletes the checkout (B3), and a background spawn that is still in flight when a removal or archive cleans up can no longer start after the cleanup looked (B2). Both findings come from the background-processes TLA+ model (coder#5464). ## Background - **B2** (`BgCleanup.tla`, `MC_cleanup_spawn_remove`): `spawn()` checked no seal and was not a pending entry, and the bash tool did not check its abort signal before spawning. A `run_in_background` spawn that was still waiting for its record name when removal's `cleanup()` listed the processes registered afterwards and ran while the checkout was deleted. Fg→bg migrations were already sealed against this (coder#4967). - **B3** (`MC_cleanup_archive`): `archiveUnlocked` stopped the stream, terminals and MCP servers, but never this backend's background processes. `ARCHIVE_OWN_ACTIVITY_POLICY` and the model-facing refusal ("would terminate") both say archive stops them. A snapshot or delete archive then deleted the checkout under the running process. ## Implementation 1. `BackgroundProcessManager`: the migration seal now covers spawns too (`sealMigrations` → `sealAdmissions`, `pendingMigrations` → `pendingAdmissions`). `spawn()` is admitted by `admitSpawn()` at entry (refused while sealed) and stays pending until it registers or fails, so `cleanup()` waits for it. It is refused again once it holds its name lock if a cleanup sealed the workspace meanwhile, so it does not start a child that cleanup would only have to stop. 2. Bash tool: a `run_in_background` call whose abort signal already fired does not call `spawn()`. The check and the spawn admission run in the same synchronous step, so a later stream stop finds the spawn pending or the workspace sealed. 3. Archive: seals the workspace and runs `cleanup()` before its project hook and `runBeforeArchive` (which may stop a dedicated Coder workspace). It keeps the seal until it settles, and `stopLiveWorkspaceActivityForArchive` runs `cleanup()` again after the stream stop. TLC found that the second cleanup is needed: without it, a foreground command of the still-running stream whose migration the seal refused is still being killed when the checkout is deleted. 4. Failure handling (fail-safe): - Archive: if the first `cleanup()` throws, archive returns `Err` before its hooks run and before anything is persisted or deleted. If teardown fails after `archivedAt` is durable (non-snapshot path), archive stays successful but skips the `afterArchive` hooks, which delete the checkout. - Removal: unchanged. A `cleanup()` that throws already fails the removal before the checkout deletion, forced removals included. A new test pins this with a failure injected at the process handle, and shows the process stays tracked for a retry. 5. Model: `BgCleanup.tla` gets an `ArchiveCleans` flag (seal, cleanup, stream stop, cleanup again, delete) and models the post-lock spawn refusal under `SpawnSealed`. The new `MC_cleanup_archive_fixed` config holds. The pre-fix configs `MC_cleanup_spawn_remove` and `MC_cleanup_archive` keep their expected violations (`ArchiveCleans = FALSE`). The B2 and B3 repros in `backgroundProcessesFormalRepro.test.ts` are now plain passing tests. The B2 repro releases the other backend's name lock while cleanup runs instead of after it returns: with the fix, cleanup waits for the spawn, so the old order waits until the 30 s name-lock timeout. ## Validation - `bun test` (bun 1.3.12): `backgroundProcessesFormalRepro`, `backgroundProcess*`, `tools/bash*`, `workspaceService*`: 1267 pass, 0 fail. `task*`, `workflows`, `agentSession*`: 2741 pass; the 2 failures are `taskGitPatchEngine` fixture tests that fail on this host (`.git/info` missing from the git template dir) and are unrelated. - With the production changes reverted, these fail at their target assertions: the B2 and B3 repros, the 4 new archive tests, the removal spawn-refusal test, and the bash abort test. - `formal/background-processes/check.sh`: exit 0, all 23 configs match EXPECT. - `make static-check`: exit 0. ## Risks Medium, in archive and removal. Archive now kills this workspace's background processes even when a later archive step fails (for example a failing `beforeArchive` hook), like removal already does. That loss is recoverable, unlike a process running in a deleted checkout. A spawn that is waiting for a name lock held by another backend now delays cleanup by at most the 30 s lock timeout. Known limitation (not changed here): `terminate()` reports success when the kill itself throws, because handles are best-effort. So cleanup's failure signal covers handle-release failures, not every failed kill. The B1 work on `terminate()` owns that. Refs coder#5464. Follow-ups (a failed kill is not a cleanup failure, unbounded pending-admission drain) are tracked in coder#5477. --- _Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high` • Cost: `$4.20`_ <!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high costs=4.20 -->
…es (coder#5472) ## Summary A command sent to the background now writes its record under the same host root that local spawns, the spawn-name lock and every backend's structural-mutation gate use (`/tmp/mux-bashes`, `TEMP` on Windows). Before, on macOS (or Linux with `TMPDIR` set), another backend's gate could not see the live migrated command and could rename, remove or archive the workspace under it. Fixes finding B4 of the background-processes model (coder#5464). ## Background `BackgroundProcessManagerLive` built the manager with `path.join(os.tmpdir(), "mux-bashes")`, so migrated records and the migration name lock lived under `os.tmpdir()`. Local spawns use `LocalBaseRuntime.tempDir()` (`/tmp`), and `hasOrphanedRunningBackgroundProcesses` scanned only `localBgWorkspaceDir` (`/tmp/mux-bashes/<ws>`). On macOS `os.tmpdir()` is `/var/folders/...`, so the two roots differ. TLC: `MC_gate_migrated_ostmp` violates `NoMutationUnderForeignProcess`, `MC_gate_migrated_tmp` holds. Side effect: spawns and migrations locked different `.spawn-name.lock` files. ## Implementation 1. One source of truth: `localRuntimeTempRoot()` (LocalBaseRuntime) feeds `LocalBaseRuntime.tempDir()` and the new `localBgRecordsRoot()` (backgroundProcessExecutor), which `localBgWorkspaceDir` and `BackgroundProcessManagerLive` now use. Writers (spawn and migration), the name lock and the gate's primary root are the same path. 2. Upgrade: the gate also scans the old root (`legacyMigratedBgRecordsRoot()` = `os.tmpdir()/mux-bashes`) and the manager's own `bgOutputDir`, deduplicated by filesystem identity (`fs.realpath`), so `TMPDIR=/private/tmp` on macOS does not rescan the shared root. A live command that an older build migrated under `os.tmpdir()` stays visible. In that legacy root the gate does not skip records whose names this manager tracks, because nothing this manager tracks lives there, and an older backend's same-named command must still count. 3. Downgrade: an older build's gate scans `/tmp/mux-bashes`, where new builds now migrate, so it sees them. 4. No new persisted state. `check.sh` EXPECT rows are unchanged: `MC_gate_migrated_ostmp` still models the old wiring, and the code now matches `MC_gate_migrated_tmp`. ## Validation All with bun 1.3.12. - B4 repro (`backgroundProcessesFormalRepro.test.ts`) is now plain tests: control (Linux `/tmp`), macOS (`TMPDIR` outside `/tmp`, both backends built through `BackgroundProcessManagerLive`), and upgrade (older-build wiring migrates, new backend's gate scans). A fourth test points `TMPDIR` at a symlink to `/tmp` and checks that a backend's own migrated command is not foreign evidence; it fails with a `path.resolve` dedupe. With the production diff reverted, the macOS and upgrade tests fail at their target assertions (`Expected: true, Received: false`), and the control passes. - `bun test` backgroundProcessExecutor, backgroundProcessManager, backgroundProcessesFormalRepro, workspaceService.mutationGate / turnAdmission / archive / bashMonitorWake, taskService.attemptAdmission / lifecycleFormalRepro, coreServicesRoot: 476 pass, 0 fail. bash tool suites (bash, bashTaskReport, bash_background_list, bash_background_terminate, bash_output): 112 pass, 0 fail. - `TLA_JAVA_OPTS=-Xmx6g formal/background-processes/check.sh`: exit 0. - `make static-check`: exit 0. ## Follow-ups - coder#5474: on Windows the root still follows the process's `TEMP` (unchanged by this PR). - coder#5480: drop the legacy `os.tmpdir()` scan after the upgrade window (a stale legacy record fails the gate closed). ## Risks Low. Affects where host-local migrated records live on macOS and with `TMPDIR` set (Linux default is unchanged: `os.tmpdir()` was already `/tmp`). The gate scans at most two extra directories; extra roots can only add evidence (over-refusal routes to user-mediated archive), never hide it. --- _Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high` • Cost: `$0.00`_ <!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high costs=0.00 -->
…er#5486) ## Summary On runtimes whose background records are not on this host (SSH/Coder, Docker, devcontainer, multi-project), a second backend no longer reinitialises a record directory that another backend still tracks. Spawn now claims the name with an atomic `mkdir` (no `-p`) on the runtime, and any existing directory, including a settled one with `exit_code`, counts as taken. Fixes the reproduced part of coder#4889 (finding from the background-processes model, coder#5464). ## Background Host-local names are serialised by the `.spawn-name.lock` file lock (`MC_name_host` holds). Non-host runtimes had no cross-backend lock, and `runtimeSpawnDirMayHoldLiveProcess` called a directory free when it held `exit_code`. So backend B reinitialised the directory backend A still tracked, even when the spawns never overlapped (TLC `MC_name_remote_serial`), and two concurrent same-name spawns could share one directory (`MC_name_remote`). A's later output and status reads then described B's command. ## Implementation 1. `claimRuntimeSpawnDir` replaces the probe: `mkdir -p <workspace dir>`, then `mkdir <record dir>`. Success means this spawn owns the directory. If it exists (or a dangling symlink sits there), the name is held and the existing suffix loop picks the next name. Any other failure aborts the spawn, as before. No new persisted state, no remote lock. Names, `bash:<name>` task IDs and monitors keep the existing suffix contract. 2. The claim creates the directory before `spawnProcess` runs, so two early failures must not leave an empty directory behind (it would hold the name and fail the remote crash-orphan probe closed): - `spawnProcess` removes the directory on a cwd-check failure, but only when the caller passes the new `recordDirClaimed` option (the manager does for non-host runtimes). - When the B2 seal (coder#5473) refuses the spawn after its name step, the manager removes the claimed directory with `rmdir` (empty-only). 3. Model: `BgSpawnName.tla` gets an `AtomicClaim` fix probe (a `Claim` step that creates the directory only when absent). New `MC_name_remote_fixed` holds all invariants. The faithful remote rows stay as they are, because they describe the old code. ## Validation All with bun 1.3.12. - `coder#4889 … B does not reinitialise the record directory A still tracks` is now a plain test. With `backgroundProcessManager.ts` and `backgroundProcessExecutor.ts` reverted to `main`, it fails at its target (`Expected: false`, `Received: true`); the host-local control passes. - New tests, each failing with its production change reverted: concurrent same-name spawns from two backends on a non-host runtime get distinct directories; a cwd-check failure removes the claimed directory; an unclaimed existing record survives a cwd-check failure; a seal refusal removes the claimed directory. The existing settled-record test now expects `settled-job (2)` and an untouched `exit_code`. - `bun test src/node/services/backgroundProcess*.test.ts src/node/services/tools/bash*.test.ts`: 268 pass, 0 fail. - `TLA_JAVA_OPTS=-Xmx6g formal/background-processes/check.sh`: exit 0. - `make static-check`: exit 0. ## Risks Low to medium, limited to background spawns on non-host runtimes. A display name used in an earlier session now gets a suffix on those runtimes until `/tmp/mux-bashes/<ws>` on the runtime is cleared, and each taken candidate costs one exec round-trip. Tracked in coder#5485 (a remote prune needs a lock or a race-free design). Host-local spawns are unchanged. Refs coder#4889 (stays open: its cross-backend evidence requirements are broader), coder#5464. --- _Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high` • Cost: `$7.74`_ <!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high costs=7.74 -->
…exit code (coder#5503) ## Summary Two parts of finding B1 from the background-process TLA+ model (coder#5464) are fixed. Concurrent stops of one background process (task_stop and the timeout timer) now share one kill sequence. A stop never overwrites the exit code the process recorded. The core B1 defect stays **open**: a stop after an unobserved natural exit still signals the process group, whose PGID may already belong to another group (coder#5481). This PR supersedes coder#5471 with a narrower scope. ## What ships, and what does not | Model invariant (`BgTerminate.tla`) | Status after this PR | | --- | --- | | `OneKillSequence` | fixed | | `NaturalExitPreserved` | fixed | | `NoSignalToReusedPgid` | **still violated** (coder#5481) | The new config `MC_term_shipped` models exactly this code. `check.sh` expects `NoSignalToReusedPgid` violated and the other two to hold. ## Implementation 1. `RuntimeBackgroundHandle.terminate` memoizes its termination promise synchronously, before the first await. Every caller of the handle shares one kill sequence. 2. The kill command (`buildTerminateCommand`) publishes 143/137 only when no `exit_code` file exists: `[ -e ] || (set -C; echo …)`. noclobber makes the create O_EXCL, and the `[ -e ]` check keeps an existing FIFO from blocking the write. A code the wrapper's EXIT trap wrote always wins. 3. The wrapper gets `trap 'exit 143' TERM`. It runs only on SIGTERM. Without it, bash killed by SIGTERM ran its EXIT trap with `$?` = 0, so with noclobber a stopped process would have recorded 0. A script's own TERM trap still wins (its code is recorded). 4. The kill decision does not change. It still signals unconditionally. In particular, `exit_code` is not read to decide whether to signal: the script runs in the wrapper shell and can write that file, so it cannot prove an exit (see coder#5471 rounds 2–4). `kill -0`, PGID existence and the in-memory status are not used either, because none of them rules out PGID reuse. ## Tests - B1 repro `a stop after a natural exit does not overwrite the exit code` is now a plain test (the file keeps `3`). With the old overwriting publish it fails: `Expected: "3"`, `Received: "143"`. - New B1 repro `a stop after a natural exit sends no signal to the process group`, wrapped in `expectReproFailure` because the defect stays open. It currently fails at its target (`Expected: true`, `Received: false`: the group's `sleep` was signaled). - New executor tests: - `concurrent terminate calls share one kill sequence`. Without the memo: `Received length: 3`. Without the TERM trap: `Expected: 143`, `Received: 0`. - `a stop keeps the exit code the script's own TERM trap recorded`. With the old overwriting publish: `Expected: 7`, `Received: 143`. - `a member that ignores SIGTERM is killed after the wrapper recorded its exit`: the escalation still sends SIGKILL. ## Validation All with bun 1.3.12. - `bun test` on `backgroundProcessesFormalRepro`, `backgroundProcessExecutor`, `backgroundCommands`, `backgroundProcessManager`, `tools/bash`, `tools/bash_output`, `tools/bash_background_list`, `tools/bash_background_terminate`, `tools/bashTaskReport`, `tools/task.bash`, `workspaceService.bashMonitorWake`: all pass. One pre-existing timing flake (`stops monitoring after maxEvents without killing the process`) failed once under load, then passed 3/3 alone and in a full rerun of the manager file. - `TLA_JAVA_OPTS=-Xmx6g formal/background-processes/check.sh`: exit 0. - `make static-check`: exit 0. ## Risks Low, limited to background-process stop. - A stopped process records the code its wrapper's EXIT trap writes (143 through the TERM trap, or the script's own TERM-trap code) instead of a forced 143. - A second concurrent stop waits for the first kill sequence instead of starting its own. - A natural exit keeps its own code even when a stale stop runs afterwards. That stop still reports the process as `killed` (unchanged). ## Open - coder#5481: no signal after a natural exit (the check-to-signal boundary), group members left after the wrapper exits, and the untrusted marker. A separate design pass covers these. - coder#5491: a transient transport failure after a stop loses the exit code (pre-existing). Refs coder#5464. Supersedes coder#5471. --- _Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking: `high` • Cost: `$20.02`_ <!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high costs=20.02 -->
Summary
Tests only. This PR adds a TLA+ model of background processes (
formal/background-processes/) and deterministic repros of the five violations TLC found (src/node/services/backgroundProcessesFormalRepro.test.ts). It changes no production code. Four fix PRs build on this commit (B1; B2+B3; B4; #4889 record names). Each fix PR turns its repro into a plain passing test.Repro contract
Each repro wraps its body in
expectReproFailure(src/node/utils/formalRepro.testHarness.ts). It passes only when the body fails at its single-line target assertion with exactly this mismatch. A fix makes the repro fail with "repro passed", and the fix PR then unwraps it.expect((await fs.readFile(exitCodeFile, "utf-8")).trim()).toBe("3")"3"/"143"expect(liveAtDeletion).toBe(false)false/trueexpect(isAlive(spawned.pid)).toBe(false)false/trueexpect(await other.hasOrphanedRunningBackgroundProcesses(ws)).toBe(true)true/falseexpect(second.outputDir === first.outputDir).toBe(false)false/trueFour plain controls show that each setup reaches the code path. The B1 fixture runs
sleep 30 & exit 3: the test's ownsleepholds the process group, so the stale stop under test can only signal that group, never a host process that reused the PGID.Findings
Line numbers are at the base of this PR.
terminate()(backgroundProcessManager.ts~2950) decides from the in-memory status only, and that status follows a natural exit only when something polls it. The kill command (backgroundCommands.ts~135-155) sendskill -15 -<pgid>without checkingexit_code, then writes 143 (orkill -9and 137). Theterminatedflags are set after awaits (backgroundProcessManager.tsterminate,backgroundProcessExecutor.ts~500-525), sotask_stopand a timeout can both run kill sequences. Effect: the natural exit code is lost, and a reused PGID can kill unrelated processes of the same user. TLC:MC_term_faithfulandMC_term_one_callerviolateNoSignalToReusedPgidandNaturalExitPreserved(MC_term_faithfulalsoOneKillSequence).MC_term_fixedholds.run_in_backgroundspawn in flight survives workspace removal.spawn()(~1617-1800) has no migration seal and no pending entry.bash.ts(~1050) never checks the abort signal around the spawn.cleanup()(~3074-3099) snapshots the process list, so a registration that lands later keeps running while the checkout is deleted. TLC:MC_cleanup_spawn_removeviolatesNoLiveAfterDelete.archiveUnlocked(workspaceService.ts~11533) stops the stream, terminals and MCP servers but never callscleanup/terminate. This contradicts theARCHIVE_OWN_ACTIVITY_POLICYcomment (~855) and the model-facing refusal message ("archiving would terminate"). TLC:MC_cleanup_archiveviolatesNoLiveAfterDelete.path.join(os.tmpdir(), "mux-bashes")(di/layers/core.ts~203). The structural-mutation gate scans/tmp/mux-bashes/<ws>(localBgWorkspaceDir,backgroundProcessExecutor.ts~99-102). The two roots differ on macOS and wheneverTMPDIRis set, and they also use different.spawn-name.lockfiles. TLC:MC_gate_migrated_ostmpviolatesNoMutationUnderForeignProcess(MC_gate_migrated_tmp, the Linux layout, holds).exit_codeas free. So a second backend reinitialises a record directory the first still tracks. TLC:MC_name_remote_serialviolatesNoReuseWhileTracked.MC_name_remote(two backends share one directory) also violatesOneProcessPerDir. The gate cannot see SSH/Docker records (MC_gate_ssh_spawn,MC_gate_docker_spawn); the Note indocs/config/server-access.mdx(~116-120) documents that limit.What holds
MC_cleanup_migration_removeholds (migrations are sealed, 🤖 bug: background cleanup can miss a command that starts migrating after its snapshot #4967).MC_name_hostholds.MC_monitor).MC_gate_local_spawn,MC_gate_devcontainer_spawn,MC_gate_migrated_tmphold.MC_mut_*config breaks one protocol step and stays caught, which shows the model can see each bug class.Not modelled (tracked in #5465)
writeMetaleaves a process without a record.Model limits
The specs abstract the shell wrapper, file system and runtimes into a few atomic steps per protocol action, with small bounds (at most two backends or two stop callers, one workspace). They check safety invariants only, not liveness. A
holdsresult covers only these bounds and the modelled steps.Changes
formal/background-processes/:BgTerminate.tla,BgCleanup.tla,BgSpawnName.tla,BgMonitor.tla,BgGateEvidence.tla, 22MC_*.cfg,check.sh.check.shruns one TLC run per (config, invariant), compares with itsEXPECTtable, creates a caller-suppliedOUT, and fails a full run when anEXPECTentry has no config file (same convention as 🤖 tests: TLA+ model of plan-file storage + failing repros #5458)..github/workflows/formal.yml: abackground-processesfilter (the model directory,backgroundCommands.ts,backgroundProcessExecutor.ts,backgroundProcessManager.ts,di/layers/core.ts,tools/bash.ts,workspaceService.ts,workspaceUseLeases.ts) and the matching coarsepathsentries.Validation
bun test src/node/services/backgroundProcessesFormalRepro.test.ts(bun 1.3.12), 3 runs: 9 pass, 0 fail each (~15 s). Nosleep 30process from the tests remained afterwards.expectReproFailurereplaced by a plain call, all five repros fail at their target lines with the mismatches in the table above, and the four controls pass.formal/background-processes/check.sh(TLC,TLA_JAVA_OPTS=-Xmx6g): exit 0, every (config, invariant) matchesEXPECT(~40 s).check.shwith one config removed: printsMC_monitor: EXPECT entry without a config fileand exits 1.make static-check: exit 0.Generated with
xum• Model:anthropic:claude-opus-5-5• Thinking:high