asr-core 0.0.3

Unified streaming, offline, and cloud speech-to-text engine for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
use super::*;
use crate::{
    AsrError, AudioBuffer, ErrorKind, Segment, SessionFailure, SessionOptions, SessionOutcome,
    Transcript, TranscriptSnapshotSink,
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

// ---------------------------------------------------------------------------
// Fixtures: one mono PCM16 wav of `secs` seconds (real bytes, so the decode
// layer runs for real) and the stand-in engine the handlers transcribe
// through (no model files).
// ---------------------------------------------------------------------------

fn wav_bytes(sample_rate: u32, secs: u32) -> Vec<u8> {
    let samples = sample_rate * secs;
    let data_len = samples * 2;
    let mut out = Vec::with_capacity(44 + data_len as usize);
    out.extend_from_slice(b"RIFF");
    out.extend_from_slice(&(36 + data_len).to_le_bytes());
    out.extend_from_slice(b"WAVE");
    out.extend_from_slice(b"fmt ");
    out.extend_from_slice(&16u32.to_le_bytes());
    out.extend_from_slice(&1u16.to_le_bytes()); // PCM
    out.extend_from_slice(&1u16.to_le_bytes()); // mono
    out.extend_from_slice(&sample_rate.to_le_bytes());
    out.extend_from_slice(&(sample_rate * 2).to_le_bytes());
    out.extend_from_slice(&2u16.to_le_bytes());
    out.extend_from_slice(&16u16.to_le_bytes());
    out.extend_from_slice(b"data");
    out.extend_from_slice(&data_len.to_le_bytes());
    for i in 0..samples {
        let t = i as f32 / sample_rate as f32;
        let v = (t * 440.0 * 2.0 * std::f32::consts::PI).sin() * 0.3;
        out.extend_from_slice(&((v * i16::MAX as f32) as i16).to_le_bytes());
    }
    out
}

/// The budget the stand-in engine was invoked with, plus the failure kind
/// it answers with (`None` transcribes into a fixed one-segment transcript).
type Captured = std::sync::Arc<std::sync::Mutex<(Option<Duration>, Option<ErrorKind>)>>;

/// The transcript every stand-in engine answers with.
fn fixture_outcome() -> SessionOutcome {
    SessionOutcome {
        transcript: Transcript {
            segments: vec![Segment {
                id: "s0".to_string(),
                index: 0,
                text: "你好世界".to_string(),
                start_seconds: Some(0.0),
                end_seconds: Some(1.0),
            }],
        },
        ..Default::default()
    }
}

/// A stand-in with a streaming face: it reports the given snapshots through
/// the sink (pausing briefly so the handler can observe each one), then
/// answers with the given final text (`Ok`) or a failure of the given kind.
/// `cancelled` records whether the sink reported the consumer gone.
struct ProgressEngine {
    snapshots: Vec<String>,
    outcome: Result<String, ErrorKind>,
    cancelled: Arc<AtomicBool>,
}

impl Transcribe for ProgressEngine {
    fn transcribe(
        &self,
        _buffer: &AudioBuffer,
        _options: SessionOptions,
        _deadline: Instant,
    ) -> SessionResult {
        Ok(fixture_outcome())
    }

    fn supports_streaming(&self) -> bool {
        true
    }

    fn transcribe_streaming(
        &self,
        _buffer: &AudioBuffer,
        _options: SessionOptions,
        _deadline: Instant,
        mut progress: TranscriptSnapshotSink,
    ) -> SessionResult {
        for snapshot in &self.snapshots {
            std::thread::sleep(Duration::from_millis(30));
            if !progress.emit(snapshot) {
                self.cancelled.store(true, Ordering::SeqCst);
                return Err(Box::new(SessionFailure {
                    error: AsrError::new(ErrorKind::Cancelled, "engine", "client went away"),
                    outcome: SessionOutcome::default(),
                }));
            }
        }
        match &self.outcome {
            Ok(text) => Ok(SessionOutcome {
                transcript: Transcript {
                    segments: vec![Segment {
                        id: "s0".to_string(),
                        index: 0,
                        text: text.clone(),
                        start_seconds: Some(0.0),
                        end_seconds: Some(1.0),
                    }],
                },
                ..Default::default()
            }),
            Err(kind) => Err(Box::new(SessionFailure {
                error: AsrError::new(*kind, "engine", "the mock refuses"),
                outcome: SessionOutcome::default(),
            })),
        }
    }
}

struct MockEngine {
    captured: Captured,
}

impl Transcribe for MockEngine {
    fn transcribe(
        &self,
        _buffer: &AudioBuffer,
        _options: SessionOptions,
        deadline: Instant,
    ) -> SessionResult {
        let mut captured = self.captured.lock().unwrap();
        captured.0 = Some(deadline.duration_since(Instant::now()));
        if let Some(kind) = captured.1 {
            return Err(Box::new(SessionFailure {
                error: AsrError::new(kind, "engine", "the mock refuses"),
                outcome: SessionOutcome::default(),
            }));
        }
        Ok(fixture_outcome())
    }
}

/// An engine that never looks at the deadline and only stops when told:
/// the stand-in for a third-party backend that blocks forever.
struct DeadlineBlindEngine {
    release: Arc<AtomicBool>,
}

impl Transcribe for DeadlineBlindEngine {
    fn transcribe(
        &self,
        _buffer: &AudioBuffer,
        _options: SessionOptions,
        _deadline: Instant,
    ) -> SessionResult {
        let started = Instant::now();
        while !self.release.load(Ordering::Relaxed) && started.elapsed() < Duration::from_secs(30) {
            std::thread::sleep(Duration::from_millis(50));
        }
        Ok(fixture_outcome())
    }
}

/// An engine that enforces a one-session budget itself and answers Busy
/// beyond it: the stand-in for the real engine's `max_active_sessions`
/// permit, exercised here through real concurrent HTTP requests.
struct SingleSessionEngine {
    active: Arc<std::sync::Mutex<usize>>,
}

impl Transcribe for SingleSessionEngine {
    fn transcribe(
        &self,
        _buffer: &AudioBuffer,
        _options: SessionOptions,
        _deadline: Instant,
    ) -> SessionResult {
        let mut active = self.active.lock().unwrap();
        *active += 1;
        if *active > 1 {
            *active -= 1;
            return Err(Box::new(SessionFailure {
                error: AsrError::new(ErrorKind::Busy, "engine", "the mock is at its limit"),
                outcome: SessionOutcome::default(),
            }));
        }
        drop(active);
        std::thread::sleep(Duration::from_millis(200));
        *self.active.lock().unwrap() -= 1;
        Ok(fixture_outcome())
    }
}

fn mock_options() -> ServeOptions {
    ServeOptions {
        model_id: "test-model".to_string(),
        family: "SenseVoice".to_string(),
        ..ServeOptions::default()
    }
}

/// Bind the router on a loopback port and return its base URL.
async fn spawn(engine: Arc<dyn Transcribe>, options: ServeOptions) -> String {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        axum::serve(listener, router(engine, options))
            .await
            .unwrap();
    });
    format!("http://{addr}")
}

async fn upload(base: &str, form: reqwest::multipart::Form) -> reqwest::Response {
    reqwest::Client::new()
        .post(format!("{base}/v1/audio/transcriptions"))
        .multipart(form)
        .send()
        .await
        .unwrap()
}

fn file_form(bytes: Vec<u8>) -> reqwest::multipart::Form {
    reqwest::multipart::Form::new().part(
        "file",
        reqwest::multipart::Part::bytes(bytes)
            .file_name("clip.wav")
            .mime_str("audio/wav")
            .unwrap(),
    )
}

// ---------------------------------------------------------------------------
// The HTTP surface: real decode, real multipart, real status mapping.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn a_well_formed_upload_transcribes_to_the_openai_body() {
    let captured: Captured = Captured::default();
    let base = spawn(
        Arc::new(MockEngine {
            captured: captured.clone(),
        }),
        mock_options(),
    )
    .await;
    let response = upload(&base, file_form(wav_bytes(8000, 2))).await;
    assert_eq!(response.status(), 200);
    let body: serde_json::Value = response.json().await.unwrap();
    assert_eq!(body["text"], "你好世界");
}

#[tokio::test]
async fn a_missing_file_field_is_a_named_bad_request() {
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        mock_options(),
    )
    .await;
    let form = reqwest::multipart::Form::new().text("model", "whisper-1");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 400);
    let body: serde_json::Value = response.json().await.unwrap();
    assert!(body["error"]["message"]
        .as_str()
        .unwrap()
        .contains("'file' is required"));
}

#[tokio::test]
async fn unsupported_response_formats_are_refused() {
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("response_format", "verbose_json");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 400);
    let body: serde_json::Value = response.json().await.unwrap();
    assert!(body["error"]["message"]
        .as_str()
        .unwrap()
        .contains("only 'json' and 'text' are supported"));
}

#[tokio::test]
async fn text_response_format_answers_plain_text() {
    // What the crate's own client reads in HttpResponse::Text mode.
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("response_format", "text");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 200);
    let content_type = response
        .headers()
        .get("content-type")
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default()
        .to_string();
    assert!(
        content_type.starts_with("text/plain"),
        "got content-type {content_type}"
    );
    assert_eq!(response.text().await.unwrap(), "你好世界");
}

#[tokio::test]
async fn streaming_answers_the_sse_event_protocol() {
    // The exact wire the crate's own client parses in HttpResponse::Sse
    // mode: delta frames accumulate by appending, done carries the final
    // text, and the stream ends. What a mock engine reports as snapshots
    // ("你" then "你好" then "你好世界") travels as the deltas "你", "好",
    // "世界"; the done frame repeats the final text the one-shot body
    // would carry.
    let base = spawn(
        Arc::new(ProgressEngine {
            snapshots: vec!["你".to_string(), "你好".to_string()],
            outcome: Ok("你好世界".to_string()),
            cancelled: Arc::new(AtomicBool::new(false)),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("stream", "true");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 200);
    let content_type = response
        .headers()
        .get("content-type")
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default()
        .to_string();
    assert!(
        content_type.starts_with("text/event-stream"),
        "got content-type {content_type}"
    );
    let body = response.text().await.unwrap();
    let frames = sse_frames(&body);
    assert_eq!(
        frames
            .iter()
            .map(|(event, _)| event.as_str())
            .collect::<Vec<_>>(),
        [
            "transcript.text.delta",
            "transcript.text.delta",
            "transcript.text.done"
        ]
    );
    assert!(body.contains(r#""delta":"你""#), "{body}");
    assert!(body.contains(r#""delta":"好""#), "{body}");
    assert!(body.contains(r#""text":"你好世界""#), "{body}");
}

/// Parses an SSE body into `(event-name, data-json)` frames. Comment and
/// keep-alive blocks (no `data:`) are skipped; a block whose data is not
/// valid JSON never parses, so malformed frames fail the tests that count
/// frames rather than silently passing.
fn sse_frames(body: &str) -> Vec<(String, serde_json::Value)> {
    let mut frames = Vec::new();
    for block in body.split("\n\n") {
        let mut event = String::new();
        let mut data = Vec::new();
        for line in block.lines() {
            if let Some(name) = line.strip_prefix("event: ") {
                event = name.to_string();
            } else if let Some(payload) = line.strip_prefix("data: ") {
                data.push(payload);
            }
            // Comment lines (keep-alive) carry neither field.
        }
        if let Ok(json) = data.join("\n").parse() {
            frames.push((event, json));
        }
    }
    frames
}

#[tokio::test]
async fn the_wire_opens_with_a_typed_delta_and_types_live_in_the_json() {
    // OpenAI streaming contract, pinned here: the first frame is a
    // transcript.text.delta carrying real text (never a heartbeat,
    // metadata or empty event — a client waiting on it must not stall),
    // and the event type travels inside the JSON `type` field — clients
    // parse that, not the SSE `event:` line, which only mirrors it.
    let base = spawn(
        Arc::new(ProgressEngine {
            snapshots: vec!["hello".to_string(), "hello world".to_string()],
            outcome: Ok("hello world".to_string()),
            cancelled: Arc::new(AtomicBool::new(false)),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("stream", "true");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 200);
    let body = response.text().await.unwrap();
    let frames = sse_frames(&body);
    assert!(!frames.is_empty(), "{body}");
    let (first_event, first_json) = &frames[0];
    assert_eq!(first_event, "transcript.text.delta");
    assert_eq!(first_json["delta"], "hello");
    for (event, json) in &frames {
        assert_eq!(json["type"], *event, "frame without a JSON type: {json}");
    }
    // The terminal frame is the done event with the full text, and the
    // deltas a client appends converge exactly to it.
    let (last_event, last_json) = frames.last().unwrap();
    assert_eq!(last_event, "transcript.text.done");
    assert_eq!(last_json["text"], "hello world");
    let concatenated: String = frames[..frames.len() - 1]
        .iter()
        .map(|(_, json)| json["delta"].as_str().unwrap_or_default())
        .collect();
    assert_eq!(concatenated, "hello world");
}

#[tokio::test]
async fn the_wire_matches_the_openai_sse_fixture_byte_for_byte() {
    // A pinned fixture of the exact frames a generic OpenAI-compatible
    // client parses — `data:` lines carrying JSON with the `type` field,
    // with the `event:` line only mirroring it. Byte-for-byte, so any
    // serialization drift (axum, serde_json ordering) fails loudly here
    // instead of silently on some provider's client.
    let base = spawn(
        Arc::new(ProgressEngine {
            snapshots: vec!["你好".to_string()],
            outcome: Ok("你好世界".to_string()),
            cancelled: Arc::new(AtomicBool::new(false)),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("stream", "true");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 200);
    let body = response.text().await.unwrap();
    let fixture = concat!(
        "event: transcript.text.delta\n",
        "data: {\"delta\":\"你好\",\"type\":\"transcript.text.delta\"}\n",
        "\n",
        "event: transcript.text.done\n",
        "data: {\"text\":\"你好世界\",\"type\":\"transcript.text.done\"}\n",
        "\n",
    );
    assert_eq!(body, fixture);
}

#[tokio::test]
async fn a_snapshot_that_rewrites_sent_text_is_skipped_not_mangled() {
    // The wire format is append-only deltas, so a snapshot that revises
    // what was already sent ("你好" → "您") cannot travel as a delta. The
    // safe degradation: skip the frame (the client's partial lags) and let
    // the done frame carry the truth — never a panic, never a corrupted
    // partial.
    let base = spawn(
        Arc::new(ProgressEngine {
            snapshots: vec!["你好".to_string(), "您".to_string()],
            outcome: Ok("您好".to_string()),
            cancelled: Arc::new(AtomicBool::new(false)),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("stream", "true");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 200);
    let body = response.text().await.unwrap();
    assert!(body.contains(r#""delta":"你好""#), "{body}");
    assert!(!body.contains("您好世界"), "{body}");
    assert!(body.contains(r#""text":"您好""#), "{body}");
}

#[tokio::test]
async fn streaming_engine_failures_travel_as_error_events() {
    // Busy carries the retry hint; Timeout/Backend keep the
    // "transcription failed" message shape of the one-shot mapping.
    let cases = [
        (ErrorKind::Busy, "concurrent-session limit"),
        (ErrorKind::Timeout, "transcription failed"),
        (ErrorKind::Backend, "transcription failed"),
    ];
    for (kind, expected) in cases {
        let base = spawn(
            Arc::new(ProgressEngine {
                snapshots: vec![],
                outcome: Err(kind),
                cancelled: Arc::new(AtomicBool::new(false)),
            }),
            mock_options(),
        )
        .await;
        let form = file_form(wav_bytes(8000, 1)).text("stream", "true");
        let response = upload(&base, form).await;
        // Headers were already sent with 200 before the engine failed; the
        // failure is an in-stream `error` event, not an HTTP status.
        assert_eq!(response.status(), 200, "kind {kind:?}");
        let body = response.text().await.unwrap();
        assert!(body.contains("event: error"), "kind {kind:?}: {body}");
        assert!(body.contains(expected), "kind {kind:?}: {body}");
    }
}

#[tokio::test]
async fn a_disconnecting_client_cancels_the_engine() {
    // The SSE stream keeps the response body open for the whole
    // transcription, so a client that walks away mid-stream must release
    // the engine: dropping the response closes the channel receiver, the
    // sink's next send fails, the engine ends the session early instead of
    // transcribing a transcript nobody will read.
    let cancelled = Arc::new(AtomicBool::new(false));
    let base = spawn(
        Arc::new(ProgressEngine {
            // Enough snapshots that the second one lands after the drop.
            snapshots: (0..50).map(|i| "你".repeat(i + 1)).collect(),
            outcome: Ok("你好世界".to_string()),
            cancelled: cancelled.clone(),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("stream", "true");
    let client = reqwest::Client::new();
    let mut response = client
        .post(format!("{base}/v1/audio/transcriptions"))
        .multipart(form)
        .send()
        .await
        .unwrap();
    // Read one event so the stream has definitely started, then drop it.
    let chunk = response.chunk().await.unwrap().unwrap();
    assert!(!chunk.is_empty());
    drop(response);
    let started = Instant::now();
    while !cancelled.load(Ordering::SeqCst) {
        assert!(
            started.elapsed() < Duration::from_secs(10),
            "the engine was never cancelled"
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

#[tokio::test]
async fn a_non_streaming_wrapper_keeps_the_named_refusal() {
    // An engine wrapper that does not override the streaming face (the
    // trait default) must keep the pre-streaming contract: a clear 400
    // instead of a stream that never carries progress. The default is
    // exercised through a wrapper over the mock rather than a bare mock,
    // mirroring hosts that wrap `Engine` with metrics or queueing.
    struct Wrapper {
        inner: MockEngine,
    }
    impl Transcribe for Wrapper {
        fn transcribe(
            &self,
            buffer: &AudioBuffer,
            options: SessionOptions,
            deadline: Instant,
        ) -> SessionResult {
            self.inner.transcribe(buffer, options, deadline)
        }
    }
    let base = spawn(
        Arc::new(Wrapper {
            inner: MockEngine {
                captured: Captured::default(),
            },
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("stream", "true");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 400);
    let body: serde_json::Value = response.json().await.unwrap();
    assert!(
        body["error"]["message"]
            .as_str()
            .unwrap()
            .contains("no incremental endpoint"),
        "{}",
        body
    );
}

#[tokio::test]
async fn streaming_with_text_format_is_refused() {
    // The SSE data frames carry JSON events; a text-format stream would be
    // neither the plain body the client expects nor parseable events.
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1))
        .text("response_format", "text")
        .text("stream", "true");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 400);
    let body: serde_json::Value = response.json().await.unwrap();
    assert!(
        body["error"]["message"]
            .as_str()
            .unwrap()
            .contains("requires response_format 'json'"),
        "{}",
        body
    );
}

#[tokio::test]
async fn the_body_limit_answers_413() {
    let mut options = mock_options();
    options.max_body_bytes = 128;
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        options,
    )
    .await;
    let response = upload(&base, file_form(wav_bytes(8000, 1))).await;
    assert_eq!(response.status(), 413);
}

#[tokio::test]
async fn engine_failures_map_onto_their_status_codes() {
    for (kind, expected) in [
        (ErrorKind::Busy, 503),
        (ErrorKind::Timeout, 504),
        (ErrorKind::InvalidInput, 400),
        (ErrorKind::Backend, 500),
    ] {
        let captured: Captured = Captured::default();
        captured.lock().unwrap().1 = Some(kind);
        let base = spawn(
            Arc::new(MockEngine {
                captured: captured.clone(),
            }),
            mock_options(),
        )
        .await;
        let response = upload(&base, file_form(wav_bytes(8000, 1))).await;
        assert_eq!(response.status(), expected, "kind {kind:?}");
        let body: serde_json::Value = response.json().await.unwrap();
        assert!(
            body["error"]["message"].as_str().is_some(),
            "kind {kind:?}: the error body names a message"
        );
    }
}

#[tokio::test]
async fn a_pinned_language_matches_or_refuses_the_request() {
    // Pinned "zh": a request saying "zh" transcribes; "en" is refused
    // with the restart hint.
    let mut options = mock_options();
    options.language = Some("zh".to_string());
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        options,
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("language", "zh");
    assert_eq!(upload(&base, form).await.status(), 200);
    let form = file_form(wav_bytes(8000, 1)).text("language", "en");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 400);
    let body: serde_json::Value = response.json().await.unwrap();
    assert!(body["error"]["message"].as_str().unwrap().contains("zh"));

    // Unpinned: any request language is refused — the engine cannot
    // switch at runtime.
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        mock_options(),
    )
    .await;
    let form = file_form(wav_bytes(8000, 1)).text("language", "en");
    let response = upload(&base, form).await;
    assert_eq!(response.status(), 400);
}

#[tokio::test]
async fn an_explicit_timeout_is_the_hard_deadline() {
    // 100 seconds of audio under an explicit 30s wall: the engine sees
    // 30s — the audio length never stretches an explicit budget.
    let captured: Captured = Captured::default();
    let mut options = mock_options();
    options.timeout_secs = Some(30);
    let base = spawn(
        Arc::new(MockEngine {
            captured: captured.clone(),
        }),
        options,
    )
    .await;
    upload(&base, file_form(wav_bytes(8000, 100))).await;
    let budget = captured.lock().unwrap().0.unwrap();
    assert!(
        budget >= Duration::from_secs(29) && budget <= Duration::from_secs(31),
        "expected the explicit 30s wall, got {budget:?}"
    );
}

#[tokio::test]
async fn the_default_policy_stretches_with_the_audio() {
    // Without timeout_secs the built-in policy only seeds the floor:
    // 100s of audio gets audio * 3 = 300s, not 120s.
    let captured: Captured = Captured::default();
    let base = spawn(
        Arc::new(MockEngine {
            captured: captured.clone(),
        }),
        mock_options(),
    )
    .await;
    upload(&base, file_form(wav_bytes(8000, 100))).await;
    let budget = captured.lock().unwrap().0.unwrap();
    assert!(
        budget >= Duration::from_secs(299) && budget <= Duration::from_secs(301),
        "expected the audio-derived 300s budget, got {budget:?}"
    );
}

#[tokio::test]
async fn health_and_models_report_the_loaded_engine() {
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        mock_options(),
    )
    .await;
    let client = reqwest::Client::new();
    let health: serde_json::Value = client
        .get(format!("{base}/health"))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(health["status"], "ok");
    assert_eq!(health["model"], "test-model");
    let models: serde_json::Value = client
        .get(format!("{base}/v1/models"))
        .send()
        .await
        .unwrap()
        .json()
        .await
        .unwrap();
    assert_eq!(models["data"][0]["id"], "test-model");
}

/// The decode budget is the decode layer's input: a wav longer than
/// `max_audio_secs` allows is a 400, before the engine ever sees it. One
/// budget second is measured against 48 kHz, so 7 seconds at 8 kHz
/// (56_000 samples) exceeds the 48_000-sample budget.
#[tokio::test]
async fn the_decode_budget_refuses_over_long_audio() {
    let mut options = mock_options();
    options.max_audio_secs = 1;
    let base = spawn(
        Arc::new(MockEngine {
            captured: Captured::default(),
        }),
        options,
    )
    .await;
    let response = upload(&base, file_form(wav_bytes(8000, 7))).await;
    assert_eq!(response.status(), 400);
    let body: serde_json::Value = response.json().await.unwrap();
    assert!(body["error"]["message"]
        .as_str()
        .unwrap()
        .contains("budget"));
}

// ---------------------------------------------------------------------------
// Resource boundaries: the HTTP layer holds its own walls, so a request
// cannot outlive its budget and concurrency beyond the engine's budget is
// refused rather than queued.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn a_hung_engine_cannot_hang_the_request_past_the_budget() {
    // The mock ignores its deadline entirely; the HTTP layer's wall still
    // ends the request with 504, and the abandoned engine thread is
    // released afterwards so the test runtime can shut down.
    let release = Arc::new(AtomicBool::new(false));
    let mut options = mock_options();
    options.timeout_secs = Some(1);
    let base = spawn(
        Arc::new(DeadlineBlindEngine {
            release: release.clone(),
        }),
        options,
    )
    .await;
    let response = upload(&base, file_form(wav_bytes(8000, 1))).await;
    assert_eq!(response.status(), 504);
    let body: serde_json::Value = response.json().await.unwrap();
    assert!(body["error"]["message"]
        .as_str()
        .unwrap()
        .contains("exceeded the request budget"));
    release.store(true, Ordering::Relaxed);
}

#[tokio::test]
async fn concurrent_requests_beyond_the_engine_budget_answer_503_not_a_queue() {
    let base = spawn(
        Arc::new(SingleSessionEngine {
            active: Arc::new(std::sync::Mutex::new(0)),
        }),
        mock_options(),
    )
    .await;
    let (first, second) = tokio::join!(
        upload(&base, file_form(wav_bytes(8000, 1))),
        upload(&base, file_form(wav_bytes(8000, 1))),
    );
    let mut statuses = [first.status().as_u16(), second.status().as_u16()];
    statuses.sort();
    assert_eq!(
        statuses,
        [200, 503],
        "one request transcribes, the concurrent one is refused"
    );
}

// ---------------------------------------------------------------------------
// The decode policy: webm is refused up front with the opus hint instead
// of the generic probe error.
// ---------------------------------------------------------------------------

#[test]
fn webm_uploads_are_refused_with_the_opus_hint() {
    let mut bytes = vec![0x1A, 0x45, 0xDF, 0xA3];
    bytes.extend_from_slice(&[0x42, 0x82, 0x84, b'w', b'e', b'b', b'm']);
    bytes.extend_from_slice(&[0; 16]);
    let error = decode_upload(&bytes, 3600).unwrap_err();
    assert_eq!(error.kind, ErrorKind::InvalidInput);
    assert!(error.message.contains("opus"), "{}", error.message);
}

#[test]
fn matroska_files_are_not_confused_with_webm() {
    let mut bytes = vec![0x1A, 0x45, 0xDF, 0xA3];
    bytes.extend_from_slice(&[0x42, 0x82, 0x84, b'm', b'a', b't', b'r']);
    bytes.extend_from_slice(b"oska");
    bytes.extend_from_slice(&[0; 16]);
    // Not a webm: the decode layer's generic probe error applies (the
    // bytes are not decodable audio either way — the assert is on the
    // message not naming opus).
    let error = decode_upload(&bytes, 3600).unwrap_err();
    assert!(!error.message.contains("cannot be decoded here"), "{error}");
}