Skip to content

Fix try/finally: finally block now runs on Ctrl+C/SIGINT in script mode - #3

Closed
WindSoilder with Copilot wants to merge 5 commits into
mainfrom
copilot/fix-try-finally-sigint-handling
Closed

WindSoilder with Copilot wants to merge 5 commits into
mainfrom
copilot/fix-try-finally-sigint-handling

Conversation

Copilot AI commented May 2, 2026 •

Copy link
Copy Markdown
  • Investigate the problem: try { ^sleep 3 } finally { ... } not running finally on Ctrl+C
  • Verify existing fixes (previous sessions) handle the core issue in eval_ir.rs and ir/mod.rs
  • Confirm all 43 existing tests pass
  • Add try_finally_runs_when_external_command_receives_sigint test covering the exact problem scenario (SIGINT to entire process group, matching real terminal Ctrl+C behavior)
  • Fix constant naming consistency between the two SIGINT integration tests
  • All 44 tests pass
Original prompt

Create a fix for nushell try/finally so that the finally block runs when a script is interrupted via Ctrl+C/SIGINT during an external command.

Context:

Repository:

  • Target repo: WindSoilder/nushell
  • Base branch: main

Tasks:

  1. Reproduce understanding from code: identify the difference between REPL vs script execution Ctrl+C handling and how interrupts propagate through pipeline/external execution.
  2. Implement a fix so that SIGINT/Ctrl+C while running a script does NOT abort the whole process immediately but is translated into an engine-level interrupt (ShellError::Interrupted or equivalent) that allows stack unwinding and finally execution.
    • Ensure that this does not regress the explicit exit --abort behavior (which should still skip finally).
    • Ensure external commands are properly terminated on interrupt.
  3. Add regression tests:
    • A test that runs a script or nu! invocation with a long-running external (or nu --testbin helper) and triggers Ctrl+C/interrupt, asserting that finally output occurs and cleanup happens.
    • If the existing test harness can’t send real SIGINT reliably on Windows, implement a deterministic test using the engine’s signal handling primitives (triggering the shared ctrlc flag / Signals) to simulate interrupt during external execution.
  4. Update any relevant docs/comments if needed.

Acceptance criteria:

  • finally runs when a script is interrupted during an external command.
  • Behavior remains correct for normal errors and for exit --abort.
  • Tests pass.

Reference issue: nushell#18090

The following is the prior conversation context from the user's chat exploration (may be truncated):

User: Do you have any idea how to fix the issue? It works fine in repl, but it doesn't work while running script

Assistant: It’s very likely not the try/finally implementation itself, but the script runner’s Ctrl+C/SIGINT behavior: when running a .nu file, Nushell ends up terminating the whole process immediately, so the engine never gets a chance to unwind and run finally. In the REPL, Ctrl+C is typically handled “in-process” (set an interrupt flag, cancel the running pipeline, then return to the prompt), so finally can still run.

There’s a strong hint of this difference in run_file():

let result = evaluate_file(/*...*/);

if let Err(err) = result {
    report_shell_error(Some(&stack), engine_state, &err);
    std::process::exit(err.exit_code().unwrap_or(0));
}

If Ctrl+C during an external command is currently treated like an “abort the whole process now” path (or the OS delivers SIGINT in a way that kills the parent nu when running non-interactively), finally won’t run because the interpreter never resumes.

What a real fix in Nushell probably looks like

Goal: on Ctrl+C during script execution, Nushell should convert the signal into a normal engine-level “interrupt”/cancellation result, not an immediate process termination, so the interpreter can unwind and run finally, then exit.

Concretely, the fix is usually some combination of:

  1. Ensure Ctrl+C is always captured by Nushell (sets engine_state.signals().interrupted() / triggers signal handlers) instead of killing the process outright.
  2. When an external is interrupted, return an interrupt error to the evaluator (something like ShellError::Interrupted), not “abort the process”.
  3. Make the evaluator’s try { … } finally { … } path run finally not only for regular errors, but also for the interrupt error (unless it is explicitly an “abort” kind of exit).
  4. After finally finishes, propagate the interrupt (exit with 130, or whatever Nushell’s convention is).

There’s already an explicit notion of “abort means don’t run finally” in the tests:

#[test]
fn try_abort_not_run_finally() {
    let actual = nu!("try { exit 3 --abort} finally { print 'this finally' }");
    assert!(!actual.out.contains("this finally"));
    assert_eq!(actual.status.code(), Some(3));
}

So Ctrl+C is currently behaving more like “abort” in script mode, which is exactly the wrong semantic for try/finally.

A minimal thing to add (to prove/fix it)

Add a test that reproduces the bug at the engi...

This pull request was created from Copilot chat.

- In eval_ir.rs: add ShellError::Interrupted handling that bypasses
  catch blocks and jumps directly to the finally block, mirroring the
  Return/Exit behavior. Also reset the interrupt flag when jumping to
  any finally block so the finally block's instructions can execute.

- In tester/mod.rs: add with_signals() and add_command() builder
  methods to NuTester for deterministic interrupt testing.

- In try_.rs: add three regression tests:
  1. try_finally_runs_on_interrupt (deterministic, in-process)
  2. try_catch_finally_finally_runs_on_interrupt (deterministic, in-process)
  3. try_finally_runs_when_script_receives_sigint (Unix integration test)

Agent-Logs-Url: https://github.com/WindSoilder/nushell/sessions/a8cd72bc-56d5-49ca-9d49-28b23f7469a6

Co-authored-by: WindSoilder <[email protected]>
Copilot AI changed the title [WIP] Fix try/finally to run finally block on SIGINT during external command Fix try/finally: finally block now runs on Ctrl+C/SIGINT in script mode May 2, 2026
Copilot AI requested a review from WindSoilder May 2, 2026 14:01
@WindSoilder WindSoilder closed this May 3, 2026
@WindSoilder WindSoilder reopened this May 3, 2026
Two root causes for catch not working on interrupt:

1. check_interrupt (ir/mod.rs) only fired at Jump/Return. For
   try { } catch { }, the success path is TryCollect → PopErrorHandler
   → Jump. The interrupt was detected at Jump, after PopErrorHandler
   had already removed the catch handler — making catch unreachable.
   Fix: add TryCollect to check_interrupt so the interrupt is detected
   before PopErrorHandler removes the catch/finally handlers.

2. The previous fix added an Interrupted arm that bypassed catch
   entirely. Fix: remove that arm; let Interrupted go through the
   generic Err(err) path which routes to catch when available.

3. The interrupt flag was not reset when entering the catch block,
   causing check_interrupt to fire again at the catch block's first
   instruction. Fix: reset signals when routing any error to catch
   (same as was already done for finally).

Also update try_catch_finally_finally_runs_on_interrupt test: catch
now correctly runs (and finally runs after it, result is Ok).

Agent-Logs-Url: https://github.com/WindSoilder/nushell/sessions/d068b029-f86c-4a4f-a79d-32f10e1c4c19

Co-authored-by: WindSoilder <[email protected]>
@WindSoilder WindSoilder closed this May 7, 2026
WindSoilder pushed a commit that referenced this pull request Jul 7, 2026
## Description

- nushell#16832

Errors raised for assignment errors did not point to the relevant
assignment, just pointed to the values origin.

## User-facing changes (Release notes)

### More helpful errors for failed assignments with
`enforce-runtime-annotations`

With `enforce-runtime-annotations` enabled, assignments with incorrect
types raise errors.

Previously this error was `nu::shell::cant_convert` originally used for
unsuccessful type coercions of command arguments. Unfortunately, this
error only pointed at the assigned values *origin* and not at the failed
assignment.

This error has been switched to `nu::shell::type_mismatch` and now
points to the failed assignment in addition to the value's origin.

##### example 1
<table>
<tr>
<td>Code</td>
<td width="1000">

```nushell
mut execution_time = -1
$execution_time = $env.CMD_DURATION_MS
```

</td>
</tr>

<tr>
<td>Before</td>
<td>

```
Error: nu::shell::cant_convert

  × Can't convert to int.
   ╭─[Host Environment Variables:1:1]
 1 │ "LANG"="en_US.UTF-8"
   · ▲
   · ╰── can't convert string to int
 2 │ "LC_TIME"="en_DK.UTF-8"
   ╰────
```

</td>
</tr>

<tr>
<td>After</td>
<td>

```
Error: nu::shell::type_mismatch

  × Type mismatch.
   ╭─[repl_entry #3:2:17]
 1 │ mut execution_time = -1
 2 │ $execution_time = $env.CMD_DURATION_MS
   ·                 ┬
   ·                 ╰── expected int, got string
   ╰────
```

</td>
</tr>
</table>

##### example 2
<table>
<tr>
<td>Code</td>
<td width="1000">

```nushell
# delibarete type erasure
# we need to bypass parse-time
# type checking for this example
let stuff: any = {
	foo: "bar"
}

mut x = 1

$x = $stuff.foo
```

</td>
</tr>

<tr>
<td>Before</td>
<td>

```
Error: nu:🐚:cant_convert

  × Can't convert to int.
   ╭─[repl_entry nushell#7:5:7]
 4 │ let stuff: any = {
 5 │     foo: "bar"
   ·          ──┬──
   ·            ╰── can't convert string to int
 6 │ }
   ╰────
```

</td>
</tr>

<tr>
<td>After</td>
<td>

```
Error: nu:🐚:type_mismatch

  × Type mismatch.
    ╭─[repl_entry #1:5:7]
  4 │ let stuff: any = {
  5 │     foo: "bar"
    ·          ──┬──
    ·            ╰── the value is a string
  6 │ }
  7 │ 
  8 │ mut x = 1
  9 │ 
 10 │ $x = $stuff.foo
    ·    ┬
    ·    ╰── expected int, got string
    ╰────
```

</td>
</tr>
</table>

## Additional notes

- This should make it much easier to diagnose problems described in
nushell#18528
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.

2 participants