Skip to content

fix(server): let the stale-session sweep re-acquire a lost lease - #1302

Merged
jhrozek merged 2 commits into
mainfrom
fix-sweep-lease-tombstone
Sep 9, 2026
Merged

jhrozek merged 2 commits into
mainfrom
fix-sweep-lease-tombstone

Conversation

@jhrozek

@jhrozek jhrozek commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Fixes stale-session sweep can never recover a session whose lease loss was self-inflicted (late renew, not a real competitor) #1299: the crash-orphaned-running-session reconcile sweep (SettleIfStale, issue Sessions left StateRunning by a crash report as in-progress forever #475) could never recover a session whose lease was lost via a merely-late renew rather than a real competing owner — flocklease.Renew returns ErrLeaseHeld identically for both cases, and the resulting lostOwnership tombstone is otherwise only ever cleared by CloseSession's teardown (fix(server): let CloseSession clear a stale lost-lease tombstone #1266), which the sweep never reaches. It failed identically on every 5-minute sweep tick, forever, until a process restart.
  • Adds acquireMutationLeaseForStaleSettle, used only by SettleIfStale: its caller is authorized as the system stale-reconciler and has already independently verified (age-horizon + IsLive) that the session is a genuine crash orphan, so it's safe to attempt a real re-Acquire past the tombstone and clear it on success. Every other lease caller (normal run-entry, ApproveRun's awaiting-resume, RenameSession/DeleteSession/other management mutations) is untouched — a stale owner must still be permanently refused there even when no successor ever took over (pinned by TestADR_0294_AwaitingLeaseLossRetractsLocalAskPreservesSnapshot and two session-affinity-and-handoff scenario tests; an earlier, broader version of this fix regressed all three and was reverted in favor of this narrow scoping).
  • Extracted the shared Acquire→classify→install-and-renew body into acquireLeaseCore(ctx, id, bypassTombstone bool), used by both reaffirmLease (the unchanged general path) and the new function — this also fixes a real lease-leak: the old duplicated dup-collapse check treated any existing heldLeases[id] entry as a live winner, including a stale invalidated one onLeaseLost's preserveAwaiting branch deliberately leaves behind, silently dropping a freshly-Acquired lease without ever releasing it.
  • Documents (rather than gates) that the stale-settle path skips acquireLease's drain check — repairing an already-crash-orphaned session is cleanup, not a new admission.
  • Corrects two comments/docs that claimed CloseSession is the only place the tombstone is cleared (lostOwnership's field doc, and ADR 0027 List 1 row 27).

This PR went through a 9-agent MoE panel review (Spec/Standards/Test-adequacy axes + a 6-agent Domain panel: secure-code-reviewer, go-security-reviewer, software-architect, go-architect, library-reuse-reviewer, code-duplication-reviewer). All important-and-above findings are addressed in the second commit; one reviewer's "blocker" (claiming the new function was unreferenced dead code) was independently verified false.

Test plan

  • TestStaleSessionSweepRecoversAfterSelfInflictedLeaseLoss (new): reproduces the deadlock via a genuine renewer failure (not a shortcut), fails without the fix, passes with it.
  • TestStaleSessionSweepRefusesWhenGenuinelyHeldElsewhere (new): the sweep's bypass still correctly refuses when a real competitor holds the lease, snapshot left untouched.
  • go test ./internal/adapter/server/... — full suite green, including TestADR_0294_AwaitingLeaseLossRetractsLocalAskPreservesSnapshot and the Scenario5/Scenario7 session-affinity-and-handoff tests (unregressed).
  • go build ./..., go vet ./..., gofmt -l, golangci-lint run ./internal/adapter/server/... (0 issues).
  • docs/lint TestRealDesignDocsCitations (ADR citation check) green.
  • Pre-existing, unrelated failures on main (TestReconcileStaleFireAfterSessionSettles, TestSessionDebuggerCrossBoundaryAcceptance) confirmed present without this change too — not introduced by this PR.

🤖 Generated with Claude Code

@jhrozek
jhrozek force-pushed the fix-sweep-lease-tombstone branch from 9d6f50d to 743e86b Compare September 9, 2026 18:35
jhrozek and others added 2 commits September 9, 2026 22:25
SettleIfStale (the crash-orphaned-running-session reconcile sweep,
issue #475) could never recover a session whose lease was lost via a
merely-late renew rather than a real competing owner: flocklease's
Renew returns ErrLeaseHeld identically for both cases, onLeaseLost
sets a permanent lostOwnership tombstone, and reaffirmLease fails
fast on that tombstone without ever attempting a real backend
Acquire. The only caller that ever clears the tombstone is
CloseSession's teardown (77e2b32), which SettleIfStale never
reaches — so a session recovered only by the periodic sweep (never
closed) was stuck in StateRunning forever, failing "session is leased
by another process" on every sweep tick.

Add acquireMutationLeaseForStaleSettle, used only by SettleIfStale:
its caller is already authorized as the system stale-reconciler and
has independently verified (age-horizon + IsLive) that the session is
a genuine crash orphan, so it attempts a real Acquire past the
tombstone and clears it on success. Every other lease caller
(acquireLease/reaffirmLease, and therefore normal run-entry and
approval-resume) is untouched — an earlier, broader version of this
fix regressed the awaiting-lease-loss and session-affinity/handoff
tests, which deliberately require a stale owner to stay refused even
when no successor ever took over.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Extract the Acquire->classify->install-and-renew body shared by
reaffirmLease and acquireMutationLeaseForStaleSettle into one
acquireLeaseCore(ctx, id, bypassTombstone bool), fixing two real
issues the duplication was hiding:

- The post-Acquire dup-collapse only ever checked for ANY existing
  heldLeases[id] entry. onLeaseLost's preserveAwaiting branch
  deliberately leaves a stale, invalidated entry behind (it isn't
  deleted, only marked invalid) — so a stale-settle re-Acquire that
  landed on such an id would see that stale entry, wrongly treat it
  as a live winner, cancel its own just-acquired lease's renewer, and
  drop the fresh port.Lease without ever releasing it. The dup-check
  now only collapses against a genuinely VALID existing entry.
- Four independent reviewers (Standards, software-architect,
  library-reuse-reviewer, code-duplication-reviewer) flagged the
  ~50-line duplication itself as a drift risk; the shared core
  removes it while keeping the one safety-relevant axis
  (bypassTombstone) as an explicit, documented parameter rather than
  folding it into shared control flow.

Also, per review:
- Document (don't gate) that the stale-settle path skips
  acquireLease's drain check — repairing an already-crash-orphaned
  session is cleanup, not a new admission, so this is deliberate.
- Correct two comments that still claimed CloseSession is the ONLY
  place lostOwnership is cleared (the lostOwnership field comment,
  reverted to stale wording by an earlier `git checkout`, and ADR
  0027 List 1 row 27).
- Cross-reference TestCallerIdentityEdgeRejectsMalformedPrincipal
  (caller_identity_test.go) from the new method's doc comment: it
  already pins that staleReconcileAuthorized's system-principal check
  can't be forged from any external gRPC/HTTP surface, closing the
  "no co-located test" gap a reviewer raised.
- Add TestStaleSessionSweepRefusesWhenGenuinelyHeldElsewhere: the
  negative case adjacent to the recovery test — a real competitor
  holding the lease when the sweep runs must still be refused, with
  the durable snapshot left untouched.

One reviewer's "blocker" (claiming acquireMutationLeaseForStaleSettle
was unreferenced dead code) was independently verified false — a
stale patch snapshot on that reviewer's side, not a real gap.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek force-pushed the fix-sweep-lease-tombstone branch from 743e86b to aa1a53d Compare September 9, 2026 20:25
@jhrozek
jhrozek merged commit 0841e8e into main Sep 9, 2026
32 of 33 checks passed
@jhrozek
jhrozek deleted the fix-sweep-lease-tombstone branch September 9, 2026 20:54
jbeda added a commit that referenced this pull request Sep 11, 2026
* commit 'cc6b16afbf7feec3e16451fdc590a3265fbf0c0b':
  docs: amend Shell diagnostic ownership (#1330)
  fix(mecatui): refresh status context on session continuation (#1328)
  fix(jsonlstore): preserve session saves with legacy lineage (#1327)
  test(sessiondebug): eliminate handle tampering flake (#1323)
  fix(agent): authorize structured subagent results (#1317)
  feat(mcp): support attachment-backed broker queries for CallMcpWithQuery (#1309)
  docs(agents): document full-gate timeout guidance (#1316)
  fix(server): let the stale-session sweep re-acquire a lost lease (#1302)
  feat(clientauth): headless Linux credential storage (#1291)
  chore(mcpbroker): trace protected call latency (#1314)

# Conflicts:
#	docs/acceptance/canonical-shell-command-tool.md
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.

stale-session sweep can never recover a session whose lease loss was self-inflicted (late renew, not a real competitor)

1 participant