Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): idle reaper no longer kills in-flight background agent work #4994

ClosedZeus-Deus(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/4994/headopened View on GitHub

Closes #4198. Builds on #4199 by @ChamaruAmasara (credited as co-author) — this incorporates its last_seen_at refresh together with its review feedback, and adds the hard busy guard and orphan-settling discussed in the issue comments.

What Changed

Liveness refresh from runtime activity (from #4199, plus review fixes)

  • touchLastSeen through the runtime repository and session directory: a targeted UPDATE of last_seen_at that skips stopped rows (a reaped session is never resurrected) and reports whether a live row was actually updated.
  • ProviderService.processRuntimeEvent refreshes last_seen_at on runtime events, throttled per thread (default 60s). The throttle arms only after a confirmed live-row write, so a failed or no-op touch retries on the next event instead of leaving the timestamp stale. The touch is best-effort (Effect.catch, so fiber interrupts propagate) and bounded by a timeout so a stalled write cannot block the per-instance event pump. Because every runtime event funnels through here, ordinary and synthetic follow-up turns now refresh liveness too — reporters observed last_seen_at frozen at initial startup despite later foreground turns.
  • The throttle map is evicted on stopSession/runStopAll (the unresolved memory-leak review on #4199), and entries are only created for threads with a live binding row.

Hard busy guard: outstanding background tasks

  • ProviderService tracks started-but-not-terminal background tasks in memory from task.started/task.progress/task.completed events (task.progress also registers unknown tasks, covering subscriptions that attach mid-task). In-memory is deliberate: in-flight background work never survives a server restart, so a persisted entry could only pin a session that is already gone.
  • New hasOutstandingBackgroundTasks(threadId); the reaper checks it immediately before stopSession and skips busy threads (provider.session.reaper.skipped-outstanding-tasks). The existing activeTurnId guard is preserved unchanged. A quiet-but-outstanding task blocks reaping past the inactivity threshold.
  • Staleness backstop: after an extended period with no task events at all (default 90 min, 3× the reap threshold), tracked tasks are presumed dead, settled, and logged (provider.session.tasks.presumed-abandoned) — a stranded entry (e.g. an instance rebuilt by a settings edit, which emits no session.exited) cannot exempt a thread from reaping forever.

Never silently orphan a task

  • On stopSession, runStopAll, and session.exited, whatever is still outstanding is settled by publishing a synthetic terminal task.completed(status: "stopped") with an explanatory summary, so downstream ingestion records a terminal activity instead of leaving a spinner alive forever. session.exited settles only tasks recorded against the same provider instance (fail-closed), so a stale exit cannot clobber a newer session's tasks.

Why

The reaper stops any provider session after 30 min of last_seen_at inactivity, and its only busy signal was the projection's activeTurnId. Background work keeps running after the foreground turn settles (activeTurnId → null), and nothing refreshed last_seen_at from runtime activity, so long-running background workflows were torn down mid-run — killing the provider child process and everything it owned — and the loss only surfaced on the next user message. Multiple independent reports on the issue confirmed both halves: stale timestamps despite later turns, and reaps landing ~60–90s after background tasks started.

Two complementary mechanisms are needed: liveness refresh handles the common case cheaply, and the busy guard protects tasks that are temporarily quiet; settling makes any remaining race visible instead of silent.

Validation

  • vp test run on all 8 touched test files: 209 tests pass (ProviderService 37, ProviderSessionReaper 7, ProviderSessionDirectory 8, plus adapter/orchestration doubles).
  • Regression tests match the criteria from the issue discussion: a stale binding with no active foreground turn but an outstanding task is not stopped by a sweep, and becomes reapable once the task reaches a terminal state (verified to fail with the guard removed); touch bumps a live row and never resurrects a stopped one; a failed touch does not arm the throttle; two-thread isolation; fail-closed instance matching on session.exited; the staleness backstop settles exactly once.
  • Typecheck (tsgo --noEmit): 0 errors. Lint: clean. vp fmt applied.

UI Changes

None directly; threads whose session is stopped while background tasks are outstanding now show those tasks as stopped ("Session stopped before the task finished") instead of a spinner that never resolves.

Checklist

  • This PR is focused on one concern
  • I explained what changed and why
  • No UI changes

Note

Medium Risk Changes session lifecycle, reaper behavior, and runtime event ordering in ProviderService; mistakes could leave sessions pinned or reap active work, but the design is heavily tested and fails closed on instance matching.

Overview Fixes sessions being stopped mid-run when background workflows (dynamic tasks, subagents, shells) keep working after the foreground turn ends. The idle reaper only looked at activeTurnId and stale last_seen_at, so it could kill the provider child while work was still running.

Liveness from runtime activity — Adds touchLastSeen on the runtime repository and session directory (updates only live rows, never stopped ones). ProviderService bumps last_seen_at on runtime events with per-thread throttling (default 60s), arms the throttle only after a successful write, and bounds the DB call with a timeout so the event pump does not stall.

Outstanding background tasks — In-memory tracking from task.started / task.progress / task.completed, plus hasOutstandingBackgroundTasks. The session reaper skips stop when that returns true. After prolonged silence (default 90 min), tasks are presumed abandoned, settled, and the thread becomes reapable again.

Synthetic task settlement — On stop, exit, or runStopAll, still-running tasks get a published task.completed with status: stopped and a user-facing summary so the activity feed does not spin forever. session.exited settles only tasks owned by the exiting provider instance.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e578131f84f2def55bdd5224488483df695b4713. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Fix idle reaper to skip sessions with in-flight background agent tasks

  • Adds hasOutstandingBackgroundTasks(threadId) to ProviderServiceShape and implements it in ProviderService.ts, tracking in-memory background tasks per thread with staleness detection.
  • Updates ProviderSessionReaper.ts to call hasOutstandingBackgroundTasks before stopping a stale session, skipping reap if tasks are still running.
  • Adds touchLastSeen(threadId) to ProviderSessionDirectory and the underlying ProviderSessionRuntimeRepository, updating last_seen_at only for non-stopped rows; ProviderService calls this on runtime activity, throttled per thread.
  • Emits synthetic task.completed events to settle outstanding tasks when a session stops, exits, or tasks go stale.
  • Behavioral Change: sessions with active background tasks are no longer reaped by the idle sweeper even when they appear inactive.
📊 Macroscope summarized e578131. 6 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 596b750d-db15-4d17-b084-7848978d2c43

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      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.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. @@ -70,3 +70,4 @@
      7070 continue;
      7171 }
      7272
      73+ // Checked immediately before the stop so the window in which a task can
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/ProviderSessionReaper.ts:73

      The hasOutstandingBackgroundTasks check at line 75 is not atomic with stopSession at line 83, so a background task that starts in between the check and the stop is killed by the idle reaper. A task.started or task.progress event can be processed by the event pump after the check returns false but before stopSession runs, and that newly tracked task is reaped alongside the session. If closing this race window is not feasible with the current architecture, consider documenting why this best-effort check is acceptable so the known limitation is explicit.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/ProviderSessionReaper.ts around line 73:
      
      The `hasOutstandingBackgroundTasks` check at line 75 is not atomic with `stopSession` at line 83, so a background task that starts in between the check and the stop is killed by the idle reaper. A `task.started` or `task.progress` event can be processed by the event pump after the check returns `false` but before `stopSession` runs, and that newly tracked task is reaped alongside the session. If closing this race window is not feasible with the current architecture, consider documenting why this best-effort check is acceptable so the known limitation is explicit.
      @@ -283,0 +489,21 @@
      489+ // saw the `task.started`, and an untracked running task is exactly the
      490+ // case the reaper must not miss.
      491+ case "task.progress":
      492+ return Effect.map(Clock.currentTimeMillis, (nowMs) =>
      493+ rememberOutstandingTask(
      494+ event.threadId,
      495+ event.payload.taskId,
      496+ {
      497+ provider: event.provider,
      498+ ...(event.providerInstanceId !== undefined
      499+ ? { providerInstanceId: event.providerInstanceId }
      500+ : {}),
      501+ },
      502+ nowMs,
      503+ ),
      504+ );
      505+ // The only terminal task event, for every status it can carry.
      506+ case "task.completed":
      507+ return Effect.map(Clock.currentTimeMillis, (nowMs) =>
      508+ forgetOutstandingTask(event.threadId, event.payload.taskId, nowMs),
      509+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/ProviderService.ts:506

      In trackBackgroundTasks, the task.completed branch calls forgetOutstandingTask with only (threadId, taskId) — it does not check event.providerInstanceId against the stored task's owner. If a replaced adapter drains a queued completion for a provider-native task ID after a newer instance has registered the same taskId on the same thread, the newer task is deleted from outstandingTasksByThread. The reaper then sees no outstanding work for that thread and can stop the new session while its background task is still running. The session.exited branch already guards by providerInstanceId; the task.completed branch should do the same before removing the entry.

      Suggested change
      506- case "task.completed":
      507- return Effect.map(Clock.currentTimeMillis, (nowMs) =>
      508- forgetOutstandingTask(event.threadId, event.payload.taskId, nowMs),
      509- );
      506+ case "task.completed":
      507+ return Effect.map(Clock.currentTimeMillis, (nowMs) =>
      508+ forgetOutstandingTaskIfOwner(
      509+ event.threadId,
      510+ event.payload.taskId,
      511+ nowMs,
      512+ event.providerInstanceId,
      513+ ),
      514+ );
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/ProviderService.ts around lines 506-509:
      
      In `trackBackgroundTasks`, the `task.completed` branch calls `forgetOutstandingTask` with only `(threadId, taskId)` — it does not check `event.providerInstanceId` against the stored task's owner. If a replaced adapter drains a queued completion for a provider-native task ID after a newer instance has registered the same `taskId` on the same thread, the newer task is deleted from `outstandingTasksByThread`. The reaper then sees no outstanding work for that thread and can stop the new session while its background task is still running. The `session.exited` branch already guards by `providerInstanceId`; the `task.completed` branch should do the same before removing the entry.
    4. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e578131f84f2def55bdd5224488483df695b4713. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -855,3 +1125,12 @@
      8551125 if (routed.isActive) {
      8561126 yield* routed.adapter.stopSession(routed.threadId);
      8571127 }
      1128+ // Settled after the adapter stop so that any terminal event the adapter
      1129+ // had already handed us wins. This is not a complete drain: adapter
      1130+ // events reach us through a forked per-instance pump, so `stopSession`
      1131+ // returning does not mean the queue is empty, and a `task.started`
      1132+ // still in flight can re-add an entry right after `forgetThreadState`.
      1133+ // The staleness ceiling in `hasOutstandingBackgroundTasks` is what
      1134+ // bounds those leftovers.
      1135+ yield* settleOutstandingTasks(input.threadId, TASK_SETTLED_BY_STOP_SUMMARY);
      1136+ forgetThreadState(input.threadId);

      Ghost tasks pin later sessions

      Medium Severity

      stopSession assumes the staleness check in hasOutstandingBackgroundTasks will bound leftover tasks re-added by late task.started/task.progress events after forgetThreadState, but the reaper skips stopped bindings before calling that API, and startSession never clears the map. Those ghosts can linger for the process lifetime and later mark a restarted idle thread busy for up to the 90-minute ceiling.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit e578131f84f2def55bdd5224488483df695b4713. Configure [here](https://www.cursor.com/dashboard/bugbot).
    5. Approvability

      Verdict: Needs human review

      2 blocking correctness issues found. This PR introduces significant new runtime behavior for tracking background tasks and preventing premature session reaping. Multiple high-severity review comments identify potential race conditions and logic errors in the new task tracking system that should be evaluated before merging.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Closing in favor of #2829 (orchestration V2).

      #2829 replaces the V1 orchestration engine wholesale, and the behavior this PR adds already landed there natively — so this change is a no-op against the new base.

      Thanks for the work here, and sorry for the churn on a long-lived branch. Once #2829 merges, please rebase onto main and reopen if the behavior is still missing — happy to take it.

    7. juliusmarminge closed this

Sign in to join this conversation.