Repository navigation
Serialise sd.cpp installs against the binaries they replace - #8274
Conversation
…ep binaries a bundle did not supply
… install can replace Five fixes from review: - The sweep ran before the malformed-bundle check, so an archive shipping no sd-cli deleted the working one and only then raised. That is the copy ensure_sd_cpp_binary keeps so a failed upgrade still leaves something to generate with. Refuse the bundle first. - _tree_reader now claims only for a binary inside the managed tree. An sd-cli from SD_CLI_PATH, UNSLOTH_SD_CPP_PATH, an in-tree build or PATH is one the installer cannot replace, so blocking it behind an unrelated download bought nothing. - A wait_for timeout is no longer treated as admission. The install still holds the tree at that point, and starting the binary it is replacing is the race this exists to prevent. - Re-resolve the engine inside the claim. An install that lands during the wait can move its sd-cli and sweep the copy resolved before it, leaving the cached path pointing at a file that is gone. - A sweep that cannot finish now raises SupersededBinaryError, and ensure_* no longer memoises that as a failed accelerator upgrade. The installer withholds the record so the next load retries; memoising suppressed the mismatch for the rest of the process and served the mixed tree instead. - installed_accelerator retires the memo only on a successful record read that disagrees. An unreadable record is not proof someone else rewrote it, and dropping the memo there hands the next selection the stale accelerator, which is a multi-GB reinstall on every load.
|
Round triaged. All six items were real; all six are fixed in 8756350, and I reproduced each one against 1be7c77 before touching it rather than taking the claim on faith.
Two of these are regressions this PR introduced rather than latent ones, and both come from the same widening. The old Three and four interact and are fixed as one decision. Refusing on timeout, on its own, would have turned an unrelated managed install into a hard failure for a generation running a user-supplied sd-cli. Scoping the claim to managed binaries first means the refusal can only ever hit a generation that really was about to execute out of the tree being replaced. Evidence that each item was live on 1be7c77:
Tests,
The +6 passes are the new tests. The 77 pre-existing lines are this sandbox's On the CI that reads red: every workflow on the previous head SHA was cancelled by a queue-wide flush, not failed. The one genuine red was |
Two more from review: - The H3 native path runs sd-cli out of the managed tree straight from video.py, outside the reader protocol, so a concurrent image-engine request saw no readers and could start a layout-changing install underneath it. It now takes the same claim, and if the binary it was loaded with is gone once the wait is over it says so rather than handing a missing path to a subprocess. - _discard_superseded_binaries sweeps sd-cli before sd-server, so it can remove the old CLI and then raise on the old server. Both ensure_* returned the fallback resolved before the install, which in that case names a deleted file. They now re-find, so the answer is a binary that exists, often the one the new bundle just extracted, or None.
|
Second round on this PR, two items, both real and both fixed in c109462.
The video one is an inconsistency I introduced by wrapping the one-shot image path and not this one, when it is the same sd-cli executing out of the same tree. It is slightly worse than described, too: The fallback one is the loose end of last round's Three tests: Tests,
The +9 across both rounds are the new tests. The |
Two more from review: - The partial-sweep raise happens before install()'s _make_executable, so a freshly extracted copy has no execute bit on POSIX and find_sd_cpp_binary only checks that the path is a file. Both ensure_* now put the re-found path through _usable_or_discard_managed, which probes it and, since it is ours, removes it when it cannot run so the next load reinstalls cleanly. - The H3 native guard checked only that the binary still existed. An install that lands during the wait can put its replacement at the same path, and that build is not the one ensure_h3_sd_cpp_binary vetted at load: a different accelerator, or one predating the H3 options, which aborts partway through a render. Compare (size, mtime_ns) captured before the wait instead, which covers deletion too and costs no subprocess.
|
Third round on this PR, two items, both real and both from my own previous fixes. Fixed in f115dff.
The first is exactly the ordering trap I fixed one round earlier, now on my own code: The second is the likelier half of a case I had already accepted: an install replacing the binary at the same path, which is what a same-layout bundle for a different accelerator does. I took the identity suggestion rather than the re-probe one, because it costs no subprocess per image and is strictly broader, catching a replacement that would pass both an H3-capability and an accelerator probe and still not be the build this runtime was checked against. Reload rather than re-resolve remains deliberate: the video runtime's engine is committed at load, unlike the image path's. Three tests: Tests, |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f115dff613
ℹ️ 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 _may_own: | ||
| _discard_superseded_binaries(target, supplied) |
There was a problem hiding this comment.
Coordinate standalone installs with active runtimes
The new reader/writer admission state exists only in sd_cpp_backend.py, while the documented python studio/install_sd_cpp_prebuilt.py ... entry point calls install() directly; a second backend process sharing the same managed root also has independent state. If either performs a layout-changing install while another process is running a managed CLI or server from a path absent from the new archive, this sweep can unlink that executable without seeing its reader: Linux leaves cached paths missing for subsequent requests, while Windows can raise partway through and leave a mixed tree. Protect the replacement with an interprocess lock/runtime check that the standalone installer also participates in.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one in this PR, and I want to be clear that it is scope rather than disagreement: the gap you describe is real. python studio/install_sd_cpp_prebuilt.py calls install() directly and a second Studio process has its own admission state, so neither sees the other's readers.
Three reasons it does not belong here. It is pre-existing, not introduced: before this PR there was no admission at all, in-process or otherwise, so this change strictly narrows the window rather than opening one. It is not a small fix but a protocol: where the lock file lives relative to a root the user can move, what happens to a stale lock after a crash or a kill, and POSIX flock against Windows mandatory locking, which behave differently enough that getting it wrong turns a rare race into a Studio that refuses to install at all. And a half-considered interprocess lock is worse than none, because it reads as a guarantee.
The right shape is probably a lock file at the managed root that install() itself takes, so the standalone entry point participates by construction rather than by remembering to. That is a separate change with its own tests, and I would rather do it properly than bolt it onto this one.
…and let a cancel out of the wait Four more from review: - The H3 binary identity was captured at generation time, so an install that landed between the load and a generation was compared against itself. MiniMaxH3NativeRuntime now records it where ensure_h3_sd_cpp_binary vetted the file, and every generation compares against that. A runtime with no recorded identity is still held to the existence check rather than refused. - The asset download runs for minutes with nothing claiming the tree, so an install can sweep the server binary between layouts after _resolve_backend picked it. The path is re-resolved before the server is constructed, and the load drops to the one-shot fallback when nothing runnable survived. - The install wait held the generate lock uninterruptibly, so a cancel or unload during it read as a hung Studio for up to 900s while nothing had started. The wait now takes the request's cancel event and re-checks on a short tick, since nothing notifies the condition on cancel. - An interprocess lock for the standalone installer is not in this change; the gap is real and pre-existing and wants its own design.
|
Fourth round on this PR, four items: three taken, one declined on scope. Fixed in 815beb7.
The identity one is the sharpest of the four: it makes last round's guard nearly useless, because two reads taken after an in-place replacement agree with each other while agreeing with nothing that was ever vetted, and the load-to-generation window is the wider one. The identity is now pinned where the binary was checked, and the regression test replaces the bytes BEFORE the generation, which is precisely where the old comparison passed. The cancellation one is the worst-feeling: nothing has started, and the UI is unresponsive for up to fifteen minutes because the generate lock is held inside an uninterruptible wait. The tick matters as much as the event, because On the declined one, to be explicit that it is scope and not disagreement. The standalone installer and a second Studio process genuinely do not see each other's readers. But it is pre-existing rather than introduced (before this PR there was no admission at all, so this change narrows the window), and it is a protocol rather than a fix: where the lock lives relative to a root the user can move, what happens to a stale lock after a crash, and POSIX Four new tests, twelve across the four rounds. Tests, |
… video cancel sentinel Four more from review: - ensure_h3_sd_cpp_binary vetted the file and the identity was taken afterwards, so an install landing between the two made an unchecked replacement the recorded identity. The re-vet and the stat now happen under one reader claim, with the H3 --help probe repeated inside it. - Re-resolving the server after the asset download did not claim the tree, so an installer that had already passed its in-use check could sweep the executable between the re-read and the start. The re-resolve, the construction and publishing _pending_server all happen under the reader now, which hands over to _tree_in_use with no gap. - A cudart download, digest or extract failure after the sweep left the old binaries gone while reporting something that is not a SupersededBinaryError, so the accelerator was memoised and the caller kept deleted paths. The cudart fetch moves ahead of the sweep, and everything from the sweep onwards is reported as an incomplete replacement. - The shared reader raised the image cancellation sentinel, which the video path does not recognise, so a cancelled H3 render surfaced as a failure. The message is the caller's now.
|
Fifth round on this PR, four items, all four real and all four fixed in f8c6e27.
Three of these are follow-ons from my own previous fixes, which is worth saying plainly rather than presenting as four independent catches. The identity has needed tightening three rounds running, each version closing a wider window and leaving a narrower one; this one closes it properly by doing the vetting and the capture under a single claim, so the build that answers The cudart one is the same failure shape as the last two rounds reached by a different route, and it is fixed twice on purpose: moving the fetch ahead of the sweep removes the window rather than handling it (nothing cudart writes is an sd-cli or an sd-server, so the sweep cannot take it), and reporting everything from the sweep onwards as Five new tests, seventeen across the five rounds. Notably Tests, |
…lerator Two gaps on the same theme, that a decision made before a slow step is acted on after it. _server_binary_runnable can sit for 20s revalidating, and an unload arriving in that window finds no _pending_server to stop, so the load went on to spawn sd-server anyway and held the device for the whole start() timeout. The recheck now happens inside the same lock that publishes, so an unload either stops this server or is seen here and cannot fall between the two. The one-shot path re-resolves sd-cli per image, so an install landing mid-batch is adopted silently. Existence is not identity: that install may be for a different accelerator, while the state's device and offload flags describe the build the load committed to. Record the accelerator at load and refuse a mismatch, as the server path already does.
--list-devices spawns the managed sd-cli, so it needs the same reader claim the run takes. Unclaimed, an install started by another in-process load sees no reader and extracts over the executing binary: Windows fails on the locked file, Linux can leave the replacement half-written. The claimed recheck later in the load compares answers and cannot undo damage this first probe already allowed.
|
Picked this up and pushed the three open items. Correcting my own earlier framing first: I had these noted as three P1s, and that was wrong. Exactly one is a P1, and two of the three are P2. Recheck cancellation before publishing the server (P1)Right, and the 20 second figure is what makes it matter. The recheck now happens inside the same lock that publishes, so an unload either stops this server or is seen here; it cannot fall between the two. On the cancelled path Regression test asserts the process is never spawned. Removing the guard, it fails with Revalidate the accelerator after re-resolving the CLI (P2)Also right, and worth stating why the existing machinery cannot catch it: generation calls
Two tests, the refusal and the control. The control matters here: without it a regression that reloaded on every image would look exactly like a working guard. Claim the managed tree before running accelerator probes (P2)Correct, and the comment sitting above that line said "Re-checked under the reader claim", which is true of the recheck and was not true of the first probe. Now under Not addressed, and whyCoordinate standalone installs with active runtimes. This one is real and I am leaving it. The admission state is per process, so Treat different-layout extraction failures as replacements was already handled by Commits and tests
|
The fallback resolved an sd-cli, used it only to answer "is one usable", and then threw it away, leaving the local engine at the server path's None. state.sd_accelerator was recorded off that None, so the first one-shot generation, which re-resolves sd-cli and reads its real accelerator, saw a mismatch and refused the very binary the load had just fallen back to: the load reported success and then could not generate at all. Resolve once and keep it, in both fallback paths. The up-front one resolved twice as well, which can answer with two different binaries if an install lands between the two calls.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b2d0e43366
ℹ️ 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 binary and ( | ||
| current_identity is None | ||
| or (binary_identity is not None and current_identity != binary_identity) | ||
| ): |
There was a problem hiding this comment.
Reject a missing load-time binary identity
When _sd_cli_identity() fails during load and stores None—for example because of a transient stat or filesystem error after the subprocess probes succeeded—this condition deliberately skips the identity comparison on every generation. A later in-place replacement is therefore treated as vetted as long as the path is readable, allowing a build for another accelerator or one without the required H3 behavior to run under the already-committed runtime. Refuse the load when its identity cannot be captured, or treat a missing recorded identity as a mismatch here rather than silently disabling the protection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining this one, and the degrade is deliberate.
binary_identity has exactly one production writer, video.py:1268. It runs inside the tree reader claim, after engine.version() and sd_cpp_supports_minimax_h3(binary) have both executed that very file as a subprocess, and after the not binary guard above has already raised. So the only way it lands as None is for Path(binary).stat() to raise OSError on a file this thread just ran two processes out of, while holding the claim that keeps installs off it. That is not a state a real session reaches; there is no legitimate input that produces it.
Refusing the load on it would make things worse, not safer: it converts a stat hiccup on a fully vetted binary into a failed load of a model that passed every real check seconds earlier, and the H3 load is minutes of downloading to redo. Treating None as a mismatch at generation time has the same cost with a worse shape, since it fails after the load reported success.
What the check does keep in that state is the part that still has an answer: current_identity is None (the binary is gone or unreadable now) still refuses, unconditionally. So the runtime is held to the question it can answer and not to the one it cannot, which is what the comment at that condition says.
|
@codex review |
1 similar comment
|
@codex review |
The one-shot pin added in 6c0f580 is taken up front, next to the server pin, which is right for a load that resolves to one-shot there. It is wrong for the load that starts in server mode and drops to one-shot later. There are two such fallbacks. The start-failure one re-pins off the engine it resolved, but the other one, taken when the re-resolution under the reader claim finds sd-server no longer usable after the asset download, does not: it swaps in an sd-cli from _resolve_engine and leaves engine_accelerator holding the value sampled while engine was still None. The refusal below then compares a real accelerator against None and fails the load every single time, so the documented "sd-server is no longer usable after the asset download" fallback could never complete. Same shape as the bug b2d0e43 fixed on the sibling path. Pinned where the engine is resolved, inside the claim, so it is vetted at the moment it is recorded. test_server_unusable_after_the_download_keeps_the_engine_the_fallback_resolved drives the real _run_load with a server that is runnable up front and unusable by the re-check, and asserts the load lands in one-shot with the accelerator of the binary it fell back to and can generate on it. The accelerator stub answers for one tree, so the only refusal it can produce is the pin being read off the wrong engine. Mutation checked: dropping the re-pin fails with "the fallback was refused: ... replaced by an install for a different accelerator".
|
Codex Review: Didn't find any major issues. Another round soon, 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". |
|
@codex review |
1 similar comment
|
@codex review |
|
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". |
One conflict, in test_video_backend.py, and it is additive on both sides: this branch appended the two-partition H3 denoiser cases at the end of the file while #8274 appended its managed-tree admission cases in the same place. Kept both. 214 passed in that file, 642 across the video, H3 and sd.cpp suites.
Follow-up to #8208, which merged at b4cdeff without this last commit. Three findings from the tail of that PR's review, all in the same area: an install replaces the binaries in the managed sd.cpp tree, so it must not run while anything is executing out of it, and the tree it leaves behind must match the record it writes.
An install could still start under a running generation
_managed_tree_in_use()was a point-in-time sample taken beforeinstall(), and an install spends seconds to minutes downloading before it extracts. A one-shot generation admitted inside that window launches the verysd-clithe extraction then overwrites: ETXTBSY on Linux, a sharing violation on Windows, or a half-replaced tree.generate()does not take_install_lock, so nothing connected the two decisions.Admission is now one decision instead of a sample, over a
_tree_statecondition:_tree_claimed_for_install), and the claim is held across the download AND the extraction, not just the check;sd-cliruns are readers (_tree_readeraroundengine.generate);No cycle with the existing locks: readers never take
_install_lock, the writer never takes_generate_lock, and neither holds_tree_stateacross the long operation.A bundle left behind binaries it did not supply
Extraction MERGES into the tree, so a bundle whose layout differs from the previous one leaves the old accelerator's executables in place, and
_layout_candidatesprefersbuild/binover the prebuilt's versioned subdirectory, so the stale copy keeps winning. The record then names the new accelerator,_accelerator_changedtrusts it, and a CUDA request serves the old CPU build indefinitely. Nothing downstream repairs it either: a leftover binary is still runnable, so_usable_or_discard_managedkeeps it._archive_binary_pathsnow reads from the archive's member list where each executable lands, and_discard_superseded_binariesremoves every managedsd-cliandsd-serverthis bundle did not write, at any path, before the record is committed. A removal that fails raises, which withholds the record so the next load retries rather than trusting a tree that does not match it.The install-record memo was too broad
The memo added in #8208 covered an unwritable record, but it also outranked a record another process had legitimately updated. It is now written ONLY when the write actually failed, keyed on the record content seen at that moment, so it speaks for exactly the stale file it could not replace: once anything else rewrites that file the snapshot no longer matches, the memo is dropped, and the file wins again. A successful write retires any earlier memo.
Tests
test_a_generation_cannot_start_inside_the_install_windowblocks a real thread mid-install and releases it;test_an_install_stands_down_while_a_generation_is_runningcovers the other direction. Plustest_a_bundle_drops_the_binaries_it_did_not_supply,test_a_bundle_keeps_every_binary_it_wrote,test_an_external_record_update_retires_the_memoandtest_a_successful_record_write_retires_an_earlier_memo.Full studio backend suite run against a clean
origin/mainbaseline: identical FAILED/ERROR line sets, no new failures. The prebuilts themselves were verified on a CUDA host as part of #8208: both Linux assets match the published sha256 manifest, and the CUDA build brings upggml_cuda_initon a real card.