Skip to content

measure and speed up rstudio desktop startup - #18716

Merged
kevinushey merged 29 commits into
mainfrom
feature/startup-timing
Sep 8, 2026
Merged

kevinushey merged 29 commits into
mainfrom
feature/startup-timing

Conversation

@kevinushey

@kevinushey kevinushey commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Make RStudio Desktop start faster, and make it possible to see where startup time goes so future changes can be measured rather than guessed at.

Measured as a matched pair on this machine (Apple silicon, dev build, fresh config and data home per run; the baseline is the timing-instrumentation commit alone, built in its own worktree, with both series run back-to-back under the same ambient load): with the full branch the workbench paints at a median of 1,927 ms after Electron process creation versus 3,627 ms for the baseline (47% faster), and a first launch after install goes from 5.6 s to 2.6 s (53% faster). Absolute numbers track machine load -- an earlier pair measured on a quieter machine mid-branch came out 2,511 ms -> 1,279 ms with the same ratio.

Approach

Two waves of commits, intended to be reviewed separately. The first four groups instrument startup and fix the desktop/session sides; a second wave (commits from install the initial gwt fragment... on) addresses the client side, guided by Chromium startup traces of the renderer.

1. Startup timing checkpoints. With RSTUDIO_STARTUP_TIMING=<file> set, the Electron main process, rsession, and the GWT client each append JSON-line checkpoints to that file, giving one timeline across all three processes. npm run startup-timing -- --runs=N (a new task in tasks/) launches the app repeatedly and prints the merged timeline as medians plus the longest spans; --app=<binary> measures an installed build, --report=<dir> re-prints. The client's checkpoints are performance.mark("rstudio:...") entries, so they also show up in the DevTools Performance panel. Zero cost when the variable is unset.

2. Desktop launch sequence (src/node/desktop):

  • R was queried twice for the same executable, plus two /usr/bin/file calls; detection results are cached per executable and the Mach-O header is read directly.
  • On macOS, rsession ran the user's login shell to recover PATH at the start of every launch (~550 ms on this machine, entirely on the critical path). The desktop now asks the shell at the top of main.ts and passes the answer to rsession with RSTUDIO_SESSION_PATH_INITIALIZED=1, so the session skips its own query. If the shell has not answered by launch time, the previous launch's answer (kept in the desktop's state store) is used and the fresh one is remembered for next time; only a first launch with nothing remembered waits. Machines with a fast profile therefore always get a fresh PATH; on slow profiles a changed profile applies from the following launch.
  • The main window navigated before the session was listening, failed, showed the loading page, and polled at 200 ms intervals. It now shows the loading page first and navigates as soon as a 20 ms probe finds the listener up.

3. Query R while Electron is still starting (src/node/desktop). Detecting R means running it (~150 ms), and startup did that only once it needed the answer. The query now starts at the top of main.ts and fills the same cache the synchronous path reads, trying the executables startup would pick anyway and stopping at the first that answers. Choosing candidates and parsing the query output are now shared with the synchronous path instead of duplicated. R detection no longer appears on the critical path: it resolves about 1 ms after the launch sequence asks, and the session spawns roughly 135 ms earlier.

4. Session serves the client during R init (src/cpp):

  • The GWT file handler is registered before the http listener starts, and static GET requests that fall through to it (the page, scripts, styles) are handed by the listener thread to a dedicated static-asset thread. The client loads while R initializes; the first request the main thread sees is client_init. Measured alone this saved ~440 ms.
  • Files served in desktop mode are no longer runtime-gzipped: deflating the 6.8 MB permutation cost 161 ms per launch over loopback; it now takes 29 ms to serve. Server mode keeps runtime compression for files without a precompressed variant.
  • The large content-hashed GWT outputs (*.cache.js / *.cache.css) are now gzipped once at build time (tools/precompress.js, run from the gwtc ant target), and the file handler serves the .gz sibling with Content-Encoding: gzip whenever the client accepts it -- in both desktop and server modes, since a precompressed file costs nothing to serve and reads less disk. Server mode stops re-deflating the same immutable assets on every first load.

Baseline budget and the ranked remaining opportunities (desktop main-thread work delaying the probe by ~200 ms, the serialized set_user_state/set_user_prefs round trips before initializeWorkbench, a stable per-user port so Chromium's caches survive launches, lazy quarto/git init) are written up in the profiling report; happy to file follow-ups.

5. Client-side wave (src/gwt), from renderer trace analysis:

  • The GWT permutation was delivered as string literals and installed via eval (the xsiframe linker's default), forcing a ~125 ms main-thread compile of the 6.8 MB payload and defeating both streaming compilation and Chromium's cross-launch code cache. installCode=false makes the linker use a script tag instead: the parse moves to a background thread and the code becomes cache-eligible (the cache also needs a stable origin across launches, a possible follow-up). Wall-clock neutral alone; groundwork for the rest.
  • The boot sequence serialized Ace + style injection ahead of client_init, though neither is needed to send it; the main window now sends client_init first and loads Ace during the round trip, joining on Ace before building the workbench (~40 ms).
  • initializeWorkbench no longer waits for the set_user_state/set_user_prefs round trips (~115 ms, queued behind the session's deferred init); the local pref refresh they perform synchronously is all the workbench needs.
  • The vim/emacs keybinding bundles load lazily, requested by the first editor whose keybindings pref needs them; acesupport and ext-language-tools load in parallel after ace itself (a new AsyncJavaScriptLoader expresses staged parallel loads). Setup that must piggyback on the keybindings' arrival (vim ex commands, the emacs Return unbinding, the incremental-search message hook) re-runs on load, and everything that touched those modules unconditionally now tolerates their absence.
  • Two bugs surfaced along the way: RpcRequest caught exceptions thrown by response handlers (not just JSON parsing) and misreported them as transmission errors, hiding real client bugs behind bogus retries -- the catch now covers only the parse; and ConsolePane.getCharacterWidth() could be called before the console shell exists once workbench init stopped blocking on the pref writes (it now reports 0, the documented "no valid measurement" value).

Open points for review:

  • The static-asset fast path lives in SessionHttpConnectionListenerImpl, which all platforms use: Windows has constructed a TcpIpHttpConnectionListener (derived from it) since a7ffd1f (2017), so it gets the fast path too. SessionNamedPipeHttpConnectionListener.hpp duplicates the enqueue logic without the fast path, but nothing has included it since that commit; it could be deleted in a separate cleanup.
  • Static files are now always served from a dedicated session thread, for the life of the session, not just during startup. That seems like an improvement (deferred JS fragments load even while R is busy) but is a behavior change worth a look.
  • A non-interactive zsh -l -c does not read ~/.zshrc; that is pre-existing behavior of SessionPath.cpp, not changed here.

Automated Tests

  • Desktop unit tests for the timing writer, the login-shell PATH handoff (first launch waits, later launches use the remembered answer), and the Mach-O header reader; npm test, npm run lint, and npm run typecheck pass in src/node/desktop.
  • The tests/panes/editor Playwright suite passes against the client-side wave (179 passed; the 13 failures are all @ai Copilot tests that need credentials not available locally), including the vimrc keybinding tests, which exercise the lazy vim path end-to-end.
  • The Playwright desktop startup smoke test (PW_RUN_SMOKE=1 npm run test:desktop-dev -- tests/smoke/startup.test.ts) passes against the dev build, so the automation-agent launch path (no splash, pre-seeded cookies) still comes up.
  • C++ (RelWithDebInfo) and full GWT builds are clean. The C++ unit test suite was not run locally.

QA Notes

  • On macOS, launch from the Dock or Finder (not a terminal) and compare Sys.getenv("PATH") with a new Terminal window; they should match on the second launch and after (the first launch after install still asks the shell before starting the session).
  • Run npm run startup-timing -- --runs=3 from the checkout to reproduce the timeline. Run 1 is a first launch; compare runs 2 and later.
  • Start with a slow session (RSTUDIO_SESSION_SLEEP_ON_STARTUP=10): the loading page should appear immediately and the IDE should load when the session comes up, with no error page.
  • Kill rsession during startup: the launch error page should still appear.

When RSTUDIO_STARTUP_TIMING names a file, the Electron main process, the
rsession process, and the GWT client each append their startup checkpoints
to it as JSON lines, so one timeline can be reconstructed across all three:

- desktop (src/node/desktop/src/main/startup-timing.ts): process start,
  app ready, R detection, session spawn, window creation, page load, and
  workbench initialization; it also copies the renderer's navigation,
  resource, and performance.mark() entries into the file once the
  workbench is up
- rsession (src/cpp/core/StartupTiming.cpp): main, options, prefs, the
  http listener, R initialization, module initialization (with a span per
  sourced module R file), client_init, and deferred init
- client (org.rstudio.core.client.StartupTiming): performance marks from
  module load through the first painted workbench frame

`npm run startup-timing` (tasks/startup-timing.ts) launches RStudio Desktop
repeatedly with the variable set and prints the merged timeline as medians
across runs, followed by the longest measured spans.
…once the session listens

Three changes to the desktop's launch sequence, each measured with the
startup timing checkpoints:

- R was queried twice for the same executable (once while scanning for
  installations, once to prepare the environment), and libR's architecture
  was checked by spawning /usr/bin/file. Detection results are now cached
  per executable and the Mach-O header is read directly.

- On macOS, rsession asked the user's login shell for PATH at the start of
  every launch (SessionPath.cpp), which with a typical profile costs
  hundreds of milliseconds on the critical path. The desktop now asks the
  shell itself, at the top of main.ts, and passes the answer to rsession
  with RSTUDIO_SESSION_PATH_INITIALIZED=1, which makes the session skip
  its own query. If the shell has not answered by the time the session is
  launched, the previous launch's answer (kept in the desktop's state
  store) is used and the fresh one is remembered for next time; only a
  first launch with nothing remembered waits.

- The main window navigated to the session URL immediately, which failed
  because the session was not yet listening, and then showed the loading
  page and polled at 200 ms intervals before reloading. It now shows the
  loading page first and navigates as soon as a 20 ms probe finds the
  listener up.
In desktop and standalone modes the GWT file handler was registered at the
end of rInit, after R and every module initializer had run, and requests
were only drained from the connection queue by the main thread once it
reached its first waitForMethod. The client could therefore not begin
loading until the session was fully initialized.

The file handler is now registered before the http listener starts, and
the listener thread serves GET requests that fall through to it (no
module-registered handler, not an rpc or events request) directly, the
same way it already handles offlineable requests. The page and its
scripts load while R initializes, and the first request the main thread
sees is client_init.

Files served in desktop mode are no longer gzipped: over a loopback
connection compressing the multi-megabyte client costs far more than
sending it uncompressed. Server mode keeps compression.
@kevinushey kevinushey added this to the 2026.10 (Blue Mistflower) milestone Sep 2, 2026
Detecting R means running it, which costs about 150 ms, and startup did it
only once it needed the answer. The query now starts at the top of main.ts
and fills the same per-executable cache the synchronous path reads, so by
the time the launch sequence detects R the answer is already there; run()
awaits the background query first, which on a first launch is where any
remaining wait is paid.

The background query tries the executables startup would pick anyway --
RSTUDIO_WHICH_R, then the platform's stored, registry, or well-known
locations -- and stops at the first one that answers. Choosing the R
candidates and parsing the query output are now shared with the
synchronous path rather than duplicated, and the query result parser is
exported so it can be tested without launching R.

R detection no longer appears on the critical path at all: it resolves
about 1 ms after the launch sequence asks for it, and the session is
spawned roughly 135 ms earlier.
Distinguishes 'the probe has not started yet' from 'the probe is waiting',
which is what separates main-window construction from work blocking the
main thread while the probe is in flight.
installCode=false makes the xsiframe linker add a script tag (we always
serve same-origin), so the browser parses the 6.8 MB permutation on a
background thread instead of the renderer main thread (~125 ms there),
and the compiled-code cache can apply across launches once the origin
is stable. Wall-clock neutral on its own; groundwork for overlapping
startup work with the parse.
the boot sequence serialized ace + style injection ahead of the
client_init request, though neither is needed to send it; the main
window now starts the application first and loads ace while the round
trip is in flight, joining on ace (via a second AceEditor.load, a no-op
once loaded) before building the workbench. satellites still load ace
up front since they construct editors immediately. moves client_init
~40 ms earlier after module load.
…ound trips

the local pref refresh both the workbench and the automation agent need
is the synchronous first step of writeState()/writeUserPrefs(); the rpc
round trips only echo those values back to the server, and were queued
behind the session's deferred init (~115 ms on the startup critical
path). fire them without waiting.
the catch around response dispatch was meant for json parsing, but also
caught exceptions thrown by response handlers, converting real client
bugs into bogus 'transmission error' retries and hiding them from the
uncaught-exception log. only the parse is caught now.
with workbench startup no longer blocked on the pref write round trips,
a font-size change can request pane metrics before the console pane has
created its widget; report 0, the documented 'no valid measurement yet'
value.
the base ace load (AceEditor.load) no longer includes the vim and emacs
keybinding bundles, and loads acesupport and ext-language-tools in
parallel after ace itself. the keybindings load on demand, requested by
the first editor whose keybinding pref needs them
(AceEditor.loadKeybindings); setup that must piggyback on that load --
the vim ex commands, the emacs Return unbinding, the incremental-search
message hook -- runs via onKeybindingsLoaded or is re-applied in the
load completion, and code that touched the modules unconditionally
(copy/paste unmap/remap, VimAPI resolution, the TextEditingTarget and
AceEditorNative static initializers) now tolerates their absence.

saves two fetches (~140 KB) and their evaluation on every startup for
users on default keybindings, and trims satellite window boot, where
ace still loads up front.
wraps the callback-counter pattern from AceEditor.load into a reusable
class: each add() call contributes a stage, stages load sequentially,
and the scripts within a stage load in parallel; onFinished handlers
run after every successful execution. AceEditor's base and keybindings
loads now declare their stages with it, which also parallelizes the
vim/emacs fetch.
- treat a signal-killed rsession as exited in the session listener
  probe loop (exitCode stays null on signals)
- parse the login shell's PATH on 'close' rather than 'exit', so stdout
  is fully drained before the answer is cached
- don't block the explicitly requested Windows R chooser on the
  background R probe (the user may be choosing a different R precisely
  because the default one hangs)
- restore the default eval-based install in the Super Dev Mode modules:
  the code server serves from another origin, which the script-tag
  install requires to be same-origin
- report a null RpcResponse parse result as a transmission error;
  parse failures return null rather than throw, so they previously
  relied on the response handler crashing inside the old catch
- serve listener-thread static assets via the default handler directly
  and gate the fast path on an atomic 'registered' flag, so a module
  handler registered between the check and the dispatch can't run on
  the listener thread
- harvest the renderer timeline once the client's deferred-init-completed
  mark exists (bounded poll) instead of a fixed 3 s delay, so slow
  launches are captured in full before the measurement run ends
- keep the loading UI up until the workbench is about to be built, so a
  client_init response that beats the ace load doesn't expose a blank
  shell (switch-project keeps its existing 10 s overlay timer)
- record the session-url-reachable checkpoint only when the probe
  actually succeeded, not from .finally()
- thread the compress flag through setCacheableFile /
  setIndefiniteCacheableFile, so the desktop's no-gzip-over-loopback
  behavior also covers cacheable assets (including the multi-megabyte
  permutation), not just the main page
- replace the wall-clock detect-r cache test with a deterministic one:
  a stand-in R script answers the query, is deleted, and the synchronous
  path must still succeed, which is only possible via the cache
The startup writeState()/writeUserPrefs() calls existed only for their
synchronous updatePrefs() first step: UserPrefs can be GIN-constructed
before the client_init response arrives (eager singletons like Assistant
and both application headers inject it during Application construction),
so its pref layers start out empty. The old comment's claim that this is
desktop-exclusive is stale, and the server round trips just echoed
sessionInfo's own values back, unconditionally rewriting the pref and
state files on every IDE load.

Add UserPrefs/UserState.loadFromSessionInfo() and call that instead,
saving two RPCs and two file writes per startup.
- bound each session listener probe with a request timeout, so a
  connected socket that never answers (e.g. another process shadowing
  the port) cannot hang startup past the loop's 30 s ceiling
- drive the detect-r cache test through startRDetection() and
  rDetectionReady(), the wiring startup actually uses
registerPrefs() enumerates userPrefs_.allPrefs(); if UserPrefs was
constructed before client_init and never refreshed from the session
info, every pref registers with its default value (the #17733 failure
mode, which surfaced as an anonymous gray screen). Check explicitly and
throw with a clear message instead -- a plain Java assert would be
compiled out of the optimized GWT output that automation runs against.

Verified both ways: with the startup loadFromSessionInfo() calls
temporarily disabled, agent startup fails with the new exception
attributed to initializeAgent in the rsession log; with them in place,
the vimrc keybindings desktop e2e suite passes.
the gwt compile now writes a gzipped sibling next to each large
*.cache.js / *.cache.css output (tools/precompress.js, run from the
gwtc target with the pinned node), and the file handler serves the
sibling with Content-Encoding: gzip when the client accepts it. the
compression cost moves from every request to once per build: server
mode stops re-deflating the same immutable assets on every first load,
and the desktop gets compact transfers at zero runtime cost. the
compress option continues to govern only runtime deflate.
- skip the R-probe wait whenever the Windows chooser is going to show
  (explicitly requested, or a first run with no remembered selection),
  not just when explicitly requested
- make the login-shell PATH timeout terminal: resolve null immediately
  and SIGKILL the shell, so a profile that traps the signal cannot leave
  a first launch waiting
- when the desktop's bounded login-shell query fails or times out, tell
  the session to keep the inherited PATH (its own probe has no timeout
  and would hang on the same profile)
- ignore stored Windows R candidates that no longer exist on disk when
  predicting whether the chooser will show
- write timing-harvest-timeout instead of timing-harvested when the
  client never completes deferred init, and have the measurement task
  fail that run as incomplete
- treat the synthesized placeholder pref layer ([{}], no values) as not
  loaded in hasLoadedLayers(), so the agent-init tripwire catches the
  missing-user-layer case too
- keep a terminal launch's PATH on macOS: when the inherited PATH already
  contains /usr/local/bin (the session's own initializePath() heuristic),
  the desktop no longer overrides it with the login shell's answer, so
  customizations like an activated conda environment survive; such
  launches also skip the first-launch wait for the shell query
- a libR.dylib read failure now fails the launch again instead of
  silently letting the two callers guess different architectures
- install the Ace keyboard previewer and event listeners even while the
  vim/emacs keybinding bundles are still loading; only the choice of
  keyboard handler waits on them
- escape checkpoint names when writing startup-timing JSON lines (one
  call site embeds a request URI)
- the startup-timing report skips runs whose timing file has no
  checkpoints instead of crashing on them
- reword the stale s_gwtHandlersRegistered comment (the handlers were
  never registered in server mode) and drop the now-dead duplicate
  node.bin block in build.xml
the listener thread now hands static asset requests to their own queue,
drained by a worker thread (desktop and standalone modes only), so their
file reads and socket writes can no longer stall connection accepts or
abort/suspend/interrupt handling on the listener thread
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Addressed this round in 94eddbe and 73c1eba -- details in the inline replies. The duplicate node.bin block is gone too (the older one at build.xml:617 was the dead one). The only item I pushed back on is the automation-tripwire throw; see that thread.

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

LGTM!

This branch was previously deployed

1 inactive deployment
e2e-playwright — 73c1eba3 Deployed Sep 4, 2026 by kevinushey via macos / e2e-desktop-macos (1) #853
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.

2 participants