Skip to content

fix(install): restore symlink members when extracting sd.cpp prebuilts - #9487

Closed
yzxcj797 wants to merge 20 commits into
unslothai:mainfrom
yzxcj797:fix/sd-cpp-symlink-extract-9268
Closed

yzxcj797 wants to merge 20 commits into
unslothai:mainfrom
yzxcj797:fix/sd-cpp-symlink-extract-9268

Conversation

@yzxcj797

Copy link
Copy Markdown
Contributor

Summary

What

_safe_extractall in studio/install_sd_cpp_prebuilt.py now recreates symlink members after zipfile.extractall: members carrying the Unix symlink mode in external_attr are re-created with symlink_to, and the link target is resolved through the same containment guard the member paths already use — a link whose target escapes the install dir raises unsafe symlink in archive instead of writing outside it.

Why

#9268 — CPython's zipfile.extractall does not restore symlinks: it writes each symlink member's data (the link-target text) as a regular file. Upstream sd.cpp release zips ship libggml*.so, libwebp*.so, libwebpmux*.so, libsharpyuv*.so as symlinks, so after install libwebpmux.so.3 is a 19-byte file containing the text libwebpmux.so.3.1.2, and sd-cli fails with error while loading shared libraries: ... file too short, surfacing as video.load_failed: stable-diffusion.cpp could not be installed or started for MiniMax-H3.

Same shape as the reporter's suggested fix, with the containment check kept in one loop and applied to both member paths and link targets.

Testing (studio/backend/tests/test_sd_cpp_install.py):

  • New test_safe_extractall_restores_symlink_members: builds a zip with a real member plus a symlink-mode member (the exact shape CPython writes when zipping a symlink), extracts, asserts libwebpmux.so.3 is_symlink(), its readlink() names the real library, and its size equals the real file's — the pre-fix behavior was a tiny text file. Runs on CI's Linux runners; skips on hosts where symlink creation needs privilege (Windows non-dev-mode — my Windows host skips it locally, the same CI-gating pattern as the whisper/llama installer suites).
  • New test_safe_extractall_rejects_escaping_symlink: a ../../outside.so link target raises unsafe symlink and nothing lands outside the install dir — this one runs everywhere (the check precedes any link creation) and fails on the pre-fix code (no such rejection existed).
  • Existing safe_extractall traversal/normal-members tests unchanged: 3 passed + 1 skipped locally.

Fixes #9268

CPython's zipfile.extractall writes each symlink member's payload (the
link-target text) as a regular file, so every lib*.so link in an
upstream sd.cpp release zip landed as a 19-byte text file — sd-cli
then dies with 'error while loading shared libraries: libwebpmux.so.3:
file too short' and MiniMax-H3 reports video.load_failed (unslothai#9268).

_safe_extractall now recreates symlink members after extraction, with
the link target resolved against the same containment guard the member
paths use: a link escaping the install dir raises instead of writing
outside it.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed _safe_extractall in studio/install_sd_cpp_prebuilt.py still calls plain extractall, so the lib*.so links in the Linux prebuilt zips land as text files and sd-cli cannot start. Will get this reviewed.

Extraction merges into the managed tree, so install() re-extracts over the links a
previous install wrote. Resolving the member destination followed those links, so
extractall wrote the link text through them into the real library and the restore
loop then replaced that library with a link to itself. A second install of the same
bundle turned every lib*.so in the ROCm archive into a cycle and sd-cli exited 127;
a third could no longer extract at all.

- keep the lexical member destination, resolving only for the containment check
- skip symlink members in extractall so their payloads are never written
- validate every member path and link target before the first write
- reject absolute, drive-relative, empty, NUL-bearing, oversized and cyclic targets
- require create_system == 3 before reading external_attr as a Unix mode
- fall back to the flattened member when symlink_to has no privilege (Windows)
- compare binary paths lexically now that the tree can hold symlinks
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this, the diagnosis in #9268 is exactly right and the first install is fixed by it. I pushed a follow-up commit to your branch because re-extracting over the tree the fix itself created was destroying it.

What I hit

install() merges into the managed directory, it never wipes it, so a retry, a version bump or an accelerator switch re-extracts over the links the previous install wrote. dest = (base / member.filename).resolve() follows those links, so dest became the real library rather than the link. Two things then went wrong at once: extractall opened the link path "wb" and wrote the 19-byte link text straight through into the real ELF, and the restore loop unlinked that real library and put a link to itself in its place.

Measured on the exact archive from the issue, sd-master-bfbef5b-bin-Linux-Ubuntu-24.04-x86_64-rocm-7.14.0.zip (37 members, 10 symlinks, sha256 e6f60a09...):

pass result
merge base 10 flattened 12-22 byte files, ldd: file too short, sd-cli --help exit 127
this PR, 1st install all 10 links restored, ldd clean, sd-cli --help exit 0 (commit bfbef5b)
this PR, 2nd install all 15 lib entries are ELOOP cycles, real payloads gone, exit 127
this PR, 3rd install extractall itself raises OSError: [Errno 40], the tree cannot be extracted into again

That last row is the one that worried me most. _usable_or_discard_managed deletes an unrunnable managed sd-cli and reinstalls into the same directory, which is exactly this path, so the tree would have gone from a one-shot file too short into a state that reinstalling could no longer clear.

What the follow-up changes

  • Keep the lexical member destination and resolve only for the containment check. This is the load-bearing line.
  • Skip symlink members in extractall entirely, so a link payload is never materialised and never written through a surviving link.
  • Move link target validation above extractall. Previously an archive with a good sd-cli followed by an escaping link overwrote the working binary and then raised, so a rejected archive still replaced the install it was rejected over.
  • Reject absolute, Windows drive-relative (C:outside.dll, which Win32 resolves against that drive's cwd), empty, NUL-bearing, self-referential and cyclic targets, and cap the payload at PATH_MAX. zf.read holds it in memory, and a 2 MB zip could expand to 2 GB of link payloads before any check ran.
  • 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, which is also what the new test models.
  • Catch OSError from symlink_to and fall back to the flattened member. On Windows outside developer mode the old code raised after having already deleted the extracted file, leaving the tree worse than before the PR.
  • _archive_binary_paths and _discard_superseded_binaries now compare lexically. They resolved through the tree, which was safe only while the tree held no symlinks, and this PR is what changes that.

Chained links keep working, which matters because upstream ships them: libwebpmux.so -> libwebpmux.so.3 -> libwebpmux.so.3.1.2.

Verification

studio/backend/tests/test_sd_cpp_install.py is at 131 passed. I added cases for 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. The two tests you added both still fail against the merge base, so they remain a real regression proof; I only replaced assert link.stat().st_size == real.stat().st_size with a content check, since stat() follows the link and that assertion could not fail once is_symlink() had passed.

Beyond the suite I ran a simulation matrix comparing the merge base, this PR as submitted, and the follow-up across 69 checks: asset selection over 80 platform x accelerator x arch combinations (identical in all three, nothing about selection changed), every real release archive, repeated and upgrade installs, 18 adversarial archives, an install directory under a symlinked parent, the downstream binary sweep, and install() end to end three times against a fake release. Every check passes on the follow-up. The 17 that fail are all the PR-as-submitted column and are the bug above. Python 3.9 through 3.13 all pass the idempotency check.

Backwards compatibility: the Linux CPU, Linux Vulkan and macOS arm64 assets carry no symlink members at all, and their extracted manifests are byte identical between the merge base and this branch, so those installs are untouched. Only the Linux ROCm asset has symlinks, which is why this surfaced on an AMD host. Existing installs are covered too: a flattened tree from an older Unsloth is repaired, and a tree a user repaired by hand following the issue survives.

The test_video_* failures on this branch are pre-existing and unrelated, they reproduce identically without these two files changed. Worth rebasing on main before merge, and the Python 3.13 Backend CI leg was cancelled at its 45 minute limit rather than passing, so that one needs a re-run.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The pre-extraction pass validates every member before the first write, but it runs
while no archive link exists yet. An earlier member can then redirect a later one's
parent: a -> . followed by a/out -> ../outside_dir makes a/out/victim resolve outside
the install dir, so the unlink and symlink_to replaced a file the archive never owned.

Re-resolve the parent and the target immediately before each link is created, and
refuse a parent that no longer resolves to itself.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
The creation-time re-check refused any parent that did not resolve to itself, which
also refused a managed tree that symlinks one of its own subdirectories, with no
security gain: a write through a link that stays inside the install dir cannot escape,
and a parent pointing outside is already refused by the member-path check.

Ask both the parent and the target whether they still resolve inside the install dir.
The redirected-parent archive is still rejected, one member earlier than before.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Three holes reachable through the merge that install() performs:

extractall opens each destination "wb" and follows a link a previous bundle left
there, so a name shipped as a link by one bundle and as a regular file by the next
lost its member's bytes into the file the old link pointed at. An accelerator switch
lands exactly there, since upstream ships lib*.so as links and the mirror ships plain
copies. Stale links at any destination this archive writes now go first.

The cycle check only walked archive-to-archive edges, so an archive edge could close a
loop with a link the previous bundle left. The created link is now resolved and undone
if it loops, so the retry does not meet the same pair.

A symlink member at the install-record or ownership-marker path made
_write_install_record follow it and overwrite its target while the record still read
back, reporting a corrupted install as successful. Those paths are now refused.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits August 23, 2026 07:38
Making the binary comparison fully lexical fixed a bundle that ships sd-cli as a
symlink, but broke a managed tree that symlinks one of its own subdirectories:
rglob reports the extracted binary under the real directory while the member path
still spells it through the link, so the sweep deleted the executable the bundle had
just supplied and finalisation then found no sd-cli, on every retry.

Both halves are needed, so compare on the parent resolved plus the final component
untouched, on both sides.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The creation-time check stopped the outside write, but it fired half way through:
extractall had already replaced the working binary and the first link had been
created before the second one was rejected, so a refused archive left a mixed tree
and retrying it repeated the same partial replacement.

No member may sit under a directory the same archive turns into a link, and that is
decidable from the member list alone. Refusing it in preflight puts the rejection back
before the first write, so the archive changes nothing at all.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
Path.resolve(strict = True) raises RuntimeError on a loop up to 3.12 and OSError only
from 3.13, so the except OSError branch never ran on the versions the repo still
supports: the loop escaped with the wrong message and, worse, the half this archive
had just created was left on disk for the retry to meet again.

os.stat reports ELOOP as an OSError on 3.9 through 3.13 alike, so switch to the raw
errno. Checked on all five interpreters: the cycle is rejected and our link removed on
every one. Also lift the check out of the symlink_to try, so an unrelated stat error
cannot be mistaken for a missing symlink privilege.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
pre-commit-ci Bot and others added 2 commits August 23, 2026 08:25
The list tracking every destination had drifted to holding tuples while still annotated
as paths, and the ancestor walk compared with str.startswith, which treats /a/bc as
sitting under /a/b. Neither could bite today, since the containment check above keeps
every destination under base, but both are traps for the next reader.

Normalise once where the destination is built, then compare Paths throughout and walk
dest.parents instead of slicing strings.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A member path is not where its link lands. A directory link a previous bundle left
behind redirects it, and every preflight check here compared names instead.

alias -> . makes a member named alias/<record> land on the install record itself, so
the reserved-path comparison missed it, symlink_to created the link at the real record
path, and _write_install_record followed it and overwrote sd-cli with JSON while the
record still read back as a valid install.

alias -> real makes members alias/a -> b and real/b -> a one cycle, not two unrelated
lexical paths, so the walk terminated and an ELOOP layout installed clean.

The directory-collision check ran after extractall, so an archive refused for it had
already replaced the working binary.

_plan_key resolves the parents and leaves the leaf alone, skipping links this archive
replaces since they are gone before anything is written, and the reserved, collision
and cycle checks all key on it. Everything is decided before the first write.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

a -> a/x never reaches a second node, so exact-node repetition never fires, but
resolving a walks a again and the install lands with an ELOOP library the loader
cannot read and the runtime probe would discard and refetch on every load. Anything
under the link it came from is a loop.

Refusing to flatten off Windows was still being decided at creation time, so a
filesystem that rejects symlinks (EPERM on exFAT and on SMB without unix extensions)
took the new binary before it raised, and the upgrade lost the install it was
replacing. Probe once, alongside the other preflight checks, so an upgrade that cannot
finish leaves the previous one runnable.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

This comment was marked as resolved.

extractall DROPS a .. component instead of cancelling the one before it, so
'a/../victim' is 'a/victim' to it. The guard normalised the name first and cleared a
path zipfile never writes to, and with a link at 'a' left by a previous bundle the
member landed outside the install tree entirely. No release ships '..', so refuse it.

Two link members can also point through each other's directories: a -> b/x with
b -> a/y is one cycle, but neither link exists on disk while the graph is built, so
following only on-disk parents missed it and an ELOOP layout installed clean. Parent
resolution now follows the archive's own links, bounded at the depth the loader gives
up at, and a runaway is the cycle it describes.

The three sweep tests spelled the binary the POSIX way, so they failed on a Windows
runner where _binary_names() spells it sd-cli.exe. They ask the host now.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
pre-commit-ci Bot and others added 2 commits August 23, 2026 09:11
…ts on it

The ownership marker is already there before extraction on any root Studio owns, so
sd-cli -> .unsloth-studio-owned resolves to a file, _locate_sd_cli reports the empty
marker as the executable, and the install claims success. Only the destination was
being compared against the reserved paths; the target is now resolved the same way,
so a chain that ends on one is refused too.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: e751b62c02

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

Copy link
Copy Markdown

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

Reviewed commit: 097cb9341a

ℹ️ 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Closing this in favour of #9270, which is the original report and the original fix for #9268, and which I have brought up to parity rather than landing a second PR over it.

Nothing here is lost. The hardening from this branch is now on #9270: the pre-write ordering, the create_system gate, the target shape and containment rules, the PATH_MAX cap, cycle detection, the reserved installer paths, the filesystem probe, the Windows flatten fallback, and the lexical binary sweep. The test cases came across with it.

Thanks for the work on this, it is what made the failure modes in the naive fix visible, and the reinstall case in particular was worth catching before this shipped.

@danielhanchen

Copy link
Copy Markdown
Member

Validated this on a real gfx1151 ROCm host (AMD DevLab runner, Linux, HIP 7.13.99004) against the actual release asset rather than a synthetic zip. Confirmed.

Before running any of this PR's code I checked the three Linux assets of master-813-bfbef5b by reading their central directories over range requests:

asset members symlink members
...x86_64-rocm-7.14.0.zip 37 10
...x86_64-vulkan.zip 36 0
...x86_64.zip (CPU) 35 0

So the defect is specific to the ROCm build, which is consistent with #9268 being reported from ROCm hardware.

Then installed the real asset (sha256 e6f60a096ba31c13...) three times into the same managed root, at the merge base, this PR's head, and the GitHub merge result. Only the download boundary was stubbed; asset selection, containment, extraction, the sweep and the install record all ran for real.

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

The merge base reproduces the reported failure exactly:

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

and the flattened members are the shape the issue describes, for example libsharpyuv.so as 16 bytes of the text libsharpyuv.so.0. At the head all ten are real symlinks whose bytes equal their targets, target hashes unchanged across all three installs, no ELOOP. Checked with is_symlink(), readlink(), resolve(strict=True) containment and byte comparison rather than stat().st_size, since that follows the link and cannot fail.

Backend suite on the same host: 116 passed at the base, 148 passed at the head.

Two notes for reviewers, neither blocking:

  • The diff is considerably larger than "recreate symlink members": it also adds cycle detection across the prospective link graph, reserved installer path guards, directory collision checks, a filesystem symlink capability probe and a Windows flattening fallback. Worth knowing when budgeting review time.
  • Things this run cannot speak to: Windows without developer mode, and filesystems that refuse symlinks (exFAT, SMB without unix extensions). Both are mock only here.

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)

2 participants