Skip to content

don't let a duplicate session launch take over a live session's socket - #18944

Merged
kevinushey merged 5 commits into
mainfrom
bugfix/18941-duplicate-launch-socket
Sep 26, 2026
Merged

kevinushey merged 5 commits into
mainfrom
bugfix/18941-duplicate-launch-socket

Conversation

@kevinushey

@kevinushey kevinushey commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

On RStudio Server, a duplicate launch of a user's session locked the user out: the duplicate unlinked the live session's stream socket before binding its own, aborted on the source-database lock the live session holds (since #18853), and removed the socket it had bound on the way out. The live session was left listening on an unlinked inode, so every recovery launch repeated the abort until the original rsession was killed by hand.

Fixes #18941.

Note: the issue names LocalStreamAsyncServer; the session's listener is actually LocalStreamHttpConnectionListener (HttpConnectionListenerImpl::start() ran cleanup() before binding, and stop() / /rpc/abort ran it again on exit). Same mechanism, different class.

Approach

Session side:

  • Claim the socket first thing. rsessionMain now calls claimSessionStream() right after logging is up, before it touches anything a second process for the same session would share (active-session metadata, project settings, source database). The listener is split into bindEndpoint() (bind and listen now, so connections wait in the backlog) and start() (accept). A duplicate of a running session stops here with a single warning naming the owning process, and exits before writing anything:

    WARNING Not starting: this session is already running in process 55600 [stream=.../rstudio-rsession/kevin-d]
    
  • Bind first, probe on EADDRINUSE (claimLocalStream in LocalStreamSocketUtils.hpp). The path is no longer unlinked up front. If the bind fails with address in use, a non-blocking connect() decides whether a process is listening there: if so, fail with address_in_use and leave the path alone; if not (a socket left by a crashed or killed session), remove it and bind again. Of two processes racing for a missing path, the kernel picks one and the other fails.

  • Only remove what we bound. The listener records the socket's device and inode at bind time, and cleanup() removes the socket and pid file only if the path still leads to that socket, so a supplanted session cannot take its successor's socket with it. The pid file is written after the bind succeeds. stop() runs cleanup before closing the acceptor, so an exiting session unlinks its path while still listening and a successor never sees a refused-but-about-to-release socket.

  • Keep the socket from children. The claimed socket is opened close-on-exec, so a process R starts with system() can't inherit it and, once the session has been killed, keep the path answering the probe as though the session were still running.

  • Release the claim if startup fails. rsessionMain removes the socket and pid file (with the same identity check) on any early return after the claim, so a session that fails to start doesn't leave behind a pid file naming a dead process.

  • waitWithTimeout chains the last error that kept it waiting into its timeout error.

Server side (ServerSessionManager.cpp): the launch that produced the duplicate got through the #18572 dedupe because that guard needs a recorded pid, and the pid is only recorded after the launch function returns. A request for the context ending in that window -- an RPC to the exiting predecessor dying with EOF, or a last-gasp response from it -- erased the fresh pending launch, and the next recovery pass launched again. The entry now carries a launching flag that keeps it through both request errors and successes until the launch function has returned; endLaunching matches on launch time so it cannot clear a newer entry. Custom launchers keep their clear-on-error behavior after that point.

Test runner (rstudio-tests.in): a session no longer takes over a socket another process is listening on, so concurrent test runs (several worktrees, or the rsession and r scopes side by side) each get their own RS_SESSION_TMP_DIR, cleaned up on exit.

The address_in_use check in startHttpConnectionListenerWithTimeout compares against a generic-category code, so it never matches asio's system-category bind error and that retry loop has never run (Error::operator== matches on category name; see #18946). Server sessions no longer reach the loop for the in-use case, and making it match would also switch on retries for TCP sessions that leak a listener per attempt, so it's left for #18946.

Not covered here: two launches claiming the same stale socket at the same instant can still both proceed (the gap between the probe and the rebind is microseconds; closing it needs a lock around the claim: #18962). rserver still can't attribute a request outcome to the process that produced it, which the launching flag and the #18572 guard each cover only in part: #18963. A live session whose socket path vanished for some other reason (nothing answers, so the probe treats it as stale) still needs the "self-detect being supplanted" follow-up noted in #18572.

Automated Tests

  • src/cpp/core/http/LocalStreamSocketUtilsTests.cpp (new): the probe on a missing path, a regular file, a listening socket, and a socket left by a closed listener; identity survives a close and differs after a rebind; claimLocalStream binds a missing path, refuses a live listener with address_in_use and leaves it intact, replaces a stale socket, and opens the socket close-on-exec. The two identity tests hard-link the old socket so its inode stays allocated: Linux hands a freed inode number straight to the next socket (20 of 20 rebinds in a jammy container got the old inode; 0 of 20 with the link), which is what failed Jenkins c++-unit-tests.
  • src/cpp/session/http/SessionLocalStreamHttpConnectionListenerTests.cpp (new): starts real listeners on temp paths; bindEndpoint() claims the stream before start() and refuses a duplicate; a stale socket is replaced; a live one refuses a second listener and is left intact; a supplanted listener leaves its successor's socket and pid file in place on stop; stop tolerates a path that is already gone; releaseEndpoint() removes a stream that was claimed but never started.
  • src/cpp/server/ServerSessionManagerTests.cpp: request outcomes (error and success) raised from inside the launch function no longer clear the pending launch, and a failed launch still clears it.

Ran locally on macOS: rstudio-core-tests (774 passed), rstudio-tests --scope rsession (666 passed), rserver-tests --gtest_filter='SessionManagerTest.*' (9 passed; server code unchanged since).

Manual verification

With npm run rserver-dev for this branch: launched a session through rserver, then started a second rsession with the live session's exact arguments and environment. The duplicate exited with status 1 at once with the warning above; the original process kept its socket and pid file, and proxied requests kept reaching it with no relaunch.

QA Notes

  • Restart R and browser refreshes on RStudio Server, including rapid ones, should never produce the "recovery data is locked" R Session Aborted page.
  • A session killed with SIGKILL (stale socket left behind) should still be replaced by the next launch as before.
  • Desktop is unaffected in practice (each relaunch gets a fresh socket path or follows the previous process's exit), but restart and "Start New Session" flows are worth a pass.
  • Windows sessions listen on TCP and are unaffected; claimSessionStream() is a no-op there.

Documentation

No NEWS entry: the lockout needs the source-database lock from #18853, which hasn't shipped in a release.

Checklist

  • Includes a linked NEWS.md entry (not needed; see Documentation).
  • Local regression tests pass.
  • A reviewer is assigned.

A duplicate rsession launch for the same session unlinked the live
session's stream socket before binding its own, then aborted on the
source-database lock the live session holds (#18853) and removed the
socket it had bound on the way out. The live session was left listening
on an unlinked inode, and every recovery launch repeated the abort, so
the user could not get back in until the original process was killed.

The local stream listener now probes the path before binding and reports
it as in use when a process answers, so the duplicate exits after the
startup retry window instead of supplanting the live session. On exit it
only removes the socket and pid file if they are still the ones it bound
(compared by device and inode), so a supplanted session cannot take its
successor's socket with it either.

rserver could launch the duplicate because a request error landing
between recording a pending launch and learning its pid erased the
entry (the #18572 guard needs a pid); the entry is now kept while the
launch function is in flight. The address_in_use retry comparison in the
session's listener startup never matched asio's system-category error,
and waitWithTimeout now reports the last error that kept it waiting.

Addresses #18941
…rough both request outcomes

Fold in the stronger structure from a parallel take on #18941:

- claimSessionStream() binds the session's local stream first thing in
  rsessionMain, before any state a second process for the same session
  would share; a duplicate exits at once with a warning naming the
  owning process. The listener is split into bindEndpoint() and start().
- claimLocalStream() binds without unlinking and probes only on
  EADDRINUSE, so of two processes racing for a missing path the kernel
  picks the winner. stop() runs cleanup() before closing the acceptor,
  so an exiting session unlinks its path while still listening.
- The rserver pending-launch entry is kept through request successes as
  well as errors while the launch function runs, and endLaunching()
  matches on launch time so it never clears a newer entry.
- rstudio-tests gives each run its own RS_SESSION_TMP_DIR: sessions no
  longer take over a socket another test run is listening on.
- Tests adapted and extended (claimLocalStream, bindEndpoint-before-start).

Addresses #18941
@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
3282 0 190 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 2 0 10 0
✅ desktop-linux 823 0 39 1
✅ desktop-macos 829 0 34 1
✅ desktop-windows 826 0 43 0
✅ server-linux 774 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 b2df0e294ac948e64c335f5692a5d7cabfd07680 - Run #1246

…ease it on failed startup

- Pin the old socket's inode with a hard link in the two identity tests:
  Linux reuses a freed inode number at once, so a rebound socket could
  get the old identity (the Jenkins c++-unit-tests failure).
- Set FD_CLOEXEC on the claimed session socket, so a child that outlives
  a killed session can't make it look alive to the next launch.
- Release the claimed stream (socket + pid file) when rsessionMain returns
  early, i.e. when startup fails after the claim.
- Back out the address_in_use comparison change: server sessions no
  longer reach that retry loop, and enabling it for TCP sessions leaks a
  listener per retry. Left for #18946.
- Drop the NEWS entry: the lockout exists only since #18853 (unreleased).
- Drop bindEndpoint()'s cleanup() call, which is a no-op before a claim.

Addresses #18941.
@kevinushey
kevinushey merged commit c41a08b into main Sep 26, 2026
34 checks passed
@kevinushey
kevinushey deleted the bugfix/18941-duplicate-launch-socket branch September 26, 2026 16:43
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.

duplicate session launch locks the user out: the aborting duplicate removes the live session's socket

1 participant