Repository navigation
Description
Problem
Posit Assistant installs to a single shared directory per source, which every session using that source runs from. Because there is one directory, updating it mutates something other sessions may be executing from.
For the user's own install (<userDataDir>/pai/bin), #18276 addressed the resulting corruption with cross-session file locks, but the coordination is a refusal: an update fails while another session is running the assistant, and the user is told to close their other RStudio instances.
The administrator's install (<systemConfigDir>/pai/bin) has the same problem with no coordination at all. RStudio never writes there, but that does not make the directory immutable -- the package manager replaces it, and it does so while sessions are running. An in-place replace does not merely risk corruption:
- Client assets are read from the installation on every request (
servedInstallationPath()inChatStaticFiles.cpp). Since Serve Posit Assistant chat assets from the installation the backend runs #18832 the session pins the installation it serves, but the pin is a path, not bytes: content-hashed chunks are fetched from disk long after the pane loaded, and replacing the tree under the pinned path makes the loaded page ask for filenames that no longer exist. - The Content-Security-Policy is rebuilt when the pinned installation changes or the backend starts (Read the chat pane Content-Security-Policy from the installation being served #18833). A third party replacing the directory in place triggers neither, so a new client is served under the old package's policy.
- The backend keeps the files it has already opened, but anything it imports later comes from the new tree.
So an administrator rolling out a new version has to get every user out of the assistant first, which means draining or restarting sessions across the deployment. That is the cost this issue exists to remove, and today it falls on the party least able to accept it.
The single directory has a second consequence. It maps a protocol version to exactly one package version, and RStudio's supported protocol is compiled in (kProtocolVersion, currently 11.0). Two RStudio releases on different protocols sharing a home compete for the one install: the older sees the newer package as a protocol mismatch, computes its own protocol's package as an available install, and prompts to replace it -- after which the newer prompts to replace it back.
Proposal
Install each package version into its own directory ("slot"), append-only: slots are created, never modified or deleted. Because no operation touches a directory another session could be executing from, the corruption #18276 coordinated against becomes unrepresentable, and no cross-session locking is needed at all.
<userDataDir>/pai/ <systemConfigDir>/pai/
├── versions/1.1.0/ ├── versions/1.1.0/ # slots and selector
├── versions/1.1.0-2/ ├── versions/1.0.4/ # both written by the
├── versions/1.0.4/ ├── selected.json # administrator,
├── selected.json │ # never by RStudio
├── manifest-check.json └── bin/ # legacy; still read
└── bin/ # legacy; never read, written, or deleted
The storage root stays pai/; only the backend's working directory (today pai/bin) becomes the slot.
Slots. The first install of a version gets the plain name (1.1.0); a fresh slot for the same version appends an ordinal (1.1.0-2). Names carry no version or protocol identity -- 1.1.0-2 is valid semver that sorts before 1.1.0, and SemanticVersion::parse rejects it outright -- so both always come from package.json and protocol.json inside the slot. The one thing read from a name is the reinstall ordinal, and only to order slots whose package.json versions are equal (slotOrdinal() in ChatSelector.cpp; a name not derived from the version scores 0). A slot name must never be passed to the version parser or reported as a version.
Selector. selected.json holds {"selected": {"11.0": "1.1.0-2", "10.0": "0.4.8"}} -- slot names keyed by protocol, so RStudio releases on different protocols no longer compete. It is advisory: if the named slot is missing, fails verification, or declares a different protocol, resolution falls back to the newest verifying slot for the protocol, ties broken by the later reinstall ordinal, then by name as a last resort so the answer is stable. Written temp-then-rename; concurrent writers are last-writer-wins, and a dropped entry self-heals through the same fallback.
In the user's directory the fallback also repairs the entry. The administrator's directory carries the same selected.json, in the same format and with the same meaning, but RStudio never writes there: the administrator's tooling records the selection when it installs a version (a separate work item), and a system selector naming a missing or unverifying slot resolves through the fallback without being rewritten. selector::resolveSlot() as merged in #18666 always repairs, so it needs a read-only mode (or a sibling) for the system tier; today's best-effort write would fail and warn on every resolve against a read-only /etc/rstudio.
Resolution
#18774 established the rule and it does not change here: the sources contribute candidates that race by what they declare -- protocol-compatible first, then highest version, ties in source order (user, system, bundled) -- and posit-assistant-path sits outside the race, used outright when it verifies and ending the read-only search when it does not. userInstallWouldBeSelected() keeps gating the update offer. What each source contributes is what changes:
- User (
pai/versions, the only writable source): the slotselected.jsonnames forkProtocolVersion, or the fallback above. One candidate, so a manifest that serves a lower version for this protocol (isVersionDowngrade) still decides what runs. Skipped entirely whenuserInstallEnabledis false (Add a setting to disable user-managed Posit Assistant installs #18691). Because the selector is keyed by protocol, this source never contributes an incompatible slot: after an RStudio upgrade to a new protocol the user tier reads as not installed and the update check takes the initial-install path (fetching immediately, sinceshouldFetchManifest()never throttles when nothing is installed). The protocol-mismatch messaging (hasProtocolMismatch(),unsupportedProtocol) stays reachable only through the read-only sources. - System (
<systemConfigDir>/pai/versions): the slot the administrator'sselected.jsonnames, or the same fallback, resolved but not rewritten. This is how an administrator chooses which installed version a deployment runs -- including holding users on an older slot while a newer one sits beside it -- without RStudio writing to a directory it does not own. - System legacy (
<systemConfigDir>/pai/bin): one unversioned candidate, as today. It is what deployments have today and RStudio does not own it. Until the admin's package adoptsversions/, an in-place replace keeps breaking live sessions exactly as it does now -- that is the migration cost, and it is the package's to pay. - Bundled: a single directory beside the session binary, unchanged.
posit-assistant-path stays an unversioned single installation directory ("the directory containing the installation's dist directory", as the option documents it). An administrator who wants side-by-side uses <systemConfigDir>/pai/versions; teaching the option to accept a versions/ root as well is deferred.
The user's legacy pai/bin is never read, written, or deleted. Older RStudio releases still mutate it, unaware of the versioned layout, so reading it would re-import the problem this issue removes, and copying it into a slot would record a manifest of whatever another release had left there. A versioned-aware release does a fresh install into pai/versions/. The user-visible consequence: on first launch of the versioned-aware release, a user with a working pai/bin is prompted to install (initial-install wording, ~18 MB download) once; the old copy keeps serving any older RStudio release that shares the home.
The bundled copy stays a single directory. Only the Workbench package produces one (bundledPositAssistantInstallPath() derives it from resourcePath(); nothing in this repository installs it), and replacing it means replacing the session binaries beside it, which takes that node's sessions down. Its lifecycle is the RStudio install's -- one RStudio version ships one bundled assistant -- so versioning it would imply an independence it does not have.
Resolve once per session. A session resolves the installation once, lazily on first need, and every consumer reads that one answer: the backend start (startChatBackend()), the agent start (paiLanguageServerPath() in SessionAssistant.cpp), the asset handler and its CSP (today's staticfiles::setInstallationPath() pin, which becomes a reader of the shared resolution rather than a second pin), and installed-version and protocol reporting (getInstalledVersion(), getInstalledProtocolVersion(), chat_verify_installed, chat_get_backend_status). The pinned path is re-validated with the cheap existence check on each read, as servedInstallationPath() does today, so a slot removed out of band falls back to a fresh resolution. It is cleared by exactly one thing: this session's own successful install, so the components it restarts come back on the new slot. An install elsewhere -- another session, an administrator -- takes effect at this session's next start. The update check compares the manifest against the pinned version, so a session still running an older slot after another session installed a newer one is offered the update, and accepting it skips the download (below) and just re-selects.
Install
Download -> verify SHA-256 -> extract to a staging directory under pai/versions/ -> check the extracted package's identity -> allocateSlot() (write the slot manifest, verify, rename into place) -> update the selector -> stop and restart the backend and agent. Staging and final slot are siblings so the rename is atomic. The manifest is written before verification because verification includes checking it.
The identity check compares the extracted package.json version and protocol.json protocol against the manifest entry that was downloaded. A mis-published package would otherwise publish under another protocol's selector entry -- changing what a different RStudio release resolves -- and report an update this session cannot run. A package without protocol.json fails this check and is refused; writeProtocolVersionFileIfMissing(), which backfilled RStudio's compiled-in protocol into pai/bin, is deleted rather than carried into the staging step.
If the target version already exists in a verifying slot that declares the same version and protocol, skip the download and just update the selector. Concurrent installs of the same version race on the rename: the loser adopts the now-existing target when it verifies and declares the same version and protocol (SlotPolicy::AdoptExisting), otherwise bumps the suffix and renames again -- a directory's name is never taken as evidence of what it holds. The ai.prev backup and every restore branch in installPackage() are deleted: a slot only reaches its final name after verification, so a torn install cannot exist under a final name. The Windows access-denied message ("close all other instances of RStudio and try again") goes with them; it described a directory swap losing to another session's open handles, which no longer happens.
Staging directories are unique per install (.tmp-<host>-<pid>-<nonce>) and are never cleared. Two sessions sharing an NFS home can compute the same pid-based name -- under container runtimes they routinely do, each session pod having its own PID namespace -- and clearing that name would delete another session's half-extracted tree. The victim would then record a manifest describing the damage, verify it against itself, and publish a truncated slot that keeps verifying for the rest of its life.
Because nothing on disk is mutated, the backend and agent are stopped after the install succeeds rather than before it. Stopping is only about picking up the new version, so a failed install leaves a working assistant running, and the reap-wait (waitForOwnComponentsReaped()) with its "a process is still shutting down" failure path in performInstall() goes away.
Verification
Today's check (verifyPositAiInstallation()) only tests that three paths exist; a zero-byte main.js passes. Slot verification (slots::verifySlot(), merged) is: the expected paths exist and are non-empty, package.json parses with a version, protocol.json parses with a protocol, and every file in the slot's manifest exists with its recorded size. The manifest (relative path -> size, plus SHA-256s recorded for future use but not routinely checked) is written after extraction, when the tree is known to match the verified zip. A slot with no manifest does not verify: every published slot has one, so its absence means no install ran to completion there. The stat walk is milliseconds even on NFS homes. What escapes detection is correct-size garbage -- which is what Reinstall is for.
Unversioned sources (posit-assistant-path, the administrator's legacy directory, the bundled copy) carry no manifest and are not named for a version, so they get the paths-exist-and-are-non-empty check and nothing more. What they declare is reported downstream to the update check rather than gating them here. verifyPositAiInstallation() and the package.json/protocol.json readers in ChatInstallation.cpp are replaced by that check and the slot readers -- including at their callers in bundledPositAssistantInstallPath() and servedInstallationPath() -- so two definitions of "valid install" never coexist.
Reinstall
When the manual check (Check for Posit Assistant Updates) finds installed and available versions equal, the result dialog offers Reinstall instead of only reporting nothing to do. The startup check is unchanged. It is the ordinary install path with two changes: the skip-if-verifies shortcut is bypassed, and it never adopts an existing slot -- SlotPolicy::AlwaysFresh, so on a rename collision it always bumps the suffix and the user provably gets fresh bits. The old slot is left in place (another session may be running from it) and stops being selected. This is the in-product recovery for corruption that passes verification, and it deletes nothing, so it needs no locking.
Surface: the update state keeps the manifest's download URL and SHA-256 for the current protocol even when no update is available, chat_install_update takes a reinstall flag that bypasses the "No update available" guard, and the presenter's onNoUpdateAvailable path becomes a dialog with a Reinstall button (en and fr strings; _fr.properties is hand-maintained). Managed mode refuses it the way it refuses install and update.
Uninstall is removed
The uninstallPositAssistant command and the chat_uninstall_posit_assistant RPC go away, with their menu entry, Commands.java stub, en/fr strings, presenter handling, the PaneManager carve-out that keeps the command visible, the uninstall-posit-ai.test.ts Playwright test, and the "Removing Posit Assistant" section of docs/user/rstudio/ide/guide/tools/posit-ai.qmd. That section is replaced, not just deleted: the same PR documents how to remove every Posit Assistant installation by hand, with RStudio closed -- the user data pai/ directory on each platform (~/.local/share/rstudio/pai, ~/Library/Application Support/rstudio/pai where applicable, %LOCALAPPDATA%\rstudio\pai), noting that it holds versions/, selected.json, the legacy bin/, and the assistant's own storage, and that the administrator's copy under <systemConfigDir>/pai and the copy bundled with RStudio are not the user's to remove. Detectable corruption self-heals via the selector fallback, undetectable corruption is handled by Reinstall, and removing the assistant from disk has no in-product path until the manage-installs work below. #18662 did this once and #18679 reverted it; since then #18691 (managed-mode refusal), #18815 (bundled-vs-system refusal wording) and #18832 (unpinning the served installation) have all changed the handler, so this is a re-implementation against current main, with #18662 as the checklist of what to touch.
Locking is removed
ChatInstallLock.{hpp,cpp} and its tests (~1,700 lines) are deleted, along with the installLock() accessor in SessionChat.hpp, the MutationScope call site in performInstall(), the in-use acquire/release around the backend start in SessionChat.cpp and the agent start in SessionAssistant.cpp (three call sites each), and the #18790 owner-id fix that lives inside the lock. Every mutation is create-only into a directory nothing can be using, so the rename is the only arbiter concurrent writers need. Two fixes from #18276 that are not about locking must survive, both in SessionAssistant.cpp: the onError handling that no longer clears agent tracking state on a stream error, and the setenv (replace, not append) helper launch environment.
Deferred
- Managing installs. Slots accumulate (~18 MB each) and install reclaims nothing, so
.tmp-*directories from interrupted installs, superseded slots and corrupt slots remain until a future effort covering retention, deletion of unused slots, and removing the assistant entirely. That work needs a per-slot "in use" signal (a slot can be running-but-unselected), which is where a successor to the Coordinate Posit Assistant update/uninstall across concurrent sessions #18276 lock machinery would return. Until then there is no in-product way to reclaim the disk. - System-tier retention. An ordinary package upgrade removes the version it replaces, so side-by-side requires the administrator's tooling to keep N versions instead. Pruning them safely needs the same in-use signal, so that side has to decide retention explicitly rather than inherit the default of removing what it replaces. Read support here does not depend on it: a system directory holding one slot behaves like today's single install.
posit-assistant-pathas a versions root. The option keeps naming one unversioned installation. Accepting a directory holdingversions/andselected.jsonwould give a pinned shared-mount deployment side-by-side too; small once the system source exists, but not needed for the first release.- Slot blacklisting on runtime failure. The strongest corruption detector is the backend repeatedly failing to launch from a slot, but a backend can die for reasons that are not corruption, and wrongly blacklisting a good slot is worse. Reinstall covers the need manually.
Decisions and assumptions
- Downgrade to a user-chosen version is out of scope. The layout permits it and the selector is the hard part, so a picker can be added later without rework.
- Lost-selection downgrade is accepted, not made durable.
selectSlot()is an unserialized read-modify-write, so two sessions recording different protocols at once can drop an entry, and the repair converges on the newest verifying slot, not on what the entry said. WithisVersionDowngradewired to slots, a lost entry can resolve up to a newer slot the same protocol already accepted. It needs two sessions on different protocols installing in the same instant, and the next update check re-selects the manifest's version with no download. Making it durable would mean serializing the selector write (locking, which this effort exists to remove) or recording intent inside the slot (retention policy, deferred). - After an RStudio protocol bump the user tier reads as not installed (Resolution, source 1). The alternative -- surfacing the old slot as an incompatible candidate -- would keep the "update required" wording for one release at the cost of re-introducing the two-releases-compete loop the selector exists to end.
- Existing users re-download once (Resolution, legacy
pai/bin). - Concurrent mixed-version access to the shared store is assumed safe. Side-by-side installs mean sessions can run different assistant versions against the same
pai/storage -- by user action today, and as an operational certainty once Workbench bundles the assistant (rstudio/rstudio-pro#12483), where a rolling cluster upgrade briefly runs different bundled versions against one NFS-shared home. Posit Assistant is expected to tolerate this.
Implementation sequence
State today (2026-09-21): the slot machinery landed inert in #18666 (ChatSlots, ChatSlotManifest, ChatSelector; nothing calls them). The uninstall removal landed (#18662) and was reverted (#18679). The wiring PR #18673 was closed unmerged; its branch feature/pai-versioned-installs-wire is four commits on a 2026-08-28 base, and the resolver, static-file handler and CSP code it rewrote have since been rewritten again by #18691, #18815, #18832 and #18833. Treat the branch as a reference for shape (three self-contained source functions, the identity check, e2e/rstudio/fixtures/pai-seed.ts), not as something to rebase.
- Remove uninstall -- re-implemented against
main(see above), including the user-guide section on manual removal that replaces the command. No dependency on the new layout; every later PR gets smaller once it is gone. NEWS entry: this removes a shipped command and should point at the manual-removal documentation. - Slot machinery -- done in Add slot, manifest and selector machinery for versioned Posit AI installs #18666. Two changes land with PR 3: the read-only resolve for the system tier (Selector, above), and removing the prerelease and build-metadata handling from
preferredOver()inChatSelector.cpp(releasePortion(),hasPrerelease(), and the four tests that pin them). Posit Assistant versions are plainx.y.zand every other parser site rejects a suffixed version, so the selector must not be the one place that accepts one. What remains is: parse version, compare, then ordinal, then name. A re-review of the merged code (2026-09-21) found three more small items to take at the same time, none a correctness bug:- Retry the publish rename in
allocateSlot()(ChatSlots.cpp:359). On Windows, antivirus or the indexer briefly holds a handle inside a freshly extracted tree andMoveFileExfails with access denied; today that returns the error and orphans the staging directory. A bounded retry when the target does not exist turns a spurious failure into a success. The old install path had the same exposure behind the "close all other instances" message this PR deletes. - Cap the hostname in the staging name at 32, not 180 (
ChatSlots.cpp:136). The nonce carries uniqueness; the long cap only risks pushing deepdist/client/assets/paths pastMAX_PATHduring extraction on Windows. - Filter
verifiedSlots()byisUsableSlotName()(ChatSlots.cpp:268). It skips only dot-prefixed entries, whileresolveSlot()rejects a selection that failsisUsableSlotName(), so a hand-made directory with a trailing space is recorded, rejected on the next read, and recorded again on every resolve. - Add a test that
resolveSlot()still returns the fallback when the storage directory is unwritable. The read-only system tier depends on that best-effort claim and nothing exercises it. The lost-rename-race branch (ChatSlots.cpp:372) has no test either and needs an injection hook to get one; acceptable to leave.
- Retry the publish rename in
- Wire it: resolver sources + install path rewrite. The one behavior-changing PR.
rankedCandidates()gains the two slot sources, each read through its ownselected.json;installPackage()/performInstall()become download -> stage -> identity check -> publish -> select -> restart; theai.prevbackup, the stop-before-install reap-wait andwriteProtocolVersionFileIfMissing()come out; the single per-session resolution replaces the per-call resolves and the separate static-file pin; the selector gains its read-only mode and loses its prerelease handling (PR 2, above).verifyPositAiInstallation()and thepackage.json/protocol.jsonreaders are replaced, not left beside the slot equivalents. The e2e sandbox provisioning (PW_SEED_PAI, today copied todata-home/paiwithbin/) is laid out as a slot with a manifest and a selector, the version-under-test report follows the selector, and the per-spec data home must not write into the shared seed (todaypaiis symlinked per spec, so an install test would publish a slot into the seed every other spec reads). NEWS entry. - Delete the locking. After PR 3,
ChatInstallLockis vestigial. A separate PR keeps PR 3 reviewable, is independently revertible, and forces the explicit check that Coordinate Posit Assistant update/uninstall across concurrent sessions #18276's two non-locking fixes survive. - Reinstall -- the forced-install path plus the dialog change for the installed-equals-available case. NEWS entry.
PRs 1-4 are a unit from the user's perspective and must ship in the same release; PR 5 only has to make that release. rstudio/rstudio-pro#12483's bundled install rule is independent of this and already landed on the OSS side (#18690).
Testing
Each PR updates the e2e Playwright tests it impacts as part of the same change (uninstall-command tests with the removal; sandbox provisioning and install/update assertions with the wiring; new coverage with Reinstall), alongside unit tests for the slot, selector and verification code:
GTEST_FILTER='Chat*:SessionAssistant*:PositAssistant*' ./build/src/cpp/rstudio-tests --scope rsession
Activity
Remove the Uninstall Posit Assistant command (#18662)
Derive slot identity from the staged package, not its name
Harden the staging directory name against a missing hostname
Give each staged install a private directory
gtritchie commentedon Aug 27, 2026
Implementation notes from PR 2 (#18666)
The body above has been updated to match what was built. This comment records what changed and why, so the reasoning isn't lost in an edit.
1. Staging directories are unique per install and are never cleared.
The body previously specified
pai/versions/.tmp-<pid>/, "cleared first, so a crashed session's leftovers don't accumulate under our own pid." It now specifies.tmp-<host>-<pid>-<nonce>with no clearing.Two sessions sharing an NFS home can compute the same pid-based name, and under container runtimes they routinely do — each session pod has its own PID namespace, so low pids repeat across pods. The second session's prepare would delete the first's half-extracted tree. That is worse than a failed install, because the slot manifest is recorded from whatever is on disk when it runs: the first session would record a manifest describing the second's partial extraction, verify it successfully against itself, and publish a truncated slot that keeps verifying for the rest of its life — the corruption this layout exists to make unrepresentable.
Reclaiming by name cannot be rescued, even narrowed to
<myhost>-<mypid>-*: any directory deleted for looking abandoned may belong to a live peer, which just moves the corruption to the other side. So the cost is that an interrupted install leaves its extraction behind, joining the orphans the Deferred section already expects manage-installs to collect. Host and pid stay in the name to give that work something to identify them by.Risk is near-zero on desktop and single-node Server, where one host cannot run two processes with the same pid, and concentrated in containerized Workbench.
2. The install step order as originally written could not be performed.
It listed
extract → verify → write the slot manifest → rename, but verification as defined in the Verification section includes checking every manifest entry — so verifying before the manifest exists is circular. The body now readsextract → write manifest → verify → rename, with the verify happening insideallocateSlot()rather than in the caller, so that "a slot only reaches a final name after verification" holds by construction instead of by each install path remembering to check.3. Adoption compares package identity, not the slot name.
"The loser re-verifies the now-existing target, adopts it if it verifies" is implemented, and now stated, as: adopt only if it verifies and its
package.jsonversion andprotocol.jsonprotocol match the staged package. A directory named1.1.0is not evidence that it holds1.1.0, and adopting on name alone would silently leave the session on a version nobody asked for — the same rule the Slots section states, applied to adoption.4. Fallback tie-break on equal versions. Two slots can hold the same version (
1.1.0and1.1.0-2after a Reinstall). Resolution orders by version descending, then slot name descending. Now noted in the Selector section.5. Protocol matching is exact string equality, matching what
hasProtocolMismatch()already does. Confirmed that only the.0minor is ever used in practice, so the highest-minor-within-major lookup ingetPackageInfoFromManifest()never fires with a differing minor. Left out of the body, which never claimed anything about matching semantics.Order same-version slots by reinstall ordinal, not by name
Validate slot names from the archive and from selected.json
Keep symlinks out of the slot manifest
30 remaining items
Compare reinstall ordinals only within one version string
Build the CSP header from the installation the handler resolved
Retry the publish rename on Windows only
Check the managed-mode warning flag before resolving the user slot
Leave the seed's locks directory out of the sandbox
Run a post-check install from the scheduler, not inside the poll
Return the rebuilt CSP header under the rebuild lock
Do not sleep after the final publish attempt
Resolve Posit Assistant from versioned install slots (#18892)
Remove the Posit Assistant cross-session install lock (#18920)
Offer to reinstall Posit Assistant when it is up to date (#18927)
tidy up NEWS.md for 2026.10 (#18928)
gtritchie commentedon Sep 28, 2026
The deferred item
posit-assistant-pathas a versions root is taken up in #18973, which also changes the resolution rules described here:<systemConfigDir>/pai(itsversions/,selected.jsonandbin/) is no longer read. The system tier exists only whenposit-assistant-pathis set, and the directory it names can holdversions/+selected.jsonor be a single installation directory as in 2026.09.posit-assistant-pathinstallation always runs, over both the bundled copy and the user's slots, instead of competing by version.The "System-tier retention" item applies to that configured directory.
Remove the Posit Assistant slot manifest (#18986)