Skip to content

Studio: MCP audio reports what it applied, explains audio errors, checks takes and cancels by id - #14080

Merged
danielhanchen merged 59 commits into
unslothai:mainfrom
Etherll:studio-mcp-audio-reports-cancel-m4
Oct 19, 2026
Merged

danielhanchen merged 59 commits into
unslothai:mainfrom
Etherll:studio-mcp-audio-reports-cancel-m4

Conversation

@Etherll

@Etherll Etherll commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Includes #14075 (Studio: clearer audio.cpp errors, cleaner Speak/Clone, reproducible takes); review the non-merge commits from 14e6b65 to HEAD (skipping #14075's own fix commits that came in by merge), or git diff dfa58e0347..HEAD against #14075's head.

Summary

An agent using Unsloth Studio over MCP could not tell when a music duration was clamped or an option was dropped, got bare error text from audio.cpp failures, had no way to check a finished take, and could not stop an audio run (cancel said "Audio runs cannot be cancelled"). This adds those four things to the audio routes and the MCP tools.

Changes

Audio routes:

  • /audio/run answers with applied (the music duration_s actually used) and warnings ("duration_s 600 clamped to 240", plus one Ignored option <name> line per entry in ignored_options). Clip rows carry voice_id and source_clip_id, and Separate stem rows carry source_clip_id.
  • /audio/run takes an optional cancel_id. POST /audio/cancel {"cancel_id": ...} stops that run the way a client disconnect does: it answers 499 and saves nothing. The key is namespaced as ("audio", id), so a chat cancel_id cannot stop an audio run. The run registers its id before any model switch, so a cancel sent while a cold model is still loading stops the run once the load ends, before anything is generated. A cancel that arrives while the clips are being saved removes the clips the run made, including an Edit source recording it saved (one an earlier run kept, or one another Edit now plays, stays; an Edit's source handoff and this cleanup share a lock), and still answers 499. A second run under a cancel_id that a running audio run holds gets 409, so one cancel never stops two runs. A cancel that arrives before the run starts is kept for 30 s.
  • New POST /audio/analyze measures an upload, history clip or saved voice: duration, integrated loudness (BS.1770-4, gated), true peak (4x oversampled), clipped samples (runs of 3+ identical samples at full scale that the waveform lands on or leaves more steeply than a smooth peak could: PCM rounds a clean peak to a flat top of L samples that it leaves by at most about ((L + 1) / (L - 1))² quantization steps, so the limit is twice that, using the WAV's own sample width (for 32-bit PCM the float32 spacing near full scale, 2^-24). Clean 16-bit tones from 1 Hz to 2 kHz at 0.99-1.0 of full scale count 0 (400 random tones), and a 2% overdrive counts from 10 Hz to 1 kHz, in 8-bit too, where a clean tone within 1% of full scale also reads as clipped because 8-bit is too coarse to tell the two apart) and the span that holds sound (a final partial 20 ms frame counts, so a 6 ms beep has a span). With expected_text it transcribes with the resident speech-to-text model (or the default) and returns match_score, 1 minus the word error rate, or null when the two texts are too long to align (over 50 million word pairs, about a quarter second of numpy work). Nothing is saved. Clips over 10 minutes get 413. The measurements are in core/inference/audio_metrics.py, which uses numpy only and walks the audio in chunks: a 10-minute 48 kHz stereo clip needs about 21 MiB of working memory on top of the decoded audio, and clipping runs are judged per chunk, so even audio at full scale every other sample stays at a few MiB. Transcript scoring runs off the event loop.
  • An audio.cpp runtime that dies or goes silent mid-request on generate, separate or music now raises a 500 with code runtime_stopped and the message "The audio runtime stopped: . Try again; if it fails again, load the model again." Paths and tokens are removed from the reason. A failure that Studio: clearer audio.cpp errors, cleaner Speak/Clone, reproducible takes #14075 already classified (out of memory and so on) is re-raised unchanged.

MCP tools:

  • generate_audio returns applied, warnings, ignored_options and cancel_id. It accepts a cancel_id and makes one (mcp-<hex>) when omitted. A reused id that is still running or was cancelled in the last 30 s is refused.
  • When the loaded music model makes variations one at a time (variations.how == "sequential" in status), generate_audio sends them take by take under one group_id, reusing take 1's seed, as the Audio page does. A cancel between takes stops before the next POST and keeps the finished takes. A take that fails after earlier takes succeeded becomes a warning instead of losing the finished clips.
  • cancel(kind="audio", id=<cancel_id>) stops a run: between takes it stops locally, otherwise it posts to /api/inference/audio/cancel.
  • Audio route failures with a known code now start with a [code] tag and end with what to do next, from AUDIO_HINTS in studio_mcp/errors.py. For example [out_of_memory] suggests device='cpu' and lists the smaller variants when the error body carries them (the /v1 error envelope that generate_audio reads keeps only the code, so there the hint stays generic), and [runtime_stopped] says to retry once and then reload the model.
  • transcribe gains speakers (labels each segment's speaker; it needs a diarizing model and always uses the stored-audio route) and expected_text (adds match_score).
  • New analyze_audio tool wraps /audio/analyze. It is not marked read-only, because inline audio or a path is uploaded to Unsloth Studio first. If the speech-to-text model is not downloaded, the 409 hint says to run transcribe once or leave out expected_text.
  • studio_status lists the active music model's duration_s min, max and default per mode as audio_music, so an agent can see the clamp range before it asks for a duration.
  • studio/MCP.md documents analyze_audio and the new transcribe arguments. Its cancel row and the "Audio runs cannot be cancelled" sentence are left alone here: Studio: MCP errors, cancels and chat controls agents can act on #14081 rewrites that row into a kind-agnostic form and Studio: MCP agents follow long work in one call and see every model a load unloads #14089 removes the sentence, and those PRs own those lines. The audio kind is documented in the cancel tool's own docstring.

One small edit lands on #14075's code (the only edit outside this PR's own files, in its own commit):

  • d46103b: _CODES in audio_cpp_failures.py gains runtime_stopped, so the worker and orchestrator keep that code when they rebuild a failure.

Testing

New tests:

  • tests/test_audio_metrics.py: a -20 dBFS 1 kHz sine measures -23.0 LUFS and -20.0 dBTP within 0.05; hard clipping is detected and clean full-scale 10 Hz, 100 Hz and 1 kHz sines are not, also as 16-bit WAVs at 10 Hz and 40 Hz and at 50 Hz and 0.999 of full scale, while a 10% overdriven 10 Hz WAV is, and so is an overdriven 100 Hz 8-bit WAV; 8-bit clipping counts on both rails; small chunk sizes give exactly the one-pass numbers; padded silence gives the expected span; silence gives None; cross-checks against pyloudnorm and jiwer when installed.
  • tests/test_audio_analyze_route.py: metrics, match_score with a stubbed transcriber, the speech-to-text 409, non-WAV input through transcode, on both mounts.
  • tests/test_audio_edit_route.py: a cancel during the save removes the source recording the run saved (with or without a kept output) and keeps one an earlier run saved or another Edit now plays.
  • tests/test_audio_run_cancel.py: two concurrent runs with ids A and B; cancelling A gives A 499 and B 200; a chat /cancel with id A stops nothing; a cancel sent during a slow model load gives 499 and never starts generation; a cancel sent while the clip saves gives 499 and removes the saved clip; a second run under a live cancel_id gets 409.
  • tests/test_audio_run_extras.py: applied, clamp and ignored-option warnings, voice_id and source_clip_id on clip rows.
  • tests/test_audio_runtime_stopped.py: generate, separate and music map a mid-request stop to runtime_stopped with no path or token in the message; an attached out_of_memory passes through unchanged; the code survives the worker, orchestrator, route and /v1 envelope.
  • tests/test_mcp_audio_takes.py, tests/test_mcp_audio_reports.py, tests/test_mcp_audio_hints.py: take-by-take runs and cancel during and between takes, reused id refusal, batch mode as one request, reported fields, and [code] hints.

Existing MCP contract tests (test_mcp_server.py, test_mcp_tool_contract.py, test_mcp_no_host_paths.py, test_mcp_tools_audio.py, test_mcp_tools_status.py) are updated for the new tool, the audio cancel kind and the new output fields.

Results on c7d6ade (Linux, CPU):

  • Every test file this PR touches (25 files, including test_audio_run_route.py and test_audio_edit_route.py) plus test_audio_edit_requests.py and test_audio_gallery.py: 1035 passed.
  • On 2e46efe, all tests/test_mcp_*.py: 1475 passed, 3 skipped, 3 failed. The 3 failures are in test_mcp_images.py and fail the same way on Studio: clearer audio.cpp errors, cleaner Speak/Clone, reproducible takes #14075's head (a transformers / huggingface-hub version mismatch in the test venv).
  • A live check on an earlier head: with a dead audio runtime injected on the first request, a fresh agent driving the MCP tools got [runtime_stopped], retried once as the hint says, and got its clip.
  • Negative controls: without the new except branches the three runtime_stopped cases raise the bare runtime error; with runtime_stopped removed from _CODES the orchestrator drops the code; without the namespaced cancel key /audio/cancel stops nothing and a chat /cancel would stop the audio run; without the run-length rule a 2-sample burst counts as clipping; with the cancel registered only after the model switch (the previous code), the slow-load cancel test times out because the run goes on to generate; without the after-save check the save-time cancel answers 200 and keeps the clip.

The first commit (14e6b65) is the shared one-name-per-line reshape of test_mcp_server.py, byte-identical to the same commit in the sibling MCP PRs, so their tool-name additions merge cleanly.

cd studio/backend
python -m pytest tests/test_audio_metrics.py tests/test_audio_analyze_route.py tests/test_audio_run_cancel.py tests/test_audio_run_extras.py tests/test_audio_runtime_stopped.py tests/test_mcp_audio_takes.py tests/test_mcp_audio_reports.py tests/test_mcp_audio_hints.py tests/test_mcp_server.py tests/test_mcp_tool_contract.py tests/test_mcp_no_host_paths.py tests/test_mcp_tools_audio.py tests/test_mcp_tools_status.py -q

Etherll and others added 8 commits October 17, 2026 12:49
…le takes

- audio_cpp_failures.py classifies audio.cpp failures (runtime missing, family
  unknown to the runtime, out of memory, GPU unavailable, eSpeak missing,
  incomplete file) from the upstream messages and returns a structured
  {code, message} detail with a 4xx/503 status instead of the generic 500.
  Out of memory lists smaller variants with a memory estimate and names expert
  offload options when the runtime spec declares them. A GPU that cannot start
  falls back to the CPU once. The update banner can install a missing runtime.
- The audio pages map each code to an existing control: the runtime update,
  the CPU RAM device choice, a smaller variant, or the model selector.
- Options the loaded model does not take are dropped and returned as
  ignored_options, shown with a warning toast.
- Speak and Clone: one voice picker, no "Alias of"/JSON rows, the description
  and Clone language only when the model reads them, saved voices on Speak,
  the reference transcribed automatically when a model needs it and an STT
  model is on disk, and a reference length hint.
- Takes: a Seed field, the seed used returned with each clip and saved in
  history, "Reuse seed" in the clip menu, and sequential music takes sent one
  by one so Stop keeps finished takes, with "Take i of n" status.
…can be measured

/audio/run answers with applied (the music duration_s it used) and warnings (a
clamped duration, each ignored option), clip rows carry voice_id and
source_clip_id, a run sent with cancel_id stops through POST /audio/cancel, and
POST /audio/analyze measures a clip's loudness (BS.1770), true peak, clipping
and speech span, with a match score against expected_text.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-18T13:42:35.490882Z c9cb901 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…takes up front, and name the audio code once
…takes

- Out of memory offers the variant key the variant listing uses, gives CPU advice
  when the run was already on the CPU, and no longer offers CPU RAM there.
- eSpeak is only named when the library or its data is missing.
- Separate returns classified failures; the OOM retry and API monitor read them.
- A CPU fallback after a restart reaches the parent.
- Clone auto-transcribe waits for an idle page; music group ids work over plain HTTP.
- The update banner says "audio runtime" for a first install.
pre-commit-ci Bot and others added 11 commits October 17, 2026 23:24
When history could not keep the first sequential take, the run answered
with inline audio and no clips, so later takes lost the seed and fixed-seed
music models restarted from a new random base. The inline audio now carries
the seed and the takes loop reads it there too.

Also round-trips a capacity failure through from_payload in the tests, and
trims per-line source citations (the strings grep at v0.9.2) to stay within
the size cap.
…take metrics stream in chunks

- /audio/run registers its cancel_id before any model switch and every stage shares that event, so a cancel sent while a cold model loads (longer than the 30 s a stashed cancel is kept) answers 499 instead of generating.
- Clipping counts runs of identical full-scale samples, so a clean 10 Hz tone never counts and the 8-bit positive rail does.
- Loudness, true peak, clipping and the sound span walk the audio in chunks: a 10-minute 48 kHz stereo take peaks at about 21 MiB of working memory instead of about 960 MiB, with the same numbers.
- test_audio_run_route pins the clip keys including voice_id and source_clip_id.
A runtime 4xx 'does not fit in device memory' on a CPU run kept the
GPU-side advice and no device extra, so the page offered Load into CPU
RAM, which fails the same way. It now says to shorten the input and
marks the failure as already on the CPU.
…e phase

The installer can exit 0 without installing anything when the release
lookup cannot answer. That case only changed the message, so the update
job reported success and the page said the runtime was updated. It now
fails the phase, so the action stays retryable.
…s get a span, and transcript scoring is bounded

- /audio/run checks its cancel event once the run is unregistered: a cancel that arrived while the clips were being saved removes the clips the run made (a reused source clip stays) and answers 499.
- The sound span counts the final partial 20 ms frame, so a beep shorter than one frame has a span and the end is not cut short.
- match_score aligns a whole row of the word table at a time with numpy and gives no score past 50 million word pairs, so a long expected_text cannot tie up a worker thread.
@danielhanchen
danielhanchen merged commit 8252333 into unslothai:main Oct 19, 2026
danielhanchen added a commit that referenced this pull request Oct 19, 2026
#14080 and #14081 landed together and their error tagging now overlaps:
`tool_error` (from #14081) leads every route error with its `[code]`
tag, while an audio.cpp failure whose message already starts with
`[out_of_memory]` got the tag a second time (`[out_of_memory]
[out_of_memory] Out of memory.`). Five tests in
`tests/test_mcp_audio_hints.py` fail on main because of it.

- `studio_mcp/errors.py`: `tool_error` leaves a message that already
starts with its own `[code]` tag as it is.
- `tests/test_mcp_audio_hints.py`: the gpu_busy case expects the
`[gpu_busy retry_after=5]` tag #14081 adds (still no audio tag), and the
"other errors" cases check that the audio path returns exactly what the
generic route error returns instead of asserting no tag at all.

`python -m pytest tests/test_mcp_*.py`: 2038 passed, 5 skipped (main: 5
failed in test_mcp_audio_hints.py).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants