Skip to content

feat(agent-email): auto-reap sidecar on parent exit/crash (no manual wiring) - #1841

Merged
itomek merged 8 commits into
mainfrom
tmi/agent-email-crash-cleanup-docs
Jun 24, 2026
Merged

itomek merged 8 commits into
mainfrom
tmi/agent-email-crash-cleanup-docs

Conversation

@itomek

@itomek itomek commented Jun 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1840

Before, the package spawned the email-agent sidecar detached and only reaped it if the consumer explicitly called shutdown() — a crash or Ctrl+C orphaned the frozen binary, which kept holding port 8131 until the next EADDRINUSE. After, the package auto-reaps its own sidecar by default on exit / crash / SIGINT / SIGTERM / SIGHUP, so consumers get no leak with zero wiring. Opt out with autoCleanup: false to manage the lifecycle yourself; shutdown() remains the graceful, awaited path.

Proof (branch build + real frozen binary, darwin-arm64)

Built from this branch; verified autoCleanup present in dist/lifecycle.js (grep -c autoCleanup node_modules/@amd-gaia/agent-email/dist/lifecycle.js → 1). No consumer signal handlers in any script.

Test 1 — crash-default (autoCleanup: true, default)

$ node crash-default.mjs
[agent-email:lifecycle] spawning .../resources/email-agent --host 127.0.0.1 --port 8131
[agent-email:lifecycle] sidecar healthy after 33 probe(s)
[agent-email:lifecycle] version OK: apiVersion=2.0 agentVersion=0.2.0
SIDECAR_PID=73080
Error: boom
    at file://.../crash-default.mjs:8:7

$ lsof -nP -iTCP:8131 -sTCP:LISTEN
(no output = port free)
$ ps -p 73080
pid 73080: NOT FOUND (reaped)

→ REAPED — auto-cleanup caught the uncaughtException, port 8131 free.

Test 2 — sigint-default (autoCleanup: true, default)

$ node sigint-default.mjs &   # PID 73162, sidecar PID 73164
$ lsof -nP -iTCP:8131 -sTCP:LISTEN
COMMAND     PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
email-age 73165 tomasz    7u  IPv4 ...                          TCP 127.0.0.1:8131 (LISTEN)
$ kill -INT 73162
$ lsof -nP -iTCP:8131 -sTCP:LISTEN
(no output = port free)
$ ps -p 73164
pid 73164: NOT FOUND (reaped)

→ REAPED — auto-cleanup caught SIGINT, port 8131 free.

Test 3 — optout-leak (autoCleanup: false)

$ node optout-leak.mjs
SIDECAR_PID=74053
Error: boom    [Node.js v20.19.5 uncaught exception]

$ lsof -nP -iTCP:8131 -sTCP:LISTEN
COMMAND     PID   USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
email-age 74057 tomasz    7u  IPv4 ...                          TCP 127.0.0.1:8131 (LISTEN)
$ ps -p 74053
74053 ??   0:00.14  .../resources/email-agent --host 127.0.0.1 --port 8131
$ pkill -f resources/email-agent && lsof -nP -iTCP:8131 -sTCP:LISTEN
(no output = port free, cleaned up)

→ LEAK — opt-out confirmed: sidecar survived the crash, proving the default auto-reaper is what does the work.

Handlers needed: uncaughtException + unhandledRejection in addition to "exit" and signals — on Node v20, "exit" alone does not fire for an uncaught exception before the process terminates.

Tests

  • Unit (vitest): 35 passed (32 existing + 3 new lifecycle-cleanup tests: exit listener installed, idempotent install, autoCleanup:false opts out)
  • Build: tsc clean, no errors
  • Real-world: crash + SIGINT auto-reaped with zero consumer wiring; autoCleanup: false leaks (opt-out verified)

Test plan

  • cd hub/agents/npm/agent-email && npm install && npm run build && npm test — must pass (35 tests, tsc clean)
  • On a machine with the frozen binary: node crash-default.mjs exits with uncaught error; lsof -nP -iTCP:8131 -sTCP:LISTEN returns nothing (port free)
  • node optout-leak.mjs → port still held after crash (opt-out behavior verified)

Tomasz Iniewicz added 2 commits June 24, 2026 11:28
…tion/unhandledRejection)

Extend the "Running in production" shutdown guidance to cover a hard
crash. The prior snippet only wired SIGINT/SIGTERM; an uncaught throw
exits the parent but leaves the detached sidecar holding its port.

Documents the reap() funnel pattern and explains why direct
process.exit() bypasses async shutdown.
…pt-out via autoCleanup:false)

Install process handlers (exit, uncaughtException, unhandledRejection, SIGINT, SIGTERM,
SIGHUP) on first spawnSidecar call so the detached email-agent binary is always reaped
when the parent goes away. No consumer wiring required. Pass autoCleanup:false to own
the lifecycle yourself. shutdown() remains the graceful path; the auto-reaper is a
SIGKILL backstop on top of it.
@itomek itomek changed the title docs(agent-email): document crash-path sidecar cleanup feat(agent-email): auto-reap sidecar on parent exit/crash (no manual wiring) Jun 24, 2026
@itomek
itomek marked this pull request as ready for review June 24, 2026 16:25
@itomek
itomek requested a review from kovtcharov-amd as a code owner June 24, 2026 16:25
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions — no blocking issues.

This makes the email-agent npm sidecar reap itself automatically when the host process exits, crashes, or is interrupted, instead of leaking the frozen binary (and holding port 8131) whenever a consumer forgot to call shutdown(). Default-on, opt-out via autoCleanup: false, with shutdown() still the graceful path. The real-world proof in the PR (crash + SIGINT reaped, opt-out leaks) is exactly the right way to validate this, and the implementation is careful about not stomping on a consumer's own handlers.

One thing worth a conscious decision before merge: by default, importing and spawning now installs process-global uncaughtException/unhandledRejection/signal handlers, and the sidecar gets SIGKILLed on any uncaught error anywhere in the host process — even one unrelated to email that the consumer meant to catch and recover from. That's the intended "never leak" behavior and it's opt-out + documented, so it's not blocking — just confirm that aggressiveness is the contract you want. A couple of smaller polish notes are below.

🔍 Technical details

🟡 Important (worth confirming, not blocking)

Default-on global crash handlers reap on unrelated errors (src/lifecycle.ts:137-150)
The uncaughtException/unhandledRejection handlers fire for any error in the host process, not just sidecar-related ones, and unconditionally reapAllSync(). A consumer who registers their own uncaughtException handler to log-and-continue (discouraged, but a real pattern) will find their sidecar killed out from under a process they intended to keep alive. This is defensible — Node's default for both is to terminate, so "about to die → reap" is consistent — and autoCleanup: false exists. Just calling it out as a deliberate contract choice rather than an accident. The listenerCount === 1 guard correctly avoids hijacking the exit decision, but the reap happens regardless of who owns it.

🟢 Minor

Possible truncated stderr on the sole-listener crash path (src/lifecycle.ts:140-141, 147-148)

console.error(err);
process.exit(1);

When stderr is a pipe/file (not a TTY), writes are async and an immediate process.exit(1) can truncate the error output — a known Node footgun. Node's own default uncaughtException printer flushes before exiting. Minor in practice (the message usually makes it out), but if you want parity with the default crash output, consider process.exitCode = 1 plus a re-raise rather than a hard process.exit. Not worth blocking over.

Unit tests cover install/opt-out but not the reap itself (test/lifecycle-cleanup.test.ts)
The three tests verify listener installation, idempotency, and opt-out — all good. The actual kill path (killTreeSync), the signal re-raise (removeListener → process.kill(self, sig)), and the uncaughtException-triggers-reap behavior are only covered by the manual real-world proof in the PR body, not by the suite. Those are genuinely awkward to unit-test, so this is an observation, not a request — but a test that spies on a mocked process.kill/spawnSync and fires a fake liveSidecars entry through reapAllSync would lock in the most important behavior cheaply.

Cross-platform signal registration (src/lifecycle.ts:108, 151-163)
SIGTERM/SIGHUP aren't delivered on Windows (only SIGINT via Ctrl+C is meaningfully supported). Registering listeners for them is harmless (won't throw), and killTreeSync already routes Windows through taskkill, so there's no bug here — just noting the signal set is effectively POSIX-only, which matches the tree-kill comment block. No change needed.

Strengths

  • The listenerCount === N guard is the right instinct: reap unconditionally, but only own the exit/terminate decision when you're the sole listener, and re-raise the original signal after removing your handler so Ctrl+C still terminates. That's the correct idiom and it's well-commented.
  • registerForCleanup wires child.once("exit", …) to drop the sidecar from liveSidecars, so per-spawn state is cleaned up and process-level handlers install exactly once — no listener accumulation across many spawns.
  • shutdown() calling liveSidecars.delete(sidecar) cleanly hands the lifecycle back to the explicit path; the auto-reaper becoming a pure SIGKILL backstop is a tidy separation.
  • Real-world verification (crash + SIGINT reaped, opt-out leaks, port-free lsof checks) directly proves the user-observable outcome, and correctly identified that "exit" alone doesn't fire for an uncaught exception on Node 20 — that's the kind of thing unit tests miss.
  • README accurately mirrors the code (default-on, the awaited-shutdown graceful path, the autoCleanup: false opt-out wiring).

kovtcharov-amd
kovtcharov-amd previously approved these changes Jun 24, 2026
@itomek

itomek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks — addressed the suggestions in e2ff10b:

  • Truncated stderr on the sole-listener crash path — fixed. Both the uncaughtException and unhandledRejection handlers now flush synchronously via fs.writeSync(2, …) before process.exit(1), so the crash output can't be cut off on a piped/redirected stderr.
  • No unit coverage for the reap itself — added. A new test spies on process.kill, fires the installed SIGINT handler, and asserts the sidecar's detached group is SIGKILLed (process.kill(-pid, "SIGKILL")). Suite is 36 green.
  • Default-on global crash handlers reap on any uncaught error — confirmed intentional. "Never leak the sidecar" is the contract; it's opt-out via autoCleanup: false, and the listenerCount === 1 guard means we only take over the exit decision when we're the sole listener — a consumer's own handler still runs and owns how it exits.
  • POSIX-only signal set on Windows — acknowledged; harmless (extra listeners don't throw, and the Windows path goes through taskkill), so no change.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The new SIGKILL assertion in the reap test will fail on Windows — killTreeSync takes the taskkill/spawnSync branch there, not process.kill, but the test has no platform guard and only asserts the POSIX path.

🔍 Technical details

lifecycle.ts:88–94 branches on process.platform === "win32" and calls spawnSync("taskkill", ...) instead of process.kill(-pid, "SIGKILL"). The process.kill spy in the test (lifecycle-cleanup.test.ts:315–317) never fires on Windows, so the assertion at line 332 will always fail there:

expect(killSpy).toHaveBeenCalledWith(-12345, "SIGKILL");  // Windows: never called

spawnSync is mocked via vi.doMock("node:child_process", ...) in loadLifecycle, so the taskkill call itself is safely stubbed — the test just doesn't assert the Windows side. A platform guard fixes it:

if (process.platform === "win32") {
  const { spawnSync } = vi.mocked(await import("node:child_process"));
  expect(spawnSync).toHaveBeenCalledWith(
    "taskkill", ["/PID", "12345", "/T", "/F"], { stdio: "ignore" },
  );
} else {
  expect(killSpy).toHaveBeenCalledWith(-12345, "SIGKILL");
}

Comment thread hub/agents/npm/agent-email/README.md Resolved
@kovtcharov

Copy link
Copy Markdown
Contributor

Nice — the auto-reap is the right default, and the README "Running in production" rewrite reads well.

One consistency thing worth folding into this PR before it ships in agent-email 0.2.1: the same lifecycle claim this PR corrects in the README also lives in SPEC.md and SKILL.md (added in #1839, now on main), and those still say "always shutdown or the child is orphaned." Since the release publishes all three docs together, they'd ship contradicting each other. This PR only touches README.md, so SPEC/SKILL would be left stale.

The spots to sync to the new auto-cleanup behavior:

🔍 Exact lines
  • SPEC.md:33-34 — "wire shutdown into SIGTERM/SIGINT so the frozen binary's child is always reaped" → now automatic; drop the manual-wiring instruction (keep the re-startSidecar resilience point).
  • SPEC.md:121 — shutdown note: "the frozen one-file binary orphans a child otherwise" → only on a hard SIGKILL of the parent now; soften.
  • SKILL.md:55 — "Always shutdown(sidecar) on exit … only the process-tree kill in shutdown reaps it" → auto-cleanup also reaps on exit; shutdown is the graceful, awaited option.
  • SKILL.md:112 — "Wire shutdown into SIGTERM/SIGINT so the sidecar's child is reaped" → now automatic.
  • SKILL.md:136 — gotcha "Always shutdown — otherwise the sidecar's child process is orphaned" → stale.
  • README.md:240 — Troubleshooting row "Sidecar process lingers after exit → Always call shutdown(sidecar)" → auto-cleanup prevents this now (lingering implies autoCleanup: false or a hard SIGKILL).

Note: "the package does not restart a crashed sidecar" stays accurate — this adds auto-reap, not auto-restart.

Happy to hand you the exact diffs for SPEC.md/SKILL.md if that's easier than re-deriving them — just say the word.

@itomek

itomek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Windows test gap in e001abf — the reap test now platform-guards its assertion: on win32 it asserts the spawnSync("taskkill", ["/PID", …, "/T", "/F"]) branch, on POSIX the process.kill(-pid, "SIGKILL") branch. Build clean, 36 tests green.

The auto-reap default corrected in the README also lived in SPEC.md and
SKILL.md (always-shutdown-or-orphaned); since the release publishes all
three docs together they would have shipped contradicting each other.
@itomek

itomek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch — synced in d2a3d91. SPEC.md (the spawn-lifecycle paragraph + the shutdown API note) and SKILL.md (the lifecycle bullet, the production checklist, and the gotcha) now describe the auto-reap default instead of "always shutdown or it's orphaned", and I also softened the README troubleshooting row and a stale "always call this" example comment in SKILL.md. Kept "the package does not restart a crashed sidecar" as-is — still accurate (this adds auto-reap, not auto-restart). All three docs now agree, so the release won't ship them contradicting each other.

@itomek
itomek enabled auto-merge June 24, 2026 16:54
@itomek
itomek added this pull request to the merge queue Jun 24, 2026
Merged via the queue into main with commit e95cb2c Jun 24, 2026
25 checks passed
@itomek
itomek deleted the tmi/agent-email-crash-cleanup-docs branch June 24, 2026 16:55
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jun 24, 2026
…PEC/SKILL/CHANGELOG) (amd#1842)

## Why this matters

A functional change to an agent (behavior, API, contract, defaults,
lifecycle, error codes) almost always has the same claim repeated across
several **bundled** docs. Updating only one ships a package whose own
docs contradict each other — and the contradiction goes live the moment
that version publishes. This adds a rule under **Documentation
Requirements** so that doesn't happen.

The rule enumerates the hub-agent doc surfaces that must stay in sync —
`README.md`, `SPEC.md`, `SKILL.md`, `CHANGELOG.md`, and any
runtime/`openapi` spec — and says to grep the old
claim/symbol/status-code across all of them before calling the change
done.

Concrete trigger: **amd#1841** (agent-email auto-reap) updated `README.md`
to "cleanup is automatic" but left `SPEC.md` and `SKILL.md` still saying
"always call `shutdown` or the child is orphaned" — both due to publish
in the same 0.2.1 release.

## Test plan

- [ ] Docs-only change to `CLAUDE.md`; read the new subsection under
**### Documentation Requirements** for accuracy and tone.
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jul 16, 2026
…t 2.4 (amd#2102)

A Node integrator (and the amd#1653 dogfood) couldn't reach the sidecar's
streaming agent loop through `@amd-gaia/agent-email` — the 2.4 endpoints
landed Python-side in amd#2061 but the package's answer was "hand-roll
`fetch` + SSE parsing". Now `client.query()` streams the seven typed
canonical events (frozen amd#2057 contract) as an async iterator and
`client.cancelQuery(runId)` stops a run mid-flight, with bearer auth and
host-minted `run_id` semantics handled for you. The client speaks
contract 2.4 (`SCHEMA_VERSION` 2.3 → 2.4, additive — every 2.3 shape
unchanged), and streams fail loud: a malformed event, a non-SSE
response, or a stream that dies without the mandated terminal
`final`/`error` throws, while an unknown event type is surfaced as a
visible placeholder, never dropped.

Closes amd#2097

## Test plan

- [ ] `cd hub/agents/npm/agent-email && npm ci && npm run build && npm
test` — 101 tests: SSE parser (chunk splits at every boundary,
multi-line data, CRLF, multibyte flush), client call-shape +
event-stream unit tests, and the existing suite.
- [ ] Integration (needs a venv with the repo installed):
`GAIA_EMAIL_TEST_PYTHON=<repo-venv>/bin/python npm test` —
`startSidecar` spawns the real Python sidecar in dev mode (scripted
fake-agent seam, the same one `test_query_route.py` swaps) and asserts
the 2.4 version handshake, the `status→tool_call→tool_result→final`
sequence, mid-run cancel via `cancelQuery`, the 401 bearer gate, and the
404 cancel. Skips visibly on npm CI (no capable interpreter there).
- [ ] Docs updated together per amd#1841 — `grep -rn 'no wrapper yet'
hub/agents/npm/agent-email/{README,SPEC,SKILL}.md` no longer matches the
`/query` rows.
kovtcharov-amd added a commit that referenced this pull request Nov 1, 2026
CLAUDE.md requires README, SPEC.md, SKILL.md and CHANGELOG.md to change
together for a hub package (#1841 shipped a SPEC and SKILL contradicting
the README). The checklist only compared the README with the code.
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.

agent-email: auto-reap the spawned sidecar on parent exit/crash/Ctrl+C (no manual wiring)

4 participants