Skip to content

Restore symlink members when extracting the sd.cpp prebuilt - #9270

Merged
danielhanchen merged 13 commits into
unslothai:mainfrom
FrancescoBrunoDev:fix/sd-cpp-symlink-extractall
Aug 24, 2026
Merged

danielhanchen merged 13 commits into
unslothai:mainfrom
FrancescoBrunoDev:fix/sd-cpp-symlink-extractall

Conversation

@FrancescoBrunoDev

@FrancescoBrunoDev FrancescoBrunoDev commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9268

Problem

_safe_extractall() calls zipfile.extractall(), and CPython's zipfile does 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 extraction libwebpmux.so.3 is a 19-byte file containing libwebpmux.so.3.1.2, and sd-cli fails with error 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.

  • Restore symlink members from the archive's member list, with the containment guard already used for member paths applied to link targets too.
  • Extraction merges into the managed directory instead of wiping it, so the same archive can land on the links a previous install wrote. Member destinations stay lexical, and a stale link at a destination is dropped before extractall rather than written through.
  • Gate on create_system == 3 before reading external_attr as a Unix mode.
  • Reject absolute, Windows drive-relative, empty, NUL-bearing and self-referential link targets, and cap the payload at PATH_MAX.
  • Reject cycles, which would install a library nothing can read and send the runtime probe round a reinstall on every load. Chains keep working, since upstream ships them.
  • Refuse a link at or pointing to the installer's own record and ownership marker, and a member sitting under a directory the archive turns into a link.
  • Probe symlink support before extracting, and fall back to the flattened member when symlink_to fails on Windows outside developer mode. Every Windows asset ships plain files, so flattening there costs nothing; elsewhere it raises.
  • _archive_binary_paths and _discard_superseded_binaries compare 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.py is 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.

Copilot AI lite review requested due to automatic review settings August 19, 2026 07:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +537 to +538
if dest.is_symlink() or dest.exists():
dest.unlink()
Comment thread studio/install_sd_cpp_prebuilt.py Outdated
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"):
@danielhanchen

Copy link
Copy Markdown
Member

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 6b0fac4f5a

ℹ️ 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".

@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: 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".

Comment thread studio/install_sd_cpp_prebuilt.py Outdated
Comment on lines +528 to +530
for dest in destinations:
if dest.is_symlink():
dest.unlink()

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 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@Imagineer99

Copy link
Copy Markdown
Member

@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: 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".

Comment thread studio/install_sd_cpp_prebuilt.py Outdated
Comment on lines +534 to +536
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}")

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 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

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".

@danielhanchen

Copy link
Copy Markdown
Member

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 dest plus the stale-link unlink pass means that works: I ran three consecutive installs of a chained archive in the real upstream shape (libwebpmux.so -> libwebpmux.so.3 -> libwebpmux.so.3.1.2) and all three passes end with the links intact and the payload readable, against a merge base that fails all three.

What the follow-up changes

The load-bearing one is ordering. Link targets were validated after extractall, so an archive with a good sd-cli followed by an escaping link overwrote the working binary and then raised. Nothing escaped the tree, but a rejected archive still replaced the install it was rejected over. Every check now runs before the first write, so a refused archive leaves the previous install exactly as it was.

The rest:

  • Gate on create_system == 3 before reading external_attr as a Unix mode. Those high bits are only a Unix mode when a Unix host wrote the entry.
  • Reject absolute, Windows drive-relative (C:outside.dll, which Win32 resolves against that drive's cwd), empty, NUL-bearing and self-referential targets, and cap the payload at PATH_MAX. zf.read holds it in memory, so a small zip could otherwise expand to gigabytes of link payloads before any check ran.
  • Reject cycles. A cycle installs a library nothing can read, and since the runtime probe discards an unrunnable managed sd-cli and reinstalls into the same directory, that turns a one-shot failure into a reinstall on every load. Chains still work, which matters because upstream ships them.
  • Catch OSError from symlink_to and fall back to the flattened member on Windows, which is the Copilot note above. Outside developer mode the old code raised after having already deleted the extracted file, leaving the tree worse than before. Every Windows asset ships plain files, so flattening there costs nothing. Anywhere else a refusal means the filesystem cannot hold the layout sd-cli needs, so it raises instead.
  • Refuse a link at or pointing to the installer's own record and ownership marker, and refuse a member sitting under a directory the archive turns into a link.
  • _archive_binary_paths and _discard_superseded_binaries now compare with parents resolved and the final component left alone. They resolved the whole path, which was safe only while the tree held no symlinks, and this PR is what changes that.

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 _usable_or_discard_managed reinstalls into that same directory. That is why it is worth ordering the checks even though the archive is verified.

Verification

studio/backend/tests/test_sd_cpp_install.py is at 151 passed. Your three tests are kept, rewritten onto the shared symlink-member helper so they exercise the create_system gate, and two of them still fail against the merge base, so they remain a real regression proof. The rest cover 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 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

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 3b35753.

Before and after

Before, _safe_extractall called zipfile.extractall, which writes a symlink member's payload (the link target text) as a regular file. After, symlink members are recreated, and everything is validated before the first write.

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:

merge base this PR
ldd reports file too short yes no
sd-cli --help exit code 127 0
symlink members restored 0 of 10 10 of 10

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 found

Creator 19 was treated as non-Unix. The gate was create_system == 3. Creator 19 is OS X, which Apple's ditto and Archive Utility stamp, and it lays external_attr out exactly as creator 3 does. A macOS-built archive shipping symlinks would have been silently flattened, which is the very bug this PR exists to fix. Now gated on (3, 19), with FAT and NTFS still correctly ignored since those bits are DOS attribute flags there, not a mode.

The symlink probe needed the install root to already exist. A first install into a root that had not been created yet failed as this filesystem cannot store symlinks, when the real reason was that nothing had been created. extractall makes the tree itself, so the probe now does too. Both production call sites happen to mkdir first, so this was not reachable today, but the error was wrong and the ordering was fragile.

Both have regression tests.

Does it break the old pathways

No, 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:

  • 15 assets scanned, and exactly one ships symlinks: the Linux ROCm build, 10 links, all creator 3. That matches the report coming from an AMD host.
  • The other 14, including every Windows asset, both macOS assets, Linux CPU, Linux Vulkan and the whole Unsloth mirror, carry zero symlink members. For those, links is empty and the new code is skipped entirely.

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 platform.system() x platform.machine() x accelerator x release, including degenerate and empty releases, give identical answers on both sides, with 480 non-empty resolutions so the comparison is not vacuously equal.

Host and accelerator matrix

The changed code branches on exactly two OS-specific things, sys.platform and whether symlink_to works, so I pinned both and ran the product against the real archive each cell installs. 42 cells, all as intended:

host symlink-free assets ROCm asset
Linux, WSL on ext4, macOS, Windows dev mode unchanged links restored
Windows without dev mode, exFAT unchanged flattens and finishes, as it did before
WSL on a /mnt/c DrvFs root unchanged refuses with a clear error, nothing written

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 file too short install in the issue. It now fails with a reason instead, and only for the one asset that has links.

Coverage

  • 153 tests in test_sd_cpp_install.py, plus 154 in the engine and backend suites that consume the install tree.
  • 32 adversarial and benign archives: escaping, absolute, drive-relative, empty, NUL-bearing, self-referential and oversized targets, two and three node cycles, a link descending through itself, members under a symlink member, links at and pointing to the installer's own record and marker, plus benign shapes like directory links, dangling but contained targets, 200 links, a 30 deep chain, unicode names, duplicate members and ./ prefixes.
  • 6 upgrade paths through the binary sweep, which this PR moved off resolve(): same-layout reinstall, accelerator switch, a bundle shipping no server, a binary shipped as a symlink, and binaries under a directory symlinked by either this archive or a previous one.
  • All of the above on Python 3.9 through 3.14, matching requires-python = ">=3.9,<3.15".

No frontend, JS, TS, CSS or Playwright file is touched, so there is no browser-facing surface here.

The test_video_* failures on this branch are pre-existing. I ran them on the merge base as well and the failing set is identical, 80 failed and 292 passed on both, and they reproduce without these two files changed.

@danielhanchen

Copy link
Copy Markdown
Member

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 _safe_extractall directly on this x86 box, with no AMD hardware anywhere.

state links restored flattened sd-cli --help
merge base 0/10 10 rc=127
head, installs 1 to 3 10/10 0 rc=0

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 branch

The 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:

  • _is_symlink_member widened from create_system == 3 to in (3, 19). All ten symlinks in the ROCm asset are creator 3, so this selects exactly the same members in the validated scenario. It only adds macOS-created archives, which no current asset is.
  • base.mkdir(parents = True, exist_ok = True) before the symlink probe, which only runs when an archive has links, and only makes a directory that extraction would create anyway.
  • One local variable inlined, no behaviour change.

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 file too short and rc=127, this branch gives rc=0 with 10/10 links, and every symlink-free real asset still extracts to a byte identical tree.

The gap that remains

The 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.

@danielhanchen

Copy link
Copy Markdown
Member

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. studio-backend-ci.yml runs pytest tests/ on ubuntu-latest only, and no Windows or macOS leg touches test_sd_cpp_install.py.

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:

  • Windows without developer mode: catch OSError and flatten, keeping an install that used to finish finishing.
  • A filesystem that cannot store links: refuse with a clear error instead of writing a tree whose libraries cannot load.

Both are the right calls, and both are currently proven only against a monkeypatched symlink_to.

Closing this for real is cheap if anyone wants it. The extraction tests do not need the backend stack or conftest.py, only pytest, and they run in well under a second:

python -m pytest studio/backend/tests/test_sd_cpp_install.py -k safe_extractall --noconftest -q

36 passed, 0.18s locally on a bare interpreter with nothing but pytest installed. A windows-latest leg doing exactly that would exercise the flatten fallback on a real host rather than a mock. I have not added it here, since it changes CI config on this PR and spends org queue time, which is a maintainer call rather than mine.

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.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 24, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 24, 2026
@unslothai unslothai deleted a comment from Imagineer99 Aug 24, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b5a5cd83db

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@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: 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".

Comment on lines +593 to +594
if depth > _MAX_LINK_DEPTH:
raise RuntimeError(f"symlink cycle in archive: {str(path.relative_to(base))!r}")

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 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member

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 sd-cli refusing to start. Three consecutive installs into the same managed root at each state, since install() merges rather than wipes and a fix that works once but eats the tree on reinstall is not a fix.

States: base fdf83cbd6, head b5d439299, merge feacc8934.

state pass links restored flattened ldd "file too short" sd-cli --help
base 1 0/10 10 yes rc=127
base 2 0/10 10 yes rc=127
base 3 0/10 10 yes rc=127
head 1 10/10 0 no rc=0
head 2 10/10 0 no rc=0
head 3 10/10 0 no rc=0
merge 1 to 3 10/10 0 no rc=0

Base loader error, which is the failure the issue reports:

sd-cli: error while loading shared libraries: .../build/bin/libwebpmux.so.3: file too short

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 sd-master-bfbef5b-bin-Linux-Ubuntu-24.04-x86_64-rocm-7.14.0.zip). If upstream ever stops shipping them the run would report VOID instead of quietly passing.

Why this only matters on AMD

Selection 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:

Linux x86_64  accelerator=rocm   via the upstream fallback
Linux AMD64   accelerator=rocm   via the upstream fallback

The Unsloth mirror publishes no ROCm asset, so a ROCm host falls through to upstream, and auto never resolves to rocm (Linux auto picks the plain CPU build). Every other asset, including all four Windows ones, both macOS ones, Linux CPU and Linux Vulkan, has zero symlink members, so the new code is skipped entirely and those trees extract byte for byte as before.

Not tested here

The claims above are bounded by one integrated GPU, on Linux, under ROCm:

  • windows: needs a Windows host; this runner is Linux
  • no_symlink_privilege: needs Windows outside developer mode
  • exfat_or_smb: needs a filesystem that refuses symlinks

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 windows-latest runner, which covers the flatten fallback but not the no-privilege condition itself.

@danielhanchen

Copy link
Copy Markdown
Member

Wanted: a run on a Windows AMD machine

Everything 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 symlink_to, and both are Windows-shaped:

  1. Windows outside developer mode, where creating a symlink is refused and the installer must flatten and finish, exactly as it did before this PR.
  2. A filesystem that refuses symlinks (exFAT, or SMB without unix extensions), where it must stop with a clear error instead of writing a tree whose libraries cannot load.

I have added check_windows_amd.py at the repo root as a temporary measure. It is marked temporary in its own docstring and should be deleted before merge.

The thing to know before running

No published Windows asset ships symlink members. I checked both over range requests: win-rocm has 3 members and 0 symlinks, win-cpu has 20 members and 0 symlinks. So installing the real Windows ROCm build will not reach the new code at all, and a report saying "installed fine on Windows" would not test what needs testing. The fallback has to be driven with a synthetic archive, which is what the script does.

Run it

git fetch origin pull/9270/head:pr-9270
git checkout pr-9270
python check_windows_amd.py

Two 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-network

It prints a markdown block starting at ===== paste everything below into the PR =====. Paste the whole thing, including the Host section, since which branch you exercised depends on whether your host can create symlinks at all.

What each section means

section what it establishes
Host Windows build, GPU, the install directory's filesystem, and whether this host can create symlinks. The last one decides which branch is live for you.
2 With symlink privilege, a chained libwebp.so -> .so.7 -> .so.7.2.0 is restored and reads back the real payload.
3 With privilege denied, Windows flattens and the install still finishes with sd-cli.exe present. On a non-Windows host the same section instead asserts a clear refusal, which is the other half of the design.
4 Confirms the published Windows assets still carry no symlink members.
5 The 36 extraction tests, run with --noconftest so they need only pytest and none of the backend stack.

The most valuable run

A Windows AMD box with developer mode OFF, which is the default for most users. On that host section 3 is not a simulation: symlink_to genuinely fails and the real fallback executes. If you also have an exFAT USB stick, a second run with --install-dir E:\... covers the other untested branch.

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

  • Section 3 FAIL on Windows: the install does not complete when links are refused. That is a genuine regression against pre-PR behaviour and blocks merge.
  • Section 2 FAIL with developer mode on: symlink restoration does not work on Windows.
  • Section 4 UNEXPECTED: upstream started shipping symlinks in a Windows asset, which makes the Windows path live rather than insurance.

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.

@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: 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".

Comment thread check_windows_amd.py Outdated
# 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.

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 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member

Windows AMD run: developer mode OFF

Ran check_windows_amd.py on the configuration called out as the most valuable one: a Windows 11 AMD host with developer mode OFF, so section 3 executed the real fallback rather than a monkeypatched one. symlink_to genuinely raised WinError 1314.

Host

  • OS: Windows-11-10.0.26200-SP0
  • Python: 3.13.13, machine AMD64
  • GPU: AMD Radeon(TM) 8060S Graphics (Strix Halo, gfx1151)
  • Install dir filesystem: NTFS (drive C:\)
  • Developer mode: OFF
  • Can create symlinks: False — OSError: [WinError 1314] A required privilege is not held by the client

Results

check outcome detail
2. links restored when privilege is available SKIP this host cannot create symlinks, so section 3 is the live path
3. Windows flattens and finishes when links are refused PASS raised=None, sd-cli.exe present=True, link member flattened to a regular file=True
4. win-rocm asset carries no symlink members PASS 3 members, 0 symlink members
4. win-cpu asset carries no symlink members PASS 20 members, 0 symlink members
5. extraction test suite FAIL 3 failed, 20 passed, 14 skipped, 117 deselected

Section 3 is the branch that needed proving and it is not simulated here. The installer flattened and finished, sd-cli.exe present. No regression against pre-PR behaviour on a no-privilege Windows host.

Run twice, identical both times (3s).

Section 5: the 3 failures are missing skip gates, not product bugs

The test file already has _can_create_symlinks(tmp_path) and 14 tests skip on it correctly with symlink creation needs privilege on this host (Windows non-dev-mode). These three do not have that gate:

  • test_safe_extractall_rejects_a_reserved_path_reached_through_a_directory_alias (L687)

  • test_safe_extractall_rejects_a_cycle_hidden_behind_a_directory_alias (L704)

    Both fail in fixture setup, at (target / "alias").symlink_to("real"), before _safe_extractall is ever called. They need the same gate as their neighbours.

  • test_safe_extractall_restores_symlink_members_on_reinstall (L3332)

    Asserts link.is_symlink(), which is false by design on a host without privilege — the Windows fallback flattens. Either gate it, or split it so the reinstall-idempotency half still runs and asserts the flattened shape instead.

Verified the third directly, outside pytest: two consecutive _safe_extractall passes over the same archive both leave build/bin/libfoo.so as a regular file containing b'libfoo.so.1', with build/bin/libfoo.so.1 holding the real payload. Idempotent, no error, exactly the documented zf.extract(member, target) fallback.

Two notes

  1. The flattened result is byte-for-byte the sd.cpp prebuilt installer flattens archive symlinks, breaking sd-cli on Linux (lib*.so: file too short) #9268 shape. It is safe only because section 4 holds. If upstream ever ships a symlink member in a Windows asset, this path produces the broken install silently rather than failing loudly. The sys.platform != "win32" branch above it raises; the Windows branch does not. Worth at least a comment at the zf.extract(member, target) line recording that section 4 is the load-bearing assumption.

  2. Not covered: the "filesystem refuses symlinks" branch. This host has only NTFS fixed disks, no exFAT stick or SMB share, so --install-dir could not exercise it. On win32 that refusal path is unreachable by construction anyway (the sys.platform != "win32" guard), so proving it needs a non-Windows host on a refusing mount rather than a Windows one.

Reproduction

git fetch origin pull/9270/head:pr-9270
git checkout pr-9270
python check_windows_amd.py

@danielhanchen

Copy link
Copy Markdown
Member

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 fixed

They 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 sys.platform to win32 and making symlink_to raise 1314: 3 failed, 20 passed, 14 skipped, the same split you saw. Pinning the platform mattered, since without it the non-Windows branch raises instead of flattening and a fourth test fails for the wrong reason.

Fixed in 3592dff:

  • The two directory-alias tests now carry the same _can_create_symlinks gate as their neighbours.
  • test_safe_extractall_restores_symlink_members_on_reinstall is split rather than just gated, as you suggested. The symlink half is gated; a new test_safe_extractall_reinstall_is_idempotent_without_symlink_privilege runs only where symlinks are unavailable and asserts the flattened shape, so a no-privilege host now gets real reinstall coverage instead of a skip. That matches what you verified by hand.

On the same spoofed host that reproduced your 3 failures: 22 passed, 18 skipped, 0 failed. Linux is 310 passed.

Your note 1

Agreed, and recorded at the zf.extract(member, target) line. I deliberately did not change the behaviour: an archive that would trigger it does not exist in either release repo, so making Windows raise would be hardening against an input the code never receives, and it would trade a completing install for a failing one on nothing but speculation. The comment now names section 4 as the load bearing assumption and says to revisit the branch rather than treat it as a fallback if a Windows asset ever ships a link.

Your note 2

Correct 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.

Separately

Codex flagged that a chain longer than the kernel allows installed and then ELOOPed. Reproduced: 41 hops installed, then OSError 40, Too many levels of symbolic links. _MAX_LINK_DEPTH = 40 was documented as what Linux allows but the walk permitted 41, so it was an off by one against its own rule. Fixed by counting hops followed rather than nodes seen; 40 still installs and reads back, 41 is refused.

check_windows_amd.py is removed now that it has been run. It remains at 7bcd7ab if anyone wants the exFAT case.

@danielhanchen

Copy link
Copy Markdown
Member

Re-ran on the same Windows AMD host at 3592dff

Same machine as the previous report: Windows 11 10.0.26200, AMD Radeon(TM) 8060S Graphics (Strix Halo, gfx1151), NTFS, developer mode OFF, so symlink_to genuinely raises WinError 1314 rather than being monkeypatched.

1. The three failures are fixed, confirmed on real hardware

python -m pytest tests/test_sd_cpp_install.py -k safe_extractall -q --noconftest -p no:cacheprovider
22 passed, 18 skipped, 117 deselected in 1.02s

That matches the 22 passed, 18 skipped, 0 failed reported against the spoofed host exactly, now measured where the platform is real rather than pinned.

2. The split works: the new test runs here rather than skipping

This is the part that mattered more than the gating, so it is worth showing explicitly:

test_safe_extractall_rejects_a_reserved_path_reached_through_a_directory_alias  SKIPPED
test_safe_extractall_rejects_a_cycle_hidden_behind_a_directory_alias           SKIPPED
test_safe_extractall_restores_symlink_members_on_reinstall                     SKIPPED
test_safe_extractall_reinstall_is_idempotent_without_symlink_privilege         PASSED

A no-privilege host now gets real reinstall coverage instead of three skips and a hole. Splitting rather than only gating was the right call — it is what my hand check had to stand in for last time, and it is now asserted in the suite.

3. Separately: the rest of this file has never passed on Windows, and it is not this PR

Running the whole file rather than the safe_extractall subset gives 23 failures. To check whether the PR caused them I ran the identical command on the PR's base commit fdf83cb, in the same venv:

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_extractall subset runs under system Python 3.13.13 with --noconftest, which is what makes it stdlib-only and portable. With conftest enabled, system Python errors all 157 on the backend stack (httpx and 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.

@danielhanchen

Copy link
Copy Markdown
Member

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 set

I ran the same full-file comparison on Linux with sys.platform pinned to win32 inside the installer module, base fdf83cb against 3592dff:

failures sets
your Windows host 23 each identical
pinned-platform Linux 22 each identical

Same conclusion from two directions, and the dominant cause matches exactly: 17 of mine are contained no sd-cli binary, against 17 of your 23.

The 22 against 23 is worth recording as the limit of the simulation rather than as noise. Pinning sys.platform leaves platform.system(), os.name and the path separators Linux-shaped, so a real Windows host finds one more than the spoof can. That is the second time this round that real hardware has found something a pin could not, the first being the three skip gates, and it is the argument for these runs existing.

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 _binary_names() cause, the note that studio-backend-ci.yml is ubuntu-only so this file has never run on Windows, and a suggested direction of building the fixture archives from _binary_names() rather than a literal sd-cli. Agreed it is out of scope here and not a blocker.

One thing recorded there rather than here: the safe_extractall subset needs only pytest and no backend stack, so a Windows leg for that subset is cheap, while a leg for the whole file needs the studio venv and is a larger commitment. Worth deciding separately from the fixture fix.

Where that leaves this PR on Windows

  • 22 passed, 18 skipped, 0 failed on a real no-privilege host, matching the pinned-platform prediction exactly.
  • The flatten fallback is exercised for real, not monkeypatched.
  • A no-privilege host now carries real reinstall coverage instead of a hole.
  • Still uncovered: a filesystem that refuses symlinks. Unreachable on win32 by construction, so it needs a non-Windows host on a refusing mount, and I am not claiming it from the Windows result.

FrancescoBrunoDev and others added 13 commits August 24, 2026 04:36
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.
@danielhanchen
danielhanchen force-pushed the fix/sd-cpp-symlink-extractall branch from 3592dff to bc1848d Compare August 24, 2026 04:37
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: bc1848d981

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 2921990 into unslothai:main Aug 24, 2026
52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sd.cpp prebuilt installer flattens archive symlinks, breaking sd-cli on Linux (lib*.so: file too short)

4 participants