fix(server): cap background-work deferral and report session-teardown losses #5711
main fromrefs/pull/5711/head·opened View on GitHubWhat Changed#
Completes #5677. The background-liveness skip gets a wedge cap (backgroundWorkMaxIdleMs, default 4h) so a task that never reaches a terminal state cannot pin its session and child process forever. The binding's lastSeenAt now refreshes on provider-initiated turn/task lifecycle events, not just user sendTurn. session.exited flowing through the event pump marks the persisted binding stopped — guarded against stale exits from a replaced session, including replacements on a different provider instance. Claude session teardown drains still-live task ids with terminal task.completed(stopped) events, and a stream death with live tasks emits a runtime.error naming the lost agents plus a structured log.
Why#
#5677 correctly stopped the reaper from killing sessions with live background work, but the edges around it are still lossy or unbounded. The deferral is unconditional, so the failure mode just flips: a wedged task now pins its session forever instead of being killed too early. lastSeenAt still only moves on user-initiated turns, so a thread doing autonomous work reads as idle from the user's last keystroke — background liveness defers the reap, but the idle clock itself stays dishonest for anything else keyed to it. Adapter-internal exits (stream end, session replace, stopAll) never pass through stopSession and leave ghost running rows the sweep re-visits forever. And when teardown does kill live agents, the user finds out on their next message, potentially 40+ minutes later.
This was diagnosed from a production day with 13 session stops across three threads, each landing 30.1–39.7 minutes after the last user message while background agents were mid-work — one session was killed while running the test suite that verifies this fix. With the heartbeat in place, the wedge cap means "no heartbeat at all for the cap window", which is the definition of wedged.
The sweep reads ThreadBackgroundLivenessService directly rather than the projected shell — the shell's backgroundLiveness is computed from the same service at snapshot-build time, so it is the same signal minus the snapshot staleness. #5677's test is kept and adapted to the capped deferral: its months-stale scenario now correctly reaps, and that boundary is pinned by its own wedge-cap test. The stale-exit guard's cross-instance test fails without the guard (verified by reverting and re-running). ProviderSessionReaper + ProviderService + ClaudeAdapter: 110/110 on this base; ProviderRuntimeIngestion: 45/45; typecheck clean.
Bigger than the contributing guide prefers — it stays one PR because the four pieces enforce one invariant (background work is neither silently killed nor allowed to pin a session, and its loss is visible), and the heartbeat is what makes the cap meaningful. Happy to split it if you'd rather take it piecewise.
Checklist#
- This PR is small and focused (focused: one subsystem, one invariant — but not small, see note above)
- I explained what changed and why
-
I included before/after screenshots for any UI changes(no UI changes) -
I included a video for animation/interaction changes(n/a)
Change authored by Claude Fable 5 via Claude Code.
Note
Medium Risk Changes core provider session teardown, persisted binding sync, and reaper heuristics; mistakes could leave ghost running sessions or reap live autonomous work, though extensive guards and tests target the production failure modes.
Overview Tightens background-work session lifecycle so autonomous provider work is neither silently killed nor allowed to pin processes forever, and teardown losses are visible.
Claude adapter: On SDK stream exit (clean or failed) while liveTaskIds remain, the adapter now logs claude.session.stream-ended-with-live-tasks, emits a runtime.error naming the lost agents, and drains each live task with task.completed (stopped), including a second drain after stream-fiber interrupt to close races with in-flight handlers.
Provider event pump: Adds syncBindingOnRuntimeEvent so session.exited marks the persisted binding stopped (clearing ghost running rows from adapter-internal exits), with guards for stale exits (newer replacement session on the same instance, or binding owned by a different provider instance). Turn/task lifecycle events refresh lastSeenAt (60s throttle) so provider-initiated work does not look idle since the user’s last sendTurn.
Session reaper: Defers reaping idle sessions while ThreadBackgroundLivenessService reports live work, but only up to backgroundWorkMaxIdleMs (default 4h, floored above the inactivity threshold); beyond that, wedged “live” work is reaped anyway. Sweep uses the liveness service directly instead of the projected shell.
Tests and docs/internals/providers.md document the three rules (teardown reports loss, binding follows session, reaper respects background work with a cap).
Note
Cap background-work deferral in session reaper and report live-task losses on session teardown#
- The Claude adapter's
handleStreamExitnow detects background tasks still tracked as live at stream termination, emits aruntime.errordescribing the loss, and emitstask.completed(statusstopped) for each live task. A structured warning is also logged. - The
ProviderSessionReaperdefers reaping idle sessions while background work is live, up to a configurablebackgroundWorkMaxIdleMscap (default 4h), after which the session is reaped regardless. - The
ProviderServiceevent pump now syncs persisted bindings: marks a bindingstoppedonsession.exited(guarded against stale cross-instance or replaced-session exits), and refresheslastSeenAton turn/task lifecycle events with per-thread 60s throttling. - Tests and providers.md documentation are added for all three behaviors.
- Behavioral Change: sessions with live background work that exceed the idle wedge cap are now reaped unconditionally, even if liveness still reports active.
📊 Macroscope summarized 5aeeb1b. 4 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted
🗂️ Filtered Issues#
No issues evaluated.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -283,0 +327,21 @@327+ return Effect.gen(function* () {328+ const threadKey = String(event.threadId);329+ if (!isSessionExit) {330+ const nowMs = yield* Clock.currentTimeMillis;331+ const lastTouch = lastBindingTouchAtMs.get(threadKey);332+ if (lastTouch !== undefined && nowMs - lastTouch < BINDING_TOUCH_THROTTLE_MS) {333+ return;334+ }335+ } else {336+ lastBindingTouchAtMs.delete(threadKey);337+ }338+ const binding = Option.getOrUndefined(yield* directory.getBinding(event.threadId));339+ const providerInstanceId = binding?.providerInstanceId;340+ if (341+ binding === undefined ||342+ binding.status === "stopped" ||343+ providerInstanceId === undefined344+ ) {345+ return;346+ }347+ if (isSessionExit) {
🟡 Medium
Layers/ProviderService.ts:347syncBindingOnRuntimeEventskips theproviderInstanceIdownership check for activity events (turn.*/task.*), so after a thread moves to a different provider instance, stale events still in the old subscription's stream overwrite the new binding'slastRuntimeEvent/lastRuntimeEventAtand refreshlastSeenAt. The stale event also consumes the thread-wide 60-second throttle, which can suppress a legitimate heartbeat from the replacement session. The session-exited branch guards against this by comparingevent.providerInstanceIdagainst the persisted binding, but the activity-touch branch does not. Apply the same instance-ownership guard before activity touches, and key the throttle map by instance id so overlapping stale streams cannot suppress the replacement's heartbeats.🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/server/src/provider/Layers/ProviderService.ts around line 347: `syncBindingOnRuntimeEvent` skips the `providerInstanceId` ownership check for activity events (`turn.*`/`task.*`), so after a thread moves to a different provider instance, stale events still in the old subscription's stream overwrite the new binding's `lastRuntimeEvent`/`lastRuntimeEventAt` and refresh `lastSeenAt`. The stale event also consumes the thread-wide 60-second throttle, which can suppress a legitimate heartbeat from the replacement session. The session-exited branch guards against this by comparing `event.providerInstanceId` against the persisted binding, but the activity-touch branch does not. Apply the same instance-ownership guard before activity touches, and key the throttle map by instance id so overlapping stale streams cannot suppress the replacement's heartbeats. Approvability#
Verdict: Needs human review
1 blocking correctness issue found. This PR introduces substantial new runtime behavior in session lifecycle management: lost-task reporting on teardown, binding synchronization on runtime events, and reaper deferral for background work. These are significant infrastructure changes beyond a targeted bug fix, and there is an unresolved Medium-severity finding about missing instance ownership guards for activity events.
You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).Thanks for the PR. We're not taking changes to the orchestration and provider layers right now: that part of the server is being rewritten for V2, and merging into the current code would either conflict with or be thrown away by that work.
Closing for now. If this is still an issue once V2 lands, please reopen (or open a fresh PR against the new code) and we'll take a proper look.
juliusmarminge closed this
Sign in to join this conversation.
Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
7d0111c1-0880-4602-9f95-2f70f03091faYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
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