Skip to content

Coordinate Posit Assistant update/uninstall across concurrent sessions - #18276

Merged
gtritchie merged 32 commits into
mainfrom
bugfix/pai-concurrent-session-locking
Jul 17, 2026
Merged

gtritchie merged 32 commits into
mainfrom
bugfix/pai-concurrent-session-locking

Conversation

@gtritchie

@gtritchie gtritchie commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Posit Assistant is installed per-user at <user data dir>/pai/bin and shared by every rsession the user runs. Update and uninstall previously mutated that directory guarded only by a session-local mutex, stopping only the invoking session's own processes — a concurrent session running the assistant could be left with a corrupted or deleted installation (sharing violations and partially deleted installs on Windows, deleted-working-directory and mixed-version breakage on macOS/Linux, ESTALE failures on NFS-backed Workbench, torn installs when two sessions install at once).

This PR coordinates those operations across the user's sessions.

What changed

New InstallLock helper (src/cpp/session/modules/chat/ChatInstallLock.{hpp,cpp}), built on core::FileLock:

  • Each session holds an "in use" lock (pai/locks/sessions/<id>.lock) while its chat backend and/or NES agent runs from the shared install. These are held OS locks, not marker files: advisory locks (desktop) are released by the kernel the moment a crashed session dies, and link-based locks (server) go stale via the existing PID/heartbeat machinery — so a crashed session cannot cause a persistent false "in use" report.
  • Update and uninstall take a mutation lock (pai/locks/install.lock) and refuse, with a clear retryable message, while any other session's in-use lock is live. Probes fail closed: when lock state cannot be determined, the mutation is refused rather than risked.
  • Starting the backend or agent acquires the in-use lock and then probes for a mutation in progress elsewhere. The acquire-then-probe / probe-after-acquire ordering on the two sides means simultaneous racers each see the other and back off.
  • Lock releases are generation-tokened and happen only from reaped-exit callbacks, so a late exit callback from a force-terminated process cannot release a restarted process's lock; overlapping unreaped generations each pin the lock until all are reaped.

Mutation flow changes (SessionChat.cpp):

  • Update/uninstall take the lock before stopping their own processes (previously an update killed its own backend before the point where it could fail).
  • Both confirm their own processes are actually reaped before touching the installation on disk, aborting with a message on timeout — uninstall previously proceeded with a live process after a timeout.
  • Uninstall now fails instead of reporting success when the ai.prev backup cannot be removed, so an executable tree is never silently left behind.

Agent lifecycle fixes (SessionAssistant.cpp):

  • onError no longer clears tracking state — a stream IO error does not mean the process exited — and instead terminates the process group, letting the reaped exit callback clean up and release the lock.
  • Helper launch environment variables are set with setenv (replacing inherited values) instead of appended, so the helper deterministically observes the paths RStudio resolved.

All refusal messages flow through existing UI channels (install status polling, client_info errors, backend-start error descriptions); there are no GWT changes.

Tests

26 gtest cases in ChatInstallLockTests.cpp cover the token/generation state machine, the two-flag protocol, fail-closed probe paths, stale-lock cleanup, and include two fork-based advisory tests (cross-process conflict, kernel release on holder death, and non-destructive probing).

Known limitations (documented in code)

  • Desktop and server rsessions sharing one home directory use different lock types and cannot see each other's locks reliably — a pre-existing core::FileLock limitation; a uniform type can be forced via the file-locks configuration file.
  • Windows process termination does not cover detached descendants — a pre-existing platform gap shared by every stop path; a surviving descendant holding handles causes the mutation to fail with the existing sharing-violation message rather than corrupting.

Manual verification

Requires multi-session scenarios: one session chatting while another updates or uninstalls (refused with a message); kill -9 of a session mid-chat (locks clear immediately on desktop, within the staleness timeout on server); starting the assistant during a mutation elsewhere (refused, retry succeeds).

Closes #18271, Closes #17365

gtritchie added 26 commits July 16, 2026 16:03
Held-lock in-use markers plus a mutation lock over core::FileLock, with
generation tokens so late exit callbacks cannot release a restarted
process's lock. Addresses #18271.
Backend start holds the session in-use lock and refuses during another
session's mutation; update/uninstall take the mutation lock before
stopping their own processes, confirm reap before touching disk, and
fail uninstall when ai.prev cannot be removed. Addresses #18271.
isLocked() reports false for both a free lock and a failed inspection,
which could delete a live session lock or start a backend mid-mutation.
Also derive the staleness hint from FileLock::getTimeoutInterval() and
add a fork-based advisory-lock test for the desktop path.
A force-terminated backend can still be alive when its replacement
starts; releasing the session lock when the replacement exits would
unlock while the old process lives. Hold the lock until every
outstanding generation is reaped.
startAgent acquires the NesAgent component (and refuses during another
session's mutation); onExit is the sole release point. onError no longer
clears state — a stream IO error does not mean the process exited — and
instead terminates the process group, letting onExit clean up.
An acquire-and-release probe unlinks install.lock on release, opening a
takeover race where two mutators can lock different inodes of the same
path. isLocked never unlinks; its fail-open error mode is covered by the
mutator's fail-closed session probe (the protocol's second flag).
Decide agent locking from the configured source instead of a path lookup
(a mid-swap path can read as missing and reappear), resolve the agent
executable once under the lock, generation-guard agent exit callbacks,
and replace the starter's isLocked probe with a tri-state non-destructive
probe that fails closed on inspection errors.
An override pointing inside pai/bin now takes the in-use lock, and the
pinned path is reused at launch so an override that disappears cannot
silently fall back to the shared install without a lock.
Resolve symlinked overrides before the pai/bin containment check, and
skip override classification when a helper-script branch (which ignores
the override) will launch — a Copilot start must not be refused because
of an unrelated Posit Assistant update.
Lock when the override path itself or its fully-canonicalized target
lies inside pai/bin; canonicalization failure errs toward locking.
A symlinked ancestor of the user-data dir (e.g. /var on macOS) would
otherwise defeat containment; also route boost paths through
utf8ToSystem so non-ASCII override paths survive on Windows.
Classifying whether a dev override resolves inside the managed install
was an unbounded rabbit hole (symlink chains, canonicalization,
platform path semantics). Over-locking is always safe: Posit-type
agents take the lock regardless of override; Copilot and none never
launch from pai/bin and never lock.
A direct Copilot launch honoring RSTUDIO_AGENT_PATH could resolve into
pai/bin; every effective direct-path override now takes the lock.
The helper branches pushed RSTUDIO_AGENT_PATH et al. onto an
environment that may already contain an inherited override, leaving it
unspecified which value the helper observes. setenv replaces.
Apply PR-review findings: the acquire-probe-rollback start protocol moves
into the helper so its TOCTOU ordering is unskippable and testable;
non-contention lock failures now surface their real error instead of
masquerading as an update in progress; the backend locks for everything
but the read-only system install (matching the agent's over-locking
rule); a stale expected-shutdown flag is reset per backend generation;
component storage is a sentinel-sized std::array; tokens are zeroed on
failed acquire; comment rot from review iterations fixed (header probe
description, orphaned performInstall doc, sole-release-point wording,
onError semantics, license header).
acquireInUseForStart now probes with the tri-state directly so an
inspection failure refuses the start (fail closed) with 'unable to
verify' text instead of claiming an update is in progress. Adds twelve
tests: the fail-closed probe paths, the advisory (desktop) starter probe
including its never-unlinks property, the two-sessions-in-use steady
state, MutationScope failure isolation, token-0/wrong-component release
no-ops, non-lock file handling, and the acquireInUseForStart contract;
existing expected-failure assertions now pin the failure identity.
@gtritchie gtritchie added this to the 2026.08 (Yellow Yarrow) milestone Jul 17, 2026
@posit-snyk-bot

posit-snyk-bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

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

Passed Failed Skipped Flaky
1852 0 67 1
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ desktop-linux 465 0 14 0
✅ desktop-macos 469 0 10 0
✅ desktop-windows 468 0 16 1
✅ server-linux 450 0 27 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 eb34f330e543302f60cfd090a54fb32116776144 - Run #250

@kevinushey kevinushey left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Overview

The two-flag protocol looks right to me: sessions hold an OS-level "in use" lock while the backend/agent runs, mutators take install.lock and refuse while another session's in-use lock is live, and the acquire-then-probe ordering on both sides means simultaneous racers each see the other and back off.

I verified the load-bearing assumptions against the codebase, and they all hold:

  • file(GLOB_RECURSE SESSION_TEST_FILES "*Tests.cpp") in src/cpp/session/CMakeLists.txt picks up the new test file automatically.
  • core::system::setenv(Options*, ...) and static FilePath::exists(string) exist as used.
  • Link-based locks stay fresh while held: FileLock::refreshPeriodically is wired on the HTTP listener's io_context (SessionHttpConnectionListenerImpl.hpp), so a server session's held in-use lock won't go stale mid-chat.
  • Both process lifecycles set callbacksRequireMainThread = true, so the class's "main thread only, no internal locking" contract is sound, including during the event-pumping wait loops (re-entrant starts during a mutation are correctly refused via mutationActive_).
  • The generation-staleness design is safe for the backend: startChatBackend early-returns when s_chatBackendPid != -1, so the generation only advances when tracking state is already cleared; a stale-generation onExit skips only already-cleared state while still releasing its token.
  • helperBranchSelected in the new startAgent code exactly mirrors the real launch-branch conditions (isEmpty() selection, exists() inside), and the resolvedAgentPath chain reproduces assistantLanguageServerPath's override-first ordering for the direct-launch branch.
  • Error::operator== compares code + category only, so the operation_in_progress contention comparison in acquireInUseForStart works as intended.
  • The systemInstall comparison in startChatBackend is lexically identical to how locatePositAssistantInstallation builds the system path, so == is safe there; an RSTUDIO_POSIT_AI_PATH override compares unequal and over-locks, which is the safe direction.

The TOCTOU reasoning, the fail-closed probe paths, the non-destructive tri-state probeLock (avoiding the advisory unlink-on-release takeover race), and the own-file-skip to dodge the POSIX fcntl self-probe hazard all check out as far as I can trace them. This is careful work.

Issues and questions (none blocking)

  1. Behavior change: RSTUDIO_AGENT_PATH is now ignored in helper-script mode (SessionAssistant.cpp, both helper branches). Previously the resolved path was push_back'd after the inherited environment, and since getenv in the child returns the first match, an inherited dev override typically won. With setenv replacing it, the helper now always gets the RStudio-resolved path. Fixing the nondeterminism is defensible, but this does remove a dev workflow (overriding the agent while a helper is configured, i.e., all Workbench deployments). Worth confirming this is intended rather than collateral.

  2. updateInProgressElsewhere() has no production call sites — only tests exercise it; the start-side path uses probeLock directly inside acquireInUseForStart. If it exists for the pro repo, fine; otherwise it's shipping a dead public API whose fail-closed semantics could drift from the real path.

  3. onStarted is not generation-guarded (SessionAssistant.cpp). A late onStarted from a superseded agent process can stomp s_agentPid with a dead PID, and the corresponding stale-generation onExit now deliberately skips clearing it. This self-heals (a new startAgent is gated on runtime status, not PID, and onStarted for the replacement overwrites it), and the stomp predates this PR — but the generation machinery makes the window slightly more observable. A one-line generation guard on onStarted would close it cheaply.

  4. Server hard-crash + fast restart of the same session leaves the session's own link-based in-use lock live for up to the staleness timeout, and acquireInUseForStart reports that as "A Posit Assistant update is in progress." The code comment acknowledges this; the message is mildly misleading for that case but retryable. Acceptable, just noting the UX.

  5. Uninstall now hard-fails when ai.prev can't be removed — on Windows an AV scanner or indexer briefly holding a handle turns a previously "successful" uninstall into an error with "restart RStudio and try again." The rationale (never silently leave an executable tree behind) is sound and the message is actionable, but expect some support noise from this.

  6. The mutation lock is held across the entire network download in performInstall, so other sessions are refused assistant starts for the full download duration. The refusal message is accurate and retryable, and locking only around the directory swap would reopen the race the PR closes, so this seems like the right trade-off — just noting it.

Code quality and tests

  • Style matches the codebase (3-space indent, Allman braces, *LOGF macros, chat-module layout). Comment density is high but earns its keep — nearly every comment states a constraint (fcntl self-probe release, inode takeover race, fail-closed rationale) rather than restating code.
  • NEWS.md entry is present, correctly formatted, and in the right section.
  • Test coverage is genuinely strong: the token/generation state machine, zero-token and wrong-component no-ops, overlapping unreaped generations, nested MutationScope non-release, fail-closed on uninspectable locks (both sides), non-destructive probing, and two fork-based tests proving kernel release on holder death. The POSIX-only guard is well justified, and the pipe-synchronized fork tests are correctly constructed (_exit, no gtest assertions in the child beyond the status byte).
  • Security: lock files live under the user's own data dir; malicious/garbage entries in the locks dir are handled fail-closed (tested with a planted directory); owner IDs come from session IDs or UUIDs, so no path-injection surface.
  • Performance: one file-lock acquisition per backend/agent start and a directory scan per mutation — negligible; lock refresh rides the existing timer.

Verdict

LGTM. The concurrency design is unusually well-reasoned and well-tested for this kind of change. Items 1 and 2 are the only ones I'd want answered before merge (intended behavior change? dead API?); 3–6 are notes/follow-ups, not blockers.

@gtritchie
gtritchie merged commit bbcd65b into main Jul 17, 2026
1 of 2 checks passed
@gtritchie
gtritchie deleted the bugfix/pai-concurrent-session-locking branch July 17, 2026 20:55
gtritchie added a commit that referenced this pull request Sep 24, 2026
Installs now publish a new version slot and never modify a directory
another session could be running from, so the lock from #18276 no longer
protects anything. Delete ChatInstallLock and its tests, the installLock()
accessor, the MutationScope around performInstall(), and the in-use
acquire/release around the chat backend and agent starts. The e2e seed no
longer skips a locks/ directory.

The two non-locking #18276 fixes in SessionAssistant.cpp stay: onError
does not clear agent tracking state, and the helper environment is set
with setenv rather than appended.

Addresses #18658.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants