Repository navigation
Serve Posit Assistant chat assets from the installation the backend runs - #18832
Merged
Merged
Conversation
handleAIChatRequest() resolved the Posit Assistant installation on every /ai-chat/ static asset request, and loading the chat pane issues dozens of them. Since #18815 that search ranks every tier rather than returning the first hit, so each request read and parsed package.json and protocol.json for up to three tiers. On a network-mounted home directory that is per-request latency multiplied by the number of assets in the chat UI. startChatBackend() now hands the installation it resolved to the static file handler, which serves assets from it for the backend's lifetime. The UI and the server process it talks to come from the same installation, and no filesystem work happens on the asset path at all. The pin is set before the port, because setChatBackendPort() rebuilds the CSP header cache, which reads dist/csp.json from the served installation. The pin outlives the backend, so a page whose backend exited can still load lazily-loaded chunks; the next start overwrites it, which is also how an install or update takes effect. Uninstall clears it, having deleted the directory it names, so requests resolve again and can still find a system-wide or bundled copy. An out-of-band change to the installation -- an administrator replacing the system-wide copy mid-session -- now takes effect at the next backend start rather than on the next asset request. Addresses #18819
The pin was cleared on chatUninstallPositAssistant()'s success tail, but the backup-removal failure returns after aiDir.removeIfExists() has already succeeded, so that path left the static file handler pinned to a deleted directory -- where validateAndResolvePath() fails to canonicalize the client root and asset requests answer 403 rather than resolving to a system-wide or bundled copy. Clear it immediately after the installation directory is removed, which is where the claim that it is gone becomes true, and which covers both exits. Addresses #18819
startChatBackend() pinned the installation before acquiring the in-use lock and launching the process, and the failure paths in between do not clear it. A start that failed therefore left the static file handler pinned while this session held no in-use lock -- which is what stops another session from mutating the installation -- so a concurrent uninstall could delete the pinned directory and leave asset requests answering 403 instead of resolving to a system-wide or bundled copy. Pin after runProgram() succeeds instead. Every failure above it now returns with nothing pinned, so asset requests resolve for themselves exactly as they do before a backend has ever started, and no failure path needs to remember to clear it. This costs one tier search per backend start: setChatBackendPort() rebuilds the CSP header cache, which reads dist/csp.json through the resolver, and now does so before the pin is set. That is once per start against the dozens of per-request searches this removes, and it resolves the same installation startChatBackend() just chose. Addresses #18819
Moving the installation pin after runProgram() left setChatBackendPort() ahead of it, so the CSP header cache -- which reads dist/csp.json through the resolver and keeps it for the rest of the session -- could seed from a different installation than the one whose assets are then served, if an out-of-band mutation landed between the two. Publish all three things the static file handler knows about the backend together, after the launch succeeds: the installation first, then the port (whose setter rebuilds the CSP cache, now reading from that installation), then the auth token. The token is still generated before launch, because the backend receives it in its environment. Every failure path above now returns having told the handler nothing, so asset requests resolve the installation for themselves exactly as they do before a backend has started. Addresses #18819
A rolled-back update or an out-of-band removal can leave the pin naming a directory that no longer exists. Treat that as nothing pinned, so asset requests fall back to whatever tier still holds an installation instead of 404ing for the rest of the session.
e94b595 added the fallback but no coverage for it. The test pins a staged installation, asserts it is served, removes the directory, and asserts the next request is not answered from it. The status assertion is what gives the test teeth: a dead pin reaches validateAndResolvePath(), which cannot canonicalize the client root under it and answers Forbidden. Asserting only on the body would pass either way, since that failure returns an empty one -- confirmed by removing the existence guard, where the body assertion still passed and the status assertion caught it (403 vs 403). Addresses #18819
e94b595 fell back when the pinned directory was gone, but a directory that is there without being an installation stayed selected. installPackage() extracts into pai/bin in place, and when unzip fails both the cleanup removeIfExists() and the aiPrevDir restore can fail with only a log (SessionChat.cpp:4421-4434) -- leaving a half-extracted pai/bin that the existence check accepts, so asset requests answer from it for the rest of the session instead of falling back to a system-wide or bundled copy. Test the pin with verifyPositAiInstallation(), the same definition the resolver requires of a tier before it will rank it. Four stats per request rather than one, against the twelve stats and six JSON reads this issue started from. The test removes only dist/client/index.html and leaves the requested asset in place, so the half-extracted installation would still serve it: with the existence check the assertion fails on the served body, which is what gives it teeth. Addresses #18819
The comment above the static file handler setters said every failure path in startChatBackend() returns having told the handler nothing, and that pinning the installation first makes the CSP cache read dist/csp.json from it. The lock and launch failures call clearChatBackendPort(), which resets the handler's port and token and rebuilds the CSP header; the pin-first order only matters when this start makes the session's first rebuild.
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 |
This was referenced Sep 15, 2026
gtritchie
added a commit
that referenced
this pull request
Sep 23, 2026
* Give the slot selector a read-only mode and drop prerelease ordering 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. * Prefer the latest reinstall when re-selecting an installed version 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. * Resolve Posit Assistant from versioned install slots 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. * Seed the Playwright sandbox as a versioned Posit Assistant install 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. * Document the versioned Posit Assistant layout 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. * Refuse a PW_SEED_PAI build RStudio could not run 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. * Describe selected.json as a selection, not the running version 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. * Stop pointing manual installs at pai/versions 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 * Name the legacy bin directory in the not-found message 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 * Match the manifest protocol entry exactly 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 * Report an unusable manifest entry as protocol_not_supported 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 * Check package identity in the installation module and discard failed staging installPackage() left its staging directory behind when extraction, the version/protocol identity check or slot allocation failed. The directory is this call's own (no other session can name it), and after an identity mismatch the same update is offered again, so each retry added an orphaned tree under pai/versions. The three error returns now remove it. The identity check moves to chat_installation::verifyDeclaredIdentity() so its error paths have unit tests: version mismatch, protocol mismatch, a package without protocol.json, and one without package.json. ChatIntegrity.GetPackageInfoErrorsOnInvalidProtocolVersion is deleted: since the lookup became an exact match it only repeated the absent-key case that GetPackageInfoUnusableEntryReportsProtocolNotSupported covers. Addresses #18658 * Filter slots by protocol before walking their manifests verifiedSlots() ran the full manifest check (one stat per recorded file) on every slot and only then did its callers drop the ones for another protocol. When no slot serves the current protocol nothing is selected, an empty resolution is not held, and the walk repeated on every resolve, growing with the slots left by earlier protocols. The protocol is now read first and slots declaring another one are skipped for the cost of one small read. Addresses #18658 * Use positAiStorageDir() for the manifest-check state path manifestCheckStatePath() built userDataDir()/pai by hand; positAiStorageDir() is the one definition of the storage root. Addresses #18658 * Shorten the #18658 NEWS entry The layout detail lives in the user guide; the entry keeps what a user notices. Addresses #18658 * Apply the protocol filter inside the slot verifier verifiedSlots() read protocol.json before verifySlot() had rejected a symlinked or junction slot, so the filter followed a link into a tree the slot does not contain, and the protocol was read twice, once to filter and once to fill the SlotInfo. The filter now runs inside the verifier after the link and directory checks, and the protocol is read once, so the slot returned is the one that was checked. Addresses #18658 * Read the slot protocol before the other verification steps verifySlotForProtocol() compared the protocol only after verifyInstallDir() and the package.json read, so a slot for another protocol still cost four stats and a parse, against the header's promise of one small read. The protocol is now read and compared right after the directory and link checks. Addresses #18658 * Say that the first install after upgrading re-downloads Posit Assistant The versioned layout does not adopt an existing pai/bin, so the NEWS entry states the one-time download. Addresses #18658 * Say installPackage() leaves installations, not all files, untouched selectSlot() rewrites selected.json, so "nothing already on disk is modified" overstated it. Addresses #18658 * Drop installPackage()'s version out-parameter verifyDeclaredIdentity() guarantees the published slot declares the requested version, so the parameter only echoed its input. Addresses #18658 * Fail the install when the assistant agent does not stop 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 * Report the resolved version after an install, not the requested one 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 * Clear the test backend port before restoring the real search paths 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 * Compare reinstall ordinals only within one version string 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 * Build the CSP header from the installation the handler resolved 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 * Retry the publish rename on Windows only 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 * Check the managed-mode warning flag before resolving the user slot 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 * Leave the seed's locks directory out of the sandbox 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 * Run a post-check install from the scheduler, not inside the poll 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 * Return the rebuilt CSP header under the rebuild lock 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 * Do not sleep after the final publish attempt With a single attempt outside Windows, a failed rename still slept 100 ms before returning its error. Addresses #18658
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
handleAIChatRequest()resolved the Posit Assistant installation on every/ai-chat/static asset request, and loading the chat pane issues dozens of them. Since #18815 that search ranks every tier rather than returning the first hit, so each request ranverifyPositAiInstallation()plus apackage.jsonread and aprotocol.jsonread for up to three tiers. On a workstation that is microseconds; on RStudio Server with a network-mounted home directory it is per-request latency multiplied by the number of assets in the chat UI.What the code does now
startChatBackend()hands the installation it resolved to the static file handler oncerunProgram()has succeeded, together with the backend port and the auth token. Asset requests serve from that installation, so the tier search and its JSON reads no longer run per request.Publishing all three only after the launch succeeds means a failed start never pins its installation or announces its port and token: asset requests keep serving whatever was pinned before -- nothing, before the first successful start -- and no failure path has to undo a pin. The lock-refusal and launch-failure paths still call
clearChatBackendPort(), as they did before this change, which resets the handler's port and token.The installation is published before the port because
setChatBackendPort()rebuilds the CSP header, and the session's first rebuild readsdist/csp.jsonfrom the served installation and caches it for the rest of the session (#18831). If an HTML request, a backend stop, or a lock or launch failure has already rebuilt it, this ordering has no effect.The pinned installation outlives the backend, so a page whose backend exited can still load lazily-loaded chunks. It is replaced by the next start, which is how an install or an update takes effect, and cleared by uninstall once the directory is actually gone.
It also invalidates itself.
servedInstallationPath()tests the pin withverifyPositAiInstallation(), the same definition the resolver requires of a tier before it will rank it, so a path that stops holding a complete installation falls back to the tier search rather than answering from a directory that cannot serve. That covers a rolled-back update, a removal out of band, and apai/binleft half-extracted by a failedunzipwhose cleanup and backup restore both failed (installPackage()reports those with a log and carries on). The check costs four stats per asset request, against twelve stats and up to six JSON reads before.Behaviour change worth noting
An out-of-band change to the installation -- an administrator replacing the system-wide copy mid-session -- now takes effect at the next backend start rather than on the next asset request. In exchange, the assets served and the backend process they talk to come from the same installation.
Testing
Five tests in
ChatStaticFilesTests.cppdrivehandleAIChatRequest()directly against staged installations, requesting a.jsasset so the request skips the handler's HTML branch and its dependence on session options and the editor theme:The two negative tests were each checked against the weaker implementation they exist to rule out, so neither passes vacuously: without the existence check the dead-pin test fails on the status code (403, which is the signature of the pin having been used), and without
verifyPositAiInstallation()the half-extracted test fails on the served body, since that installation still holds the requested asset../build/src/cpp/rstudio-tests --scope rsession-- 580 tests from 53 test suites, all passing.No NEWS entry
The per-request cost arrived with #18774 and #18815, both inside the unreleased 2026.10.0 cycle, so no official-release user has encountered it.
Related
Reviews of this branch twice raised that
loadCspDirectives()cachesdist/csp.jsonfor the lifetime of the session, which predates this change (#17132) and is out of scope here. Filed separately as #18831, since an in-session update restarts only the backend and therefore keeps serving the previous version's CSP.Fixes #18819.