Skip to content

fix windows hang on project switch from unstopped io_context workers - #18021

Merged
kevinushey merged 5 commits into
rel-blue-plumbagofrom
bugfix/ppm-io-context-exit-hang
Jun 18, 2026
Merged

kevinushey merged 5 commits into
rel-blue-plumbagofrom
bugfix/ppm-io-context-exit-hang

Conversation

@kevinushey

@kevinushey kevinushey commented Jun 18, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

RStudio Desktop on Windows hangs indefinitely when switching projects, closing a project, or opening a project from "no project". Reproduces on 2026.05.1+225 ("Golden Wattle"), not on 2026.05.0+218.

Root cause

server_rpc's vulnerability/RPC io_context worker thread (SessionServerRpc.cpp) is a file-scope global, launched detached behind a perpetual make_work_guard, and was never stopped. On project switch/close the desktop session quits via exitEarly() -> ::exit(), which runs static/global destructors. So ~io_context() runs on the main thread while the detached worker is still inside run() -- undefined behavior that characteristically hangs on the Windows IOCP backend.

This started hitting ordinary desktop users because of two commits between +218 and +225:

Fix

The hang:

  • Retain a joinable handle for the server_rpc worker and stop() + join it from exitEarly().
  • Add a core::thread::joinOrAbandonThread() helper that performs the bounded shutdown join: optional interrupt, timed_join, and detach() on timeout so the exit path never trades the teardown hang for an indefinite join hang. It never throws (safe from a destructor), and requires callers to state whether the thread needs interrupting (io_context workers are not interruption points and must be released via io_context::stop()).
  • Fix the same latent race in the monitor io_context worker (it was stop()'d but never joined).
  • Migrate the other duplicated bounded-join shutdown tails onto the helper: OfflineService, ClientEventService, file monitor, ConsoleInputService, HttpConnectionListener, and the rserver child-reaper in ServerMain. This also fixes latent std::terminates where a join timeout left a thread joinable (ConsoleInputService's destructor; the rserver reaper). Win32ChildProcess's pipe-reader timed_joins are intentionally left as-is -- one reader writes an outer stack buffer by reference, so detaching on timeout would be a use-after-scope and needs a different fix.

Related defect found during investigation (trailing-slash detection):

  • .rs.ppm.fromRepositoryUrl matched with a fully-anchored regex ending in (?<snapshot>[^/]+)$, so a PPM repo URL with a trailing slash (e.g. .../cran/latest/) did not match. RStudio's own CRAN-mirror UI normalizes repo URLs with a trailing slash, so users who configured a PPM repo that way silently received no vulnerability badges -- the feature [Golden Wattle] drive ppm vulnerability display off the session repositories, not env vars #17823 was meant to deliver to desktop. The detection regex now tolerates an optional trailing slash.

Testing

  • Verified all affected C++ translation units compile.
  • rstudio-tests --scope r --filter ppm passes, including a new fromRepositoryUrl case covering the trailing-slash form.
  • The hang itself is a Windows-only shutdown race that requires a PPM repo (without a trailing slash) active at session start; manual verification on Windows is recommended.

Addresses #18018.

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.
.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.
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.
@kevinushey
kevinushey force-pushed the bugfix/ppm-io-context-exit-hang branch from 1706513 to b509132 Compare June 18, 2026 21:41
@kevinushey
kevinushey changed the base branch from main to rel-blue-plumbago June 18, 2026 21:41
@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Important

  1. src/cpp/tests/testthat/test-ppm.R:505 — the test comment attributes the trailing-slash /
    vulnerability-badge defect to rstudio#18018, but that issue is exclusively the Windows hang
    (its body never mentions badges or trailing slashes); SessionServerRpc.cpp:137 already uses
    IDE hangs while switching projects #18018 correctly for the hang. Fix: drop the (rstudio#18018) citation here, or point it at the
    trailing-slash defect's own issue if one is filed.

  2. src/cpp/core/Thread.cpp:64 — joinOrAbandonThread has no unit test, yet its contract is pure
    and deterministic: no-op-returns-true on a non-joinable handle, join-success returns true,
    timeout bounds the wait and detaches (returns false), and the interrupt path. A regression that
    inverts the return, drops the detach(), or breaks the timeout bound would ship silently. Add a
    test covering these paths. Trap: name it ThreadTests.cpp — the existing
    Thread_ThreadsafeQueue_gtests.cpp is never compiled, because the *Tests.cpp glob at
    src/cpp/core/CMakeLists.txt:357 does not match the _gtests.cpp suffix.

Suggestions

  1. src/cpp/core/Thread.cpp:64 — joinOrAbandonThread returns bool (joined vs. abandoned), but
    all 8 callers discard it and nothing warns (it isn't [[nodiscard]]). Either make it void, or
    mark it [[nodiscard]] so each discard is a deliberate, visible cast.

  2. src/cpp/session/SessionMain.cpp:1765 — server_rpc::stop() is wired only into exitEarly(),
    while stopMonitorWorkerThread() is additionally guarded by a BOOST_SCOPE_EXIT covering
    normal return-from-main paths. If main returns normally after the RPC worker has started,
    s_ioContext is destroyed while the worker may still be in run() — the same UB this PR fixes.
    Latent gap, not a live bug. Mirror the monitor's scope guard (or add server_rpc::stop() to the
    rCleanup shutdown tail).

  3. src/cpp/tests/testthat/test-ppm.R:501 — the new /? applies to every URL shape, but only the
    bare .../latest/ form is tested. Add a binary+platform+trailing-slash case
    (.../__linux__/jammy/2024-01-01/) and an expect_false(nzchar(slash[["binary"]])) assertion to
    match the sibling test's convention.

  4. src/cpp/core/Thread.cpp:96 — the empty inner catch(...) around the fallback detach() needs
    a one-line inline comment documenting the exemption (the project forbids empty catches; a
    throwing detach() here is unrecoverable mid-teardown).

  5. src/cpp/session/SessionModuleContext.cpp:138 — the migration changes the ConsoleInputService
    shutdown join from timed_join(1) (the bare int is interpreted by boost as 1 nanosecond) to
    seconds(1). This is intentional and more correct (and fixes a latent std::terminate), but is
    a real behavior change; consider an inline note so seconds(1) isn't misread as preserving the
    old 1.

  6. src/cpp/session/SessionServerRpc.cpp:137 — comment says the UB "hangs on Windows" while the
    parallel comment at SessionMain.cpp:2023 says it "can hang on Windows"; since the behavior is
    undefined, align both on "can hang".

  7. src/cpp/server/ServerMain.cpp:513 — pre-existing, low priority: now that the child reaper is
    detached on timeout (rather than terminating), line 521's WNOHANG waitpid on the main thread
    races the still-running detached reaper over the same child set. Only reachable in the degenerate
    "children won't die for 60s" path.

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

Feedback posted

@github-actions

github-actions Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

🍎 macOS Desktop E2E · ARM64

✅ All tests passed!

████████████████████ 100% pass rate

✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
387 0 11 1
📥 Download Playwright report

⬇️ playwright-report.zip — extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


2 shards · macos-26 ARM64 · commit 0c14a79ed5cf99a0a7e142b8de6dba0ab94fa68e · Run #108

@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough pass. Addressed in 0c14a79, with notes on the rest:

#4 (server_rpc::stop only in exitEarly) is already resolved by 7af835f5 ("leak io_context globals"), which landed shortly after this review. Both s_ioContext and s_monitorIoContext are now intentionally-leaked heap globals (*new io_context(), never freed), so ~io_context() runs on no exit path -- including a normal return from main. If stop() is skipped, the worst case is a detached worker the OS reclaims at process exit (well-defined), so the exitEarly/BOOST_SCOPE_EXIT asymmetry is no longer a UB risk. Happy to add server_rpc::stop() to a scope guard anyway for prompt-cleanup symmetry if you'd prefer.

#1, #6 done: reworded the test comment so the trailing-slash defect reads as "found while investigating #18018" rather than being #18018, and documented why the inner fallback catch(...) is intentionally empty.

#2 done: added ThreadTests.cpp covering the no-op / join / timeout-detach / interrupt paths -- named *Tests.cpp so the core glob compiles it (good catch on _gtests.cpp).

#5 done: added a binary+platform+trailing-slash case.

#7 done: added an inline note that seconds(1) is a deliberate 1-second bound replacing the prior bare timed_join(1) (1 ns).

#3 considered but left as-is: the new tests consume the bool, so collapsing to void is out, and [[nodiscard]] would require (void) casts at every shutdown-path caller (and risks breaking a -Werror build if any caller is missed) for marginal benefit on a best-effort teardown helper. Happy to revisit if you feel strongly.

#8 appears moot post-7af835f5: that commit rewrote both comments to consistently describe "a documented Windows-IOCP hang" / "teardown hang" -- the earlier "hangs" vs "can hang" split is gone.

#9 pre-existing and out of scope for this PR.

@jeffvroom jeffvroom left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@kevinushey
kevinushey merged commit f467e78 into rel-blue-plumbago Jun 18, 2026
11 checks passed
@kevinushey
kevinushey deleted the bugfix/ppm-io-context-exit-hang branch June 18, 2026 23:02
kevinushey added a commit that referenced this pull request Jun 18, 2026
Document the #18018 fixes (Windows project-switch hang and trailing-slash
PPM repository URL detection) in the Blue Plumbago NEWS file. The code
changes themselves land on rel-blue-plumbago in #18021.

Addresses #18018.
@github-actions

Copy link
Copy Markdown

🪟 Windows Desktop E2E · Server 2025 x64

✅ All tests passed!

████████████████████ 100% pass rate

✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
384 0 16 1
📥 Download Playwright report

⬇️ playwright-report.zip — extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


2 shards · Windows Server 2025 x64 · commit 0c14a79ed5cf99a0a7e142b8de6dba0ab94fa68e · Run #108

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.

3 participants