Repository navigation
Restore symlink members when extracting the sd.cpp prebuilt - #9270
danielhanchen merged 13 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Updates _safe_extractall() to correctly restore symlink entries from sd.cpp prebuilt ZIPs after extraction, preventing runtime failures caused by flattened shared-library symlinks.
Changes:
- Recreates symlink members after
zipfile.extractall()while enforcing an “in-tree” containment guard for link targets. - Adds tests verifying symlink restoration and rejection of symlink targets that escape the install directory.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
studio/install_sd_cpp_prebuilt.py |
Collects symlink members pre-extraction and recreates them post-extraction with safety checks. |
studio/backend/tests/test_sd_cpp_install.py |
Adds regression tests for symlink restoration and symlink-escape prevention. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| if dest.is_symlink() or dest.exists(): | ||
| dest.unlink() |
| raise RuntimeError(f"unsafe symlink in archive: {filename!r} -> {link_target!r}") | ||
| if dest.is_symlink() or dest.exists(): | ||
| dest.unlink() | ||
| dest.symlink_to(link_target) |
| info.external_attr = (stat.S_IFLNK | 0o777) << 16 | ||
| zf.writestr(info, "../../../escape.txt") | ||
| with zipfile.ZipFile(archive) as zf: | ||
| with pytest.raises(RuntimeError, match = "unsafe symlink"): |
|
Confirmed this hits _safe_extractall in studio/install_sd_cpp_prebuilt.py, where zipfile.extractall still writes the ggml and webp symlink members as plain text files and leaves sd-cli unable to load its libraries. Will get this reviewed. |
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 64428b973b
ℹ️ 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".
| for dest in destinations: | ||
| if dest.is_symlink(): | ||
| dest.unlink() |
There was a problem hiding this comment.
Remove stale symlinks from member parent paths
When a previous managed archive leaves a directory symlink and the replacement ZIP contains only children such as alias/new.txt (ZIPs need not include an explicit alias/ entry), this loop checks only the complete destination, so the stale alias parent remains. extractall() then follows that link and writes the new payload into its old target, corrupting the upgraded layout or overwriting another managed file; inspect and remove symlinks in every destination's parent chain before extraction as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejected: this requires a stale directory symlink from an earlier provider archive, while the affected sd.cpp bundles use file-level shared-library links; it is not reachable in a normal managed upgrade.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 64428b973b
ℹ️ 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".
| resolved = (dest.parent / link_target).resolve() | ||
| if resolved != base and base not in resolved.parents: | ||
| raise RuntimeError(f"unsafe symlink in archive: {filename!r} -> {link_target!r}") |
There was a problem hiding this comment.
Validate symlink targets before extracting members
When a downloaded ZIP contains an escaping symlink member, extractall() has already overwritten the managed tree before this containment check raises. A malformed or compromised release can therefore corrupt a previously working installation despite being rejected—for example, an earlier regular member replaces an existing library and the flattened symlink-target file is also left behind. Validate every recorded link target before cleanup and extraction, just as member paths are prevalidated.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Rejected: this requires a malformed or compromised release, not legitimate provider input. The verified ZIP still cannot write outside the tree because zipfile flattens the link, and the installer reports the incomplete replacement.
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Thanks for this, and for the writeup in #9268. The root cause there is exactly right, and both this PR and #9487 are built off your fix sketch. I pushed a follow-up commit to your branch rather than landing the other one, since this is the original report and the original fix. Your last two commits already handled the case I was most worried about. Extraction merges into the managed directory instead of wiping it, so a retry, a version bump or an accelerator switch re-extracts over the links the previous install wrote. The lexical What the follow-up changesThe load-bearing one is ordering. Link targets were validated after The rest:
On the two review notes that were closed as unreachable: the escape reasoning is right, a verified zip cannot write outside the tree. The part that bit me is that the damage is the overwrite, not the escape, and Verification
Backwards compatibility: the Linux CPU, Linux Vulkan and macOS arm64 assets carry no symlink members at all, so those installs are untouched. Only the Linux ROCm asset has symlinks, which is why this surfaced on an AMD host. A flattened tree from an older Unsloth is repaired, and a tree repaired by hand following the issue survives. I left your branch history alone rather than rebasing, so this is a plain fast-forward. Worth a rebase on main before merge. |
|
I simulated this against the real release assets rather than only synthetic archives, and it turned up two defects in what I pushed earlier. Both are fixed in Before and afterBefore, I reproduced the reported symptom end to end on the real ROCm asset, extracting with each version of the code and then asking the loader:
So this is a real issue, not a theoretical one, and the fix clears it at the loader level rather than only at the tree level. Two defects the simulation foundCreator 19 was treated as non-Unix. The gate was The symlink probe needed the install root to already exist. A first install into a root that had not been created yet failed as Both have regression tests. Does it break the old pathwaysNo, and the strongest evidence is that most hosts do not reach the changed code at all. I read the zip central directory of every asset in both release repos:
Then I compared extracted trees between the merge base and this PR for the four real assets I had locally, across fresh install, three consecutive reinstalls, upgrade from an old flattened install, and a tree repaired by hand using the workaround in #9268. Every symlink-free asset produced a byte identical tree, comparing path, size, sha256 and mode. The ROCm asset was broken on the base and healthy here in all four. Asset selection is untouched: 2880 combinations of Host and accelerator matrixThe changed code branches on exactly two OS-specific things,
That last cell is the one intentional behaviour change. A filesystem that cannot hold links cannot hold a working sd.cpp tree, so the old code's "success" there was the Coverage
No frontend, JS, TS, CSS or Playwright file is touched, so there is no browser-facing surface here. The |
|
Carrying over the hardware validation from #9487, since that PR is now closed and the evidence would otherwise be stranded there: #9487 (comment) It ran on a real gfx1151 ROCm host (AMD DevLab runner, Linux, HIP 7.13.99004), installing the actual release asset three times into the same managed root with only the download boundary stubbed, so asset selection, containment, extraction, the sweep and the install record all ran for real. That is the one thing my own runs could not do: mine drive
It independently reproduces two things I measured separately here: the per-asset symlink counts (ROCm 37 members / 10 links, Vulkan 0, CPU 0) and the loader-level failure and recovery (rc=127 to rc=0). How much of it transfers to this branchThe implementation here was taken from that validated head, so I diffed the two ASTs rather than assuming. Six of the eight relevant functions are identical, and the differences are exactly three:
So the ROCm result carries over. I re-ran my own checks on this branch's head after those two changes to be sure: merge base still gives The gap that remainsThe note on that comment is right, and it is the same gap my simulations have. Windows without developer mode, and filesystems that refuse symlinks such as exFAT or SMB without unix extensions, are mocked in both runs. Nobody has exercised those on real hardware. They are the two paths where this PR deliberately does something new, flattening on Windows and refusing with a clear error elsewhere, so if there is a Windows runner or an exFAT volume handy before merge, those are the cells worth spending it on. The other note there, that the diff is much larger than "recreate symlink members", applies equally to this branch and is worth budgeting review time for. The extra surface is cycle detection, reserved installer path guards, directory collision checks, the capability probe and the Windows fallback. |
|
One coverage gap worth recording before this merges, so it is a known limitation rather than an assumed-safe one. The Windows-without-developer-mode fallback and the symlink-refusing filesystem path (exFAT, SMB without unix extensions) are mocked everywhere they have been exercised: in my simulations, in the ROCm host run linked above, and in CI. That is worth stating explicitly because those are the two paths where this PR deliberately introduces NEW behaviour. Everywhere else it either restores links or does nothing at all:
Both are the right calls, and both are currently proven only against a monkeypatched Closing this for real is cheap if anyone wants it. The extraction tests do not need the backend stack or 36 passed, 0.18s locally on a bare interpreter with nothing but pytest installed. A For balance, the reason I am not treating this as a blocker: only 1 of the 15 release assets across both repos ships symlink members, that one is the Linux ROCm build, and the Unsloth mirror carries no ROCm asset at all, so it is reached through the upstream fallback. Every Windows asset has zero symlink members, which means the Windows fallback path is not reachable from any release currently published. It is insurance against a future asset, not a live code path. |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5d4392993
ℹ️ 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".
| if depth > _MAX_LINK_DEPTH: | ||
| raise RuntimeError(f"symlink cycle in archive: {str(path.relative_to(base))!r}") |
There was a problem hiding this comment.
Reject chains at the kernel symlink-depth limit
On Linux, an archive containing a 41-hop symlink chain passes this check and is fully installed, but accessing the first link fails with ELOOP because the kernel permits only 40 traversals. If a provider bundle uses such a chain for a required shared-library alias, extraction succeeds while leaving sd-cli unable to load that library; reject the chain when the depth reaches the configured limit rather than only after exceeding it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and reproduced. A 41 hop chain installed and then failed on first read with OSError 40, Too many levels of symbolic links, while 39 and 40 were fine.
What decided it was that the code contradicted its own stated intent: _MAX_LINK_DEPTH = 40 is commented as what Linux allows before ELOOP, but the chain walk permitted 41. That is an off by one against the documented rule, not speculative hardening, and it lands a library nothing can read, which is the same failure the cycle check already exists to prevent.
Fixed in 3592dff by counting hops FOLLOWED rather than nodes seen. My first attempt counted nodes and refused a legitimate 40 chain, because the real file a chain terminates at is not a traversal. Boundary now measured: 40 installs and reads back, 41 is refused, so nothing the loader could have walked is rejected. Tests added for both sides.
|
Validated on real AMD hardware: a gfx1151 host (Radeon 8060S, Linux, torch 2.11.0+rocm7.13.0, HIP 7.13.99004), which is the same GPU family as the report in #9268. The reading is taken off the loader rather than the tree, because the defect is not a tree shape, it is States: base
Base loader error, which is the failure the issue reports: Verdict CONFIRMED: the defect reproduces at the base and is absent at the head. That wording matters, because the harness treats a green head leg with no demonstrated base failure as VOID rather than a pass, so this result only exists because the base genuinely failed first. Backend suites on the same host: base 116 passed, head 154, merge 154, no test that passed at the base fails at the head. A non-vacuity gate confirmed the asset still ships symlink members (10, in Why this only matters on AMDSelection is unchanged by this PR, and only one asset in either release repo carries symlink members. Running the full host and accelerator grid over both repos' real asset lists, exactly two combinations reach it: The Unsloth mirror publishes no ROCm asset, so a ROCm host falls through to upstream, and Not tested hereThe claims above are bounded by one integrated GPU, on Linux, under ROCm:
Those last two are the paths where this PR deliberately introduces new behaviour, flattening on Windows and refusing with a clear error elsewhere, and both remain covered only by monkeypatched tests. The 36 extraction tests do pass on a real |
Wanted: a run on a Windows AMD machineEverything automated on this PR has run on Linux, including the gfx1151 validation above. Two branches this PR adds are still proven only against a monkeypatched
I have added The thing to know before runningNo published Windows asset ships symlink members. I checked both over range requests: Run itgit fetch origin pull/9270/head:pr-9270
git checkout pr-9270
python check_windows_amd.pyTwo optional forms: # Point the file tests at an exFAT stick or an SMB share to cover case 2 for real
python check_windows_amd.py --install-dir E:\sdcpp
# Skip the asset check if the machine has no outbound network
python check_windows_amd.py --skip-networkIt prints a markdown block starting at What each section means
The most valuable runA Windows AMD box with developer mode OFF, which is the default for most users. On that host section 3 is not a simulation: Developer mode ON is still useful, it just means section 2 is the live path and section 3 stays simulated. What a failure would mean
If a section errors out rather than reporting FAIL, paste the traceback; the script is new and has only been exercised on Linux, where it reports 5 PASS. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7bcd7abd7a
ℹ️ 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".
| # SPDX-License-Identifier: AGPL-3.0-only | ||
| # Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 | ||
|
|
||
| """TEMPORARY: manual validation of PR #9270 on a Windows AMD host. Delete before merge. |
There was a problem hiding this comment.
Remove the temporary PR validation script
This 372-line root-level script explicitly identifies itself as temporary and says to delete it before merge, but it is included in the commit. It also hard-codes PR-specific wording and release asset URLs, so retaining it leaves an immediately stale manual artifact that can be mistaken for a maintained repository check; remove it before merging.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right that it must not merge. It was added deliberately and time boxed: no published Windows asset ships symlink members, so a real Windows install never reaches the new code, and the fallback could only be exercised with a synthetic archive.
It has now served its purpose. A Windows 11 AMD host with developer mode off ran it and reported the flatten fallback working for real rather than under a monkeypatch, plus three genuinely failing tests that are fixed in 3592dff.
Removed in the same commit. It stays reachable at 7bcd7ab for anyone wanting the exFAT case, which is still uncovered.
Windows AMD run: developer mode OFFRan Host
Results
Section 3 is the branch that needed proving and it is not simulated here. The installer flattened and finished, Run twice, identical both times (3s). Section 5: the 3 failures are missing skip gates, not product bugsThe test file already has
Verified the third directly, outside pytest: two consecutive Two notes
Reproductiongit fetch origin pull/9270/head:pr-9270
git checkout pr-9270
python check_windows_amd.py |
|
Thanks, this is the run that was missing, and section 3 executing for real rather than under a monkeypatch is exactly the part no CI here could reach. The three failures are real and are fixedThey are mine, not the product's, and they fail on a supported configuration, so they needed fixing rather than explaining. Reproduced them exactly before touching anything, by pinning Fixed in 3592dff:
On the same spoofed host that reproduced your 3 failures: 22 passed, 18 skipped, 0 failed. Linux is 310 passed. Your note 1Agreed, and recorded at the Your note 2Correct on both counts, and it is why I have stopped calling that branch Windows shaped. On win32 the refusal path is unreachable by construction, so exFAT and SMB need a non-Windows host on a refusing mount. Still uncovered, and honestly stated as such rather than implied by the Windows result. SeparatelyCodex flagged that a chain longer than the kernel allows installed and then ELOOPed. Reproduced: 41 hops installed, then
|
Re-ran on the same Windows AMD host at
|
| commit | failed | passed | skipped |
|---|---|---|---|
base fdf83cb |
23 | 93 | 0 |
PR 3592dff |
23 | 113 | 21 |
The failing sets are identical — comm over the two sorted lists reports zero entries on either side, so no regressions and no accidental fixes. The PR adds 20 passing tests and breaks nothing.
The cause is test portability, not product code. 17 of the 23 are:
RuntimeError: archive sd-master-...-bin-Linux-Ubuntu-24.04-x86_64.zip contained no sd-cli binary
because those tests build synthetic archives containing sd-cli, while on Windows:
>>> _binary_names()
('sd-cli.exe', 'sd-server.exe')so install() correctly refuses an archive that supplied no sd-cli.exe. The remaining six are two cudart 404 assertions, a regex assertion, an OSError, and two others in the same family.
Out of scope for #9270 and not a blocker for it, but worth its own issue: the non-safe_extractall tests in this file cannot pass on a Windows host as written. Happy to open one if useful.
Notes on method
- The
safe_extractallsubset runs under system Python 3.13.13 with--noconftest, which is what makes it stdlib-only and portable. Withconftestenabled, system Python errors all 157 on the backend stack (httpxand friends), which is exactly why the scoped invocation exists. - The full-file runs used the studio venv at
~/.unsloth/studio/unsloth_studio, which has the backend stack. Both commits were measured with the same interpreter and the same command, so the comparison is like for like.
|
Confirmed on all three points, and the split running rather than skipping is the result I most wanted to see, since last time it stood on a hand check. Corroborating the pre-existing setI ran the same full-file comparison on Linux with
Same conclusion from two directions, and the dominant cause matches exactly: 17 of mine are The 22 against 23 is worth recording as the limit of the simulation rather than as noise. Pinning I also nearly posted a wrong version of this. My first attempt reported zero failures on both commits and therefore "identical", which was vacuous: the spoof plugin could not import the installer module under the PYTHONPATH I gave it, so pytest produced no FAILED lines at all and I was comparing two empty sets. Fixed and re-measured before quoting anything. Opened as an issue#9607, with your numbers and mine, the One thing recorded there rather than here: the Where that leaves this PR on Windows
|
zipfile.extractall writes symlink entries as regular files containing the link-target text, which leaves the release bundle's lib*.so links broken and sd-cli unable to start. Recreate them from the member list after extraction, keeping the Zip-Slip guard for link targets that escape the install dir. Fixes unslothai#9268
Decide every symlink check before the first write, so a refused archive leaves the previous install intact. Adds Unix-host gating, target shape and containment rules, cycle detection, a filesystem probe and a Windows flatten fallback, and moves the binary sweep off resolve().
… probing Two defects found while simulating the fix against the real release assets. Creator 19 (OS X) lays external_attr out exactly as creator 3 does, and is what Apple's ditto and Archive Utility stamp, so gating on 3 alone would silently flatten a macOS-built archive. The symlink probe also needed the install root to exist, which made a first install into a fresh root fail as though the filesystem could not store links.
symlink_to raises EEXIST on an existing path, which the handler read as the filesystem having no symlink support, so a probe left behind by an install that died between creating and removing it blocked every later install landing on the same pid. The install directory outlives the process and a restarted container starts a fresh pid namespace, so that pid comes round again. Sweep stragglers and take a unique name.
No published Windows asset ships symlink members, so a real Windows install never reaches the code this PR adds. The flatten fallback can only be exercised with a synthetic archive, which is what this does, alongside the capability, filesystem and asset facts a report needs to be meaningful. Temporary. Delete before merge.
…n depth A Windows 11 host with developer mode off failed three tests: two create a directory link in fixture setup before the extractor is reached, and the reinstall test asserts is_symlink, which the Windows fallback deliberately makes false. Gated the first two, split the third so the idempotency half still runs there and asserts the flattened shape instead. _MAX_LINK_DEPTH is documented as what Linux allows before ELOOP, but the chain walk permitted 41 hops, so an over-long chain installed and then ELOOPed on the first load. Counted per hop followed rather than per node seen, so 40 still installs and 41 is refused. Removes the temporary Windows check script now that it has been run.
3592dff to
bc1848d
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Fixes #9268
Problem
_safe_extractall()callszipfile.extractall(), and CPython'szipfiledoes not restore symlinks: it writes each symlink entry's data (the link-target text) as a regular file. The sd.cpp release zips ship the ggml/webp shared-library links as symlinks, so after extractionlibwebpmux.so.3is a 19-byte file containinglibwebpmux.so.3.1.2, andsd-clifails witherror while loading shared libraries ... file too short.Change
Symlink members are recreated rather than extracted, and every check is decided before the first write, so an archive that is refused leaves the previous install exactly as it was.
extractallrather than written through.create_system == 3before readingexternal_attras a Unix mode.PATH_MAX.symlink_tofails on Windows outside developer mode. Every Windows asset ships plain files, so flattening there costs nothing; elsewhere it raises._archive_binary_pathsand_discard_superseded_binariescompare with parents resolved and the final component left alone, which the sweep needs now that the tree can hold symlinks.Tests
studio/backend/tests/test_sd_cpp_install.pyis at 151 passed. Coverage includes reinstall idempotency, repairing an already flattened install, landing on the hand-made workaround from #9268, cycle rejection, valid chains, the malformed target shapes, non-Unix creators, and the Windows no-privilege fallback.Backwards compatibility: the Linux CPU, Linux Vulkan and macOS arm64 assets carry no symlink members, so those installs are unchanged. Only the Linux ROCm asset has symlinks, which is why this surfaced on an AMD host.
Supersedes #9487, whose hardening and test cases are included here.