Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): [Windows] bound child process shutdown #6318

ClosedDefmon3(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/6318/headopened View on GitHub

What Changed

On Windows, wrap the CLI child-process spawner with bounded shutdown behavior.

When a scoped child process does not stop after SIGTERM, T3 waits up to two seconds before escalating to forced process-tree termination. It then waits one additional second before allowing shutdown to continue with a warning.

The wrapper also:

  • bounds explicit handle.kill() calls;
  • preserves unref() as an opt-out from scope-owned termination;
  • leaves non-Windows process handling unchanged.

Why

A child process or descendant that fails to exit can otherwise prevent the T3 server from shutting down and leave its console host running.

This revisits the Windows shutdown behavior discussed in #3573 against the current server implementation. The change is limited to Windows and uses Effect's existing Windows process-tree termination behavior.

Verification

Run on Windows with Node 24:

vp test run apps/server/src/cli/boundedChildProcessSpawner.test.ts
vp run --filter t3 typecheck

The focused test suite covers:

  • natural child exit;
  • unref() behavior;
  • bounded explicit termination with forced escalation;
  • honoring an explicit forceKillAfter grace period;
  • stale exit-event state after the process is already gone;
  • scope closure when the underlying finalizer does not return;
  • termination of a real Windows parent process and its descendant.

Expected result:

  • Seven tests pass.
  • Server typecheck passes.

Checklist

  • This PR is small and focused
  • I explained what changed and why

Implemented with GPT-5.6 Sol through the Codex harness.

Note

Add bounded child process shutdown on Windows with SIGTERM/SIGKILL grace periods

  • Introduces BoundedChildProcessSpawner in boundedChildProcessSpawner.ts, which wraps the existing ChildProcessSpawner service to enforce a timed shutdown sequence: send an initial signal (default SIGTERM), wait a configurable grace period, escalate to SIGKILL if still running, and log a warning if the process still does not stop.
  • On Windows, server.ts merges BoundedChildProcessSpawner.layer into PlatformServicesLive, replacing the default spawner with the bounded implementation.
  • Explicit kill(options) calls while the caller scope is open are forwarded unchanged to the delegate; bounded shutdown only triggers on scope close or re-reference after scope close.
  • Behavioral Change: on Windows, child processes now receive SIGTERM before SIGKILL on shutdown rather than being killed immediately.
Macroscope summarized 97dd9fa.

Note

Medium Risk Touches core process lifecycle on Windows only, but mis-timed kills or scope/finalizer ordering could affect CLI children during shutdown or after unref.

Overview On Windows only, the server wraps Effect’s ChildProcessSpawner with BoundedChildProcessSpawner so scoped children cannot block shutdown indefinitely.

When the caller scope closes (or a child is re-referenced after close), the wrapper runs bounded termination: SIGTERM, wait up to 2s (termGraceMs), then SIGKILL with a 1s grace (killGraceMs). Signals are sent in a detached fiber so parent scope finalizers are not held on a stuck delegate cleanup. unref() still opts out of scope-driven kills; explicit kill() while the scope is open is forwarded unchanged.

PlatformServicesLive in server.ts composes this layer on top of Bun/Node platform services when isHostWindows is true; non-Windows behavior is unchanged.

Adds boundedChildProcessSpawner.test.ts (mocked lifecycle cases plus a Windows integration test for parent + descendant process trees).

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 97dd9fa05c15fe04f45596d8a297ccc558461191. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      This PR introduces a new Windows-specific child process management capability (~500 lines) that changes how processes are terminated with bounded shutdown behavior. New runtime behavior like process lifecycle management warrants human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: d4ca64a9-f3bb-4c7c-88c1-b581d9de0107

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      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.
    4. Reviewed the new boundedChildProcessSpawner service module, its layer wiring in bin.ts, and the accompanying test. The implementation follows the canonical module shape (imports, options, helpers, make, layer), acquires the delegate spawner from the Effect environment inside layer, and uses subpath namespace imports. One import-convention deviation in the test file is noted inline.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +1,15 @@
      1+import { NodeServices } from "@effect/platform-node";
      2+import { expect, it } from "@effect/vitest";
      3+import * as Deferred from "effect/Deferred";
      4+import * as Effect from "effect/Effect";
      5+import * as Exit from "effect/Exit";
      6+import * as Fiber from "effect/Fiber";
      7+import * as Layer from "effect/Layer";
      8+import * as Option from "effect/Option";
      9+import * as Scope from "effect/Scope";
      10+import * as Sink from "effect/Sink";
      11+import * as Stream from "effect/Stream";
      12+import { TestClock } from "effect/testing";
      13+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
      14+
      15+import { layer, make, type ChildProcessShutdownSignal } from "./boundedChildProcessSpawner.ts";

      This imports the service module's public members (make, layer) as bare named imports, which erases the module namespace at a service boundary. Consider import * as BoundedChildProcessSpawner from "./boundedChildProcessSpawner.ts"; and referring to BoundedChildProcessSpawner.make(...), BoundedChildProcessSpawner.layer(...), and BoundedChildProcessSpawner.ChildProcessShutdownSignal, matching bin.ts and the other service tests in apps/server/src (e.g. processRunner.test.ts, externalLauncher.test.ts).

      Posted via Macroscope — Effect Service Conventions
    5. The test that covers the behaviour this PR is named for does not report as skipped on other platforms, it reports as passed:

      it.effect("kills a Windows child process tree without blocking scope close", () => {
        if (process.platform !== "win32") return Effect.void;

      Running the file on Linux:

       ✓ closes the delegate scope after a natural child exit                        5ms
       ✓ preserves unref as an opt-out from scope-owned termination                   1ms
       ✓ bounds explicit handle kill calls and escalates to SIGKILL                   2ms
       ✓ respects an explicit force-kill grace period                                 4ms
       ✓ treats a missing pid as stopped when the delegate exit event is stale        1ms
       ✓ returns from scope close before the delegate finalizer can block             1ms
       ✓ kills a Windows child process tree without blocking scope close              0ms
      
       Tests  7 passed (7)

      The last line is a green check on a run where nothing executed. Anyone reading CI concludes the tree kill is covered. it.effect.skipIf(process.platform !== "win32") reports it as skipped instead, which is the honest signal and costs nothing.

      That matters more than usual here, because the tree kill is the only part that cannot be inferred from the other six tests. Those all drive a synthetic handle whose kill just pushes a string into an array, so they verify the escalation state machine rather than that anything dies. On Windows kill() terminates the process it targets, not its descendants, so whether descendantPid actually stops depends entirely on what the delegate spawner does underneath. Has the fixture test been run on a Windows machine? If it has, saying so in the PR body would help, since CI cannot show it.

      Smaller thing: shutdown takes childScope and never uses it.

      const shutdown = Effect.fn("BoundedChildProcessSpawner.shutdown")(function* (
        handle: ChildProcessSpawner.ChildProcessHandle,
        childScope: Scope.Closeable,
        isReferenced: () => boolean,
      ) {
        if (isReferenced()) {
          yield* kill(handle);
        }
      });

      The scope is closed by the exitCode fork instead, so the parameter looks like a leftover from an earlier shape. Worth dropping so it does not read as a missed cleanup path.

      Also worth a note: sendSignal forks the kill detached and Effect.ignores the result, so a kill that fails outright is indistinguishable from one that is merely slow. Both land on the same logWarning after the full grace window. Given the whole point is bounding shutdown, a failed signal is probably worth logging at the moment it fails rather than only after the timeout.

    6. One finding: the Windows branch in bin.ts selects the runtime layer from a module-scope process.platform read instead of acquiring the host platform from the Effect environment. boundedChildProcessSpawner.ts itself follows the conventions (subpath namespace imports, make + layer, delegate acquired from the environment in layer).

      Posted via Macroscope — Effect Service Conventions
      @@ -11,10 +11,12 @@
      1111 import { connectCommand } from "./cli/connect.ts";
      1212 import { pairCommand } from "./cli/pair.ts";
      1313 import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
      14+import * as BoundedChildProcessSpawner from "./cli/boundedChildProcessSpawner.ts";
      1415 import { sharedServerCommandFlags } from "./cli/config.ts";
      1516 import { projectCommand } from "./cli/project.ts";
      1617 import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
      1718 import { serviceCommand } from "./cli/service.ts";
      1819 import { servicePreflightCommand } from "./cli/servicePreflight.ts";
      1920
      20-const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
      21+const CliRuntimeLayer = Layer.mergeAll(
      22+ process.platform === "win32"
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      process.platform is read directly in module scope, so the host-platform dependency is hidden from the Effect environment (this is also the only process.platform read left in apps/server/src and the repo's no-global-process-runtime rule flags it). Consider selecting the layer inside the environment via HostProcessPlatform/isHostWindows with Layer.unwrap, matching PtyAdapterLive in server.ts.

      Requires adding import { isHostWindows } from "@t3tools/shared/hostProcess";.

      -const CliRuntimeLayer = Layer.mergeAll(
      -  process.platform === "win32"
      -    ? BoundedChildProcessSpawner.layer().pipe(Layer.provideMerge(NodeServices.layer))
      -    : NodeServices.layer,
      -  NetService.layer,
      -);
      +const CliRuntimeLayer = Layer.mergeAll(
      +  Layer.unwrap(
      +    Effect.map(isHostWindows, (isWindows) =>
      +      isWindows
      +        ? BoundedChildProcessSpawner.layer().pipe(Layer.provideMerge(NodeServices.layer))
      +        : NodeServices.layer,
      +    ),
      +  ),
      +  NetService.layer,
      +);
      Posted via Macroscope — Effect Service Conventions
    7. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c80a1233107e78afd556be06b46577c3927b0128. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. Closing because we are no longer able to reproduce the shutdown hang against current upstream's process handler.

      We ran 10 isolated Windows checks on Node 24.13.1 using Effect 4.0.0-rc.115, the version used by upstream main at 9ea9c3d5d. Scope closure, forceKillAfter, and explicit kill all completed without a hang or timeout, including cases with parent and descendant processes.

      These checks exercised the process handler, not a full server or provider shutdown, so this does not prove every shutdown path is unaffected. We can revisit this if a concrete reproduction becomes available.

Sign in to join this conversation.