Repository navigation
Preserve REPL background jobs on Ctrl-C and clean up jobs on non-REPL exit - #19163
Conversation
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Forced-interactive command and script execution can leave background external processes running after an interrupt exits Nu.
Review effort: Balanced
Findings: 1
What changed in this PR
This PR addresses #18989 by preserving background and frozen jobs when interactive foreground work or prompt evaluation is interrupted.
Changes:
- Initialize Ctrl-C handling after determining interactive mode.
- Limit automatic job cleanup to non-interactive execution.
- Extract the callback and add tests for preservation and cleanup.
| File | Description |
|---|---|
| src/signals.rs | Conditionally register job cleanup and test interrupt behavior. |
| src/main.rs | Move signal initialization after interactive-mode configuration. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Address review feedback on the fix for nushell#18989: - Kill background jobs through `nu_engine::exit::kill_jobs_and_exit` when commands (`-c`) and scripts finish or fail, even with `-i` (where `cleanup_exit` only warned and left the jobs running), and when strict-mode `--config`/`--env-config` loading fails. If the REPL can't start, its jobs are killed before Nu exits. The server modes (`--lsp`, `--dap`, `--mcp`), `exec`, panics and fatal signals still exit without this cleanup. - Decide whether Nu runs the REPL once, from the parsed arguments (`ParsedCli::is_repl`). The Ctrl-C handler is installed at its original place again, deciding on the job-kill callback right there, and the final dispatch branches on the same value. - Keep all engine mutation in `ctrlc_protection`; the job-kill callback is a separate function that the unit tests call directly. - On Windows, start externals run by background jobs in a new process group, so console Ctrl-C doesn't stop them, as on Unix. - Replace the PID-probing test with end-to-end tests that detect leaked processes through an inherited pipe, including one on the REPL path. They never kill a process by a PID that may have been reused. Signed-off-by: akasakariko <[email protected]>
fdncred
left a comment
There was a problem hiding this comment.
More notes from my clanker, after checking the replies above against ca323a6. The first two change behavior: a job's process can still outlive Nu through an exit race, and exit under -i -c still warns, keeps running and loses its exit code. Both repros ran on this PR's build. The rest are cleanup and test robustness.
|
Updated with c3c2ddb
Local validationValidated the committed tree on macOS with Rust 1.97.1
Native test executables were run from byte-identical copies on the local temporary volume after execution on the external build volume stalled Still open
|
|
Please reply to each review comment to ensure we didn't miss anything |
|
Replied individually to all 10 outstanding review threads with the corresponding changes in Leaving the threads open for your confirmation; Windows real-console Ctrl-C coverage remains explicitly unverified |
|
You'll need to merge main/rebase on main to get the CI green too. |
|
Synced with Resolved the Validation
The full test rerun used The full Windows cross-check on macOS was blocked by missing Windows SDK headers All three new workflow runs currently require maintainer approval, so native Windows CI validation is still pending Could a maintainer approve the CI run, security audit and typos check |
## Description Related to #18989 and follows up on #19163 The REPL resets interrupt signals at the start of each iteration, before evaluating the prompt An interrupted prompt can leave the signal set for the transient prompt, line editor callbacks, and the next command - Recover interrupted signals after normal prompt evaluation, before constructing the transient prompt and entering the line editor - Keep command-boundary recovery before pre-execution hooks for interruptions from editor callbacks - Only reset at these recovery points when interrupted, avoiding extra plugin Reset messages on normal commands - Keep normal prompt errors visible and retain cancellation of running commands - Extend the existing regression test to cover the interrupted prompt result, transient prompt, custom completion, and a subsequent editor interrupt followed by a hook and command - Disable all shell-integration flags in the regression test and explain why its expressions use `match` to reach signal checks ### Reproduction - Start an interactive session with a slow prompt closure such as `{ sleep 1min; "prompt" }` - Press Ctrl-C while the prompt is evaluating - Try a custom completer that polls interruption signals, or a transient prompt closure containing `sleep` - Without prompt-boundary recovery, these callbacks inherit the interrupt until the next command is submitted - Enter `match 1 { 1 => 42 }` - Without command-boundary recovery, the command and its pre-execution hooks can inherit an interrupt from the prompt or editor - With both recovery points, the transient prompt, completion, hook, and new command run normally The macOS PTY probe compared the previous PR commit `0c3e8f749` with the updated code The previous PR binary reported normal and transient prompt interruption errors and offered no custom completion before Enter The updated binary reported only the normal prompt interruption, offered completion before Enter, and rendered the transient prompt The next hook and command succeeded in both probes, including after a separate SIGINT while waiting for input A separate PTY probe kept a background thread job and a frozen external process registered during prompt interruption and verified cancellation of a later foreground command ## User-facing changes (Release notes) Fixed stale prompt interrupts affecting completions, transient prompts, and the next interactive command with its pre-execution hooks ## Validation Local checks on macOS aarch64 with Rust 1.97.1 at `2bcf4099e` | Command | Result | | --- | --- | | `cargo test --locked --profile ci -p nu-cli --lib -- command_after_interrupted_prompt_runs_hooks_and_command` | Fails without prompt-boundary recovery at the transient prompt assertion, passes with the fix | | `cargo build --locked --profile ci --bin nu` | Passed | | `cargo test --locked --profile ci -p nu-cli --no-fail-fast` | 200 unit tests and 295 integration tests passed, 2 ignored | | `cargo test --locked --profile ci --test tests -- shell::` | 341 passed, 6 ignored, including all 29 background-job tests | | `cargo test --locked --profile ci --bin nu -- signals::` | 3 passed | | `cargo nuclippy` | Passed | | `cargo check --locked --profile ci --no-default-features --bin nu` | Passed | | `cargo fmt --all` and `cargo fmt --all --check` | Passed | | `typos` 1.51.1 | Passed | | `git diff --check` | Passed | Manual PTY checks passed for prompt errors remaining visible, completion and transient-prompt recovery before Enter, subsequent hook and command execution, editor-interrupt recovery, background and frozen job preservation, and foreground cancellation The regression test emitted no shell-integration OSC or application-mode reset sequences ## Additional notes The command-boundary recovery retains a short race for a SIGINT arriving after Enter but before the reset This is a trade-off to recover editor interruptions, not a claim that the race is eliminated One initial baseline PTY launch in this follow-up timed out after 30 seconds without output, while the rerun and updated-binary probes passed The earlier validation also recorded one 60-second PTY startup timeout The causes were not established and the passing reruns do not erase those observations This reproduction did not demonstrate actual job deletion, so this PR does not claim to resolve every scenario in #18989 or close that issue Windows and Linux runtime validation is deferred to GitHub CI and is not included in the local results above

Summary
$env.PROMPTclosure is exited prematurely #18989 by preserving REPL background and frozen jobs during foregroundCtrl-C, while non-REPL commands and scripts clean up jobs even when an interruption is caught-iwith an interactive REPL; explicitexitin-i -cor-iscript preserves requested exit code, while REPL retains first-exit warning and second-exit cleanupThreadJobshutdown under the PID lock to eliminate an orphan-process raceis_replflag in background job engine clones soexitterminates their closure instead of warning and continuingCREATE_NEW_PROCESS_GROUPandCREATE_NO_WINDOWinsideForegroundChildwithout an extra exported preparation helper; new process groups isolateCtrl-CbutCtrl+Breakis NOT isolatedabsolute_withUser-facing changes (Release notes)
Background jobs survive Ctrl-C in the REPL, and are cleaned up when a script exits
job spawnor frozen jobs. They keep running and stay listed injob list.nu -cor a script exits, including after Ctrl-C, its background jobs are terminated instead of being left behind. Ctrl-C also terminates the jobs of anu --mcp,--lspor--dapserver.exit <code>innu -i -c "..."ornu -i script.nunow exits with that code. Only the REPL keeps the "press exit again" warning on the firstexitwith running jobs.exitinside a background job's closure now ends that job, instead of printing the REPL warning and continuing.Testing
Verified on macOS on top of
ca323a65bdb7c945488b75a5f7bf5d90a8f3bff1:ThreadJobtests, and 47 root unit tests passed--no-fail-fastfornu-protocol,nu-engine,nu-command,nu-system,nu-cli; all passed except one existingcpdebug test-i -c "exit 3"returns 3 without running subsequent codecargo fmt --all --checkpassed-D warningson--all-targetsfornu,nu-protocol,nu-engine,nu-command,nu-system,nu-cli--bin nunu-command,nu-engine,nu-protocol,nu-systemnu-engine,nu-protocol,nu-systemlibrariesRemaining validation
Open verification limits and pending checks:
cpdebug test expectsreflink: unsupportedbut this macOS returnsreflink: yes, confirmed identically on original published headca323a65bdb7c945488b75a5f7bf5d90a8f3bff1cargo check --no-default-features --all-targetsfails on existingnu-plugin-engineServerCommunicationIo::LocalSocketnon-exhaustive match, reproduced in an isolated original-head source and target treeGenerateConsoleCtrlEventintegration test is still missing andping -treproduction has not been performed; compile-only Windows checks do not establish runtime behavior, so Windows review remains open