Skip to content

Serialise sd.cpp installs against the binaries they replace - #8274

Merged
danielhanchen merged 28 commits into
mainfrom
sd-cpp-install-tree-admission
Aug 10, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
sd-cpp-install-tree-admission

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 before install(), and an install spends seconds to minutes downloading before it extracts. A one-shot generation admitted inside that window launches the very sd-cli the 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_state condition:

  • installs are writers (_tree_claimed_for_install), and the claim is held across the download AND the extraction, not just the check;
  • one-shot sd-cli runs are readers (_tree_reader around engine.generate);
  • an install that finds a reader stands down and retries on a later load, and a generation that arrives mid-install waits, logging why, with a timeout so a wedged install cannot hang generation forever.

No cycle with the existing locks: readers never take _install_lock, the writer never takes _generate_lock, and neither holds _tree_state across 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_candidates prefers build/bin over the prebuilt's versioned subdirectory, so the stale copy keeps winning. The record then names the new accelerator, _accelerator_changed trusts 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_managed keeps it.

_archive_binary_paths now reads from the archive's member list where each executable lands, and _discard_superseded_binaries removes every managed sd-cli and sd-server this 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_window blocks a real thread mid-install and releases it; test_an_install_stands_down_while_a_generation_is_running covers the other direction. Plus test_a_bundle_drops_the_binaries_it_did_not_supply, test_a_bundle_keeps_every_binary_it_wrote, test_an_external_record_update_retires_the_memo and test_a_successful_record_write_retires_an_earlier_memo.

Full studio backend suite run against a clean origin/main baseline: 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 up ggml_cuda_init on a real card.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

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.

# Item Verdict What landed
3744591902 Validate the replacement CLI before deleting the working one Correct The sweep is gated on supplied actually containing an sd-cli, so a malformed bundle is refused before anything is removed.
3744591899 Do not admit readers when the install wait times out Correct A wait_for timeout is now a refusal with a clear message, not admission.
3744591905 Limit tree readers to managed binaries Correct _tree_reader takes the binary and only claims when is_managed_binary is true.
3744591896 Refresh the CLI path after waiting for installation Correct The engine is re-resolved inside the claim, per image, so a batch that releases between images is covered.
3744591909 Retry after failing to remove a superseded binary Correct The sweep raises SupersededBinaryError and both ensure_* skip _note_failed_upgrade for it, while ordinary failures are still memoised.
3744591906 Preserve the memo when the record cannot be read Correct _raw_install_record returns Optional[str]; None is "cannot tell", and only a successful read that disagrees retires the memo.

Two of these are regressions this PR introduced rather than latent ones, and both come from the same widening. The old _discard_stale_sd_server only ever removed sd-server, so nothing could delete a working sd-cli: that is what made the malformed-bundle ordering safe and what made a cached engine path safe across a wait. _discard_superseded_binaries removes every managed binary the bundle did not write, at any path, which puts both in range.

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:

Item Observed before the fix
no-cli bundle install() raises "contained no sd-cli" and build/bin/sd-cli is already gone: FileNotFoundError reading it back
timeout reader admitted after the full wait with _tree_installing = True, _tree_readers = 1
unmanaged binary _tree_reader takes no binary argument at all, so every run waits
stale engine after the sweep, the engine _generate_oneshot would launch still names the deleted path
failed-sweep memo _failed_accelerator_upgrades == {'cuda'} and _accelerator_changed(cli, 'cuda') == False
unreadable record installed_accelerator returns None on the first unreadable read, dropping the memo

Tests, studio/backend/tests/ on CUDA_VISIBLE_DEVICES=0,1, same mask both sides, excluding the three collection-error files:

1be7c77 (before) 8756350 (after)
result 62 failed, 20068 passed, 99 skipped, 15 errors 62 failed, 20074 passed, 99 skipped, 15 errors
FAILED/ERROR line set 77 lines the same 77 lines, byte for byte

The +6 passes are the new tests. The 77 pre-existing lines are this sandbox's huggingface-hub 1.27 against a transformers pinned to <1.0, not the PR. test_sd_cpp_install.py + test_sd_cpp_backend.py + test_sd_cpp_engine.py together: 203 passed, 0 failed.

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 Cross-platform parity, and it is test_installer_profile_hardening.py PSModulePath assertions, which fail identically on fix-macos-launcher-symlink-and-uninstall-scope, a branch with nothing in common with this one except that it also touches installer paths. That makes them pre-existing on main and surfaced only by the path filter, so I am not chasing them here. Separately, the two tests/test_diffusion_training.py diffusers-absent failures on the CPU Python matrix are inherited from main and fixed by #8281.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Second round on this PR, two items, both real and both fixed in c109462.

# Item Verdict What landed
3745379755 Protect managed video runs with the tree reader Correct _generate_h3_native takes _tree_reader(engine.binary) around generate_video.
3745379759 Revalidate the fallback after a partial tree sweep Correct Both ensure_* re-find on an incomplete replacement instead of returning the pre-install value.

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: _managed_tree_in_use() reads the image backend singleton, so a running H3 video generation was invisible to the install decision from every direction, not just through the reader count. The claim closes it both ways, since holding it makes _tree_claimed_for_install stand down. If the binary the runtime was loaded with is gone once the wait is over, it now says so and asks for a reload rather than handing a missing path to a subprocess; re-resolving mid-generation is not available here the way it is for images, because the video runtime's engine is committed at load.

The fallback one is the loose end of last round's SupersededBinaryError fix. _binary_names() puts sd-cli first, so the sweep can remove the old CLI and then raise on the old server, and both ensure_* were handing back a fallback resolved before the install: a path that no longer exists. They re-find now, so the answer is a binary that exists (often the one the new bundle just extracted) or None. The no-memoise behaviour is unchanged, so the next load still retries the sweep.

Three tests: test_a_managed_h3_native_run_holds_the_install_off (reader count 1 inside the run, and an install decided at that moment refused), test_an_unmanaged_h3_native_run_takes_no_claim, and test_a_partial_sweep_never_returns_the_file_it_deleted (old CLI unlinked and a new one extracted before the raise; the returned path is the new copy, is a real file, and nothing is memoised).

Tests, studio/backend/tests/, CUDA_VISIBLE_DEVICES=0,1 both sides:

1be7c77 (before this round's work) c109462
result 62 failed, 20068 passed, 99 skipped, 15 errors 62 failed, 20077 passed, 99 skipped, 15 errors
FAILED/ERROR line set 77 lines the same 77 lines, byte for byte

The +9 across both rounds are the new tests. test_video_backend.py + test_sd_cpp_install.py + test_sd_cpp_backend.py + test_sd_cpp_engine.py together: 368 passed, 0 failed.

The Cross-platform parity (windows-latest) red is still the pre-existing test_installer_profile_hardening.py PSModulePath assertions (assert [] == [...7\\Modules], then three KeyError: 'PSModulePath'). This PR touches three files, none of them studio_cmd, and the diff does not contain the string PSModulePath at all, so it is the installer path filter surfacing a main failure, not this branch.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Third round on this PR, two items, both real and both from my own previous fixes. Fixed in f115dff.

# Item Verdict What landed
3745563405 Validate the re-found CLI before returning it Correct Both ensure_* put the re-found path through _usable_or_discard_managed.
3745563411 Revalidate an in-place replacement before H3 generation Correct (size, mtime_ns) captured before the wait and compared after, instead of an existence check.

The first is exactly the ordering trap I fixed one round earlier, now on my own code: install() raises from the sweep before it reaches _make_executable, so a freshly extracted copy on POSIX has no execute bit, and find_sd_cpp_binary only checks is_file(). Re-finding without the usability gate handed the next load a binary that cannot launch. The gate probes it and, since the copy is under the owned root, removes it when it cannot run, so the next load reinstalls cleanly instead of rejecting the same file forever.

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: test_a_re_found_cli_goes_through_the_usability_gate (old CLI runnable, new one not: None comes back, the unrunnable copy is removed, nothing memoised), and test_an_in_place_binary_swap_stops_the_h3_run, which swaps the bytes at the same path from inside the wait itself and then repeats it as a deletion.

Tests, studio/backend/tests/, CUDA_VISIBLE_DEVICES=0,1 both sides: 62 failed / 20079 passed / 15 errors against the baseline's 62 / 20068 / 15, FAILED and ERROR line sets identical at 77 lines. The +11 across the three rounds are the new tests. test_video_backend.py + test_sd_cpp_install.py + test_sd_cpp_backend.py + test_sd_cpp_engine.py: 370 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +654 to +655
if _may_own:
_discard_superseded_binaries(target, supplied)

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Fourth round on this PR, four items: three taken, one declined on scope. Fixed in 815beb7.

# Item Verdict What landed
3745633909 Persist the vetted H3 binary identity at load time Correct MiniMaxH3NativeRuntime.binary_identity, recorded where ensure_h3_sd_cpp_binary vetted the file.
3745633906 Re-resolve the server binary after the asset download Correct Re-resolved immediately before SdCppServer, with the one-shot fallback if nothing runnable survived.
3745633914 Let cancelled generations leave the install wait Correct The wait takes the request's cancel event and re-checks on a 0.5s tick.
3745633910 Coordinate standalone installs with active runtimes Declined, scope Real gap, pre-existing, wants its own design.

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 Condition.wait_for only re-evaluates on a notify or its timeout and nothing notifies _tree_state on cancel, so passing the event without shortening the wait would have changed nothing.

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 flock against Windows mandatory locking, which differ enough that getting it wrong turns a rare race into a Studio that cannot install. A half-considered interprocess lock is worse than none because it reads as a guarantee. The right shape is a lock at the managed root taken inside install() itself, so the standalone entry point participates by construction; I would rather do that separately with its own tests.

Four new tests, twelve across the four rounds. Tests, studio/backend/tests/, CUDA_VISIBLE_DEVICES=0,1 both sides: 62 failed / 20080 passed / 15 errors against the baseline's 62 / 20068 / 15, FAILED and ERROR line sets identical at 77 lines. test_video_backend.py + test_sd_cpp_install.py + test_sd_cpp_backend.py + test_sd_cpp_engine.py: 371 passed, re-run after the rebase.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Fifth round on this PR, four items, all four real and all four fixed in f8c6e27.

# Item Verdict What landed
3745775044 Capture the H3 identity under the same tree claim as vetting Correct The re-vet and the stat happen under one reader claim.
3745775041 Guard server startup with managed-tree admission Correct The re-resolve, the construction and publishing _pending_server are all inside the reader.
3745775039 Sweep binaries only after CUDA runtime setup succeeds Correct cudart moves ahead of the sweep; the sweep is last and everything from it is an incomplete replacement.
3745775047 Translate install-wait cancellation to the video sentinel Correct _tree_reader takes the caller's message; the video sites pass VIDEO_CANCELLED_MSG.

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 --help is the build whose identity is stored. The server re-resolution I added last round made the answer fresher without making it safe, because allow_install = False declines to install but does not claim the tree; publishing _pending_server inside the claim is what makes the handover to _tree_in_use gapless. And the cancellation sentinel is a plain bug I shipped by reusing the image reader on the video path.

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 SupersededBinaryError catches any other way of failing mid-replacement.

Five new tests, seventeen across the five rounds. Notably test_a_cancelled_h3_install_wait_reads_as_a_cancellation asserts the exact message rather than just RuntimeError, so the two sentinels cannot drift back together, and test_the_cuda_runtime_is_fetched_before_anything_is_swept pins the ordering rather than the symptom.

Tests, studio/backend/tests/, CUDA_VISIBLE_DEVICES=0,1 both sides: 62 failed / 20083 passed / 15 errors against the baseline's 62 / 20068 / 15, FAILED and ERROR line sets identical at 77 lines. Worth recording since it bit me on the first attempt at this run: test_amd_apu_unified_memory.py reads the mask, so an unmatched one fabricates a nine-line difference (71 against 62). The numbers above are both on 0,1.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 10, 2026
…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

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. _server_binary_runnable can block that long, and an unload arriving in that window finds no _pending_server to stop, so the load went on to publish and start() anyway and held the device for up to the 600 second startup timeout before the later token check tore it down.

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 started is never set, so the backstop has nothing to unpublish and _pending_server stays clean.

Regression test asserts the process is never spawned. Removing the guard, it fails with assert ['start'] == [], which is the bug: the server really does start.

Revalidate the accelerator after re-resolving the CLI (P2)

Also right, and worth stating why the existing machinery cannot catch it: generation calls ensure_sd_cpp_binary(..., allow_install = False), which returns whatever is found, so _resolve_engine() has no way to notice that the file it just resolved is a different build. Existence is not identity.

_SdState now records the accelerator the load committed to, and the one-shot generate refuses a mismatch, as the server path already did. Only the one-shot path carries it, since it is the one that re-resolves per image; the server path asks the same question at start time against its own copy.

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. --list-devices spawns the managed sd-cli, so leaving it unclaimed lets an install started by another in-process load extract over the executing binary.

Now under _tree_reader, like the recheck. The test records the reader count at probe time and tries to take an install claim from inside it. Before the fix it reads [0, True]: no reader, and an install would have been admitted while sd-cli was running. After, [1, False].

Not addressed, and why

Coordinate standalone installs with active runtimes. This one is real and I am leaving it. The admission state is per process, so python studio/install_sd_cpp_prebuilt.py run by hand, or a second backend sharing the managed root, cannot see this process's readers. Closing it properly needs an on-disk lock rather than in-process counters, which is a different change from the one this PR is making and would want its own review. Worth an issue rather than a rushed commit here.

Treat different-layout extraction failures as replacements was already handled by 36ead445c: replacing is now set from bool(supplied) and _tree_has_binaries(target) before _safe_extractall runs, so the boundary opens ahead of extraction rather than at the sweep.

Commits and tests

  • 26c739ec1 cancellation recheck at publish, plus the one-shot accelerator pin
  • 887840d3b claim the tree for the load-time probe

tests/test_video_backend.py, test_sd_cpp_backend.py, test_sd_cpp_install.py, test_sd_cpp_engine.py, test_sd_cpp_server.py, test_sd_cpp_args.py: 471 passed. Each of the three new guards was checked by removing the fix and confirming its test fails, so none of them is a test that would pass either way.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +4286 to +4289
if binary and (
current_identity is None
or (binary_identity is not None and current_identity != binary_identity)
):

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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".
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 1aed0c70f4

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

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 79a797c269

ℹ️ 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 2f096a6 into main Aug 10, 2026
27 of 67 checks passed
@danielhanchen
danielhanchen deleted the sd-cpp-install-tree-admission branch August 10, 2026 13:01
danielhanchen added a commit that referenced this pull request Aug 10, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant