Repository navigation
Coordinate Posit Assistant update/uninstall across concurrent sessions - #18276
Conversation
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.
✅ 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. |
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
There was a problem hiding this comment.
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")insrc/cpp/session/CMakeLists.txtpicks up the new test file automatically.core::system::setenv(Options*, ...)and staticFilePath::exists(string)exist as used.- Link-based locks stay fresh while held:
FileLock::refreshPeriodicallyis 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 viamutationActive_). - The generation-staleness design is safe for the backend:
startChatBackendearly-returns whens_chatBackendPid != -1, so the generation only advances when tracking state is already cleared; a stale-generationonExitskips only already-cleared state while still releasing its token. helperBranchSelectedin the newstartAgentcode exactly mirrors the real launch-branch conditions (isEmpty()selection,exists()inside), and theresolvedAgentPathchain reproducesassistantLanguageServerPath's override-first ordering for the direct-launch branch.Error::operator==compares code + category only, so theoperation_in_progresscontention comparison inacquireInUseForStartworks as intended.- The
systemInstallcomparison instartChatBackendis lexically identical to howlocatePositAssistantInstallationbuilds the system path, so==is safe there; anRSTUDIO_POSIT_AI_PATHoverride 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)
-
Behavior change:
RSTUDIO_AGENT_PATHis now ignored in helper-script mode (SessionAssistant.cpp, both helper branches). Previously the resolved path waspush_back'd after the inherited environment, and sincegetenvin the child returns the first match, an inherited dev override typically won. Withsetenvreplacing 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. -
updateInProgressElsewhere()has no production call sites — only tests exercise it; the start-side path usesprobeLockdirectly insideacquireInUseForStart. 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. -
onStartedis not generation-guarded (SessionAssistant.cpp). A lateonStartedfrom a superseded agent process can stomps_agentPidwith a dead PID, and the corresponding stale-generationonExitnow deliberately skips clearing it. This self-heals (a newstartAgentis gated on runtime status, not PID, andonStartedfor 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 ononStartedwould close it cheaply. -
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
acquireInUseForStartreports 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. -
Uninstall now hard-fails when
ai.prevcan'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. -
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,
*LOGFmacros, 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
MutationScopenon-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.
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.
Posit Assistant is installed per-user at
<user data dir>/pai/binand 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
InstallLockhelper (src/cpp/session/modules/chat/ChatInstallLock.{hpp,cpp}), built oncore::FileLock: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.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.Mutation flow changes (
SessionChat.cpp):ai.prevbackup cannot be removed, so an executable tree is never silently left behind.Agent lifecycle fixes (
SessionAssistant.cpp):onErrorno 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.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.cppcover 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)
core::FileLocklimitation; a uniform type can be forced via thefile-locksconfiguration file.Manual verification
Requires multi-session scenarios: one session chatting while another updates or uninstalls (refused with a message);
kill -9of 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