Skip to content

revive client event stream after session restart - #18341

Merged
kevinushey merged 5 commits into
mainfrom
bugfix/event-stream-revival-after-restart
Jul 25, 2026
Merged

kevinushey merged 5 commits into
mainfrom
bugfix/event-stream-revival-after-restart

Conversation

@kevinushey

@kevinushey kevinushey commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #18340.

Problem

On RStudio Server, after a session restart the client can stop receiving events until the user's next action. See #18340 for the full mechanism and CI-run timeline; in short:

  1. suspend_for_restart takes the session down; the get_events long-poll errors (rserver maps a dead session socket to Unavailable, or a bare 503 surfaced as a transmission error). Events requests never initiate session launches, so polling alone cannot bring the session back.
  2. RemoteServerEventListener.onError stops the listener: immediately for UNAVAILABLE, or after at most 5 retries at 500ms otherwise.
  3. The existing revival hooks all depend on further client activity: every RPC send calls ensureListeningForEvents(), but its bounded ensureListening(10) burst (2.5s) typically loses the race against the session relaunch that the same RPC triggers; RPC responses only call ensureEvents() when they report "ep": "true". A client passively waiting for console output sends no RPCs, so nothing ever revives the stream -- including delivery of DeferredInitCompletedEvent, which is what runs the queued chunks after "Restart R and Run All Chunks".

Fix

RemoteServerEventListener now schedules a slow-cadence (5s) revival attempt whenever it stops due to errors (both the UNAVAILABLE path and the retry-budget-exhausted path), making revival independent of further user/RPC activity. The revival timer:

  • is cancelled by stop(), so deliberate stops -- hidden multi-session tabs (ApplicationVisibility), window close -- are not overridden;
  • re-checks isListening_ / sessionWasQuit_ / isDisconnected() before starting, so it no-ops after quit/disconnect or if ensureListening/ensureEvents already restarted the listener;
  • cannot resurrect a suspended session: rserver's events handler does not initiate session launches, so a suspended-but-not-restarting session just keeps returning Unavailable to the (cheap) 5s probes until a real RPC relaunches it.

This is the "another way to restart the listener (perhaps a global timer that checks for isListening every few seconds)" already anticipated by the comment in the listener's constructor.

Defense-in-depth hardening in the same area:

  • listenErrorCount_ now resets when a poll succeeds. It was previously only reset when the give-up branch ran, making the 5-retry budget a lifetime budget: a tab that had absorbed six transient errors over hours would skip the quick retries entirely on the next incident.
  • The 500ms quick retries now go through the same guarded revival timer instead of anonymous Timer instances, so stop() cancels them (an in-flight retry can no longer override a deliberate stop) and they observe the sessionWasQuit_ / isDisconnected() guards.
  • A revival attempt logs a single-line breadcrumb to the browser console, so future event-delivery gaps are diagnosable from a trace.

Tests

Deliberately no e2e timeout changes: a dead event stream is not woken by waiting longer (only by client activity), so extended waits would neither rescue a pre-fix binary nor help a post-fix one. The always-on rmarkdown.test.ts "empty chunk does not define variables" spec -- which runs in every PR's server-linux e2e job and exercises exactly the restart -> event-delivery -> run-chunks path -- keeps its tight 60s budget and serves as the regression canary for this fix (now noted in a comment there).

Verification

  • ant javac passes; e2e tsc --noEmit passes.
  • PR-triggered e2e workflow (desktop + server, all platforms) exercises the fix.

After a session suspend/restart on RStudio Server, the client's
get_events long-poll fails while the session is down and
RemoteServerEventListener gives up after a short retry budget,
remaining stopped indefinitely: successful RPCs only call
ensureEvents() when their response reports events pending, so the
client stays deaf to events (including DeferredInitCompletedEvent,
which triggers 'Restart R and Run All Chunks') until some later RPC
happens to report pending events.

Schedule a slow-cadence (5s) revival attempt whenever the listener
stops due to errors, cancelled by stop() so deliberate stops (hidden
multi-session tabs, window close) are unaffected.

Also harden the e2e waits that sit downstream of this delivery path
so they comfortably cover a slow-but-successful restart on binaries
without the fix.

Addresses #18340
@kevinushey kevinushey added this to the 2026.08 (Yellow Yarrow) milestone Jul 23, 2026
@posit-snyk-bot

posit-snyk-bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

The extended waits could not have rescued a pre-fix binary anyway (a
dead event stream is not woken by the passage of time, only by an RPC
that reports pending events), and with the revival fix in place the
original 60s budgets have ample margin. Keeping them tight means a
regression of #18340 fails the always-on rmarkdown spec loudly instead
of being masked.

Addresses #18340
Defense-in-depth around the revival fix:

- reset listenErrorCount_ when a poll succeeds, so the quick-retry
  budget applies per incident rather than over the lifetime of the
  page (previously six transient errors spread over hours would send
  the next incident straight to the stopped state)
- route the 500ms quick retries through the guarded revival timer,
  so they are cancelled by stop() (deliberate stops can no longer be
  overridden by an in-flight retry) and observe the same
  sessionWasQuit_ / isDisconnected guards
- log a breadcrumb when a revival attempt fires, so event delivery
  gaps are diagnosable from the browser console

Addresses #18340
@kevinushey
kevinushey requested a review from gtritchie July 23, 2026 20:08
@github-actions

github-actions Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1885 0 357 4
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ desktop-linux 468 0 88 2
✅ desktop-macos 473 0 85 1
✅ desktop-windows 474 0 90 0
✅ server-linux 454 0 94 1
✅ setup 16 0 0 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit f39ce24cbb9a55150fc51d2b1ffeceb8d0661eaf - Run #336

@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review of the event-stream revival change. Line numbers refer to the PR head (c212a1f) version of RemoteServerEventListener.java.

Important

  1. src/gwt/src/org/rstudio/studio/client/server/remote/RemoteServerEventListener.java:349 — the give-up branch resets listenErrorCount_ = 0 and then reschedules, but start() never touches the counter, so a persistent non-UNAVAILABLE error never settles into the intended slow cadence. Trace: 6 quick 500ms retries → else branch resets the count to 0 and schedules a 5s revival → that revival fails with a fresh budget → another 6-retry burst, repeating ~6 requests every ~8s indefinitely. This defeats the "no more than 5 attempts" throttle across revival cycles and contradicts the scheduleRevival comment's "slow cadence thereafter." A bare 503 surfacing as a transmission error (a mechanism called out in the PR body) hits exactly this path. Benign during a normal quick restart (the poll soon succeeds and resets the budget via line 282), but bites on prolonged non-UNAVAILABLE outages. Fix: drop the listenErrorCount_ = 0 reset in the else branch — the new reset-on-success at line 282 already refreshes the budget between incidents.

  2. src/gwt/src/org/rstudio/studio/client/server/remote/RemoteServerEventListener.java:500 — the Debug.log(...) breadcrumb fires on every revival attempt, and Debug.log writes to the real browser console in all builds (Debug.log → logToConsole → console.log), not dev-only. Revival reschedules itself while the failure persists, so an idle client on a suspended session logs one identical line every 5s indefinitely (and, combined with finding 1, ~6 lines per burst for non-UNAVAILABLE errors). This is not the "single-line breadcrumb" the comment/PR body describe; it both floods the console and defeats its own diagnostic purpose. Fix: log once when the listener first transitions into the error-stopped state (gate on a flag cleared by the successful-poll reset), and include the error code / attempt count so the line is actually diagnostic.

Suggestions

  1. src/gwt/src/org/rstudio/studio/client/server/remote/RemoteServerEventListener.java:223 — the scheduleRevival doc comment ("quick (500ms) retries while the error budget lasts, then a slow cadence thereafter") matches neither code path: the UNAVAILABLE path (line 329) goes straight to the 5s cadence with no quick phase, and the non-UNAVAILABLE path cycles bursts + one slow tick rather than transitioning to slow (see finding 1). Reword to describe both paths accurately (or fix finding 1 so the non-UNAVAILABLE path really does settle into slow).

  2. src/gwt/src/org/rstudio/studio/client/server/remote/RemoteServerEventListener.java:337 — the retained comment "throttle restart attempts in both timing (500ms delay) and quantity (no more than 5 attempts)... unthrottled restart attempts could result in our server getting hammered" is now stale: the else branch no longer leaves the listener stopped, so attempts are no longer bounded by quantity — they continue indefinitely. (Also pre-existing: listenErrorCount_++ <= 5 permits 6 attempts, not 5.) Update the comment to say the cap now only paces retries rather than capping total attempts.

  3. src/gwt/src/org/rstudio/studio/client/server/remote/RemoteServerEventListener.java:377 — retryHandler.onError still calls stop() with no scheduleRevival and no breadcrumb. If the RPC-layer recovery of the get_events request itself errors, an idle client is left permanently deaf — the exact server: client event stream not resumed after session restart; run-all-chunks and console output stall until next user action #18340 symptom — through an entry point this fix doesn't cover, and with zero diagnostics. Consider routing this path through scheduleRevival(kRevivalIntervalMs) (or at minimum logging a breadcrumb) for consistency with the other stop paths.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Feedback posted

kevinushey and others added 2 commits July 24, 2026 10:37
- drop the listenErrorCount_ reset in the give-up branch so a prolonged
  non-UNAVAILABLE outage settles into the slow revival cadence instead of
  cycling back into quick-retry bursts (the reset now lives on the
  successful poll)
- log the revival breadcrumb once when the listener first stops due to
  errors, gated on a flag cleared by the successful poll, and include the
  error code and attempt count (no longer logs on every 5s revival tick)
- route retryHandler.onError through scheduleRevival so a failed get_events
  recovery no longer leaves an idle client permanently deaf, with a breadcrumb
- refresh the scheduleRevival doc comment and the throttling comment to
  describe both revival paths accurately
@kevinushey
kevinushey merged commit 7ddf8d8 into main Jul 25, 2026
24 checks passed
@kevinushey
kevinushey deleted the bugfix/event-stream-revival-after-restart branch July 25, 2026 01:18
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.

server: client event stream not resumed after session restart; run-all-chunks and console output stall until next user action

3 participants