Skip to content

✨ Add configurable process shutdown policies - #230

Open
taras wants to merge 6 commits into
mainfrom
agent/process-exited
Open

✨ Add configurable process shutdown policies#230
taras wants to merge 6 commits into
mainfrom
agent/process-exited

Conversation

@taras

@taras taras commented Aug 7, 2026

Copy link
Copy Markdown
Member

Motivation

Closes #228.

Process.join() and Process.expect() wait for Node's child-process close
event, so a descendant that retains inherited stdout or stderr can keep process
teardown pending after the direct command exits. Shutdown needs an
application-defined way to decide whether that remaining lifetime is expected
or should be forcefully reclaimed. A fixed timeout cannot represent process
health, drain state, descendant ownership, or other application context.

Approach

  • Add shutdown: "graceful" | "forced" | ProcessShutdownPolicy to exec()
    options; omission remains graceful.
  • Keep graceful shutdown cooperative: SIGTERM for the POSIX process group, or
    Ctrl-C plus stdin closure on Windows.
  • Make forced shutdown immediate: SIGKILL on POSIX or taskkill /T /F on
    Windows.
  • Let a generator policy run after graceful shutdown begins and return either
    "graceful" or "forced".
  • Give process policies an eager, replayable { exit } operation containing the
    direct command's ExitStatus, without exposing it as a second public Process
    lifetime API.
  • Race a dynamic policy against complete process and stdio closure. Normal
    closure cancels a pending policy; "graceful" keeps waiting; "forced"
    escalates. A policy error also escalates so teardown cannot strand the tree.
  • Keep Windows taskkill in a teardown-owned task so cancellation of the policy
    that selected it cannot cancel hard termination.
  • Document the contract and bump @effectionx/process from 0.8.1 to 0.9.0.
owning scope shuts down
|
+-- omitted / "graceful"
|   request graceful shutdown
|   `-- await process + captured stdio closure
|
+-- "forced"
|   force-terminate the process tree
|   `-- await process + captured stdio closure
|
`-- generator policy
    request graceful shutdown
    race complete closure against policy decision
    |
    +-- closure wins -------- cancel policy; finish gracefully
    +-- policy: "graceful" -- keep awaiting complete closure
    `-- policy: "forced" --- force tree; await complete closure

The dynamic form can observe both process and application state without an
arbitrary grace period:

const process = yield* exec(command, {
  *shutdown({ exit }) {
    const status = yield* exit;
    const state = yield* shutdownState.expect();

    yield* state.untilForceIsRequired(status);
    return "forced";
  },
});

If descendants finish and release captured output while
untilForceIsRequired() is pending, the policy is canceled and teardown ends
gracefully.

Explicit non-goals

  • This PR does not add Exec.join({ settle: "exit" }), now or as a planned
    follow-up.
  • This PR does not change or discourage yield* yield* exec().
  • This PR does not expose Process.exited(); direct exit is policy state, not a
    second meaning for the public Process operation.
  • This PR does not introduce the fixed one-second fallback from 🐛 Bound Windows process shutdown #231.

Validation

  • pnpm test — 386 passed, 6 skipped
  • pnpm test process/test/exec.test.ts — 29 passed
  • pnpm check
  • pnpm build
  • pnpm lint
  • pnpm fmt:check
  • pnpm sync
  • git diff --check

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@taras, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 56 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 104ff7ef-263e-44d0-a4e3-7d088024fbbb

📥 Commits

Reviewing files that changed from the base of the PR and between f311298 and 7e4f2b8.

📒 Files selected for processing (9)
  • process/CHANGELOG.md
  • process/README.md
  • process/src/exec/posix.ts
  • process/src/exec/shutdown.ts
  • process/src/exec/types.ts
  • process/src/exec/win32.ts
  • process/test/exec.test.ts
  • process/test/fixtures/ignore-shutdown.ts
  • process/test/fixtures/shutdown-stdio-descendant.ts
📝 Walkthrough

Walkthrough

The process API adds Process.exited() for direct-child exit observation without waiting for stdio closure. POSIX and Windows implementations also support configurable shutdown middleware and forced process-tree termination. Tests cover exit replay, spawn errors, inherited stdio, and shutdown behavior.

Changes

Process lifecycle

Layer / File(s) Summary
API contract and documentation
process/src/exec/types.ts, process/README.md, process/CHANGELOG.md, process/package.json
The public API adds exited() and optional shutdown middleware. Documentation distinguishes exit observation from close-settled join() and expect(). The package version is updated to 0.9.0.
Platform exit and shutdown handling
process/src/exec/posix.ts, process/src/exec/win32.ts, process/src/exec/shutdown.ts
Both implementations track exit separately from close, replay exit results and spawn errors, and expose exited(). Shutdown handling can race closure, invoke middleware, and force-terminate when required.
Lifecycle validation
process/test/exec.test.ts, process/test/fixtures/*
Tests cover exit-status replay, spawn-error replay, inherited stdio, middleware context access, process-tree termination, and shutdown cancellation. Fixtures model persistent descendants and shutdown-resistant processes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant ProcessImplementation
  participant ChildProcess
  participant ShutdownMiddleware
  Caller->>ProcessImplementation: exited()
  ChildProcess-->>ProcessImplementation: exit event
  ProcessImplementation-->>Caller: ExitStatus
  Caller->>ProcessImplementation: shutdown handling
  ProcessImplementation->>ShutdownMiddleware: provide ProcessShutdownApi
  ShutdownMiddleware->>ProcessImplementation: shutdown()
  ProcessImplementation->>ChildProcess: terminate process tree
  ChildProcess-->>ProcessImplementation: close after stdio closure
Loading

Possibly related PRs

Suggested reviewers: cowboyd

🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements Process.exited(), but it also changes Windows teardown despite issue #228 requiring that work in a separate PR. Separate the Windows teardown changes from this PR, or update issue #228 to explicitly include them.
Out of Scope Changes check ⚠️ Warning Shutdown middleware, termination APIs, and related POSIX and Windows teardown changes exceed the linked issue's Process.exited() API scope. Remove the shutdown-policy and teardown changes, or link an issue that explicitly requires this broader scope.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Policy Compliance ✅ Passed The changed package has valid description and keywords, version 0.8.1→0.9.0 matches the feature, and PR commits contain no prohibited AI-marketing trailers or footers.
Title check ✅ Passed The title is concise and clearly describes the configurable process shutdown policy changes.
Description check ✅ Passed The description includes both required sections and provides detailed motivation, approach, non-goals, and validation results.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/process-exited

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Aug 7, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@effectionx/process@230

commit: 7e4f2b8

@taras
taras requested a review from cowboyd August 7, 2026 12:18
@taras
taras marked this pull request as ready for review August 7, 2026 12:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@process/src/exec/posix.ts`:
- Around line 116-123: Declare the return type of the exited generator in
process/src/exec/posix.ts (lines 116-123) as Operation<ExitStatus>. Apply the
same explicit return type to the corresponding exited generator in
process/src/exec/win32.ts (lines 138-145), preserving their existing behavior.

In `@process/src/exec/types.ts`:
- Around line 21-32: Document the spawn-error contract for Process.exited()
consistently: in process/src/exec/types.ts lines 21-32, update the exited()
JSDoc to state that spawn failures reject the operation and that evaluating it
again replays the same error; in process/README.md lines 137-165, add this
failure and replay behavior to the lifecycle documentation; and in
process/README.md lines 252-258, include the same behavior in the Process
interface summary.

In `@process/test/exec.test.ts`:
- Around line 76-98: Update the test imports used by the “.exited” test suite to
use the Node.js test runner utilities from `@effectionx/bdd` instead of
Vitest-backed describe, it, and expect, while preserving the existing test
behavior and assertions.

In `@process/test/fixtures/stdio-descendant.ts`:
- Around line 4-13: Make the descendant fixture expose a deterministic
termination mechanism for the spawned interval process, while preserving its
inherited stdio and exit behavior. In process/test/fixtures/stdio-descendant.ts
lines 4-13, add the mechanism and ensure the descendant can be terminated; in
process/test/exec.test.ts lines 101-119, invoke it from a finally path and await
descendant cleanup before the test returns so all async work is scope-owned.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 7369afd8-9cfb-45e3-a887-4d125e3af549

📥 Commits

Reviewing files that changed from the base of the PR and between d1ecfeb and 7d256a1.

📒 Files selected for processing (8)
  • process/CHANGELOG.md
  • process/README.md
  • process/package.json
  • process/src/exec/posix.ts
  • process/src/exec/types.ts
  • process/src/exec/win32.ts
  • process/test/exec.test.ts
  • process/test/fixtures/stdio-descendant.ts

Comment thread process/src/exec/posix.ts Outdated
Comment thread process/src/exec/types.ts Outdated
Comment thread process/test/exec.test.ts Outdated
Comment thread process/test/fixtures/stdio-descendant.ts Outdated
@taras
taras requested a review from jbolda August 7, 2026 12:57
@taras taras changed the title ✨ Add process exit observation ✨ Add process lifecycle observation and shutdown policies Aug 7, 2026
@taras taras changed the title ✨ Add process lifecycle observation and shutdown policies ✨ Add configurable process shutdown policies Aug 8, 2026
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.

process: no way to observe exit — join() settles on close (exit + stdio EOF), which can outlive the command

1 participant