sectorsync-wire 2026.711.0

Bounded binary wire frames and codecs for SectorSync
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
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
//! Wire frame traits and default frame shapes for `SectorSync`.

#![forbid(unsafe_code)]

use sectorsync_core::prelude::{
    BarrierId, BarrierState, ClientId, CommandEnvelope, CommandId, CommandPriority, ComponentId,
    ComponentStore, EntityId, EventId, EventKind, EventPriority, OwnerEpoch, ReplicationPlan,
    Station, StationEvent, StationId, Tick,
};

/// Runtime frame kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FrameKind {
    /// Replication update frame.
    Replication = 0,
    /// Command acknowledgement frame.
    CommandAck = 1,
    /// Runtime barrier notification.
    Barrier = 2,
    /// Client command ingress frame.
    Command = 3,
    /// Cross-station event frame.
    StationEvent = 4,
    /// Gateway-to-station command dispatch frame.
    CommandDispatch = 5,
}

impl FrameKind {
    /// Converts a byte into a frame kind.
    pub const fn from_byte(byte: u8) -> Option<Self> {
        match byte {
            0 => Some(Self::Replication),
            1 => Some(Self::CommandAck),
            2 => Some(Self::Barrier),
            3 => Some(Self::Command),
            4 => Some(Self::StationEvent),
            5 => Some(Self::CommandDispatch),
            _ => None,
        }
    }
}

/// Replication frame metadata produced per client.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReplicationFrame {
    /// Target client.
    pub client_id: ClientId,
    /// Server tick represented by this frame.
    pub server_tick: Tick,
    /// Number of entity updates in this frame.
    pub entity_count: u32,
    /// Estimated payload bytes before transport overhead.
    pub estimated_payload_bytes: u32,
    /// Concrete entity/component deltas included in this frame.
    pub entities: Vec<EntityDelta>,
}

/// Entity delta included in a replication frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntityDelta {
    /// Entity being updated.
    pub entity_id: EntityId,
    /// Owner epoch observed by the sender.
    pub owner_epoch: OwnerEpoch,
    /// Component deltas for this entity.
    pub components: Vec<ComponentDelta>,
}

/// Component delta included in an entity delta.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ComponentDelta {
    /// Component id.
    pub component_id: ComponentId,
    /// Component version.
    pub version: u64,
    /// Runtime-defined flags.
    pub flags: u8,
    /// Encoded component bytes.
    pub bytes: Vec<u8>,
}

/// Limits used by `ReplicationFrameBuilder`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ReplicationFrameLimits {
    /// Maximum entity deltas to materialize in one frame.
    pub max_entity_deltas: usize,
    /// Maximum component deltas to include per entity.
    pub max_components_per_entity: usize,
    /// Maximum component payload bytes to include per component.
    pub max_component_bytes: usize,
}

impl Default for ReplicationFrameLimits {
    fn default() -> Self {
        Self {
            max_entity_deltas: 256,
            max_components_per_entity: 16,
            max_component_bytes: 1024,
        }
    }
}

/// Component selection for frame building.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ComponentSelection {
    /// Component ids to include when present and dirty.
    pub component_ids: Vec<ComponentId>,
}

/// Frame builder statistics.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ReplicationFrameBuildStats {
    /// Entity handles selected by the replication plan.
    pub planned_entities: usize,
    /// Entity deltas materialized into the frame.
    pub encoded_entities: usize,
    /// Component deltas materialized into the frame.
    pub encoded_components: usize,
    /// Entity deltas skipped by builder limits.
    pub skipped_entities_by_limit: usize,
    /// Component deltas skipped by builder limits.
    pub skipped_components_by_limit: usize,
    /// Component payloads skipped because they exceed byte limits.
    pub skipped_components_by_size: usize,
}

/// Result of building a replication frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReplicationFrameBuild {
    /// Built frame.
    pub frame: ReplicationFrame,
    /// Build statistics.
    pub stats: ReplicationFrameBuildStats,
}

/// Builds concrete replication frames from a core replication plan.
#[derive(Clone, Copy, Debug, Default)]
pub struct ReplicationFrameBuilder {
    /// Builder limits.
    pub limits: ReplicationFrameLimits,
}

impl ReplicationFrameBuilder {
    /// Creates a frame builder with explicit limits.
    pub const fn new(limits: ReplicationFrameLimits) -> Self {
        Self { limits }
    }

    /// Builds a frame from a station plan and component store.
    pub fn build(
        &self,
        client_id: ClientId,
        server_tick: Tick,
        station: &Station,
        plan: &ReplicationPlan,
        components: &ComponentStore,
        selection: &ComponentSelection,
    ) -> ReplicationFrameBuild {
        let mut stats = ReplicationFrameBuildStats {
            planned_entities: plan.entities.len(),
            ..ReplicationFrameBuildStats::default()
        };
        let mut entity_deltas =
            Vec::with_capacity(plan.entities.len().min(self.limits.max_entity_deltas));
        let mut estimated_payload_bytes = 0_usize;

        for handle in &plan.entities {
            if entity_deltas.len() >= self.limits.max_entity_deltas {
                stats.skipped_entities_by_limit += 1;
                continue;
            }
            let Some(entity) = station.get(*handle) else {
                continue;
            };

            let mut component_deltas = Vec::new();
            for component_id in &selection.component_ids {
                if component_deltas.len() >= self.limits.max_components_per_entity {
                    stats.skipped_components_by_limit += 1;
                    continue;
                }
                let Some(blob) = components.get_blob(*component_id, *handle) else {
                    continue;
                };
                if !blob.dirty {
                    continue;
                }
                if blob.bytes.len() > self.limits.max_component_bytes {
                    stats.skipped_components_by_size += 1;
                    continue;
                }
                estimated_payload_bytes = estimated_payload_bytes
                    .saturating_add(2 + 8 + 1 + 4)
                    .saturating_add(blob.bytes.len());
                component_deltas.push(ComponentDelta {
                    component_id: *component_id,
                    version: blob.version,
                    flags: 0,
                    bytes: blob.bytes.clone(),
                });
            }

            if component_deltas.is_empty() {
                continue;
            }

            stats.encoded_components += component_deltas.len();
            estimated_payload_bytes = estimated_payload_bytes.saturating_add(8 + 8 + 2);
            entity_deltas.push(EntityDelta {
                entity_id: entity.id,
                owner_epoch: entity.role.owner_epoch(),
                components: component_deltas,
            });
        }

        stats.encoded_entities = entity_deltas.len();
        ReplicationFrameBuild {
            frame: ReplicationFrame {
                client_id,
                server_tick,
                entity_count: u32::try_from(plan.entities.len()).unwrap_or(u32::MAX),
                estimated_payload_bytes: u32::try_from(estimated_payload_bytes).unwrap_or(u32::MAX),
                entities: entity_deltas,
            },
            stats,
        }
    }
}

/// Command acknowledgement frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandAckFrame {
    /// Target client.
    pub client_id: ClientId,
    /// Acknowledged command.
    pub command_id: CommandId,
    /// Server tick at acknowledgement.
    pub server_tick: Tick,
    /// Whether the command was accepted by the runtime pipeline.
    pub accepted: bool,
    /// Game/runtime reject reason code.
    pub reason_code: u16,
}

/// Client command ingress frame.
///
/// The server stamps `received_at` when converting this into a
/// `CommandEnvelope`; game validation and anti-cheat checks remain outside the
/// wire codec.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandFrame {
    /// Client that submitted the command.
    pub client_id: ClientId,
    /// Command id used for replay and audit.
    pub command_id: CommandId,
    /// Entity the command intends to control.
    pub entity_id: EntityId,
    /// Client-side sequence number.
    pub sequence: u64,
    /// Game-defined command kind.
    pub kind: u32,
    /// Command priority.
    pub priority: CommandPriority,
    /// Opaque payload owned by the embedding game.
    pub payload: Vec<u8>,
}

impl CommandFrame {
    /// Converts an ingress frame into a runtime command envelope.
    pub fn into_envelope(self, received_at: Tick) -> CommandEnvelope {
        CommandEnvelope {
            id: self.command_id,
            client_id: self.client_id,
            entity_id: self.entity_id,
            sequence: self.sequence,
            received_at,
            kind: self.kind,
            priority: self.priority,
            payload: self.payload,
        }
    }

    /// Converts a command envelope into a wire frame, dropping server-only tick
    /// metadata.
    pub fn from_envelope(envelope: &CommandEnvelope) -> Self {
        Self {
            client_id: envelope.client_id,
            command_id: envelope.id,
            entity_id: envelope.entity_id,
            sequence: envelope.sequence,
            kind: envelope.kind,
            priority: envelope.priority,
            payload: envelope.payload.clone(),
        }
    }
}

/// Internal gateway-to-station command dispatch frame.
///
/// Unlike `CommandFrame`, this preserves the server `received_at` tick stamped
/// by the gateway pipeline before the command is forwarded to a station node.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandDispatchFrame {
    /// Target station selected by gateway/deployment routing.
    pub station_id: StationId,
    /// Client that submitted the command.
    pub client_id: ClientId,
    /// Command id used for replay and audit.
    pub command_id: CommandId,
    /// Entity the command intends to control.
    pub entity_id: EntityId,
    /// Client-side sequence number.
    pub sequence: u64,
    /// Server tick observed when the command entered `SectorSync`.
    pub received_at: Tick,
    /// Game-defined command kind.
    pub kind: u32,
    /// Command priority.
    pub priority: CommandPriority,
    /// Opaque payload owned by the embedding game.
    pub payload: Vec<u8>,
}

impl CommandDispatchFrame {
    /// Converts a stamped command envelope into an internal dispatch frame.
    pub fn from_envelope(station_id: StationId, envelope: &CommandEnvelope) -> Self {
        Self {
            station_id,
            client_id: envelope.client_id,
            command_id: envelope.id,
            entity_id: envelope.entity_id,
            sequence: envelope.sequence,
            received_at: envelope.received_at,
            kind: envelope.kind,
            priority: envelope.priority,
            payload: envelope.payload.clone(),
        }
    }

    /// Converts an internal dispatch frame back into a command envelope.
    pub fn into_envelope(self) -> CommandEnvelope {
        CommandEnvelope {
            id: self.command_id,
            client_id: self.client_id,
            entity_id: self.entity_id,
            sequence: self.sequence,
            received_at: self.received_at,
            kind: self.kind,
            priority: self.priority,
            payload: self.payload,
        }
    }
}

/// Cross-station event frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StationEventFrame {
    /// Idempotency key.
    pub event_id: EventId,
    /// Source station.
    pub source_station: StationId,
    /// Target station.
    pub target_station: StationId,
    /// Tick observed at source.
    pub source_tick: Tick,
    /// Tick at which target should apply the event.
    pub target_tick: Tick,
    /// Priority class.
    pub priority: EventPriority,
    /// Event payload kind.
    pub kind: EventKind,
}

impl StationEventFrame {
    /// Converts a runtime station event into a wire frame.
    pub fn from_event(event: &StationEvent) -> Self {
        Self {
            event_id: event.id,
            source_station: event.source,
            target_station: event.target,
            source_tick: event.source_tick,
            target_tick: event.target_tick,
            priority: event.priority,
            kind: event.kind.clone(),
        }
    }

    /// Converts a wire frame into a runtime station event.
    pub fn into_event(self) -> StationEvent {
        StationEvent {
            id: self.event_id,
            source: self.source_station,
            target: self.target_station,
            source_tick: self.source_tick,
            target_tick: self.target_tick,
            priority: self.priority,
            kind: self.kind,
        }
    }
}

/// Runtime barrier notification frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BarrierFrame {
    /// Target client.
    pub client_id: ClientId,
    /// Barrier id.
    pub barrier_id: BarrierId,
    /// Server tick associated with this barrier state.
    pub server_tick: Tick,
    /// Current barrier state.
    pub state: BarrierState,
}

/// Decoded runtime frame.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RuntimeFrame {
    /// Replication update.
    Replication(ReplicationFrame),
    /// Client command ingress.
    Command(CommandFrame),
    /// Gateway-to-station command dispatch.
    CommandDispatch(CommandDispatchFrame),
    /// Command acknowledgement.
    CommandAck(CommandAckFrame),
    /// Barrier notification.
    Barrier(BarrierFrame),
    /// Cross-station event.
    StationEvent(StationEventFrame),
}

/// Encodes frames into bytes.
pub trait FrameEncoder {
    /// Encoder error type.
    type Error;

    /// Encodes a replication frame into `out`.
    fn encode_replication(
        &mut self,
        frame: &ReplicationFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error>;

    /// Encodes a command acknowledgement frame into `out`.
    fn encode_command_ack(
        &mut self,
        frame: &CommandAckFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error>;

    /// Encodes a client command frame into `out`.
    fn encode_command(
        &mut self,
        frame: &CommandFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error>;

    /// Encodes an internal command dispatch frame into `out`.
    fn encode_command_dispatch(
        &mut self,
        frame: &CommandDispatchFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error>;

    /// Encodes a cross-station event frame into `out`.
    fn encode_station_event(
        &mut self,
        frame: &StationEventFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error>;

    /// Encodes a barrier frame into `out`.
    fn encode_barrier(
        &mut self,
        frame: &BarrierFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error>;
}

/// Decodes frames from bytes.
pub trait FrameDecoder {
    /// Decoder error type.
    type Error;

    /// Decodes one runtime frame.
    fn decode(&mut self, input: &[u8]) -> Result<RuntimeFrame, Self::Error>;
}

/// Binary decode error.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BinaryDecodeError {
    /// Input is empty.
    Empty,
    /// Unknown frame kind byte.
    UnknownFrameKind(u8),
    /// Frame ended before all fields were available.
    Truncated {
        /// Required bytes.
        needed: usize,
        /// Available bytes.
        available: usize,
    },
    /// Barrier state byte is invalid.
    InvalidBarrierState(u8),
    /// Command priority byte is invalid.
    InvalidCommandPriority(u8),
    /// Event priority byte is invalid.
    InvalidEventPriority(u8),
    /// Event kind byte is invalid.
    InvalidEventKind(u8),
    /// Trailing bytes were present after a complete frame.
    TrailingBytes(usize),
}

impl core::fmt::Display for BinaryDecodeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Empty => f.write_str("empty frame"),
            Self::UnknownFrameKind(kind) => write!(f, "unknown frame kind {kind}"),
            Self::Truncated { needed, available } => {
                write!(f, "truncated frame: needed {needed}, available {available}")
            }
            Self::InvalidBarrierState(state) => write!(f, "invalid barrier state {state}"),
            Self::InvalidCommandPriority(priority) => {
                write!(f, "invalid command priority {priority}")
            }
            Self::InvalidEventPriority(priority) => write!(f, "invalid event priority {priority}"),
            Self::InvalidEventKind(kind) => write!(f, "invalid event kind {kind}"),
            Self::TrailingBytes(bytes) => write!(f, "frame has {bytes} trailing bytes"),
        }
    }
}

impl std::error::Error for BinaryDecodeError {}

/// Binary encode error.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BinaryEncodeError {
    /// A list length exceeded `u32::MAX`.
    TooManyItems {
        /// Field being encoded.
        field: &'static str,
        /// Actual item count.
        actual: usize,
    },
    /// A byte payload exceeded `u32::MAX`.
    PayloadTooLarge {
        /// Field being encoded.
        field: &'static str,
        /// Actual byte count.
        actual: usize,
    },
}

impl core::fmt::Display for BinaryEncodeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::TooManyItems { field, actual } => {
                write!(f, "{field} has too many items: {actual}")
            }
            Self::PayloadTooLarge { field, actual } => {
                write!(f, "{field} payload is too large: {actual} bytes")
            }
        }
    }
}

impl std::error::Error for BinaryEncodeError {}

/// Simple little-endian binary frame decoder.
#[derive(Clone, Copy, Debug, Default)]
pub struct BinaryFrameDecoder;

impl FrameDecoder for BinaryFrameDecoder {
    type Error = BinaryDecodeError;

    fn decode(&mut self, input: &[u8]) -> Result<RuntimeFrame, Self::Error> {
        let mut cursor = Cursor::new(input);
        let kind_byte = cursor.read_u8()?;
        let kind = FrameKind::from_byte(kind_byte)
            .ok_or(BinaryDecodeError::UnknownFrameKind(kind_byte))?;
        let frame = match kind {
            FrameKind::Replication => RuntimeFrame::Replication(ReplicationFrame {
                client_id: ClientId::new(cursor.read_u64()?),
                server_tick: Tick::new(cursor.read_u64()?),
                entity_count: cursor.read_u32()?,
                estimated_payload_bytes: cursor.read_u32()?,
                entities: {
                    let entity_delta_count = cursor.read_u32()? as usize;
                    let mut entities = Vec::with_capacity(entity_delta_count);
                    for _ in 0..entity_delta_count {
                        let entity_id = EntityId::new(cursor.read_u64()?);
                        let owner_epoch = OwnerEpoch::new(cursor.read_u64()?);
                        let component_count = cursor.read_u16()? as usize;
                        let mut components = Vec::with_capacity(component_count);
                        for _ in 0..component_count {
                            let component_id = ComponentId::new(cursor.read_u16()?);
                            let version = cursor.read_u64()?;
                            let flags = cursor.read_u8()?;
                            let byte_len = cursor.read_u32()? as usize;
                            let bytes = cursor.read_bytes(byte_len)?;
                            components.push(ComponentDelta {
                                component_id,
                                version,
                                flags,
                                bytes,
                            });
                        }
                        entities.push(EntityDelta {
                            entity_id,
                            owner_epoch,
                            components,
                        });
                    }
                    entities
                },
            }),
            FrameKind::CommandAck => RuntimeFrame::CommandAck(CommandAckFrame {
                client_id: ClientId::new(cursor.read_u64()?),
                command_id: CommandId::new(cursor.read_u64()?),
                server_tick: Tick::new(cursor.read_u64()?),
                accepted: cursor.read_u8()? != 0,
                reason_code: cursor.read_u16()?,
            }),
            FrameKind::Command => RuntimeFrame::Command(CommandFrame {
                client_id: ClientId::new(cursor.read_u64()?),
                command_id: CommandId::new(cursor.read_u64()?),
                entity_id: EntityId::new(cursor.read_u64()?),
                sequence: cursor.read_u64()?,
                kind: cursor.read_u32()?,
                priority: decode_command_priority(cursor.read_u8()?)?,
                payload: {
                    let byte_len = cursor.read_u32()? as usize;
                    cursor.read_bytes(byte_len)?
                },
            }),
            FrameKind::CommandDispatch => RuntimeFrame::CommandDispatch(CommandDispatchFrame {
                station_id: StationId::new(cursor.read_u32()?),
                client_id: ClientId::new(cursor.read_u64()?),
                command_id: CommandId::new(cursor.read_u64()?),
                entity_id: EntityId::new(cursor.read_u64()?),
                sequence: cursor.read_u64()?,
                received_at: Tick::new(cursor.read_u64()?),
                kind: cursor.read_u32()?,
                priority: decode_command_priority(cursor.read_u8()?)?,
                payload: {
                    let byte_len = cursor.read_u32()? as usize;
                    cursor.read_bytes(byte_len)?
                },
            }),
            FrameKind::Barrier => RuntimeFrame::Barrier(BarrierFrame {
                client_id: ClientId::new(cursor.read_u64()?),
                barrier_id: BarrierId::new(cursor.read_u64()?),
                server_tick: Tick::new(cursor.read_u64()?),
                state: decode_barrier_state(cursor.read_u8()?)?,
            }),
            FrameKind::StationEvent => RuntimeFrame::StationEvent(StationEventFrame {
                event_id: EventId::new(cursor.read_u64()?),
                source_station: StationId::new(cursor.read_u32()?),
                target_station: StationId::new(cursor.read_u32()?),
                source_tick: Tick::new(cursor.read_u64()?),
                target_tick: Tick::new(cursor.read_u64()?),
                priority: decode_event_priority(cursor.read_u8()?)?,
                kind: decode_event_kind(&mut cursor)?,
            }),
        };
        cursor.finish()?;
        Ok(frame)
    }
}

/// Simple little-endian binary frame encoder.
#[derive(Clone, Copy, Debug, Default)]
pub struct BinaryFrameEncoder;

impl FrameEncoder for BinaryFrameEncoder {
    type Error = BinaryEncodeError;

    fn encode_replication(
        &mut self,
        frame: &ReplicationFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error> {
        out.push(FrameKind::Replication as u8);
        out.extend_from_slice(&frame.client_id.get().to_le_bytes());
        out.extend_from_slice(&frame.server_tick.get().to_le_bytes());
        out.extend_from_slice(&frame.entity_count.to_le_bytes());
        out.extend_from_slice(&frame.estimated_payload_bytes.to_le_bytes());
        write_len_u32("replication.entities", frame.entities.len(), out)?;
        for entity in &frame.entities {
            out.extend_from_slice(&entity.entity_id.get().to_le_bytes());
            out.extend_from_slice(&entity.owner_epoch.get().to_le_bytes());
            write_len_u16(
                "replication.entity.components",
                entity.components.len(),
                out,
            )?;
            for component in &entity.components {
                out.extend_from_slice(&component.component_id.get().to_le_bytes());
                out.extend_from_slice(&component.version.to_le_bytes());
                out.push(component.flags);
                write_bytes("replication.component.bytes", &component.bytes, out)?;
            }
        }
        Ok(())
    }

    fn encode_command_ack(
        &mut self,
        frame: &CommandAckFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error> {
        out.push(FrameKind::CommandAck as u8);
        out.extend_from_slice(&frame.client_id.get().to_le_bytes());
        out.extend_from_slice(&frame.command_id.get().to_le_bytes());
        out.extend_from_slice(&frame.server_tick.get().to_le_bytes());
        out.push(u8::from(frame.accepted));
        out.extend_from_slice(&frame.reason_code.to_le_bytes());
        Ok(())
    }

    fn encode_command(
        &mut self,
        frame: &CommandFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error> {
        out.push(FrameKind::Command as u8);
        out.extend_from_slice(&frame.client_id.get().to_le_bytes());
        out.extend_from_slice(&frame.command_id.get().to_le_bytes());
        out.extend_from_slice(&frame.entity_id.get().to_le_bytes());
        out.extend_from_slice(&frame.sequence.to_le_bytes());
        out.extend_from_slice(&frame.kind.to_le_bytes());
        out.push(encode_command_priority(frame.priority));
        write_bytes("command.payload", &frame.payload, out)?;
        Ok(())
    }

    fn encode_command_dispatch(
        &mut self,
        frame: &CommandDispatchFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error> {
        out.push(FrameKind::CommandDispatch as u8);
        out.extend_from_slice(&frame.station_id.get().to_le_bytes());
        out.extend_from_slice(&frame.client_id.get().to_le_bytes());
        out.extend_from_slice(&frame.command_id.get().to_le_bytes());
        out.extend_from_slice(&frame.entity_id.get().to_le_bytes());
        out.extend_from_slice(&frame.sequence.to_le_bytes());
        out.extend_from_slice(&frame.received_at.get().to_le_bytes());
        out.extend_from_slice(&frame.kind.to_le_bytes());
        out.push(encode_command_priority(frame.priority));
        write_bytes("command_dispatch.payload", &frame.payload, out)?;
        Ok(())
    }

    fn encode_station_event(
        &mut self,
        frame: &StationEventFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error> {
        out.push(FrameKind::StationEvent as u8);
        out.extend_from_slice(&frame.event_id.get().to_le_bytes());
        out.extend_from_slice(&frame.source_station.get().to_le_bytes());
        out.extend_from_slice(&frame.target_station.get().to_le_bytes());
        out.extend_from_slice(&frame.source_tick.get().to_le_bytes());
        out.extend_from_slice(&frame.target_tick.get().to_le_bytes());
        out.push(encode_event_priority(frame.priority));
        encode_event_kind(&frame.kind, out);
        Ok(())
    }

    fn encode_barrier(
        &mut self,
        frame: &BarrierFrame,
        out: &mut Vec<u8>,
    ) -> Result<(), Self::Error> {
        out.push(FrameKind::Barrier as u8);
        out.extend_from_slice(&frame.client_id.get().to_le_bytes());
        out.extend_from_slice(&frame.barrier_id.get().to_le_bytes());
        out.extend_from_slice(&frame.server_tick.get().to_le_bytes());
        out.push(encode_barrier_state(frame.state));
        Ok(())
    }
}

fn write_len_u16(
    field: &'static str,
    len: usize,
    out: &mut Vec<u8>,
) -> Result<(), BinaryEncodeError> {
    let len =
        u16::try_from(len).map_err(|_| BinaryEncodeError::TooManyItems { field, actual: len })?;
    out.extend_from_slice(&len.to_le_bytes());
    Ok(())
}

fn write_len_u32(
    field: &'static str,
    len: usize,
    out: &mut Vec<u8>,
) -> Result<(), BinaryEncodeError> {
    let len =
        u32::try_from(len).map_err(|_| BinaryEncodeError::TooManyItems { field, actual: len })?;
    out.extend_from_slice(&len.to_le_bytes());
    Ok(())
}

fn write_bytes(
    field: &'static str,
    bytes: &[u8],
    out: &mut Vec<u8>,
) -> Result<(), BinaryEncodeError> {
    let len = u32::try_from(bytes.len()).map_err(|_| BinaryEncodeError::PayloadTooLarge {
        field,
        actual: bytes.len(),
    })?;
    out.extend_from_slice(&len.to_le_bytes());
    out.extend_from_slice(bytes);
    Ok(())
}

fn encode_barrier_state(state: BarrierState) -> u8 {
    match state {
        BarrierState::Running => 0,
        BarrierState::Requested => 1,
        BarrierState::WaitingTickBoundary => 2,
        BarrierState::Frozen => 3,
        BarrierState::Resuming => 4,
    }
}

fn decode_barrier_state(state: u8) -> Result<BarrierState, BinaryDecodeError> {
    match state {
        0 => Ok(BarrierState::Running),
        1 => Ok(BarrierState::Requested),
        2 => Ok(BarrierState::WaitingTickBoundary),
        3 => Ok(BarrierState::Frozen),
        4 => Ok(BarrierState::Resuming),
        _ => Err(BinaryDecodeError::InvalidBarrierState(state)),
    }
}

fn encode_command_priority(priority: CommandPriority) -> u8 {
    match priority {
        CommandPriority::Normal => 0,
        CommandPriority::High => 1,
        CommandPriority::Low => 2,
    }
}

fn decode_command_priority(priority: u8) -> Result<CommandPriority, BinaryDecodeError> {
    match priority {
        0 => Ok(CommandPriority::Normal),
        1 => Ok(CommandPriority::High),
        2 => Ok(CommandPriority::Low),
        _ => Err(BinaryDecodeError::InvalidCommandPriority(priority)),
    }
}

fn encode_event_priority(priority: EventPriority) -> u8 {
    match priority {
        EventPriority::Critical => 0,
        EventPriority::Important => 1,
        EventPriority::BestEffort => 2,
    }
}

fn decode_event_priority(priority: u8) -> Result<EventPriority, BinaryDecodeError> {
    match priority {
        0 => Ok(EventPriority::Critical),
        1 => Ok(EventPriority::Important),
        2 => Ok(EventPriority::BestEffort),
        _ => Err(BinaryDecodeError::InvalidEventPriority(priority)),
    }
}

fn encode_event_kind(kind: &EventKind, out: &mut Vec<u8>) {
    match kind {
        EventKind::Custom(kind) => {
            out.push(0);
            out.extend_from_slice(&kind.to_le_bytes());
        }
        EventKind::HandoffPrepare { entity_id } => {
            out.push(1);
            out.extend_from_slice(&entity_id.get().to_le_bytes());
        }
        EventKind::HandoffCommit {
            entity_id,
            owner_epoch,
        } => {
            out.push(2);
            out.extend_from_slice(&entity_id.get().to_le_bytes());
            out.extend_from_slice(&owner_epoch.get().to_le_bytes());
        }
    }
}

fn decode_event_kind(cursor: &mut Cursor<'_>) -> Result<EventKind, BinaryDecodeError> {
    match cursor.read_u8()? {
        0 => Ok(EventKind::Custom(cursor.read_u32()?)),
        1 => Ok(EventKind::HandoffPrepare {
            entity_id: EntityId::new(cursor.read_u64()?),
        }),
        2 => Ok(EventKind::HandoffCommit {
            entity_id: EntityId::new(cursor.read_u64()?),
            owner_epoch: OwnerEpoch::new(cursor.read_u64()?),
        }),
        kind => Err(BinaryDecodeError::InvalidEventKind(kind)),
    }
}

struct Cursor<'a> {
    input: &'a [u8],
    offset: usize,
}

impl<'a> Cursor<'a> {
    fn new(input: &'a [u8]) -> Self {
        Self { input, offset: 0 }
    }

    fn read_u8(&mut self) -> Result<u8, BinaryDecodeError> {
        self.require(1)?;
        let value = self.input[self.offset];
        self.offset += 1;
        Ok(value)
    }

    fn read_u16(&mut self) -> Result<u16, BinaryDecodeError> {
        let bytes = self.read_array::<2>()?;
        Ok(u16::from_le_bytes(bytes))
    }

    fn read_u32(&mut self) -> Result<u32, BinaryDecodeError> {
        let bytes = self.read_array::<4>()?;
        Ok(u32::from_le_bytes(bytes))
    }

    fn read_u64(&mut self) -> Result<u64, BinaryDecodeError> {
        let bytes = self.read_array::<8>()?;
        Ok(u64::from_le_bytes(bytes))
    }

    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], BinaryDecodeError> {
        self.require(N)?;
        let mut out = [0_u8; N];
        out.copy_from_slice(&self.input[self.offset..self.offset + N]);
        self.offset += N;
        Ok(out)
    }

    fn read_bytes(&mut self, len: usize) -> Result<Vec<u8>, BinaryDecodeError> {
        self.require(len)?;
        let bytes = self.input[self.offset..self.offset + len].to_vec();
        self.offset += len;
        Ok(bytes)
    }

    fn require(&self, count: usize) -> Result<(), BinaryDecodeError> {
        let needed = self.offset.saturating_add(count);
        if needed > self.input.len() {
            Err(BinaryDecodeError::Truncated {
                needed,
                available: self.input.len(),
            })
        } else {
            Ok(())
        }
    }

    fn finish(&self) -> Result<(), BinaryDecodeError> {
        if self.offset == self.input.len() {
            Ok(())
        } else {
            Err(BinaryDecodeError::TrailingBytes(
                self.input.len().saturating_sub(self.offset),
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn binary_codec_roundtrips_replication_frame() {
        let frame = ReplicationFrame {
            client_id: ClientId::new(9),
            server_tick: Tick::new(42),
            entity_count: 17,
            estimated_payload_bytes: 544,
            entities: vec![EntityDelta {
                entity_id: EntityId::new(100),
                owner_epoch: OwnerEpoch::new(2),
                components: vec![ComponentDelta {
                    component_id: ComponentId::new(1),
                    version: 9,
                    flags: 0,
                    bytes: vec![1, 2, 3, 4],
                }],
            }],
        };
        let mut encoder = BinaryFrameEncoder;
        let mut bytes = Vec::new();
        encoder
            .encode_replication(&frame, &mut bytes)
            .expect("encoder is infallible");

        let decoded = BinaryFrameDecoder
            .decode(&bytes)
            .expect("decode should work");
        assert_eq!(decoded, RuntimeFrame::Replication(frame));
    }

    #[test]
    fn binary_codec_roundtrips_command_ack_frame() {
        let frame = CommandAckFrame {
            client_id: ClientId::new(1),
            command_id: CommandId::new(2),
            server_tick: Tick::new(3),
            accepted: false,
            reason_code: 7,
        };
        let mut encoder = BinaryFrameEncoder;
        let mut bytes = Vec::new();
        encoder
            .encode_command_ack(&frame, &mut bytes)
            .expect("encoder is infallible");

        let decoded = BinaryFrameDecoder
            .decode(&bytes)
            .expect("decode should work");
        assert_eq!(decoded, RuntimeFrame::CommandAck(frame));
    }

    #[test]
    fn binary_codec_roundtrips_command_frame() {
        let frame = CommandFrame {
            client_id: ClientId::new(1),
            command_id: CommandId::new(2),
            entity_id: EntityId::new(3),
            sequence: 4,
            kind: 5,
            priority: CommandPriority::High,
            payload: vec![9, 8, 7],
        };
        let mut encoder = BinaryFrameEncoder;
        let mut bytes = Vec::new();
        encoder
            .encode_command(&frame, &mut bytes)
            .expect("encoder is infallible");

        let decoded = BinaryFrameDecoder
            .decode(&bytes)
            .expect("decode should work");
        assert_eq!(decoded, RuntimeFrame::Command(frame));
    }

    #[test]
    fn binary_codec_roundtrips_command_dispatch_frame() {
        let frame = CommandDispatchFrame {
            station_id: StationId::new(10),
            client_id: ClientId::new(1),
            command_id: CommandId::new(2),
            entity_id: EntityId::new(3),
            sequence: 4,
            received_at: Tick::new(99),
            kind: 5,
            priority: CommandPriority::High,
            payload: vec![9, 8, 7],
        };
        let mut encoder = BinaryFrameEncoder;
        let mut bytes = Vec::new();
        encoder
            .encode_command_dispatch(&frame, &mut bytes)
            .expect("encoder is infallible");

        let decoded = BinaryFrameDecoder
            .decode(&bytes)
            .expect("decode should work");
        assert_eq!(decoded, RuntimeFrame::CommandDispatch(frame));
    }

    #[test]
    fn command_frame_converts_to_runtime_envelope() {
        let frame = CommandFrame {
            client_id: ClientId::new(1),
            command_id: CommandId::new(2),
            entity_id: EntityId::new(3),
            sequence: 4,
            kind: 5,
            priority: CommandPriority::Low,
            payload: vec![1, 2, 3],
        };

        let envelope = frame.clone().into_envelope(Tick::new(99));
        assert_eq!(envelope.id, frame.command_id);
        assert_eq!(envelope.received_at, Tick::new(99));
        assert_eq!(CommandFrame::from_envelope(&envelope), frame);
    }

    #[test]
    fn command_dispatch_frame_preserves_stamped_envelope_tick() {
        let envelope = CommandEnvelope {
            id: CommandId::new(2),
            client_id: ClientId::new(1),
            entity_id: EntityId::new(3),
            sequence: 4,
            received_at: Tick::new(99),
            kind: 5,
            priority: CommandPriority::Low,
            payload: vec![1, 2, 3],
        };

        let frame = CommandDispatchFrame::from_envelope(StationId::new(10), &envelope);
        assert_eq!(frame.station_id, StationId::new(10));
        assert_eq!(frame.received_at, Tick::new(99));
        assert_eq!(frame.into_envelope(), envelope);
    }

    #[test]
    fn binary_codec_roundtrips_barrier_frame() {
        let frame = BarrierFrame {
            client_id: ClientId::new(1),
            barrier_id: BarrierId::new(99),
            server_tick: Tick::new(11),
            state: BarrierState::Frozen,
        };
        let mut encoder = BinaryFrameEncoder;
        let mut bytes = Vec::new();
        encoder
            .encode_barrier(&frame, &mut bytes)
            .expect("encoder is infallible");

        let decoded = BinaryFrameDecoder
            .decode(&bytes)
            .expect("decode should work");
        assert_eq!(decoded, RuntimeFrame::Barrier(frame));
    }

    #[test]
    fn binary_codec_roundtrips_station_event_frame() {
        let frames = [
            StationEventFrame {
                event_id: EventId::new(1),
                source_station: StationId::new(10),
                target_station: StationId::new(11),
                source_tick: Tick::new(2),
                target_tick: Tick::new(3),
                priority: EventPriority::Critical,
                kind: EventKind::Custom(7),
            },
            StationEventFrame {
                event_id: EventId::new(2),
                source_station: StationId::new(10),
                target_station: StationId::new(11),
                source_tick: Tick::new(2),
                target_tick: Tick::new(3),
                priority: EventPriority::Important,
                kind: EventKind::HandoffPrepare {
                    entity_id: EntityId::new(99),
                },
            },
            StationEventFrame {
                event_id: EventId::new(3),
                source_station: StationId::new(10),
                target_station: StationId::new(11),
                source_tick: Tick::new(2),
                target_tick: Tick::new(3),
                priority: EventPriority::BestEffort,
                kind: EventKind::HandoffCommit {
                    entity_id: EntityId::new(99),
                    owner_epoch: OwnerEpoch::new(5),
                },
            },
        ];

        for frame in frames {
            let mut encoder = BinaryFrameEncoder;
            let mut bytes = Vec::new();
            encoder
                .encode_station_event(&frame, &mut bytes)
                .expect("encoder is infallible");

            let decoded = BinaryFrameDecoder
                .decode(&bytes)
                .expect("decode should work");
            assert_eq!(decoded, RuntimeFrame::StationEvent(frame));
        }
    }

    #[test]
    fn station_event_frame_converts_to_runtime_event() {
        let event = StationEvent {
            id: EventId::new(1),
            source: StationId::new(10),
            target: StationId::new(11),
            source_tick: Tick::new(2),
            target_tick: Tick::new(3),
            priority: EventPriority::Critical,
            kind: EventKind::HandoffPrepare {
                entity_id: EntityId::new(99),
            },
        };

        let frame = StationEventFrame::from_event(&event);
        assert_eq!(frame.event_id, event.id);
        assert_eq!(frame.clone().into_event(), event);
    }

    #[test]
    fn frame_builder_materializes_dirty_component_deltas() {
        use sectorsync_core::prelude::{
            Bounds, ComponentDescriptor, ComponentMigrationMode, ComponentSyncMode, InstanceId,
            NodeId, PolicyId, Position3, ReplicationPlan, StationConfig, Vec3, Vec3LeCodec,
        };

        let mut station = Station::new(StationConfig {
            station_id: sectorsync_core::prelude::StationId::new(1),
            node_id: NodeId::new(1),
            instance_id: InstanceId::new(1),
            tick_rate_hz: 20,
        });
        let handle = station
            .spawn_owned(
                EntityId::new(10),
                Position3::new(0.0, 0.0, 0.0),
                Bounds::Point,
                PolicyId::new(0),
            )
            .expect("spawn should work");

        let descriptor = ComponentDescriptor::sparse_blob(
            ComponentId::new(1),
            "velocity",
            ComponentSyncMode::Delta,
            ComponentMigrationMode::Copy,
            12,
        );
        let mut components = ComponentStore::default();
        components
            .set_typed(
                &descriptor,
                handle,
                3,
                &Vec3LeCodec,
                &Vec3::new(1.0, 2.0, 3.0),
            )
            .expect("typed component should encode");

        let build = ReplicationFrameBuilder::new(ReplicationFrameLimits {
            max_entity_deltas: 8,
            max_components_per_entity: 4,
            max_component_bytes: 64,
        })
        .build(
            ClientId::new(5),
            Tick::new(9),
            &station,
            &ReplicationPlan {
                entities: vec![handle],
                stats: sectorsync_core::prelude::ReplicationStats::default(),
            },
            &components,
            &ComponentSelection {
                component_ids: vec![ComponentId::new(1)],
            },
        );

        assert_eq!(build.stats.encoded_entities, 1);
        assert_eq!(build.stats.encoded_components, 1);
        assert_eq!(build.frame.entities[0].entity_id, EntityId::new(10));
        assert_eq!(build.frame.entities[0].components[0].version, 3);
    }
}