Repository navigation
fix: settle crash-orphaned StateRunning sessions (closes #475) - #485
Merged
Merged
Conversation
…sessions Session.Abandon() is a 4th terminal-recovery seam, sibling of Reopen/Interrupt/Recover, legal only from StateRunning. It repairs any trailing unanswered tool_use via the shared closeOutInterruptedTurn history repair using a new abandonment-accurate close-out message (never claiming a cancellation or a run failure, neither of which was observed), then resetToIdle()s exactly like the other three seams. This closes the gap where a session left StateRunning by a process that exited mid-turn had no recovery path and could report "in progress" forever. Part of #475. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…essions Service.SessionStale (age horizon first, then IsLive, then a bounded trial lease acquire as a secondary refinement) decides whether a persisted StateRunning snapshot is a crash-orphan rather than a genuinely in-flight run, mirroring internal/adapter/scheduler/scheduler.go's shouldReconcileStaleFire/isPriorFireLive ordering: age is a hard precondition (the only defense that covers subagent-*/parallel-*/team-* children, which IsLive never sees), a self-held real lease with IsLive==false counts as staleness rather than liveness, and ErrLeaseUnsupported stickily disables the whole sweep rather than falling back to a per-candidate local-only check. Service.SettleIfStale performs the actual repair (Load, re-check State==StateRunning to close the meta-scan/load TOCTOU, Abandon, Save) once a caller has decided a candidate is stale; it makes no staleness decision of its own. Both are exported for internal/app's future composition-level sweep (Step 4) to consume, mirroring the existing IsLive/Diagnostics exports childgc.go already relies on. Neither function is wired into any call site yet — Steps 3 and 4 of the plan consume them. Part of #475. Co-Authored-By: Claude Sonnet 5 <[email protected]>
StartRunContent now abandons a session whose persisted snapshot is stuck in StateRunning (a process that died mid-turn without ever reaching a terminal state) AFTER runEntryMu.lock(id) + the real acquireLease have both succeeded - never inside loadAndReopen's pre-lock switch, where a trial lease could race a concurrent caller or reject a peer's genuine acquireLease. The successful lease acquire is itself the proof of exclusive ownership, so the repair needs no trial lease or age-horizon oracle. Investigated whether StartRunContent can re-enter this point while the same id is already live in s.runs: runEntryMu only serializes the run-entry section, not a run's full lifetime, so a second call for the same id CAN land here while an earlier run this process started is still genuinely live (e.g. mid multi-turn, blocked on a later model call after an earlier turn's e.save already persisted StateRunning). Added an explicit IsLive(id) guard that refuses the repair with ErrFailedPrecondition instead of racing the live run, and a regression test proving no extra Store.Save fires when it's live. loadAndReopen's switch is left untouched (still only completed/cancelled/ failed) with explicit no-op comments for awaiting/idle and a note pointing at the new repair site. Part of #475. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ticker Part of #475. Adds internal/app/session_reconcile.go: a composition-level sweep that enumerates stored sessions via Service.ListSessions, narrows to state=="running" rows excluding "sched--" fire ids (the scheduler owns its own stale-fire reconciler), and settles every candidate Service.SessionStale judges to be a crash orphan via SettleIfStale. This is the ONLY repair path that reaches a subagent-*/parallel-*/team-* child crash-orphaned in StateRunning, since the run-entry funnel's own repair (Step 3) only fires when a caller re-opens the exact session id. Runs on its own cancelable lifetime (the startLiveModelRefresh idiom, not childGC's Build-ctx-tied one) since it is unconditional and always keeps a persistent ticker goroutine — folded into Built.Close so a caller that never cancels Build's own ctx still gets a clean teardown. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ease-sweep-disable Part of #475. - startStaleSessionReconcile's closer now cancel()s AND wg.Wait()s (mirroring startLiveModelRefresh's exact idiom), so Built.Close() can no longer return while the sweep is mid-SettleIfStale — closing the shutdown race where a write could land against a closing store connection. - sweepStaleSessions now skips its entire pass when Service.LeaseSweepDisabled() is true, instead of still doing a full ListSessions scan every tick forever after the lease backend has sticky-disabled itself. SessionStale already logs the sticky-disable transition once, so the skip stays silent.
…md + ADR 0027) Widens the "reopen-if-completed/interrupt-if-cancelled/recover-if-failed" invariant in AGENTS.md to name Abandon as the 4th run-entry recovery seam, explain why awaiting is deliberately untouched, and describe the two repair paths (StartRunContent's post-lease check, the composition-level sweep) that route through it. Adds ADR 0027 Phase 6 documenting the same mechanism in full: the problem, the fix, the honest last-write-wins-narrowed-by-a-window characterization, the new List 1 resource row for the sweep goroutine, and the three named residuals (orphaned-awaiting, the scheduler's most-recent- fire-only reconciler, and the funnel repair's lease-proof-not-age-horizon framing gap for child session ids). Part of #475. Co-Authored-By: Claude Sonnet 5 <[email protected]>
A review caught that the residual described a "concurrent second StartRunContent call" as the trigger for repairing a genuinely-live child session out from under it. Unlike the main-session case, there is no "first" funnel call that registers a child's run for IsLive to see — a single StartRunContent at a live child id is already enough, since IsLive is structurally blind to subagent-*/parallel-*/team-* children by design. Part of #475.
TestBuildSettlesStaleRunningSnapshotAcrossRestart pins the actual reported bug (a subagent-*-prefixed child crash-orphaned in StateRunning with a dangling tool_use, aged past staleSessionWindow, that nobody ever prompts or resumes again). Build 1 seeds the snapshot directly into the durable jsonlstore (bypassing StartRunContent, so the population is exactly the one the run-entry funnel repair can never reach) and closes without starting any run for the id. Build 2 opens fresh over the same store dir, drives one deterministic sweepStaleSessions pass, and asserts ListSessions reports the id settled to idle with ValidateToolPairing clean on reload — no prompt or resume in between. Negative-control verified in a throwaway git worktree pinned to 3f37a1f4 (Step 1 only, before Steps 2-4 landed): copying this test file there fails to COMPILE (`crashOrphanedSessionFixture` and `sweepStaleSessions` are undefined at that commit), confirming the test actually depends on the Step 2/4 mechanism rather than passing vacuously. The scratch worktree was removed after verification; this worktree's history and tip are unaffected. Part of #475. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…e mechanism Part of #475.
…n ids A child's session id (subagent-/parallel-/team-) is deliberately surfaced to the parent's caller via the agentId:/Team id: result trailer and InspectSubagent/InspectMember's MemberSessionID scheme. Service.IsLive is structurally blind to children (they are driven in-process by their parent's dispatch, never registered in s.runs), so a caller who learned a child's id could StartRunContent it directly while the parent was still genuinely driving it: IsLive would read false, and the StateRunning crash-orphan repair would Abandon()+Save the child's history out from under the parent, racing the parent's own drive and risking reintroducing the dangling-tool_use/ provider-400 hazard issue #475 exists to close. StartRunContent now rejects any subagent-/parallel-/team- prefixed id outright with ErrInvalidArgument, unconditionally and before loadAndReopen, the lease/lock, or the StateRunning repair branch. sched--prefixed schedule- fire sessions are excluded (scheduler_fire.go legitimately drives them through this same funnel). Part of #475. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ling, logging, test dedup) Fix six small, independent findings from the /panel-review + security-fix follow-up on issue #475: - IsLive's doc comment now states the current truth: StartRunContent's isDelegationChildSessionID guard rejects any subagent-/parallel-/team- prefixed id before it ever reaches the run registry, so IsLive no longer "genuinely protects" such an id. - sweepStaleSessions now distinguishes a genuine ListSessions error (logged via port.Diagnostics, WARN) from the degrade-to-empty no-candidates case (still a silent no-op). - SettleIfStale now wraps its three fallible steps (Load/Abandon/Save) with short step-identifying prefixes, matching StartRunContent's own inline repair and ForkSession's house style. - session_reconcile.go's new diagnostics call passes err.Error() (a string), matching the established convention in service.go's diag.Log call sites. - staterunning_repair_test.go's crash-orphan session fixtures now reuse settle_test.go's crashOrphanedSession helper instead of reimplementing the shape inline (TestStartRunContentAbandonsStaleRunningSession and TestStartRunContentRejectsDelegationChildSessionID). - TestStartRunContentRejectsDelegationChildSessionID now wires the same countingStore TestStartRunContentLeavesLiveRunningSessionAlone uses, so its "ZERO extra Store.Save" claim is actually counted rather than asserted only in prose. Part of #475. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Rebasing onto origin/main pulled in #491, which moved jsonlstore session files under an owner-only sid-v1/ subdirectory. The stale-running-session e2e test's glob predated that change and stopped finding the seeded snapshot file; check both the pre- and post-#491 locations, mirroring the existing setSessionMtime test helper. Also regenerates llms.txt and picks up additive go.work.sum checksums from the rebase. Co-Authored-By: Claude Sonnet 5 <[email protected]>
jhrozek
force-pushed
the
fix/stale-running-sessions
branch
from
August 13, 2026 11:14
c861a65 to
f5cd5c5
Compare
JAORMX
approved these changes
Aug 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #475: a session crashed mid-turn (the process died) is left
StateRunningforever in its persisted snapshot./sessions(mecatui) andService.ListSessionsreport it as in-progress indefinitely, even across restarts, even if nobody ever touches it again — and a follow-up prompt risks a provider HTTP 400 from an unrepaired danglingtool_use.Confirmed against a real session (
645004ce13d2b8dd10adc384e161f786, a background subagent child) whose last snapshot line read"state":"running"with no matching result for its trailing tool call.What changed
Session.Abandon()(engine/session/session.go) — a 4th recovery seam alongsideReopen/Interrupt/Recover, legal only fromStateRunning, closing out any orphaned trailingtool_usewith an accuracy-specific message (never claiming a cancellation or failure that wasn't observed).Service.SessionStale/SettleIfStale/LeaseSweepDisabled(internal/adapter/server/service.go) — an age-horizon-first staleness decision. Age gates before liveness/lease checks deliberately:IsLiveis structurally blind tosubagent-*/parallel-*/team-*delegation children even mid-run, so a liveness-only oracle would miss exactly the population the confirmed bug came from. A lease trial-acquire is a secondary refinement for multi-replica/leased deployments (mecak8s + Redis), with a self-held-lease correction and a sticky disable (not a silent per-candidate fallback) if the lease backend doesn't support the probe.StartRunContent, placed after the real lease/lock are held (never a trial lease there) — closes the touch-triggered case without ever being able to reject a peer's genuineacquireLease.internal/app/session_reconcile.go, wired inbuild.go) — settles sessions nobody ever prompts again, fixing the/sessionsdisplay symptom directly.StartRunContentwas wire-reachable with an arbitrary session id, and delegation-child ids are deliberately surfaced to callers (agentId:trailers,InspectSubagent). A caller could target a live child directly, and sinceIsLivecan't see children, the repair would abandon its history out from under the parent's own dispatch. Now rejected outright withErrInvalidArgumentbefore any session I/O.AGENTS.md's run-entry-funnel invariant widened to the 4-seam reality; a new Phase 6 indocs/adr/0027-cloud-native.mdwith the mechanism, the explicit "last-write-wins narrowed by a window, not atomic" characterization, and two named accepted residuals (orphaned-awaitingsessions; the scheduler's stale-fire reconciler covering only the most recent fire per schedule).Process note
Every commit on this branch went through an individual implement → adversarial-review cycle, several with real fix-up rounds driven by mutation testing (not just re-reading) — including three genuinely different design iterations before the lease-liveness mechanics were sound. A final three-axis panel review (spec / standards / domain) caught the wire-reachability gap above before merge.
Test plan
task lint && task testgreen (root module + engine module + engine-standalone hygiene proof + provider submodules)go run ./cmd/mecademoprints a full offline session including the background-subagent flowBuild()end-to-end test (TestBuildSettlesStaleRunningSnapshotAcrossRestart) reproduces the confirmed bug's exact shape and proves it's settled purely throughBuild's own composition wiring, with no prompt in between — negative-controlled against the pre-fix commit (fails to compile there)Closes #475.