Repository navigation
reduce package pane refresh overhead - #17457
Conversation
The post-install file.info diff that the install.packages hook uses to identify which packages changed now scans only the requested packages and their dependency closure (as computed from the user's 'dependencies' argument), rather than the entire library. Avoids O(library) filesystem work per install on large libraries or slow filesystems. Addresses rstudio/rstudio-pro#10771.
Replaces the onConsolePrompt substring match against 'install', 'update',
'remove', etc. with a compiled regex that requires an opening '(' after
the identifier. Stops spurious Packages pane refreshes from benign input
like 'updates <- c(1, 2)' or 'installed.packages()', while still catching
base R, devtools/remotes, pak, pacman, and renv entry points. Keywords
are listed one per line so it's easy to extend.
Addresses rstudio/rstudio-pro#10771.
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
install.packages writes to lib[[1L]] in the common case; restrict the before/after file.info scan to that path rather than every entry of lib.
install.packages only coerces 'dependencies' to FALSE in the multi-lib case when the user hadn't supplied a value (i.e. it was NA). An explicit TRUE/FALSE/character vector is respected as-is. Since the before/after scan is already restricted to lib[[1L]], over-approximating the candidate set in the multi-lib case is harmless — paths for packages that landed in other libraries simply don't appear in either snapshot.
Replaces the before/after file.info diff with a single post-install scan whose reference time is read from a freshly-created sentinel file in the target library. Halves the filesystem work performed by the hook and avoids clock-skew concerns between R's Sys.time() and the library filesystem (relevant for NFS / CIFS).
Introduces an admin-controlled session option (default true) that suppresses post-install tagging of DESCRIPTION files with RemoteType / RemoteRepos fields. When disabled, the install.packages hook skips the available.packages() fetch, dep-closure computation, sentinel write, post-install scan, and recordPackageSource step entirely. Useful for deployments where admins want to avoid mutating DESCRIPTION files in installed package directories, or where the Packages pane's detailed Source column is not needed.
Previously we called utils::available.packages() with no arguments, so it
read getOption("repos") regardless of what the user passed to
install.packages(). If those disagreed (e.g. install.packages(..., repos =
internal_url)), the db used by recordPackageSource could annotate packages
with the wrong RemoteRepos URL. Threading the hook's 'repos' formal through
keeps available.packages() and install.packages() consistent.
gtritchie
left a comment
There was a problem hiding this comment.
Sharing notes from a review pass. Architecture looks sound — scoped scan + sentinel mtime + hoisted available.packages() + tightened regex all make sense. Main concern across the diff is that the new fast path replaces a slow-but-robust full-library diff with three operations (file.create, available.packages, tools::package_dependencies) whose failure modes aren't surfaced anywhere, so a network blip or read-only library silently degrades source recording with no log line.
Critical
1. file.create(sentinel) return value discarded — src/cpp/r/R/Tools.R:2608-2611
On a read-only library, full disk, or restrictive umask, file.create() returns FALSE (with a warning, not an error). Then file.info(sentinel)$mtime is NA, after$mtime >= installStart propagates NA, and !is.na(after$mtime) & NA is FALSE for every row. Result: install.packages() succeeds, but zero DESCRIPTIONs get tagged — no warning, no log. Pre-PR code didn't have this failure mode. Suggest checking the return value and falling back to Sys.time() (or logging via .rs.logWarningMessage and skipping tagging explicitly).
2. available.packages(repos = repos) is unguarded on the hot path — Tools.R:2568-2571
Previously this only ran after a successful install (inside recordPackageSource). It now runs before every non-local install. A flaky DNS, stale repos =, or transient outage throws, the install never happens, and the user sees an error pointing at the hook rather than at their command. Worth wrapping in tryCatch with a fallback (empty db → fall back to the whole-library scan, or surface a clear message).
Important
3. tools::package_dependencies returning NULL silently shrinks the candidate set — Tools.R:2591-2598
When db is missing a requested package (Bioconductor, R-universe, private mirror, or available.packages() returned 0 rows), candidates collapses to just pkgs. Dependencies that install.packages actually fetches won't be in paths and never get tagged. At minimum, log via .rs.logWarningMessage when pkgs aren't all present in db so a repos mismatch is debuggable.
4. lib[[1L]] comment understates the limitation — Tools.R:2600-2601
"install.packages writes to the first entry of lib in the common case" is true for length>1 vectors per ?install.packages (with a warning). But if a caller passes lib = c(readonly_path, writable_path), install writes to the second entry; the scan only looks at lib[[1L]] and misses every install. Either expand the comment to acknowledge this, or resolve lib to the actual write target before scanning.
5. Regex comment conflates two mechanisms — src/cpp/session/modules/SessionPackages.cpp:351-353
"Must be followed by (" is the gate for updates <- .... installed.packages() is excluded by a different mechanism — the optional [._] suffix never matches e after install, so the alternative fails before reaching \\(. Worth splitting the rationale.
6. Test coverage gaps
The PR description lists three planned follow-up tests. A few specific gaps worth pinning before merge:
- Regex behavior is the most load-bearing change and the most regressible. A
SessionPackagesTests.cpp(followingSessionRCompletionsTests.cpp) covering at minimum:install.packages(...),pak::pkg_install(...),devtools::install_github(...),renv::install(...),update.packages(), vs.installed.packages(),updates <- c(1,2),# install foo,x <- update. Would needbuildPackageCallRegexexposed via an internal header. installedPackagesFileInfo(paths=)including theis.na(mtime)row case (dependencies that were already up-to-date) — testable directly insrc/cpp/tests/testthat/test-install-packages.R.- No-op reinstall mtime invariant — install pkg, install again, confirm DESCRIPTION is not re-tagged. Catches subsecond-mtime issues on shared filesystems.
recordPackageSource(db=...)skip-network contract — setoptions(repos = \"http://localhost:1\")and confirm install + tagging succeeds with no network call.dependenciesargument branches (TRUE / FALSE / character / NA) — currently all five paths throughwhichDepsare untested.
Suggestions
7. Tighten the dependencies tryCatch — Tools.R:2577-2580
tryCatch(get(\"dependencies\", ..., inherits = FALSE), error = function(e) NA) swallows any error, not just "binding missing." if (exists(\"dependencies\", envir = environment(), inherits = FALSE)) distinguishes the documented case from corrupted-environment cases. Or add .rs.logWarningMessage inside the catch so the breakage leaves a trace.
8. is.character(NA_character_) is TRUE — Tools.R:2582-2589
A user passing dependencies = NA_character_ would route through is.character and hand NA_character_ to tools::package_dependencies(which = ...). Exotic; userDeps[!is.na(userDeps)] in the character branch would harden it.
Strengths
allow-package-source-recordingplumbing matches the existingallow-package-installationpattern exactly acrosssession-options.json,SessionOptions.gen.hpp, and the violations accumulator.recordPackageSource(db = NULL)andinstalledPackagesFileInfo(paths = NULL)preserve back-compat for existing call sites (e.g.SessionDependencies.R:209).- NFS/CIFS clock-skew comment is accurate — the code uses
file.info()$mtime(fs clock), notSys.time()(session clock), so the comparison is in the same clock domain. The "why" is exactly right. \\b/_rationale for enumeratingpkg_*/p_*/local_*explicitly is correct:_is a word character so there's no boundary betweenpkgand_install.- All three branches (
!recordSources,isLocal, else) preserve theinteractive()post-install notification, so disabling source recording doesn't break the Packages pane refresh. - The
defineHookImplformals-copying explanation atTools.R:2573-2576is load-bearing — without it,get(\"dependencies\", envir = environment(), inherits = FALSE)looks like a bug.
Recommended order
- Address findings 1 and 2 (real silent-failure regressions vs.
main). - Add at least a log for finding 3.
- Land the regex gtest (finding 6) — cheapest hermetic protection for the most regressible behavior.
- Tighten comments at 4 and 5.
- 7 and 8 are author's call.
- guard available.packages() lookup with tryCatch; on failure, log INFO and
skip post-install source recording rather than failing the user's install
- check file.create(sentinel) return value; fall back to Sys.time() with a
warning when the library directory isn't writable
- log when requested packages aren't present in available.packages() so a
'repos' mismatch is debuggable
- scan every entry of 'lib' (install.packages recycles it against 'pkgs')
instead of only lib[[1L]]
- split the regex comment in SessionPackages.cpp to separately explain the
'\(' and '[._]' gates
- extract whichDeps mapping into .rs.installPackagesWhichDeps for testability
- expose isPackageManagementCall via SessionPackages.hpp; refactor
onConsolePrompt to use it; add SessionPackagesTests.cpp with 9 gtest cases
- add testthat tests for .rs.installPackagesWhichDeps, NA-mtime in
installedPackagesFileInfo(paths=), no-op reinstall tagging, and the
recordPackageSource(db=) skip-network contract
…packages-scan # Conflicts: # src/cpp/r/R/Tools.R
Address roborev #372: - .rs.installPackagesWhichDeps now returns list(direct, transitive). The install.packages hook expands direct deps non-recursively (which may include Suggests when dependencies = TRUE) and recurses only through the transitive (strong) set. Mirrors install.packages's getDependencies() so the candidate scan isn't over-expanded by Suggests-of-Suggests chains install.packages won't follow. - Create one sentinel per 'lib' entry. The per-path libStart recycles position-wise against paths built from outer(lib, candidates, ...), so cross-filesystem clock skew between library entries can't mask real installs in non-primary libraries. - Filter NA_character_ out of the user's 'dependencies' argument before passing to tools::package_dependencies(which = ...). Tests updated for the new list shape, plus a case for NA filtering.
The skip-if-already-tagged guard read via packageDescription(), which
prefers Meta/package.rds over DESCRIPTION. The function then appends
Remote* lines to DESCRIPTION. If the two are out of sync (e.g. after
a manual rebuild that regenerated package.rds from a tagged
DESCRIPTION), the guard would miss and we'd append a duplicate set of
Remote* lines. Reading via read.dcf(descPath) makes the guard
consistent with the write target.
Also bump degraded-mode logs from logInfoMessage to logWarningMessage:
available.packages() failures and packages absent from db both mean
silent loss of source tagging, which is worth surfacing at the
default log level.
Tests:
- new no-op assertion for recordPackageSource(character(), db = ...)
- new integration test for the transitive-dep tagging path
(install.packages('B') with B Imports A, both DESCRIPTIONs tagged)
- generalize the local-source-repo helper to take a list of package
specs so the dep test can build A and B in one repo
Intent
Addresses rstudio/rstudio-pro#10771.
Summary
Two changes that both cut work triggered by Packages pane refreshes, especially noticeable with large libraries or slow filesystems (e.g. NFS):
install.packages()hook before/after scan. The hook used to difffile.info()across the entire library to identify which packages were installed or updated. It now scopes the scan to the requested packages plus their dependency closure (derived from the user'sdependenciesargument), which is an upper bound on whatinstall.packagescan touch. Also threads a singleavailable.packages()lookup through torecordPackageSourceso we don't fetch it twice.boost::algorithm::containscheck would fire on any input containing substrings likeinstall,update, orremove. It now uses a compiled regex that requires an opening(after the identifier, eliminating false positives likeupdates <- c(1, 2)andinstalled.packages()while still catching base R, devtools/remotes, pak, pacman, and renv entry points.Related OSS issue on the broader "slow with many installed packages" theme: #17392.
Test plan
Manual verification done so far:
Tools.R;rsessionC++ build clean.get("dependencies", envir = environment(), inherits = FALSE)correctly resolves the default NA and explicitTRUE/ character-vector / unrelated-arg cases afterformals(hook) <- formals(original).Still to do (tests to be added in follow-up commits on this branch):
install.packageshook (single-pkg install, multi-pkg install,dependencies = FALSE,dependencies = TRUE).onConsolePromptdetection.RemoteReposannotations.