Skip to content

Say when attention has no fused kernel, and log the request behind a failed video - #8233

Merged
danielhanchen merged 9 commits into
mainfrom
c8225
Aug 9, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
c8225

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Two device-independent halves of #8225, where a 3.4 GB Q4_K_M video model asked a 16 GB card for a single 66.54 GiB allocation, 70 seconds into a generation.

I have no ROCm hardware, so nothing here claims to fix the gfx1200 kernel gap. What it does is stop that gap being invisible, and stop the next report needing an allocation size decoded by hand.

1. Stop reading flags that lie

Attention had degraded to the SDPA math backend, the one backend that materialises the whole batch x heads x tokens x tokens score matrix. Nothing warned, and nothing could: torch.backends.cuda.flash_sdp_enabled() and mem_efficient_sdp_enabled() report the user toggle, not whether a kernel exists. On the reporter's build both answered True while every dispatch to them raised No available kernel. Aborting execution.

So do not read them. Run a 4 KB attention under each backend and record what happens. When select_attention_backend leaves the diffusers default in place and nothing sub-quadratic executes, say so at load, naming the quadratic cost, instead of letting it surface later as a six-figure MiB allocation.

A probe that cannot answer at all stays silent. "Only math" is a claim about the hardware, and silence is not evidence for it, so an empty probe result never warns and never refuses.

I did not ship the auto -> aiter preference on ROCm. That needs AITER confirmed working on gfx1200, which I cannot do, and shipping an untestable kernel selection is how the current silent fallback happened in the first place.

I also did not ship a refusal or a resolution cap. Small shapes run fine on math; a cap would need per-family token math I cannot validate on the hardware it would fire on. The load-time warning is the fail-fast that is safe to ship: seconds, not 70.

2. Log what was being rendered

video.generate_failed logged the exception and nothing else, so the entire server-side record of that OOM was Tried to allocate 66.54 GiB and the resolution and frame count behind it had to be recovered by dividing that number by the head count.

Now the resolved request is snapshotted the moment it is known and logged alongside the failure:

video.generate_failed_request: family=ltx-2 repo_id=... gguf=model.gguf width=992 height=672
  frames=113 fps=24 steps=40 guidance=4.0 guidance_2=None seed=4242 prompt_chars=15
  negative_prompt_chars=0 device=cpu offload=none attention_backend=None

The snapped shape, which is what actually ran, not the caller's raw request. Prompt lengths, not prompt text: a length separates an empty prompt from a long one, which is all a bug report needs, and a server log is not the place for user content. An allocator failure on a math-only device also gets the diagnosis attached, so the next report arrives with it already in hand.

Cancels and "not loaded" unwind through the same handler and are outcomes, not failures, so they are not logged. A failure that beats the shape resolution logs nothing, because a half-bound record is worse than none. And the whole diagnostic is wrapped: it must never replace the failure it is describing.

Reproduction

No ROCm here, so not the gfx1200 kernel gap. The mechanism does reproduce on NVIDIA, at a head_dim the fused kernels will not serve:

FLAGS  flash=True mem_efficient=True math=True   <- all three about to be wrong
    flash          REFUSED: No available kernel. Aborting execution.
    mem_efficient  REFUSED: No available kernel. Aborting execution.
    cudnn          REFUSED: No available kernel. Aborting execution.
  kernels=('math',)  sdpa_math_only=True
  WARNING -> diffusion.attention.math_only: device=cuda dtype=torch.float16 kernels=math -- ...

Same No available kernel. Aborting execution., same runtime disabled warnings, same lying flags as the report. The probe reads it correctly.

On healthy hardware, for contrast: ('flash', 'mem_efficient', 'cudnn', 'math'), math_only=False, no warning.

Cost

None on a healthy device. The probe runs only when the result is native, is memoised per device type and dtype for the life of the process, allocates 4 KB, and cannot fail a load. target on apply_attention_backend is optional, so any caller that does not pass it behaves exactly as before.

Tests

21 added across test_diffusion_attention.py (68 passing) and test_video_backend.py.

Mutation tested, 12 mutants, each caught by the named test, both files green after restoring:

mutation caught by
an empty probe reads as math-only test_an_unanswerable_probe_is_not_a_math_only_verdict
only flash counts as sub-quadratic test_any_subquadratic_kernel_means_not_math_only
a raising probe escapes test_a_probe_that_raises_is_swallowed
the probe is not memoised test_the_probe_runs_once_per_device_and_dtype
a dtypeless target probes at fp32 test_a_dtypeless_target_probes_in_half_precision
apply() warns even when a backend engaged test_apply_native_reports_a_math_only_device
the request snapshot is never logged test_a_failed_generation_logs_the_resolved_request
the prompt text is logged test_the_failure_log_carries_no_prompt_text
every failure blames attention test_a_non_oom_failure_does_not_blame_attention
OOM recognised by class only test_out_of_memory_is_recognised_by_text_not_only_by_class
a cancel is logged as a failure test_a_cancel_is_not_logged_as_a_failure
a broken diagnostic replaces the real failure test_a_broken_diagnostic_never_replaces_the_real_failure

studio/backend/hub/tests: 354 passed, unchanged. Full studio/backend/tests line set unchanged against the merge base.

Partly addresses #8225. The pre-load VRAM check not modelling attention, also raised there, is not touched here.

…failed video

Two device-independent halves of #8225, where a 3.4 GB Q4_K_M video model asked a
16 GB card for a single 66.54 GiB allocation.

Attention had degraded to the SDPA math backend, the one backend that
materialises the whole batch x heads x tokens x tokens score matrix, and nothing
said so. It could not: torch's flash_sdp_enabled() and mem_efficient_sdp_enabled()
report the USER TOGGLE, so on that build both answered True while every dispatch
to them raised "No available kernel. Aborting execution."

So stop reading the flags and run a 4 KB attention under each backend instead.
When the result is native and nothing sub-quadratic executes, say so at load,
naming the quadratic cost, rather than letting it surface 70 seconds later as an
allocation size. A probe that cannot answer at all stays silent: "only math" is
a claim about the hardware, and silence is not evidence for it.

The second half is the record. video.generate_failed logged the exception and
nothing else, so the resolution and frame count behind that 66.54 GiB had to be
recovered by dividing it by the head count. Snapshot the resolved request -- the
snapped shape, frames, steps, seed, device, offload -- and log it alongside, with
prompt LENGTHS rather than prompt text. An allocator failure on a math-only
device also gets the diagnosis attached, so the next report arrives with it.

Reproduced on NVIDIA, which cannot show the gfx1200 kernel gap but can show the
mechanism: at a head_dim the fused kernels will not serve, all three *_sdp_enabled
flags still answer True, flash / mem-efficient / cuDNN each raise "No available
kernel. Aborting execution.", and the probe correctly reports math only.

No behaviour changes on a healthy device: the probe runs only when the result is
native, is memoised per device and dtype, and cannot fail a load.

@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: e3274eb323

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/core/inference/video.py Outdated
target, attention_backend, speed_active = effective_speed != SPEED_OFF
),
logger = logger,
target = target,

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 Probe the video's promoted compute dtype

On devices whose resolved dtype is fp16, every current video family promotes the actual pipeline dtype to fp32 because fp16_incompatible defaults to true, but this passes the original fp16 target to the probe. Fused-SDPA support is dtype-specific, so a device can appear healthy in this probe while the fp32 generation falls back to math attention; the OOM diagnostic repeats the same mistake because _probe_target supplies no dtype and therefore defaults to fp16. Build the probe target from the effective dtype used to load the pipeline and preserve that dtype for failure diagnostics.

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.

Confirmed and fixed in 2116219. video.py promotes a resolved fp16 to float32 for every family (fp16_incompatible defaults true on VideoFamily), but apply_attention_backend was handed the original target, so the probe answered for fp16. The failure diagnosis had the same gap from the other end: _probe_target passed dtype=None, which defaults the probe to fp16. Since the fused kernels are half-precision only, that is the difference between 'fused kernels exist here' and 'this run had none'. The effective dtype is now recorded on the request and used by both the load-time probe and the diagnosis, with the resolution covered by a test (including that a junk value can never become a bogus dtype).

Comment on lines +193 to +195
with _SDPA_PROBE_LOCK:
_SDPA_PROBE_CACHE.setdefault(key, available)
return _SDPA_PROBE_CACHE[key]

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 Do not cache an unanswerable probe

When the probe itself raises—for example, a transient allocator failure while creating q—the exception path converts that failure to () and then permanently caches it. Every later load for that device/dtype therefore returns “unknown” without retrying, even after memory has been freed, so the new math-only warning remains disabled for the rest of the process. Only successful probe results should be memoized, or failures need to remain retryable.

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.

Confirmed and fixed in 2116219. The memoisation is justified by 'a kernel cannot appear or vanish under a running interpreter', which is an argument for caching what the probe FOUND, not for caching its failure to run, so the code was contradicting its own rationale. An empty tuple means the probe could not complete, and caching it disabled the warning for the rest of the process, including after the memory that broke it was freed. Only non-empty results are memoised now; an unanswerable probe stays retryable and still reads as 'unknown' rather than 'math only', since silence is not evidence. Covered by a test where the first probe raises and the retry answers.

Comment on lines +151 to +153
# Small enough to be free, but shaped like real attention: the fused kernels reject head_dim
# they cannot serve, and a degenerate 1-element tensor would not exercise that.
q = torch.zeros((1, 2, 8, 64), device = device, dtype = dtype)

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 Probe the model's actual attention shapes

Fused-SDPA eligibility depends on the operation shape and options, including head dimension, masks, layout, and GQA, but this probe tests only a contiguous, unmasked head-dim-64 self-attention. On a device where that synthetic call has a fused kernel but the loaded model's real attention shape does not, sdpa_math_only reports healthy and native dispatch can still fall back to the quadratic math backend during generation. Probe representative model attention configurations, or avoid treating one successful synthetic shape as device-wide fused-kernel availability.

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. The probe is a diagnostic, not a gate: sdpa_math_only has exactly two consumers, the load-time log line and the OOM explanation, and neither changes what runs. A false 'healthy' therefore costs a warning that is not printed, not a wrong load, and the shape is deliberately chosen to be non-degenerate so head-dim rejection is exercised rather than assumed. Enumerating representative per-model attention configurations means instantiating the loaded model's real shapes, masks, layout and GQA on the load path, which is a large amount of machinery and its own OOM risk, in exchange for tightening the last few percent of an advisory message. The three cases above are different: each of them made the diagnosis describe something the run did not do, which is the part that actively misleads. Happy to revisit if a concrete device shows a real shape falling back where the probe passes.

Comment thread studio/backend/core/inference/video.py Outdated
Comment on lines +374 to +375
if _is_out_of_memory(exc) and sdpa_math_only(_probe_target(request_shape)):
logger.error("video.generate_failed_request: %s", SDPA_MATH_ONLY_MESSAGE)

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 Skip the SDPA diagnosis for an engaged external backend

When an explicit backend such as AITER or xFormers successfully engaged, request_shape["attention_backend"] is non-null and generation is not using native SDPA, but this condition ignores that field and probes the device's native kernels anyway. On a ROCm device where native SDPA is math-only but AITER is active, any allocator failure can therefore receive the false statement that attention ran on the quadratic SDPA math backend. Only attach this diagnosis when the recorded engaged backend is native.

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.

Confirmed and fixed in 2116219. attention_backend was already on request_shape and the condition simply ignored it. The load-time warning was gated correctly (it only runs in the branch that pins native after no backend engaged), but the OOM diagnosis was not, so a ROCm card with AITER active got a confident statement about a backend that never ran. The diagnosis is now attached only when the recorded engaged backend is native, and the probe is not even called otherwise. The request record itself is still logged either way, since that half is useful regardless.

danielhanchen and others added 4 commits August 9, 2026 12:01
Three ways the new diagnosis could describe something the generation never did:

- The load-time probe was handed the pre-promotion target. Every video family promotes a
  resolved fp16 to fp32, and the fused SDPA kernels are half-precision only, so the probe
  answered for a precision the pipeline does not run in. The failure diagnosis had the same
  gap from the other side, defaulting to fp16 because no dtype was recorded at all. Record
  the effective dtype and probe with it.
- An engaged external backend (AITER, xFormers) replaces torch's dispatch, so probing
  native kernels answers about code that did not execute. On a ROCm card with AITER active
  that made every OOM report a confident false cause. Diagnose only a native run.
- An unanswerable probe was memoised. An empty result means the probe could not complete,
  not that the hardware has no kernels, and caching it disabled the warning for the rest of
  the process -- including after the memory that broke it was freed. Memoise answers only.
# Conflicts:
#	studio/backend/tests/test_video_backend.py

@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: 21e212992a

ℹ️ 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 +625 to +626
if target is not None:
warn_if_sdpa_math_only(target, logger)

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 Probe native SDPA for U-Net pipelines

For supported SDXL loads, the denoiser is pipe.unet rather than pipe.transformer, so _attention_dits(pipe) returns no modules and apply_attention_backend exits at the earlier if not setters branch before reaching this probe. Consequently, an SDXL generation using native math-only SDPA receives none of the new load-time diagnosis even though it has the same quadratic-memory failure mode; run the probe for a native result even when there is no dispatcher setter, or include the U-Net denoiser in this path.

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.

Fixed in ac29337: apply_attention_backend now runs the math-only probe in the no-setters branch, so a U-Net pipeline (SDXL) gets the same load-time diagnosis a DiT does. Regression test: test_apply_reports_a_math_only_device_for_a_unet_pipeline. It stays diagnostics-only, so the load path is unchanged either way.

@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: ac29337163

ℹ️ 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 +159 to +160
with sdpa_kernel([backend]):
torch.nn.functional.scaled_dot_product_attention(q, q, q)

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 Respect disabled backends when probing native SDPA

When a process has disabled flash, memory-efficient, or cuDNN SDPA through PyTorch's backend toggles, sdpa_kernel([backend]) temporarily enables that forced backend, so this call can succeed even though the native dispatch used during generation cannot select it after the context exits. The probe then reports a subquadratic kernel—and permanently caches that result—while generation still falls back to math attention, suppressing both the load-time warning and the OOM diagnosis. Preserve the active toggle state when determining which probed kernels are available to native dispatch.

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. It is accurate about sdpa_kernel([backend]) forcing a backend on inside the context, but the consequence does not reach behaviour: sdpa_math_only has exactly two consumers, the load-time warning and the extra OOM line in _log_failed_generation, and both only print. A false healthy costs an absent diagnostic, never a different load, a different kernel or a different result. Reachability is also thin: nothing in the Studio server process turns an SDPA backend off. The one place that does is the DiT trainer's perf flags, which disable cuDNN SDPA in the spawned training child and restore it on exit, so the generation process the probe runs in never sees a disabled backend. Reading the toggles back is exactly what this code exists to avoid: the flags answer True on hardware where every dispatch raises No available kernel, which is how #8225 produced a 66.54 GiB allocation.

Comment on lines +487 to +490
logger.error(
"video.generate_failed_request: %s",
" ".join(f"{k}={v}" for k, v in request_shape.items()),
)

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 Keep client validation errors out of failure logs

When the pipeline raises a ValueError after the request snapshot is created, this unconditional error log records it as video.generate_failed_request, even though _run_generate explicitly treats every ValueError as client-input feedback and deliberately avoids the existing video.generate_failed error log. Invalid user requests can therefore start producing server-error records and alerts despite being returned to the client as expected validation failures; apply the same ValueError exclusion here as in the worker's exception mapping.

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.

Fixed in 1cab4b1: _log_failed_generation now returns on a ValueError, matching _run_generate, which maps every ValueError to client input feedback and deliberately writes no video.generate_failed record. The OOM diagnosis is unaffected (an allocator failure is never a ValueError). Regression test: test_a_rejected_request_is_not_recorded_as_a_server_failure.

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

Reviewed commit: 1cab4b1706

ℹ️ 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 7494373 into main Aug 9, 2026
39 of 44 checks passed
@danielhanchen
danielhanchen deleted the c8225 branch August 9, 2026 15:53
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 28, 2026
unslothai#8804)

* Studio: say why a generation or a model load failed, and offer the log

Three complaints from the same report, all of the shape 'it failed and I
have no idea why'. Settings > Logs gave people somewhere to look; nothing
pointed at it, and two of the three surfaces had thrown the reason away
before it got that far.

Video threw it away. core/inference/video.py logged the exception and then
overwrote str(exc) with a bare literal, so the transport carried a
constant. It now classifies, reusing the OOM and math-SDPA detection unslothai#8233
already does for the log: an OOM under native SDPA names the quadratic
score matrix and says to lower resolution or frames, a plain OOM says what
to reduce, a native crash points at the log. Fixed text only, never the
engine's own message, matching the image classifier's rule about paths and
argv. The synchronous 500 uses the same classifier, so which handler caught
a failure no longer changes what the user is told.

Image generation had two branches that skipped its classifier and answered
the bare fallback, so an OOM named its cause or not depending on which
class torch raised. Both route through it now, and the generate-progress
model gains the error field its load twin already had.

The GGUF load path was the opposite problem: the backend already sends a
summary, the llama-server tail and the log's path, and it arrived intact.
It was rendered as an 8 second toast title with no white-space rule, so
every newline collapsed and a structured diagnostic read as a wall of
prose. Summary as the title, the rest as the description, and pre-wrap so
the structure survives.

All three now offer View logs, which opens the pane on the family that
failed: llama-server for a load, server for a generation. By family rather
than source id, since an id is a digest of a path the frontend cannot
compute, and at the moment of failure the newest file in the family is the
attempt that just failed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Cover the View logs action and the request that carries it

The action and the logFamilyRequested request had no test on any of the
three surfaces that raise them. The only test loading the Logs tab is
stubbed to the no-request branch, so it could neither exercise nor
detect any of it.

Asserts the action's label comes from the shipped catalogue, that a load
failure asks for llama-server and a generation for server, and the
request's lifetime: consumed by the panel, kept across a navigation
landing back on Logs, dropped by any other tab, by closeDialog, and by
each sibling opener.

Removing the requestsFor entry fails the lifetime case 5 pass / 1 fail,
so that one is a real control rather than a restatement.

* Open the log of the attempt that failed, from the right family

Two review items on the View logs action.

This hook loads GGUF diffusion models as well, and llama_cpp.py writes
their runner output under logs/diffusion-server, which
utils/debug_log_sources.py names as its own family. A fixed
llama-server therefore opened an unrelated LLM log for exactly the
loads whose diagnostic the action exists to surface. The family is now
chosen from the resolved target and diffusion-server joins
FailureLogFamily.

Family recency also picks the wrong file after a rolled-back switch.
performLoad reloads the previous model before rethrowing, and that
rollback writes a newer log in the same family, so the newest one is
the attempt that SUCCEEDED. llama_cpp.py already appends
"Full log: <path>" to the message it raises, so the action now carries
that path and the tab prefers the source whose realpath matches,
falling back to family recency when a diagnostic has no path in it.

The path rides with the family and is dropped with it, so a later visit
cannot land on a stale file.

npm test 8175 pass, typecheck clean, i18n:check:strict parity.

* Match a diagnostic's log path on the backend, and route non-GGUF failures to the server log

Two ways View logs still opened the wrong file.

Only a GGUF load goes through a runner that writes its own file per attempt.
A Transformers or MLX load reaches the same catch in performLoad, and its
reason is in the backend's current server log, but the family was picked from
isDiffusion alone so those answered llama-server: on a host with any older GGUF
attempt that opens an unrelated runner log, which reads as the reason and is
not. The decision moves into loadFailureLogFamily(isGguf, isDiffusion).

The exact-path match compared strings across a boundary where the two sides
spell paths differently. _swa_cache_path() builds Path(home) raw, so with a
relative or unexpanded UNSLOTH_STUDIO_HOME the runner reports a relative path
or one with a literal ~ component while list_sources() reports an
os.path.realpath. Equality missed and the viewer fell back to family recency,
which after a rolled-back load is the newer log of the attempt that succeeded,
the confusion carrying the path was meant to prevent.

So match it where both spellings are known. debug_log_sources gains
source_id_for_path, which canonicalises through the existing _identity (the
Windows extended-length-prefix and case quirks it already documents) and tries
both the raw and the expanded spelling, the way _scan_roots does. The sources
route takes an optional diagnostic_path and answers matched_source_id, always
an id already in its own allowlist, and the tab selects by that id. Additive
and optional: a caller sending no path, or an older client, is unaffected.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Offer View logs only to an account that can open Logs

Settings > Logs is owner-only and resolveSettingsTab sends a managed account
asking for it to General, while /debug/logs/sources is owner-guarded as well.
A non-owner can still run an image or video generation, or a model load, so the
unconditional action opened Settings on an unrelated tab and read as a broken
link rather than as a route to the reason.

viewLogsAction now returns undefined for a non-owner. Every call site already
passes the result straight through as sonner's action, where undefined renders
nothing, so no button beats a dead one. Ownership comes from a new non-hook
isAccountOwner(), since two of the call sites raise their toast from a callback
outside a component body; useIsAccountOwner now reads through it.

* Do not name a runner log for a load that never started one

performLoad's catch also sees PREFLIGHT failures: a rejected staged-metadata
read, a cancelled HF token prompt. Those reach it before the load request goes
out, so no runner was started and no file of its own exists, but the family was
chosen from the artifact type alone and answered llama-server or
diffusion-server. View logs then opened the newest unrelated prior attempt on
the host, which reads as the reason for this failure and is not.

loadFailureLogFamily takes runnerAttempted, set where the load request is
issued, and falls back to the server log without it. Same question as isGguf in
time rather than in kind: a GGUF load that dies in preflight has no runner log
either.

* Announce the runner attempt from loadModel, not before calling it

loadModel prepares the HF token itself and only then sends the request, so a
flag set before the call was already true when that preparation prompted and
was cancelled. A local or native GGUF pick skips the outer preparation, which
is exactly where the inner one can prompt, and the failure then offered the
newest unrelated runner log for an attempt that never happened.

loadModel already has an onRequestStart callback, fired after the token and
after the abort check and immediately before the POST, for the same reason the
load notice uses it. Set the flag there.

tests/load-request-start-boundary.test.ts drives the real module and pins that
ordering as a contract: announced between the token and the request, and never
announced at all for a cancelled prompt or an abort landing during it.

* Make the generate-progress error real, and refresh Logs when a request arrives

Two things this PR added that did not work.

The error field on DiffusionGenerateProgressResponse was always None. Both
engines clear _gen in a finally and their idle progress dict omitted the key,
so Pydantic only ever supplied the default, and the frontend read active to
idle as success: a generation whose POST was lost and then failed reported
completion and could advance a multi-run batch past an output that never
arrived. Both engines now retain the reason past that clear and publish it on
the idle branch only, cleared when the next generation STARTS so it can never
be read as belonging to a run in flight. The engines keep the RAW text and the
progress route classifies it through _generate_failure_detail, so this stays
the one place that decides what a caller may see and engine text with its local
paths and argv does not escape. settleLostGeneration rejects an idle read that
carries one, outside the transport-failure catch so a reported reason is not
counted as a dropped connection.

The Logs panel read the pending request imperatively and subscribed to
neither field, so a failure toast clicked while that panel was already mounted
changed nothing: reopening the tab it is on does not remount it, and in manual
refresh mode nothing else rescans, leaving the previous log displayed. It now
subscribes to pendingLogRequestKey, which covers the family and the path so a
second failure naming a different log still looks different.

* Date a retained generation failure, and consume only the log request a fetch asked for

The retained reason has to outlive the run it came from, which is exactly why it
cannot be taken at face value: a POST lost BEFORE the backend saw it starts no
run, so a previous failure was still sitting there and was attributed to this
attempt, skipping the gallery probe that would have reported the request never
arrived. Both engines now advance a per-run counter beside the clear and publish
it next to the reason, and the route sends it only when there IS a reason, so it
is never an unexplained internal number. The client captures the counter with
the probe baseline, from the poll already running, and
generationFailureForAttempt accepts a reason only from a run that started after
that. A backend too old to send the counter is left to the probe, as before.

Separately, the Logs panel could consume a request its fetch had never asked
for: a pathless refresh in flight when the user clicks View logs would answer
the newly pending request, pick the family's newest file, and consume it, and
that consumption aborts the newer exact-path refresh through the effect's
cleanup, leaving a rollback's log open instead of the failed attempt's. Each
fetch now captures the request key it was made for and consumes only that one,
leaving a newer request for the refresh it triggered.

* Let a settling generation read its own baseline before it posts

The retained failure reason is dated with the engine's run counter, but the
counter was only sent alongside a reason and the client only froze whatever a
background poll had left behind. A run that succeeded therefore published no
counter at all, and the first attempt after a page load had never read one, so
the baseline could sit at 0 while the engine was several runs further on: a
post lost before it reached the backend then found a reason from an earlier run
looking newer than itself, and reported that instead of the gallery probe's
more accurate answer, which is that the request never arrived.

The counter is now published on the active progress branch as well as the idle
one and sent whether or not there is a reason, and the page clears its baseline
and awaits one progress read before the first post, keeping it fresh through
the 300ms poll for the runs after it. A baseline that was never observed is
null and declines to attribute rather than guessing.

* Identify a retained generation failure by the attempt that caused it

The run counter could only say "later", and later is not the same as mine. A
concurrent client on the same account, another tab or a second browser, can
start and fail its own run inside the window a lost-response waiter is polling,
and its sequence clears any baseline this attempt froze; the waiter then throws
someone else's failure before checking its own gallery record. Reading the
baseline before the post, which the counter also needed, was another way to get
the same answer wrong.

The request now carries an id the client mints per post, bounded and patterned
because it comes back out on a response. The engine keeps it where it clears the
retained reason, publishes it beside that reason, and the waiter accepts a
failure only on an exact match. A post that never reached the backend started no
run, so nothing carries its id; another client's run carries its own; and a
reason with no id at all is left to the gallery probe, as before this field
existed. The counter is gone rather than left published, since it invites the
comparison it cannot support.

This also replaces the awaited baseline read added in the previous commit, which
landed in the mount-probe resume path rather than the submit path and left a
stray await in a non-async callback.

* Choose the runner log family from the diagnostic that names one, not from the request going out

Issuing the load request is not the same as a runner starting. The backend can
refuse a sidecar swap or reject extra args before it launches one, and that
failure reaches the same catch with the flag already set, so View logs offered
the newest unrelated llama-server or diffusion-server file on the host.

The family now comes from the runner log path the backend appends to its own
diagnostic, which it names exactly when there is one to name. The family and
the path handed to the action are the same value, so a family naming a runner
can no longer pair with an action that has no path to open, and the
request-issued flag is gone rather than left as a second, weaker answer to the
same question.

* Tighten the comments this PR added

Comments and docstrings only, no code touched: comment_tools.py check passes
over all 14 changed files. Frontend 8191 passed, backend suites green.

* Keep a failed generation's reason until the attempt that ran it can read it

One retained slot is only enough while nothing else runs. A client whose POST
was lost polls once a second, and a queued client can take the slot inside that
window: the run it starts cleared the slot, so the settling client read the
newcomer going active and then idle as its own success and could advance a batch
past an output that never arrived.

Outcomes are now kept per attempt, in a bounded map beside the slot, and the
progress route takes an optional attempt_id and answers about THAT generation.
The slot stays for a client that sends no id, which is what an older one does.
Sixteen entries, oldest first out: only a settling caller reads one and it reads
it within seconds, so this cannot grow with uptime.

* Record a cancelled native generation against its attempt

sd.cpp catches SdCppCancelled ahead of its generic handler, so a run stopped by
an unload or a superseding load wrote only the single retained slot. The keyed
lookup answers whenever a client names its attempt, so that client saw no error
and could read the transition to idle as its own success though no image was
produced. The diffusers engine raises RuntimeError for the same case and reaches
the handler that already records.

* Answer an attempt-specific progress poll about that attempt only

A generation running for someone else says nothing about this one, but the
attempt-specific response still carried the global active flag and step counter.
A client settling a POST that never arrived counted that run as its own, so when
it went idle the client treated it as success and skipped the gallery proof that
would have said no image was produced.

Both engines now publish the running attempt on the active progress branch as
well as the idle one, and a named poll reports active only when the run is that
attempt's, zeroing the step counter otherwise. An unnamed poll still gets the
global answer, which is what the progress bar and an older client read.

* Key a retained outcome to its account, answer it first, and scope the persist window

Two ways a named poll could still be answered about someone else's work.

With managed accounts, a second account starting a generation between this
caller's failure and its next poll sent the caller through the
foreign-generation guard, which answers idle and hidden: a client that had
already seen its own run active read that as success. Retained outcomes are now
keyed by (account, attempt) and the named lookup runs before those guards, which
is safe precisely because of the key: a caller can only ever match its own
account's attempt, and the answer carries nothing about the generation running
now.

The persist window was global too, so records being written for any other Studio
or OpenAI image request held the active override on and a settling caller took
the end of that window for its own success. The attempts inside the window are
now tracked, and a named poll is told only about its own. An unnamed poll keeps
the global answer, which is what the reload mount probe reads.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added since the last pass

Comments only; comment_tools.py check passes on all four files and the PR's own
suite stays at 20 passed.

* Keep retained outcomes off the engine instance

A request can switch the active diffusion engine between diffusers and sd.cpp
while a client is still settling a lost POST. Held on the instance that ran the
generation, that client's reason became unreachable the moment the other engine
took over, and it was told either that its request never arrived or that another
run going idle was its own success.

The store is now one bounded, lock-guarded map for the process, keyed by
(account, attempt) as before, and neither the record nor the lookup takes an
engine.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added since the last pass

Comments only; no code change.

* Update the logged progress snapshot this PR widened

Staging CI caught it: test_generate_progress_route_logs_backend_snapshot pins the exact
dict handed to log_media_generation_progress, and the classification step this PR adds
always sets an error key, None included, so the logged snapshot gained one. The test
passes on main and failed on this head, which makes it a real break rather than an
inherited one. Updated the pinned dict and noted why the key is safe to log: the value is
classified before it goes out, so engine text with its local paths never reaches the log.

116 passed in tests/test_diffusion_routes.py, 21 in the attempt-attribution suite, 11 in
tests/test_formatter_fixed_point.py.

* Keep a cancellation a cancellation, and offer logs only where there are logs

Two review catches, both real.

The cancellation sentinel went through _generate_failure_detail, which maps every
unrecognized reason to the generic fallback. A POST that returns normally answers 409 with
the sentinel and the page treats that as the requested outcome, but a caller settling a
LOST post reads the retained reason through the classifier, so its own Stop came back as
"Image generation failed." and toasted a failure. The sentinel is fixed text already, so
it now passes through unchanged and shouldReportGenerateError recognises it as it does on
the 409 path. Everything else still goes through the classifier.

The View logs action was attached to every generate error, including
"The image generation request did not reach the server.", which never left the browser,
and the 400s the route answers without logging. Settings > Logs cannot hold either, so the
action opened an unrelated current log and pointed at a false diagnosis. It is now gated on
generationFailureWasLogged: only the 500 paths log, and they answer with a classified
reason, which always opens with "Image generation failed.".

Tests: test_a_cancelled_attempt_settles_as_a_cancellation_not_a_failure and a new case in
generation-failure-attribution.test.ts covering the predicate and the page's wiring.
Reverting either fix fails its test ("a cancellation read as a generic failure to the
client settling a lost post"; "the generate error toast still offers logs for a failure
that was never logged"). 138 backend tests in the diffusion route and attribution suites,
frontend 8192 pass / 0 fail, npm run typecheck clean.

* Do not answer an unscoped poll with another account's failure

The keyed outcome store is account-qualified, but the legacy path a poll without an
attempt id takes reads the ENGINE's slot, which is one per process and holds whoever ran
last. The account guards above only hide a generation while it is ACTIVE, so once A's run
had failed and left media_generation, B's unscoped poll on a multi-account installation
was answered with A's classified reason and the attempt id that produced it.

The keyed store is now the authority for that path too: a reason the caller can look up
under its own account is a reason it owns, and anything else is dropped before
classification. A single-identity installation (account_scope() None) has nobody else for
the slot to belong to, so the legacy answer an older client depends on is unchanged.

test_an_unscoped_poll_on_a_multi_account_install_is_not_told_someone_elses_reason covers
all three: the owner of the attempt still gets its reason, the other account gets None
with no attempt id, and the single-account install keeps the legacy answer. Reverting the
scoping fails it ("an unscoped poll was answered with another account's failure"). 138
passed across the diffusion route and attribution suites.

* Offer View logs only where a log can hold the failure

Three review catches, all the same defect in the affordance this PR adds: the action was
attached to failures the server never logged, so Settings > Logs opened an unrelated
current log and pointed at a false diagnosis.

Images. The prefix check was an inference, and classification erases exactly the
distinction it was inferring: the route answers a ValueError with its own reason and never
logs it, but a caller settling a lost POST reads the RETAINED reason, which by then wears
the same "Image generation failed." prefix as an internal failure. The retained record now
carries whether it was logged, the 400 branch marks its attempt unlogged, the poll
publishes error_logged, and the page prefers that over the prefix when it is there. The
prefix rule stays as the fallback for a failure the POST reported directly, where there is
no retained record to ask.

Video. Same shape: the worker's ValueError branch reports a client-input failure without
logging it, and the not-loaded and cancelled sentinels are not logged either.
_finish_generate_job takes error_logged, publishes it on the terminal state, and both
video-page sites (the live poll and the mount-time resume) withhold the action on an
explicit false. A worker that could not start is marked unlogged too, since nothing ran.

Chat. A load can fail before /api/inference/load is sent -- a declined token prompt, an
abort, a preflight guard -- and the backend then has nothing about it anywhere. The hook
tracks whether the request went out and offers the action only when it did or when the
diagnostic names a log. Deliberately NOT fed into the family, which is the pairing an
earlier commit here removed: a request issued is not a runner started.

Tests: test_a_client_input_failure_is_not_reported_as_one_the_log_explains,
test_the_route_marks_and_publishes_whether_the_failure_was_logged,
test_a_video_failure_says_whether_it_reached_the_log, and three frontend cases covering the
retained flag, both video sites and the load gate. Reverting each of the three gates fails
its own test. Backend 25 + 116 + 68 in the attribution, diffusion-route and video-route
suites (the one video-route failure is the quantized-reference-pick case, red on untouched
main); test_video_backend.py is 101 failed / 172 passed identically on this head and on the
merge base, all environment-related. Frontend 8195 pass / 0 fail, npm run typecheck clean.

* Reach the three failure paths the last commit's gates did not cover

A synchronous video refusal. begin_generate can fail before its worker starts, the POST is
rejected, and polling never begins, so neither progress branch can attach the action: this
is the only place it can be offered for that class. Classified refusals carry the
"Video generation failed." prefix and every branch producing one logs the exception first,
while a 400 carries the raw validation text, so the same prefix rule the image side uses
applies here.

The chat load-issued flag moves to onRequestStart, which is the actual send boundary.
loadModel does its own token preparation and abort check first, so a flag set before the
call was still set when that inner prompt was declined and the backend had received
nothing -- the case the previous commit meant to fix, on a path it did not reach.

A generation that fails across a reload. The resumed page has no POST to reject and no
settling loop, so the retained reason is its only channel, and both resume paths looked at
active alone: an idle answer carrying a reason was refreshed away as a finished run. The
resume poll and the mount probe now report it through one helper, gated on what the server
logged and still treating a cancellation as not an error.

Tests: three new frontend cases, one per path, each failing with its own message when its
hunk is reverted. One existing test moved its anchor: video-generate-refusal-resync keyed
off the toast call, which now carries an action, so it anchors on the refusal the catch
builds. Frontend 8198 pass / 0 fail, npm run typecheck clean.

* Keep the rollback out of the target's diagnosis, and cover the logged persist failure

Two follow-ups.

The rollback load set the same request-issued flag as the target, so a target that failed
before its own request went out borrowed the rollback's log -- a log of a load that
SUCCEEDED. Only the target marks it now; the rollback is a different request.

Image persistence is logged (diffusion.persist_failed) but answered with fixed text that
carries no classification prefix, so the one failure whose disk error is only in the log
was the one offering no way to it. The predicate now recognises that message explicitly,
by value rather than by widening the prefix rule, so the unlogged 400s stay excluded.

Tests: two new frontend cases; reverting either fix fails its own. Frontend 8200 pass / 0
fail. Two earlier assertions moved from two setters to one, with the reason stated.

* Report a retained image failure once, not once per navigation

The backend keeps a generation's reason until another run starts, so the idle
mount probe answers with the same one every time the page mounts. The new
replay therefore repeated a failure the user had already seen, once per
navigation back to Images, and twice for the run whose POST did arrive: the
catch toasted it and the next mount toasted it again.

One module-level slot holds the attempt already put in front of the user, and
both the replay and the handler's own catch write it. Module scope rather than
a ref, which the remount being guarded would reset, and deliberately lost on
reload, which is the case the retained reason exists for. One slot is enough
because the progress snapshot attributes at most one run at a time.

* Retain a persist failure, and key the replay guard on unattributed ones too

Two gaps in what the settling and resuming clients can read.

The persist failure is the only one raised after the attempt was already
reported active, and it retained nothing: a client whose POST was lost watched
its attempt go active-to-idle, took that for success, and the images that were
never saved are not in the gallery to contradict it. The reason is now recorded
against the attempt before the finally drops the persist marker, so the
progress poll can answer with it.

And the replay guard keyed on the attempt alone, which the OpenAI images route
never sends, so an unattributed retained reason could never match it and was
toasted again on every mount. The key falls back to the reason itself, which is
what the user is being shown, so the promise is the same in the same terms.

* Answer a queued attempt as pending, and let a reload hear a failed save

Two more channels a settling or resuming client reads.

The engine cannot name an attempt until it holds the generation slot, so a
second run queued behind an active one answered a named poll with active
False. A settling client whose POST was lost then read that as "the request
never arrived", or took the running run's newly saved record for proof that
its own had finished. The request now marks the attempt from before the wait
until the generate call returns, with the persist marker taking over with no
await in between, and the progress route reports a marked attempt as pending
without lending it the running run's step counter.

And a reloaded page polls without an attempt id, so a persist failure recorded
only in the keyed store was invisible to its mount probe: it saw an error-free
idle state and refreshed a gallery that had not changed. The reason is now
parked in the engine's unscoped slot as well, which both engines publish and
clear at the start of the next run, from the OpenAI images route too since
that one never carries an id. Its fixed text passes through classification
unchanged, because "Image generation failed" is wrong about a generation that
succeeded, and the response and the poll must not describe it differently.

Also updated one pinned literal: the OpenAI images 500 for an OOM now carries
the classified cause, which is what this PR is for, and the test still proves
the engine's own words do not leave.

* Read the log flag off the attempt the answer names

A reloaded page polls without an attempt id, and the flag was looked up under
None, so a client-input failure the route deliberately answered without
logging came back as logged and the page offered a log that cannot hold it.

The lookup falls back to the attempt the response attributes the error to,
which is the record mark_generate_failure_unlogged marked. It can only ever be
the caller's own: an unattributable or foreign error is already cleared above
on an install with accounts, and the store is account-qualified.

One source window in the test file widened too, since the handler had grown
past it and those assertions had stopped reaching its end.

* Match a failure class as a whole word, and let a retry supersede its own id

Every exception class reaches the classifier now, so its needles have to be
tokens: "oom" as a substring reported an out-of-memory failure for any message
containing "boom", "bathroom" or "zoom", and told the user to shrink an image
that was never too big. The needles are compiled once as word-bounded
patterns, and the real spellings the engines produce still classify.

And the Tauri client retries a POST whose connection dropped with the same
serialized body, so the same attempt id. A first execution's retained failure
then outranked the retry, which can be queued, running or already successful,
so the settling client declared the attempt failed and ignored the images the
retry had produced. An execution now clears the outcome retained under its id
as it takes it, beside the marker that makes it pending.

* Let a live execution outrank an outcome retained under its id

Clearing the retained outcome when a retry takes the id is not enough on its
own: the predecessor can still be running, and a failure it retains after that
point lands under an id the retry owns. The progress route read the retained
outcome before the markers, so the client reported failure and stopped
settling while the retry was queued or running.

A request holding the id now outranks the retained answer, which covers the
queue wait, the run and the persist window, and the outcome is cleared again
once this execution's own run has happened, so nothing its predecessor left
resurfaces when the markers drop. With no execution holding the id the
retained reason answers as before, which is what a client settling a run that
really did fail needs.

* Keep a stalled persist from answering for a retry that already saved

Persist runs after the engine slot is released, so two executions of one
retried POST can be persisting at once. A retry could generate and persist
successfully while the original's persist stalled, and the original failing
afterwards recorded that failure under the shared id, so the settling client
reported failure while the retry's images sat in the gallery.

Each execution takes a serial, a finished run records itself as the newest for
its attempt, and the persist failure writes neither the retained outcome nor
the unscoped slot once a later execution has finished. An older serial cannot
move that mark backwards, so the order the two persists finish in does not
decide who answers.

* Bound the finished-run bookkeeping, and clear an outcome under its lock

Every generation supplies a fresh attempt id, so the finished-run map kept one
key per generation for the life of the server. Bounded at 64, oldest out
first, like the retained outcomes: the serial only matters while a duplicate
of the same id is still persisting, so an evicted key is an id nothing can
still be racing over.

And clear_generate_failure mutated the outcome store without the lock every
other mutation holds. The bound is a read-then-pop, so an unlocked clear could
land between the eviction test and the popitem and drop one more outcome than
the bound calls for, leaving that client reading its failed generation as
absent.

* Retain the failures raised before a run starts, and clear on a successful save

Two more channels a client whose POST was lost has to be able to read.

The handler inside generate cannot see the raises that precede it: cancelled
while queued for the generation slot, no model loaded, a dead resident server,
a superseding load. Nothing was recorded for those, so settleLostGeneration
reported that the request never reached the server rather than the
cancellation that actually happened. Each now goes through one helper that
records the reason and the attempt it belongs to, in both engines, since the
block that normally stamps the attempt has not run yet.

And a successful save clears whatever is retained under this id: the images
exist, so nothing under it is a failure of this request any more. A duplicate
execution of one retried POST can fail while this one is still writing, and
its reason would otherwise answer a settling client whose images are already
in the gallery. After the save, not before, so a reason still belongs to
whichever execution is the newest if this save fails instead.

* Keep a queued attempt visible to its own client, and clear the unscoped slot on a save

A managed account's attempt can be queued behind ANOTHER account's generation,
and the guards that hide a foreign run answered idle for the poll that names
it, so a settling client whose POST was lost read that as "the request never
arrived" while it was still queued and would later spend GPU time. A live
attempt of the caller's own now passes those guards. Nothing foreign travels
with it: a named poll zeroes the step counter unless the running attempt is
this one, the reason is already suppressed while live, so the answer is
pending and nothing else, and only a request this caller made can set the
marker since the key is account-qualified.

And the unscoped slot means "the last thing that happened", which the engine
only clears when a run STARTS. A persist failure written after a newer run
began therefore outlived it, and an unscoped probe read the older failure
after the newer run had saved successfully. A successful save clears it. The
attempt field is left alone, since a run in flight publishes it and it is only
read beside a reason.

* Order the unscoped slot by execution, record a validation refusal, and mark client-state failures unlogged

The unscoped slot is one per process and the engine clears it only when a run
STARTS, so with two executions overlapping whoever finished last used to win:
an older save wiped a newer failure, and an older failure hid a newer success.
One monotone serial now decides. Both the persist-failure write and the
clear-on-success are gated on it, and the engine's own write is stamped for
the execution whose call it happened in.

The pre-lock validation guards raise before the engine's handler, so nothing
was recorded for them: marking corrects a record, it does not create one, and
a settling client whose POST was lost was told its request never reached the
server when the answer was a refusal the route had already written. The
refusal is retained and then marked, so the record exists and does not claim a
log the route never wrote.

And the pre-run failures the helper records are all answered as 409s or 400s
without logging, so they are retained as unlogged: as logged, the poll
published error_logged true and the page offered the log for an event that is
not in it.

* Announce the load send from authFetch, past its own local refusals

authFetch's account-transition gate refuses locally, with no request going
out, and loadModel announced the send before calling it, so a failed load
offered the server log for a request the backend never saw.

authFetch takes an onRequestStart option now and fires it immediately before
the transport, and loadModel hands its caller's callback through. Both callers
gain the stricter guarantee, chat's log decision and Audio's requestStarted
cancel, and the ordering they relied on is unchanged: after the token prompt,
before the POST.

* Do not leave a retried model replacement standing as a failure

The route retries a DiffusionModelReplacedError once, so the first raise is
not an outcome. The engine had already published the reason on both channels,
and an unscoped progress poll has no attempt id to be marked live by, so an
Images page opened during the queued retry read a terminal failure for a run
that was about to start again. Both records are dropped before the retry lap,
which records its own outcome; the second replacement keeps its 409.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: an unscoped progress poll reports the caller's own queued generation as pending

A reloaded page loses its attempt id and polls without one. While its request waits for the
generation slot the engine still holds the previous run's failure, so the page toasted that stale
reason and stopped polling. Also scope the wiring test to the whole route body.

* Studio: trim comments in the failure-reason change

* Studio: restore license headers and finish truncated docstrings

* Studio: classify a native sd-cli video exit, and order the OpenAI persist failure like /images/generate

The video classifier missed the runner's own 'sd-cli exited <code>' diagnostic, so a native
video crash still read as the bare fallback. The OpenAI images route wrote its persist failure
into the unscoped slot of whichever engine was active, over a later execution's reason.

* Studio: cut the failure-reason change down to what users see

Keep the video failure classifier, the image routes' two unclassified branches, the multi-line
load diagnostic as title plus description, and View logs opening the exact log the diagnostic
names. Drop the per-attempt failure retention for lost POSTs (main's settleLostGeneration already
recovers the result), the request-start plumbing, and the tests that only covered them.

* Studio: match a diagnostic's log path against the listing the sources route already has

Opening Logs from a failure toast walked every log directory a second time (about 9 ms more per
request on 500 files, a 50% rise); the route now hands its own listing over.

* Studio: an older log-sources response never overrides a newer selection

A 404 recovery reselect that finished after a View logs fetch replaced the exact failure log
with the default one.

* Studio: drop the duplicated sd-cli exit test in test_video_routes

* Studio: tighten the View logs request handling

A stale sources response now bails before touching any state, a repeated identical View logs
click carries its own sequence so a mounted Logs tab refetches, and a failed video save offers
its log like a failed image save.

* Studio: trim comments in the failure-reason change

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
unslothai#8804)

* Studio: say why a generation or a model load failed, and offer the log

Three complaints from the same report, all of the shape 'it failed and I
have no idea why'. Settings > Logs gave people somewhere to look; nothing
pointed at it, and two of the three surfaces had thrown the reason away
before it got that far.

Video threw it away. core/inference/video.py logged the exception and then
overwrote str(exc) with a bare literal, so the transport carried a
constant. It now classifies, reusing the OOM and math-SDPA detection unslothai#8233
already does for the log: an OOM under native SDPA names the quadratic
score matrix and says to lower resolution or frames, a plain OOM says what
to reduce, a native crash points at the log. Fixed text only, never the
engine's own message, matching the image classifier's rule about paths and
argv. The synchronous 500 uses the same classifier, so which handler caught
a failure no longer changes what the user is told.

Image generation had two branches that skipped its classifier and answered
the bare fallback, so an OOM named its cause or not depending on which
class torch raised. Both route through it now, and the generate-progress
model gains the error field its load twin already had.

The GGUF load path was the opposite problem: the backend already sends a
summary, the llama-server tail and the log's path, and it arrived intact.
It was rendered as an 8 second toast title with no white-space rule, so
every newline collapsed and a structured diagnostic read as a wall of
prose. Summary as the title, the rest as the description, and pre-wrap so
the structure survives.

All three now offer View logs, which opens the pane on the family that
failed: llama-server for a load, server for a generation. By family rather
than source id, since an id is a digest of a path the frontend cannot
compute, and at the moment of failure the newest file in the family is the
attempt that just failed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Cover the View logs action and the request that carries it

The action and the logFamilyRequested request had no test on any of the
three surfaces that raise them. The only test loading the Logs tab is
stubbed to the no-request branch, so it could neither exercise nor
detect any of it.

Asserts the action's label comes from the shipped catalogue, that a load
failure asks for llama-server and a generation for server, and the
request's lifetime: consumed by the panel, kept across a navigation
landing back on Logs, dropped by any other tab, by closeDialog, and by
each sibling opener.

Removing the requestsFor entry fails the lifetime case 5 pass / 1 fail,
so that one is a real control rather than a restatement.

* Open the log of the attempt that failed, from the right family

Two review items on the View logs action.

This hook loads GGUF diffusion models as well, and llama_cpp.py writes
their runner output under logs/diffusion-server, which
utils/debug_log_sources.py names as its own family. A fixed
llama-server therefore opened an unrelated LLM log for exactly the
loads whose diagnostic the action exists to surface. The family is now
chosen from the resolved target and diffusion-server joins
FailureLogFamily.

Family recency also picks the wrong file after a rolled-back switch.
performLoad reloads the previous model before rethrowing, and that
rollback writes a newer log in the same family, so the newest one is
the attempt that SUCCEEDED. llama_cpp.py already appends
"Full log: <path>" to the message it raises, so the action now carries
that path and the tab prefers the source whose realpath matches,
falling back to family recency when a diagnostic has no path in it.

The path rides with the family and is dropped with it, so a later visit
cannot land on a stale file.

npm test 8175 pass, typecheck clean, i18n:check:strict parity.

* Match a diagnostic's log path on the backend, and route non-GGUF failures to the server log

Two ways View logs still opened the wrong file.

Only a GGUF load goes through a runner that writes its own file per attempt.
A Transformers or MLX load reaches the same catch in performLoad, and its
reason is in the backend's current server log, but the family was picked from
isDiffusion alone so those answered llama-server: on a host with any older GGUF
attempt that opens an unrelated runner log, which reads as the reason and is
not. The decision moves into loadFailureLogFamily(isGguf, isDiffusion).

The exact-path match compared strings across a boundary where the two sides
spell paths differently. _swa_cache_path() builds Path(home) raw, so with a
relative or unexpanded UNSLOTH_STUDIO_HOME the runner reports a relative path
or one with a literal ~ component while list_sources() reports an
os.path.realpath. Equality missed and the viewer fell back to family recency,
which after a rolled-back load is the newer log of the attempt that succeeded,
the confusion carrying the path was meant to prevent.

So match it where both spellings are known. debug_log_sources gains
source_id_for_path, which canonicalises through the existing _identity (the
Windows extended-length-prefix and case quirks it already documents) and tries
both the raw and the expanded spelling, the way _scan_roots does. The sources
route takes an optional diagnostic_path and answers matched_source_id, always
an id already in its own allowlist, and the tab selects by that id. Additive
and optional: a caller sending no path, or an older client, is unaffected.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Offer View logs only to an account that can open Logs

Settings > Logs is owner-only and resolveSettingsTab sends a managed account
asking for it to General, while /debug/logs/sources is owner-guarded as well.
A non-owner can still run an image or video generation, or a model load, so the
unconditional action opened Settings on an unrelated tab and read as a broken
link rather than as a route to the reason.

viewLogsAction now returns undefined for a non-owner. Every call site already
passes the result straight through as sonner's action, where undefined renders
nothing, so no button beats a dead one. Ownership comes from a new non-hook
isAccountOwner(), since two of the call sites raise their toast from a callback
outside a component body; useIsAccountOwner now reads through it.

* Do not name a runner log for a load that never started one

performLoad's catch also sees PREFLIGHT failures: a rejected staged-metadata
read, a cancelled HF token prompt. Those reach it before the load request goes
out, so no runner was started and no file of its own exists, but the family was
chosen from the artifact type alone and answered llama-server or
diffusion-server. View logs then opened the newest unrelated prior attempt on
the host, which reads as the reason for this failure and is not.

loadFailureLogFamily takes runnerAttempted, set where the load request is
issued, and falls back to the server log without it. Same question as isGguf in
time rather than in kind: a GGUF load that dies in preflight has no runner log
either.

* Announce the runner attempt from loadModel, not before calling it

loadModel prepares the HF token itself and only then sends the request, so a
flag set before the call was already true when that preparation prompted and
was cancelled. A local or native GGUF pick skips the outer preparation, which
is exactly where the inner one can prompt, and the failure then offered the
newest unrelated runner log for an attempt that never happened.

loadModel already has an onRequestStart callback, fired after the token and
after the abort check and immediately before the POST, for the same reason the
load notice uses it. Set the flag there.

tests/load-request-start-boundary.test.ts drives the real module and pins that
ordering as a contract: announced between the token and the request, and never
announced at all for a cancelled prompt or an abort landing during it.

* Make the generate-progress error real, and refresh Logs when a request arrives

Two things this PR added that did not work.

The error field on DiffusionGenerateProgressResponse was always None. Both
engines clear _gen in a finally and their idle progress dict omitted the key,
so Pydantic only ever supplied the default, and the frontend read active to
idle as success: a generation whose POST was lost and then failed reported
completion and could advance a multi-run batch past an output that never
arrived. Both engines now retain the reason past that clear and publish it on
the idle branch only, cleared when the next generation STARTS so it can never
be read as belonging to a run in flight. The engines keep the RAW text and the
progress route classifies it through _generate_failure_detail, so this stays
the one place that decides what a caller may see and engine text with its local
paths and argv does not escape. settleLostGeneration rejects an idle read that
carries one, outside the transport-failure catch so a reported reason is not
counted as a dropped connection.

The Logs panel read the pending request imperatively and subscribed to
neither field, so a failure toast clicked while that panel was already mounted
changed nothing: reopening the tab it is on does not remount it, and in manual
refresh mode nothing else rescans, leaving the previous log displayed. It now
subscribes to pendingLogRequestKey, which covers the family and the path so a
second failure naming a different log still looks different.

* Date a retained generation failure, and consume only the log request a fetch asked for

The retained reason has to outlive the run it came from, which is exactly why it
cannot be taken at face value: a POST lost BEFORE the backend saw it starts no
run, so a previous failure was still sitting there and was attributed to this
attempt, skipping the gallery probe that would have reported the request never
arrived. Both engines now advance a per-run counter beside the clear and publish
it next to the reason, and the route sends it only when there IS a reason, so it
is never an unexplained internal number. The client captures the counter with
the probe baseline, from the poll already running, and
generationFailureForAttempt accepts a reason only from a run that started after
that. A backend too old to send the counter is left to the probe, as before.

Separately, the Logs panel could consume a request its fetch had never asked
for: a pathless refresh in flight when the user clicks View logs would answer
the newly pending request, pick the family's newest file, and consume it, and
that consumption aborts the newer exact-path refresh through the effect's
cleanup, leaving a rollback's log open instead of the failed attempt's. Each
fetch now captures the request key it was made for and consumes only that one,
leaving a newer request for the refresh it triggered.

* Let a settling generation read its own baseline before it posts

The retained failure reason is dated with the engine's run counter, but the
counter was only sent alongside a reason and the client only froze whatever a
background poll had left behind. A run that succeeded therefore published no
counter at all, and the first attempt after a page load had never read one, so
the baseline could sit at 0 while the engine was several runs further on: a
post lost before it reached the backend then found a reason from an earlier run
looking newer than itself, and reported that instead of the gallery probe's
more accurate answer, which is that the request never arrived.

The counter is now published on the active progress branch as well as the idle
one and sent whether or not there is a reason, and the page clears its baseline
and awaits one progress read before the first post, keeping it fresh through
the 300ms poll for the runs after it. A baseline that was never observed is
null and declines to attribute rather than guessing.

* Identify a retained generation failure by the attempt that caused it

The run counter could only say "later", and later is not the same as mine. A
concurrent client on the same account, another tab or a second browser, can
start and fail its own run inside the window a lost-response waiter is polling,
and its sequence clears any baseline this attempt froze; the waiter then throws
someone else's failure before checking its own gallery record. Reading the
baseline before the post, which the counter also needed, was another way to get
the same answer wrong.

The request now carries an id the client mints per post, bounded and patterned
because it comes back out on a response. The engine keeps it where it clears the
retained reason, publishes it beside that reason, and the waiter accepts a
failure only on an exact match. A post that never reached the backend started no
run, so nothing carries its id; another client's run carries its own; and a
reason with no id at all is left to the gallery probe, as before this field
existed. The counter is gone rather than left published, since it invites the
comparison it cannot support.

This also replaces the awaited baseline read added in the previous commit, which
landed in the mount-probe resume path rather than the submit path and left a
stray await in a non-async callback.

* Choose the runner log family from the diagnostic that names one, not from the request going out

Issuing the load request is not the same as a runner starting. The backend can
refuse a sidecar swap or reject extra args before it launches one, and that
failure reaches the same catch with the flag already set, so View logs offered
the newest unrelated llama-server or diffusion-server file on the host.

The family now comes from the runner log path the backend appends to its own
diagnostic, which it names exactly when there is one to name. The family and
the path handed to the action are the same value, so a family naming a runner
can no longer pair with an action that has no path to open, and the
request-issued flag is gone rather than left as a second, weaker answer to the
same question.

* Tighten the comments this PR added

Comments and docstrings only, no code touched: comment_tools.py check passes
over all 14 changed files. Frontend 8191 passed, backend suites green.

* Keep a failed generation's reason until the attempt that ran it can read it

One retained slot is only enough while nothing else runs. A client whose POST
was lost polls once a second, and a queued client can take the slot inside that
window: the run it starts cleared the slot, so the settling client read the
newcomer going active and then idle as its own success and could advance a batch
past an output that never arrived.

Outcomes are now kept per attempt, in a bounded map beside the slot, and the
progress route takes an optional attempt_id and answers about THAT generation.
The slot stays for a client that sends no id, which is what an older one does.
Sixteen entries, oldest first out: only a settling caller reads one and it reads
it within seconds, so this cannot grow with uptime.

* Record a cancelled native generation against its attempt

sd.cpp catches SdCppCancelled ahead of its generic handler, so a run stopped by
an unload or a superseding load wrote only the single retained slot. The keyed
lookup answers whenever a client names its attempt, so that client saw no error
and could read the transition to idle as its own success though no image was
produced. The diffusers engine raises RuntimeError for the same case and reaches
the handler that already records.

* Answer an attempt-specific progress poll about that attempt only

A generation running for someone else says nothing about this one, but the
attempt-specific response still carried the global active flag and step counter.
A client settling a POST that never arrived counted that run as its own, so when
it went idle the client treated it as success and skipped the gallery proof that
would have said no image was produced.

Both engines now publish the running attempt on the active progress branch as
well as the idle one, and a named poll reports active only when the run is that
attempt's, zeroing the step counter otherwise. An unnamed poll still gets the
global answer, which is what the progress bar and an older client read.

* Key a retained outcome to its account, answer it first, and scope the persist window

Two ways a named poll could still be answered about someone else's work.

With managed accounts, a second account starting a generation between this
caller's failure and its next poll sent the caller through the
foreign-generation guard, which answers idle and hidden: a client that had
already seen its own run active read that as success. Retained outcomes are now
keyed by (account, attempt) and the named lookup runs before those guards, which
is safe precisely because of the key: a caller can only ever match its own
account's attempt, and the answer carries nothing about the generation running
now.

The persist window was global too, so records being written for any other Studio
or OpenAI image request held the active override on and a settling caller took
the end of that window for its own success. The attempts inside the window are
now tracked, and a named poll is told only about its own. An unnamed poll keeps
the global answer, which is what the reload mount probe reads.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added since the last pass

Comments only; comment_tools.py check passes on all four files and the PR's own
suite stays at 20 passed.

* Keep retained outcomes off the engine instance

A request can switch the active diffusion engine between diffusers and sd.cpp
while a client is still settling a lost POST. Held on the instance that ran the
generation, that client's reason became unreachable the moment the other engine
took over, and it was told either that its request never arrived or that another
run going idle was its own success.

The store is now one bounded, lock-guarded map for the process, keyed by
(account, attempt) as before, and neither the record nor the lookup takes an
engine.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added since the last pass

Comments only; no code change.

* Update the logged progress snapshot this PR widened

Staging CI caught it: test_generate_progress_route_logs_backend_snapshot pins the exact
dict handed to log_media_generation_progress, and the classification step this PR adds
always sets an error key, None included, so the logged snapshot gained one. The test
passes on main and failed on this head, which makes it a real break rather than an
inherited one. Updated the pinned dict and noted why the key is safe to log: the value is
classified before it goes out, so engine text with its local paths never reaches the log.

116 passed in tests/test_diffusion_routes.py, 21 in the attempt-attribution suite, 11 in
tests/test_formatter_fixed_point.py.

* Keep a cancellation a cancellation, and offer logs only where there are logs

Two review catches, both real.

The cancellation sentinel went through _generate_failure_detail, which maps every
unrecognized reason to the generic fallback. A POST that returns normally answers 409 with
the sentinel and the page treats that as the requested outcome, but a caller settling a
LOST post reads the retained reason through the classifier, so its own Stop came back as
"Image generation failed." and toasted a failure. The sentinel is fixed text already, so
it now passes through unchanged and shouldReportGenerateError recognises it as it does on
the 409 path. Everything else still goes through the classifier.

The View logs action was attached to every generate error, including
"The image generation request did not reach the server.", which never left the browser,
and the 400s the route answers without logging. Settings > Logs cannot hold either, so the
action opened an unrelated current log and pointed at a false diagnosis. It is now gated on
generationFailureWasLogged: only the 500 paths log, and they answer with a classified
reason, which always opens with "Image generation failed.".

Tests: test_a_cancelled_attempt_settles_as_a_cancellation_not_a_failure and a new case in
generation-failure-attribution.test.ts covering the predicate and the page's wiring.
Reverting either fix fails its test ("a cancellation read as a generic failure to the
client settling a lost post"; "the generate error toast still offers logs for a failure
that was never logged"). 138 backend tests in the diffusion route and attribution suites,
frontend 8192 pass / 0 fail, npm run typecheck clean.

* Do not answer an unscoped poll with another account's failure

The keyed outcome store is account-qualified, but the legacy path a poll without an
attempt id takes reads the ENGINE's slot, which is one per process and holds whoever ran
last. The account guards above only hide a generation while it is ACTIVE, so once A's run
had failed and left media_generation, B's unscoped poll on a multi-account installation
was answered with A's classified reason and the attempt id that produced it.

The keyed store is now the authority for that path too: a reason the caller can look up
under its own account is a reason it owns, and anything else is dropped before
classification. A single-identity installation (account_scope() None) has nobody else for
the slot to belong to, so the legacy answer an older client depends on is unchanged.

test_an_unscoped_poll_on_a_multi_account_install_is_not_told_someone_elses_reason covers
all three: the owner of the attempt still gets its reason, the other account gets None
with no attempt id, and the single-account install keeps the legacy answer. Reverting the
scoping fails it ("an unscoped poll was answered with another account's failure"). 138
passed across the diffusion route and attribution suites.

* Offer View logs only where a log can hold the failure

Three review catches, all the same defect in the affordance this PR adds: the action was
attached to failures the server never logged, so Settings > Logs opened an unrelated
current log and pointed at a false diagnosis.

Images. The prefix check was an inference, and classification erases exactly the
distinction it was inferring: the route answers a ValueError with its own reason and never
logs it, but a caller settling a lost POST reads the RETAINED reason, which by then wears
the same "Image generation failed." prefix as an internal failure. The retained record now
carries whether it was logged, the 400 branch marks its attempt unlogged, the poll
publishes error_logged, and the page prefers that over the prefix when it is there. The
prefix rule stays as the fallback for a failure the POST reported directly, where there is
no retained record to ask.

Video. Same shape: the worker's ValueError branch reports a client-input failure without
logging it, and the not-loaded and cancelled sentinels are not logged either.
_finish_generate_job takes error_logged, publishes it on the terminal state, and both
video-page sites (the live poll and the mount-time resume) withhold the action on an
explicit false. A worker that could not start is marked unlogged too, since nothing ran.

Chat. A load can fail before /api/inference/load is sent -- a declined token prompt, an
abort, a preflight guard -- and the backend then has nothing about it anywhere. The hook
tracks whether the request went out and offers the action only when it did or when the
diagnostic names a log. Deliberately NOT fed into the family, which is the pairing an
earlier commit here removed: a request issued is not a runner started.

Tests: test_a_client_input_failure_is_not_reported_as_one_the_log_explains,
test_the_route_marks_and_publishes_whether_the_failure_was_logged,
test_a_video_failure_says_whether_it_reached_the_log, and three frontend cases covering the
retained flag, both video sites and the load gate. Reverting each of the three gates fails
its own test. Backend 25 + 116 + 68 in the attribution, diffusion-route and video-route
suites (the one video-route failure is the quantized-reference-pick case, red on untouched
main); test_video_backend.py is 101 failed / 172 passed identically on this head and on the
merge base, all environment-related. Frontend 8195 pass / 0 fail, npm run typecheck clean.

* Reach the three failure paths the last commit's gates did not cover

A synchronous video refusal. begin_generate can fail before its worker starts, the POST is
rejected, and polling never begins, so neither progress branch can attach the action: this
is the only place it can be offered for that class. Classified refusals carry the
"Video generation failed." prefix and every branch producing one logs the exception first,
while a 400 carries the raw validation text, so the same prefix rule the image side uses
applies here.

The chat load-issued flag moves to onRequestStart, which is the actual send boundary.
loadModel does its own token preparation and abort check first, so a flag set before the
call was still set when that inner prompt was declined and the backend had received
nothing -- the case the previous commit meant to fix, on a path it did not reach.

A generation that fails across a reload. The resumed page has no POST to reject and no
settling loop, so the retained reason is its only channel, and both resume paths looked at
active alone: an idle answer carrying a reason was refreshed away as a finished run. The
resume poll and the mount probe now report it through one helper, gated on what the server
logged and still treating a cancellation as not an error.

Tests: three new frontend cases, one per path, each failing with its own message when its
hunk is reverted. One existing test moved its anchor: video-generate-refusal-resync keyed
off the toast call, which now carries an action, so it anchors on the refusal the catch
builds. Frontend 8198 pass / 0 fail, npm run typecheck clean.

* Keep the rollback out of the target's diagnosis, and cover the logged persist failure

Two follow-ups.

The rollback load set the same request-issued flag as the target, so a target that failed
before its own request went out borrowed the rollback's log -- a log of a load that
SUCCEEDED. Only the target marks it now; the rollback is a different request.

Image persistence is logged (diffusion.persist_failed) but answered with fixed text that
carries no classification prefix, so the one failure whose disk error is only in the log
was the one offering no way to it. The predicate now recognises that message explicitly,
by value rather than by widening the prefix rule, so the unlogged 400s stay excluded.

Tests: two new frontend cases; reverting either fix fails its own. Frontend 8200 pass / 0
fail. Two earlier assertions moved from two setters to one, with the reason stated.

* Report a retained image failure once, not once per navigation

The backend keeps a generation's reason until another run starts, so the idle
mount probe answers with the same one every time the page mounts. The new
replay therefore repeated a failure the user had already seen, once per
navigation back to Images, and twice for the run whose POST did arrive: the
catch toasted it and the next mount toasted it again.

One module-level slot holds the attempt already put in front of the user, and
both the replay and the handler's own catch write it. Module scope rather than
a ref, which the remount being guarded would reset, and deliberately lost on
reload, which is the case the retained reason exists for. One slot is enough
because the progress snapshot attributes at most one run at a time.

* Retain a persist failure, and key the replay guard on unattributed ones too

Two gaps in what the settling and resuming clients can read.

The persist failure is the only one raised after the attempt was already
reported active, and it retained nothing: a client whose POST was lost watched
its attempt go active-to-idle, took that for success, and the images that were
never saved are not in the gallery to contradict it. The reason is now recorded
against the attempt before the finally drops the persist marker, so the
progress poll can answer with it.

And the replay guard keyed on the attempt alone, which the OpenAI images route
never sends, so an unattributed retained reason could never match it and was
toasted again on every mount. The key falls back to the reason itself, which is
what the user is being shown, so the promise is the same in the same terms.

* Answer a queued attempt as pending, and let a reload hear a failed save

Two more channels a settling or resuming client reads.

The engine cannot name an attempt until it holds the generation slot, so a
second run queued behind an active one answered a named poll with active
False. A settling client whose POST was lost then read that as "the request
never arrived", or took the running run's newly saved record for proof that
its own had finished. The request now marks the attempt from before the wait
until the generate call returns, with the persist marker taking over with no
await in between, and the progress route reports a marked attempt as pending
without lending it the running run's step counter.

And a reloaded page polls without an attempt id, so a persist failure recorded
only in the keyed store was invisible to its mount probe: it saw an error-free
idle state and refreshed a gallery that had not changed. The reason is now
parked in the engine's unscoped slot as well, which both engines publish and
clear at the start of the next run, from the OpenAI images route too since
that one never carries an id. Its fixed text passes through classification
unchanged, because "Image generation failed" is wrong about a generation that
succeeded, and the response and the poll must not describe it differently.

Also updated one pinned literal: the OpenAI images 500 for an OOM now carries
the classified cause, which is what this PR is for, and the test still proves
the engine's own words do not leave.

* Read the log flag off the attempt the answer names

A reloaded page polls without an attempt id, and the flag was looked up under
None, so a client-input failure the route deliberately answered without
logging came back as logged and the page offered a log that cannot hold it.

The lookup falls back to the attempt the response attributes the error to,
which is the record mark_generate_failure_unlogged marked. It can only ever be
the caller's own: an unattributable or foreign error is already cleared above
on an install with accounts, and the store is account-qualified.

One source window in the test file widened too, since the handler had grown
past it and those assertions had stopped reaching its end.

* Match a failure class as a whole word, and let a retry supersede its own id

Every exception class reaches the classifier now, so its needles have to be
tokens: "oom" as a substring reported an out-of-memory failure for any message
containing "boom", "bathroom" or "zoom", and told the user to shrink an image
that was never too big. The needles are compiled once as word-bounded
patterns, and the real spellings the engines produce still classify.

And the Tauri client retries a POST whose connection dropped with the same
serialized body, so the same attempt id. A first execution's retained failure
then outranked the retry, which can be queued, running or already successful,
so the settling client declared the attempt failed and ignored the images the
retry had produced. An execution now clears the outcome retained under its id
as it takes it, beside the marker that makes it pending.

* Let a live execution outrank an outcome retained under its id

Clearing the retained outcome when a retry takes the id is not enough on its
own: the predecessor can still be running, and a failure it retains after that
point lands under an id the retry owns. The progress route read the retained
outcome before the markers, so the client reported failure and stopped
settling while the retry was queued or running.

A request holding the id now outranks the retained answer, which covers the
queue wait, the run and the persist window, and the outcome is cleared again
once this execution's own run has happened, so nothing its predecessor left
resurfaces when the markers drop. With no execution holding the id the
retained reason answers as before, which is what a client settling a run that
really did fail needs.

* Keep a stalled persist from answering for a retry that already saved

Persist runs after the engine slot is released, so two executions of one
retried POST can be persisting at once. A retry could generate and persist
successfully while the original's persist stalled, and the original failing
afterwards recorded that failure under the shared id, so the settling client
reported failure while the retry's images sat in the gallery.

Each execution takes a serial, a finished run records itself as the newest for
its attempt, and the persist failure writes neither the retained outcome nor
the unscoped slot once a later execution has finished. An older serial cannot
move that mark backwards, so the order the two persists finish in does not
decide who answers.

* Bound the finished-run bookkeeping, and clear an outcome under its lock

Every generation supplies a fresh attempt id, so the finished-run map kept one
key per generation for the life of the server. Bounded at 64, oldest out
first, like the retained outcomes: the serial only matters while a duplicate
of the same id is still persisting, so an evicted key is an id nothing can
still be racing over.

And clear_generate_failure mutated the outcome store without the lock every
other mutation holds. The bound is a read-then-pop, so an unlocked clear could
land between the eviction test and the popitem and drop one more outcome than
the bound calls for, leaving that client reading its failed generation as
absent.

* Retain the failures raised before a run starts, and clear on a successful save

Two more channels a client whose POST was lost has to be able to read.

The handler inside generate cannot see the raises that precede it: cancelled
while queued for the generation slot, no model loaded, a dead resident server,
a superseding load. Nothing was recorded for those, so settleLostGeneration
reported that the request never reached the server rather than the
cancellation that actually happened. Each now goes through one helper that
records the reason and the attempt it belongs to, in both engines, since the
block that normally stamps the attempt has not run yet.

And a successful save clears whatever is retained under this id: the images
exist, so nothing under it is a failure of this request any more. A duplicate
execution of one retried POST can fail while this one is still writing, and
its reason would otherwise answer a settling client whose images are already
in the gallery. After the save, not before, so a reason still belongs to
whichever execution is the newest if this save fails instead.

* Keep a queued attempt visible to its own client, and clear the unscoped slot on a save

A managed account's attempt can be queued behind ANOTHER account's generation,
and the guards that hide a foreign run answered idle for the poll that names
it, so a settling client whose POST was lost read that as "the request never
arrived" while it was still queued and would later spend GPU time. A live
attempt of the caller's own now passes those guards. Nothing foreign travels
with it: a named poll zeroes the step counter unless the running attempt is
this one, the reason is already suppressed while live, so the answer is
pending and nothing else, and only a request this caller made can set the
marker since the key is account-qualified.

And the unscoped slot means "the last thing that happened", which the engine
only clears when a run STARTS. A persist failure written after a newer run
began therefore outlived it, and an unscoped probe read the older failure
after the newer run had saved successfully. A successful save clears it. The
attempt field is left alone, since a run in flight publishes it and it is only
read beside a reason.

* Order the unscoped slot by execution, record a validation refusal, and mark client-state failures unlogged

The unscoped slot is one per process and the engine clears it only when a run
STARTS, so with two executions overlapping whoever finished last used to win:
an older save wiped a newer failure, and an older failure hid a newer success.
One monotone serial now decides. Both the persist-failure write and the
clear-on-success are gated on it, and the engine's own write is stamped for
the execution whose call it happened in.

The pre-lock validation guards raise before the engine's handler, so nothing
was recorded for them: marking corrects a record, it does not create one, and
a settling client whose POST was lost was told its request never reached the
server when the answer was a refusal the route had already written. The
refusal is retained and then marked, so the record exists and does not claim a
log the route never wrote.

And the pre-run failures the helper records are all answered as 409s or 400s
without logging, so they are retained as unlogged: as logged, the poll
published error_logged true and the page offered the log for an event that is
not in it.

* Announce the load send from authFetch, past its own local refusals

authFetch's account-transition gate refuses locally, with no request going
out, and loadModel announced the send before calling it, so a failed load
offered the server log for a request the backend never saw.

authFetch takes an onRequestStart option now and fires it immediately before
the transport, and loadModel hands its caller's callback through. Both callers
gain the stricter guarantee, chat's log decision and Audio's requestStarted
cancel, and the ordering they relied on is unchanged: after the token prompt,
before the POST.

* Do not leave a retried model replacement standing as a failure

The route retries a DiffusionModelReplacedError once, so the first raise is
not an outcome. The engine had already published the reason on both channels,
and an unscoped progress poll has no attempt id to be marked live by, so an
Images page opened during the queued retry read a terminal failure for a run
that was about to start again. Both records are dropped before the retry lap,
which records its own outcome; the second replacement keeps its 409.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: an unscoped progress poll reports the caller's own queued generation as pending

A reloaded page loses its attempt id and polls without one. While its request waits for the
generation slot the engine still holds the previous run's failure, so the page toasted that stale
reason and stopped polling. Also scope the wiring test to the whole route body.

* Studio: trim comments in the failure-reason change

* Studio: restore license headers and finish truncated docstrings

* Studio: classify a native sd-cli video exit, and order the OpenAI persist failure like /images/generate

The video classifier missed the runner's own 'sd-cli exited <code>' diagnostic, so a native
video crash still read as the bare fallback. The OpenAI images route wrote its persist failure
into the unscoped slot of whichever engine was active, over a later execution's reason.

* Studio: cut the failure-reason change down to what users see

Keep the video failure classifier, the image routes' two unclassified branches, the multi-line
load diagnostic as title plus description, and View logs opening the exact log the diagnostic
names. Drop the per-attempt failure retention for lost POSTs (main's settleLostGeneration already
recovers the result), the request-start plumbing, and the tests that only covered them.

* Studio: match a diagnostic's log path against the listing the sources route already has

Opening Logs from a failure toast walked every log directory a second time (about 9 ms more per
request on 500 files, a 50% rise); the route now hands its own listing over.

* Studio: an older log-sources response never overrides a newer selection

A 404 recovery reselect that finished after a View logs fetch replaced the exact failure log
with the default one.

* Studio: drop the duplicated sd-cli exit test in test_video_routes

* Studio: tighten the View logs request handling

A stale sources response now bails before touching any state, a repeated identical View logs
click carries its own sequence so a mounted Logs tab refetches, and a failed video save offers
its log like a failed image save.

* Studio: trim comments in the failure-reason change

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
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