koh 0.9.1

koh — a resilient peer-to-peer remote shell: mosh, rewritten in Rust over iroh
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
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
//! The generic SSP [`Transport`]: one per peer, carrying the local state out and the
//! remote state in. A direct port of mosh's `TransportSender` + `Transport::recv`,
//! restructured as a pure, clock-injected state machine (no I/O, no async).

use std::collections::VecDeque;

use crate::wire::{Fragment, FragmentAssembly, Fragmenter, Instruction, PROTOCOL_VERSION};
use serde::de::DeserializeOwned;
use serde::Serialize;
use tracing::trace;

use crate::ssp::{
    RttEstimator, SyncState, ACK_DELAY, ACK_INTERVAL, ACTIVE_RETRY_TIMEOUT, NEVER,
    RECEIVED_STATES_CAP, SEND_MINDELAY, SENT_STATES_CAP, SHUTDOWN_RETRIES, SHUTDOWN_SENTINEL,
};

/// A state snapshot tagged with its sequence number and the wall-clock ms it was created.
///
/// Internal SSP machinery: `mod transport` is private and the `ssp` re-export was dropped, so this
/// is crate-only and not part of the public API (the never-empty-deque invariant is upheld inside
/// [`Transport`]).
#[derive(Debug, Clone)]
struct TimestampedState<S> {
    timestamp: u64,
    num: u64,
    state: S,
}

/// Outcome of feeding one datagram to [`Transport::recv`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecvOutcome {
    /// Fragment buffered; the instruction it belongs to is not yet complete.
    Incomplete,
    /// A new, newest-in-order remote state was applied. The app should react.
    NewState,
    /// An older (out-of-order) state was inserted; the newest state is unchanged.
    OutOfOrder,
    /// Already had this `new_num`; nothing applied (still processed the ack).
    Duplicate,
    /// The diff's base (`old_num`) is not in our `received_states`; dropped (replay guard).
    MissingBase,
    /// Refused by the anti-accumulation bound: the received-state count ceiling
    /// ([`RECEIVED_STATES_CAP`]) or the per-direction resource budget
    /// ([`SyncState::RECEIVE_BUDGET_UNITS`]) would be exceeded.
    Quenched,
}

/// One synchronization channel to a single peer.
///
/// `Local` is the state this side authors and sends (`UserInput` on the client,
/// `TerminalScreen` on the server). `Remote` is the state it receives.
pub struct Transport<Local: SyncState, Remote: SyncState> {
    // ---- sender side (our authoritative local state) ----
    current_state: Local,
    /// Front = most-recent state known-acked by the peer (the diff base). Back = last
    /// transmitted. Never empty.
    sent_states: VecDeque<TimestampedState<Local>>,
    /// `num` of the newest sent state we believe the peer already has.
    assumed_receiver_num: u64,
    fragmenter: Fragmenter,
    next_ack_time: u64,
    next_send_time: u64,
    /// Newest remote `num` we have received in order — what we advertise as our ack.
    ack_num: u64,
    pending_data_ack: bool,
    last_heard: u64,
    /// Start of the current input-coalescing window, or [`NEVER`] when none is pending.
    mindelay_clock: u64,
    // ---- shutdown ----
    shutdown_in_progress: bool,
    shutdown_tries: u32,
    shutdown_start: u64,
    // ---- receiver side (peer's remote state) ----
    received_states: Vec<TimestampedState<Remote>>,
    assembly: FragmentAssembly,
    /// Snapshot of the remote state the app last consumed via [`get_remote_diff`](Transport::get_remote_diff).
    last_delivered_remote: Remote,
    // ---- shared ----
    rtt: RttEstimator,
    connected: bool,
    /// Datagram payload budget (bytes). Updated from `Connection::max_datagram_size()`.
    mtu: usize,
}

impl<Local: SyncState, Remote: SyncState> Transport<Local, Remote> {
    /// Create a transport at time `now` (ms). `mtu` is the datagram payload budget.
    pub fn new(now: u64, mtu: usize) -> Self {
        let mut sent_states = VecDeque::new();
        sent_states.push_back(TimestampedState {
            timestamp: now,
            num: 0,
            state: Local::default(),
        });
        let received_states = vec![TimestampedState {
            timestamp: now,
            num: 0,
            state: Remote::default(),
        }];
        Self {
            current_state: Local::default(),
            sent_states,
            assumed_receiver_num: 0,
            fragmenter: Fragmenter::new(),
            next_ack_time: now,
            next_send_time: now,
            ack_num: 0,
            pending_data_ack: false,
            last_heard: 0,
            mindelay_clock: NEVER,
            shutdown_in_progress: false,
            shutdown_tries: 0,
            shutdown_start: NEVER,
            received_states,
            // Reassemble inbound instructions under THIS direction's decompressed ceiling: the
            // server (Remote = UserInput) gets the tight keystroke cap, the client (Remote =
            // TerminalScreen) the screen cap (KOH-02).
            assembly: FragmentAssembly::with_limit(Remote::RECV_DECODE_LIMIT),
            last_delivered_remote: Remote::default(),
            rtt: RttEstimator::new(),
            connected: false,
            mtu,
        }
    }

    // ----- never-empty-deque invariant -----
    //
    // `sent_states` and `received_states` are seeded with one element in `new()` and every
    // mutation keeps at least one (the front/last is never the element removed). These helpers are
    // the ONLY place that invariant is unwrapped, so the panic surface is a handful of audited
    // one-liners and any *new* stray `.unwrap()` elsewhere in the impl is still caught by clippy.

    #[expect(clippy::unwrap_used, reason = "sent_states is never empty (invariant)")]
    fn sent_front(&self) -> &TimestampedState<Local> {
        self.sent_states.front().unwrap()
    }
    #[expect(clippy::unwrap_used, reason = "sent_states is never empty (invariant)")]
    fn sent_back(&self) -> &TimestampedState<Local> {
        self.sent_states.back().unwrap()
    }
    #[expect(clippy::unwrap_used, reason = "sent_states is never empty (invariant)")]
    fn sent_back_mut(&mut self) -> &mut TimestampedState<Local> {
        self.sent_states.back_mut().unwrap()
    }
    #[expect(
        clippy::unwrap_used,
        reason = "received_states is never empty (invariant)"
    )]
    fn received_first(&self) -> &TimestampedState<Remote> {
        self.received_states.first().unwrap()
    }
    #[expect(
        clippy::unwrap_used,
        reason = "received_states is never empty (invariant)"
    )]
    fn received_last(&self) -> &TimestampedState<Remote> {
        self.received_states.last().unwrap()
    }

    // ----- accessors / driver hooks -----

    /// Mutable access to the live local state (append input, update the screen, …).
    pub const fn current_mut(&mut self) -> &mut Local {
        &mut self.current_state
    }

    /// Read the live local state. Test-only: production mutates via [`current_mut`](Self::current_mut)
    /// and reads the peer's stream via [`remote_state`](Self::remote_state); it never reads the live
    /// local state back.
    #[cfg(test)]
    pub const fn current(&self) -> &Local {
        &self.current_state
    }

    /// The newest in-order remote state we hold (what the app should render/process).
    pub fn remote_state(&self) -> &Remote {
        &self.received_last().state
    }

    /// `num` of the newest in-order remote state (what we ack to the peer).
    pub fn remote_num(&self) -> u64 {
        self.received_last().num
    }

    /// Consume the change since the app last looked: the diff from the previously-delivered
    /// remote state to the newest one, then collapse stored received states (mosh
    /// `get_remote_diff`). The server uses this to drain newly-typed input for the PTY.
    ///
    /// Intended to be called after a [`recv`](Self::recv) returning [`RecvOutcome::NewState`]. It is
    /// always safe to call regardless: with no new state the returned diff is empty (`diff_from`
    /// against the already-delivered state), so an unconditional caller just gets a no-op.
    pub fn get_remote_diff(&mut self) -> Remote::Diff {
        let newest = self.received_last().state.clone();
        let diff = newest.diff_from(&self.last_delivered_remote);
        // Rationalize the received list against its oldest element (mirror of the send side).
        let oldest = self.received_first().state.clone();
        for s in &mut self.received_states {
            s.state.subtract_prefix(&oldest);
        }
        self.last_delivered_remote = self.received_last().state.clone();
        diff
    }

    /// `num` of the newest local state we have transmitted.
    pub fn newest_sent_num(&self) -> u64 {
        self.sent_back().num
    }

    /// Mark the QUIC connection up/down. While down, [`tick`](Self::tick) sends nothing
    /// and [`wait_time`](Self::wait_time) returns [`NEVER`].
    pub fn set_connected(&mut self, connected: bool) {
        self.connected = connected;
    }

    /// Update the datagram payload budget (from `Connection::max_datagram_size()`).
    pub fn set_mtu(&mut self, mtu: usize) {
        self.mtu = mtu;
    }

    /// Feed a smoothed RTT sample (ms), typically `Connection::rtt()` each tick.
    pub fn observe_rtt(&mut self, rtt_ms: f64) {
        self.rtt.sample(rtt_ms);
    }

    /// The send interval (ms) = `clamp(ceil(SRTT/2), MIN, MAX)`. This — NOT raw SRTT — is what
    /// the adaptive predictor's engage/flag thresholds are tuned against (mosh feeds the same
    /// quantity to `PredictionEngine`; see `terminaloverlay.cc` SRTT handling).
    pub fn send_interval(&self) -> u64 {
        self.rtt.send_interval()
    }

    /// Wall-clock (ms) of the most recent decoded inbound datagram, or 0 if we've never heard
    /// from the peer. Updated on *every* inbound (incl. duplicates/keepalives), so the driver
    /// can drive its "link down / resuming" UI off real liveness rather than only new state.
    pub fn last_heard(&self) -> u64 {
        self.last_heard
    }

    /// Whether the peer has been heard from within the last `window` ms. Returns `false` until
    /// the first datagram is received (so the UI shows "connecting", not "link down", at start).
    pub fn link_up_within(&self, now: u64, window: u64) -> bool {
        self.last_heard > 0 && now.saturating_sub(self.last_heard) <= window
    }

    // ----- shutdown -----

    /// Begin a clean shutdown: outgoing instructions carry the [`SHUTDOWN_SENTINEL`]
    /// `new_num` so the peer flushes our final state, then acks the close.
    pub fn start_shutdown(&mut self, now: u64) {
        if !self.shutdown_in_progress {
            self.shutdown_in_progress = true;
            self.shutdown_start = now;
        }
    }

    pub fn shutdown_in_progress(&self) -> bool {
        self.shutdown_in_progress
    }

    /// The peer has acknowledged our shutdown (our acked base is the sentinel).
    pub fn shutdown_acknowledged(&self) -> bool {
        self.sent_front().num == SHUTDOWN_SENTINEL
    }

    /// We have given up waiting for the peer to ack our shutdown.
    pub fn shutdown_ack_timed_out(&self, now: u64) -> bool {
        if !self.shutdown_in_progress {
            return false;
        }
        self.shutdown_tries >= SHUTDOWN_RETRIES
            || now.saturating_sub(self.shutdown_start) >= ACTIVE_RETRY_TIMEOUT
    }

    // ----- timers -----

    /// Recompute `assumed_receiver_num`, collapse states, and recompute send/ack deadlines.
    /// Idempotent; run at the top of [`tick`](Self::tick) and [`wait_time`](Self::wait_time).
    fn calculate_timers(&mut self, now: u64) {
        self.update_assumed_receiver_state(now);
        self.rationalize_states();

        if self.pending_data_ack && self.next_ack_time > now + ACK_DELAY {
            self.next_ack_time = now + ACK_DELAY;
        }

        let back_ts = self.sent_back().timestamp;
        let interval = self.rtt.send_interval();
        let rto = self.rtt.timeout();
        let recently_heard = self.last_heard + ACTIVE_RETRY_TIMEOUT > now;

        let current_eq_back = self.current_state == self.sent_back().state;
        let current_eq_assumed = self.current_state == *self.assumed_state();
        let current_eq_front = self.current_state == self.sent_front().state;

        if !current_eq_back {
            // (A) new unsent input — coalesce ≥ SEND_MINDELAY, but respect the frame rate.
            if self.mindelay_clock == NEVER {
                self.mindelay_clock = now;
            }
            self.next_send_time = (self.mindelay_clock + SEND_MINDELAY).max(back_ts + interval);
        } else if !current_eq_assumed && recently_heard {
            // (B) nothing new, but the peer may lack our latest — retransmit at frame rate.
            self.next_send_time = back_ts + interval;
            if self.mindelay_clock != NEVER {
                self.next_send_time = self.next_send_time.max(self.mindelay_clock + SEND_MINDELAY);
            }
        } else if !current_eq_front && recently_heard {
            // (C) peer assumed-current but hasn't acked our base — slow retransmit.
            self.next_send_time = back_ts + rto + ACK_DELAY;
        } else {
            // (D) fully in sync (or peer silent > 10s).
            self.next_send_time = NEVER;
        }

        if self.shutdown_in_progress || self.ack_num == SHUTDOWN_SENTINEL {
            self.next_ack_time = back_ts + interval;
        }
    }

    /// `assumed_receiver_num` = newest state we believe the peer holds: the acked base plus
    /// any state sent within `RTO + ACK_DELAY` of now ("benefit of the doubt").
    fn update_assumed_receiver_state(&mut self, now: u64) {
        let horizon = self.rtt.timeout() + ACK_DELAY;
        let mut assumed = self.sent_front().num;
        for s in self.sent_states.iter().skip(1) {
            if now.saturating_sub(s.timestamp) < horizon {
                assumed = s.num;
            } else {
                break;
            }
        }
        self.assumed_receiver_num = assumed;
    }

    /// Express the live state and every stored state relative to the acked base, so diffs
    /// stay small and acked input is physically dropped (see [`SyncState::subtract_prefix`]).
    fn rationalize_states(&mut self) {
        let known = self.sent_front().state.clone();
        self.current_state.subtract_prefix(&known);
        for s in &mut self.sent_states {
            s.state.subtract_prefix(&known);
        }
    }

    fn assumed_idx(&self) -> usize {
        self.sent_states
            .iter()
            .position(|s| s.num == self.assumed_receiver_num)
            .unwrap_or(0)
    }

    #[expect(
        clippy::indexing_slicing,
        reason = "assumed_idx() returns a valid in-bounds position (or 0, and sent_states is non-empty)"
    )]
    fn assumed_state(&self) -> &Local {
        &self.sent_states[self.assumed_idx()].state
    }

    /// Milliseconds until the next send/ack is due, or [`NEVER`] when idle/disconnected.
    pub fn wait_time(&mut self, now: u64) -> u64 {
        self.calculate_timers(now);
        if !self.connected {
            return NEVER;
        }
        let next = self.next_ack_time.min(self.next_send_time);
        if next == NEVER {
            NEVER
        } else {
            next.saturating_sub(now)
        }
    }

    // ----- send -----

    /// Decide whether to send this tick and return the datagrams (encoded [`Fragment`]s) to
    /// transmit. Empty when nothing is due. Mirrors mosh `TransportSender::tick`.
    #[expect(
        clippy::indexing_slicing,
        reason = "assumed_idx() and chosen_idx (0 or assumed_idx) are valid in-bounds positions"
    )]
    pub fn tick(&mut self, now: u64) -> Vec<Vec<u8>> {
        self.calculate_timers(now);
        if !self.connected {
            return Vec::new();
        }
        if now < self.next_ack_time && now < self.next_send_time {
            return Vec::new();
        }

        // Compute the diff against the assumed receiver state, then maybe retarget to the
        // acked base if that is cheaper / self-healing (prospective resend optimization).
        let assumed_idx = self.assumed_idx();
        let mut chosen_idx = assumed_idx;
        // Only the serialized bytes are transmitted; don't hold the typed diff (a repaint can be a
        // few MiB) alive past serialization.
        let mut diff_bytes = encode_diff(
            &self
                .current_state
                .diff_from(&self.sent_states[assumed_idx].state),
        );

        if self.assumed_receiver_num != self.sent_front().num {
            let resend_bytes = encode_diff(&self.current_state.diff_from(&self.sent_front().state));
            let shorter = resend_bytes.len() <= diff_bytes.len();
            let modestly_longer = resend_bytes.len() < 1000
                && resend_bytes.len().saturating_sub(diff_bytes.len()) < 100;
            if shorter || modestly_longer {
                trace!(
                    from_num = self.sent_states[assumed_idx].num,
                    to_num = self.sent_front().num,
                    "retargeting diff to the acked base (prospective resend)"
                );
                chosen_idx = 0;
                diff_bytes = resend_bytes;
            }
        }

        let chosen_base_num = self.sent_states[chosen_idx].num;
        // The diff is empty exactly when the live state equals the chosen base state.
        let is_empty = self.current_state == self.sent_states[chosen_idx].state;

        if is_empty {
            let mut out = Vec::new();
            if now >= self.next_ack_time {
                out = self.send_empty_ack(now);
                self.mindelay_clock = NEVER;
            }
            if now >= self.next_send_time {
                self.next_send_time = NEVER;
                self.mindelay_clock = NEVER;
            }
            out
        } else if now >= self.next_send_time || now >= self.next_ack_time {
            let out = self.send_to_receiver(now, chosen_base_num, diff_bytes);
            self.mindelay_clock = NEVER;
            out
        } else {
            Vec::new()
        }
    }

    /// Assign `new_num`, store the state, build the instruction, and fragment it.
    fn send_to_receiver(&mut self, now: u64, old_num: u64, diff: Vec<u8>) -> Vec<Vec<u8>> {
        let back_num = self.sent_back().num;
        let current_eq_back = self.current_state == self.sent_back().state;
        // saturating_add: once a shutdown sentinel state (num == u64::MAX) is the back, a
        // `+ 1` would overflow (debug panic) before the sentinel override below.
        let new_num = if self.shutdown_in_progress {
            SHUTDOWN_SENTINEL
        } else if current_eq_back {
            back_num
        } else {
            back_num.saturating_add(1)
        };

        if new_num == back_num {
            self.sent_back_mut().timestamp = now; // retransmit: bump ts only
        } else {
            self.add_sent_state(now, new_num, self.current_state.clone());
        }

        let out = self.send_in_fragments(old_num, new_num, diff);
        self.assumed_receiver_num = self.sent_back().num;
        self.next_ack_time = now + ACK_INTERVAL;
        self.next_send_time = NEVER;
        self.pending_data_ack = false;
        out
    }

    /// Pure ack / keep-alive: advances `new_num`, stores the (unchanged) state, empty diff.
    fn send_empty_ack(&mut self, now: u64) -> Vec<Vec<u8>> {
        let back_num = self.sent_back().num;
        // saturating_add so an already-sentinel back never overflows; override for shutdown.
        let new_num = if self.shutdown_in_progress {
            SHUTDOWN_SENTINEL
        } else {
            back_num.saturating_add(1)
        };
        let old_num = self.assumed_receiver_num;
        if new_num == back_num {
            // Repeat of an existing num (e.g. the shutdown sentinel every tick): bump the
            // timestamp, don't push a duplicate-num state and churn `sent_states`.
            self.sent_back_mut().timestamp = now;
        } else {
            self.add_sent_state(now, new_num, self.current_state.clone());
        }
        let out = self.send_in_fragments(old_num, new_num, Vec::new());
        // This empty ack discharges any pending data-ack obligation, so clear the flag (mirroring
        // `send_to_receiver`). Without this, `calculate_timers` keeps yanking `next_ack_time` back to
        // `now + ACK_DELAY` (the guard below uses `pending_data_ack`), so an idle ack-only side would
        // re-emit an empty ack every ~ACK_DELAY ms forever instead of settling onto the much slower
        // ACK_INTERVAL idle cadence (~10x the idle datagram rate — mobile battery/radio cost).
        self.pending_data_ack = false;
        self.next_ack_time = now + ACK_INTERVAL;
        self.next_send_time = NEVER;
        out
    }

    fn send_in_fragments(&mut self, old_num: u64, new_num: u64, diff: Vec<u8>) -> Vec<Vec<u8>> {
        let instr = Instruction {
            protocol_version: PROTOCOL_VERSION,
            old_num,
            new_num,
            ack_num: self.ack_num,
            throwaway_num: self.sent_front().num,
            diff,
        };
        if new_num == SHUTDOWN_SENTINEL {
            self.shutdown_tries += 1;
        }
        trace!(
            old_num,
            new_num,
            ack_num = self.ack_num,
            "sending instruction"
        );
        let frags = match self.fragmenter.fragment(&instr, self.mtu) {
            Ok(f) => f,
            Err(e) => {
                tracing::error!(error=%e, "fragmentation failed");
                return Vec::new();
            }
        };
        frags.iter().filter_map(|f| f.encode().ok()).collect()
    }

    fn add_sent_state(&mut self, now: u64, num: u64, state: Local) {
        self.sent_states.push_back(TimestampedState {
            timestamp: now,
            num,
            state,
        });
        if self.sent_states.len() > SENT_STATES_CAP {
            // Drop the 16th-from-end: keeps the acked base (front) and the recent tail.
            let idx = self.sent_states.len() - 16;
            self.sent_states.remove(idx);
        }
    }

    /// Drop every sent state below `ack` (peer confirmed it holds `ack`). No-op for a stale
    /// ack naming a state we already culled.
    fn process_acknowledgment_through(&mut self, ack: u64) {
        if self.sent_states.iter().any(|s| s.num == ack) {
            self.sent_states.retain(|s| s.num >= ack);
            trace!(
                ack,
                sent_states = self.sent_states.len(),
                "processed peer ack"
            );
        }
    }

    // ----- receive -----

    /// Feed one inbound datagram (an encoded [`Fragment`]). Returns the outcome; on
    /// [`RecvOutcome::NewState`] the app should consume [`remote_state`](Self::remote_state).
    #[expect(
        clippy::unwrap_used,
        clippy::indexing_slicing,
        reason = "ref_idx comes from .position() (valid); last() follows a push (non-empty)"
    )]
    pub fn recv(&mut self, now: u64, datagram: &[u8]) -> RecvOutcome {
        let frag = match Fragment::decode(datagram) {
            Ok(f) => f,
            Err(e) => {
                tracing::warn!(error=%e, "dropping undecodable fragment");
                return RecvOutcome::Incomplete;
            }
        };
        // Any decoded datagram is a sign of life from the peer, so refresh the
        // active-retransmission liveness gate here — NOT only when a new newest-in-order state
        // lands. On a lossy link the peer's retransmits/dups/acks may be all that arrives; if
        // those didn't refresh `last_heard`, we'd stop retransmitting our own state to a peer
        // that is demonstrably still connected (mosh sets last_heard on every recv).
        self.last_heard = now;
        let instr = match self.assembly.add(frag) {
            Ok(Some(i)) => i,
            Ok(None) => return RecvOutcome::Incomplete,
            Err(e) => {
                tracing::warn!(error=%e, "dropping unreassemblable instruction");
                return RecvOutcome::Incomplete;
            }
        };

        // The peer's ack of OUR stream is processed even for dup/out-of-order packets.
        self.process_acknowledgment_through(instr.ack_num);

        // Idempotency: already have this state.
        if self.received_states.iter().any(|s| s.num == instr.new_num) {
            return RecvOutcome::Duplicate;
        }
        // Must hold the diff base, else drop (out-of-order / replay defense).
        let Some(ref_idx) = self
            .received_states
            .iter()
            .position(|s| s.num == instr.old_num)
        else {
            tracing::trace!(
                old_num = instr.old_num,
                "dropping instruction: diff base not held (out-of-order / replay)"
            );
            return RecvOutcome::MissingBase;
        };
        // Clone the base BEFORE the throwaway GC. A peer controls `throwaway_num`, and
        // `process_throwaway_until` legitimately drops every state below it — including this
        // base when `throwaway_num > old_num`. Re-resolving the base after the GC and
        // `.expect()`-ing it is a peer-triggerable panic (remote DoS of a pure state machine).
        // Owning the clone makes the GC harmless.
        let mut new_state = self.received_states[ref_idx].state.clone();

        self.process_throwaway_until(instr.throwaway_num);

        // Anti-accumulation count ceiling: refuse (don't merely throttle) once the received list is
        // at the cap, so a peer that pins `old_num`/`throwaway_num` to prevent collapse can't grow
        // it without bound. Honest peers collapse well below the cap, so this never trips for them.
        if self.received_states.len() >= RECEIVED_STATES_CAP {
            // debug, not warn: off by default (no spam in normal ops), but lets an operator
            // distinguish a throttled hostile peer (KOH-01/02) from a benign duplicate under
            // `RUST_LOG=koh=debug`. Same for the byte-budget quenches below.
            tracing::debug!(
                cap = RECEIVED_STATES_CAP,
                "quenched: received-states count at cap"
            );
            return RecvOutcome::Quenched;
        }

        // Anti-accumulation *byte/units* budget across all retained received states (KOH-01).
        // Summed BEFORE the (potentially multi-MB) decode+apply so a budget-saturated receiver
        // short-circuits without doing the work (K-14): every new state contributes >= 0 units, so
        // once the retained set alone meets the budget the outcome is already Quench — decoding and
        // applying a state only to discard it is wasted CPU/alloc a hostile peer could repeat on
        // every datagram. `received_states <= RECEIVED_STATES_CAP`, so the sum is cheap, and it is
        // recomputed each datagram so it stays correct as `subtract_prefix` shrinks states.
        let retained: usize = self
            .received_states
            .iter()
            .map(|s| s.state.resource_units())
            .sum();
        if retained >= Remote::RECEIVE_BUDGET_UNITS {
            tracing::debug!(
                retained_units = retained,
                budget = Remote::RECEIVE_BUDGET_UNITS,
                "quenched: receive byte budget saturated (pre-decode)"
            );
            return RecvOutcome::Quenched;
        }

        if !instr.diff.is_empty() {
            match decode_diff::<Remote::Diff>(&instr.diff) {
                Ok(d) => new_state.apply(&d),
                Err(e) => {
                    tracing::warn!(error=%e, "dropping instruction with undecodable diff");
                    return RecvOutcome::Incomplete;
                }
            }
        }

        // Precise check now that the new state is fully built: its exact size against the
        // already-summed retained budget (received_states is unchanged by decode/apply above).
        if retained.saturating_add(new_state.resource_units()) > Remote::RECEIVE_BUDGET_UNITS {
            tracing::debug!(
                budget = Remote::RECEIVE_BUDGET_UNITS,
                "quenched: receive byte budget exceeded by new state (post-decode)"
            );
            return RecvOutcome::Quenched;
        }

        let ts = TimestampedState {
            timestamp: now,
            num: instr.new_num,
            state: new_state,
        };

        // Insert sorted by num (handles reordering).
        if let Some(pos) = self.received_states.iter().position(|s| s.num > ts.num) {
            self.received_states.insert(pos, ts);
            RecvOutcome::OutOfOrder
        } else {
            self.received_states.push(ts);
            // Newest in-order state: advance our ack, owe a fast ack. (`last_heard` was
            // already refreshed for this datagram above, on any decoded inbound.)
            self.ack_num = self.received_states.last().unwrap().num;
            if !instr.diff.is_empty() {
                self.pending_data_ack = true;
            }
            RecvOutcome::NewState
        }
    }

    /// GC received states below `throwaway_num` (the peer's acked base). Always keeps ≥ 1.
    fn process_throwaway_until(&mut self, throwaway_num: u64) {
        if self.received_states.len() <= 1 {
            return;
        }
        let keep_from = self
            .received_states
            .iter()
            .position(|s| s.num >= throwaway_num)
            .unwrap_or(0);
        if keep_from > 0 {
            self.received_states.drain(0..keep_from);
        }
    }
}

/// Serialize a typed diff for the wire. A no-change diff still serializes to a few bytes,
/// which is why emptiness is decided by state equality, not by this length.
#[expect(
    clippy::expect_used,
    reason = "postcard serialization of our own Serialize types into a Vec is infallible"
)]
fn encode_diff<D: Serialize>(diff: &D) -> Vec<u8> {
    postcard::to_allocvec(diff).expect("diff serialization is infallible for our types")
}

fn decode_diff<D: DeserializeOwned>(bytes: &[u8]) -> Result<D, postcard::Error> {
    postcard::from_bytes(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::wire::{Fragmenter, Instruction};
    use serde::{Deserialize, Serialize};

    /// A trivial absolute-value state: each diff fully describes the target, so we can craft
    /// arbitrary instructions without worrying about diff bases.
    #[derive(Clone, Default, PartialEq, Debug)]
    struct Abs(u64);
    #[derive(Serialize, Deserialize, Clone)]
    struct AbsDiff(u64);
    impl SyncState for Abs {
        type Diff = AbsDiff;
        // Cost-free test stub: declare the (now-required) bounds explicitly as unbounded/zero.
        const RECV_DECODE_LIMIT: usize = crate::wire::MAX_DECOMPRESSED;
        const RECEIVE_BUDGET_UNITS: usize = usize::MAX;
        fn resource_units(&self) -> usize {
            0
        }
        fn diff_from(&self, _base: &Self) -> AbsDiff {
            AbsDiff(self.0)
        }
        fn apply(&mut self, d: &AbsDiff) {
            self.0 = d.0;
        }
    }

    fn instr(old: u64, new: u64, throwaway: u64, val: u64) -> Instruction {
        Instruction {
            protocol_version: PROTOCOL_VERSION,
            old_num: old,
            new_num: new,
            ack_num: 0,
            throwaway_num: throwaway,
            diff: postcard::to_allocvec(&AbsDiff(val)).unwrap(),
        }
    }

    /// Encode a (small) instruction as a single datagram, the way the wire layer ships it.
    ///
    /// Each call models a DISTINCT send from the peer's single, monotonic [`Fragmenter`] (one per
    /// connection in production — see `Transport::fragmenter`), so it stamps a fresh increasing
    /// fragment id. Reusing the RETURNED bytes (not calling this again) reproduces the same id and is
    /// therefore a genuine byte-identical replay — which is exactly what the fragment-layer replay
    /// gate (K-06) drops. A fresh `Fragmenter::new()` per call (the old helper) instead reused id 1
    /// for every datagram, which no real sender does and which the replay gate would treat as a
    /// replay of the first instruction.
    fn datagram(i: &Instruction) -> Vec<u8> {
        thread_local! {
            static NEXT_FRAG_ID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
        }
        let id = NEXT_FRAG_ID.with(|c| {
            let v = c.get();
            c.set(v + 1);
            v
        });
        let mut frags = Fragmenter::new().fragment(i, 1200).unwrap();
        assert_eq!(frags.len(), 1, "test instruction must fit one fragment");
        frags[0].id = id;
        frags[0].encode().unwrap()
    }

    /// An absolute state whose "resource cost" is its value, with a tiny receive budget — so the
    /// anti-accumulation bound can be exercised without crafting megabytes of input (KOH-01).
    #[derive(Clone, Default, PartialEq, Debug)]
    struct Grow(u64);
    #[derive(Serialize, Deserialize, Clone)]
    struct GrowDiff(u64);
    impl SyncState for Grow {
        type Diff = GrowDiff;
        const RECV_DECODE_LIMIT: usize = crate::wire::MAX_DECOMPRESSED;
        const RECEIVE_BUDGET_UNITS: usize = 100;
        fn resource_units(&self) -> usize {
            self.0 as usize
        }
        fn diff_from(&self, _base: &Self) -> GrowDiff {
            GrowDiff(self.0)
        }
        fn apply(&mut self, d: &GrowDiff) {
            self.0 = d.0;
        }
    }

    fn grow_datagram(old: u64, new: u64, throwaway: u64, val: u64) -> Vec<u8> {
        datagram(&Instruction {
            protocol_version: PROTOCOL_VERSION,
            old_num: old,
            new_num: new,
            ack_num: 0,
            throwaway_num: throwaway,
            diff: postcard::to_allocvec(&GrowDiff(val)).unwrap(),
        })
    }

    #[test]
    fn received_state_budget_refuses_accumulation() {
        // KOH-01: a peer that pins old_num/throwaway to prevent collapse is refused once the
        // retained received-state resource budget would be exceeded — not allowed to OOM us.
        let mut t = Transport::<Grow, Grow>::new(0, 1200);
        // First large state fits (base num-0 is 0 units + 60 = 60 <= the 100 budget).
        assert_eq!(
            t.recv(10, &grow_datagram(0, 1, 0, 60)),
            RecvOutcome::NewState
        );
        // A second large state from the same (un-collapsed) base would push retained 60 + 60 over
        // the budget, so it is refused rather than accumulated.
        assert_eq!(
            t.recv(20, &grow_datagram(0, 2, 0, 60)),
            RecvOutcome::Quenched
        );
        assert_eq!(
            t.remote_state().0,
            60,
            "the refused state must not have been applied"
        );
    }

    #[test]
    fn recv_missing_base_is_reported_and_state_unchanged() {
        // The diff base (old_num) must be held or the instruction is dropped as MissingBase — the
        // out-of-order / replay defense. A fresh transport holds only the num-0 base, so an old_num
        // of 5 references no held base.
        let mut t = Transport::<Abs, Abs>::new(0, 1200);
        assert_eq!(
            t.recv(10, &datagram(&instr(5, 6, 0, 99))),
            RecvOutcome::MissingBase
        );
        assert_eq!(t.remote_num(), 0, "no state was applied");
    }

    #[test]
    fn idle_empty_acks_settle_to_ack_interval_not_a_flood() {
        // Regression: after receiving data (which owes a fast ack), an idle ack-only side must emit
        // ONE settling empty ack and then fall back to the slow ACK_INTERVAL keepalive cadence — it
        // must NOT re-emit an empty ack every ACK_DELAY ms forever. The bug was that `send_empty_ack`
        // reset `next_ack_time` to ACK_INTERVAL but left `pending_data_ack` set, so `calculate_timers`
        // kept yanking the deadline back to `now + ACK_DELAY`. ~10-30x the idle datagram rate on a
        // quiesced link — exactly the mobile battery/radio cost ACK_INTERVAL exists to avoid.
        let mut t = Transport::<Abs, Abs>::new(0, 1200);
        t.set_connected(true);
        // A non-empty inbound state owes a fast ack; our local state stays at its default, so every
        // subsequent transmission is a pure empty ack (no diff to send).
        assert_eq!(
            t.recv(0, &datagram(&instr(0, 1, 0, 42))),
            RecvOutcome::NewState
        );
        assert!(t.pending_data_ack, "a received data state owes an ack");

        // Walk time forward in ACK_DELAY steps across a full ACK_INTERVAL, recording every tick that
        // actually emits a datagram.
        let mut ack_times = Vec::new();
        let mut now = 0;
        while now <= ACK_INTERVAL {
            now += ACK_DELAY;
            if !t.tick(now).is_empty() {
                ack_times.push(now);
            }
        }
        assert!(
            !t.pending_data_ack,
            "the empty ack must discharge the pending-data-ack obligation"
        );
        // No empty acks between the single settling ack and the slow keepalive: a flood would land
        // repeatedly inside this window.
        let flooded = ack_times
            .iter()
            .any(|&at| at > ACK_DELAY && at < ACK_INTERVAL);
        assert!(
            !flooded,
            "idle side flooded empty acks every ~ACK_DELAY instead of settling onto ACK_INTERVAL; \
             emissions at {ack_times:?}"
        );
    }

    #[test]
    fn recv_out_of_order_inserts_without_regressing_the_newest() {
        // A state whose num lands BEFORE an already-held newer state is OutOfOrder: inserted in num
        // order, but the newest-in-order value (what we render/ack) must not regress.
        let mut t = Transport::<Abs, Abs>::new(0, 1200);
        assert_eq!(
            t.recv(10, &datagram(&instr(0, 2, 0, 22))),
            RecvOutcome::NewState
        );
        assert_eq!(
            t.recv(20, &datagram(&instr(2, 10, 0, 33))),
            RecvOutcome::NewState
        );
        assert_eq!(t.remote_num(), 10);
        // Deliver num 5 (between the held 2 and 10): inserted out of order.
        assert_eq!(
            t.recv(30, &datagram(&instr(2, 5, 0, 44))),
            RecvOutcome::OutOfOrder
        );
        assert_eq!(
            t.remote_num(),
            10,
            "the newest in-order state must not regress"
        );
        assert_eq!(
            t.remote_state().0,
            33,
            "render still reflects the newest (num 10) state"
        );
    }

    /// Regression for P1a: a peer-supplied `throwaway_num > old_num` makes the throwaway GC
    /// drop the diff base. Before the fix, recv() re-resolved the base after the GC with
    /// `.expect()` and panicked on this peer-controlled input. After the fix, the base is
    /// cloned before the GC and applied safely.
    #[test]
    fn throwaway_gc_dropping_base_does_not_panic() {
        let mut t = Transport::<Abs, Abs>::new(0, 1200);
        // received_states = [0, 2]
        assert_eq!(
            t.recv(10, &datagram(&instr(0, 2, 0, 22))),
            RecvOutcome::NewState
        );
        assert_eq!(t.remote_state().0, 22);
        // old=0 base, but throwaway_num=1 GCs num 0 (the base) before apply.
        assert_eq!(
            t.recv(20, &datagram(&instr(0, 5, 1, 55))),
            RecvOutcome::NewState
        );
        assert_eq!(
            t.remote_state().0,
            55,
            "diff must apply against the base cloned before the throwaway GC"
        );
    }

    /// Regression for P1c: `last_heard` (the active-retransmission liveness gate) must refresh
    /// on EVERY decoded datagram, including duplicate keepalives — not only on a new state.
    /// Otherwise a peer whose only-arriving traffic is dups/retransmits falsely times out.
    #[test]
    fn last_heard_updates_on_duplicate() {
        let mut t = Transport::<Abs, Abs>::new(0, 1200);
        let dg = datagram(&instr(0, 2, 0, 22));
        assert_eq!(t.recv(10, &dg), RecvOutcome::NewState);
        assert_eq!(t.last_heard(), 10);
        // (a) A byte-identical replay (same fragment id) is dropped at the fragment layer as a
        // replay — it is NOT re-inflated/re-applied (K-06) — but `recv` still stamps last_heard for
        // any decoded datagram BEFORE reassembly, so a re-sent keepalive of unchanged content still
        // proves liveness.
        assert_eq!(t.recv(5000, &dg), RecvOutcome::Incomplete);
        assert_eq!(
            t.last_heard(),
            5000,
            "a replayed keepalive still refreshes last_heard"
        );
        // (b) A DISTINCT datagram re-announcing an already-held new_num (a fresh fragment id — e.g. a
        // keepalive whose carried ack advanced) reassembles past the replay gate and is caught by
        // the SSP-level duplicate check (new_num 2 already held) — and likewise advances liveness.
        assert_eq!(
            t.recv(9000, &datagram(&instr(0, 2, 0, 22))),
            RecvOutcome::Duplicate
        );
        assert_eq!(
            t.last_heard(),
            9000,
            "a duplicate keepalive must refresh last_heard"
        );
        assert!(t.link_up_within(9100, 10_000));
        assert!(!t.link_up_within(20_000, 10_000));
    }

    /// Regression for P1d: a long shutdown must not overflow (`back_num + 1` on the sentinel)
    /// nor push a fresh u64::MAX state every tick. Exactly one sentinel state should be resident.
    #[test]
    fn shutdown_dedups_sentinel_and_never_overflows() {
        let mut t = Transport::<Abs, Abs>::new(0, 1200);
        t.set_connected(true);
        t.start_shutdown(0);
        // Many ticks at the frame rate; pre-fix this churned sent_states with sentinels (and
        // risked a `u64::MAX + 1` overflow). Reaching the end without panicking is half the test.
        for i in 0..200u64 {
            let _ = t.tick(i * 100);
        }
        assert_eq!(t.newest_sent_num(), SHUTDOWN_SENTINEL);
        // base (num 0) + a single deduped sentinel — not a queue churned toward the 32 cap.
        assert!(
            t.sent_states.len() <= 2,
            "shutdown sentinel must be deduped (bump ts), got {} sent_states",
            t.sent_states.len()
        );
    }

    /// Ported from mosh src/tests/network-no-diff.test: the sender must not generate a new diff/
    /// state while the application state is unchanged (mosh's regression was the server busy-
    /// looping / repainting when nothing changed). An unchanged state may be retransmitted for
    /// reliability but mints no new state number; a real change always gets a fresh one.
    #[test]
    fn unchanged_state_mints_no_new_content_state() {
        let mut t = Transport::<Abs, Abs>::new(0, 1200);
        t.set_connected(true);
        t.observe_rtt(20.0);

        // A real change is sent.
        t.current_mut().0 = 1;
        let mut now = 0u64;
        let mut sent = Vec::new();
        for _ in 0..100 {
            now += 20;
            sent = t.tick(now);
            if !sent.is_empty() {
                break;
            }
        }
        assert!(!sent.is_empty(), "a changed state must be sent");
        let after_first = t.newest_sent_num();

        // Unchanged across many ticks (well inside the ACK_INTERVAL): the transport may RETRANSMIT
        // the still-unacked state (reliability), but it must not mint a NEW state number — there
        // is no new screen content to diff. This is the heart of mosh's no-diff guarantee.
        for _ in 0..10 {
            now += 20;
            let _ = t.tick(now); // retransmits allowed; content is unchanged
            assert_eq!(
                t.newest_sent_num(),
                after_first,
                "unchanged state must not mint a new content state (retransmit reuses the number)"
            );
        }

        // A subsequent real change is sent again, with a fresh state number.
        t.current_mut().0 = 2;
        let mut sent_again = Vec::new();
        for _ in 0..100 {
            now += 20;
            sent_again = t.tick(now);
            if !sent_again.is_empty() {
                break;
            }
        }
        assert!(!sent_again.is_empty(), "a later change must be sent");
        assert!(
            t.newest_sent_num() > after_first,
            "the changed state gets a fresh number"
        );
    }

    proptest::proptest! {
        #![proptest_config(proptest::prelude::ProptestConfig::with_cases(128))]

        /// Feed ARBITRARY SSP envelopes (old/new/ack/throwaway including `u64::MAX` / the shutdown
        /// sentinel, inverted `old > new`, repeats) into the receive path. `recv` is the SSP
        /// reconciliation trust boundary where every peer-controlled num drives held-base lookup,
        /// throwaway GC (which once shipped a panic), the insertion-sort, and the cap/budget gates —
        /// yet it had no property coverage. With release `overflow-checks` on, an unguarded `+`/`-` on
        /// a wire num would panic here; instead it must never panic, and `received_states` must stay
        /// non-empty and bounded under any sequence. (KSSP-01)
        #[test]
        fn recv_survives_arbitrary_envelopes(
            ops in proptest::collection::vec(
                (
                    proptest::prelude::any::<u64>(),
                    proptest::prelude::any::<u64>(),
                    proptest::prelude::any::<u64>(),
                    proptest::prelude::any::<u64>(),
                    0u64..200,
                ),
                0..64,
            ),
        ) {
            let mut t = Transport::<Grow, Grow>::new(0, 1200);
            let mut now = 0u64;
            for (old, new, ack, throwaway, val) in ops {
                now = now.saturating_add(1);
                let dg = datagram(&Instruction {
                    protocol_version: PROTOCOL_VERSION,
                    old_num: old,
                    new_num: new,
                    ack_num: ack,
                    throwaway_num: throwaway,
                    diff: postcard::to_allocvec(&GrowDiff(val)).unwrap(),
                });
                let _ = t.recv(now, &dg); // must never panic on any envelope
                proptest::prop_assert!(
                    !t.received_states.is_empty(),
                    "received_states must never be empty (the never-empty invariant)"
                );
                proptest::prop_assert!(
                    t.received_states.len() <= RECEIVED_STATES_CAP,
                    "received_states {} exceeded the {} cap",
                    t.received_states.len(),
                    RECEIVED_STATES_CAP
                );
            }
        }
    }
}