Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: require full-length music benchmark evidence (#4361)

[._.]/ Adam Eivy942da423d8b3
diff --git a/.changelog/next/fixed-issue-4361.md b/.changelog/next/fixed-issue-4361.md
new file mode 100644
index 0000000000..93df39aee9
--- /dev/null
+++ b/.changelog/next/fixed-issue-4361.md
@@ -0,0 +1 @@
+- Local music renderer profile changes now require full-length listening evidence.
diff --git a/docs/README.md b/docs/README.md
index 2878d7ae83..a4cc685725 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -16,6 +16,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects |
| [QUOTA-BURN.md](./QUOTA-BURN.md) | Quota-burn automation — spending subscription-backed CLI quota before expiry |
| [THREEJS_MODELS.md](./THREEJS_MODELS.md) | Three.js procedural 3D model generation and trust boundary |
+| [features/music-renderer-benchmarks.md](./features/music-renderer-benchmarks.md) | Technical and full-length listening evidence for local music renderer profiles |
| [CONTRIBUTING.md](./CONTRIBUTING.md) | Dev setup (PostgreSQL required), code conventions |
| [GITHUB_ACTIONS.md](./GITHUB_ACTIONS.md) | CI and release workflows |
| [VERSIONING.md](./VERSIONING.md) | SemVer + release process (`/do:release`) |
diff --git a/docs/features/music-renderer-benchmarks.md b/docs/features/music-renderer-benchmarks.md
new file mode 100644
index 0000000000..996626b02a
--- /dev/null
+++ b/docs/features/music-renderer-benchmarks.md
@@ -0,0 +1,82 @@
+# Music renderer benchmark evidence
+
+Performance and memory changes to local music renderers need evidence that the
+full result still works. A short clip, duration number, or aggregate spectral
+metric can miss audible chunk-boundary failures, so technical checks and a
+human listen are separate gates.
+
+## What a benchmark records
+
+`scripts/music_benchmark.py` writes a small JSON report containing:
+
+- prompt and lyrics shape only (character, word, and line counts); the text is
+ never copied into the report;
+- fixed seed, requested duration, renderer/backend version, profile name,
+ elapsed time, and peak VRAM;
+- WAV format, actual duration, RMS/peak/clipping/silence measures, a broad
+ spectral profile, and a SHA-256 output checksum;
+- technical validation status plus an explicit `listeningRequired: true`
+ review marker.
+
+Generated audio and user prompts stay outside Git. Reports are safe to attach
+to a local investigation because they contain no audio bytes or prompt text.
+
+## Technical check
+
+Run the analyzer after a fixed-seed render. Replace the example values with the
+profile and environment being tested:
+
+```bash
+python scripts/music_benchmark.py \
+ --audio /path/to/example.wav \
+ --output /path/to/example-report.json \
+ --prompt-file /path/to/example-prompt.txt \
+ --lyrics-file /path/to/example-lyrics.txt \
+ --duration 180 \
+ --backend-version diffusers-example \
+ --profile balanced \
+ --elapsed-ms 123456 \
+ --peak-vram-mb 24576 \
+ --seed 17
+```
+
+The analyzer expects 16-bit PCM WAV and the shared 32 kHz library rate. It
+rejects malformed or truncated files, unexpected duration, near-silence,
+excessive clipping, and catastrophic broad-band drift against an optional
+baseline report. A rejected report is a failed technical gate. A passed report
+does not approve the music.
+
+For CUDA Diffusers MiniMax Music 3, `--seed` is a sidecar-only benchmark hook:
+
+```bash
+python scripts/generate_minimax_music3.py \
+ --model MiniMaxAI/MiniMax-Music3 \
+ --text "Example instrumental prompt" \
+ --lyrics "[intro]\n[instrumental]\n[outro]" \
+ --duration 180 \
+ --output /path/to/example.wav \
+ --seed 17
+```
+
+The sidecar passes the seed only when the installed Diffusers pipeline exposes a
+`generator` argument. Ordinary PortOS generation does not pass a seed and is
+unchanged. If the installed pipeline has no deterministic generator support,
+the seeded benchmark exits clearly instead of claiming repeatability.
+
+## Required full-length listening review
+
+After technical checks pass, listen to the entire output from beginning to
+end. Repeat the comparison with the prior supported profile using the same
+prompt shape, lyrics shape, duration, and fixed seed. Record:
+
+1. whether the song reaches the intended ending without a cut or repeated
+ chunk;
+2. whether transitions, rhythm, stereo image, and loudness remain coherent;
+3. whether the new profile introduces clicks, silence, clipping, stitching
+ seams, or audible spectral changes;
+4. the reviewer, date, profile, seed, and a short outcome in the local report
+ or release evidence.
+
+Only a report with passing technical checks and an explicit positive
+full-length listening result may support marking a renderer profile as
+supported. Numerical checks never substitute for that listen.
diff --git a/scripts/generate_minimax_music3.py b/scripts/generate_minimax_music3.py
index 9ccf0826db..5c3493ccb6 100644
--- a/scripts/generate_minimax_music3.py
+++ b/scripts/generate_minimax_music3.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
"""MiniMax Music 3 Diffusers sidecar using PortOS' STAGE/RESULT protocol."""
import argparse
+import inspect
import json
import os
import sys
@@ -29,6 +30,22 @@ def to_stereo(audio, np):
return audio.T if audio.shape[1] == 2 else np.stack([audio[0], audio[0]])
+def seeded_generation_kwargs(pipe, torch, seed):
+ """Return a CUDA generator only when this Diffusers pipeline accepts one."""
+ if seed is None:
+ return {}
+ try:
+ parameters = inspect.signature(pipe.__call__).parameters
+ except (TypeError, ValueError):
+ return {}
+ accepts_generator = 'generator' in parameters or any(
+ parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in parameters.values()
+ )
+ if not accepts_generator:
+ return {}
+ return {'generator': torch.Generator(device='cuda').manual_seed(int(seed))}
+
+
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model', required=True)
@@ -37,6 +54,10 @@ def main():
parser.add_argument('--duration', type=float, required=True)
parser.add_argument('--output', required=True)
parser.add_argument('--runtime-dir', default='')
+ # This is intentionally a sidecar-only benchmark hook. The production
+ # server does not pass it, so normal user renders retain the model's
+ # default sampling behavior.
+ parser.add_argument('--seed', type=int, default=None)
args = parser.parse_args()
if args.runtime_dir:
sys.path.insert(0, args.runtime_dir)
@@ -52,11 +73,15 @@ def main():
pipe.load_components(dtype=torch.bfloat16)
pipe.to('cuda')
print('STAGE:generate', file=sys.stderr, flush=True)
+ generation_kwargs = seeded_generation_kwargs(pipe, torch, args.seed)
+ if args.seed is not None and not generation_kwargs:
+ raise RuntimeError('this Diffusers pipeline does not support deterministic --seed generation')
audio = to_numpy(pipe(
prompt=args.text,
lyrics=args.lyrics,
audio_duration=float(max(1, min(300, args.duration))),
output='audios',
+ **generation_kwargs,
)[0], np, torch)
audio = to_stereo(audio, np)
source_rate = int(pipe.sampling_rate)
@@ -69,7 +94,10 @@ def main():
os.makedirs(os.path.dirname(args.output), exist_ok=True)
with wave.open(args.output, 'wb') as wav:
wav.setnchannels(2); wav.setsampwidth(2); wav.setframerate(32000); wav.writeframes(pcm.tobytes())
- print('RESULT:' + json.dumps({'durationSec': len(pcm) / 32000}), flush=True)
+ print('RESULT:' + json.dumps({
+ 'durationSec': len(pcm) / 32000,
+ **({'seed': args.seed, 'seedApplied': True} if args.seed is not None else {}),
+ }), flush=True)
if __name__ == '__main__':
diff --git a/scripts/generate_minimax_music3.test.js b/scripts/generate_minimax_music3.test.js
index 624a9954df..f063a836fc 100644
--- a/scripts/generate_minimax_music3.test.js
+++ b/scripts/generate_minimax_music3.test.js
@@ -46,6 +46,13 @@ const PRELUDE = [
const runPython = (body) => execFileSync(pyBin, ['-c', `${PRELUDE}\n${body}`, script], {
encoding: 'utf8',
}).trim();
+const runPythonWithoutNumpy = (body) => execFileSync(pyBin, ['-c', [
+ 'import importlib.util, json, sys',
+ 'spec = importlib.util.spec_from_file_location("mm3", sys.argv[1])',
+ 'mod = importlib.util.module_from_spec(spec)',
+ 'spec.loader.exec_module(mod)',
+ body,
+].join('\n'), script], { encoding: 'utf8' }).trim();
describe.skipIf(!hasNumpy)('generate_minimax_music3 sidecar helpers', () => {
describe('to_numpy', () => {
@@ -115,3 +122,29 @@ describe.skipIf(!hasNumpy)('generate_minimax_music3 sidecar helpers', () => {
});
});
});
+
+describe.skipIf(!pyBin)('generate_minimax_music3 deterministic benchmark hook', () => {
+ it('builds a CUDA generator for pipelines that expose generator', () => {
+ const out = runPythonWithoutNumpy([
+ 'class Generator:',
+ ' def __init__(self, device): self.device = device',
+ ' def manual_seed(self, seed): self.seed = seed; return self',
+ 'class SeedTorch:',
+ ' Generator = Generator',
+ 'class Supported:',
+ ' def __call__(self, prompt, generator=None): pass',
+ 'r = mod.seeded_generation_kwargs(Supported(), SeedTorch, 17)["generator"]',
+ 'print(json.dumps({"device": r.device, "seed": r.seed}))',
+ ].join('\n'));
+ expect(JSON.parse(out)).toEqual({ device: 'cuda', seed: 17 });
+ });
+
+ it('does not claim deterministic support when generator is absent', () => {
+ const out = runPythonWithoutNumpy([
+ 'class Unsupported:',
+ ' def __call__(self, prompt): pass',
+ 'print(json.dumps(mod.seeded_generation_kwargs(Unsupported(), object(), 17)))',
+ ].join('\n'));
+ expect(JSON.parse(out)).toEqual({});
+ });
+});
diff --git a/scripts/music_benchmark.py b/scripts/music_benchmark.py
new file mode 100644
index 0000000000..434279c7ef
--- /dev/null
+++ b/scripts/music_benchmark.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+"""Technical checks for repeatable local music-renderer benchmark reports.
+
+The analyzer is deliberately conservative: it can reject malformed or
+pathological output, but it never turns numerical checks into an approval of
+musical quality. A passing report still requires a human full-length listen.
+"""
+
+import argparse
+import hashlib
+import json
+import math
+import re
+import sys
+import wave
+from array import array
+from pathlib import Path
+
+
+SCHEMA_VERSION = 1
+TARGET_SAMPLE_RATE = 32000
+SILENCE_RMS_THRESHOLD = 0.001
+SPECTRAL_BAND_EDGES_HZ = (0, 80, 200, 500, 1000, 2000, 4000, 8000, 16000)
+
+
+def text_shape(text):
+ """Summarize text without retaining the prompt or lyrics themselves."""
+ value = text if isinstance(text, str) else ""
+ return {
+ "characters": len(value),
+ "words": len(re.findall(r"\S+", value)),
+ "lines": len(value.splitlines()) if value else 0,
+ }
+
+
+def sha256_file(path):
+ digest = hashlib.sha256()
+ with Path(path).open("rb") as source:
+ for chunk in iter(lambda: source.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _read_pcm16(path):
+ try:
+ with wave.open(str(path), "rb") as wav:
+ channels = wav.getnchannels()
+ sample_width = wav.getsampwidth()
+ sample_rate = wav.getframerate()
+ frame_count = wav.getnframes()
+ if wav.getcomptype() != "NONE":
+ raise ValueError(f"unsupported WAV compression {wav.getcomptype()}")
+ if channels < 1 or sample_rate < 1 or frame_count < 1:
+ raise ValueError("WAV has no usable channels, sample rate, or frames")
+ if sample_width != 2:
+ raise ValueError(f"expected 16-bit PCM WAV, got {sample_width * 8}-bit")
+ raw = wav.readframes(frame_count)
+ except (OSError, EOFError, wave.Error) as error:
+ raise ValueError(f"invalid WAV: {error}") from error
+
+ expected_bytes = frame_count * channels * sample_width
+ if len(raw) != expected_bytes:
+ raise ValueError(f"truncated WAV payload: expected {expected_bytes} bytes, got {len(raw)}")
+
+ samples = array("h")
+ samples.frombytes(raw)
+ if sys.byteorder != "little":
+ samples.byteswap()
+ return samples, channels, sample_rate, frame_count
+
+
+def _spectral_profile(mono_samples, sample_rate):
+ """Return normalized energy in eight broad bands using fixed-size windows."""
+ band_count = len(SPECTRAL_BAND_EDGES_HZ) - 1
+ if not mono_samples:
+ return [0.0] * band_count
+
+ window_size = 256
+ window_count = min(16, max(1, math.ceil(len(mono_samples) / window_size)))
+ window = [0.5 - 0.5 * math.cos(2 * math.pi * index / (window_size - 1)) for index in range(window_size)]
+ energy = [0.0] * band_count
+ half_window = window_size // 2
+
+ for window_index in range(window_count):
+ max_start = max(0, len(mono_samples) - window_size)
+ start = 0 if window_count == 1 else round(window_index * max_start / (window_count - 1))
+ frame = [0.0] * window_size
+ available = min(window_size, len(mono_samples) - start)
+ for index in range(available):
+ frame[index] = mono_samples[start + index] * window[index]
+
+ for bin_index in range(1, half_window + 1):
+ real = 0.0
+ imaginary = 0.0
+ for sample_index, value in enumerate(frame):
+ angle = 2 * math.pi * bin_index * sample_index / window_size
+ real += value * math.cos(angle)
+ imaginary -= value * math.sin(angle)
+ frequency = bin_index * sample_rate / window_size
+ for band_index, (lower, upper) in enumerate(zip(SPECTRAL_BAND_EDGES_HZ, SPECTRAL_BAND_EDGES_HZ[1:])):
+ if lower <= frequency < upper:
+ energy[band_index] += real * real + imaginary * imaginary
+ break
+
+ total = sum(energy)
+ return [value / total for value in energy] if total > 0 else [0.0] * band_count
+
+
+def _spectral_drift(current, baseline):
+ if not isinstance(baseline, list) or len(baseline) != len(current):
+ return None
+ return sum(abs(float(now) - float(was)) for now, was in zip(current, baseline)) / len(current)
+
+
+def analyze_wav(
+ path,
+ expected_duration_sec,
+ baseline_audio=None,
+ expected_sample_rate=TARGET_SAMPLE_RATE,
+ duration_tolerance_sec=1.0,
+ min_rms=0.003,
+ max_silent_frame_ratio=0.98,
+ max_clipping_ratio=0.0005,
+ max_spectral_drift=0.45,
+):
+ """Analyze a renderer output and return ``(audio_metrics, validation_errors)``."""
+ samples, channels, sample_rate, frame_count = _read_pcm16(path)
+ sample_count = len(samples)
+ duration_sec = frame_count / sample_rate
+ peak = max(abs(value) for value in samples) / 32768.0
+ clipping_count = sum(1 for value in samples if abs(value) >= 32767)
+ squared_sum = sum(value * value for value in samples)
+ rms = math.sqrt(squared_sum / sample_count) / 32768.0
+
+ mono = []
+ silent_frames = 0
+ for frame_index in range(frame_count):
+ offset = frame_index * channels
+ frame_sum = 0.0
+ frame_squared_sum = 0.0
+ for channel_index in range(channels):
+ value = samples[offset + channel_index] / 32768.0
+ frame_sum += value
+ frame_squared_sum += value * value
+ frame_rms = math.sqrt(frame_squared_sum / channels)
+ mono.append(frame_sum / channels)
+ if frame_rms <= SILENCE_RMS_THRESHOLD:
+ silent_frames += 1
+
+ spectral_profile = _spectral_profile(mono, sample_rate)
+ spectral_drift = _spectral_drift(
+ spectral_profile,
+ baseline_audio.get("spectralProfile") if isinstance(baseline_audio, dict) else None,
+ )
+ metrics = {
+ "durationSec": round(duration_sec, 6),
+ "sampleRate": sample_rate,
+ "channels": channels,
+ "sampleWidthBits": 16,
+ "rms": round(rms, 8),
+ "peak": round(peak, 8),
+ "clippingRatio": round(clipping_count / sample_count, 8),
+ "silentFrameRatio": round(silent_frames / frame_count, 8),
+ "spectralProfile": [round(value, 8) for value in spectral_profile],
+ "spectralDrift": round(spectral_drift, 8) if spectral_drift is not None else None,
+ }
+
+ errors = []
+ if sample_rate != expected_sample_rate:
+ errors.append(f"unexpected sample rate: expected {expected_sample_rate}, got {sample_rate}")
+ if abs(duration_sec - expected_duration_sec) > duration_tolerance_sec:
+ errors.append(
+ f"unexpected duration: expected {expected_duration_sec:.3f}s ± {duration_tolerance_sec:.3f}s, got {duration_sec:.3f}s",
+ )
+ if rms < min_rms:
+ errors.append(f"near-silent output: RMS {rms:.6f} is below {min_rms:.6f}")
+ if metrics["silentFrameRatio"] > max_silent_frame_ratio:
+ errors.append(
+ f"too much silence: {metrics['silentFrameRatio']:.3%} of frames are below the silence threshold",
+ )
+ if metrics["clippingRatio"] > max_clipping_ratio:
+ errors.append(
+ f"excessive clipping: {metrics['clippingRatio']:.3%} of samples are at full scale",
+ )
+ if spectral_drift is not None and spectral_drift > max_spectral_drift:
+ errors.append(
+ f"catastrophic spectral drift: {spectral_drift:.3f} exceeds {max_spectral_drift:.3f}",
+ )
+ return metrics, errors
+
+
+def build_report(
+ audio_path,
+ prompt,
+ lyrics,
+ requested_duration_sec,
+ backend_version,
+ profile,
+ elapsed_ms,
+ peak_vram_mb,
+ seed,
+ baseline_report=None,
+ **analysis_options,
+):
+ """Build a privacy-preserving benchmark report from one generated WAV."""
+ errors = []
+ try:
+ checksum = sha256_file(audio_path)
+ except OSError as error:
+ checksum = None
+ errors.append(f"could not read output checksum: {error}")
+
+ baseline_audio = baseline_report.get("audio") if isinstance(baseline_report, dict) else None
+ try:
+ audio, audio_errors = analyze_wav(
+ audio_path,
+ requested_duration_sec,
+ baseline_audio=baseline_audio,
+ **analysis_options,
+ )
+ errors.extend(audio_errors)
+ except ValueError as error:
+ audio = {}
+ errors.append(str(error))
+
+ report = {
+ "schemaVersion": SCHEMA_VERSION,
+ "input": {
+ "promptShape": text_shape(prompt),
+ "lyricsShape": text_shape(lyrics),
+ },
+ "run": {
+ "seed": int(seed),
+ "requestedDurationSec": float(requested_duration_sec),
+ "backendVersion": str(backend_version),
+ "profile": str(profile),
+ "elapsedMs": float(elapsed_ms),
+ "peakVramMb": float(peak_vram_mb) if peak_vram_mb is not None else None,
+ },
+ "audio": {
+ "sha256": checksum,
+ **audio,
+ },
+ "validation": {
+ "status": "passed" if not errors else "rejected",
+ "errors": errors,
+ },
+ "review": {
+ "listeningRequired": True,
+ "status": "pending",
+ "metricsAreNotSubjectiveApproval": True,
+ },
+ }
+ return report
+
+
+def _read_text(inline, path):
+ if path:
+ return Path(path).read_text(encoding="utf-8")
+ return inline or ""
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--audio", type=Path, required=True)
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--prompt", default="")
+ parser.add_argument("--prompt-file", type=Path)
+ parser.add_argument("--lyrics", default="")
+ parser.add_argument("--lyrics-file", type=Path)
+ parser.add_argument("--duration", type=float, required=True, help="Requested duration in seconds")
+ parser.add_argument("--backend-version", required=True)
+ parser.add_argument("--profile", required=True)
+ parser.add_argument("--elapsed-ms", type=float, required=True)
+ parser.add_argument("--peak-vram-mb", type=float, required=True)
+ parser.add_argument("--seed", type=int, required=True, help="Fixed sidecar seed used for this benchmark")
+ parser.add_argument("--baseline-report", type=Path)
+ parser.add_argument("--duration-tolerance-sec", type=float, default=1.0)
+ args = parser.parse_args(argv)
+
+ if args.prompt and args.prompt_file:
+ parser.error("use only one of --prompt and --prompt-file")
+ if args.lyrics and args.lyrics_file:
+ parser.error("use only one of --lyrics and --lyrics-file")
+
+ baseline_report = None
+ if args.baseline_report:
+ baseline_report = json.loads(args.baseline_report.read_text(encoding="utf-8"))
+ report = build_report(
+ audio_path=args.audio,
+ prompt=_read_text(args.prompt, args.prompt_file),
+ lyrics=_read_text(args.lyrics, args.lyrics_file),
+ requested_duration_sec=args.duration,
+ backend_version=args.backend_version,
+ profile=args.profile,
+ elapsed_ms=args.elapsed_ms,
+ peak_vram_mb=args.peak_vram_mb,
+ seed=args.seed,
+ baseline_report=baseline_report,
+ duration_tolerance_sec=args.duration_tolerance_sec,
+ )
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ print(json.dumps({"status": report["validation"]["status"], "errors": report["validation"]["errors"]}))
+ return 0 if report["validation"]["status"] == "passed" else 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/music_benchmark.test.js b/scripts/music_benchmark.test.js
new file mode 100644
index 0000000000..8cb8074fc5
--- /dev/null
+++ b/scripts/music_benchmark.test.js
@@ -0,0 +1,102 @@
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { resolveTestPython } from '../server/lib/testHelper.js';
+
+const script = join(dirname(fileURLToPath(import.meta.url)), 'music_benchmark.py');
+const pyBin = resolveTestPython();
+const PRELUDE = [
+ 'import importlib.util, json, math, os, struct, sys, tempfile, wave',
+ 'spec = importlib.util.spec_from_file_location("music_benchmark", sys.argv[1])',
+ 'mod = importlib.util.module_from_spec(spec)',
+ 'spec.loader.exec_module(mod)',
+ 'def write_wav(path, values, sample_rate=32000, channels=2):',
+ ' with wave.open(path, "wb") as wav:',
+ ' wav.setnchannels(channels); wav.setsampwidth(2); wav.setframerate(sample_rate)',
+ ' wav.writeframes(b"".join(struct.pack("<h", value) * channels for value in values))',
+].join('\n');
+
+const runPython = (body) => execFileSync(pyBin, ['-c', `${PRELUDE}\n${body}`, script], {
+ encoding: 'utf8',
+}).trim();
+
+describe.skipIf(!pyBin)('music benchmark analyzer', () => {
+ it('records text shape and technical metadata without retaining prompt content', () => {
+ const output = runPython([
+ 'path = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name',
+ 'write_wav(path, [int(12000 * math.sin(2 * math.pi * 440 * index / 32000)) for index in range(32000)])',
+ 'report = mod.build_report(path, "Example prompt", "[Instrumental]", 1, "diffusers-example", "balanced", 1234, 2048, 17)',
+ 'print(json.dumps(report))',
+ 'os.unlink(path)',
+ ].join('\n'));
+ const report = JSON.parse(output);
+
+ expect(report.input.promptShape).toEqual({ characters: 14, words: 2, lines: 1 });
+ expect(report.input.lyricsShape).toEqual({ characters: 14, words: 1, lines: 1 });
+ expect(report.input).not.toHaveProperty('prompt');
+ expect(report.run).toMatchObject({
+ seed: 17,
+ requestedDurationSec: 1,
+ backendVersion: 'diffusers-example',
+ profile: 'balanced',
+ elapsedMs: 1234,
+ peakVramMb: 2048,
+ });
+ expect(report.audio.sha256).toMatch(/^[0-9a-f]{64}$/);
+ expect(report.validation).toEqual({ status: 'passed', errors: [] });
+ expect(report.review).toEqual({
+ listeningRequired: true,
+ status: 'pending',
+ metricsAreNotSubjectiveApproval: true,
+ });
+ });
+
+ it('rejects silence, clipping, and duration drift', () => {
+ const output = runPython([
+ 'path = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name',
+ 'write_wav(path, [32767] * 20 + [0] * 7980)',
+ 'report = mod.build_report(path, "p", "l", 1, "backend", "profile", 1, 1, 1, duration_tolerance_sec=0.1)',
+ 'print(json.dumps(report["validation"]))',
+ 'os.unlink(path)',
+ ].join('\n'));
+ const validation = JSON.parse(output);
+
+ expect(validation.status).toBe('rejected');
+ expect(validation.errors.join('\n')).toMatch(/near-silent|too much silence/);
+ expect(validation.errors.join('\n')).toMatch(/clipping/);
+ expect(validation.errors.join('\n')).toMatch(/unexpected duration/);
+ });
+
+ it('rejects a large spectral change against a baseline report', () => {
+ const output = runPython([
+ 'baseline_path = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name',
+ 'current_path = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name',
+ 'write_wav(baseline_path, [int(12000 * math.sin(2 * math.pi * 440 * index / 32000)) for index in range(32000)])',
+ 'write_wav(current_path, [int(12000 * math.sin(2 * math.pi * 8000 * index / 32000)) for index in range(32000)])',
+ 'baseline = mod.build_report(baseline_path, "p", "l", 1, "backend", "profile", 1, 1, 1)',
+ 'current = mod.build_report(current_path, "p", "l", 1, "backend", "profile", 1, 1, 1, baseline_report=baseline, max_spectral_drift=0.05)',
+ 'print(json.dumps({"drift": current["audio"]["spectralDrift"], "validation": current["validation"]}))',
+ 'os.unlink(baseline_path); os.unlink(current_path)',
+ ].join('\n'));
+ const result = JSON.parse(output);
+
+ expect(result.drift).toBeGreaterThan(0.05);
+ expect(result.validation.status).toBe('rejected');
+ expect(result.validation.errors.join('\n')).toContain('catastrophic spectral drift');
+ });
+
+ it('reports malformed WAV output as a technical rejection', () => {
+ const output = runPython([
+ 'path = tempfile.NamedTemporaryFile(suffix=".wav", delete=False).name',
+ 'with open(path, "wb") as raw: raw.write(b"not a wav")',
+ 'report = mod.build_report(path, "p", "l", 1, "backend", "profile", 1, 1, 1)',
+ 'print(json.dumps(report["validation"]))',
+ 'os.unlink(path)',
+ ].join('\n'));
+ const validation = JSON.parse(output);
+
+ expect(validation.status).toBe('rejected');
+ expect(validation.errors.join('\n')).toMatch(/invalid WAV|file does not start with RIFF id/);
+ });
+});
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index af5a3c7ebe..e8afd77523 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -25,6 +25,11 @@
* `generateMusic` throws a 503 with that backend's install hint rather than a
* bare spawn error — exactly like the FLUX.2 venv gate.
*
+ * Performance or memory profiles are not supported from metrics alone: the
+ * full-length benchmark protocol in
+ * `docs/features/music-renderer-benchmarks.md` requires an explicit listening
+ * review after the technical checks pass.
+ *
* Output: a WAV written into the shared music library (PATHS.music) under a
* `music-gen-<uuid>.wav` basename, so the picker treats a generated track
* identically to an uploaded one.
@@ -67,6 +72,7 @@ const ACESTEP_SCRIPT = join(__dirname, '../../../scripts/generate_acestep.py');
const ACESTEP15_SCRIPT = join(__dirname, '../../../scripts/generate_acestep15.py');
const MINIMAX_MUSIC3_SCRIPT = join(__dirname, '../../../scripts/generate_minimax_music3.py');
const MINIMAX_MUSIC3_MLX_SCRIPT = join(__dirname, '../../../scripts/generate_minimax_music3_mlx.py');
+export const MUSIC_RENDERER_BENCHMARK_GUIDE = 'docs/features/music-renderer-benchmarks.md';
// Back-compat alias for the pre-multi-engine `buildMusicGenArgs` default.
const SIDECAR_SCRIPT = MUSICGEN_SCRIPT;
@@ -317,6 +323,8 @@ export const ENGINES = Object.freeze({
cudaRequired: true,
executionProfile: 'cuda-bf16-single-gpu',
vramProfiles: MINIMAX_MUSIC3_VRAM_PROFILES,
+ benchmarkGuide: MUSIC_RENDERER_BENCHMARK_GUIDE,
+ requiresFullLengthListening: true,
},
'minimax-music3-mlx': {
id: 'minimax-music3-mlx',
diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.js
index 842424fe3b..a4c9251a82 100644
--- a/server/services/pipeline/musicGen.test.js
+++ b/server/services/pipeline/musicGen.test.js
@@ -36,6 +36,7 @@ import {
MUSIC_VRAM_READINESS,
resolveVramReadiness,
resolveEngineVramReadiness,
+ MUSIC_RENDERER_BENCHMARK_GUIDE,
} from './musicGen.js';
describe('MUSICGEN_MODELS registry', () => {
@@ -146,6 +147,14 @@ describe('ENGINES backend registry', () => {
recommendedVramGb: null,
});
});
+
+ it('keeps MiniMax profile support gated on technical checks plus full-length listening', () => {
+ expect(ENGINES['minimax-music3']).toMatchObject({
+ benchmarkGuide: MUSIC_RENDERER_BENCHMARK_GUIDE,
+ requiresFullLengthListening: true,
+ });
+ expect(MUSIC_RENDERER_BENCHMARK_GUIDE).toBe('docs/features/music-renderer-benchmarks.md');
+ });
});
describe('VRAM readiness', () => {