Skip to content

fix: drain journal failure recovery before session host teardown - #18974

Open
nwparker wants to merge 3 commits into
mainfrom
nwparker/fix-session-teardown-sink-recovery
Open

nwparker wants to merge 3 commits into
mainfrom
nwparker/fix-session-teardown-sink-recovery

Conversation

@nwparker

@nwparker nwparker commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​138 $\color{#cf222e}{\Huge{\mathbf{−}}}$​18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​120
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​123 $\color{#cf222e}{\Huge{\mathbf{−}}}$​58 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​65

ELI5

Orca keeps a written log of everything an agent session does. If a write to that log fails (a disk hiccup, a full disk), Orca quietly starts a background cleanup: it stops the agent's process and records that the session ended. The bug was that quitting Orca did not wait for that cleanup to finish — it closed the log files and forgot the session while the cleanup was still writing to them. The cleanup then wrote into files that were already closed, which surfaced as errors on quit and, in tests, as a session folder that refused to delete. Now quit waits for that cleanup to finish first. And if the cleanup itself gets stuck, quit gives up on it after five seconds instead of hanging forever.

What Changed

  • StructuredAgentSessionEventRecovery tracks its in-flight sink-failure recoveries and exposes drainSinkRecoveries().
  • A new drain-sink-recoveries teardown phase runs after flush-event-sinks (the flush is what surfaces the failure that starts recovery) and before journals close. It is bounded by the same 5s deadline as drain-handoffs.
  • The teardown phase list moved into structured-agent-session-host-teardown.ts as structuredAgentSessionTeardownPhases(), next to the runner that consumes it. structured-agent-session-host.ts was at its 300-line max-lines budget, so the bound did not fit inline.
  • The tracked-promise-drain idiom was already implemented for attaches. It is now one PendingOperationDrain class reused by both trackAttach/drainAttaches and the new sink recoveries, rather than a second copy (AGENTS.md "Reuse Before Reimplementing").
  • flushAllEventSinks now settles every sink before throwing. Promise.all short-circuited on the first failure, so with two or more open sessions a still-draining sink could raise its recovery after the new drain phase had already run — the exact leak this PR closes.

Why

The recovery started as fire-and-forget (void this.context.serialize(...)) and nothing awaited it. This is structurally the same leak the neighbouring drain-handoffs phase already documents: a flow left running writes rows into a journal teardown is about to close. The fix is the same shape, in the same place.

Bounding it matters: the recovery awaits adapter.forceCloseSession ?? closeSession — Claude has no forceCloseSession, and its closeSession path awaits an in-flight acquire handshake, a transcript read, and a durable store write, none with a deadline. It can then re-attach and spawn a new provider child. Unbounded, a wedged recovery holds the quit open forever.

Linked Issue

Fixes #

Visual Proof

N/A — main-process session-teardown ordering. There is no rendered surface; the observable difference is the absence of post-close journal writes on quit. Per AGENTS.md, local Electron launches are paused for this work, so validation is unit-level and CI.

Tradeoffs

Genuine user-facing costs of this change:

  • Quit can be slower. When a journal write has failed and its recovery is in flight, shutdown now waits for it — up to 5s in the worst case. Previously it did not wait at all. A normal quit is unchanged: with nothing pending the drain resolves immediately.
  • Worst-case quit adds a second 5s window. drain-handoffs and drain-sink-recoveries are bounded independently, so a pathological quit that wedges both can now take ~10s rather than ~5s before journals close.
  • Give-up is not cancellation. If the 5s bound expires, teardown proceeds while the abandoned recovery keeps running, so it can still write into a closed journal. That is strictly no worse than today's behaviour (which never waited), but the bound converts "always leaks" into "leaks only when wedged" rather than eliminating it. This is the same accepted tradeoff drain-handoffs documents.
  • Teardown can now wait on a provider respawn. holds.dispose() does not clear the holder set, so a recovery during teardown can still pass hasResumeCapableHolder and re-attach. Quit waits for that (bounded). Suppressing the re-attach outright would be the better fix and is deliberately not attempted here.
  • flushAllEventSinks no longer fails fast. With multiple sessions it now waits for every sink barrier before throwing, so a teardown with one failed and one slow sink takes as long as the slow one. It still throws the first failure, so callers see the same error.
  • Regression surface. drainAttaches and the handoff drain now share PendingOperationDrain, and the teardown phase list moved files. Both are behaviour-preserving, but they touch the quit path, which is hard to exercise outside tests.

Not addressed (residual risk, unchanged by this PR): drain-attaches remains the one unbounded drain on the quit path.

Testing

  • pnpm tc:node — pass.

  • pnpm test src/main/native-chat/agent-session-wire/ — 52 files / 327 tests pass after merging current main.

  • pnpm test src/main/runtime/ — 597 files / 6487 tests pass.

  • main merged into the branch to clear an import conflict in structured-agent-session-host.ts; re-verified after the merge.

  • oxlint and oxfmt --check clean on changed files.

  • The wedged-recovery test was verified to fail (teardown hangs to timeout) when the 5s bound is removed, so it is a real regression test rather than a tautology.

  • Platforms: logic is platform-independent main-process code; no path, shell, or process-spawn behaviour changed. Structured sessions are local-only today (both adapters gate on executionHostId === LOCAL_EXECUTION_HOST_ID), so there is no SSH/remote wire surface here.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

Three tests added: teardown waits for recovery; teardown gives up on a wedged recovery; and unit coverage for PendingOperationDrain (re-enqueue during drain, rejected entry, never-settling entry).

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

No persisted schema, wire format, or IPC payload changed — this is teardown ordering only, so there is no mixed-version or rollback surface.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change tracks sink-failure recovery promises in StructuredAgentSessionEventRecovery. It removes each promise after settlement and exposes drainSinkRecoveries(). flushAllStreamedEvents now drains these recoveries after flushing event sinks. A regression test verifies that teardown waits for journal recovery settlement before releasing and removing the session.

Merge Risk: 🟡 Moderate · up to 2285f

Teardown now waits for journal-recovery completion before releasing a session, preventing writes after journal closure. However, an adapter shutdown that never completes can indefinitely block session teardown, so this should be resolved before merge.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 3…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: draining journal failure recovery before session host teardown.
Description check ✅ Passed The description is detailed, relevant, and covers the change, rationale, tradeoffs, testing, compatibility, and checklist. The required Linked Issue entry is incomplete because it contains only "Fixes…
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 5bfd2bbd-03b8-4dfd-9a00-0c69f9969869

📥 Commits

Reviewing files that changed from the base of the PR and between d7722a6 and 2285fa9.

📒 Files selected for processing (3)
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-recovery.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

{ name: 'drain-attaches', run: () => this.tasks.drainAttaches() },
{ name: 'flush-event-sinks', run: () => this.runtimeState.flushAllEventSinks() }
{ name: 'flush-event-sinks', run: () => this.runtimeState.flushAllEventSinks() },
{ name: 'drain-sink-recoveries', run: () => this.eventRecovery.drainSinkRecoveries() }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Prevent an unbounded host teardown wait.

drainSinkRecoveries() waits for recoverAfterSinkFailure() to settle. That recovery awaits adapter.forceCloseSession or adapter.closeSession. This phase has no timeout. A non-settling adapter operation keeps flushAllStreamedEvents() pending indefinitely during teardown.

Use a bounded, cancellable recovery protocol. Do not only race the promise with a timeout, because a recovery that continues after teardown can again write after its journal closes.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The new drain-sink-recoveries phase is unbounded on the app-quit path, where the adjacent drain-handoffs phase is deliberately bounded to avoid holding quit open forever. Worth bounding (or explicitly documenting why unbounded is safe) before merge.

Reviewed changes

This run reviewed the sink-failure recovery drain: in-flight recovery tracking in StructuredAgentSessionEventRecovery, a new drain-sink-recoveries teardown phase, and a regression test in structured-agent-session-surface-lifetime.test.ts.

  • Track pending recoveries — recoverAfterSinkFailure records each recovery promise in pendingSinkRecoveries and removes it on settlement.
  • Drain before closing journals — a new drain-sink-recoveries phase runs after flush-event-sinks and before the teardown's trailing journal close(), awaiting all pending recoveries.
  • Regression test — a gate-controlled store.transitionHandoff spy proves teardown stays blocked while lease persistence is in flight.

⚠️ Unbounded recovery drain on the app-quit path

The new phase awaits Promise.allSettled(this.pendingSinkRecoveries) with no timeout, in direct tension with the pattern the adjacent drain-handoffs phase already rejects. drain-handoffs is bounded to HANDOFF_DRAIN_TIMEOUT_MS (5s) with a comment explaining that a wedged flow on the quit path would otherwise "hold the quit open forever." A sink recovery that hangs — forceCloseSession/closeSession never resolving, or resumeHeldStructuredAgentSession's acquire spawning a provider that never comes up — now blocks flushAllStreamedEvents() (and therefore app quit) indefinitely, and the trailing journal close() never runs.

Technical details
# Bound (or justify) the sink-recovery drain on the app-quit path

## Affected sites
- src/main/native-chat/agent-session-wire/structured-agent-session-event-recovery.ts:73 — `drainSinkRecoveries()` awaits `Promise.allSettled` with no timeout
- src/main/native-chat/agent-session-wire/structured-agent-session-host.ts:271 — new phase has no bound, unlike the adjacent `drain-handoffs` (`HANDOFF_DRAIN_TIMEOUT_MS`)

## Required outcome
- Decide whether a wedged provider recovery may hold app quit open indefinitely, and either bound the drain (e.g. `withTimeout` like `handoffs.drain()`) or document why unbounded is safe here.

## Open questions for the human
- Unlike handoffs, "giving up" on a sink recovery re-introduces the lease-persists-after-journal-close bug this PR fixes (the ENOTEMPTY path). If bounded, what should happen to the not-yet-persisted lease on timeout — retry via `agentSessionJournalCloseRetries`, or accept the orphan with the recovery still tracked for a later drain?

ℹ️ Nitpicks

  • runtimeState.eventSinkFor(SESSION) in the new test (structured-agent-session-surface-lifetime.test.ts:302) is load-bearing — it swaps out the failed cached sink so the flush-event-sinks phase does not reject and await teardown resolves — but, unlike the sibling test at line 353, it has no comment explaining why it is there. A one-line comment would save the next reader the same trace.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

The new drain-sink-recoveries teardown phase was unbounded, unlike the
drain-handoffs phase beside it. Recovery awaits closeSession (Claude has no
forceCloseSession, and its close path awaits an in-flight acquire handshake, a
transcript read and a durable write) and can re-attach a provider child, none
of it with a deadline — so a wedged recovery held the quit open forever. A test
proves teardown hangs to timeout without the bound.

Also: flushAllEventSinks used Promise.all, which short-circuited on the first
failing sink, so with two or more sessions a still-draining sink could raise its
recovery after the drain phase had already run — the leak this phase exists to
close. It now settles every sink before throwing the first failure.

Reuse rather than a second copy: the tracked-promise-drain idiom already existed
as trackAttach/drainAttaches, so both now share one PendingOperationDrain, with
unit coverage for re-enqueue-during-drain, a rejected entry, and one that never
settles. The teardown phase list moved next to its runner because host.ts sat
exactly at its 300-line max-lines budget and the bound did not fit inline.
…teardown-sink-recovery

# Conflicts:
#	src/main/native-chat/agent-session-wire/structured-agent-session-host.ts

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

This run reviewed the delta against the prior review (commit a367048): bounding the sink-recovery drain, closing the multi-session flush gap, and the PendingOperationDrain extraction.

  • Bounded the recovery drain — drain-sink-recoveries now runs under the same 5s withTimeout(..., undefined) as drain-handoffs, resolving the prior ⚠️ about a wedged recovery holding quit open forever.
  • Closed the multi-session flush gap — flushAllEventSinks now settles every sink via Promise.allSettled before throwing the first rejection, so a slow secondary sink can no longer raise its recovery after the drain phase has already run.
  • Extracted PendingOperationDrain — the fire-and-forget tracking + drain idiom is now one class shared by trackAttach/drainAttaches and the sink recoveries, replacing the duplicated attach set.
  • Moved the teardown phase list — structuredAgentSessionTeardownPhases() lives next to the runner that consumes it, keeping structured-agent-session-host.ts under its max-lines budget.
  • Tests — two regression tests (teardown blocks on recovery; teardown gives up on a wedged recovery) plus PendingOperationDrain unit coverage (re-enqueue during drain, rejected entry, never-settling entry).

The prior ⚠️ (unbounded drain) and nitpick (undocumented eventSinkFor swap) are both addressed. The give-up-on-timeout tradeoff and the still-unbounded drain-attaches phase are documented in the PR body as accepted residual risk and are unchanged in behavior from today.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

This branch has not been deployed

No deployments
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.

1 participant