Skip to content

reduce blocking work during startup - #19030

Merged
kevinushey merged 17 commits into
mainfrom
bugfix/startup-performance
Oct 10, 2026
Merged

kevinushey merged 17 commits into
mainfrom
bugfix/startup-performance

Conversation

@kevinushey

@kevinushey kevinushey commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Reduce startup work that blocks the R session and avoid repeating installation probes on subsequent launches. Automatic Python discovery currently runs synchronously during deferred initialization even when no Python feature is being used.

On macOS arm64, the final worktree build compared with unchanged b2d42d0224 produced these medians across three repeated launches, after one fresh-profile launch:

Phase Before After
Workbench painted, from Electron process start 1,871 ms 1,498 ms
Wait for R metadata after app ready 375 ms 66 ms
Session module initialization 370 ms 255 ms
Blocking deferred initialization 1,698 ms 56 ms
Deferred completion milestone, from process start 4,514 ms 2,566 ms
Client initialization 122 ms 157 ms

Both builds used Debug rsession, draft GWT, Electron 43.7.7, R 4.6.1 and Quarto 1.10.18. Profiles were isolated and reused within each measurement. These are local timings, not a cross-platform performance guarantee. Client initialization did not improve in this comparison. The deferred completion milestone includes the existing one-second scheduled hook.

Approach

  • Run automatic Python discovery in an asynchronous child R process, with a 30-second deadline. Resolve explicit configuration immediately and discard late results after interpreter initialization or a synchronous terminal request. A terminal that needs the result before discovery finishes retains its existing synchronous fallback. A discovery that fails is recorded as "no Python" so terminals don't repeat it synchronously; one that merely times out is retried in the background the next time a terminal asks.
  • Cache successful R metadata queries on disk, checking executable and installation file identity/timestamps and relevant environment variables before reuse. Keep the existing early asynchronous probe on cache misses.
  • Cache successful quarto --paths results, keyed by installation, version and Quarto environment overrides. A hit still requires a launchable launcher, its tools directory and the cached directories; development versions bypass the cache, damaged or stale caches trigger the original probe, and a launcher that later fails to start drops the cache for the next session.
  • Leave TeX capability checks to their existing on-demand RPC consumers, which now cache the first answer in session info and share one in-flight probe, so later editors skip the round trip. The TeX probe used to put TinyTeX on the session PATH as a side effect; deferred initialization now does that explicitly. HTML capabilities (a knitr install check costing well under a millisecond) stay in client init. These package/tool checks can change during a session, so persistent caching would be inappropriate.
  • Register SQL and Stan helpers/RPCs through lazy proxies derived from each module's definitions (only definitions at the start of a line, never shadowing a helper another module already defined), and source the R modules on first use. A proxy re-issues the caller's own call against the loaded definition rather than forwarding ..., so substitute(), match.call(), match.arg() and sys.function() behave as in a direct call. Defer the chat base-package scan until guardrails are first installed, before hooks are active.

R metadata and Quarto paths are needed for launch configuration and are stable enough to cache with invalidation. Python and authoring capabilities are optional during initialization, so they use asynchronous discovery or RPCs instead. SQL and Stan have no startup hooks and can load at first use.

Automated Tests

Built and tested on macOS arm64; Windows and Linux remain untested locally.

  • Native session build and GWT draft build passed.
  • TypeScript typecheck and ESLint passed for the desktop changes.
  • Electron tests: 453 passing (12 for R detection), covering R detection, disk-cache reuse, production output separators, installation changes, environment changes, symlinks, missing installations and damaged cache entries.
  • Native cache and Quarto tests: 9 passing, plus PythonDiscoveryState (timeout retried, failure recorded, success reused) and quartoPathsUsable (launcher permissions, missing tools or resources directories) under gtest; 682 rsession tests pass.
  • R integration tests: 137 passing assertions, no warnings/failures; six existing Python execution tests skipped with no configured interpreter. Covers lazy loading, retry after failed loading, SQL/Stan first use, Python configuration and chat guardrails. The second review round added tests for the anchored definition scan, proxies that never shadow existing helpers, replacement by a later lazy module, the TinyTeX PATH helper (called directly, since deferred init does not run under --run-script), and proxy invocation semantics including forwarded dots and lapply (59 passing in the affected files).
  • With RETICULATE_PYTHON=/usr/bin/python3, Python tests passed 29 assertions; one existing test skipped because it requires Python 3.14.
  • Four final launches completed successfully using node tasks/startup-timing.ts --warm-profile --runs=4 --out=<isolated-directory>. The committed build also completed a fresh-profile startup smoke test. Checked timing-tool help and rejection of incompatible profile flags.

QA Notes

Verify cold and repeated launches, switching/upgrading R and Quarto, environment overrides, terminal creation while Python discovery is pending, interpreter initialization during discovery, R Markdown/TeX authoring, and SQL/Stan first use. Repeat on Windows and Linux. The new --warm-profile mode clears its isolated profile on run 1 and reuses it thereafter, so cache measurements do not require the user's real profile.

Documentation

Updated timing-tool help for repeated-launch measurements. No user setting or new UI is introduced. The NEWS entry links this PR; there is no associated issue.

Checklist

  • NEWS entry added (links this PR; no associated issue)
  • No new or changed UI
  • Relevant local builds and tests pass
  • Cross-platform QA

@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
3471 0 200 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 10 0
✅ desktop-linux 873 0 39 0
✅ desktop-macos 878 0 34 1
✅ desktop-windows 864 0 53 1
✅ server-linux 826 0 44 0
✅ setup 28 0 20 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 79e968482fb57be918c0c8e09e6001f5ae123f07 - Run #1432

@gtritchie gtritchie added this to the 2026.11 (Montauk Daisy) milestone Oct 5, 2026
- clear a damaged r-environment.json instead of failing on every launch
- wait for the HTML capability probe in preview/compile actions; retry
  a failed probe; drive refreshes with a generation counter
- cache the first TeX capability answer in session info
- derive lazy-module proxies from the module's own definitions
- key the Quarto paths cache on the installation only, not cwd/PATH
- record a timed-out or failed Python discovery so terminals don't
  repeat it synchronously
- NEWS entry
@kevinushey
kevinushey marked this pull request as ready for review October 7, 2026 23:01
- prefetch HTML capabilities from an eager FileTypeCommands singleton as
  soon as session info exists, not only when an editor is already open
- add TinyTeX to the PATH during deferred init now that client init no
  longer probes TeX
- lazy module proxies: anchor the definition scan to line starts, never
  shadow a helper another module already defined, and hoist the loader
  out of the closure
- retry a timed-out Python discovery in the background instead of
  recording "no Python" for the session
- a Quarto paths cache hit requires a launchable launcher and its tools
  directory; a launcher that fails to start drops the cache
- share the R environment cache read/write between the sync and async
  detection paths; drop the dead exit-status guard and the duplicated
  immediate branch in TextEditingTarget
…roxy calls

- extract PythonDiscoveryState so the timeout/failure/success transitions
  and the terminal's resulting action are plain values under gtest
- export quartoPathsUsable (launcher passed in) and test it against a
  temporary quarto layout
- lazy module proxies re-issue the caller's call against the loaded
  definition instead of forwarding '...', so substitute(), match.call(),
  match.arg() and sys.function() behave as in a direct call; tested
  along with forwarded dots and lapply-style invocation
@kevinushey
kevinushey requested a review from gtritchie October 8, 2026 21:57

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

Review of the startup changes. Items whose impact I couldn't fully confirm are marked as such in the inline comments.

Main points:

  • SessionChat.R: the lazy chat.basePackages promise resolves rownames / installed.packages through the global env at first chat use, which can empty the guardrail's base-package list (credential-pattern check). Easy fix: eval.env = baseenv().
  • SessionReticulate.cpp: background and synchronous Python discovery run in different working directories, so project .venv/pipenv detection depends on timing.
  • HTML capabilities: previewHTML waits even for .md/.html, and clicks during a failed probe queue silently. Given the measured client-init numbers, it may be simpler to keep the capability checks in client init.
  • test-tinytex.R may depend on deferred init, which I don't think runs in the r test scope.

The rest are minor (efficiency, a leak on the lazy-load error path, reuse, two convention nits).

.rs.setVar("chat.basePackages", rownames(
installed.packages(priority = "base", lib.loc = .Library)
))
delayedAssign(

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.

Guardrail base-package list is now resolved through the global env at first chat use.

The promise's eval env is the local() env created by SourceManager::source, which is evaluated in R_GlobalEnv (executeString). So rownames / installed.packages are looked up through the global env when chat.injectBindings() first forces the promise, not at module init as before.

.RData is restored as a deferred action after module init (RInit.cpp, deferredRestoreNewSession). A global rownames <- function(...) character(0), left by agent code and saved to .RData, is therefore in place before the next session's first chat use. I checked this in R by emulating local(source(local = TRUE)) from globalenv: the forced value has length 0. With basePkgs empty, chat.hasTrustedCallerImpl treats base namespaces as trusted callers, and isFileReadAllowed skips the denyReadPatterns credential check for e.g. base::readLines(...). The not-world-readable check still applies, unless the umask strips world-read.

Suggested fix: delayedAssign(..., eval.env = baseenv(), ...) with utils::installed.packages / base::rownames.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 6a722d3: the promise now evaluates in baseenv() with base::rownames / utils::installed.packages. Verified with a global rownames override that the original form yields a zero-length list and the fixed one the full base-package list.

discovery->start(
command,
{{"RETICULATE_MINICONDA_ENABLED", "FALSE"}},
module_context::safeCurrentPath(),

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.

Async and synchronous discovery run in different working directories.

This child runs in safeCurrentPath(). The synchronous fallback (.rs.inferReticulatePython() → .rs.executeFunctionInChildProcess with workingDir = NULL) setwd()s into a temp script dir before launching R. reticulate::py_discover_config() checks Pipfile/pipenv and ./venv, ./.venv, ./virtualenv, ./.virtualenv relative to the cwd (R/config.R in rstudio/reticulate).

In a project with a .venv, a terminal opened while discovery is still pending records a different interpreter, or none, than the background path would. RETICULATE_PYTHON_FALLBACK and the terminal hooks then depend on timing. Running both paths in the same directory would make them agree.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 67d6988: the synchronous fallback now passes workingDir = getwd() so both probes run where the session is. Worth noting that before this PR the only discovery path ran in executeFunctionInChildProcess's temp dir, so project .venvs were never found; now both paths find them.

skip_if(!nzchar(Sys.which(file.path(bin, "pdflatex"))), "TinyTeX has no pdflatex")

# client init no longer probes TeX; deferred init adds TinyTeX instead
expect_true(nzchar(Sys.which("pdflatex")))

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.

This seems to depend on deferred init, which I don't think runs in the r test scope.

onDeferredInit fires from ensureDeserialized(), which is reached via ensureSessionInitialized() (HTTP/client init) or the suspend path. The r scope runs under --run-script with no client, and I couldn't find another trigger (rInitComplete and RReadScript don't call it). If so, on a TinyTeX-only machine both skip_ifs pass and this fails; where pdflatex is already on PATH it passes without exercising the new code. I couldn't run it to confirm, so please double-check.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

You're right: nothing reaches ensureSessionInitialized under --run-script, and here the test passed only because MacTeX is on PATH. cb977b5 adds an rs_addTinytexToPath call method; the test now strips every pdflatex from PATH, calls it, and asserts pdflatex is reachable again. That exercises the helper rather than the deferred-init wiring, which is one line.

}


void previewHTML()

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.

previewHTML now waits on the capability probe even for .md / .html files.

For those types verifyPrerequisites always returns true, but the preview still defers through withHTMLCapabilities. If the probe hasn't answered (e.g. get_html_capabilities is queued behind a long .RData restore at deferred init), ShowHTMLPreviewEvent fires from the RPC callback, and HTMLPreview's openSatellite (window.open) runs outside the click. On Server the browser can block it. Waiting only when fileType_.requiresKnit() || fileType_.isRpres(), as the editor-init path does, would keep these synchronous.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Moot now: html_capabilities is back in client init (see the SessionClientInit thread), so previewHTML is synchronous for every type again.

Comment thread src/cpp/session/SessionClientInit.cpp Outdated
sessionInfo["compile_pdf_state"] = modules::authoring::compilePdfStateAsJson();

sessionInfo["html_capabilities"] = modules::html_preview::capabilitiesAsJson();
sessionInfo["html_capabilities"] = json::Object();

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.

Is deferring HTML capabilities worth the extra machinery?

.rs.getHTMLCapabilities only checks whether knitr is installed and its version. Moving it out of client init added an eager singleton, a generation counter, a retry timer, a callback queue, wrapped editor actions and an e2e test. The PR's own table shows client init going from 122 ms to 157 ms. Keeping html_capabilities (and tex_capabilities) here would avoid the timing-dependent behaviour in FileTypeCommands/TextEditingTarget noted in the other comments.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed. The knitr check measures at about 0.6 ms warm, so deferring it bought nothing. 79e9684 moves html_capabilities back into client init and removes the FileTypeCommands probe machinery, the wrapped editor actions, FileTypeCommandsTests and the e2e test. Only the TeX probe stays deferred.

{
Error error = sourceModuleRFile(r::sexp::asString(moduleSEXP));
if (error)
r::exec::error(error.getSummary());

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.

Minor: r::exec::error is Rf_error, a longjmp. It runs while error and the getSummary() temporary are alive, so their destructors are skipped and each failed lazy load leaks them. Copy the message into a scoped string, let error go out of scope, then raise.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 2798ed1: the message is copied out and the Error goes out of scope before r::exec::error.

// still pending when the editor closes is released with it.
private void withHTMLCapabilities(CommandWithArg<HTMLCapabilities> callback)
{
releaseOnDismiss_.add(fileTypeCommands_.withHTMLCapabilities(callback));

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.

Minor: each Preview/Compile Report click adds a registration to releaseOnDismiss_, including the no-op returned when capabilities are already cached. They are released only when the editor closes, so they pile up in long-lived editors.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Moot now: withHTMLCapabilities and these registrations are gone with the revert in the SessionClientInit thread.

constructor(directory?: string) {
// conf parses the file here; a damaged one must be a miss on this and
// every later launch, not a throw that disables the cache until repaired.
this.store = new ElectronStore({

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.

Minor (reuse): login-shell-path.ts already keeps a startup-state ElectronStore for remembered startup probes, with the same CJS/ESM interface workaround. Storing the R query under a key there would avoid a second store file and wrapper (clearInvalidConfig is already set differently between the two).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'd keep them separate: the R cache relies on clearInvalidConfig: true so a damaged file is a miss that heals itself, while login-shell-path opens its store in a try/catch and treats failure as "no remembered path". Sharing one file couples those lifecycles and both test suites' fixtures.

Comment thread NEWS.md

### New
-
- ([#19030](https://github.com/rstudio/rstudio/pull/19030)): Reduced the work that blocks session startup: automatic Python discovery for reticulate now runs in the background, R and Quarto installation details are cached between launches, and SQL and Stan support loads on first use.

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.

Nit: .claude/CLAUDE.md asks NEWS entries to follow ([#NNNN](https://github.com/rstudio/rstudio/issues/NNNN)). This links /pull/19030, the only /pull/ link in the file.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This follows the existing practice for entries without an issue: #17822, #18020, #18091 and #18330 link their PRs in the 2026.05 through 2026.08 release notes.

Comment thread src/cpp/session/modules/ModuleTools.R Outdated
#
#

# The names a module would register when sourced. Startup enumerates RPC

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.

Nit: .claude/CLAUDE.md says to document R code in Roxygen style. ModuleTools.R has no Roxygen blocks today, so this matches the file; flagging only for the rule.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 477a788: the new helpers now have Roxygen blocks.

@kevinushey
kevinushey requested a review from gtritchie October 9, 2026 17:24

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

Thanks -- the fixes look good. Agreed on the NEWS link (my mistake) and on keeping the two stores separate.

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