dynamo-llm 1.7.0

Dynamo LLM Library
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Replay state for one realtime transcription connection.
//!
//! The frontend's `RealtimeSession` drives worker streams and borrows the WebSocket
//! halves owned by `handle_socket`.
//! [`RealtimeRecovery`](super::RealtimeRecovery) owns retry eligibility, the attempt
//! budget, and the recovery deadline. Its [`Journal`] stores the input and output
//! history needed to replace a worker without duplicating client-visible output;
//! it does not own inference state or perform I/O.
//!
//! # Recording unfinished turns
//!
//! Journaling is enabled only with a positive migration limit for PCM transcription
//! sessions with manual commits and no server-side VAD. Recovery also requires the
//! first worker's `session.updated` acknowledgement. Omni sessions are ineligible.
//!
//! [`Journal::record`] retains audio append, commit, and clear events as the frontend
//! queues them for the worker. Turns are ordered: a commit closes the current input
//! turn, and subsequent audio starts another. A clear discards the open turn's audio
//! and leaves a marker until its clear acknowledgement arrives. A committed turn is
//! retired after its terminal transcription event; completed audio is not retained.
//! The journal keeps the original session setup, unfinished turns, and the last
//! completed item's ID mapping, rather than the full conversation.
//!
//! # Replaying and reconciling
//!
//! On an eligible worker failure, [`Journal::start_replay`] returns the saved setup,
//! rewinds each unfinished turn's input cursor, and resets worker-specific IDs.
//! [`Journal::next_replay`] waits for the replacement's session acknowledgement,
//! then supplies saved events in order. The frontend sends these before new input.
//! `RealtimeRecovery` bounds replacement attempts and input replay with one absolute
//! five-second deadline; replayed output can continue after input has drained.
//!
//! Before each client write, [`Journal::reconcile`] maps replacement item IDs back
//! to the IDs already exposed to the client, suppresses duplicate session/commit
//! acknowledgements, and removes transcript delta prefixes already delivered.
//! Prefix matching tolerates different delta boundaries but rejects divergent text
//! or out-of-order output. Final transcripts may revise interim text and are not
//! treated as delta prefixes. A failed client write ends the session without retry.
//!
//! # Limits and disabling recovery
//!
//! Retention is limited per connection to 16 MiB of accounted bytes and 4096 events,
//! including setup. Accounting includes serialized event size, inline structures,
//! IDs, and transcript capacity; it is not an exact heap limit or a shared budget.
//! Overflow, unsupported sessions/events, or worker `error` events disable further
//! recovery while allowing the current worker session to continue.
//!
//! Disabling recovery releases retained input, except for unsent replay events that
//! still belong to the current attempt. Those events move into `unsent` and drain
//! after the frontend's pending event under the existing recovery deadline. Item
//! mappings and unmatched transcript prefixes remain only where needed to reconcile
//! output already in flight. Disabling retries must not discard accepted input or
//! turn already-visible output into duplicates.

use std::collections::VecDeque;
use std::io::{self, Write};

use dynamo_protocols::types::realtime::{
    DynamoRealtimeClientEvent, RealtimeAudioFormats, RealtimeClientEvent,
    RealtimeClientEventSessionUpdate, RealtimeServerEvent, Session,
};

const MAX_RETAINED_BYTES: usize = 16 * 1024 * 1024;
const MAX_RETAINED_EVENTS: usize = 4096;

#[derive(Default)]
struct Turn {
    events: Vec<RealtimeClientEvent>,
    next_event: usize,
    bytes: usize,
    is_committed: bool,
    is_cleared: bool,
    commit_acknowledged: bool,
    has_terminal: bool,
    client_item: Option<String>,
    worker_item: Option<String>,
    prefix: String,
    replay_remaining: usize,
}

/// Only unfinished, ordered ASR turns belong here. Workers own inference state.
pub(super) struct Journal {
    session: Option<RealtimeClientEventSessionUpdate>,
    turns: VecDeque<Turn>,
    unsent: VecDeque<RealtimeClientEvent>,
    is_replaying: bool,
    previous_item: Option<(String, String)>,
    bytes: usize,
    events: usize,
    max_bytes: usize,
    max_events: usize,
    pub(super) is_acknowledged: bool,
    pub(super) waiting_for_session: bool,
}

fn eligible(session: &Session) -> bool {
    matches!(session, Session::RealtimeTranscriptionSession(s)
        if s.audio.input.turn_detection.is_none()
            && matches!(s.audio.input.format, RealtimeAudioFormats::PCMAudioFormat { .. }))
}

impl Journal {
    pub(super) fn new(session: &RealtimeClientEventSessionUpdate) -> Option<Self> {
        if !eligible(&session.session) {
            return None;
        }
        let bytes = retained_size(session);
        if bytes > MAX_RETAINED_BYTES {
            tracing::debug!("Realtime recovery disabled: session exceeds retention limit");
            return None;
        }
        Some(Self {
            session: Some(session.clone()),
            turns: VecDeque::new(),
            unsent: VecDeque::new(),
            is_replaying: false,
            previous_item: None,
            bytes,
            events: 1,
            max_bytes: MAX_RETAINED_BYTES,
            max_events: MAX_RETAINED_EVENTS,
            is_acknowledged: false,
            waiting_for_session: true,
        })
    }

    pub(super) fn can_recover(&self) -> bool {
        self.session.is_some() && self.is_acknowledged
    }

    pub(super) fn disable(&mut self, reason: &'static str) {
        if self.session.take().is_none() {
            return;
        }
        tracing::debug!(reason, "Realtime recovery disabled");
        for turn in &mut self.turns {
            if self.is_replaying {
                // This input still belongs to the current worker, even without future retries.
                self.unsent.extend(turn.events.drain(turn.next_event..));
            }
            turn.events = Vec::new();
            // Keep only reconciliation still needed by output already in flight.
            if turn.replay_remaining == 0 {
                turn.prefix = String::new();
            }
        }
        if self.is_replaying {
            self.turns
                .retain(|turn| turn.client_item.is_some() || turn.worker_item.is_some());
        }
        self.waiting_for_session = false;
        self.bytes = 0;
        self.events = 0;
    }

    pub(super) fn record(&mut self, event: &DynamoRealtimeClientEvent) {
        let DynamoRealtimeClientEvent::OpenAI(event) = event else {
            self.disable("unsupported client event");
            return;
        };
        if !matches!(
            event,
            RealtimeClientEvent::InputAudioBufferAppend(_)
                | RealtimeClientEvent::InputAudioBufferCommit(_)
                | RealtimeClientEvent::InputAudioBufferClear(_)
        ) {
            self.disable("session changed or unsupported client event");
            return;
        }

        let has_open_turn = self
            .turns
            .back()
            .is_some_and(|t| !t.is_committed && !t.is_cleared);
        if matches!(event, RealtimeClientEvent::InputAudioBufferCommit(_))
            && has_open_turn
            && let Some(turn) = self.turns.back_mut()
        {
            turn.is_committed = true;
        }
        if matches!(event, RealtimeClientEvent::InputAudioBufferClear(_))
            && has_open_turn
            && let Some(turn) = self.turns.pop_back()
            && self.session.is_some()
        {
            self.bytes -= turn.bytes;
            self.events -= turn.events.len();
        }
        if self.session.is_none() {
            if matches!(event, RealtimeClientEvent::InputAudioBufferClear(_)) && has_open_turn {
                self.turns.push_back(Turn {
                    is_cleared: true,
                    ..Default::default()
                });
            } else if matches!(event, RealtimeClientEvent::InputAudioBufferCommit(_))
                && let Some(turn) = self.turns.back_mut()
                && !turn.is_cleared
            {
                turn.is_committed = true;
            }
            return;
        }

        let needs_turn =
            !has_open_turn || matches!(event, RealtimeClientEvent::InputAudioBufferClear(_));
        let bytes = retained_size(event) + if needs_turn { size_of::<Turn>() } else { 0 };
        if self.bytes.saturating_add(bytes) > self.max_bytes || self.events >= self.max_events {
            if matches!(event, RealtimeClientEvent::InputAudioBufferClear(_)) {
                self.turns.push_back(Turn {
                    is_cleared: true,
                    ..Default::default()
                });
            }
            self.disable("retention limit exceeded");
            return;
        }
        self.bytes += bytes;
        self.events += 1;
        if needs_turn {
            self.turns.push_back(Turn::default());
        }
        if let Some(turn) = self.turns.back_mut() {
            turn.bytes += bytes;
            turn.is_committed = matches!(event, RealtimeClientEvent::InputAudioBufferCommit(_));
            turn.is_cleared = matches!(event, RealtimeClientEvent::InputAudioBufferClear(_));
            if let Some(event) = clone_audio_event(event) {
                turn.events.push(event);
            }
        }
    }

    pub(super) fn start_replay(&mut self) -> Option<DynamoRealtimeClientEvent> {
        let session = self.session.as_ref()?.clone();
        self.is_replaying = true;
        self.waiting_for_session = true;
        if let Some((worker, client)) = self.previous_item.take() {
            self.bytes -= worker.len() + client.len();
        }
        for turn in &mut self.turns {
            turn.next_event = 0;
            if let Some(id) = turn.worker_item.take() {
                turn.bytes -= id.len();
                self.bytes -= id.len();
            }
            turn.replay_remaining = turn.prefix.len();
        }
        Some(RealtimeClientEvent::SessionUpdate(session).into())
    }

    pub(super) fn next_replay(&mut self) -> Option<DynamoRealtimeClientEvent> {
        if let Some(event) = self.unsent.pop_front() {
            return Some(event.into());
        }
        self.unsent = VecDeque::new();
        if !self.is_replaying || self.waiting_for_session {
            return None;
        }
        for turn in &mut self.turns {
            if let Some(event) = turn.events.get(turn.next_event) {
                turn.next_event += 1;
                return clone_audio_event(event).map(Into::into);
            }
        }
        self.is_replaying = false;
        None
    }

    fn finish_turn(&mut self) {
        if let Some(turn) = self.turns.pop_front() {
            if self.session.is_some() {
                self.bytes -= turn.bytes;
                self.events -= turn.events.len();
            }
            if let (Some(worker), Some(client)) = (turn.worker_item, turn.client_item) {
                if self.session.is_some() {
                    if let Some((worker, client)) = &self.previous_item {
                        self.bytes -= worker.len() + client.len();
                    }
                    self.bytes += worker.len() + client.len();
                }
                self.previous_item = Some((worker, client));
            }
        }
    }

    /// Called immediately before delivering output; a failed write ends the session.
    pub(super) fn reconcile(
        &mut self,
        event: &mut RealtimeServerEvent,
    ) -> Result<bool, &'static str> {
        use RealtimeServerEvent::*;
        match event {
            SessionCreated(_) => return Ok(false),
            SessionUpdated(updated) => {
                let is_duplicate = self.is_acknowledged && self.waiting_for_session;
                self.waiting_for_session = false;
                self.is_acknowledged = true;
                if !eligible(&updated.session) {
                    self.disable("worker acknowledged an unsupported session");
                }
                return Ok(!is_duplicate);
            }
            Error(_) => {
                self.disable("worker application error");
                // An ordered error can cancel replay before the replacement assigns an item ID.
                self.turns
                    .retain(|turn| turn.client_item.is_none() || turn.worker_item.is_some());
                return Ok(true);
            }
            InputAudioBufferCleared(_) => {
                if self.turns.front().is_some_and(|t| t.is_cleared) {
                    self.finish_turn();
                } else if self.session.is_some() {
                    return Err("out-of-order clear acknowledgement");
                }
                return Ok(true);
            }
            _ => {}
        }
        if let InputAudioBufferCommitted(e) = event
            && let Some(previous) = &mut e.previous_item_id
            && let Some((worker, client)) = &self.previous_item
            && previous == worker
        {
            *previous = client.clone();
        }
        let (item_id, delta, is_terminal, is_commit) = match event {
            InputAudioBufferCommitted(e) => (&mut e.item_id, None, false, true),
            ConversationItemInputAudioTranscriptionDelta(e) => {
                (&mut e.item_id, Some(&mut e.delta), false, false)
            }
            ConversationItemInputAudioTranscriptionCompleted(e) => {
                (&mut e.item_id, None, true, false)
            }
            ConversationItemInputAudioTranscriptionFailed(e) => (&mut e.item_id, None, true, false),
            _ => {
                self.disable("unsupported worker event");
                return Ok(true);
            }
        };
        // A recoverable application error may abort a turn without a final event.
        // Once replay is disabled, a new item retires that stale binding.
        while self.session.is_none()
            && self
                .turns
                .front()
                .is_some_and(|turn| turn.worker_item.as_ref().is_some_and(|id| id != item_id))
        {
            self.turns.pop_front();
        }
        let Some(turn) = self.turns.front_mut() else {
            if self.session.is_some() {
                return Err("transcription output without an input turn");
            }
            return Ok(true);
        };
        if turn.is_cleared || (turn.has_terminal && !is_commit) {
            return Ok(false);
        }
        match &turn.worker_item {
            Some(bound) if bound != item_id => return Err("out-of-order transcription output"),
            None => {
                turn.worker_item = Some(item_id.clone());
                let bytes = item_id.len();
                turn.bytes += bytes;
                self.bytes += bytes;
            }
            _ => {}
        }
        if let Some(original) = &turn.client_item {
            *item_id = original.clone();
        } else {
            turn.client_item = Some(item_id.clone());
            turn.bytes += item_id.len();
            self.bytes += item_id.len();
        }

        let mut forward = true;
        if is_commit {
            if !turn.is_committed {
                return Err("commit acknowledgement without a client commit");
            }
            forward = !turn.commit_acknowledged;
            turn.commit_acknowledged = true;
        }
        if let Some(delta) = delta {
            let offset = turn.prefix.len() - turn.replay_remaining;
            let matched = turn.replay_remaining.min(delta.len());
            if turn.prefix.as_bytes()[offset..offset + matched] != delta.as_bytes()[..matched] {
                return Err("replayed transcription diverged");
            }
            // Equal UTF-8 prefixes of complete strings always end on a character boundary.
            turn.replay_remaining -= matched;
            delta.drain(..matched);
            forward = !delta.is_empty();
            if self.session.is_some() && self.bytes.saturating_add(delta.len()) <= self.max_bytes {
                let capacity = turn.prefix.capacity();
                turn.prefix.push_str(delta);
                let added = turn.prefix.capacity() - capacity;
                turn.bytes += added;
                self.bytes += added;
            } else if self.session.is_some() {
                self.disable("transcript retention limit exceeded");
            }
        }
        if is_terminal {
            // Finals may revise an interim hypothesis; they are not delta prefixes.
            let turn = self.turns.front_mut().ok_or("missing terminal turn")?;
            turn.has_terminal = true;
            if !turn.is_committed {
                self.disable("worker completed an open turn");
            }
        }
        if self
            .turns
            .front()
            .is_some_and(|t| t.has_terminal && t.is_committed)
        {
            self.finish_turn();
        }
        if self.bytes > self.max_bytes {
            self.disable("retention limit exceeded");
        }
        Ok(forward)
    }
}

fn clone_audio_event(event: &RealtimeClientEvent) -> Option<RealtimeClientEvent> {
    use RealtimeClientEvent::*;
    Some(match event {
        InputAudioBufferAppend(event) => InputAudioBufferAppend(event.clone()),
        InputAudioBufferCommit(event) => InputAudioBufferCommit(event.clone()),
        InputAudioBufferClear(event) => InputAudioBufferClear(event.clone()),
        _ => return None,
    })
}

fn retained_size(value: &impl serde::Serialize) -> usize {
    struct Counter(usize);
    impl Write for Counter {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            self.0 = self.0.saturating_add(bytes.len());
            Ok(bytes.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }
    let mut count = Counter(size_of_val(value));
    if serde_json::to_writer(&mut count, value).is_err() {
        return usize::MAX;
    }
    count.0
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Value, json};

    fn configuration() -> RealtimeClientEventSessionUpdate {
        serde_json::from_value(json!({"session": {
            "type": "transcription", "audio": {"input": {
                "format": {"type": "audio/pcm", "rate": 24000},
                "transcription": {"model": "asr"}, "turn_detection": null
            }}
        }}))
        .unwrap()
    }

    fn record(journal: &mut Journal, value: Value) {
        journal.record(&serde_json::from_value(value).unwrap());
    }

    fn server(journal: &mut Journal, value: Value) -> Result<Option<Value>, &'static str> {
        let mut event = serde_json::from_value(value).unwrap();
        journal
            .reconcile(&mut event)
            .map(|forward| forward.then(|| serde_json::to_value(event).unwrap()))
    }

    fn acknowledge(journal: &mut Journal) -> Option<Value> {
        server(
            journal,
            json!({
                "type": "session.updated", "event_id": "setup",
                "session": configuration().session
            }),
        )
        .unwrap()
    }

    fn delta(item: &str, text: &str) -> Value {
        json!({"type": "conversation.item.input_audio_transcription.delta",
            "event_id": "delta", "item_id": item, "content_index": 0, "delta": text})
    }

    fn committed(item: &str) -> Value {
        json!({"type": "input_audio_buffer.committed", "event_id": "commit",
            "item_id": item, "previous_item_id": null})
    }

    fn completed(item: &str, text: &str) -> Value {
        json!({"type": "conversation.item.input_audio_transcription.completed",
            "event_id": "done", "item_id": item, "content_index": 0,
            "transcript": text, "usage": {"type": "duration", "seconds": 1.0}})
    }

    #[test]
    fn replay_preserves_unicode_ids_and_acknowledgements_but_allows_final_revisions() {
        let mut journal = Journal::new(&configuration()).unwrap();
        assert!(!journal.can_recover());
        assert!(acknowledge(&mut journal).is_some());
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
        );
        assert!(
            server(&mut journal, delta("original", "hé🙂"))
                .unwrap()
                .is_some()
        );
        record(&mut journal, json!({"type": "input_audio_buffer.commit"}));
        assert!(
            server(&mut journal, committed("original"))
                .unwrap()
                .is_some()
        );

        let bytes = journal.bytes;
        for replacement in ["replacement", "another"] {
            let setup = serde_json::to_value(journal.start_replay().unwrap()).unwrap();
            assert!(setup["session"]["audio"]["input"]["turn_detection"].is_null());
            assert!(journal.next_replay().is_none());
            assert!(acknowledge(&mut journal).is_none());
            assert!(matches!(
                journal.next_replay(),
                Some(DynamoRealtimeClientEvent::OpenAI(
                    RealtimeClientEvent::InputAudioBufferAppend(_)
                ))
            ));
            assert!(matches!(
                journal.next_replay(),
                Some(DynamoRealtimeClientEvent::OpenAI(
                    RealtimeClientEvent::InputAudioBufferCommit(_)
                ))
            ));
            assert!(journal.next_replay().is_none());
            assert!(
                server(&mut journal, delta(replacement, "h"))
                    .unwrap()
                    .is_none()
            );
            assert!(
                server(&mut journal, delta(replacement, "é🙂"))
                    .unwrap()
                    .is_none()
            );
            assert!(
                server(&mut journal, committed(replacement))
                    .unwrap()
                    .is_none()
            );
        }
        assert!(
            journal.bytes <= bytes + 16,
            "replacing worker IDs must release old storage"
        );
        let event = server(&mut journal, delta("another", " next"))
            .unwrap()
            .unwrap();
        assert_eq!(event["item_id"], "original");
        assert_eq!(event["delta"], " next");
        let event = server(&mut journal, completed("another", "A corrected final."))
            .unwrap()
            .unwrap();
        assert_eq!(event["item_id"], "original");
        assert_eq!(event["transcript"], "A corrected final.");
        assert!(journal.turns.is_empty());
        assert_eq!(journal.events, 1);
        assert_eq!(
            journal.bytes,
            retained_size(&configuration()) + "another".len() + "original".len()
        );
    }

    #[test]
    fn queued_turns_clear_and_idle_replay_retain_only_unfinished_input() {
        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "first"}),
        );
        record(&mut journal, json!({"type": "input_audio_buffer.commit"}));
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "discarded"}),
        );
        record(&mut journal, json!({"type": "input_audio_buffer.clear"}));
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "open"}),
        );
        journal.start_replay().unwrap();
        acknowledge(&mut journal);
        let mut replay = Vec::new();
        while let Some(event) = journal.next_replay() {
            replay.push(serde_json::to_value(event).unwrap());
        }
        assert_eq!(replay.len(), 4);
        assert_eq!(replay[0]["audio"], "first");
        assert_eq!(replay[1]["type"], "input_audio_buffer.commit");
        assert_eq!(replay[2]["type"], "input_audio_buffer.clear");
        assert_eq!(replay[3]["audio"], "open");
        server(&mut journal, committed("first")).unwrap();
        server(&mut journal, completed("first", "first")).unwrap();
        assert!(
            server(&mut journal, delta("cleared", "stale"))
                .unwrap()
                .is_none()
        );
        server(
            &mut journal,
            json!({"type": "input_audio_buffer.cleared", "event_id": "clear"}),
        )
        .unwrap();
        assert_eq!(
            server(&mut journal, delta("open", "new")).unwrap().unwrap()["item_id"],
            "open"
        );
        record(&mut journal, json!({"type": "input_audio_buffer.commit"}));
        server(&mut journal, committed("open")).unwrap();
        server(&mut journal, completed("open", "new")).unwrap();
        journal.start_replay().unwrap();
        acknowledge(&mut journal);
        assert!(
            journal.next_replay().is_none(),
            "idle recovery must not replay history"
        );
        assert_eq!(journal.events, 1);
    }

    #[test]
    fn divergence_fails_and_retention_or_application_errors_disable_recovery() {
        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
        );
        server(&mut journal, delta("old", "hé🙂")).unwrap();
        journal.start_replay().unwrap();
        acknowledge(&mut journal);
        assert!(server(&mut journal, delta("new", "hé🙃")).is_err());

        for event_limit in [true, false] {
            let mut journal = Journal::new(&configuration()).unwrap();
            acknowledge(&mut journal);
            if event_limit {
                journal.max_events = 1;
            } else {
                journal.max_bytes = journal.bytes + 1;
            }
            record(
                &mut journal,
                json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
            );
            assert!(!journal.can_recover());
            assert_eq!(journal.events, 0);
            assert!(journal.turns.iter().all(|t| t.events.is_empty()));
        }
        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        assert!(
            server(
                &mut journal,
                json!({"type": "error", "event_id": "invalid",
            "error": {"type": "invalid_request_error", "message": "invalid audio"}})
            )
            .unwrap()
            .is_some()
        );
        assert!(!journal.can_recover());
    }

    #[test]
    fn disabling_recovery_preserves_inflight_output_and_early_finals() {
        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        journal.max_events = 2;
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
        );
        server(&mut journal, delta("old", "hé")).unwrap();
        journal.start_replay().unwrap();
        acknowledge(&mut journal);
        let event = server(&mut journal, delta("new", "héllo"))
            .unwrap()
            .unwrap();
        assert_eq!(event["delta"], "llo");
        assert_eq!(event["item_id"], "old");
        record(&mut journal, json!({"type": "input_audio_buffer.commit"}));
        assert!(
            !journal.can_recover(),
            "commit exceeds the injected event limit"
        );
        server(
            &mut journal,
            json!({"type": "error", "event_id": "invalid", "error": {
                "type": "invalid_request_error", "message": "unsupported event"
            }}),
        )
        .unwrap();
        assert_eq!(
            server(&mut journal, committed("new")).unwrap().unwrap()["item_id"],
            "old"
        );
        assert_eq!(
            server(&mut journal, completed("new", "hello"))
                .unwrap()
                .unwrap()["item_id"],
            "old"
        );
        let mut ack = committed("next");
        ack["previous_item_id"] = json!("new");
        assert_eq!(
            server(&mut journal, ack).unwrap().unwrap()["previous_item_id"],
            "old"
        );

        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
        );
        assert!(
            server(&mut journal, completed("early", "finished before commit"))
                .unwrap()
                .is_some()
        );
        assert!(!journal.can_recover());
        assert!(
            server(&mut journal, completed("early", "duplicate"))
                .unwrap()
                .is_none()
        );
        record(&mut journal, json!({"type": "input_audio_buffer.commit"}));
        assert!(server(&mut journal, committed("early")).unwrap().is_some());
        assert!(journal.turns.is_empty());
    }

    #[test]
    fn retention_overflow_drains_replay_and_preserves_output_reconciliation() {
        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        let frames = [
            json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
            json!({"type": "input_audio_buffer.append", "audio": "BBBB"}),
            json!({"type": "input_audio_buffer.commit"}),
        ];
        for frame in &frames {
            record(&mut journal, frame.clone());
        }
        server(&mut journal, committed("old")).unwrap();
        server(&mut journal, delta("old", "hé🙂")).unwrap();
        journal.start_replay().unwrap();
        acknowledge(&mut journal);
        let pending = journal.next_replay().unwrap();
        assert_eq!(serde_json::to_value(pending).unwrap(), frames[0]);

        journal.max_bytes = journal.bytes;
        assert!(
            server(&mut journal, delta("replacement", "h"))
                .unwrap()
                .is_none()
        );
        assert!(!journal.can_recover());
        for frame in &frames[1..] {
            assert_eq!(
                serde_json::to_value(journal.next_replay().unwrap()).unwrap(),
                *frame
            );
        }
        assert!(journal.next_replay().is_none());
        let event = server(&mut journal, delta("replacement", "é🙂next"))
            .unwrap()
            .unwrap();
        assert_eq!(event["delta"], "next");
        assert_eq!(event["item_id"], "old");
        assert!(
            server(&mut journal, committed("replacement"))
                .unwrap()
                .is_none()
        );
        assert_eq!(
            server(&mut journal, completed("replacement", "hé🙂next"))
                .unwrap()
                .unwrap()["item_id"],
            "old"
        );

        record(&mut journal, frames[0].clone());
        assert!(
            journal.next_replay().is_none(),
            "live input must not be replayed"
        );
    }

    #[test]
    fn error_after_replay_drain_does_not_hide_output_before_a_clear() {
        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        for frame in [
            json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
            json!({"type": "input_audio_buffer.append", "audio": "BBBB"}),
            json!({"type": "input_audio_buffer.commit"}),
            json!({"type": "input_audio_buffer.clear"}),
        ] {
            record(&mut journal, frame);
        }
        server(&mut journal, delta("old", "hello")).unwrap();
        journal.start_replay().unwrap();
        acknowledge(&mut journal);
        journal.next_replay().unwrap();
        journal.max_bytes = journal.bytes;
        server(&mut journal, delta("replacement", "h")).unwrap();
        while journal.next_replay().is_some() {}
        assert!(!journal.is_replaying);
        server(
            &mut journal,
            json!({"type": "error", "event_id": "invalid", "error": {
                "type": "invalid_request_error", "message": "invalid audio"
            }}),
        )
        .unwrap();
        let event = server(&mut journal, committed("residual"))
            .unwrap()
            .unwrap();
        assert_eq!(event["item_id"], "residual");
        assert!(
            server(&mut journal, delta("residual", "next"))
                .unwrap()
                .is_some()
        );
        server(
            &mut journal,
            json!({"type": "input_audio_buffer.cleared", "event_id": "clear"}),
        )
        .unwrap();
    }

    #[test]
    fn application_error_preserves_pending_clear_acknowledgements() {
        let mut journal = Journal::new(&configuration()).unwrap();
        acknowledge(&mut journal);
        record(
            &mut journal,
            json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
        );
        record(&mut journal, json!({"type": "input_audio_buffer.clear"}));
        server(
            &mut journal,
            json!({"type": "error", "event_id": "invalid", "error": {
                "type": "invalid_request_error", "message": "invalid audio"
            }}),
        )
        .unwrap();
        assert!(
            server(&mut journal, delta("cleared", "stale"))
                .unwrap()
                .is_none()
        );
        server(
            &mut journal,
            json!({"type": "input_audio_buffer.cleared", "event_id": "clear"}),
        )
        .unwrap();
        assert!(
            server(&mut journal, delta("fresh", "next"))
                .unwrap()
                .is_some()
        );
    }

    #[test]
    fn application_error_allows_a_new_turn_after_the_worker_cancels_an_open_turn() {
        for stage in ["original", "replacement-unbound", "replacement-bound"] {
            let mut journal = Journal::new(&configuration()).unwrap();
            acknowledge(&mut journal);
            record(
                &mut journal,
                json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
            );
            server(&mut journal, delta("original", "partial")).unwrap();
            if stage != "original" {
                journal.start_replay().unwrap();
                acknowledge(&mut journal);
                while journal.next_replay().is_some() {}
            }
            if stage == "replacement-bound" {
                assert!(
                    server(&mut journal, delta("replacement", "partial"))
                        .unwrap()
                        .is_none()
                );
            }
            server(
                &mut journal,
                json!({"type": "error", "event_id": "invalid", "error": {
                    "type": "invalid_request_error", "code": "invalid_audio",
                    "message": "input audio exceeds 60 seconds"
                }}),
            )
            .unwrap();
            assert!(!journal.can_recover());
            record(
                &mut journal,
                json!({"type": "input_audio_buffer.append", "audio": "AAAA"}),
            );
            record(&mut journal, json!({"type": "input_audio_buffer.commit"}));
            for value in [
                committed("fresh"),
                delta("fresh", "next"),
                completed("fresh", "next"),
            ] {
                let mut event: RealtimeServerEvent = serde_json::from_value(value).unwrap();
                let expected = serde_json::to_value(&event).unwrap();
                assert!(journal.reconcile(&mut event).unwrap());
                assert_eq!(serde_json::to_value(event).unwrap(), expected);
            }
            assert!(journal.turns.is_empty());
        }
    }
}