Skip to content

Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856

Open

Description

@admarble

Three sequant run invocations were killed by an external SIGTERM mid-run. Investigation identified the trigger; the timer's owner is still unidentified.

Finding

A nested phase claude that hangs after finishing its turn is terminated at ~106s (±1s) from spawn, and the termination takes down the entire process tree — including the parent sequant run.

A nested claude that exits cleanly is never killed, at any lifetime.

Evidence

mDNSResponder stamps every claude process by PID, giving exact lifetimes (/usr/bin/log show --predicate 'process == "mDNSResponder" AND eventMessage CONTAINS "claude"'):

PID lifetime outcome
21762 107.08s KILLED (parent died 01:21:57)
33738 106.23s KILLED (parent died 01:36:05)
40181 105.41s KILLED (parent died 01:39:36)
17241 316s exited normally — no blanket cap
outside-session phase 131.7s clean exit — longer than 106s, survived

Spread across the three deaths: 1.7s.

The discriminator is not lifetime, session, repo, or -Q. It is whether the agent hangs on exit. From .entire/logs/entire.log, the Stop-hook to SessionEnd gap:

  • healthy phase: 0.36s
  • the three killed phases: 96.3s / 58.0s / 92.7s

One killed phase did ~9s of actual work, then sat idle ~93s with all ~12 MCP servers still up. At each death every MCP server quit inside a 60ms window — simultaneous teardown, not a cascade.

Ruled out (each by direct measurement)

  • Idle-output timeout. A background task that printed one line then stayed silent 300s completed normally. Independently, one victim survived a 107s intra-run silence and died after a 108s one — a threshold cannot sit in a 1s window crossed in both directions.
  • Lifetime cap. Two runs survived 26m54s and 22m49s.
  • CLAUDE_STREAM_IDLE_TIMEOUT_MS. Governs the model API response stream and aborts/retries a request; it does not SIGTERM a child.
  • sequant signalling itself. Five signal-capable sites; the only cross-process SIGTERM requires both --force and --signal-other (CLI-only, unreachable from settings or env) and is self/parent-guarded at the syscall. No timeout constant between 100-300s exists anywhere in the source.
  • Hooks. Zero kill/pkill/killall/trap across all four hook scripts and both mirrors. Verified the hooks did fire inside the nested agent.
  • entire CLI. Logged "no files modified during session, skipping checkpoint" on every turn; no git operations. git reflog is empty at all three death timestamps.
  • launchd. Only com.admarble.pm-orchestrator can kill; wrong schedule, and it only signals the PID in its own lockfile.
  • jetsam / memory pressure / sandbox denials / TMOUT / ulimit — all checked, all negative.
  • Concurrent process-group kill from the test suite. The successful outside-session run began 6 minutes AFTER the last death; no overlap.
  • Stale PID / lock reuse, and the MCP group-kill at src/mcp/tools/run.ts:893 (detached: true is set at :750, so kill(-pid) targets a genuine group leader).

Not reproducible on demand

A later in-session run with the identical -Q flags cleared spec and ran 8m53s into exec before being stopped manually. The hang is intermittent, which is why an outside-session run of the same command succeeded — nothing about being outside the session was protective.

Acceptance Criteria

  • AC-1: The owner of the ~106s timer is identified, by tracing signal delivery during a reproduction (sudo dtrace -n 'proc:::signal-send /args[2] == 15/') or equivalent.
  • AC-2: The cause of the post-turn hang is identified; the first hypothesis to test is MCP server shutdown, since every hung session had ~12 servers up including npm exec sequant@latest serve (a registry fetch per phase).
  • AC-3: A phase run with --no-mcp is compared against the 0.36s healthy Stop-hook-to-SessionEnd baseline, establishing whether MCP shutdown causes the hang.
  • AC-4: When a run is terminated by an external signal, the failure is surfaced to the user as an abort with its cause rather than silently truncating.

Related defects found during this investigation

  1. A SIGTERM'd run is logged as a success. run-2026-07-29T06-37-48-*.json records issues[0].status: "success" and summary.passed: 1 for a run with zero completed phases and totalDurationSeconds: 0. Aborted phases leave no phases[] entry and no errorContext, so no stdoutTail survives for diagnosis.
  2. Truncated teardown leaks locks. When the shutdown is escalated to SIGKILL mid-cleanup, "Release issue locks" does not complete and .sequant/locks/*.lock plus .sequant/pids/*.pid are left behind. One run left the worktree corrupted with every tracked file showing as deleted.
  3. Stale locks with recycled PIDs read as fresh. .sequant/locks/505.lock (pid 28809, 2026-05-14), 708.lock (pid 97866, 2026-06-03) and 803.lock (pid 58609, 2026-07-25) all hold long-dead PIDs. classifyStaleness treats a same-hostname live PID as fresh, so a recycled PID silently blocks those issues from ever running.

Environment note

log is shadowed by a zsh function on the affected machine — log show ... fails with (eval):log:1: too many arguments. Use /usr/bin/log.

Activity

  1. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    #856 — Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run
    Open
    ────────────────────────────────────────────────────────────────

    → PARK — AC-1/2/3 are diagnostic measurements that need a live reproduction; the body states the hang is intermittent and not reproducible on demand
    Resume after: a hang is captured live under sudo dtrace -n 'proc:::signal-send /args[2] == 15/', or AC-4 and the three related defects are split into their own issues
    ────────────────────────────────────────────────────────────────
    ⚠ AC-1/2/3 need a live reproduction under sudo dtrace; the body states the hang is not reproducible on demand
    ⚠ AC-4 plus the three related defects (SIGTERM'd run logged as success, leaked locks, recycled-PID stale locks) are independently automatable — splitting them unblocks work the diagnosis ACs hold up
    ────────────────────────────────────────────────────────────────

  2. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    Investigation: the ~106s killer is Claude Code's bg-pty watchdog (group SIGKILL), not anything in sequant

    Follow-up investigation, 2026-07-29. The original sweep covered sequant's source, hooks, launchd, and the OS — everything except Anthropic's own code. That's where the killer is.

    AC-1 candidate answer: [bg-pty] host-dead watchdog in Claude Code 2.1.220

    The installed claude binary (2.1.220, Mach-O; the same code ships inside @anthropic-ai/claude-agent-sdk's CLI) contains a background-task PTY subsystem, "bg-pty". Background Bash tasks run under a detached helper (claude --bg-pty-host <sock> <cols> <rows> -- <cmd>, detached: true, argv0: "claude bg-pty-host"); a claude session is the client that connects to the sock. Extracted from the binary (minified, reformatted):

    // client-side poll loop `z()`:
    try { process.kill(t, 0) }          // is host pid t alive?
    catch { /* dead → graceful cleanup: read tail, unlink sock, emit */ }
    ...
    if (g >= xhp) {                      // xhp = 30 failed connect attempts
      w(`[bg-pty] ${e}: ${g} connect attempts failed; treating host as dead`, {level:"warn"});
      try { process.kill(-t, "SIGKILL") }        // GROUP kill
      catch { try { process.kill(t, "SIGKILL") } catch {} }
    }

    Constants: xhp=30 (attempt cap), connect backoff ladder [50,100,250,500,1000,2000]ms. The same subsystem has a teardown path that does group SIGTERM → 5s grace → group SIGKILL, and an adopt-mode short-circuit (ENOENT on adopt — sock file externally deleted; respawning) that jumps the counter straight to 30. Telemetry names for upstream searchability: tengu_bg_ptyhost_crash, tengu_bg_adopt_sock_unlinked, tengu_bg_revival_guard.

    Why this matches every measurement:

    • The discriminator. The kill fires only when the host pid is alive but its socket won't accept — precisely "hangs after finishing its turn". A clean exit makes process.kill(t,0) throw → graceful branch → never killed, at any lifetime. This is the only mechanism found anywhere on the machine that keys on exactly that state.
    • The 60ms simultaneous teardown + parent death. It's a process-group kill. Verified live: an SDK-spawned phase claude, all its MCP servers, and the parent sequant run share one pgid (specimen: sequant run 771 pid 9403 = pgid of itself, the nested claude 12659, and both sequant serve processes). One group signal produces the whole observed death pattern.
    • Spawn-anchored constant timing. 30 attempts on a fixed retry schedule from monitor start ≈ constant wall time; monitor start coincides with session start (adoption/claim of persisted bg-pty state happens at startup). Arithmetic note: the ladder alone sums to 51.9s; observed ~105s implies ~1.8s additional per-attempt cost (e.g. a connect that must time out against a wedged-but-alive listener) — unresolved, needs the live capture.

    Victims identified by transcript — all three, to the second

    session project dir first entry last entry wall run_in_background calls
    2b7de5d9 worktrees/feature-848 06:20:10.848Z 06:21:57.075Z 106.2s 1
    78565ed5 Projects/sequant (main) 06:34:20.059Z 06:36:05.464Z 105.4s 0
    a5d0bda3 Projects/sequant (main) 06:37:52.232Z 06:39:36.828Z 104.6s 0

    Last-entry timestamps equal the three parent-death times (01:21:57 / 01:36:05 / 01:39:36 local) exactly.

    Two structural facts fall out:

    1. The victim runs were backgrounded Bash tasks in an interactive session. The spawning session's tail -f <tasks>/b6byn5iih.output (started 01:34, mid-death-window) is still running, orphaned, parented to the still-alive interactive claude (pid 70335). So each victim tree lived under a bg-pty host's process group — a group the interactive session's client machinery holds a kill switch for.
    2. Two of three victims made zero background calls of their own but ran with cwd in the same project directory as the interactive session. Their own bg tasks can't be the trigger; shared per-project bg-pty state (spare-pool claim or sock adoption contention between the nested claude and the interactive session that owns the sock) is the leading trigger hypothesis. That also explains intermittency: it depends on what persisted bg-pty state was visible at the moment the phase claude started.

    The post-turn hang and the kill are then one defect, not two: the same client machinery that can't connect is what blocks SessionEnd (the ~12 MCP servers still being up is a downstream symptom of never reaching teardown, not the cause). This redirects AC-2's first hypothesis away from MCP shutdown.

    Corrections to the ACs

    • AC-1's dtrace predicate must include signal 9. args[2] == 15 captures only SIGTERM; the primary kill here is a group SIGKILL (a SIGTERM→SIGKILL path exists in the same subsystem, so capture both: args[2] == 15 || args[2] == 9). "External SIGTERM" in the original finding was inferred, not captured — a 15-only capture may record nothing and falsely exonerate.
    • AC-3's --no-mcp control is still worth running, but the sharper repro matrix is: {backgrounded vs foreground launch} × {concurrent same-cwd interactive session vs none}. Prediction: foreground launches from a plain shell never die (confirmed by the surviving specimens — the 131.7s and 316s clean runs, and today's terminal-launched run 771); backgrounded launches with a same-project interactive session are the vulnerable configuration.
    • AC-4 (surface external termination) stands unchanged and is independently automatable, as are the three related defects.

    Upstream

    If a live capture confirms, this is a Claude Code bug to file upstream: the "treating host as dead" heuristic group-SIGKILLs a process tree whose host is alive-but-busy, and the process group it kills can contain the caller's own ancestors. Reference the extracted strings and telemetry names above; version 2.1.220.

    Workaround available today

    Until confirmed/fixed upstream: launch long sequant runs from a plain terminal (or via the MCP sequant_run tool), not as a backgrounded Bash task inside an interactive Claude session. Every observed death was a backgrounded launch; no foreground launch has ever died.

  3. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    #856 — Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run
    Open
    ────────────────────────────────────────────────────────────────

    Supersedes prior assess from 2026-07-29 (PARK)

    → PARK — The ~106s killer is now identified as Claude Code 2.1.220's [bg-pty] host-dead watchdog issuing a group SIGKILL — an upstream defect, not a sequant one. AC-1/2/3 remain diagnostic measurements needing a live reproduction, and the body states the hang is intermittent and not reproducible on demand.
    Resume after: a live capture confirms the bg-pty group SIGKILL, or AC-4 and the three related defects are split into their own issues
    ────────────────────────────────────────────────────────────────
    Cleanup:
    gh issue edit 856 --add-label bug # unlabeled
    ────────────────────────────────────────────────────────────────
    ⚠ New 17:01 investigation redirects AC-2 away from MCP shutdown — the post-turn hang and the kill are one upstream defect, not two, with the ~12 MCP servers a downstream symptom of never reaching teardown
    ⚠ AC-1's dtrace predicate is wrong as written: the primary kill is a group SIGKILL, so capture args[2] == 15 || args[2] == 9 — a 15-only capture may record nothing and falsely exonerate
    ⚠ AC-4 and the three related defects (SIGTERM'd run logged as success, leaked locks, recycled-PID stale locks) are independently automatable — splitting them unblocks work the diagnostic ACs hold up
    ⚠ Workaround available today: launch long sequant runs from a plain terminal or via the MCP sequant_run tool, never as a backgrounded Bash task inside an interactive Claude session
    ────────────────────────────────────────────────────────────────

  4. admarble commented on Jul 30, 2026

    @admarble
    ContributorAuthor

    Plan (/spec) — scoped to AC-4 + the three related defects

    Complexity: Standard (4 ACs, 1 directory) · Scope decision: AC-1/AC-2/AC-3 are diagnostic measurements requiring a live reproduction of an intermittent hang under sudo dtrace. They are not automatable and stay unchecked. This run implements AC-4 and the three related defects from the issue body, and lands the AC-1/AC-2 investigation findings into the repo so they survive outside a GitHub comment.

    AC Quality Check

    Linter: ✅ all 4 ACs clear and testable. But the linter does not model feasibility — AC-1/2/3 each require capturing a non-deterministic event that the issue body itself states is "not reproducible on demand". That is a scoping problem, not a wording problem.

    Scope Assessment

    Metric Value Status
    Feature count 1 ✅
    AC items 4 ✅
    Directory spread 1 ✅

    Non-Goals: not present in the issue body. Declared here:

    Verdict: ⚠️ SCOPE_WARNING (missing Non-Goals — supplied above). Quality loop auto-enabled.


    Root causes located

    Each related defect traced to a specific line. All three are variants of one pattern: absence of evidence is being read as evidence of success.

    # Defect Root cause
    1 SIGTERM'd run logged as success src/lib/workflow/log-writer.ts:125 — startIssue() seeds status: "success" optimistically. If no phase ever completes, logPhase() never runs, so deriveIssueLogStatus() never overwrites it. The Finalize run logs shutdown task then calls completeIssue() for every in-flight issue and persists success with phases: [], totalDurationSeconds: 0. Reinforced by run-log-schema.ts:457 — deriveIssueLogStatus([]) also returns "success" for zero phases.
    2 Truncated teardown leaks locks src/lib/workflow/run-orchestrator.ts:961-971 registers Release issue locks plus a sync process.on("exit") net. Neither can run under SIGKILL — uncatchable by construction. The only available fix is recovery on next start, which defect 3's fix provides.
    3 Recycled PIDs read as fresh src/lib/locks/lock-manager.ts:137-140 — the same-host branch returns null (fresh) whenever isPidAlive(pid) is true, with no age bound at all. A 2026-05-14 lock whose PID 28809 has since been recycled reads as fresh forever, permanently blocking #505. Confirmed live: 505.lock, 708.lock, 803.lock are 76 / 56 / 4 days old.
    AC-4 External termination not surfaced src/lib/shutdown.ts:219-221 — gracefulShutdown() prints "Interrupted. Cleanup complete." and calls this.exit(0). A run killed by an external SIGTERM therefore exits 0 with no cause named, and runCommand() never reaches displaySummary(), so the existing abortReason rendering path (run-display.ts:119) is never reached.

    Acceptance Criteria

    AC-1: Owner of the ~106s timer identified

    Verification: Manual (live capture) — NOT MET, out of scope this run
    Candidate answer already recorded: Claude Code 2.1.220's [bg-pty] host-dead watchdog (xhp=30 failed connects → process.kill(-pid, "SIGKILL")). Confirming it requires catching an intermittent hang under sudo dtrace -n 'proc:::signal-send /args[2] == 15 || args[2] == 9/'. This run persists the evidence to docs/incidents/856/ and leaves the box unchecked.

    AC-2: Cause of the post-turn hang identified

    Verification: Manual (live capture) — NOT MET, out of scope this run
    The 17:01 investigation redirects this away from MCP shutdown: hang and kill are one upstream defect, with ~12 live MCP servers a downstream symptom of never reaching teardown. Recorded, not proven.

    AC-3: --no-mcp compared against the 0.36s baseline

    Verification: Manual measurement — NOT MET, out of scope this run
    Deliberately excluded: per AC-2's redirect, MCP shutdown is no longer the leading hypothesis, so this control now tests the wrong variable. The sharper matrix ({backgrounded vs foreground} × {concurrent same-cwd session vs none}) is recorded in the incident doc.

    AC-4: External termination surfaced as an abort with its cause

    Verification: Unit Test + Integration Test
    Scenario: Given a sequant run with an in-flight issue → When the process receives SIGTERM from outside → Then the CLI prints an abort banner naming the signal and its likely cause, exits 128+signum (143), and the run log records the issue as a failure marked aborted carrying the signal — not success.
    Assumptions: SIGKILL is uncatchable; AC-4 is satisfiable only for catchable signals. The SIGKILL case is covered indirectly by defect 2/3's recovery-on-next-start.

    Related defect 1: aborted run must not log as success

    Verification: Unit Test — LogWriter.finalize({ aborted }) marks in-flight issues aborted; finalizeRunLog excludes them from summary.passed.

    Related defect 2: leaked locks recoverable after truncated teardown

    Verification: Integration Test — a lock left behind by a killed process is cleared on the next acquire rather than blocking it forever.

    Related defect 3: recycled PID must not read as fresh

    Verification: Unit Test — classifyStaleness with a same-host, PID-alive, 76-day-old lock returns a stale reason instead of null.


    Implementation Plan

    Phase 1 — Lock staleness ceiling (defects 2 + 3)

    1. src/lib/locks/types.ts: add DEFAULT_MAX_LOCK_AGE_MS (24h) and a "max-age-exceeded" staleness reason on AcquireResult / LockListing.
    2. src/lib/locks/lock-manager.ts: in classifyStaleness, apply the absolute ceiling before the same-host PID branch, so it binds regardless of host, PID liveness, or skipPidCheck. 24h is ~48× the 30-min run timeout and 4× the 6h skill TTL — no false positives against any real run, while every leaked lock becomes self-clearing. Add maxLockAgeMs constructor option + SEQUANT_MAX_LOCK_AGE_MS env override (mirrors the existing resolveSkillLockTtlMs seam).
    3. Surface the new reason in sequant locks list output.

    Phase 2 — Abort-aware run logging (defect 1)

    1. src/lib/workflow/run-log-schema.ts: add additive optional aborted?: boolean + abortReason?: string to IssueLogSchema, and abortedBy?: string to RunLogSchema. Deliberately not a new IssueStatus enum value — follows the capped precedent at run-log-schema.ts:164-170, which reuses "failure" plus a boolean specifically to keep the persisted-log schema stable at version: 1.
    2. Same file: make deriveIssueLogStatus([]) stop returning "success" for zero phases (an issue that ran no phase did not pass).
    3. src/lib/workflow/log-writer.ts: finalize(options?: { aborted?: { signal: string; reason: string } }) — when set, every still-active issue is completed as status: "failure", aborted: true, abortReason: <cause>.

    Phase 3 — Surface the abort (AC-4)

    1. src/lib/shutdown.ts: gracefulShutdown(signal) exits 128 + signum (SIGINT→130, SIGTERM→143) instead of 0, and prints an abort banner naming the signal. For SIGTERM specifically, include the known-cause pointer (external termination; see docs/incidents/856/), since no interactive user sends SIGTERM by hand.
    2. src/lib/workflow/run-orchestrator.ts:750: the Finalize run logs cleanup passes the abort context through to writer.finalize() so the persisted log and the console banner agree on one cause.

    Phase 4 — Persist the investigation (AC-1/AC-2 evidence)

    1. docs/incidents/856/ — the bg-pty watchdog findings, the three victim transcripts, the corrected dtrace predicate (args[2] == 15 || args[2] == 9), the repro matrix, and the standing workaround. GitHub comments are not durable evidence; .sequant/ rotates at 100 files.

    Rule Touchpoints

    No AC triggers the behavior-rule heuristic (<2 keywords from default|always|never|rule|behavior|skip, no always X unless Y pattern). Section omitted per the short-circuit.

    Sibling-site scan

    Three co-located instances of "absence reads as success" — all in scope, all in the fix above: log-writer.ts:125 (optimistic seed), run-log-schema.ts:466 (empty-phases derive), shutdown.ts:221 (exit(0) after interruption). Not widening scope beyond these; they are the same root cause in three places.

    Design Review

    1. Where does this logic belong? Staleness policy is already a pure function (classifyStaleness) — the ceiling belongs there, not in callers. Abort semantics belong in LogWriter/ShutdownManager; the orchestrator only wires the two together.
    2. Simplest correct approach? An absolute age ceiling, not process-start-time cross-checking. Reading a PID's start time to detect recycling is more precise but needs ps subprocess calls and per-platform parsing; a 24h ceiling clears every observed stale lock with zero risk to a 30-minute run, as a pure function with no I/O.
    3. What existing pattern does this follow? capped (feat(orchestrator): preserve partial output for turn-capped phases in phase-executor #739) for the additive-boolean-over-new-enum choice; resolveSkillLockTtlMs for the env-override seam; abortReason on IssueResult for abort vocabulary that run-display.ts already renders.
    4. What would a senior reviewer challenge? "Why does SIGINT now exit 130 — won't that break scripts?" Because a run interrupted mid-flight is not a success, and 128+signum is the POSIX convention. Existing assertions in shutdown.test.ts will be updated deliberately, not loosened.

    Feature Quality Planning

    • Gate tests need mutation verification (CLAUDE.md): each new test must be shown to fail when its target is reverted, recorded in the PR body.
    • SIGKILL remains unfixable in-process — AC-4 is honest only about catchable signals. This will be stated in the PR, not papered over.
    • Schema back-compat: all new fields optional; version: 1 unchanged; existing logs still parse.

    Open Questions

    1. 24h ceiling, or process-start-time recycle detection? — Recommendation: 24h ceiling. Impact if wrong: a genuine >24h run would lose its lock; no such run exists (timeout is 30 min).
    2. Should deriveIssueLogStatus([]) change globally, or only on the abort path? — Recommendation: change globally; zero phases is never a pass. Impact if wrong: a caller relying on empty-means-success flips. Will be checked against all call sites during exec.

    Recommended Workflow

    Phases: spec → exec → qa · Quality loop: enabled (SCOPE_WARNING) · Testgen: skipped — every touched module already has a test file (lock-manager.test.ts, log-writer.test.ts, shutdown.test.ts, run-log-schema.test.ts); stubs would be untracked noise. Browser test: skipped (no UI).

    Label Review

    Current: none · Recommended: bug → gh issue edit 856 --add-label bug

  5. added
    bug
    planned
    on Jul 30, 2026
  6. admarble commented on Jul 30, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete — PR #877

    Scope: AC-4 + the three related defects. AC-1/AC-2/AC-3 deliberately not attempted (see below).

    AC Coverage

    AC Status Note
    AC-1 — owner of the ~106s timer identified NOT_MET Candidate answer (Claude Code 2.1.220 [bg-pty] host-dead watchdog, group SIGKILL) is now preserved in docs/incidents/856/ with the corrected dtrace predicate. Closing it needs a live capture of an intermittent hang under sudo.
    AC-2 — cause of the post-turn hang identified NOT_MET Redirected by the 17:01 investigation: hang and kill are one upstream defect, MCP shutdown is a downstream symptom. Recorded, not proven.
    AC-3 — --no-mcp vs the 0.36s baseline NOT_MET Skipped on purpose — per AC-2's redirect this control now tests the wrong variable. The sharper repro matrix is in the incident doc.
    AC-4 — external termination surfaced as an abort with its cause MET Exit 128+signum, abort banner naming the cause, SIGTERM pointer to the incident doc, sequant logs renders ABORTED.
    Related defect 1 — SIGTERM'd run logged as success MET completeIssue derives from phases; abort forces failure; deriveIssueLogStatus([]) is no longer a pass; additive aborted/abortReason/abortedBy + summary.aborted.
    Related defect 2 — truncated teardown leaks locks MET (recovery only) SIGKILL is uncatchable, so no in-process release can fire. Leaked locks now self-clear via the 24h ceiling on next acquire.
    Related defect 3 — recycled PIDs read as fresh MET Absolute 24h ceiling in classifyStaleness, checked before the same-host PID branch. Clears 505.lock / 708.lock / 803.lock.

    Quality Metrics

    • Full suite: 228 files, 4714 passed, 1 expected fail, 2 skipped
    • Build/typecheck: tsc --noEmit clean; eslint --max-warnings 0 clean; prettier clean
    • Mutation verification: 6 mutations, each killing exactly its intended tests (table in the PR body)

    Risk Assessment

    • Likely failure mode: the 24h lock ceiling is a fixed constant. A future long-running mode (a multi-hour chained run, a paused ready-gate) that legitimately holds a lock past 24h would have it cleared out from under it. Mitigated by SEQUANT_MAX_LOCK_AGE_MS, but the constant would need revisiting rather than the env var being the answer.
    • Not tested: the actual SIGKILL path — untestable in-process by definition. The abort surfacing is verified for catchable signals only (SIGINT/SIGTERM); the real bg-pty kill is SIGKILL, where only the lock-recovery half applies.
    • Not tested: end-to-end that a real interrupted sequant run writes an aborted log. The wiring (registerCleanup → finalize({aborted})) is unit-tested at both ends but not exercised through a live run.

    Progress

    Phase Iterations Status
    Spec 1/1 Complete
    Exec 1/3 Complete
    Test — Skipped (no UI)
    QA 1/2 Complete

    Verdict: AC_MET_BUT_NOT_A_PLUS — everything in the agreed scope is met and verified, but three of the issue's four ACs remain open by design.

    Recommended follow-up

    Split AC-1/AC-2/AC-3 into a dedicated diagnostic issue (both prior /assess runs recommended this), so #856 can close on the work that is actually done. Reopening the diagnosis needs a live capture, not another implementation pass.

    Separately: a test in this suite writes to the shared ${TMPDIR}/claude-parallel-*.marker namespace that the live pre-tool.sh hook reads, and during this run it transiently hijacked the session's worktree enforcement. Worth its own issue.

  7. added a commit that references this issue on Jul 30, 2026
  8. admarble commented on Jul 30, 2026

    @admarble
    ContributorAuthor

    Gap-fix pass — AC-3 now met, untested paths covered

    Follow-up to the previous comment. Everything it listed as unmet-but-fixable or untested is now closed, and one statement in it was wrong.

    AC-3 is met — and the answer is "no"

    Ran the comparison rather than arguing it away. Flipped exactly the variable --no-mcp flips (the Agent SDK's mcpServers option, drivers/claude-code.ts:118), 3 reps per arm, alternating, everything else constant:

    Arm MCP servers Teardown gap Mean
    MCP ON 15 1.69s, 0.82s, 1.17s 1.23s
    MCP OFF 0 1.23s, 1.52s, 1.54s 1.43s

    MCP shutdown does not cause the hang. Both arms sit ~50× below the 58–96s victim band and in the same order as the 0.36s healthy baseline; the MCP-off arm was marginally slower. MCP costs ~5s of startup, not teardown. This is AC-2's redirect confirmed by measurement instead of by reasoning.

    The method is validated against this incident — it reproduces the published victim gaps at their exact death timestamps:

    Published Reproduced At
    92.7s 92.71s 2026-07-29T01:39:36 ✅
    58.0s 57.99s 2026-07-29T01:36:05 ✅

    One correction to the original investigation's method: the metric is TurnEnd → SessionEnd, not SessionStop → SessionEnd. entire records SessionStop as a session phase transition (idle/active → ended); it pairs with SessionEnd for only 10 of 555 sessions and yields multi-day gaps. The Claude Code Stop hook fires at end-of-turn, which entire logs as TurnEnd.

    Limits, stated plainly: n=3 per arm on a trivial prompt, and no hang occurred in any run. This establishes that MCP presence alone does not produce a 58–96s gap; it cannot prove MCP is irrelevant during a hang, because no hang was reproduced. These were direct SDK queries, not full sequant run phases.

    Both scripts are preserved in docs/incidents/856/tools/ so this is reproducible — including the trap that cost two runs: reading MCP servers from ~/.claude.json instead of the desktop config silently yields zero servers and turns the treatment arm into a second control, producing a convincing null result.

    New evidence for AC-1/AC-2

    On the incident day, 8 sessions had a 30–120s teardown gap. Two are the known victims. The other 6 survived. So the post-turn hang is necessary but not sufficient for the kill — consistent with the bg-pty trigger depending on contended socket/adoption state rather than on hang duration. Recorded in the incident doc; AC-1/AC-2 still need the live capture.

    Untested paths now covered

    • End-to-end abort wiring. The unit tests covered each half of the mechanism, but the original defect was neither half — it was the wiring, finalize() called with no argument. New abort-logging.integration.test.ts sends a real SIGTERM/SIGINT to a real process wiring LogWriter + ShutdownManager as the orchestrator does, then reads the log off disk: exit 143/130, aborted: true, abortedBy, summary.passed: 0.
    • That test's own blind spot. It embeds a copy of the orchestrator wiring, so it would still pass if run-orchestrator.ts regressed. A third test asserts the real registerCleanup("Finalize run logs", …) block forwards its abort argument — scoped to that block, not the file. Mutation-verified by reverting the orchestrator to a bare finalize().
    • Recycled-PID recovery against a real lock file. Previously unit-only. Now writes a 30-day-old lock whose PID is 1 (always alive, never ours, kill(1,0) throws EPERM → reads as alive), so only the age ceiling can free it — plus a negative control proving a recent lock on a live PID is still respected.

    8 mutations total now, each killing exactly its intended tests.

    Correction

    My previous comment said a test in the suite writes the shared claude-parallel-*.marker. That was wrong. /exec's parallel-group protocol creates /tmp/claude-parallel-group-1.marker under a hardcoded, globally-shared name, and pre-tool.sh globs that namespace and takes the first hit with no project scoping. So a parallel group in any project redirects worktree enforcement for every concurrent session on the machine — and the session that loses the race gets its guard silently pointed at an unrelated directory, which is worse than the blocked edit that made it visible. Filed as #881.

    Remaining

    AC-1 and AC-2 only, both requiring a live capture of an intermittent hang under sudo dtrace with the corrected predicate (args[2] == 15 || args[2] == 9 — the original captures only SIGTERM and would falsely exonerate). Everything else in this issue is done.

    Verdict: READY_FOR_MERGE for the implementable scope. PR #877.

  9. added 2 commits that reference this issue on Jul 30, 2026
  10. admarble commented on Jul 30, 2026

    @admarble
    ContributorAuthor

    How to test AC-1/AC-2 — plus a correction to the bg-pty attribution

    Went looking for a way to actually test the ~106s kill instead of waiting for it. Two things came out of that: the previous attribution was overstated, and there's a much better lead.

    Correction: the bg-pty conclusion was overstated

    My earlier comment (and the incident doc) called the [bg-pty] host-dead watchdog the cause with "high confidence." That rested entirely on strings extracted from the binary, never on observed runtime behaviour. Watching the runtime changes it:

    • CLAUDE_BG_BACKEND is "daemon". Background tasks are managed by a transient daemon, which spawns bg-pty hosts as a spare pool (~/.claude/daemon.log: bg spare spawned host pid=33010).
    • That daemon is origin=transient and exits idle 5s with no clients. With no daemon up, a backgrounded task is just a child of the interactive claude in its own pgid — no host, no socket. So a naive "is there a bg-pty host?" check returns nothing and looks like a refutation when it's really "not testable right now."
    • The pgid detail also matches the incident: the backgrounded task's shell is its own group leader, so a group kill takes out the sequant run tree while leaving the interactive session alive — which is exactly what happened (the spawning session, pid 70335, is still running).

    The bg-pty watchdog is still a live candidate. It is no longer the only one.

    Stronger lead: the daemon lost its auth token 17 minutes before the first death

    [2026-07-29T06:04:22.520Z] [supervisor] auth: proactive refresh starting
    [2026-07-29T06:04:22.601Z] [supervisor] auth: proactive refresh failed, signalling re-auth required
    [2026-07-29T06:04:22.628Z] [supervisor] auth: headless daemon cannot complete OAuth — run `claude auth login` to refresh
    [2026-07-29T06:04:22.632Z] [supervisor] auth: no token found, will re-check keychain every 30s
    
    Event UTC After auth loss
    daemon auth lost 06:04:22 —
    victim 1 started / died 06:20:10 / 06:21:57 +15.8 / +17.6 min
    victim 2 started / died 06:34:20 / 06:36:05 +30.0 / +31.7 min
    victim 3 started / died 06:37:52 / 06:39:36 +33.5 / +35.2 min

    All three victims started inside the unauthenticated window, and no run has died outside it. An unauthenticated supervising daemon would explain both halves at once: an agent blocking on an auth-dependent teardown step, and a supervisor that eventually tears the tree down.

    Three samples is correlation, not cause. Stating it because it is the strongest untested lead and — unlike the intermittent hang — it is inducible on demand. Caveat: the daemon log has no entry at any of the three death timestamps, so whatever killed them didn't log it there.

    Recovered: the killed run's own stdout, still on disk

    tasks/b6byn5iih.output from the incident session survived (its orphaned tail -f is still running, 22h later):

    [01:34:18] ▸ #846 spec
    
    !  Received SIGTERM, shutting down gracefully...
    ✓ Aborted 1 active phase
    

    Then nothing — no cleanup task ever reported. Two consequences:

    1. Received SIGTERM was captured, not inferred. The first signal is catchable, so much of this is observable without dtrace at all.
    2. This is the SIGTERM→SIGKILL escalation caught in the act, and it confirms the code path PR fix(#856): surface externally-terminated runs as aborts; stop logging them as success #877 fixes is the one that actually runs.

    The test plan — three tiers, cheapest first

    Tier 1 — induce the auth window (no sudo, best lead). The only condition separating every victim from every survivor. Start the daemon, invalidate its token, confirm auth: no token found, then launch sequant run backgrounded from inside an interactive session with tools/watch-signals.sh --no-dtrace recording. Positive → AC-1 and AC-2 both collapse to "unauthenticated daemon tears down its background tree." Negative → the correlation is coincidence, worth knowing before anyone builds on it.

    Tier 2 — induce a wedged host (deterministic). tools/induce-bgpty-hang.sh. The watchdog's condition is "pid alive but socket won't accept", and kill -STOP produces exactly that — so the mechanism is testable without waiting for the intermittent trigger. Requires a running daemon first.

    Tier 3 — name the sender (sudo; SIP may block). sudo tools/watch-signals.sh. Only dtrace identifies the sender directly. SIP is enabled here, so the script preflights the probe — an empty capture under SIP means unknown, never nothing was sent. Captures signal 9 and 15.

    All three scripts are in docs/incidents/856/tools/ in PR #877.

    One harness bug worth recording, found by dry-running it: a loose grep bg-pty matched the script's own command line and SIGSTOPped the parent shell. Target selection is now strict and refuses self/parent, mirroring LockManager.signalOther's guard.

  11. added 3 commits that reference this issue on Jul 30, 2026
  12. 22 remaining items

  13. added 12 commits that reference this issue on Sep 9, 2026
  14. added a commit that references this issue on Sep 30, 2026
  15. admarble commented on Oct 6, 2026

    @admarble
    ContributorAuthor

    Upstream fixes to re-test against before more work here: v2.1.288 (#1334) "Fixed headless (-p / SDK) sessions occasionally ignoring SIGTERM when a supervisor such as timeout or systemd sends SIGCONT alongside it", and v2.1.285 (#1328) "Fixed synchronous hooks hanging Claude Code while a background process the hook started kept its output open". templates/hooks/post-tool.sh:377 backgrounds a subshell ( … ) & without detaching its stdout/stderr, so it is one such process. Reproduce on ≥ 2.1.288 first. If the hang is gone, record that here and close, or narrow the issue to what remains.

  16. admarble commented on Oct 9, 2026

    @admarble
    ContributorAuthor

    Correction to my 2026-10-06 comment. The two upstream fixes I pointed at do not touch this bug's mechanism, so a re-test against them would prove nothing.

    • v2.1.288's SIGTERM fix is about headless sessions ignoring SIGTERM. This bug is a SIGKILL to the whole process group from Claude Code's bg-pty watchdog.
    • v2.1.285's hook-hang fix is about a synchronous hook waiting on a background child. That is unrelated to the watchdog declaring a bg-pty host dead.

    Status as of 2026-10-09 (Claude Code 2.1.295, sequant 2.19.0):

    No new evidence suggests a code change in Sequant. Closing, narrowing to the upstream tracker, or keeping this open as the recurrence tracker is the owner's call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions