Repository navigation
reduce blocking work during startup - #19030
Conversation
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
- 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
- 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
gtritchie
left a comment
There was a problem hiding this comment.
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.basePackagespromise resolvesrownames/installed.packagesthrough 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:
previewHTMLwaits 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
rtest 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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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(), |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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"))) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Moot now: html_capabilities is back in client init (see the SessionClientInit thread), so previewHTML is synchronous for every type again.
| sessionInfo["compile_pdf_state"] = modules::authoring::compilePdfStateAsJson(); | ||
|
|
||
| sessionInfo["html_capabilities"] = modules::html_preview::capabilitiesAsJson(); | ||
| sessionInfo["html_capabilities"] = json::Object(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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({ |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
|
|
||
| ### 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. |
There was a problem hiding this comment.
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.
| # | ||
| # | ||
|
|
||
| # The names a module would register when sourced. Startup enumerates RPC |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Done in 477a788: the new helpers now have Roxygen blocks.
gtritchie
left a comment
There was a problem hiding this comment.
Thanks -- the fixes look good. Agreed on the NEWS link (my mistake) and on keeping the two stores separate.
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
b2d42d0224produced these medians across three repeated launches, after one fresh-profile launch: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
quarto --pathsresults, keyed by installation, version and Quarto environment overrides. A hit still requires a launchable launcher, itstoolsdirectory 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...., sosubstitute(),match.call(),match.arg()andsys.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.
PythonDiscoveryState(timeout retried, failure recorded, success reused) andquartoPathsUsable(launcher permissions, missingtoolsor resources directories) under gtest; 682 rsession tests pass.--run-script), and proxy invocation semantics including forwarded dots andlapply(59 passing in the affected files).RETICULATE_PYTHON=/usr/bin/python3, Python tests passed 29 assertions; one existing test skipped because it requires Python 3.14.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-profilemode 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