Skip to content

Preserve REPL background jobs on Ctrl-C and clean up jobs on non-REPL exit - #19163

Merged
fdncred merged 6 commits into
nushell:mainfrom
akasakariko:fix/18989-prompt-job-interrupt
Oct 16, 2026
Merged

fdncred merged 6 commits into
nushell:mainfrom
akasakariko:fix/18989-prompt-job-interrupt

Conversation

@akasakariko

@akasakariko akasakariko commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Addresses Handle to background job is dropped if $env.PROMPT closure is exited prematurely #18989 by preserving REPL background and frozen jobs during foreground Ctrl-C, while non-REPL commands and scripts clean up jobs even when an interruption is caught
  • Determine execution mode once (REPL, command, script, server) without conflating -i with an interactive REPL; explicit exit in -i -c or -i script preserves requested exit code, while REPL retains first-exit warning and second-exit cleanup
  • Serialize OS process creation and PID registration against ThreadJob shutdown under the PID lock to eliminate an orphan-process race
  • Clear cloned is_repl flag in background job engine clones so exit terminates their closure instead of warning and continuing
  • Centralize forced cleanup and lock-poison recovery, completing non-REPL cleanup before publishing interrupts while preserving early signal-handler initialization
  • Windows combines CREATE_NEW_PROCESS_GROUP and CREATE_NO_WINDOW inside ForegroundChild without an extra exported preparation helper; new process groups isolate Ctrl-C but Ctrl+Break is NOT isolated
  • Cross-platform lifecycle tests use Nu as the child, bounded handshakes and Windows owned process handles opened before child exit to avoid PID reuse
  • Add tests for lock registration, chained spawns, explicit exit, REPL two exits and background exit; remove fixed 500ms sleep
  • Fix minimal-feature plugin-only import warning for absolute_with

User-facing changes (Release notes)

Background jobs survive Ctrl-C in the REPL, and are cleaned up when a script exits

  • Pressing Ctrl-C to stop a foreground command in the REPL no longer kills background jobs from job spawn or frozen jobs. They keep running and stay listed in job list.
  • When nu -c or a script exits, including after Ctrl-C, its background jobs are terminated instead of being left behind. Ctrl-C also terminates the jobs of a nu --mcp, --lsp or --dap server.
  • exit <code> in nu -i -c "..." or nu -i script.nu now exits with that code. Only the REPL keeps the "press exit again" warning on the first exit with running jobs.
  • exit inside a background job's closure now ends that job, instead of printing the REPL warning and continuing.
  • Fixed a race where killing a job while it was spawning an external command could leave that process orphaned.
  • On Windows, externals started from a job run in their own process group, so Ctrl-C in the console no longer reaches them. Ctrl+Break still does.

Testing

Verified on macOS on top of ca323a65bdb7c945488b75a5f7bf5d90a8f3bff1:

  • 29 background job regressions, 3 ThreadJob tests, and 47 root unit tests passed
  • Shell suite: 320 passed, 6 ignored
  • Related crate tests and doctests ran with --no-fail-fast for nu-protocol, nu-engine, nu-command, nu-system, nu-cli; all passed except one existing cp debug test
  • Chained-spawn stress test produced 0/1000 leaks versus 5/50 on original head; -i -c "exit 3" returns 3 without running subsequent code
  • cargo fmt --all --check passed
  • Clippy passed with -D warnings on --all-targets for nu, nu-protocol, nu-engine, nu-command, nu-system, nu-cli
  • Minimal-feature check passed for --bin nu
  • WASM target checks passed for nu-command, nu-engine, nu-protocol, nu-system
  • Windows cross-compilation check passed for nu-engine, nu-protocol, nu-system libraries

Remaining validation

Open verification limits and pending checks:

  • Local cp debug test expects reflink: unsupported but this macOS returns reflink: yes, confirmed identically on original published head ca323a65bdb7c945488b75a5f7bf5d90a8f3bff1
  • cargo check --no-default-features --all-targets fails on existing nu-plugin-engine ServerCommunicationIo::LocalSocket non-exhaustive match, reproduced in an isolated original-head source and target tree
  • Windows real-console GenerateConsoleCtrlEvent integration test is still missing and ping -t reproduction has not been performed; compile-only Windows checks do not establish runtime behavior, so Windows review remains open
  • Updated GitHub CI validation is pending publication

Copilot AI 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.

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 High severity

Open (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.

Comment thread src/signals.rs Resolved

@fdncred fdncred 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.

Review notes below from my clanker.

The first two change behavior (Windows, and error exits that skip job cleanup). The rest are about the tests and some cleanup.

Comment thread src/signals.rs Resolved
Comment thread src/signals.rs Resolved
Comment thread src/main.rs Resolved
Comment thread tests/shell/mod.rs Resolved
Comment thread src/signals.rs Resolved
Comment thread src/main.rs Resolved
Comment thread src/main.rs Resolved
Comment thread src/signals.rs Resolved
Comment thread tests/shell/mod.rs Resolved
Comment thread src/main.rs Resolved
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 fdncred 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.

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.

Comment thread crates/nu-engine/src/exit.rs Resolved
Comment thread src/main.rs Resolved
Comment thread crates/nu-engine/src/exit.rs Resolved
Comment thread src/main.rs Resolved
Comment thread src/main.rs Resolved
Comment thread tests/shell/background_jobs.rs Resolved
Comment thread tests/shell/background_jobs.rs Resolved
@akasakariko akasakariko changed the title Preserve background and frozen jobs on interactive Ctrl-C interrupts Preserve REPL background jobs on Ctrl-C and clean up jobs on non-REPL exit Oct 11, 2026
@akasakariko

akasakariko commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated with c3c2ddb

  • Merged main at d211796 and resolved the src/main.rs conflict
  • Preserved the PR's RunMode dispatch and upstream MCP HTTP allowed-hosts and allowed-origins configuration
  • The resolved branch also merges cleanly with the subsequently published main at f5affec, checked with git merge-tree

Local validation

Validated the committed tree on macOS with Rust 1.97.1

  • Background job regression executable: 29 passed
  • cargo test --locked -p nu-protocol --lib engine::jobs -- --test-threads=4: 3 passed
  • cargo test --locked -p nu --bin nu -- --test-threads=4: 53 passed
  • cargo test --locked -p nu --test tests shell:: -- --test-threads=4: 306 passed, 6 ignored
  • Related crate tests and doctests ran with --no-fail-fast for nu-protocol, nu-engine, nu-command, nu-system, nu-cli, and nu-mcp, including 28 passing MCP tests
  • After building missing test helper binaries and removing proxy variables from the test subprocess environment, the full nu-command integration rerun had 3621 passed, 1 failed, and 45 ignored
  • cargo fmt --all --check: passed, including a fresh check before committing
  • cargo clippy --offline --locked -p nu -p nu-protocol -p nu-engine -p nu-command -p nu-system -p nu-cli -p nu-mcp --all-targets -- -D warnings: passed
  • cargo check --locked --no-default-features --bin nu: passed
  • cargo check --locked --target wasm32-unknown-unknown --no-default-features --lib -p nu-command -p nu-engine -p nu-protocol -p nu-system: passed
  • cargo check --locked --target x86_64-pc-windows-msvc --lib -p nu-engine -p nu-protocol -p nu-system: passed, compile-only

Native test executables were run from byte-identical copies on the local temporary volume after execution on the external build volume stalled
Source and build trees remained on the external volume, and no test assertions or platform security settings were changed

Still open

  • commands::ucp::test_cp_debug_default expects reflink: unsupported but this macOS reports reflink: yes
  • cargo check --locked --no-default-features --all-targets fails with E0004 for ServerCommunicationIo::LocalSocket in nu-plugin-engine
  • Both failures match the limitations already documented in the PR, but this update did not rebuild an independent baseline
  • Windows real-console GenerateConsoleCtrlEvent coverage and the ping -t reproduction are still missing, so cross-compilation does not resolve the Windows runtime review
  • The local typos check was not run because the executable is unavailable
  • GitHub Continuous Integration, Typos, and Security audit workflows are blocked with action_required, with no jobs started, so maintainer action is needed before CI can validate this commit
  • CI run: https://github.com/nushell/nushell/actions/runs/38662464477

@fdncred

fdncred commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Please reply to each review comment to ensure we didn't miss anything

@akasakariko

Copy link
Copy Markdown
Contributor Author

Replied individually to all 10 outstanding review threads with the corresponding changes in 8b5f9a0dd and the remaining verification limits

Leaving the threads open for your confirmation; Windows real-console Ctrl-C coverage remains explicitly unverified

@fdncred

fdncred commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

You'll need to merge main/rebase on main to get the CI green too.

@akasakariko

Copy link
Copy Markdown
Contributor Author

Synced with main at 818d4ac06 in ab7775383

Resolved the Cargo.toml conflict by retaining both the Windows /c dependency and the existing Windows test dependencies

Validation

  • Background-job regression tests: 29 passed
  • Prompt-push regression tests: 2 passed
  • Full tests for nu, nu-cli, nu-command, nu-engine, nu-protocol and nu-system: 7818 passed, 70 ignored
  • cargo fmt --all --check, cargo nuclippy, typos 1.51.1, WASM check and Windows core-library check passed
  • cargo audit: no vulnerabilities, 4 non-blocking warnings

The full test rerun used [::1] in NO_PROXY and a temporary directory on the repository volume to resolve local proxy and cross-volume copy failures, without changing tests or assertions

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

@fdncred
fdncred merged commit 356e7bc into nushell:main Oct 16, 2026
12 checks passed
@fdncred fdncred added notes:fixes Noted in "Bug fixes" section notes:ready Indicates Ready for Release notes labels Oct 16, 2026
@github-actions github-actions Bot added this to the v0.117.0 milestone Oct 16, 2026
akasakariko added a commit to akasakariko/akasakariko that referenced this pull request Oct 16, 2026
fdncred pushed a commit that referenced this pull request Oct 24, 2026
## 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

notes:fixes Noted in "Bug fixes" section notes:ready Indicates Ready for Release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants