Skip to content

fix: stop background jobs when the shell is dropped or wait is cancelled - #258

Merged
ferdingler merged 5 commits into
strands-agents:mainfrom
ferdingler:fix/abort-background-jobs-on-drop
Nov 13, 2026
Merged

ferdingler merged 5 commits into
strands-agents:mainfrom
ferdingler:fix/abort-background-jobs-on-drop

Conversation

@ferdingler

@ferdingler ferdingler commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A job started with & keeps running after the shell that started it is gone. If you drop the shell, or cancel a run while it's sitting in wait, the job carries on in the background and keeps reading and writing files and starting programs until it ends on its own. For an embedder that runs many shells on one long-lived runtime, that means a cancelled request can keep doing work long after the caller gave up on it.

Now the shell owns every background job it starts, including ones started inside a subshell or from Lua's os.execute and io.popen, and stops them when it's dropped. That includes a pipeline running inside a job, like loop | cat &. A cancelled wait stops the jobs it was waiting for. This applies whether or not a command handler is set. Otherwise nothing changes: an open shell keeps its jobs between calls, a job started in a subshell still outlives that subshell, and & and wait behave as before. No public API changes.

I checked dropping the shell and cancelling wait with jobs that never finish, with background loops that append to a file, with those loops piped into another command, and with jobs started from Lua. Each one fails on main and passes with the change. The full Rust suite, the docs build, fmt and clippy pass locally, with no new warnings. I didn't run the Python or Node suites locally, so I'm relying on CI for those.

Related Issues

N/A

Documentation PR

N/A

Type of Change

Bug fix

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.

  • I ran the relevant test suites for the bindings I touched (cargo test --workspace --all-targets, pytest tests/python, npm test)
  • If I touched Rust, I ran cargo fmt and cargo clippy

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

A background job is a detached task. When a caller drops a Shell, or
cancels a run that is in `wait`, the job continues to run and its effects
continue to reach the kernel.

The Shell now owns the background jobs that its process and the forks of
that process start, and aborts them when it drops. A cancelled `wait`
aborts the jobs that it took. An open shell keeps its jobs across calls,
and `&` and `wait` behave as before.
@ferdingler
ferdingler requested a review from a team as a code owner November 12, 2026 23:21
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent please review

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested: the fix works for plain & jobs, but two common shapes still keep running after the shell is dropped. @ferdingler

I reviewed head 6058441. Plain & jobs, functions, eval, source, subshells and the cancelled-wait path all stop as the PR says, and both new tests fail if the fix is removed. CI is green. These two still escape:

  1. 🟡 A pipeline inside a background job keeps running after drop. Repro: loop | cat &. With the default kernel the stages aren't owned by anything, so aborting the job leaves them running. Details on exec.rs:2155.
  2. 🟡 Jobs started from Lua os.execute / io.popen are never owned. They run in a process built with Process::new, which has no owner. Details on os.rs:381.

On main nothing was stopped, so neither is a regression. But the PR says the shell owns "every background job it starts", and cmd | cat & is the kind of job an embedder will hit.

✅ What I verified, routing, questions, appendix

Routing. I ran two passes: a correctness reviewer, and an adversarial tester with repros. The change touches concurrency and cancellation, so it warranted the second. I skipped the API pass because there's no public surface change: Tasks, own_background_jobs and add_background_job are all pub(crate), and no tool, prompt or doc text is touched. No docs change is needed.

Verified at 6058441, in a clean git archive copy:

  • cargo test --test command_fallback --test shell_integration: 23/23 and 1773 passed. The 4 failures are *_from_cli tests that need the CLI binary, which isn't built under --no-default-features.
  • Removing the fix makes the new tests fail. I tried two ways: dropping _cancel in wait.rs, and resetting background_owner in fork. Both new command_fallback tests fail either way.
  • 25 adversarial repros. Stopped on drop: about 25 shapes, including blocked &, (blocked &), { … & }, functions, eval, source/., nested subshells, &&/||, and fallback-kernel pipelines. Also fine: a cancelled wait (including wait $!, and nested waits that cascade), dropping outside a LocalSet or after the runtime is gone (no panic), and a job aborted mid host write (no hang on the next run).
  • Still running: pipelines in & jobs on the default kernel (loop | cat &, f | cat &, (loop | cat) &, (loop) | cat &; a cancelled wait on loop | cat & wait went from 18 to 35 bytes), and Lua os.execute/io.popen jobs (1 to 18 bytes after drop).
  • Repros and logs are uploaded as PR artifacts: adv-repros.rs, adv-repros.log, reviewer-scratch.rs.

Questions (non-blocking)

  • Foreground stage cancellation (ForegroundTasks) only applies when a command fallback is set; without_a_handler_dropping_run_keeps_legacy_task_ownership pins that. Background abort here applies to every shell. Is that difference intended? I think it's the right call for background jobs, but the PR body's "nothing else changes" undersells it. Embedders without a handler will now see jobs die on drop.

Reading order: src/os.rs (Tasks, own_background_jobs, add_background_job, fork), then src/shell.rs, then src/builtins/wait.rs, then the tests.

Appendix: non-blocking (3)

  • ⚪ Tasks (src/os.rs:20-38) is nearly identical to ForegroundTasks (src/exec.rs:16-40), which also aborts its handles on drop. One could build on the other.
  • ⚪ Add regression tests for both findings, next to dropping_the_shell_stops_a_background_loop: a | cat & case and a Lua os.execute case. Also a default-kernel cancelled-wait test; the current ones only use a fallback kernel.
  • ⚪ src/mcp.rs:387 builds a process with no owner the same way. I didn't count it as a finding: the MCP server's runtime ends when serve_io returns, so no job outlives it.

Comment thread src/exec.rs Resolved
Comment thread src/os.rs Resolved
ferdingler and others added 3 commits November 12, 2026 16:53
A pipeline inside a `&` job kept running after the shell dropped or `wait` was cancelled, because the job owned its stages only when the kernel has a command fallback. A background job now owns its stages on every kernel. dropping_the_shell_stops_a_background_pipeline and cancelling_wait_stops_a_background_pipeline pin this.
Lua built the child process with Process::new, so a `&` job it started had no owner and kept running after the shell dropped. The child now takes the owner and the background-job flag of the lua process. dropping_the_shell_stops_a_lua_background_job pins this.
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent please review

@ferdingler

Copy link
Copy Markdown
Collaborator Author

On the question: yes, the difference is intended. A background job has no caller left to wait for it once the shell drops, so it stops on every kernel. Foreground stages without a handler keep the legacy ownership, which without_a_handler_dropping_run_keeps_legacy_task_ownership pins. I also left mcp.rs as it is, for the reason you gave.

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve: both findings from my last review are fixed at 3972d59, and I found nothing new. @ferdingler

  • ✅ Pipelines inside a & job (800888d): fixed. Every repro from last time (loop | cat &, f | cat &, (loop | cat) &, (loop) | cat &, and a cancelled wait on a pipeline) now stops on drop.
  • ✅ Lua os.execute / io.popen jobs (3972d59): fixed. Both now stop on drop, with the default kernel and with a fallback kernel.
  • ✅ Question about no-handler shells: answered by the updated PR body ("applies whether or not a command handler is set").
What I checked
  • I re-ran my 25 adversarial repros against a clean git archive of 3972d59. All 7 that failed before now pass. 3 still fail: (blocked &) | cat and x=$(blocked &). Those failed at 6058441 too, and they're bash-like: the job inherits the pipe, so the reader waits for it. Not a regression.
  • Suites: lib 72/72, command_fallback 23/23, lua_integration 228/228, shell_integration 1926/1926. One CLI test first failed against a stale binary in my sandbox; with the cli feature built, the 4 *_from_cli tests pass.
  • Mutation check: I commented out sub.in_background_job = true and both sub_proc.background_owner = owner lines. The 3 new tests fail (dropping_the_shell_stops_a_background_pipeline, cancelling_wait_stops_a_background_pipeline, dropping_the_shell_stops_a_lua_background_job), then pass again once the change is reverted.
  • I tried to break the fix itself:
    • All 3 ForegroundTasks::new call sites pass proc.
    • concurrent_stderr is still gated on the fallback only, so foreground stderr behaviour without a handler is unchanged.
    • run_pipeline awaits every stage before it returns (exec.rs:3858-3864), so tracking stages inside a background job doesn't cut off a job that finishes normally.
    • The other spawn_local sites in vfs_kernel.rs drain file writes, and they finish once the aborted job drops its writers.
  • CI on 3972d59 is green.

@ferdingler
ferdingler merged commit 56c518e into strands-agents:main Nov 13, 2026
32 checks passed
@ferdingler
ferdingler deleted the fix/abort-background-jobs-on-drop branch November 13, 2026 02:01
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