Repository navigation
Resolve Posit Assistant from versioned install slots - #18892
Conversation
The administrator's storage directory carries the same selected.json as the user's, but RStudio never writes there, so resolveSlot() now takes a SelectorRepair argument: Enabled records the fallback as before, Disabled resolves through the same fallback without touching the file. Before this every resolve against a read-only /etc/rstudio would have tried the repair, failed, and warned. preferredOver() no longer parses a release portion out of a version or ranks releases above prereleases. Posit Assistant versions are plain x.y.z and every other parser site rejects a suffixed one, so the selector was the one place that accepted them. What remains is: parse, compare, then reinstall ordinal, then name. The four tests that pinned the prerelease handling go with it, replaced by one that pins an unparsable version ranking below every parsed one. selectInstalledVersion() records a slot that already holds the requested version for a protocol, which the install path uses to skip the download when the target version is already on disk. Three small fixes to the slot machinery, found on re-review: - allocateSlot() retries the publish rename briefly while the target name is still free. On Windows, antivirus or the indexer can hold a handle inside a freshly extracted tree and MoveFileEx fails with access denied for a moment; that used to orphan the staging directory. - The hostname in a staging directory name is capped at 32 characters rather than 180. The nonce carries the uniqueness, and the long cap only pushed deep dist/client/assets/ paths towards MAX_PATH. - verifiedSlots() skips any entry isUsableSlotName() rejects, not only dot-prefixed ones. A hand-made directory with a trailing space was otherwise recorded as the fallback, rejected on the next read, and recorded again on every resolve. Also adds the test that resolveSlot() still returns the fallback when the storage directory cannot be written, which the read-only system tier depends on. Addresses #18658.
selectInstalledVersion() took the first slot the directory listing yielded that held the requested version. After a reinstall two slots hold one version, and the later one exists precisely because the earlier one is suspect, so re-selecting the version could hand the older slot back and undo the reinstall. It now picks the preferred matching slot by the same order the fallback uses (later reinstall ordinal first), and leaves a selection that already names a slot holding the version as it is. Addresses #18658.
The slot machinery merged inert in #18666 is now what the session runs from. ChatInstallation resolves from four sources: the user's slots under pai/versions (chosen by protocol through the user's selected.json, which a stale entry repairs), the administrator's slots under the system config directory's pai/versions (chosen through the administrator's selected.json, which is never rewritten), the administrator's legacy pai/bin, and the bundled copy. They race as #18774 established -- compatible protocol first, then highest version, ties in that order -- and posit-assistant-path stays outside the race. The user's legacy pai/bin is never read: older releases still mutate it, and reading it would re-import the corruption the layout removes. The session resolves once, lazily on first need, and holds the answer. The backend start, the agent start, the asset handler and its Content-Security-Policy, and every report of the installed version and protocol read that one resolution, so they cannot drift onto different installations. It is re-checked structurally on each read, so an installation removed out of band is resolved around, and it is cleared by exactly one thing: this session's own successful install. An install made elsewhere takes effect at the next session start. The separate static-file pin from #18832 is gone; the CSP cache is keyed on the installation being served, so it still follows a change of resolution that no backend start accompanies. The install path is now download, verify SHA-256, extract into a private staging directory, check that the extracted package declares the requested version and this build's protocol, publish it as a slot, select it, and only then stop the backend and agent so they restart on the new slot. A version already on disk in a verifying slot skips the download and is just re-selected. Nothing already on disk is modified, so the ai.prev backup and its restore branches, the stop-before-install reap-wait with its "still shutting down" failure, and the Windows "close all other instances" message are gone. A package without protocol.json is refused rather than backfilled, so writeProtocolVersionFileIfMissing() is deleted. verifyPositAiInstallation() and the package.json/protocol.json readers are replaced by verifyInstallDir(), declaredVersion() and declaredProtocol(), which slots::verifySlot() now builds on, so there is one definition of a runnable installation. The lock call sites stay for the follow-up PR that removes the locking. Addresses #18658.
A versioned-aware RStudio never reads pai/bin, so a PW_SEED_PAI tree copied as-is would resolve nothing and the @ai suite would download the official package instead of the build that was asked for. globalSetup now lays the seed's bin/ out as a version slot with its install manifest, selected for the protocol it declares (fixtures/pai-seed.ts, mirroring the C++ wire format). Any versions/ or selected.json beside the seed's bin/ belong to the machine's own installs and are not copied. Each per-spec data home gets its own pai storage directory provisioned from the seed -- selected.json and the shared state copied, the slots hardlink-cloned -- instead of a symlink to it. An install run by the session under test publishes a slot and rewrites selected.json where it resolves, which through the link was the seed every other spec reads. The version-under-test report follows the selector rather than reading bin/package.json, and reports every selected install because which one the session ran depends on the protocol compiled into the IDE. Addresses #18658.
The user guide's removal section now describes what pai holds after this change -- one directory per installed version under versions/, selected.json, and a bin/ only if an earlier release installed there -- and that installs add directories and remove nothing. The ai.prev note is attributed to earlier releases, which are the only ones that create it. NEWS entry for #18658. Addresses #18658.
inspectSeed() checked only the identity files, so a stale or partial build -- a missing or zero-byte main.js or index.html -- was laid out as a selected slot that RStudio then rejected, and the run downloaded the official package without saying so. It now applies the same structural check as installation::verifyInstallDir() before anything is written, and the harness spec covers a missing and an empty required file. Addresses #18658.
The administrator's selected.json chooses which slot the system-wide installation offers; the newest compatible copy among the user's, the system-wide and the bundled one still wins, and posit-assistant-path is what pins one outright. The NEWS entry now says so. The user guide's description of pai now calls the version directories installs (a reinstall adds a suffixed one) and selected.json a per-protocol record of what was selected rather than the version in use. Addresses #18658.
A directory under pai/versions is only used when it carries the slot manifest an install writes, so a package extracted there by hand is skipped. The NEWS entry said an administrator could provide versions "the same way", and the not-found error told users to install into their own pai/versions; both described something that does not work. The release note now names the manifest requirement, and the error points at the in-product install and the system-wide location. Addresses #18658
Without a pinned path the message named the system pai directory itself, which the resolver never reads directly: it reads versions/ slots, which need the manifest an install writes, and the legacy bin child. Name pai/bin, the one system location an administrator can populate by hand, as the message did before the versioned layout. Addresses #18658
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 |
The manifest lookup matched on major version and took the highest minor, while the mismatch check, the selector and the install identity check all compare the protocol string exactly. A manifest entry for a higher minor (11.1 on an 11.0 build) was therefore offered as an update and then refused by the install, each attempt downloading the package again and leaving an extracted copy in pai/versions. Protocol versions are published as <major>.0 and nothing else, so the lookup now reads the entry for the exact protocol string; an entry of any other form is warned about, since it can never be selected. A test pins kProtocolVersion to that form so a stray minor fails the build's tests rather than surfacing as a failed install. Addresses #18658
The exact-match lookup returned bad_message or a readObject error when the entry for the protocol was not an object or lacked version or url. The update check only treats protocol_not_supported as "nothing to offer", so a fresh installation facing such an entry was reported as current instead of as having no compatible version, as it was when the old loop skipped the entry. Every unusable-entry path now returns protocol_not_supported, and a test pins the code for each. The <major>.0 warning used SemanticVersion::parse, which accepts "11", "v11.0" and "11.0.0". isProtocolVersionForm() is a textual check shared by the manifest warning and the kProtocolVersion test. Addresses #18658
Code review findingsActionable items from a code review of Important
Suggestions
|
kevinushey
left a comment
There was a problem hiding this comment.
A few things from a read-through, roughly most important first: the agent-stop timeout in finishInstall(), the unlocked read-modify-write of selected.json, and currentVersion being set from the request rather than the resolution. The rest are smaller.
One broader question: nothing reclaims old slots or orphaned .tmp-* staging directories, so pai/versions grows by a full package tree (~18 MB) per update, and the slot walks noted inline grow with it. Is a reaper (keep the selected slot plus the last N) planned for the follow-up, or is documenting it in the guide the intended end state?
| stopChatBackendForInstall("update"); | ||
|
|
||
| DLOG("Stopping assistant agent to pick up Posit Assistant {}", version); | ||
| if (!assistant::stopAgentForUpdate()) |
There was a problem hiding this comment.
If stopAgentForUpdate() times out, this only logs and carries on: the pin is cleared and the install reports Complete, so the client restarts the backend on the new slot while the old agent (launched from the previous slot) may still be running. ensureAgentRunning() would then see it as running and leave it alone, and the two halves end up on different installations -- the drift the one-resolution-per-session design is meant to prevent. Previously the reap wait refused the install with "A Posit Assistant process is still shutting down". Should a timeout here fail the install (or at least not report Complete) rather than just warn?
There was a problem hiding this comment.
Agreed. Fixed in 3999852: a timeout now reports the install as an error with the old "still shutting down, try again" message and leaves the held resolution in place, so the restart meanwhile stays on one installation. The slot is already published and selected, so a retry hits the already-installed shortcut and repeats only the stop.
There was a problem hiding this comment.
Follow-up in b7ed302: when the install is queued behind an update check, the check's completion can run inline inside the main thread's supervisor poll, where the agent-stop wait cannot reap anything (the nested poll is a no-op). The post-check install is now scheduled as delayed work so it runs after the poll returns; without that, failing on timeout would have failed every such install for nothing.
| @@ -227,7 +191,68 @@ | |||
| return writeSelections(storageDir, selections); | |||
There was a problem hiding this comment.
selectSlot() is a read-modify-write of the shared selected.json with no lock around it. The install calls it on the main thread outside both s_resolutionMutex and MutationScope, while resolveSlot() repair can call it from another session (e.g. a different release with its own protocol entry) or from an HTTP asset thread. If one of those reads before the install's write and saves after it, the install's selection is silently reverted and clearPinnedInstallation() re-resolves to the old slot. writeStringToFileAtomic keeps the file intact but doesn't prevent lost updates; this probably wants a file lock around the read + write (or one selector file per protocol).
There was a problem hiding this comment.
This one is in the issue's accepted list ("Lost-selection downgrade is accepted, not made durable", #18658), with the same scenario: it needs two sessions on different protocols writing in the same instant, and for an upgrade the repair converges on the newly installed slot anyway, since the fallback is newest-verifying. The same-process case is narrower than it looks: an HTTP thread only re-resolves when the held path is empty or invalid, which it is not during an install. Making it durable means serializing the selector write, which is the locking step 4 removes, or per-protocol selector files, which changes the layout the issue specifies. Leaving as accepted, unless you want to reopen that decision.
| s_updateState.installMessage = "Update complete"; | ||
| s_updateState.updateAvailable = false; | ||
| s_updateState.unsupportedInstalledVersion = false; | ||
| s_updateState.currentVersion = version; |
There was a problem hiding this comment.
This records the requested version rather than what the session resolves after clearPinnedInstallation(). If the selection is lost (see the selectSlot() comment) or a read-only source outranks the user slot, the pane reports 1.2.0 while the session runs 1.1.0, and carryPendingUpdateThroughSkip() compares against the wrong baseline on the next throttled skip. Reading getInstalledVersion() after the clear would report what's actually in use.
There was a problem hiding this comment.
Agreed. Fixed in 51a036a: after clearPinnedInstallation() the state records getInstalledVersion(), with a debug line when it differs from the installed version and a warning (falling back to the requested version) if nothing resolves at all.
| { | ||
| setInstallationPath(FilePath()); | ||
| setSearchPathsForTesting(boost::none); | ||
| setChatBackendPort(kChatBackendPortNone); |
There was a problem hiding this comment.
After the real search paths are restored, setChatBackendPort() rebuilds the CSP through locatePositAssistantInstallation(), which resolves against the real user storage with SelectorRepair::Enabled. On a machine with a stale selection under ~/.local/share/rstudio/pai, running rstudio-tests --scope rsession would rewrite the developer's (or CI machine's) real selected.json. Could the teardown avoid resolving against the real paths, e.g. by clearing the port while the test paths are still in place?
There was a problem hiding this comment.
Good catch. Fixed in 2743847: the port is cleared while the test's pinned sources are still in place, then the real paths are restored. The fixture comment now says why the order matters.
|
|
||
| int lhsOrdinal = slotOrdinal(lhs.name, lhs.version); | ||
| int rhsOrdinal = slotOrdinal(rhs.name, rhs.version); | ||
| if (lhsOrdinal != rhsOrdinal) |
There was a problem hiding this comment.
This compares reinstall ordinals even when the version strings differ, as long as neither parses (or both parse equal but are spelled differently): 1.2.0-beta.1-10 would outrank 1.2.0-beta.2 on ordinal alone. Suffixed versions are rejected elsewhere, so this may be unreachable today, but the previous guard (and DoesNotCompareReinstallOrdinalsAcrossVersions) was cheap -- worth keeping the ordinal comparison to slots whose version strings are equal?
There was a problem hiding this comment.
Agreed; the guard is about what an ordinal means, not about suffix handling. Restored in 31b7ce3 along with DoesNotCompareReinstallOrdinalsAcrossVersions.
| // the fallback uses. Two slots hold one version after a reinstall, and | ||
| // the later one exists precisely because the earlier one is suspect, so | ||
| // the first slot the directory listing happens to yield will not do. | ||
| std::vector<slots::SlotInfo> installed = |
There was a problem hiding this comment.
verifiedSlots() walks the manifest of every slot for the protocol before discarding the ones whose version differs; bestSlotForProtocol() similarly verifies every slot when it only needs the best one that verifies. Since slots are never removed, this grows with every update, and it runs on the main thread (or on an HTTP thread under s_resolutionMutex). Filtering by declared version first, or sorting best-first and stopping at the first slot that verifies, would keep it to one small JSON read per slot.
There was a problem hiding this comment.
Leaving this one. Both call sites are off the steady-state path: the fallback runs only when the selection is missing or stale, and selectInstalledVersion() once per install. With the protocol filter now applied before the manifest walk (d61d731, c3aa6e9), the walk is bounded to one protocol's slots, roughly one per assistant release within a protocol's lifetime.
| // runs, and can be a downgrade, so say so once per session. Read-only: | ||
| // ignoring the directory includes not repairing its selector. | ||
| if (!paths.userInstallEnabled && | ||
| !userSlot(paths, selector::SelectorRepair::Disabled).isEmpty() && RS_ONCE()) |
There was a problem hiding this comment.
userSlot(...) (a full resolve including the manifest walk) is evaluated before RS_ONCE(), and an empty resolution is never held, so with user installs disabled and nothing installed system-wide, every locate -- each /ai-chat/ asset request, backend status poll, chat_verify_installed -- walks the user's slots just to decide whether to log a warning that has already been logged. A cheap already-warned flag checked before the resolve would avoid that.
There was a problem hiding this comment.
Agreed. Fixed in ee57cc0: a static warned flag is checked before userSlot() is evaluated, so the resolve happens at most once.
| DLOG("Installed Posit Assistant {} (protocol {}) as slot {}", | ||
| expectedVersion, kProtocolVersion, slotDir.getFilename()); | ||
|
|
||
| *pVersion = expectedVersion; |
There was a problem hiding this comment.
Nit: pVersion is always set to expectedVersion (which verifyDeclaredIdentity() already guarantees), so the out-parameter carries no information. performInstall() could call finishInstall(newVersion, cont) directly.
There was a problem hiding this comment.
Agreed. Fixed in d56b481: the out-parameter is gone and performInstall() calls finishInstall(newVersion, cont).
| @@ -5264,7 +5241,9 @@ Error startChatBackend(bool resumeConversation) | |||
|
|
|||
| uint64_t lockToken = 0; | |||
| bool systemInstall = | |||
There was a problem hiding this comment.
Nit: this rebuilds <systemConfigDir>/pai/bin by hand (as does the not-found message above) rather than using legacySystemInstall(paths) / InstallSearchPaths::systemStorageDir from ChatInstallation. If the layout changes there, this check silently stops matching and starts taking the in-use lock for the system install. Exporting one helper would keep them in sync.
There was a problem hiding this comment.
Leaving this one: step 4 deletes this in-use lock acquisition along with the rest of ChatInstallLock, so the check disappears rather than needing a shared helper. The not-found message builds its path from InstallSearchPaths::systemStorageDir and kLegacyInstallDirName already.
| if (entry === SEED_PACKAGE_DIR || entry === VERSIONS_DIR_NAME || entry === SELECTOR_FILE_NAME) { | ||
| continue; | ||
| } | ||
| fs.cpSync(path.join(seedRoot, entry), path.join(storageDir, entry), { recursive: true }); |
There was a problem hiding this comment.
This still copies the seed's locks/ directory into the sandbox and every per-spec data home. When PW_SEED_PAI points at a real ~/.local/share/rstudio/pai, that brings along the developer's live in-use lock entries, which can make e2e installs refuse. The old code had the same exposure, but since this now lists its exclusions explicitly, locks might be worth adding to them.
There was a problem hiding this comment.
Agreed. Fixed in 01953b3: locks joins the exclusions, with the harness test extended to assert it is not copied.
verifyDeclaredIdentity() guarantees the published slot declares the requested version, so the parameter only echoed its input. Addresses #18658
finishInstall() only warned when stopAgentForUpdate() timed out, then cleared the held resolution and reported Complete, so the backend restarted on the new slot while the agent could still be running from the old one. It now reports the install as an error asking for a retry and leaves the resolution alone; the retry finds the version installed and repeats only the stop. Addresses #18658
finishInstall() recorded the installed version as current, but a read-only source can outrank the new user slot, and the throttled update check uses that value as its baseline. It now reads the version the session resolves after the held resolution is cleared. Addresses #18658
The fixture restored the session's search paths first, so clearing the port rebuilt the CSP header by resolving against the real user storage with selector repair enabled, and a test run could rewrite the selector of the machine running it. Addresses #18658
preferredOver() compared ordinals across two unparsed versions that differ, so the tenth reinstall of one could outrank a later other. Differing versions are ordered by string first, as they were before the prerelease handling was removed, and the test returns. Addresses #18658
An HTML request resolved the installation three times: in the handler, in buildCspHeader() and in rebuildCspHeaderCache(). An install landing between them could serve one slot's page under another's policy. The handler's resolution is now passed through both, which also drops the two extra resolves. Addresses #18658
The retry exists for antivirus and indexer handles on Windows. On other platforms a rename between siblings either works or fails for good, so ten attempts a second apart only delayed the error on the main thread. Addresses #18658
With user installs disabled and nothing installed anywhere, every locate resolved the user's slots to decide whether to log a warning that had already been logged, because RS_ONCE() was evaluated last. Addresses #18658
A real pai used as PW_SEED_PAI carries the machine's live in-use lock entries, which could make installs in every sandbox refuse. Addresses #18658
When the main thread's own process-supervisor poll reaps the manifest fetch, the check's completion runs inline inside that poll, so an install queued behind it called finishInstall() there. Its agent stop waits on the same poll, which is a no-op when re-entered, so the wait could never reap the agent and, since the timeout now fails the install, would fail it for nothing. The install is scheduled as delayed work instead, which runs after the poll has returned. Addresses #18658
buildCspHeader() released the lock after rebuilding and re-took it to copy the cached header, so a rebuild for another installation in between would have been returned for this request. rebuildCspHeaderCache() now returns the header it built. Addresses #18658
With a single attempt outside Windows, a failed rename still slept 100 ms before returning its error. Addresses #18658
Addresses #18658.
Step 3 of the plan in #18658: the resolver switch and install path rewrite, plus the step 2 adjustments the issue lists. The slot machinery merged inert in #18666 is now what the session uses.
What changes
Resolution.
locatePositAssistantInstallation()ranks candidates from four sources: the user'spai/versionsslot named bypai/selected.json(repairing a stale selection), the system-wide<systemConfigDir>/pai/versionsslot named by its ownselected.json(read-only, never repaired), the legacy<systemConfigDir>/pai/bin, and the bundled copy. The #18774 rules are unchanged: compatible protocol first, then highest version, ties user > system slot > system legacy > bundled;posit-assistant-pathis used outright and ends the search when it does not verify;userInstallWouldBeSelected()still gates the update offer; managed mode skips the user tier. The user's legacypai/binis never read.One resolution per session. The session resolves lazily on first need and every consumer reads that answer: backend start, agent start, the
/ai-chat/asset handler and its CSP, and installed-version reporting. It is mutex-guarded because the asset handler reads it from HTTP threads, re-validated structurally on each read, and cleared only by the session's own install. An empty resolution is not held. This replaces the separatestaticfiles::setInstallationPath()pin; the CSP cache is keyed on the served installation path, and the asset handler passes its one resolution into the CSP build.Install. Download, SHA-256, extract into a private staging directory (
.tmp-<host>-<pid>-<nonce>, removed by the call that created it when the install fails, never reclaimed by anyone else), check the extractedpackage.jsonversion andprotocol.jsonprotocol against the manifest entry withverifyDeclaredIdentity(),allocateSlot(),selectSlot(), then stop the backend and agent so they restart on the new slot. An agent that does not stop in time fails the install with a retry message and leaves the held resolution alone; the retry skips the download. The reported current version is what the session resolves afterwards. A version already present in a verifying slot is re-selected without a download. Theai.prevbackup andwriteProtocolVersionFileIfMissing()are gone; a package withoutprotocol.jsonis refused.Selector (step 2 adjustments).
resolveSlot()gainsSelectorRepair::Disabledfor the system tier;preferredOver()is parse-compare, then ordinal, then name, with the prerelease handling removed;selectInstalledVersion()prefers the latest reinstall and keeps an existing matching selection;verifySlot()builds oninstallation::verifyInstallDir()/declaredVersion()/declaredProtocol()so there is one definition of a valid install;verifiedSlots()takes the protocol and skips other slots before walking their manifests.Manifest lookup.
getPackageInfoFromManifest()reads the entry for the exact protocol string instead of the highest minor within the major, matching every other protocol comparison. Protocol versions are only ever published as<major>.0;types::isProtocolVersionForm()is the textual check, a unit test pinskProtocolVersionwith it, and a manifest key of any other form is warned about. An entry that is absent or unusable (not an object, no version or url, non-HTTPS) reportsprotocol_not_supported, the one code the update check reads as "nothing to offer". Without this, an11.1entry on an11.0build was offered and then refused by the install identity check on every attempt.Test harness.
PW_SEED_PAIis laid out as a slot with a manifest and a selector, each spec gets its ownpaiprovisioned by hardlink clone (no more symlinked seed), and the version-under-test report follows the selector.Docs. NEWS entry and the user guide's manual-removal section describe the
versionsandselected.jsonlayout.Deviations from the issue body
waitForOwnComponentsReaped()is deleted here rather than in step 4: with the stop-before-install reap-wait gone it would be an unused static.MutationScopeand the in-use lock acquire in backend and agent start remain as call sites for step 4, which deletesChatInstallLock.*.Follow-ups filed
deploy:rstudiomust publish a slot with a manifest.Verification
GTEST_FILTER='Chat*:ProtocolVersion*:IsProtocolVersionForm*:SessionAssistant*:PositAssistant*' ./build/src/cpp/rstudio-tests --scope rsession: 314 passed.e2e/rstudio:npm run -s typecheckclean;tests/harness/pai-seed.test.ts13 passed.