Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): keep provider sessions alive during background agent work #4199

ClosedChamaruAmasara(GitHub profile, opens in a new tab)wants to merge 5 commits intomain fromrefs/pull/4199/headopened View on GitHub

Closes #4198

What Changed

  • Add a targeted touchLastSeen to the provider session runtime repository and session directory: a lightweight update that bumps only last_seen_at, and only for non-stopped rows (so a reaped session is never resurrected).
  • In ProviderService, refresh a session's last_seen_at from runtime activity: processRuntimeEvent now calls touchLastSeen when the adapter emits runtime events, throttled per thread (default 60s) so an event burst is at most one lightweight write per window. The touch is best-effort — a failed write never breaks event processing.
  • Tests: persistence/directory tests for touchLastSeen (bumps a live row; leaves a stopped row untouched); a ProviderService test proving a runtime event triggers a touch and that a rapid burst is throttled.

Why

ProviderSessionReaper stops any provider session after 30 min of last_seen_at inactivity. Background agent work — dynamic workflows and subagents — keeps running after the foreground turn settles, but at that point the adapter session has gone ready with no active turn, and nothing refreshes last_seen_at. So a long-running background workflow with no foreground turn is torn down mid-run, and the in-flight background orchestration is lost.

Runtime events are the reliable signal for background activity: while a workflow runs, the adapter keeps emitting events (e.g. task.progress from subagents) even with no active foreground turn. Refreshing last_seen_at from these events keeps the session warm exactly when the reaper would otherwise reap it. Throttling keeps DB churn negligible (one write per thread per window instead of one per event).

Validation

  • vp test run apps/server/src/provider/Layers/ProviderService.test.ts — includes a new test that a runtime event touches lastSeenAt and that a burst is throttled (verified it fails without the fix).
  • vp test run apps/server/src/provider/Layers/ProviderSessionDirectory.test.ts — touchLastSeen bumps a live binding; leaves a stopped binding untouched.
  • All affected provider test files pass (83 tests).
  • End-to-end: with a live server and a running background workflow, last_seen_at kept advancing from task.progress activity and the reaper did not reap the session past its idle threshold.
  • Typecheck: 0 errors. Lint: clean.

UI Changes

None.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • No UI changes

Note

Medium Risk Touches session lifecycle and reaper inputs (last_seen_at) on every runtime event path; behavior is best-effort and scoped to non-stopped rows, with tests for throttle and failure semantics.

Overview Background runtime events now refresh session liveness so the idle reaper does not stop sessions that are still doing work after the foreground turn finishes (e.g. dynamic workflows emitting task.progress).

Adds touchLastSeen through persistence (UPDATE last_seen_at only, skipping stopped rows), ProviderSessionDirectory, and wiring in ProviderService.processRuntimeEvent: best-effort, per-thread throttled (default 60s, overridable in tests). The throttle arms only after a successful write, so a failed touch can retry on the next event instead of leaving last_seen_at stale.

Tests cover directory behavior (live vs stopped), throttling, and retry-on-failure; adapter test doubles stub touchLastSeen.

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

Note

Keep provider sessions alive by touching last_seen_at during background agent activity

  • Adds touchLastSeen(threadId) to ProviderSessionDirectory and its underlying repository, issuing a targeted SQL UPDATE on last_seen_at that skips rows with status = 'stopped'.
  • ProviderService calls touchLastSeen on each ProviderRuntimeEvent, throttled to at most one successful write per thread per 60s (configurable via runtimeActivityTouchThrottleMs).
  • Failed writes are silently ignored and do not arm the throttle, so the next event will retry immediately.
Macroscope summarized faca14e.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      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

      Run ID: a03e75b1-3f47-42c2-bb66-0eae85e1edc0

      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
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      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. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      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).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 8bd44f20094b90aafb7981422319e9d7a657be03. Configure [here](https://www.cursor.com/dashboard/bugbot).
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      1 blocking correctness issue found. This PR introduces new runtime behavior for session lifecycle management (keeping sessions alive during background work). There is an unresolved review comment about a potential memory leak in the throttle map that should be addressed before merge.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. @@ -213,3 +219,10 @@
      213219 const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
      214220 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
      215221 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
      222+ // Throttle `lastSeenAt` refreshes keyed by thread. A running dynamic workflow
      223+ // emits many runtime events per second (`task.progress`, token-usage updates,
      224+ // …); we only need to bump the inactivity clock often enough that the session
      225+ // reaper never mistakes an active background session for an idle one. One
      226+ // write per thread per window is plenty and keeps the DB churn negligible.
      227+ const lastSeenTouchMs = options?.runtimeActivityTouchThrottleMs ?? 60_000;
      228+ const lastSeenTouchByThread = new Map<ThreadId, number>();

      🟡 Medium Layers/ProviderService.ts:228

      The lastSeenTouchByThread map in refreshLastSeenForActivity retains an entry for every threadId that ever emits a runtime event, and entries are never removed when sessions stop or are replaced. On a long-lived server serving an unbounded sequence of threads, this map grows for the process lifetime, leaking memory. Consider evicting entries in stopSession and runStopAll (e.g., via a small clearLastSeenTouch(threadId) helper) so the map stays bounded by the number of active threads.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/ProviderService.ts around line 228:
      
      The `lastSeenTouchByThread` map in `refreshLastSeenForActivity` retains an entry for every `threadId` that ever emits a runtime event, and entries are never removed when sessions stop or are replaced. On a long-lived server serving an unbounded sequence of threads, this map grows for the process lifetime, leaking memory. Consider evicting entries in `stopSession` and `runStopAll` (e.g., via a small `clearLastSeenTouch(threadId)` helper) so the map stays bounded by the number of active threads.
    6. commenting for exposure. would be great if this could be prioritized

    7. Closing in favor of #2829 (orchestration V2).

      #2829 deletes the V1 orchestration layer this PR builds on — apps/server/src/orchestration/**, provider/Layers/*Adapter.ts and provider/Services/** are removed and replaced by apps/server/src/orchestration-v2/**, with the IPC surface renamed to ORCHESTRATION_V2_WS_METHODS. The files this PR touches either no longer exist or are rewritten, so it can't be rebased — it would need reimplementing against the V2 adapters.

      This is not a judgement on the change itself. Several of these are real gaps we still want fixed; the base just moved out from under them.

      Once #2829 merges, please rebase onto main, port the change to the V2 equivalent, and reopen (or open a fresh PR). Ping me and I'll prioritise the review.

    8. juliusmarminge closed this

Sign in to join this conversation.