Skip to content

Record which uv cache the install used, instead of inferring it later - #10410

Merged
danielhanchen merged 12 commits into
studio-update-uv-cachefrom
studio-uv-cache-marker
Sep 7, 2026
Merged

danielhanchen merged 12 commits into
studio-update-uv-cachefrom
studio-uv-cache-marker

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Stacked on #10386, which this targets. That PR makes unsloth studio update pick a uv cache by inspecting what the two candidate caches contain. This one makes the installers say which they used, because content cannot always tell.

The case content cannot decide

In shared mode the installers deliberately point the running backend at the Studio cache once the install is done (_prepare_studio_uv_cache_for_launch in install.sh, Set-StudioUvCacheForLaunch in install.ps1), even though the install itself used uv's own cache. So one on-demand install from the server, such as studio/backend/utils/wheel_utils.py:405, drops package bytes into the Studio cache.

Both caches now hold packages. The update's content rule prefers the Studio one and abandons the cache that actually has the Torch and CUDA wheels.

Reproduced end to end with uv 0.10.7, running the real _with_studio_uv_cache from each branch against the same scratch install:

install's cache: 24 files | studio cache (runtime leftovers): 61 files

#10386 alone   picks <StudioHome>/cache/uv   -> UV_OFFLINE=1 update FAILED
with this PR   picks the uv default cache    -> UV_OFFLINE=1 update SUCCEEDED

The mirror case is just as wrong and just as reachable: a studio install loses to uv's default the moment the user runs an unrelated uv pip install and warms it. No content rule separates these, because by then both caches genuinely hold package bytes. Only the installer knows which one it used.

What this adds

install.sh and install.ps1 write the cache they selected to <StudioHome>/cache/uv-cache-dir, and _with_studio_uv_cache reads it before falling back to inspecting both caches.

Every mode records, a caller's own UV_CACHE_DIR included. That is where the install actually put its wheels, and leaving an earlier install's marker in place would aim later updates at a cache this one never filled. A caller keeps control regardless: a nonblank UV_CACHE_DIR outranks the marker at update time too, so a CI image that pins a cache is unaffected either way. The marker only decides anything when the caller sets nothing.

A marker is honoured only while the cache it names still holds packages. uv cache clean is the user's to run, and a pointer to an emptied cache should not outrank a warm one.

Installs that predate the marker keep working. They have none, so the content fallback stays. The update also records what that fallback worked out, once setup has returned 0, and replaces a marker whose cache has since been emptied. A caller's UV_CACHE_DIR is never promoted into a marker: that belongs to one run, and the installers are what record an install.

Note the ordering is deliberately opposite on the two sides. The installer writes before the work, because the marker configures that work, and restores it if the work fails. The update writes after, because it is recording a conclusion rather than a configuration.

The marker travels with the environment

Written absolute. uv cache dir answers cache-dir = "relcache" with relcache verbatim and UV_CACHE_DIR may itself be relative, while the update resolves the marker against its own working directory. On the PowerShell side that needs $PWD explicitly: [System.IO.Path]::GetFullPath resolves against the .NET process directory, which Set-Location does not move, so it would anchor to wherever the process started.

Restored on rollback. Both installers put the previous environment back when an install fails (_restore_studio_venv_replacement, Restore-StudioVenvRollback), and a marker naming the cache of an install that never happened would outlive the environment it was chosen for. The previous contents are captured before the first write and restored at every point the environment comes back, which on PowerShell is two branches, the merged split-move and the plain move. A first install that fails removes the marker rather than restoring one that was never there.

Reset per run. Under irm | iex the script scope is the caller's session, the same hazard the rollback state next to it already documents.

Never fatal. An unwritable Studio root skips the marker rather than failing the install, which on PowerShell means -ErrorAction SilentlyContinue rather than Stop, since a parity test already forbids anything after the bucket scan from failing closed. Restore-StudioUvCacheMarker takes [AllowEmptyString()] and returns early on a blank root deliberately: it runs from the rollback, where the partial branch sits outside any try and the other branch's catch would report "could not restore previous environment" for a move that had already succeeded.

Read as utf-8-sig. Windows PowerShell 5.1 writes -Encoding utf8 with a BOM, which plain utf-8 would decode into the first character of the path.

Tests

tests/sh/test_install_uv_cache_root.sh goes from 45 to 81 checks under sh, bash and dash: what each mode records, custom mode replacing an earlier install's marker, a rolled-back install restoring the previous marker, a rolled-back first install leaving none behind, a relative cache recorded absolute, a relative UV_WORKING_DIR anchored to the run directory, and an unwritable Studio root still installing.

The pwsh selector test asserts the same marker for every parametrised mode, and there are new parametrised tests for the rollback round trip and the relative-path case. A parity test pins the marker in both installers, including that every call site sits after the custom branch and that neither write can fail closed.

unsloth_cli/tests/test_studio_update_uv_cache.py gains 14 tests: the marker beating both guesses in either direction, a stale marker not outranking a warm cache, a reinstall into a custom cache not being shadowed, a BOM-prefixed marker being read back, a relative marker resolved, the legacy backfill, a failed update recording nothing, a live marker not being overwritten, a caller value never promoted, and a cache path holding bytes that are not UTF-8 recorded and read back unchanged.

Three existing rollback tests and tests/studio/test_install_rollback_lifecycle.ps1 splice Restore-StudioVenvRollback into a fresh shell, so they now extract the new helper alongside it. tests/sh/test_install_rollback_lifecycle.sh does the same for the sh side; note the parity workflow runs that file with sh, whatever the shebang says, so the join is printf rather than $'\n'.

tests/sh/test_install_rollback_lifecycle.sh goes from 40 to 43, including a first install that commits and then fails afterwards. Two of its existing marker cases were passing vacuously until this round: _record_uv_cache_choice is defined outside the block they splice, so the harness exited 127 before writing anything, which satisfies any expectation about a marker that must not change. The helper is spliced alongside the others now and the cases fail if the harness writes to stderr or dies on a missing command.

sh / dash / bash tests/sh/test_install_uv_cache_root.sh          81 checks each
sh / dash / bash tests/sh/test_install_rollback_lifecycle.sh     43 checks each
pytest test_studio_update_uv_cache.py + parity + hardening       183 passed
all 24 tests/studio/*.ps1                                        pass
install.ps1 AST parse                                            clean
ruff 0.15.18 check, scripts/run_ruff_format.py                   clean

Run the Python tests with UV_CACHE_DIR unset. If your shell sets it, _with_studio_uv_cache returns at its first line and none of this is exercised.

Not in this PR

A shared install still writes its Torch and CUDA wheels to the user-wide cache, outside the Studio root, where the uninstallers cannot reclaim them, so the storage half of #10193 stays open. Closing that means making the Studio cache the install default and offering the reuse as an opt-in, which reverses the measured trade-off #10204 landed on and is a product call rather than a bug.

Content cannot answer the question the update asks. In shared mode the
installers point the running backend at the Studio cache
(_prepare_studio_uv_cache_for_launch, Set-StudioUvCacheForLaunch), so one
on-demand install from the server (wheel_utils.py:405) leaves package bytes
there. Both caches then hold packages, and the update stops preferring the one
the install filled: a duplicate download online, and under UV_OFFLINE or
uv.toml offline = true an update that cannot resolve. The mirror case is just
as wrong, a studio-mode install losing once the user warms their own default
cache with an unrelated uv pip install.

Both installers now write the cache they chose to
<StudioHome>/cache/uv-cache-dir and the update reads it, falling back to
inspecting both caches for installs that predate the marker.

Every mode records, a caller's own UV_CACHE_DIR included, since that is where
the install put its wheels and an earlier marker left in place would aim later
updates at a cache this install never filled. A caller keeps control either
way: a nonblank UV_CACHE_DIR outranks the marker at update time too. The
marker is honoured only while the cache it names still holds packages, so
`uv cache clean` does not leave a stale pointer outranking a warm cache.

The marker describes the environment, so it travels with it. It is written
absolute, since the update resolves it against its own working directory (on
PowerShell that needs $PWD explicitly: GetFullPath resolves against the .NET
process directory, which Set-Location does not move). The previous contents
are saved before the first write and restored wherever a failed install rolls
the venv back, and the snapshot resets per run because under `irm | iex` the
script scope is the caller's session. An unwritable Studio root skips the
marker rather than failing the install.

For installs that predate the marker, the update records what the fallback
worked out once setup has returned 0, and replaces a marker whose cache has
since been emptied. A caller's UV_CACHE_DIR is never promoted: that belongs to
one run, and the installers are what record an install.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-07T03:44:32.260190Z 1d2e65e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…failure

Four fixes, all on the marker's lifecycle.

The per-run reset ran AFTER Set-StudioUvCacheEnvironment, which is what writes
the marker, so it cleared the snapshot that call had just taken and made both
Restore-StudioUvCacheMarker calls no-ops. A failed reinstall kept the new
marker. Moved above the call, and the parity test now pins it to the lines
directly above rather than anywhere in the file, since searching the file
matches the copy inside the restore helper and passes either way.

Restoring only from inside the venv rollback missed every failure that happens
before a replacement is in flight: a first install has no previous venv, the
ownership guard can refuse the directory, the backup move can fail. The
restore now runs from the exit and signal handlers on the sh side and from
Exit-InstallFailure and the commit guard's finally on the PowerShell side.

Test-Path was unsuppressed under $ErrorActionPreference = "Stop". Probing a
path inside a directory the ACL denies throws UnauthorizedAccessException
rather than returning false, so an optional marker could abort the install.
Measured: Test-Path THREW UnauthorizedAccessException on a chmod 000 parent.

The reader stripped whole lines. The installers write UV_CACHE_DIR through
verbatim and a directory name may legitimately begin or end with a space, so
stripping probed a different path and read a warm cache as cold. splitlines
already drops the terminator; blank lines are still skipped, since blank means
unset.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bd822c0336

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.ps1
Comment on lines +1250 to +1253
if (-not [System.IO.Path]::IsPathRooted($Cache)) {
$Cache = Join-Path $PWD.Path $Cache
}
$Cache = [System.IO.Path]::GetFullPath($Cache)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve partially qualified Windows paths against $PWD

When UV_CACHE_DIR is a valid drive-relative or root-relative Windows path such as C:cache or \cache, Path.IsPathRooted returns true even though the path is not fully qualified. This skips the $PWD anchoring, and GetFullPath resolves it using the .NET process directory/current drive—the exact location that the preceding comment notes can differ after Set-Location—whereas uv runs relative to the PowerShell working directory. The marker can consequently name a different cold cache from the one the install populated; test for a fully qualified path rather than merely a rooted one.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rejecting this one, with the reasoning laid out since it is a real if narrow observation.

Path.IsPathRooted does return true for C:cache and \cache, so those skip the $PWD anchoring, and GetFullPath then resolves them against the process directory and current drive. That much is accurate.

Two reasons not to change it. Drive-relative and root-relative paths are not a shape UV_CACHE_DIR realistically takes; the strict bar here is a bug reachable on well-formed real input, and C:cache is not that. And the correct API, Path.IsPathFullyQualified, does not exist on .NET Framework, so it is unavailable in Windows PowerShell 5.1, which this installer supports. The fix would be a hand-rolled path-shape parser sitting in front of every ordinary path, which carries more risk of breaking the common case than the case it protects.

If a concrete report ever shows a real install using one of these spellings I would revisit it.

Same reason the probe stopped expanding: the installers write this path
through as uv would read it, and uv treats a leading tilde as an ordinary
segment rather than $HOME. Both installers already make the value absolute,
so expanduser could only ever have been wrong here, never right.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Eight findings, all on when the marker may be written, reverted or kept.

Committing the environment commits the marker. The unconditional restore I
added reverted it on any nonzero exit, including after the venv was already
committed, so a later failure left the installed environment pointing at the
previous install's cache. Both shells now clear the snapshot at the commit.

The PowerShell reset moves to the first lines of Install-UnslothStudio. It sat
after the lock checks, and nothing clears the flag on success, so under
`irm | iex` a second install failing early reverted the marker belonging to
the first, which had succeeded.

A marker that cannot be read is left alone. `cat` failing was recorded as an
empty snapshot with existed=true, so a rollback wrote a blank marker over the
previous install's; Get-Content failing left $null, and TrimEnd on it throws
inside the rollback, before -ErrorAction can apply.

Writes no longer follow symlinks. A redirection, Set-Content and write_text
all truncate the target rather than replacing the entry, so a marker path
linked elsewhere silently destroyed an unrelated file.

Relative caches resolve against uv's working directory, which --directory and
UV_WORKING_DIR move, rather than the installer's $PWD.

The marker directory is created with the .NET API, since New-Item -Path treats
brackets in a custom Studio root as a wildcard, as this installer already
notes at two other call sites.

The backfill is suppressed during a staged update: STUDIO_HOME names the live
install there, and the stage can still be rejected.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… venv flag

UV_WORKING_DIR may itself be relative, and uv resolves it against the
directory the installer ran from before it resolves the cache under it.
Recording "work/cache" would name somewhere else at update time. Both shells
anchor the base first; on PowerShell that has to be $PWD.Path, since
GetFullPath would use the .NET process directory instead.

The commit cleared the marker flag after the venv flag and after the backup
deletion. A signal in that window kept the newly committed environment,
because venv rollback was already inactive, and reverted the marker it came
with, because that flag was still set. Both are cleared together now, and a
parity test asserts the order rather than mere presence.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 4c4f9fb895

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comments and docstrings only, no code. Verified with comment_tools.py check
and by rerunning the suites: 183 passed, the two sh suites under sh, dash and
bash, and all 24 pwsh studio tests.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 1d2e65e448

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 7, 2026
@danielhanchen
danielhanchen merged commit c04cd21 into studio-update-uv-cache Sep 7, 2026
86 of 90 checks passed
@danielhanchen
danielhanchen deleted the studio-uv-cache-marker branch September 7, 2026 04:47
@danielhanchen

Copy link
Copy Markdown
Member Author

CI triage for the three red checks, none of which belong to this branch.

Core (HF=4.57.6 + TRL<1), Core (HF=default + TRL=default) and Core (HF=latest + TRL=latest) all fail in the same step, unsloth_zoo @ main - full pytest (CPU), on seven tests in unslothai/unsloth-zoo:

tests/test_unreadable_modeling_source.py  6 failed
tests/test_compiler_getsource_tokenerror.py  1 failed

They assert that inspect.getsource(function.forward) in the zoo compiler is still wrapped in a try, and it no longer is. That is a zoo-side change on its main branch, reached by every PR in this repo that runs the Core matrix, and nothing here is in its import path: this PR touches the two installers, unsloth_cli/commands/studio.py and tests.

Everything this branch does have coverage for is green on this commit, the Chat UI lanes and the Windows and macOS installer matrices included.

danielhanchen added a commit that referenced this pull request Sep 7, 2026
…es (#10386)

* Give `unsloth studio update` the same uv cache the install used

Three places pick a uv cache and only two of them agreed. install.sh and
install.ps1 choose one for the install itself (#10204), and
storage_roots._setup_cache_env seeds cache_root()/uv for the backend server.
An update reaches neither: `unsloth studio update` runs setup.sh / setup.ps1
straight from the CLI process, nothing on that path sets UV_CACHE_DIR, and
_setup_cache_env is only called from the backend, so uv fell back to its own
user-wide default. On a fresh install the installer downloads into
<StudioHome>/cache/uv and the first update downloads all of it again into
~/.cache/uv or %LOCALAPPDATA%\uv\cache, where uninstall cannot reclaim it.

The rule is the installer's own rather than an unconditional redirect: prefer
the Studio cache, and defer to uv's default only when the Studio one holds no
package bytes and uv's does. _setup_cache_env mkdirs an empty Studio cache on
every server start, so a shared-mode install would otherwise be sent to a
cache holding nothing -- one duplicate download online, and with UV_OFFLINE,
--offline or uv.toml offline = true, where uv may read only what is cached, an
update that cannot resolve at all.

Whichever cache wins is passed to the child as an explicit absolute path. uv
reads UV_CACHE_DIR as --cache-dir, so a blank inherited value is a missing
argument rather than an unset one (`UV_CACHE_DIR= uv cache dir` exits 2 with
"a value is required"), and uv answers a relative cache-dir with the relative
spelling, which setup.sh would resolve from a different directory.

* Resolve uv's cache answer the way uv does

Two ways the probe could name a directory uv never uses, both measured on the
uv this repo pins, 0.10.7.

A configured `cache-dir = "~/.myuv"` is printed verbatim and uv treats the
tilde as an ordinary relative segment: it creates a literal "~" directory in
its working directory, not one in $HOME. expanduser therefore probed a path
that does not exist, so a warm configured cache read as cold, or an unrelated
$HOME cache was picked up.

A relative cache-dir resolves against uv's working directory, and --directory
(env alias UV_WORKING_DIR) moves that out from under ours. Measured: with
UV_WORKING_DIR set, `uv cache dir` prints "relcache" and the cache lands under
UV_WORKING_DIR, not under the caller's cwd.

* Fall back to uv's platform cache when the probe cannot answer

uv discovers configuration from the CURRENT directory, so a malformed uv.toml
beside whoever ran `unsloth studio update` makes `uv cache dir` exit nonzero
even though setup.sh changes directory before it runs uv at all. Treating that
as "there is no default cache" sent the update to a cold Studio cache: a
duplicate download online, and an offline update that cannot resolve despite a
populated platform cache.

install.sh:646 already falls back to XDG_CACHE_HOME/uv or HOME/.cache/uv in
exactly this situation. The probe now does the same, adding LOCALAPPDATA/uv/cache
for Windows, and returns nothing only when there is no anchor to build a path
from.

* Trim the comments this branch added

Delete first, collapse second. The rationale that survives names a mistake the
next reader would otherwise make: metadata-only caches reading as warm,
UnicodeDecodeError escaping an OSError handler, a blank UV_CACHE_DIR exiting 2,
uv's literal tilde. The measured numbers and the alternatives considered are in
the PR description, which is where they belong.

Prose in the added block: 51 lines to 16.

* Record which uv cache the install used, instead of inferring it later (#10410)

* Record which uv cache the install used, instead of inferring it later

Content cannot answer the question the update asks. In shared mode the
installers point the running backend at the Studio cache
(_prepare_studio_uv_cache_for_launch, Set-StudioUvCacheForLaunch), so one
on-demand install from the server (wheel_utils.py:405) leaves package bytes
there. Both caches then hold packages, and the update stops preferring the one
the install filled: a duplicate download online, and under UV_OFFLINE or
uv.toml offline = true an update that cannot resolve. The mirror case is just
as wrong, a studio-mode install losing once the user warms their own default
cache with an unrelated uv pip install.

Both installers now write the cache they chose to
<StudioHome>/cache/uv-cache-dir and the update reads it, falling back to
inspecting both caches for installs that predate the marker.

Every mode records, a caller's own UV_CACHE_DIR included, since that is where
the install put its wheels and an earlier marker left in place would aim later
updates at a cache this install never filled. A caller keeps control either
way: a nonblank UV_CACHE_DIR outranks the marker at update time too. The
marker is honoured only while the cache it names still holds packages, so
`uv cache clean` does not leave a stale pointer outranking a warm cache.

The marker describes the environment, so it travels with it. It is written
absolute, since the update resolves it against its own working directory (on
PowerShell that needs $PWD explicitly: GetFullPath resolves against the .NET
process directory, which Set-Location does not move). The previous contents
are saved before the first write and restored wherever a failed install rolls
the venv back, and the snapshot resets per run because under `irm | iex` the
script scope is the caller's session. An unwritable Studio root skips the
marker rather than failing the install.

For installs that predate the marker, the update records what the fallback
worked out once setup has returned 0, and replaces a marker whose cache has
since been emptied. A caller's UV_CACHE_DIR is never promoted: that belongs to
one run, and the installers are what record an install.

* Reset the marker snapshot before the selector, and restore it on any failure

Four fixes, all on the marker's lifecycle.

The per-run reset ran AFTER Set-StudioUvCacheEnvironment, which is what writes
the marker, so it cleared the snapshot that call had just taken and made both
Restore-StudioUvCacheMarker calls no-ops. A failed reinstall kept the new
marker. Moved above the call, and the parity test now pins it to the lines
directly above rather than anywhere in the file, since searching the file
matches the copy inside the restore helper and passes either way.

Restoring only from inside the venv rollback missed every failure that happens
before a replacement is in flight: a first install has no previous venv, the
ownership guard can refuse the directory, the backup move can fail. The
restore now runs from the exit and signal handlers on the sh side and from
Exit-InstallFailure and the commit guard's finally on the PowerShell side.

Test-Path was unsuppressed under $ErrorActionPreference = "Stop". Probing a
path inside a directory the ACL denies throws UnauthorizedAccessException
rather than returning false, so an optional marker could abort the install.
Measured: Test-Path THREW UnauthorizedAccessException on a chmod 000 parent.

The reader stripped whole lines. The installers write UV_CACHE_DIR through
verbatim and a directory name may legitimately begin or end with a space, so
stripping probed a different path and read a warm cache as cold. splitlines
already drops the terminator; blank lines are still skipped, since blank means
unset.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the marker the way uv reads a path

Same reason the probe stopped expanding: the installers write this path
through as uv would read it, and uv treats a leading tilde as an ordinary
segment rather than $HOME. Both installers already make the value absolute,
so expanduser could only ever have been wrong here, never right.

* Tie the marker's lifetime to the environment it describes

Eight findings, all on when the marker may be written, reverted or kept.

Committing the environment commits the marker. The unconditional restore I
added reverted it on any nonzero exit, including after the venv was already
committed, so a later failure left the installed environment pointing at the
previous install's cache. Both shells now clear the snapshot at the commit.

The PowerShell reset moves to the first lines of Install-UnslothStudio. It sat
after the lock checks, and nothing clears the flag on success, so under
`irm | iex` a second install failing early reverted the marker belonging to
the first, which had succeeded.

A marker that cannot be read is left alone. `cat` failing was recorded as an
empty snapshot with existed=true, so a rollback wrote a blank marker over the
previous install's; Get-Content failing left $null, and TrimEnd on it throws
inside the rollback, before -ErrorAction can apply.

Writes no longer follow symlinks. A redirection, Set-Content and write_text
all truncate the target rather than replacing the entry, so a marker path
linked elsewhere silently destroyed an unrelated file.

Relative caches resolve against uv's working directory, which --directory and
UV_WORKING_DIR move, rather than the installer's $PWD.

The marker directory is created with the .NET API, since New-Item -Path treats
brackets in a custom Studio root as a wildcard, as this installer already
notes at two other call sites.

The backfill is suppressed during a staged update: STUDIO_HOME names the live
install there, and the stage can still be rejected.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Anchor a relative uv working directory, and clear the marker with the venv flag

UV_WORKING_DIR may itself be relative, and uv resolves it against the
directory the installer ran from before it resolves the cache under it.
Recording "work/cache" would name somewhere else at update time. Both shells
anchor the base first; on PowerShell that has to be $PWD.Path, since
GetFullPath would use the .NET process directory instead.

The commit cleared the marker flag after the venv flag and after the backup
deletion. A signal in that window kept the newly committed environment,
because venv rollback was already inactive, and reverted the marker it came
with, because that flag was still set. Both are cleared together now, and a
parity test asserts the order rather than mere presence.

* Commit the marker on a first install, gate its write, and record paths as bytes

Three items from the last review.

The commit cleared _UV_MARKER_SAVED inside the rollback branch, and a first
install has no previous environment, so it took no branch and left the marker
revertible. Anything failing after that point, the shim-path guard or a signal,
kept the newly installed environment and reverted the marker it came with. Both
shells clear it before the branch now.

The unlink that keeps a symlinked marker from truncating what it points at can
fail silently, on a directory that denies deletion while the target stays
writable. Both writes now happen only once the entry is confirmed gone; on
PowerShell that probe is Get-Item -Force, since Test-Path follows the link and
reports a broken one as absent.

A POSIX path may hold bytes that are not UTF-8, and Python hands those over as
surrogates. Encoding them raised UnicodeEncodeError, which is not an OSError and
escaped the best-effort handler, failing an update whose setup had already
succeeded and whose old marker was already unlinked. The path is written with
os.fsencode and read back with surrogateescape.

Two of the existing marker cases in the rollback suite were passing vacuously:
_record_uv_cache_choice sits outside the spliced block, so the harness exited
127 before writing anything, which satisfied every expectation about a marker
that must not change. The helper is spliced alongside the others and the cases
now fail if the harness writes to stderr or dies on a missing command.

* Tighten the comments added by this PR

Comments and docstrings only, no code. Verified with comment_tools.py check
and by rerunning the suites: 183 passed, the two sh suites under sh, dash and
bash, and all 24 pwsh studio tests.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Publish a staged update's cache choice, and treat a malformed marker as cold

Two items from the last review.

A desktop update never runs the direct path, so suppressing the backfill under
--stage left exactly the installs the marker exists for permanently on the
content fallback. The staged child still cannot write the live marker, since
STUDIO_HOME names the environment it is replacing and the stage may never
activate, so it parks the choice in the stage root and _studio_stage.stage
promotes it after the probes pass. A stage that fails verification publishes
nothing, and a stage that parks nothing leaves the live marker alone.

A marker holding an embedded NUL builds a Path fine and then raises ValueError,
not OSError, out of scandir, so a corrupted or hand-edited file aborted every
update before setup ran. That cache reads as cold now, which is what the rest of
this code already does with a cache it cannot inspect.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Probe uv where setup will run it, and record the marker unambiguously

Two items from the last review.

Both setup scripts change into their own directory before the dependency pass
(studio/setup.sh:1788), and uv discovers uv.toml and pyproject.toml from its
working directory. The probe asked from the caller's, so running an update while
standing in an unrelated project answered with that project's cache, and the
answer is then forced on the child through UV_CACHE_DIR. It now runs with the
setup script's directory as its working directory, and resolves a relative
answer against that same base.

A newline is legal in a POSIX path and uv reports one verbatim, but the marker
reader split the record into lines and kept the last fragment, so such a cache
read as absent and the update redirected uv elsewhere. The record is one path
followed by one delimiter now: strip that delimiter, keep everything else.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make one install agree with itself about its cache, and commit in one step

Six items from the last review.

setup.ps1 never changes directory: it addresses everything through PSScriptRoot
and hands install_python_stack.py the cwd it inherited, so probing from the
script's directory answered for a configuration that child never sees. The probe
now uses the directory setup will actually run uv from, which is the script's on
POSIX and the inherited one on Windows.

UV_WORKING_DIR may itself be relative, and uv resolves it after starting where
the probe started, so it is anchored to the probe's directory rather than to
wherever the update was launched.

uv reports a cache path verbatim, and stripping the reported line changed a
directory name that legitimately ends in a space. Blank lines are still dropped.

A relative UV_CACHE_DIR named a different directory in each phase of one install,
because setup.sh changes into its own directory before the dependency pass. It is
resolved once, before anything reads it, so both phases and the marker agree.
What is restored afterwards is still the caller's own spelling.

Windows PowerShell 5.1 decodes a BOM-less file with the active ANSI code page,
and the update writes this marker BOM-less UTF-8, so a non-ASCII path was read
back as mojibake and restored that way. It is read as UTF-8 explicitly.

The commit cleared two flags, and a signal between them put the previous
environment back while keeping the marker of the attempt that replaced it. One
flag decides both rollbacks now, set first and alone, and both restores consult
it.

* Resolve the Windows cache through one helper, and leave ambiguous installs alone

Two items from the last review.

The custom branch on Windows anchored a relative UV_CACHE_DIR to $PWD alone,
ignoring UV_WORKING_DIR, and rooting it that way also stopped the marker writer
from applying its own resolution. From C:\work with UV_WORKING_DIR=subdir and
UV_CACHE_DIR=cache, uv uses C:\work\subdir\cache and the installer recorded
C:\work\cache. Both call Resolve-StudioUvCachePath now, which mirrors
_absolutize_uv_cache_dir.

An install that predates the marker cannot say which cache it used, and content
cannot tell either: the running backend is pointed at the Studio cache even in
shared mode, so one on-demand wheel warms it. Where both caches are warm and no
marker settles it, the update keeps uv's default, which is what such an install
has been updating from all along. Preferring the Studio cache there was a new way
for an offline update to fail on an install that cannot record its way out. A
Studio cache that wins on content alone still wins when uv's default is cold,
which is the case this PR exists for, and a recorded marker still settles both.

* Tighten the comments this branch added

Comments and docstrings only, no code. Verified with comment_tools.py check and
by rerunning the suites: 238 passed, both sh suites under sh, dash and bash, and
all 24 pwsh studio tests.

* Stay out of the way when uv is told not to cache

Confirmed against uv 0.10.7: UV_NO_CACHE=1 makes `uv cache dir` report a
temporary directory that is discarded when the process exits. The probe
inherited that, read the throwaway as cold, and the update then seeded a
UV_CACHE_DIR that --no-cache outranks anyway and recorded it as the install's
cache. On an install predating the marker that redirected every later update to
a cache nothing had ever filled.

Neither seeds nor records now, on uv's own boolish spelling of the variable: 0
and false leave caching on, and a value uv cannot parse is one it refuses to run
on at all, which is not the same as running without a cache.

* Tighten the comments the last change added

Comments and docstrings only, no code. Verified with comment_tools.py check and
by rerunning the suites: 246 passed, both sh suites under sh, dash and bash, and
all 24 pwsh studio tests.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant