Skip to content

move PPM vulnerability download off the R main thread - #17808

Merged
kevinushey merged 6 commits into
rel-golden-wattlefrom
bugfix/17807-async-ppm-vulns-golden-wattle
Jun 1, 2026
Merged

kevinushey merged 6 commits into
rel-golden-wattlefrom
bugfix/17807-async-ppm-vulns-golden-wattle

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses #17807.

When PPM integration is enabled and the active repo is a PPM URL, RStudio fetched
package vulnerability data on a blocking curl::curl_fetch_memory() call on the
R main thread, inside the synchronous get_package_state path reached at startup. A
slow or unreachable PPM therefore froze the entire IDE for the full TCP timeout
(~60s in the report).

Changes

  • Stop downloading from R. Removed all networking from SessionPPM.R. It now only
    does fast, local, pure-CPU work: build a request plan (what to fetch + a netrc-derived
    Authorization header + the request body), fold an NDJSON response into the per-repo
    cache, and aggregate the cache by package name. Also hardened the NDJSON parser against
    empty bodies (the subscript out of bounds case noted in the issue).
  • Fetch asynchronously, governed from C++. ppm::refreshVulnerabilitiesAsync() runs
    the POST off the main thread via TcpIpAsyncClientSsl/TcpIpAsyncClient on
    server_rpc::ioContext(), with an explicit 10s connection timeout, then marshals back
    to the main thread to update the cache and publish results. Supports both https and
    http endpoints (parity with the old curl path), and honors https_proxy.
  • Decoupled delivery. get_package_state no longer carries vulnerability data; the
    package list returns immediately. Vulnerabilities arrive shortly after via a new
    package_vulnerabilities_ready client event, applied to the table without rebuilding
    the package list. The event is published when each refresh batch drains (success or
    total failure, including when no request is launched) so the pane is always updated
    deterministically and never shows stale badges.

Testing

  • rstudio-tests --scope r --filter ppm: 35/35 pass (reworked request-plan /
    record-response / cached-aggregation coverage).
  • GWT ant javac and backend cmake --build both clean.

No NEWS.md entry: this release branch does not track NEWS.md.

Fetch package vulnerability data asynchronously from C++ instead of
issuing a blocking curl request on the R main thread, so a slow or
unreachable Posit Package Manager can no longer freeze IDE startup.
Results are delivered to the client via a new package_vulnerabilities_ready
event. Also hardens the NDJSON parser against empty responses.

Addresses #17807
- support both http and https PPM endpoints (mirror SocketRpc), rather
  than hard-rejecting non-https and silently dropping vuln checks for
  http-configured deployments
- publish vulnerability data when the request batch drains (on success
  or total failure) instead of only per successful response, so a failed
  fetch after a repo/package change can't leave stale badges in the pane
If every entry in a non-empty request plan fails preflight URL
validation, no async request is started and the batch never drains, so
no event would be published. Publish the cached set after the loop when
s_activeRequests is still zero, keeping every refresh deterministic.
@kevinushey kevinushey added this to the Golden Wattle milestone Jun 1, 2026
@kevinushey
kevinushey requested a review from gtritchie June 1, 2026 17:35
@gtritchie

gtritchie commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Review

No blocking issues. A couple of behavioral items are worth a look before merge.

Important

1. A connected-but-stalled PPM hangs a request forever and permanently disables vuln refresh for the session. SessionPPM.cpp (kConnectionTimeout, sendVulnerabilityRequest)

kConnectionTimeout (10s) is passed only to TcpIpAsyncConnector::connect, so it bounds the TCP connect phase only — AsyncClient has no read/handshake deadline (only a connection-retry timer). A PPM that completes the TCP handshake but then stalls during TLS or while streaming the body keeps the request in-flight indefinitely: neither completion callback fires, so s_activeRequests never returns to 0. Because refreshVulnerabilitiesAsync() only sets s_refreshPending = true when the counter is non-zero, every later refresh (install, libpath change, repo switch) is then silently dropped for the rest of the session.

The IDE itself no longer freezes (the primary goal holds), but a degraded-but-reachable PPM — exactly the target scenario — silently kills the feature after a single hung request. Consider a response/read deadline that closes the socket and routes to the error callback so the batch always drains.

2. The get_package_state RPC path no longer triggers a refresh, so re-join shows no badges and Refresh doesn't re-fetch. SessionPackages.cpp:455-465, Packages.java:206-207

refreshVulnerabilitiesAsync() is called from onDeferredInit and enquePackageStateChanged, but not from the get_package_state RPC handler. That RPC is the sole path for (a) re-join/reconnect to an already-running session (Packages.java:206-207, where onDeferredInit won't re-fire) and (b) the user-facing Refresh command. Since getPackageStateJson now returns empty vulns and a reconnected client's vulns_ starts empty, a re-joined session shows no vulnerability badges until some incidental package mutation fires enquePackageStateChanged. The old synchronous code returned vulns inline on every get_package_state, so this is a regression. Fix looks like a one-liner: call ppm::refreshVulnerabilitiesAsync() from the getPackageState handler.

(These two compound: once a request hangs per #1, even the refresh triggers that do exist are blocked.)

Suggestions

  • Empty HTTP-200 body marks all requested packages "safe" and caches it. SessionPPM.R parseVulnerabilityResponse/recordVulnerabilityResponse — a 2xx with an empty/whitespace body returns the empty marker (not NULL), so every requested key is cached as "checked, no vulns" and not retried. Roughly matches legacy behavior (not a regression), but it's the one path that can wrongly clear badges. Consider returning NULL for a genuinely-empty server body (retry) while keeping the empty result only for the length(contents) == 0L crash-guard case.
  • A few C++ log-and-return paths skip the deterministic client update. SessionPPM.cpp enqueCachedVulnerabilities/startVulnerabilityRequests — if the R call or jsonValueFromObject fails, no package_vulnerabilities_ready event is emitted, so the "always update the UI" guarantee holds only when those R calls succeed. Low likelihood (our own SEXP), but it weakens the determinism the design leans on.
  • Dead code: PackageState.getVulnerabilityInfo() (PackageState.java:41) has zero remaining callers now that setPackageState stopped reading it. Per "replace, don't deprecate", worth removing the accessor and trimming the now-empty vulns payload from the PackageState JSON.
  • Stale comment: test-ppm.R:24 references .rs.ppm.getVulnerabilityInformationImpl, which this PR deletes; it's the only surviving reference to that name anywhere. Repoint to .rs.ppm.repoVulnCache / aggregateVulnsByName.
  • Unrelated change: the TextEditingTargetWidget.java lambda -> ScheduledCommand swap with // avoid lambda here (makes gwt devmode sad) is unrelated to PPM and the comment is contradicted by the ~38 other lambdas in that same file (including the identical scheduleDeferred pattern just above). Either state the concrete dev-mode failure (+ a tracking issue) or drop it; ideally it's a separate commit.
  • Lost per-repo error isolation: getCachedVulnerabilities dropped the per-repo tryCatch the old code had, so one repo's aggregation error now kills the whole event; and a malformed NDJSON line propagates an exception, leaving that repo to re-request on every refresh. Both low likelihood, but a defensive tryCatch would preserve the old robustness.

Test gaps

The R tests are strong (13 parser cases, server-error retry semantics, boundary-targeted mocks). A few worth adding:

  • The exact crash the issue describes is untested: parseVulnerabilityResponse(character(0)) — the length(contents) == 0L branch the guard comment is about — has no test (only "" is covered). Also whitespace-only inputs (" ", "\n").
  • buildVulnerabilityRequestBody is never asserted directly (the omit_* flags; single-key names round-tripping as a JSON array vs. unboxing to a scalar).
  • Auth-header inclusion in the plan isn't asserted, and the unmocked plan tests implicitly depend on the test runner's real .netrc.
  • Multi-repo plan selection and the C++ coalescing/batching state machine are untested (the latter is an understandable gap absent a test seam).

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

A few things that seem worth a peek

listInstalledPackages reached .rs.ppm.getMetadata -> updateMetadataCache,
which issued a blocking curl::curl_fetch_memory on the R main thread with
no timeout. With the PPM metadata column enabled, a slow or unreachable
PPM froze get_package_state (and IDE startup) just like the vulnerability
path did before it was moved off-thread.

filter/packages returns both vulns and custom metadata in a single
response (has_vulns is only a server-side filter), so fold metadata into
the request already issued asynchronously from C++ rather than running a
second, blocking request:

- drop has_vulns from the request body so every requested package is
  returned, each carrying its vulns array and metadata
- parse the NDJSON once (parsePackageRecords) and fold both vulns and
  metadata into their per-repo caches in recordVulnerabilityResponse
- getMetadata now reads the cache only -- no network access -- and the
  blocking updateMetadataCache is removed
- when the metadata column is enabled and a fetch batch succeeds,
  re-deliver the package list so the column fills in (metadata rides on
  PackageInfo); vulnerabilities still arrive via their own event

Addresses #17807
@kevinushey
kevinushey merged commit d7f274e into rel-golden-wattle Jun 1, 2026
0 of 3 checks passed
@kevinushey
kevinushey deleted the bugfix/17807-async-ppm-vulns-golden-wattle branch June 1, 2026 19:10
kevinushey added a commit that referenced this pull request Jun 2, 2026
… vars (#17822)

* drive ppm vulnerability display off the session repositories, not env vars

Vulnerability badges in the Packages pane are intentionally not opt-in: they
should appear whenever the session is using a Posit Package Manager repository
(a PPM URL in getOption("repos")), including open-source / desktop RStudio. This
was made an explicit decision in 88778df "always try to provide vuln info if
available", which removed an env-var gate that had been applied incidentally.

The async rewrite in #17808 reintroduced that gate, adding isPpmIntegrationEnabled()
early-returns to both refreshVulnerabilitiesAsync() (C++) and
getVulnerabilityRequestPlan() (R). isPpmIntegrationEnabled() requires the
Workbench-injected PWB_PPM_* env vars, so any session that points options(repos)
at PPM by hand (without Workbench PPM integration configured) stopped showing
vulnerability badges entirely.

Remove both gates so enablement is once again driven by repository detection,
keeping the env-var gate only for the Workbench-only metadata column. Add a
cheap PPM-URL pre-filter so installed.packages() is still skipped for non-PPM
sessions, and add comments recording the motivation.

* address review: harden ppm repo url parsing and add coverage

- guard .rs.ppm.fromRepositoryUrl against non-string/NA repo entries so an
  NA in getOption("repos") no longer aborts the now-unconditional vuln plan
- soften the integration-gate comment (the env-var gate also feeds
  ppm_integration_enabled in client session info)
- add tests: mixed PPM/non-PPM repos, installed.packages() skip for non-PPM
  sessions, NA repo tolerance, and direct fromRepositoryUrl coverage
kevinushey added a commit that referenced this pull request Jun 2, 2026
…itories, not env vars (#17823)

* drive ppm vulnerability display off the session repositories, not env vars

Vulnerability badges in the Packages pane are intentionally not opt-in: they
should appear whenever the session is using a Posit Package Manager repository
(a PPM URL in getOption("repos")), including open-source / desktop RStudio. This
was made an explicit decision in 88778df "always try to provide vuln info if
available", which removed an env-var gate that had been applied incidentally.

The async rewrite in #17808 reintroduced that gate, adding isPpmIntegrationEnabled()
early-returns to both refreshVulnerabilitiesAsync() (C++) and
getVulnerabilityRequestPlan() (R). isPpmIntegrationEnabled() requires the
Workbench-injected PWB_PPM_* env vars, so any session that points options(repos)
at PPM by hand (without Workbench PPM integration configured) stopped showing
vulnerability badges entirely.

Remove both gates so enablement is once again driven by repository detection,
keeping the env-var gate only for the Workbench-only metadata column. Add a
cheap PPM-URL pre-filter so installed.packages() is still skipped for non-PPM
sessions, and add comments recording the motivation.

* address review: harden ppm repo url parsing and add coverage

- guard .rs.ppm.fromRepositoryUrl against non-string/NA repo entries so an
  NA in getOption("repos") no longer aborts the now-unconditional vuln plan
- soften the integration-gate comment (the env-var gate also feeds
  ppm_integration_enabled in client session info)
- add tests: mixed PPM/non-PPM repos, installed.packages() skip for non-PPM
  sessions, NA repo tolerance, and direct fromRepositoryUrl coverage

* add NEWS entry for ppm vulnerability badge regression
kevinushey added a commit that referenced this pull request Jun 18, 2026
On project switch/close, the desktop session quits via exitEarly() ->
::exit(), which runs static/global destructors. The server_rpc file-scope
io_context worker thread was launched detached and never stopped, so
~io_context() could run on the main thread while the worker was still
inside run() -- undefined behavior that hangs on Windows (IOCP). This
began affecting ordinary desktop users once the PPM vulnerability fetch
(#17808) started driving async work on that io_context for any session
using a Posit Package Manager repository (#17823).

Retain a joinable handle for the server_rpc worker and stop+join it from
exitEarly(), via a new core::thread::joinOrAbandonThread() helper that
bounds the wait (timed_join) and detaches on timeout, so the exit path can
never trade the teardown hang for an indefinite join hang. The helper
never throws (safe to call from a destructor) and requires callers to
state whether the thread needs interrupting, since io_context workers are
not interruption points and must be released via io_context::stop().

The monitor io_context worker had the same latent race (stopped but never
joined); fix it the same way. Migrate the other duplicated join/log/detach
shutdown tails (OfflineService, ClientEventService, file monitor,
ConsoleInputService, HttpConnectionListener) onto the shared helper; this
also fixes a latent std::terminate in ConsoleInputService's destructor,
which left its thread joinable on a join timeout.

Addresses #18018.
kevinushey added a commit that referenced this pull request Jun 18, 2026
…18021)

* fix windows hang on project switch from unstopped io_context workers

On project switch/close, the desktop session quits via exitEarly() ->
::exit(), which runs static/global destructors. The server_rpc file-scope
io_context worker thread was launched detached and never stopped, so
~io_context() could run on the main thread while the worker was still
inside run() -- undefined behavior that hangs on Windows (IOCP). This
began affecting ordinary desktop users once the PPM vulnerability fetch
(#17808) started driving async work on that io_context for any session
using a Posit Package Manager repository (#17823).

Retain a joinable handle for the server_rpc worker and stop+join it from
exitEarly(), via a new core::thread::joinOrAbandonThread() helper that
bounds the wait (timed_join) and detaches on timeout, so the exit path can
never trade the teardown hang for an indefinite join hang. The helper
never throws (safe to call from a destructor) and requires callers to
state whether the thread needs interrupting, since io_context workers are
not interruption points and must be released via io_context::stop().

The monitor io_context worker had the same latent race (stopped but never
joined); fix it the same way. Migrate the other duplicated join/log/detach
shutdown tails (OfflineService, ClientEventService, file monitor,
ConsoleInputService, HttpConnectionListener) onto the shared helper; this
also fixes a latent std::terminate in ConsoleInputService's destructor,
which left its thread joinable on a join timeout.

Addresses #18018.

* detect ppm repository urls with a trailing slash

.rs.ppm.fromRepositoryUrl matched with a fully-anchored regex ending in
(?<snapshot>[^/]+)$, so a repo URL with a trailing slash (e.g.
".../cran/latest/") did not match and yielded an empty vulnerability
request plan. RStudio's own CRAN-mirror UI normalizes repo URLs with a
trailing slash, so users who configured a PPM repo that way silently got
no vulnerability badges. Tolerate an optional trailing slash in the
detection regex.

Addresses #18018.

* migrate server child-reaper join onto joinOrAbandonThread

ServerMain's shutdown child-reaper thread used a bare timed_join(60s); on
timeout the thread stayed joinable and ~boost::thread would std::terminate.
Route it through core::thread::joinOrAbandonThread so a child that refuses
to die is abandoned (and the existing stuck-process check reports it)
rather than crashing shutdown. The reaper blocks in waitpid(), not an
interruption point, so interrupt is false.

(Win32ChildProcess's pipe-reader timed_joins are intentionally left as-is:
one reader writes an outer stack buffer by reference, so detaching it on
timeout would be a use-after-scope -- it needs a different fix, not this
mechanical migration.)

Addresses #18018.

* leak io_context globals so abandoned-worker exit can't run ~io_context()

* address pr review: unit-test joinOrAbandonThread and minor doc/test fixes
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