Repository navigation
Wait for the claim release, not the teardown, in the idle-unload test - #11257
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
4ec9f18 to
c1948d0
Compare
f3781b5 to
902bddf
Compare
902bddf to
1eb284f
Compare
76d1742 to
c9796c8
Compare
1eb284f to
7acd6ca
Compare
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
7acd6ca to
af3cf7e
Compare
c9796c8 to
b430ebb
Compare
c0f1bff to
b3cfaf6
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
* Stop a redundant step-cache engage from tearing the cache down diffusers' enable_cache raises ValueError when a cache is already enabled, so a second apply_step_cache on the same transformer lands in the recovery branch, which calls disable_cache() and returns None. One redundant call and the working First-Block-Cache is gone, reported only at warning level. Same settings are now a no-op. Different settings go through disable_cache first, which is the only order diffusers accepts a new config in. The recovery branch also clears _unsloth_step_cache: that marker is read well away from here as "this transformer step caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a failed engage sends a transformer that is not caching down the caching path for the rest of the process. Latent rather than live: nothing on main calls apply_step_cache twice on one transformer today. Three of the four new tests fail without the fix. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the step-cache marker when the cleanup could not take the hooks off The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the desync this guard exists to remove, only pointing the other way. The two directions are not equally bad. A marker left set on a transformer that is not caching forces eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we land on. Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which did unhook still clears the marker, so this does not just pin the marker on forever. * Ask the model whether the re-configure cleanup actually unhooked The re-entry guard's cleanup runs two statements, and which one raised changes the answer. _restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and there the old behaviour returned the prior mode and left the marker set on a transformer that no longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable because the marker says it is already caching. So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale marker is dropped and the engage proceeds at the new settings. Two tests, one per side. The re-engage case fails without the change. * Take the cache hooks off directly instead of asking diffusers whether they are gone After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked, and clearing the marker there lets the CUDA graph wrapper capture that forward. _unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker now comes off only when that removal is known to have happened; when the registry or the hook names cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong. The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous head. * Finish the teardown in the re-entry guard too, not just the recovery branch disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears _cache_config only after both, so a raise between them leaves block hooks installed with no leader to make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior cache as healthy when half of it was gone, and the next generation skips blocks on stale state. Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports the prior mode when the removal cannot be verified at all, which is the only case left where asking is the best available answer. Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled. The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case, which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head. * Do not tear down a cache that is not ours _cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and clearing the state made diffusers forget a cache that is still installed, after which enable_cache stacks FBC on top of the live hooks. The unhook now declines when _cache_config is some other config type, which the caller already reads as unverified: it reports the cache that is actually running and leaves it alone. Matched by class name because the config is exported from two different modules depending on the diffusers version. One test, failing without the change. The mid-teardown fixture from the last round used a bare object as the stand-in config and is now an FBC-named one, which is what it was always meant to represent. * Ask the model, not the marker, whether the call is redundant The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if the rebuild then fails. The live _cache_config decides now, and the marker is repaired on the way out rather than being trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round established a way the marker can disagree with the hooks, so it is the derived value, not the fact. One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its cache untouched and comes back with the marker written. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Let only the live cache config authorize the no-op, and integrate one we adopt * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Leave an FBCache installed through the low-level API alone * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Integrate and mark a low-level cache before reporting it engaged Adopting hooks installed through apply_first_block_cache ran neither post-enable step and left _unsloth_step_cache clear over live hooks, which is the marker GraphedForward.__call__ short-circuits to eager on: the CUDA graph wrapper could capture a cache-hooked forward whose skip decision is data-dependent. Run the same integration the live-config branch runs, and set the marker (mode only, since the adopted cache's threshold is its installer's) before returning. * Unhook an adopted cache in auto mode instead of trusting disable_cache A cache adopted from apply_first_block_cache has no _cache_config, so diffusers' disable_cache warns and returns having removed nothing. maybe_toggle_step_cache cleared the marker on the strength of that call, leaving it clear over live FBCache hooks and reporting the transformer uncached, which is the state GraphedForward reads as safe to capture. Take the hooks off by name and clear the marker only once they are known gone; an unverifiable teardown keeps the marker and stays engaged. * Trim the comments added by this branch Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to 17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
test_idle_auto_unload_releases_chat_ownership fails on main in Backend CI
(Python 3.13, rest) with
AssertionError: phantom resident after idle unload:
{'loaded': [], 'loading': [], 'yours': False}
and passes everywhere else. That body is exactly
account_access.hidden_chat_status_response(), so bob was shown the mask, which
means alice's CHAT claim was still held. The product is right and the test was
watching the wrong signal.
FakeLlama.unload_model runs through asyncio.to_thread, so `unloaded` becomes
visible to the polling loop the instant the worker thread sets it, which can be
before the keepwarm task is rescheduled. The test broke its wait there and
cancelled, and the CancelledError was delivered at the await the loop was still
suspended on, so clear_resident and release_chat_gpu_claim never ran at all.
On an idle box the loop wins that race inside one 10ms tick every time; on a
loaded runner it does not.
The wait now watches the release. Polling with sleep(0) instead of sleep(0.01)
wins the race deterministically, so the window gets a test of its own rather
than a comment, and the A/B is exact: old condition reproduces the CI failure
text verbatim, new condition passes.
Also fixes the comment above the assertions in both teardown tests. It said the
masked answer is {"loaded": True, "yours": False}, which is the generic mask;
this route's mask is the chat-shaped one with an EMPTY "loaded", so `loaded ==
[]` does not discriminate here and only the "yours" key does. A new test pins
the masked body so neither assertion can be dropped as redundant.
The window test asserted the claim was still held after breaking on chat_resident.unloaded with sleep(0), which made it depend on undocumented asyncio wakeup order. Worse, it would fail against an implementation that made teardown and release atomic, so a genuine improvement would have looked like a regression. The hook goes on release_chat_gpu_claim itself: the loop reaches it, signals, and blocks until the test lets it through. Inside that window the test asserts the backend is down, the claim is alice's and bob gets the mask; then it opens the gate and asserts the claim is gone and bob gets the real answer. An atomic teardown-and-release still calls the release, so the hook still fires and the test keeps asking its question instead of becoming a tripwire. 20 consecutive runs, 4 passed each.
b3cfaf6 to
a6edba6
Compare
…unslothai#11257) * Stop a redundant step-cache engage from tearing the cache down (unslothai#11174) * Stop a redundant step-cache engage from tearing the cache down diffusers' enable_cache raises ValueError when a cache is already enabled, so a second apply_step_cache on the same transformer lands in the recovery branch, which calls disable_cache() and returns None. One redundant call and the working First-Block-Cache is gone, reported only at warning level. Same settings are now a no-op. Different settings go through disable_cache first, which is the only order diffusers accepts a new config in. The recovery branch also clears _unsloth_step_cache: that marker is read well away from here as "this transformer step caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a failed engage sends a transformer that is not caching down the caching path for the rest of the process. Latent rather than live: nothing on main calls apply_step_cache twice on one transformer today. Three of the four new tests fail without the fix. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the step-cache marker when the cleanup could not take the hooks off The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the desync this guard exists to remove, only pointing the other way. The two directions are not equally bad. A marker left set on a transformer that is not caching forces eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we land on. Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which did unhook still clears the marker, so this does not just pin the marker on forever. * Ask the model whether the re-configure cleanup actually unhooked The re-entry guard's cleanup runs two statements, and which one raised changes the answer. _restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and there the old behaviour returned the prior mode and left the marker set on a transformer that no longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable because the marker says it is already caching. So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale marker is dropped and the engage proceeds at the new settings. Two tests, one per side. The re-engage case fails without the change. * Take the cache hooks off directly instead of asking diffusers whether they are gone After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked, and clearing the marker there lets the CUDA graph wrapper capture that forward. _unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker now comes off only when that removal is known to have happened; when the registry or the hook names cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong. The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous head. * Finish the teardown in the re-entry guard too, not just the recovery branch disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears _cache_config only after both, so a raise between them leaves block hooks installed with no leader to make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior cache as healthy when half of it was gone, and the next generation skips blocks on stale state. Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports the prior mode when the removal cannot be verified at all, which is the only case left where asking is the best available answer. Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled. The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case, which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head. * Do not tear down a cache that is not ours _cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and clearing the state made diffusers forget a cache that is still installed, after which enable_cache stacks FBC on top of the live hooks. The unhook now declines when _cache_config is some other config type, which the caller already reads as unverified: it reports the cache that is actually running and leaves it alone. Matched by class name because the config is exported from two different modules depending on the diffusers version. One test, failing without the change. The mid-teardown fixture from the last round used a bare object as the stand-in config and is now an FBC-named one, which is what it was always meant to represent. * Ask the model, not the marker, whether the call is redundant The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if the rebuild then fails. The live _cache_config decides now, and the marker is repaired on the way out rather than being trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round established a way the marker can disagree with the hooks, so it is the derived value, not the fact. One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its cache untouched and comes back with the marker written. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Let only the live cache config authorize the no-op, and integrate one we adopt * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Leave an FBCache installed through the low-level API alone * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Integrate and mark a low-level cache before reporting it engaged Adopting hooks installed through apply_first_block_cache ran neither post-enable step and left _unsloth_step_cache clear over live hooks, which is the marker GraphedForward.__call__ short-circuits to eager on: the CUDA graph wrapper could capture a cache-hooked forward whose skip decision is data-dependent. Run the same integration the live-config branch runs, and set the marker (mode only, since the adopted cache's threshold is its installer's) before returning. * Unhook an adopted cache in auto mode instead of trusting disable_cache A cache adopted from apply_first_block_cache has no _cache_config, so diffusers' disable_cache warns and returns having removed nothing. maybe_toggle_step_cache cleared the marker on the strength of that call, leaving it clear over live FBCache hooks and reporting the transformer uncached, which is the state GraphedForward reads as safe to capture. Take the hooks off by name and clear the marker only once they are known gone; an unverifiable teardown keeps the marker and stays engaged. * Trim the comments added by this branch Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to 17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Wait for the claim release, not the teardown, in the idle-unload test test_idle_auto_unload_releases_chat_ownership fails on main in Backend CI (Python 3.13, rest) with AssertionError: phantom resident after idle unload: {'loaded': [], 'loading': [], 'yours': False} and passes everywhere else. That body is exactly account_access.hidden_chat_status_response(), so bob was shown the mask, which means alice's CHAT claim was still held. The product is right and the test was watching the wrong signal. FakeLlama.unload_model runs through asyncio.to_thread, so `unloaded` becomes visible to the polling loop the instant the worker thread sets it, which can be before the keepwarm task is rescheduled. The test broke its wait there and cancelled, and the CancelledError was delivered at the await the loop was still suspended on, so clear_resident and release_chat_gpu_claim never ran at all. On an idle box the loop wins that race inside one 10ms tick every time; on a loaded runner it does not. The wait now watches the release. Polling with sleep(0) instead of sleep(0.01) wins the race deterministically, so the window gets a test of its own rather than a comment, and the A/B is exact: old condition reproduces the CI failure text verbatim, new condition passes. Also fixes the comment above the assertions in both teardown tests. It said the masked answer is {"loaded": True, "yours": False}, which is the generic mask; this route's mask is the chat-shaped one with an EMPTY "loaded", so `loaded == []` does not discriminate here and only the "yours" key does. A new test pins the masked body so neither assertion can be dropped as redundant. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Hold the release window open with a hook, not a scheduler race The window test asserted the claim was still held after breaking on chat_resident.unloaded with sleep(0), which made it depend on undocumented asyncio wakeup order. Worse, it would fail against an implementation that made teardown and release atomic, so a genuine improvement would have looked like a regression. The hook goes on release_chat_gpu_claim itself: the loop reaches it, signals, and blocks until the test lets it through. Inside that window the test asserts the backend is down, the claim is alice's and bob gets the mask; then it opens the gate and asserts the claim is gone and bob gets the real answer. An atomic teardown-and-release still calls the release, so the hook still fires and the test keeps asking its question instead of becoming a tripwire. 20 consecutive runs, 4 passed each. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
What
studio/backend/tests/multi_account/test_chat_unload_ownership.py::test_idle_auto_unload_releases_chat_ownershipfails on main inBackend CI / (Python 3.13, rest):It passes locally, alone and in its file. That body is exactly
account_access.hidden_chat_status_response(), so bob was handed the mask, which means alice's CHAT claim was still held when the test looked. The product is right; the test was watching the wrong signal.Why
FakeLlama.unload_modelreaches the loop throughawait asyncio.to_thread(backend.unload_model). The flag it sets is visible to the polling loop the instant the worker thread sets it, which can be before the keepwarm task is rescheduled. The test broke its wait right there and cancelled, so theCancelledErrorwas delivered at the await the loop was still suspended on, and the tail of the teardown never ran at all:On an idle box the loop wins that race inside one 10 ms tick, every time. I measured it:
owner_at_breakwasNoneon 5 of 5 runs here. On a loaded CI runner it does not.The fix
The wait now watches the release, which is what the test is named for.
Polling with
sleep(0)instead ofsleep(0.01)wins the race deterministically, so the window gets a test rather than a comment. The A/B is exact:chat_resident.unloaded(old)AssertionError: phantom resident after idle unload: {'loaded': [], 'loading': [], 'yours': False}- the CI text, verbatimchat_resident.unloaded and gpu_arbiter.current_owner() is None(new)Reproduced 5 of 5 with the tight poll, with
owner_after_cancel == 'chat'proving the release never ran.Also
The comment above the assertions in both teardown tests was wrong. It said the hidden-resident answer is
{"loaded": True, "yours": False}; that is the generic mask, and this route's is the chat-shapedhidden_chat_status_response()with an emptyloaded. Soloaded == []is what both answers report here and only theyourskey separates them.test_only_the_yours_key_separates_the_two_answerspins the masked body directly, so neither assertion can be dropped as redundant later.Verification
test_chat_unload_ownership.py: 4 passed (2 before, 2 added).tests/multi_account/: 128 failed, 701 passed with this change and 128 failed, 699 passed on unmodified main at the same commit. Same failures, same count; the 128 are pre-existingroutes.ragroute-matrix failures on this host, unrelated and untouched. The delta is the 2 new tests.