Skip to content

Observe the owned child exit in the shutdown regression - #6248

Merged
ymichael merged 1 commit into
mainfrom
bb/runtime-shutdown-exit-observation-20261024
Oct 25, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/runtime-shutdown-exit-observation-20261024

Conversation

@ymichael

@ymichael ymichael commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Windows main CI 40136960806 reported the replacement process alive immediately after shutdown in does not wait for stalled replacement initialization during full shutdown.

The test queried a numeric PID after the managed child had exited. PID reuse makes that an ambiguous identity check. Managed stop already rejects unless its own child has observed an exit, so the test should observe that same child. The original incident was not reproduced in 30 focused Windows repetitions or 20 complete lifecycle-file repetitions; PID reuse is a plausible explanation, not a captured cause, and this PR does not claim a production process leak was fixed.

What changed

Test-only: listen for the owned replacement child's exit before starting full shutdown, then require that event to have arrived when shutdown completes. Preserve the real stalled child, the initialization-ready signal, and the existing one-second shutdown bound. Register owned-child cleanup for a failed test.

No production, timeout, fixture-delay, CI selection, cache, shard, or skipped-coverage changes.

How you verified

  • With termination deliberately omitted from RuntimeProviderProcessManager.shutdown(), the original assertion fails (expected true to be false) and the revised assertion fails (no owned-child exit). Both use the real child. Restored production source byte for byte afterward.
  • VITEST_MAX_WORKERS=2 pnpm exec turbo run test typecheck --filter=@bb/agent-runtime: all 313 tests across 23 files and typecheck pass.
  • Formatting and git diff --check pass. Reviewed against docs/CODE_REVIEW.md and deslop guidance.
  • Baseline Windows diagnostics: 30 focused repetitions and 20 complete lifecycle-file repetitions / 640 cases pass. Five complete package repetitions under CI worker concurrency / 1,565 cases also pass.
  • Final-head CI 40139155349 passes on 5fd5b0c840, including Windows host packages (the changed test), both Linux server shards, all three Windows server shards, Linux/Windows integration, lint/typecheck, model listing, and checks.

AGENT GENERATED

@ymichael
ymichael merged commit c115cfb into main Oct 25, 2026
34 checks passed
@ymichael
ymichael deleted the bb/runtime-shutdown-exit-observation-20261024 branch October 25, 2026 02:53
ymichael added a commit that referenced this pull request Nov 6, 2026
… the GitHub PR Status plugin (#7205)

## Human comments

## What was wrong

#6125 (first shipped in bb 0.47.0) deleted the server plugin SDK methods
`bb.sdk.environments.pullRequest`, `markPullRequestReady`,
`markPullRequestDraft` and `mergePullRequest` outright, along with
core's routes. Every other retirement took the name out of the typings
only. The runtime kept working and the build warned with the
replacement. Published plugins that still call these four now get
`TypeError: ... is not a function`. Community plugins genui
(`project/environments.ts`, `project/source.ts`) and linear
(`server.ts`'s PR-merged → Done write-back, hidden behind an `as never`
cast) are broken today, and about 14 marketplace plugins reference the
methods.

## What changed

These four follow the pattern the Git plugin's retired reads use
(`retired-environment-reads.ts`, `retired-sdk-members.ts`):

- **Runtime adapters** in
`packages/sdk/src/areas/retired-environment-pull-requests.ts`, mixed
into `sdk.environments` next to the Git read adapters. The
`EnvironmentsArea` typings are unchanged. Each one forwards to the
bundled GitHub PR Status plugin (`bb--github-pr-status`) and returns the
old shape:
- `pullRequest({ environmentId })` calls `pullRequests` with `keys:
[environmentId]` and returns that row: `available` with `pullRequest`,
`absent`, or `unavailable` with `message`. The plugin's row schema is
the same as the old `ThreadPullRequest` field for field. It returns
`unavailable` if the plugin sends back no row.
- `markPullRequestReady` / `markPullRequestDraft` / `mergePullRequest`
call `markReady` / `markDraft` / `merge`. They return `{ ok: true,
action: "pull_request_ready" | "pull_request_draft" |
"pull_request_merge", message }`, and merge also returns `method`. The
messages are the same strings the old route returned.
- Errors: a plugin `not_found` refusal becomes 404
`environment_not_found`. A `conflict` refusal becomes 409
`pull_request_action_failed` and keeps the plugin's reason ("Pull
request is not a draft", "No pull request found", …), matching the old
route's 409s. When the plugin is disabled, the call fails with the RPC
error, as the Git read adapters do.
- **Plugin caller token**
(`apps/server/src/services/plugins/plugin-api.ts`). A plugin's `bb.sdk`
already sends `plugins.callRpc` with the plugin's caller token.
`sdk.environments`, though, came from the shared base SDK, so the
adapters reached `bb--github-pr-status` as an anonymous client. The
plugin answers client (app viewer) reads from its saved row and
refreshes it in the background. For a PR merged long ago, that saved row
can still say `open`, while `markReady`, which always reads fresh, finds
no PR. `wrapSdkForPlugin` now builds the retired environment members
(these four and the Git reads) on the caller-token `callRpc`, via
`createRetiredEnvironmentMembers` from `@bb/sdk` (its own module, so the
published plugin SDK types are unchanged). `pullRequest` then waits for
a row fresher than 10 seconds, as the old route and a direct `callRpc`
from a plugin do.
- **Build warning** in
`packages/plugin-build/src/retired-sdk-members.ts`. The four names join
the same `environments.<name>` scan (member access, optional chaining,
bracket access, destructuring). The warning names the replacement call,
e.g. `bb.sdk.plugins.callRpc({ pluginId: "bb--github-pr-status", method:
"merge", input: { environmentId, method } })`, and points at the
github-pr-status skill. Builds still never fail.
- **Recorded** in `docs/api_to_audit.md`, in a new "Retired environment
pull request methods" section next to the Git reads entry.

No wire, CLI or published SDK surface changes.
`check-plugin-sdk-version.mjs` reports "Plugin SDK surface unchanged".

## How you verified

- New `packages/sdk/test/retired-environment-pull-requests.test.ts`
drives the real SDK over the HTTP transport. It covers the read's row
passthrough and the missing-row case, each action's RPC path, input and
old result shape, and the 409 and 404 refusal mappings. Each test fails
on main, where the members don't exist.
- `retired-sdk-members.test.ts` adds detection of all four names in the
forms genui and linear use (including `bb.sdk.environments.pullRequest({
environmentId }) as never`, destructuring with an alias, and optional
chaining). It also checks the exact merge warning text and that
`pullRequests` RPC calls aren't flagged.
- Live, against a running bb server and its real GitHub PR Status
plugin, using this branch's SDK source:
- `pullRequest` on an environment with an open PR returned
`{"outcome":"available","pullRequest":{"number":6248,…,"checks":{"state":"passing",…}}}`,
the shape genui's `pullRequestInfo` and linear's `pr-runner` read.
- `pullRequest` on a branch without a PR returned
`{"outcome":"absent"}`.
- `markPullRequestReady` on that environment was refused before any
write: `409 pull_request_action_failed HTTP 409: No pull request found`.
That contradicted the read. #6248 was merged on Oct 25, and the read was
a saved Oct 24 row, served because my harness called with no caller
token (an app viewer read). Inside a plugin the same thing happened,
because `sdk.environments` didn't carry the token. That is fixed in the
second commit. `bb pull-request show env_p5z4xpvfak` now returns
`absent`, matching the action.
- `plugin-sdk.test.ts` adds a running-server test. It calls a plugin's
`bb.sdk.environments.pullRequest` and `markPullRequestReady` and asserts
that both requests carry the plugin's `x-bb-plugin-caller` token. It
fails without the `plugin-api.ts` change. The existing whoami test
covers how the token resolves to a plugin caller.
- `mergePullRequest` on an unknown environment returned `404
environment_not_found`.
- `pnpm exec turbo run test typecheck lint --filter=@bb/sdk
--filter=@bb/plugin-build` passes (sdk 137 tests, plugin-build 262).
`@bb/server` typecheck and lint pass, and the two caller tests in
`plugin-sdk.test.ts` pass. Full suites are left to CI.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 18, 2026
## Human comments

## What was wrong

Tests decided whether a process was alive, or had restarted, from its
PID. The operating system reuses PIDs, and Windows does so quickly. So a
test can be failed by an unrelated process that later takes the number:
- `process.kill(pid, 0)`;
- a liveness helper given a PID;
- `expect(newPid).not.toBe(oldPid)`.

The fixes were per file. Each one patched its own checks, and three of
them copied the same diagnostics-channel tracker into their own package.
Nothing stopped the next test from writing the pattern again.
`runtime.process-lifecycle.test.ts` and `plugin-host-manager.test.ts`
are on their sixth fix. Background: the C16 section of the ui-label
verification report.

Related failure modes came with it:
- fixtures publishing a PID file and racing its write;
- sleeps before a liveness check ("sleep 200 ms, then probe the PID");
- cleanup that SIGKILLs a remembered PID, which can hit an unrelated
process.

## What changed

**Guard.** `scripts/check-test-process-identity.mjs` runs in CI's `plan`
job, next to the provider-literal ratchet. It has no dependencies and
uses no Turbo cache, so it covers every package, including the ~40 that
have no `lint` script. It parses call arguments with balanced brackets,
so nested forms like `isAlive(Number(readFileSync(pidFile)))` are
caught. In test code (`*.test.*`, `test/`, `tests/`, `testing/`,
fixtures, test-support, `@bb/test-helpers`) it rejects:
- `signal-zero-probe`: `kill(x, 0)` and shell `kill -0`;
- `pid-liveness-helper`: `…Alive(`/`…Running(`/`…Exists(` given a PID or
PID file, or passed as a callback over PIDs;
- `pid-os-probe`: `/proc/<pid>` reads and `ps -p <pid>` existence
probes;
- `pid-identity-assertion`: `.not.toBe/toEqual/toContain` on a PID, and
`expect(a.pid === b.pid)`;
- `pid-signal`: `process.kill(<remembered pid>, signal)`, including
group signals. A failed spawn's `child.pid ?? 0` would signal the
runner's whole process group.

What stays allowed:
- the test process's own `process.pid` and `process.ppid`;
- `ps` calls that read a start time (`lstart`, `etime`) to compare a
recorded identity;
- the two owner modules that implement guarded signalling
(`child-processes.ts`, `process-sweep.ts`).

There is no allowlist. Each message names the replacement.
`packages/scripts/test/test-process-identity.test.mjs` pins the rule
with 52 cases kept as JSON data, so the rule passes on itself. They
include the verbatim checks past fixes removed and each form an
independent review found missing.

**One owner: `@bb/test-helpers/child-processes`.**
- `trackChildProcesses()` is #7681's diagnostics-channel tracker, made
shared. It offers `children`, `running()`, `waitForExit()`,
`waitForClose()`, `killRunning()` and `dispose()`.
- `createProcessLifeline()` is a local socket (a named pipe on Windows)
for descendants the test does not spawn itself.
- A Node process joins with `holdSource(label, onHeld?)`. `onHeld` runs
once the hold is registered, for scripts that block next.
- `holder.exited` and `alive()` follow the connection. `holder.kill()`
signals only while the connection is open, so a reused PID is never
signalled. `close()` reaps the holders still connected.
- The hello message carries the PID, which replaces fixture PID files
and their publish races.
- `createDescendantPipe()` is a POSIX FIFO for shell descendants that
must start instantly, such as `sleep 60 > "$pipe" &` racing a 300 ms
production timeout. `opened` and `closed` follow the inherited write
end.
- Waits are event-driven and bounded by each test's existing timeout. No
new per-test budgets; several PID-poll deadlines were deleted.

**Plugin SDK, additive and backward compatible.**
`@get-bb/plugin-sdk/testing` gains `experimental_trackChildProcesses`,
`experimental_createProcessLifeline` and
`experimental_createDescendantPipe`, plus their `Experimental*` types.
They are thin wrappers over the same module, so forkable plugins use
core's path. Nothing existing changed.
- SDK bumped to 0.6.156. Four other open PRs hold 0.6.152–0.6.155.
- Documented in `docs/api_to_audit.md`,
`plugins/plugin-api-docs/src/surfaces.ts` and the plugin-authoring
`testing.md`. Repository guidance is in `docs/debugging-and-qa.md`
("Observing Processes in Tests").

**Migration.** Every finding on main (163 in 42 files) moved onto the
owner:
- process-utils: `process-tree`, `portable-process`,
`exec-portable-file`;
- `config` (`verified-process-stop`);
- `test-helpers` `process-sweep`: liveness after SIGTERM now re-lists
processes and matches PID plus args, and only those still listed get
SIGKILL;
- the `frp-client` fixture and its two callers;
- agent-runtime: process-lifecycle, codex-topology, acp-topology;
- provider-bridge-acp: `bridge`, `shutdown`, and `fake-acp-agent.mjs`,
which now runs a hold instead of writing a PID file;
- host-daemon: `environment-lifecycle-script`, `runtime-manager`,
`connect-next`, and the server-move fixture plus activation and service
tests;
- plugins: codex test-support and 4 callers, automations,
browser-automation, mcp, environment-personal-workspace,
environment-git-worktree, storage-retention (2), connect-next frp e2e;
- apps/server: `install-machine-script`;
- apps/desktop: `log-viewer`;
- scripts: `start-bb`;
- `tests/integration/global-setup.ts` and
`fake/recovery/reconnect-open-work`;
- tests/qa: `shared.ts`, `standalone-restart-command`,
`spawn-logged-process`, `scripts/run-root-command.mjs`;
- second pass, for the forms the review found:
- `install-machine-script`: 13 remembered-daemon kills deleted, since
the file's `afterEach` path sweep already owns them. Its fake `launchctl
bootout` waits on a recorded `ps -o lstart=` instead of `kill -0`.
- `desktop bb-process`: the grandchild reports its own `/proc/self/stat`
group and holds a lifeline; it no longer reads `/proc/<pid>`.
- `process-utils oom-score` and `agent-runtime` OOM: children report
their own `/proc/self/oom_score_adj`.
- `bb-app app-update-run-command`: tracker `killRunning()` instead of a
remembered-PID set.
- `plugin-sdk kill-processes`: `child.kill()`; the `child.pid ?? 0` path
is gone.
- `bb-app managed-process`, `cli broken-pipe` e2e, server-move fixture:
`killProcessGroup({ child })`.
- agent-runtime topology and lifecycle, ACP `bridge` (4 readyFile
kills), Codex archived-rebuild, integration reconnect: tracked
`ChildProcess.kill()`.
- `agent-runtime` live recorder: `signalDescendantProcesses()`, a new
sweep owner that signals selected descendants of the test process
straight from a fresh listing.
- `tests/qa` `killProcess` and integration `global-setup`:
`readProcessIdentity()` plus `stopVerifiedProcess()` from `@bb/config`.
- `tests/qa` `buildDaemonRestartCommand`: waits on a recorded `lstart`
in shell.

Processes that cannot hold a handle are confirmed by identity, never by
bare PID:
- stale servers from earlier runs, by `lsof` or `ps` start time;
- Windows MSYS `sleep`, by `readProcessIdentity`.

`plugin-host-manager.test.ts` keeps #7683's self-reported `bootId`,
which already satisfies the rule.

## Past fixes this root cause produced

| Fix | What it patched | Under this PR |
|---|---|---|
| #5052 | `expect(replacementProvider.child.pid).not.toBe(exitedPid)` ×3
| `pid-identity-assertion` rejects it |
| #5487 | server-move `isProcessGroupAlive(prepared.pid)`, Windows PID
reuse | `pid-liveness-helper` rejects it; the fixture now hands out the
owned `ChildProcess` |
| #6248 | runtime shutdown `processIsAlive(child.pid)` | rejected;
tracker |
| #6212 | long-lived processes orphaned on failure | `lifeline.close()`
/ `killRunning()` reap holders and tracked children |
| #6568, #7046, #7048 | fixtures read a PID file before it was written |
lifeline hello replaces those PID files |
| #6735 | descendant liveness checked right after the parent closed |
`await holder.exited` |
| #6978, #3689 | only the root awaited, descendants held temp dirs |
`waitForClose()`, lifeline/pipe `exited`/`closed` |
| #7681 | Codex, ACP and runtime teardown polled `kill(pid, 0)`; added 3
tracker copies | copies deleted; shared tracker |
| #7683 | restarted worker assumed a new PID | rejected by the rule;
boot id kept |
| #7686 | Pi version test added its own tracker for reaping | copy
deleted; `waitForClose()` |

**Patches this deletes:**
- five diagnostics-channel tracker copies: #7681's in agent-runtime,
provider-bridge-acp and provider-codex; #7686's in provider-pi; and
those in Pi `test-support` and `parity.test.ts`;
- every local signal-0 wrapper (`isAlive`, `processIsAlive`,
`isPidAlive`, `isProcessRunning`, `alive`, …);
- the fixture PID files and their write-then-rename publication;
- the fixed sleeps before liveness checks, including mcp's `sleep 200
ms` and qa's 500 ms after signalling;
- the 8 s app-server exit poll in Codex test-support.

There are no linked issues: this class was fixed in PRs only.

## How you verified

- **Guard fails on main for the known cases.**
- The rule applied to `origin/main` (`f1c53045c94`) reports 163 findings
in 42 files; on this branch, 0.
  - The rule test passes 52 cases:
- caught: the verbatim removed checks from #5052, #5487, #6248, #7681
(Codex and ACP) and #7683, plus the reviewer's forms (nested pid-file
reads, `processExists(pid)`, shell `kill -0`, `/proc/${pid}`, `ps -p`,
`a.pid === b.pid`, `.not.toContain(oldPid)`, remembered-PID SIGKILL,
`pid ?? 0`);
- accepted: handle and identity forms (`exitCode`, boot id,
`holder.alive()`, `isProcessGroupAlive(child)`, `ps -o lstart=`,
`process.pid`/`process.ppid`, `/proc/self`, a full `ps -A` listing, a
`"parent.pid"` file name).
- **Fixture tests (12)** include a holder that reports a PID belonging
to a live bystander. After the holder exits, `kill(pid, 0)` still
succeeds, but `alive()` is false and `kill()` refuses.
- **Targeted Turbo tests passed for every migrated file:**
- process-utils 16 (5 Windows-only skipped), config 1, test-helpers 12;
- agent-runtime 42, provider-bridge-acp 232, host-daemon 142 +
connect-next 11 (real frp);
  - provider-bridge-protocol parity;
- plugins: codex 12, automations, browser-automation 6, mcp 8,
personal-workspace 5, git-worktree 63, storage-retention 67,
connect-next frp 10, Pi version and lifecycle;
- apps and scripts: server install-machine-script 54, desktop log-viewer
13, scripts start-bb 4 plus the rule test, qa 25.
- process-tree, exec-portable-file and process-sweep passed 3 repeated
runs.
- Second pass: targeted tests for every migrated file passed:
- server install-machine-script; qa (all, including 11
spawn-logged-process); integration reconnect-open-work 2/2;
- desktop bb-process 8, plus 1 Linux-only skipped locally; host-daemon
server-move 83; agent-runtime 41;
- bb-app; plugin-sdk kill-processes; ACP bridge 217; Codex
archived-rebuild 2; cli broken-pipe 8; test-helpers (including
`signalDescendantProcesses`).
- `turbo run typecheck lint lint:type-aware --filter='[origin/main]'`:
78 tasks passed.
- plugin-sdk, plugin-api-docs, bb-guide and domain tests passed.
- Not run locally: the Windows-only cases (`.cmd` shim kill, MSYS
lifecycle cancellation) and the integration suite. CI covers them.

## Decisions for review

- **Integration global setup.** It now stops stale `lsof` holders only
after verifying their recorded identity (`stopVerifiedProcess`). It no
longer re-lists and signals by PID.

- **QA tooling.**
- `cleanupStandaloneOrphans` now judges a parent alive by `ps` start
time against when the state was written, not by signal 0.
- `killProcess` verifies the target with `stopVerifiedProcess` (60 s
start-time tolerance) and skips processes it cannot inspect.
- The daemon restart command's wait ends as soon as the original start
time is gone. Its EPERM-era warning changed from "parent … is not
signalable" to "parent … could not be inspected". A live parent owned by
another user is now skipped silently, because `ps` can see it.
- **New public SDK surface.** Three `experimental_` testing exports with
audit criteria in `docs/api_to_audit.md`. The patch bump means
third-party plugins can opt in, and existing ones are unaffected.
- **Failure mode.** A process that never exits now fails on the test's
existing timeout rather than at a separate PID-poll deadline. The
failure message is less specific, in exchange for no extra budget.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

1 participant