Skip to content

fix(run): a watchdog-killed run writes no run log and half-deletes a clean worktree — worktree removal outruns the 5 s SIGKILL grace #1222

Closed

Description

@admarble

Tier: mechanical Found: 2026-09-29, field graph wave 3 (tracker #1203)

Problem. When the MCP no-progress watchdog kills a sequant run, the run writes no run log and can leave a half-deleted worktree. The chain, traced in code:

  1. killProcessGroup sends SIGTERM, then SIGKILL after SIGKILL_GRACE_MS = 5000 (src/mcp/tools/run.ts:1039).
  2. ShutdownManager runs cleanups last-in-first-out (src/lib/shutdown.ts:279). "Finalize run logs" is registered early (run-orchestrator.ts:817). Each Cleanup worktree for #N is registered later, as its worktree is created (worktree-manager.ts:457), so the worktree cleanups run first.
  3. cleanupWorktreeOnShutdown force-removes any worktree that is not dirty (worktree-manager.ts:437), even if its phase is mid-flight with all work committed. git worktree remove --force on a tree with node_modules takes longer than 5 seconds.
  4. SIGKILL lands during the removal. The worktree is left partly deleted, and "Finalize run logs" never runs.

Observed: the 4-issue sequant_run for #1213/#1200/#1209/#1198 was killed at 3561 s ("no progress for 1800000ms"). No run-*.json was written for that run. #1198's worktree (clean, 3 WIP commits, exec in progress) came back with 44 tracked top-level files deleted (bin/, evals/, stacks/, CHANGELOG.md, LICENSE, .mcp.json, …) while src/, node_modules/ etc. remained. git checkout -- . restored it. #877 made SIGTERM finalize the log as aborted, but that cleanup is queued behind the removals and never reached.

Not previously filed (checked #877, #935, #1049, #1032).

AC

  • AC-1: On a signal-driven shutdown, "Finalize run logs" runs before any worktree-removal cleanup, so an aborted run log is written even if the process is SIGKILLed during worktree removal. Evidence: npx vitest run src/lib/shutdown.test.ts src/lib/workflow/run-orchestrator.test.ts
  • AC-2: On a signal-driven shutdown, a worktree whose issue has a phase in progress, or that has commits not on the base branch, is preserved rather than force-removed. Only a clean worktree with no branch-only commits is removed. Evidence: npx vitest run src/lib/workflow/worktree-manager.test.ts
  • AC-3: The MCP kill's SIGKILL grace is at least as long as the shutdown manager's own force-exit timeout, so a cleanup that respects its own timeout is not cut off by the outer SIGKILL. Evidence: npx vitest run src/mcp/tools/run.test.ts

Graph metadata

  • Blocked by: (none)

May touch

  • src/lib/shutdown.ts, src/lib/shutdown.test.ts
  • src/lib/workflow/run-orchestrator.ts, src/lib/workflow/run-orchestrator.test.ts
  • src/lib/workflow/worktree-manager.ts, src/lib/workflow/worktree-manager.test.ts
  • src/mcp/tools/run.ts, src/mcp/tools/run.test.ts

Related: #1049 (the watchdog itself), #877 (SIGTERM → aborted log), #935 (preserve dirty worktrees on signal).

Activity

  1. added
    bug
    graph-2026-09-prerelease
    on Sep 30, 2026
  2. admarble commented on Sep 30, 2026

    @admarble
    ContributorAuthor

    Context for the run (re-checked against main @ 9da8aeb8, 2026-09-30; graph tracker #1236, wave 1)

    The line refs in the body all still hold:

    • src/mcp/tools/run.ts:1039: SIGKILL_GRACE_MS = 5000.
    • src/lib/shutdown.ts: cleanups run LIFO (:278), and forceExitTimeout defaults to 10000 ms (:126).
    • run-orchestrator.ts:817: "Finalize run logs" is registered early.
    • worktree-manager.ts:457: Cleanup worktree for #N is registered later, lazily as each worktree is created.
    • worktree-manager.ts:427: cleanupWorktreeOnShutdown.

    Shape of the fix:

    • AC-1: registration order can't solve this, because the worktree cleanups register lazily after the log finalizer, so LIFO always runs them first. Prefer something structural: one early-registered "worktrees" cleanup that iterates a list the manager appends to, or a priority/phase field on cleanup tasks, so "Finalize run logs" provably runs before any worktree removal. Avoid an ordering hack that depends on call order.
    • AC-2: "phase in progress" is orchestrator state. Pass a predicate or Set into the registration rather than having worktree-manager read state itself. The commits-ahead-of-base rule alone would have saved feat(logs): run log records each phase's model and the sequant version #1198's worktree, which was clean with 3 WIP commits. Compare against the worktree's actual base, not a hardcoded origin/main (see bug(exec): sequant run worktrees never record sequantBase, so the zero-diff/uncommitted guard compares against origin/main and a --base ahead of main disables it #1234, where sequantBase is never written).
    • AC-3: name the relationship in code. SIGKILL grace ≥ the shutdown manager's force-exit timeout (10000 ms today), preferably derived from one shared constant rather than two literals that can drift.

    Standard block:

  3. admarble commented on Sep 30, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (3 ACs, 4 files: src/lib/shutdown.ts, src/lib/workflow/run-orchestrator.ts, src/lib/workflow/worktree-manager.ts, src/mcp/tools/run.ts)

    AC Quality Check

    All 3 AC pass lintAcceptanceCriteria — single-line, declared Evidence: resolving to unit_test, no vague/unmeasurable/open-ended flags.

    Traced against main@9da8aeb8 — none are vacuous, all currently fail:

    • AC-1: shutdown.ts:279 is strict LIFO. "Finalize run logs" registers early (run-orchestrator.ts:817); per-worktree cleanups register later (:1222) → LIFO runs it last.
    • AC-2: shouldPreserveWorktree (worktree-manager.ts:410) checks only git status --porcelain — no phase-in-progress or commits-ahead-of-base check. Root cause of feat(logs): run log records each phase's model and the sequant version #1198's data loss.
    • AC-3: SIGKILL_GRACE_MS = 5000 (run.ts:1039) < ShutdownManager's forceExitTimeout = 10000 (shutdown.ts:126).

    Scope Assessment

    Non-Goals: ⚠️ Not found in issue body — low-risk to omit given a traced, owner-narrowed 3-AC fix.

    Metric Value Status
    AC items 3 ✅
    Directory spread src/lib/ + src/mcp/tools/ ✅

    Verdict: ✅ SCOPE_OK (performScopeAssessment: "3 AC items, 0 directories", trivial short-circuit)


    Acceptance Criteria

    AC-1: "Finalize run logs" always precedes worktree-removal cleanup on signal shutdown

    Verification: Unit Test
    Scenario: Given "Finalize run logs" registered early and worktree-removal tasks registered later → When gracefulShutdown(signal) runs → Then log-finalize executes before any worktree removal, regardless of registration order.
    Assumptions: Fix lives in ShutdownManager itself, testable in isolation in shutdown.test.ts.

    AC-2: A worktree with an in-progress phase or unmerged commits is preserved on signal shutdown

    Verification: Unit Test
    Scenario: Given a git-clean worktree with commits not reachable from its base, or whose issue has a phase running → When signal shutdown cleans it up → Then it's preserved. A worktree with none of these is still removed.
    Assumptions: Phase-in-progress read from RunOrchestrator.issueStates (:371), passed in — not re-derived by worktree-manager.ts. Base comparison reuses the resolveBaseRef pattern (phase-executor.ts:841: branch.<name>.sequantBase config, falls back to origin/main) rather than a hardcoded origin/main. Known gap (#1234, out of scope): sequant run-created worktrees often lack sequantBase, so the fallback path will be common.

    AC-3: SIGKILL grace ≥ shutdown manager's force-exit timeout

    Verification: Unit Test
    Scenario: Given forceExitTimeout (10000 ms default) → When SIGKILL_GRACE_MS is read → Then it's ≥ that value, derived from one shared constant.
    Assumptions: A small buffer above equality (e.g. +1000 ms) avoids racing a cleanup's own process.exit() against the outer SIGKILL.


    Implementation Plan

    Phase 1: ShutdownManager cleanup phasing (AC-1)

    1. Add a phase option to registerCleanup(name, task, { phase? }) — "finalize" (runs first) vs. default "resource" — sorted before LIFO-within-phase, so the existing LIFO test (shutdown.test.ts:147) still holds for same-phase tasks.
    2. Sort tasksToRun by phase in gracefulShutdown before reversing.
    3. Register "Finalize run logs" (run-orchestrator.ts:817) with { phase: "finalize" }.

    Phase 2: Worktree preservation predicate (AC-2)

    1. Extend shouldPreserveWorktree in worktree-manager.ts to also check phaseInProgress and commits-ahead-of-base (git rev-list --count <base>..HEAD, base via a resolveBaseRef-equivalent — direct import from phase-executor.ts is safe, no existing cycle; extract to a shared helper instead if that pulls in too much surface).
    2. Change cleanupWorktreeOnShutdown/registerWorktreeRemovalCleanup to take a () => boolean phase-in-progress callback (lazy — phase state changes over the run), not a boolean snapshot.
    3. At run-orchestrator.ts:1222, pass () => this.issueStates.get(issueNum)?.currentPhase != null.

    Phase 3: SIGKILL grace vs. force-exit timeout (AC-3)

    1. Export the force-exit default as a named constant from shutdown.ts.
    2. In run.ts, derive SIGKILL_GRACE_MS from it plus a buffer instead of the standalone 5000 literal.

    Design Review

    1. Where does this belong? Ordering (AC-1) → ShutdownManager (general contract, not orchestrator wiring). Preservation policy (AC-2) → worktree-manager.ts, but live phase-state input → RunOrchestrator, passed in. The timeout constant (AC-3) → shutdown.ts, since run.ts is the dependent.
    2. Simplest correct approach? AC-1: (a) a phase field on CleanupTask, recommended — unit-testable in isolation, independent of orchestrator call order, matches the AC's own evidence file. (b) a single early-registered aggregate "Cleanup worktrees" task (owner's alternate suggestion) — rejected as primary: changes when worktree cleanups are captured, a larger change to run-orchestrator.ts's control flow for the same outcome.
    3. Existing pattern? AC-2 reuses resolveBaseRef (fix(orchestrator): respect custom base branch in exec zero-diff guard (#534 follow-up) #537) instead of a second base-resolution path. AC-3 follows the owner's "one shared constant" instruction directly.
    4. Reviewer pushback? Whether worktree-manager.ts should import resolveBaseRef directly from phase-executor.ts or via an extracted shared helper — import if narrow, extract if it drags in more surface than that one function.

    ADR required in the exec PR: Q2 names a rejected alternative for ShutdownManager ordering — add docs/adr/0003-<slug>.md per docs/adr/README.md.


    Feature Quality Planning

    All standard checks pass. Notable items:

    • No full npm test in exec/qa — targeted: timeout 600 npx vitest run src/lib/shutdown.test.ts src/lib/workflow/run-orchestrator.test.ts src/lib/workflow/worktree-manager.test.ts src/mcp/tools/run.test.ts (run-orchestrator.test.ts can be slow; keep the timeout).
    • Add a CHANGELOG ### Fixed entry under [Unreleased].
    • If any AC is treated as a gate test, failedTest in the mutation marker must start with the test file path.

    Open Questions

    1. phase as a fixed 2-value enum vs. open numeric priority? Recommendation: fixed enum ("finalize" | "resource") — only two ordering classes exist today; a numeric priority invites unneeded tiers. Impact if wrong: a low-cost additive widening later.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: SCOPE_OK, 3 well-specified AC with an owner comment already narrowing the fix shape and naming touchpoints — low ambiguity. testgen skipped per the bug-label-only rule despite declared Unit Test evidence, since exact test files/assertions are already named.


    Label Review

    Current: bug, graph-2026-09-prerelease
    Recommended: bug, graph-2026-09-prerelease, planned
    Reason: Correctly labeled; add planned per spec-phase convention.
    Quality Loop: Won't auto-enable — SCOPE_OK, no complexity/refactor label.

    → gh issue edit 1222 --add-label planned

  4. added
    planned
    on Sep 30, 2026
  5. admarble commented on Sep 30, 2026

    @admarble
    ContributorAuthor

    QA Verdict: NEEDS_VERIFICATION

    AC coverage: 3/3 met

    Gaps:

    • Required CI check still pending
    • Orchestrator registration of Finalize run logs as a finalize-phase cleanup (and the isPhaseInProgress callback wiring) has no test
    • Preserve log message misstates the reason when a worktree is kept for phase-in-progress or commits-ahead-of-base
    • worktree-manager.ts:479: the preserved message still says preserved (uncommitted changes) even when the worktree was kept because a phase was running or it had commits ahead of base. After a kill like feat(logs): run log records each phase's model and the sequant version #1198's (clean tree, 3 commits), that message would be wrong.
    • There is no orchestrator-level test that "Finalize run logs" is registered as phase: "finalize", or that the shutdownOrchestratorRef callback reaches isPhaseInProgress (see the mutation above).

    Suggestions:

    • Include the preservation reason in the log line.
    • If a worktree was provisioned before the RunOrchestrator exists, instance is undefined and the phase check returns false. That's safe, because the commit check still applies, but a comment saying so would help.
  6. added a commit that references this issue on Sep 30, 2026
  7. admarble commented on Sep 30, 2026

    @admarble
    ContributorAuthor

    Runner verification: PR #1238 (QA NEEDS_VERIFICATION, 3/3). QA's key gap was real: the orchestrator's { phase: "finalize" } registration had no test (removing it left every suite green). The runner extracted registerRunLogFinalizer and phaseInProgressPredicate and tested both. Each mutation now fails exactly its test. The preserve message also names its real reason now (uncommitted changes | phase in progress | commits ahead of base), which covers the #1198 shape of a clean tree with committed WIP. There are no new import cycles, and currentPhase clears between phases. Details in the PR.

  8. added a commit that references this issue on Sep 30, 2026
  9. added a commit that references this issue on Sep 30, 2026
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

    buggraph-2026-09-prereleaseplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions