fly_ruler_proto_core 0.4.0

Protobuf UDP runtime and time-series state kernel for aerospace simulation
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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
//! State store and persistence layer.
//!
//! Responsibilities in this module:
//! - Trajectory level: append + query only (no trajectory delete/modify APIs)
//! - Aircraft level: create/read/update/delete and per-aircraft settings
//! - Async persistence and restore

use std::collections::BTreeSet;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::time::{Duration, Instant};

use arrow::array::{Array, BinaryArray, Float64Array, StringArray};
use arrow::datatypes::{DataType, Field, Schema};
use arrow::record_batch::RecordBatch;
use dashmap::DashMap;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use parquet::arrow::ArrowWriter;
use prost::Message as ProstMessage;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{debug, info, warn};

use crate::config::StoreConfig;
use crate::pb;
use crate::utils::uuid_to_hex;
use crate::PROTOCOL_VERSION;

/// Identifier for an aircraft, represented as a lowercase hex UUID string.
pub type AircraftId = String;

/// Configuration metadata persisted for a spawned aircraft.
#[derive(Debug, Clone)]
pub struct AircraftConfig {
    /// Aircraft display name.
    pub name: String,
    /// Raw TOML configuration string.
    pub toml_config: String,
    /// Immutable telemetry stream schemas registered at spawn.
    pub telemetry_schemas: Vec<pb::TelemetryStreamSchema>,
}

/// Lifecycle events that can be stored for an aircraft.
#[derive(Debug, Clone)]
pub enum Event {
    /// Aircraft spawn event, including initial configuration.
    Spawn(Box<pb::AircraftSpawnInfo>),
    /// Aircraft despawn event.
    Despawn(pb::DespawnInfo),
    /// Custom named event.
    Custom(String),
}

/// A single aircraft state sample with its timestamp.
#[derive(Debug, Clone)]
pub struct TimestampedState {
    /// Timestamp in seconds on the producer-defined source timeline.
    pub timestamp_secs: f64,
    /// Aircraft state at this timestamp.
    pub state: pb::AircraftState,
}

/// A single aircraft event with its timestamp.
#[derive(Debug, Clone)]
pub struct TimestampedEvent {
    /// Timestamp in seconds on the producer-defined source timeline.
    pub timestamp_secs: f64,
    /// Event that occurred at this timestamp.
    pub event: Event,
}

/// One schema-validated telemetry frame with its timestamp.
#[derive(Debug, Clone)]
pub struct TimestampedTelemetryFrame {
    /// Frame timestamp in seconds.
    pub timestamp_secs: f64,
    /// Telemetry values and stream sequence.
    pub frame: pb::TelemetryFrame,
}

/// A lifecycle/custom event paired with its aircraft identifier.
#[derive(Debug, Clone)]
pub struct GlobalTimestampedEvent {
    /// Aircraft that emitted the event.
    pub aircraft_id: AircraftId,
    /// Event timestamp in seconds.
    pub timestamp_secs: f64,
    /// Stored event payload.
    pub event: Event,
}

/// Time-series data for one aircraft.
#[derive(Debug, Clone, Default)]
pub struct AircraftTimeSeries {
    /// State samples, kept sorted by timestamp.
    pub states: Vec<TimestampedState>,
    /// Lifecycle events, kept sorted by timestamp.
    pub events: Vec<TimestampedEvent>,
    /// Telemetry frames, retained without automatic trimming.
    pub telemetry: Vec<TimestampedTelemetryFrame>,
    /// Configuration set by the first `Spawn` event.
    pub config: Option<AircraftConfig>,
}

/// Summary metadata for one aircraft time series.
#[derive(Debug, Clone)]
pub struct AircraftSummary {
    /// Aircraft identifier.
    pub id: AircraftId,
    /// Spawn configuration, if available.
    pub config: Option<AircraftConfig>,
    /// First and last state timestamps.
    pub time_range: Option<(f64, f64)>,
    /// Number of stored states.
    pub state_count: usize,
    /// Number of stored lifecycle/custom events.
    pub event_count: usize,
    /// Number of stored telemetry frames.
    pub telemetry_count: usize,
}

/// One page of a bounded time-range query.
#[derive(Debug, Clone)]
pub struct StorePage<T> {
    /// Page items.
    pub items: Vec<T>,
    /// Total matching items before pagination.
    pub total: usize,
    /// Requested offset.
    pub offset: usize,
    /// Requested limit.
    pub limit: usize,
}

/// In-memory time-series store for aircraft states and events.
#[derive(Debug, Default)]
pub struct TimeSeriesStore {
    data: RwLock<DashMap<AircraftId, AircraftTimeSeries>>,
    live_state_receipts: DashMap<AircraftId, Instant>,
}

/// Errors that can occur when persisting or loading store data.
#[derive(Debug, Error)]
pub enum StoreError {
    /// IO error.
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    /// JSON serialization/deserialization error.
    #[error("json error: {0}")]
    Json(#[from] serde_json::Error),

    /// Parquet read/write error.
    #[error("parquet error: {0}")]
    Parquet(#[from] parquet::errors::ParquetError),

    /// Arrow conversion error.
    #[error("arrow error: {0}")]
    Arrow(#[from] arrow::error::ArrowError),

    /// Protobuf decode error.
    #[error("decode error: {0}")]
    Decode(#[from] prost::DecodeError),

    /// Invalid or inconsistent data.
    #[error("invalid data: {0}")]
    InvalidData(String),
}

#[derive(Debug, Serialize, Deserialize)]
struct MetaFile {
    version: String,
    aircrafts: Vec<MetaAircraft>,
}

#[derive(Debug, Serialize, Deserialize)]
struct MetaAircraft {
    id: String,
    name: Option<String>,
    toml_config: Option<String>,
    time_range: Option<(f64, f64)>,
    state_count: usize,
    event_count: usize,
}

impl TimeSeriesStore {
    /// Create a new empty store.
    pub fn new() -> Self {
        Self {
            data: RwLock::new(DashMap::new()),
            live_state_receipts: DashMap::new(),
        }
    }

    /// Append a state sample for the given aircraft.
    ///
    /// States are kept sorted by timestamp.
    pub fn append_state(&self, id: AircraftId, timestamp: f64, state: pb::AircraftState) {
        if !timestamp.is_finite() {
            warn!(target: "fly_ruler_proto_core.store", aircraft_id = id, "ignored state with non-finite source timestamp");
            return;
        }
        let data = read_unpoisoned(&self.data);
        let mut series = data.entry(id).or_default();
        if series
            .states
            .last()
            .is_none_or(|last| last.timestamp_secs <= timestamp)
        {
            series.states.push(TimestampedState {
                timestamp_secs: timestamp,
                state,
            });
            return;
        }

        let insert_at = series
            .states
            .partition_point(|state| state.timestamp_secs <= timestamp);
        series.states.insert(
            insert_at,
            TimestampedState {
                timestamp_secs: timestamp,
                state,
            },
        );
    }

    /// Append an event for the given aircraft.
    ///
    /// Events are kept sorted by timestamp. A `Spawn` event sets the aircraft
    /// configuration.
    pub fn append_event(&self, id: AircraftId, timestamp: f64, event: Event) {
        if !timestamp.is_finite() {
            warn!(target: "fly_ruler_proto_core.store", aircraft_id = id, "ignored event with non-finite source timestamp");
            return;
        }
        let data = read_unpoisoned(&self.data);
        let mut series = data.entry(id).or_default();
        if let Event::Spawn(spawn) = &event {
            series.config = Some(AircraftConfig {
                name: spawn.name.clone(),
                toml_config: spawn.toml_config.clone(),
                telemetry_schemas: spawn.telemetry_schemas.clone(),
            });
        }

        if series
            .events
            .last()
            .is_none_or(|last| last.timestamp_secs <= timestamp)
        {
            series.events.push(TimestampedEvent {
                timestamp_secs: timestamp,
                event,
            });
            return;
        }

        let insert_at = series
            .events
            .partition_point(|event| event.timestamp_secs <= timestamp);
        series.events.insert(
            insert_at,
            TimestampedEvent {
                timestamp_secs: timestamp,
                event,
            },
        );
    }

    /// Append a telemetry frame after validating it against the spawn schema.
    pub fn append_telemetry(
        &self,
        id: AircraftId,
        timestamp: f64,
        frame: pb::TelemetryFrame,
    ) -> Result<(), StoreError> {
        if !timestamp.is_finite() {
            return Err(StoreError::InvalidData(
                "telemetry timestamp must be finite".to_string(),
            ));
        }
        let data = read_unpoisoned(&self.data);
        let mut series = data
            .get_mut(&id)
            .ok_or_else(|| StoreError::InvalidData(format!("aircraft not found: {id}")))?;
        let schemas = series
            .config
            .as_ref()
            .map(|config| config.telemetry_schemas.as_slice())
            .unwrap_or_default();
        validate_telemetry_frame(schemas, &frame)?;
        let sample = TimestampedTelemetryFrame {
            timestamp_secs: timestamp,
            frame,
        };
        if series
            .telemetry
            .last()
            .is_none_or(|last| last.timestamp_secs <= timestamp)
        {
            series.telemetry.push(sample);
        } else {
            let insert_at = series
                .telemetry
                .partition_point(|entry| entry.timestamp_secs <= timestamp);
            series.telemetry.insert(insert_at, sample);
        }
        Ok(())
    }

    /// Append a protobuf message to the store using default store config.
    pub fn append_message(&self, msg: pb::Message) {
        self.append_message_with_config(msg, &StoreConfig);
    }

    /// Append a protobuf message to the store with the given store config.
    ///
    /// `config` is currently a placeholder for future store-level knobs.
    pub fn append_message_with_config(
        &self,
        msg: pb::Message,
        #[allow(unused_variables)] config: &StoreConfig,
    ) {
        let Some(pb::message::Envelope::Request(req)) = msg.envelope else {
            debug!(target: "fly_ruler_proto_core.store", "ignored non-request envelope");
            return;
        };

        let timestamp = req.timestamp;
        if !timestamp.is_finite() {
            warn!(target: "fly_ruler_proto_core.store", "ignored aircraft event with non-finite source timestamp");
            return;
        }
        let Some(command) = req.command.and_then(|c| c.kind) else {
            warn!(target: "fly_ruler_proto_core.store", "ignored request without command");
            return;
        };

        let pb::request_command::Kind::AircraftEvent(event) = command else {
            debug!(target: "fly_ruler_proto_core.store", "ignored non-aircraft command");
            return;
        };

        let aircraft_id = event
            .aircraft_id
            .as_ref()
            .map(uuid_to_hex)
            .unwrap_or_else(|| "unknown".to_string());

        let Some(info) = event.info.and_then(|i| i.kind) else {
            warn!(target: "fly_ruler_proto_core.store", aircraft_id = aircraft_id, "ignored aircraft event without command info");
            return;
        };

        match info {
            pb::aircraft_command_info::Kind::StateUpdate(state) => {
                self.append_state(aircraft_id.clone(), timestamp, state);
                self.live_state_receipts.insert(aircraft_id, Instant::now());
            }
            pb::aircraft_command_info::Kind::Spawn(spawn) => {
                if let Err(error) = validate_telemetry_schemas(&spawn.telemetry_schemas) {
                    warn!(target: "fly_ruler_proto_core.store", aircraft_id = aircraft_id, error = %error, "ignored spawn with invalid telemetry schema");
                    return;
                }
                if let Some(state) = spawn.initial_state.clone() {
                    self.append_state(aircraft_id.clone(), timestamp, state);
                    self.live_state_receipts
                        .insert(aircraft_id.clone(), Instant::now());
                }
                self.append_event(aircraft_id, timestamp, Event::Spawn(Box::new(spawn)));
            }
            pb::aircraft_command_info::Kind::Despawn(despawn) => {
                self.append_event(aircraft_id.clone(), timestamp, Event::Despawn(despawn));
                self.live_state_receipts.remove(&aircraft_id);
            }
            pb::aircraft_command_info::Kind::CustomEvent(custom) => {
                self.append_event(aircraft_id, timestamp, Event::Custom(custom));
            }
            pb::aircraft_command_info::Kind::TelemetryFrame(frame) => {
                if let Err(error) = self.append_telemetry(aircraft_id.clone(), timestamp, frame) {
                    warn!(target: "fly_ruler_proto_core.store", aircraft_id = aircraft_id, error = %error, "ignored invalid telemetry frame");
                }
            }
        }
    }

    /// Return the local monotonic age of the last received live state packet.
    ///
    /// Source timestamps are intentionally not used here: producers may use
    /// Unix time, simulation time starting at zero, or another shared replay
    /// timeline. Loaded sessions and states appended directly to the store do
    /// not have live receipt metadata and therefore return `None`.
    pub fn live_state_age(&self, id: &str) -> Option<Duration> {
        self.live_state_receipts
            .get(id)
            .map(|received_at| received_at.elapsed())
    }

    /// Return whether an aircraft has no live state receipt within `timeout`.
    pub fn live_state_is_stale(&self, id: &str, timeout: Duration) -> bool {
        self.live_state_age(id).is_none_or(|age| age > timeout)
    }

    /// Return the latest state sample for an aircraft, if any.
    pub fn get_latest(&self, id: &AircraftId) -> Option<TimestampedState> {
        let data = read_unpoisoned(&self.data);
        data.get(id)
            .and_then(|series| series.states.last().cloned())
    }

    /// Return the last state whose timestamp is less than or equal to `timestamp`.
    pub fn get_state_at_or_before(
        &self,
        id: &AircraftId,
        timestamp: f64,
    ) -> Option<TimestampedState> {
        if !timestamp.is_finite() {
            return None;
        }
        let data = read_unpoisoned(&self.data);
        data.get(id).and_then(|series| {
            let end = series
                .states
                .partition_point(|state| state.timestamp_secs <= timestamp);
            end.checked_sub(1)
                .and_then(|index| series.states.get(index).cloned())
        })
    }

    /// Return whether an aircraft is spawned at the given timestamp.
    pub fn is_spawned_at(&self, id: &AircraftId, timestamp: f64) -> bool {
        let data = read_unpoisoned(&self.data);
        data.get(id)
            .and_then(|series| {
                let end = if timestamp.is_infinite() && timestamp.is_sign_positive() {
                    series.events.len()
                } else if timestamp.is_finite() {
                    series
                        .events
                        .partition_point(|event| event.timestamp_secs <= timestamp)
                } else {
                    0
                };
                series.events[..end]
                    .iter()
                    .rev()
                    .find_map(|entry| match entry.event {
                        Event::Spawn(_) => Some(true),
                        Event::Despawn(_) => Some(false),
                        Event::Custom(_) => None,
                    })
            })
            .unwrap_or(false)
    }

    /// Return all state samples for an aircraft within the inclusive time range.
    pub fn get_states_range(
        &self,
        id: &AircraftId,
        start: f64,
        end: f64,
    ) -> Option<Vec<TimestampedState>> {
        let data = read_unpoisoned(&self.data);
        data.get(id).map(|series| {
            series
                .states
                .iter()
                .filter(|s| s.timestamp_secs >= start && s.timestamp_secs <= end)
                .cloned()
                .collect()
        })
    }

    /// Return telemetry schemas registered for an aircraft.
    pub fn get_telemetry_schemas(&self, id: &AircraftId) -> Option<Vec<pb::TelemetryStreamSchema>> {
        let data = read_unpoisoned(&self.data);
        data.get(id).map(|series| {
            series
                .config
                .as_ref()
                .map(|config| config.telemetry_schemas.clone())
                .unwrap_or_default()
        })
    }

    /// Visit telemetry frames within an inclusive time range without cloning them.
    pub fn visit_telemetry_range<R>(
        &self,
        id: &AircraftId,
        start: f64,
        end: f64,
        visitor: impl FnOnce(&[TimestampedTelemetryFrame]) -> R,
    ) -> Option<R> {
        let data = read_unpoisoned(&self.data);
        data.get(id).map(|series| {
            let first = series
                .telemetry
                .partition_point(|sample| sample.timestamp_secs < start);
            let last = series
                .telemetry
                .partition_point(|sample| sample.timestamp_secs <= end);
            visitor(&series.telemetry[first..last])
        })
    }

    /// Return a paginated state range using binary search boundaries.
    pub fn get_states_page(
        &self,
        id: &AircraftId,
        start: f64,
        end: f64,
        offset: usize,
        limit: usize,
    ) -> Option<StorePage<TimestampedState>> {
        let data = read_unpoisoned(&self.data);
        data.get(id).map(|series| {
            let first = series
                .states
                .partition_point(|state| state.timestamp_secs < start);
            let last = series
                .states
                .partition_point(|state| state.timestamp_secs <= end);
            page_slice(&series.states[first..last], offset, limit)
        })
    }

    pub(crate) fn visit_states_range<R>(
        &self,
        id: &AircraftId,
        start: f64,
        end: f64,
        visitor: impl FnOnce(&[TimestampedState]) -> R,
    ) -> Option<R> {
        let data = read_unpoisoned(&self.data);
        data.get(id).map(|series| {
            let first = series
                .states
                .partition_point(|state| state.timestamp_secs < start);
            let last = series
                .states
                .partition_point(|state| state.timestamp_secs <= end);
            visitor(&series.states[first..last])
        })
    }

    /// Return all events for an aircraft within the inclusive time range.
    pub fn get_events_range(
        &self,
        id: &AircraftId,
        start: f64,
        end: f64,
    ) -> Option<Vec<TimestampedEvent>> {
        let data = read_unpoisoned(&self.data);
        data.get(id).map(|series| {
            series
                .events
                .iter()
                .filter(|e| e.timestamp_secs >= start && e.timestamp_secs <= end)
                .cloned()
                .collect()
        })
    }

    /// Return a paginated event range using binary search boundaries.
    pub fn get_events_page(
        &self,
        id: &AircraftId,
        start: f64,
        end: f64,
        offset: usize,
        limit: usize,
    ) -> Option<StorePage<TimestampedEvent>> {
        let data = read_unpoisoned(&self.data);
        data.get(id).map(|series| {
            let first = series
                .events
                .partition_point(|event| event.timestamp_secs < start);
            let last = series
                .events
                .partition_point(|event| event.timestamp_secs <= end);
            page_slice(&series.events[first..last], offset, limit)
        })
    }

    /// Return a globally sorted page of events across all aircraft.
    ///
    /// Equal timestamps are ordered by aircraft ID and then by their original
    /// per-aircraft insertion order, providing deterministic replay markers.
    pub fn get_global_events_page(
        &self,
        start: f64,
        end: f64,
        offset: usize,
        limit: usize,
    ) -> StorePage<GlobalTimestampedEvent> {
        let data = read_unpoisoned(&self.data);
        let mut aircraft_ids = data
            .iter()
            .map(|entry| entry.key().clone())
            .collect::<Vec<_>>();
        aircraft_ids.sort();
        let mut events = Vec::new();
        for aircraft_id in aircraft_ids {
            let Some(series) = data.get(&aircraft_id) else {
                continue;
            };
            let first = series
                .events
                .partition_point(|event| event.timestamp_secs < start);
            let last = series
                .events
                .partition_point(|event| event.timestamp_secs <= end);
            events.extend(
                series.events[first..last]
                    .iter()
                    .map(|entry| GlobalTimestampedEvent {
                        aircraft_id: aircraft_id.clone(),
                        timestamp_secs: entry.timestamp_secs,
                        event: entry.event.clone(),
                    }),
            );
        }
        events.sort_by(|left, right| {
            left.timestamp_secs
                .total_cmp(&right.timestamp_secs)
                .then_with(|| left.aircraft_id.cmp(&right.aircraft_id))
        });
        page_slice(&events, offset, limit)
    }

    /// Return the previous globally unique state timestamp.
    ///
    /// Equal timestamps from different aircraft count as one frame. When
    /// `count` exceeds the remaining number of frames, the earliest available
    /// timestamp is returned.
    pub fn previous_global_state_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
        self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::State, false)
    }

    /// Return the next globally unique state timestamp.
    ///
    /// Equal timestamps from different aircraft count as one frame. When
    /// `count` exceeds the remaining number of frames, the latest available
    /// timestamp is returned.
    pub fn next_global_state_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
        self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::State, true)
    }

    /// Return the previous globally unique lifecycle/custom event timestamp.
    pub fn previous_global_event_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
        self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::Event, false)
    }

    /// Return the next globally unique lifecycle/custom event timestamp.
    pub fn next_global_event_timestamp(&self, cursor: f64, count: usize) -> Option<f64> {
        self.adjacent_global_timestamp(cursor, count, TimelineEntryKind::Event, true)
    }

    fn adjacent_global_timestamp(
        &self,
        cursor: f64,
        count: usize,
        kind: TimelineEntryKind,
        forward: bool,
    ) -> Option<f64> {
        if !cursor.is_finite() || count == 0 {
            return None;
        }

        let data = read_unpoisoned(&self.data);
        let mut probe = cursor;
        let mut result = None;
        for _ in 0..count {
            let candidate = data
                .iter()
                .filter_map(|entry| match kind {
                    TimelineEntryKind::State => {
                        if forward {
                            let index = entry
                                .states
                                .partition_point(|state| state.timestamp_secs <= probe);
                            entry.states.get(index).map(|state| state.timestamp_secs)
                        } else {
                            let index = entry
                                .states
                                .partition_point(|state| state.timestamp_secs < probe);
                            index
                                .checked_sub(1)
                                .and_then(|index| entry.states.get(index))
                                .map(|state| state.timestamp_secs)
                        }
                    }
                    TimelineEntryKind::Event => {
                        if forward {
                            let index = entry
                                .events
                                .partition_point(|event| event.timestamp_secs <= probe);
                            entry.events.get(index).map(|event| event.timestamp_secs)
                        } else {
                            let index = entry
                                .events
                                .partition_point(|event| event.timestamp_secs < probe);
                            index
                                .checked_sub(1)
                                .and_then(|index| entry.events.get(index))
                                .map(|event| event.timestamp_secs)
                        }
                    }
                })
                .reduce(|best, candidate| {
                    if (forward && candidate.total_cmp(&best).is_lt())
                        || (!forward && candidate.total_cmp(&best).is_gt())
                    {
                        candidate
                    } else {
                        best
                    }
                });
            let Some(candidate) = candidate else {
                break;
            };
            result = Some(candidate);
            probe = candidate;
        }
        result
    }

    /// Return all aircraft IDs currently in the store, sorted.
    pub fn get_aircraft_ids(&self) -> Vec<AircraftId> {
        let data = read_unpoisoned(&self.data);
        let mut ids: Vec<_> = data.iter().map(|item| item.key().clone()).collect();
        ids.sort();
        ids
    }

    /// Return sorted summary metadata for all aircraft.
    pub fn aircraft_summaries(&self) -> Vec<AircraftSummary> {
        let data = read_unpoisoned(&self.data);
        let mut summaries: Vec<_> = data
            .iter()
            .map(|entry| {
                let series = entry.value();
                AircraftSummary {
                    id: entry.key().clone(),
                    config: series.config.clone(),
                    time_range: aircraft_time_range(series),
                    state_count: series.states.len(),
                    event_count: series.events.len(),
                    telemetry_count: series.telemetry.len(),
                }
            })
            .collect();
        summaries.sort_by(|left, right| left.id.cmp(&right.id));
        summaries
    }

    /// Clone a consistent store snapshot while ingestion is externally paused.
    pub fn snapshot_clone(&self) -> Self {
        let snapshot = Self::new();
        let data = read_unpoisoned(&self.data);
        let snapshot_data = write_unpoisoned(&snapshot.data);
        for entry in &*data {
            snapshot_data.insert(entry.key().clone(), entry.value().clone());
        }
        drop(snapshot_data);
        snapshot
    }

    /// Atomically replace all contents with a clone of another store.
    pub fn replace_from(&self, other: &Self) {
        if std::ptr::eq(self, other) {
            return;
        }
        let replacement = DashMap::new();
        let other_data = read_unpoisoned(&other.data);
        for entry in &*other_data {
            replacement.insert(entry.key().clone(), entry.value().clone());
        }
        drop(other_data);
        *write_unpoisoned(&self.data) = replacement;
        self.live_state_receipts.clear();
    }

    /// Remove all in-memory data.
    pub fn clear(&self) {
        *write_unpoisoned(&self.data) = DashMap::new();
        self.live_state_receipts.clear();
    }

    /// Persist the store to disk at the given directory path.
    pub fn save_to_disk(&self, path: &Path) -> Result<(), StoreError> {
        info!(target: "fly_ruler_proto_core.store", path = %path.display(), "saving store to disk");
        fs::create_dir_all(path)?;

        self.write_meta(path)?;
        self.write_states_parquet(path)?;
        self.write_events_parquet(path)?;
        self.write_telemetry_parquet(path)?;
        info!(target: "fly_ruler_proto_core.store", path = %path.display(), aircraft_count = self.get_aircraft_ids().len(), "store save completed");
        Ok(())
    }

    /// Load a store snapshot from disk, replacing current in-memory contents.
    pub fn load_from_disk(&self, path: &Path) -> Result<(), StoreError> {
        info!(target: "fly_ruler_proto_core.store", path = %path.display(), "loading store from disk");
        let loaded = Self::new();
        loaded.read_states_parquet(path)?;
        loaded.read_events_parquet(path)?;
        loaded.read_telemetry_parquet(path)?;
        loaded.read_meta(path)?;
        self.replace_from(&loaded);
        info!(target: "fly_ruler_proto_core.store", path = %path.display(), aircraft_count = self.get_aircraft_ids().len(), "store load completed");
        Ok(())
    }

    fn write_meta(&self, path: &Path) -> Result<(), StoreError> {
        let mut aircrafts = Vec::new();
        let data = read_unpoisoned(&self.data);
        for item in &*data {
            let id = item.key().clone();
            let series = item.value();
            let time_range = aircraft_time_range(series);

            aircrafts.push(MetaAircraft {
                id,
                name: series.config.as_ref().map(|c| c.name.clone()),
                toml_config: series.config.as_ref().map(|c| c.toml_config.clone()),
                time_range,
                state_count: series.states.len(),
                event_count: series.events.len(),
            });
        }

        aircrafts.sort_by(|a, b| a.id.cmp(&b.id));
        let meta = MetaFile {
            version: PROTOCOL_VERSION.to_string(),
            aircrafts,
        };

        let bytes = serde_json::to_vec_pretty(&meta)?;
        fs::write(path.join("meta.json"), bytes)?;
        Ok(())
    }

    fn read_meta(&self, path: &Path) -> Result<(), StoreError> {
        let meta_path = path.join("meta.json");
        if !meta_path.exists() {
            return Ok(());
        }

        let data = fs::read(meta_path)?;
        let meta: MetaFile = serde_json::from_slice(&data)?;
        for entry in meta.aircrafts {
            let data = read_unpoisoned(&self.data);
            if let Some(mut series) = data.get_mut(&entry.id) {
                if let (Some(name), Some(toml_config)) = (entry.name, entry.toml_config) {
                    let telemetry_schemas = series
                        .config
                        .as_ref()
                        .map(|config| config.telemetry_schemas.clone())
                        .unwrap_or_default();
                    series.config = Some(AircraftConfig {
                        name,
                        toml_config,
                        telemetry_schemas,
                    });
                }
            };
        }

        Ok(())
    }

    fn write_states_parquet(&self, path: &Path) -> Result<(), StoreError> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("aircraft_id", DataType::Utf8, false),
            Field::new("timestamp", DataType::Float64, false),
            Field::new("state_payload", DataType::Binary, false),
        ]));

        let mut ids = Vec::<String>::new();
        let mut ts = Vec::<f64>::new();
        let mut payloads = Vec::<Vec<u8>>::new();

        let data = read_unpoisoned(&self.data);
        for item in &*data {
            let id = item.key().clone();
            for state in &item.value().states {
                ids.push(id.clone());
                ts.push(state.timestamp_secs);
                payloads.push(state.state.encode_to_vec());
            }
        }

        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(ids)) as Arc<dyn Array>,
                Arc::new(Float64Array::from(ts)) as Arc<dyn Array>,
                Arc::new(BinaryArray::from_iter_values(payloads)) as Arc<dyn Array>,
            ],
        )?;

        let file = File::create(path.join("states.parquet"))?;
        let mut writer = ArrowWriter::try_new(file, schema, None)?;
        writer.write(&batch)?;
        writer.close()?;
        Ok(())
    }

    fn write_events_parquet(&self, path: &Path) -> Result<(), StoreError> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("aircraft_id", DataType::Utf8, false),
            Field::new("timestamp", DataType::Float64, false),
            Field::new("event_type", DataType::Utf8, false),
            Field::new("event_payload", DataType::Binary, false),
        ]));

        let mut ids = Vec::<String>::new();
        let mut ts = Vec::<f64>::new();
        let mut kinds = Vec::<String>::new();
        let mut payloads = Vec::<Vec<u8>>::new();

        let data = read_unpoisoned(&self.data);
        for item in &*data {
            let id = item.key().clone();
            for event in &item.value().events {
                ids.push(id.clone());
                ts.push(event.timestamp_secs);
                let (kind, payload) = encode_event(&event.event);
                kinds.push(kind);
                payloads.push(payload);
            }
        }

        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(ids)) as Arc<dyn Array>,
                Arc::new(Float64Array::from(ts)) as Arc<dyn Array>,
                Arc::new(StringArray::from(kinds)) as Arc<dyn Array>,
                Arc::new(BinaryArray::from_iter_values(payloads)) as Arc<dyn Array>,
            ],
        )?;

        let file = File::create(path.join("events.parquet"))?;
        let mut writer = ArrowWriter::try_new(file, schema, None)?;
        writer.write(&batch)?;
        writer.close()?;
        Ok(())
    }

    fn write_telemetry_parquet(&self, path: &Path) -> Result<(), StoreError> {
        let schema = Arc::new(Schema::new(vec![
            Field::new("aircraft_id", DataType::Utf8, false),
            Field::new("timestamp", DataType::Float64, false),
            Field::new("frame_payload", DataType::Binary, false),
        ]));
        let mut ids = Vec::<String>::new();
        let mut timestamps = Vec::<f64>::new();
        let mut payloads = Vec::<Vec<u8>>::new();
        let data = read_unpoisoned(&self.data);
        for item in &*data {
            for sample in &item.value().telemetry {
                ids.push(item.key().clone());
                timestamps.push(sample.timestamp_secs);
                payloads.push(sample.frame.encode_to_vec());
            }
        }
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(ids)),
                Arc::new(Float64Array::from(timestamps)),
                Arc::new(BinaryArray::from_iter_values(payloads)),
            ],
        )?;
        let file = File::create(path.join("telemetry.parquet"))?;
        let mut writer = ArrowWriter::try_new(file, schema, None)?;
        writer.write(&batch)?;
        writer.close()?;
        Ok(())
    }

    fn read_states_parquet(&self, path: &Path) -> Result<(), StoreError> {
        let file_path = path.join("states.parquet");
        if !file_path.exists() {
            return Ok(());
        }

        let file = File::open(file_path)?;
        let mut reader = ParquetRecordBatchReaderBuilder::try_new(file)?
            .with_batch_size(1024)
            .build()?;

        for maybe_batch in &mut reader {
            let batch = maybe_batch?;
            let ids = as_string_array(batch.column(0), "aircraft_id")?;
            let timestamps = as_f64_array(batch.column(1), "timestamp")?;
            let payloads = as_binary_array(batch.column(2), "state_payload")?;

            for i in 0..batch.num_rows() {
                let id = ids.value(i).to_string();
                let ts = timestamps.value(i);
                let state = pb::AircraftState::decode(payloads.value(i))?;
                self.append_state(id, ts, state);
            }
        }

        Ok(())
    }

    fn read_events_parquet(&self, path: &Path) -> Result<(), StoreError> {
        let file_path = path.join("events.parquet");
        if !file_path.exists() {
            return Ok(());
        }

        let file = File::open(file_path)?;
        let mut reader = ParquetRecordBatchReaderBuilder::try_new(file)?
            .with_batch_size(1024)
            .build()?;

        for maybe_batch in &mut reader {
            let batch = maybe_batch?;
            let ids = as_string_array(batch.column(0), "aircraft_id")?;
            let timestamps = as_f64_array(batch.column(1), "timestamp")?;
            let kinds = as_string_array(batch.column(2), "event_type")?;
            let payloads = as_binary_array(batch.column(3), "event_payload")?;

            for i in 0..batch.num_rows() {
                let id = ids.value(i).to_string();
                let ts = timestamps.value(i);
                let event = decode_event(kinds.value(i), payloads.value(i))?;
                self.append_event(id, ts, event);
            }
        }

        Ok(())
    }

    fn read_telemetry_parquet(&self, path: &Path) -> Result<(), StoreError> {
        let file_path = path.join("telemetry.parquet");
        if !file_path.exists() {
            return Ok(());
        }
        let file = File::open(file_path)?;
        let mut reader = ParquetRecordBatchReaderBuilder::try_new(file)?
            .with_batch_size(1024)
            .build()?;
        for maybe_batch in &mut reader {
            let batch = maybe_batch?;
            let ids = as_string_array(batch.column(0), "aircraft_id")?;
            let timestamps = as_f64_array(batch.column(1), "timestamp")?;
            let payloads = as_binary_array(batch.column(2), "frame_payload")?;
            for index in 0..batch.num_rows() {
                self.append_telemetry(
                    ids.value(index).to_string(),
                    timestamps.value(index),
                    pb::TelemetryFrame::decode(payloads.value(index))?,
                )?;
            }
        }
        Ok(())
    }
}

fn validate_telemetry_schemas(schemas: &[pb::TelemetryStreamSchema]) -> Result<(), StoreError> {
    let mut stream_ids = BTreeSet::new();
    for schema in schemas {
        if schema.stream_id.trim().is_empty() || !stream_ids.insert(&schema.stream_id) {
            return Err(StoreError::InvalidData(format!(
                "telemetry stream id must be non-empty and unique: {:?}",
                schema.stream_id
            )));
        }
        if schema
            .nominal_rate_hz
            .is_some_and(|rate| !rate.is_finite() || rate <= 0.0)
        {
            return Err(StoreError::InvalidData(format!(
                "telemetry stream {} has invalid nominal rate",
                schema.stream_id
            )));
        }
        let mut field_ids = BTreeSet::new();
        for field in &schema.fields {
            if field.field_id.trim().is_empty() || !field_ids.insert(&field.field_id) {
                return Err(StoreError::InvalidData(format!(
                    "telemetry field id must be non-empty and unique in stream {}: {:?}",
                    schema.stream_id, field.field_id
                )));
            }
            if !matches!(
                pb::TelemetryValueType::try_from(field.value_type),
                Ok(kind) if kind != pb::TelemetryValueType::Unspecified
            ) {
                return Err(StoreError::InvalidData(format!(
                    "telemetry field {} has invalid value type",
                    field.field_id
                )));
            }
        }
    }
    Ok(())
}

fn validate_telemetry_frame(
    schemas: &[pb::TelemetryStreamSchema],
    frame: &pb::TelemetryFrame,
) -> Result<(), StoreError> {
    let schema = schemas
        .iter()
        .find(|schema| schema.stream_id == frame.stream_id)
        .ok_or_else(|| {
            StoreError::InvalidData(format!("unknown telemetry stream: {}", frame.stream_id))
        })?;
    if frame.values.len() != schema.fields.len() {
        return Err(StoreError::InvalidData(format!(
            "telemetry stream {} expects {} values, got {}",
            frame.stream_id,
            schema.fields.len(),
            frame.values.len()
        )));
    }
    for (field, value) in schema.fields.iter().zip(&frame.values) {
        let valid = matches!(
            (
                pb::TelemetryValueType::try_from(field.value_type),
                value.kind.as_ref()
            ),
            (
                Ok(pb::TelemetryValueType::F64),
                Some(pb::telemetry_value::Kind::F64Value(_))
            ) | (
                Ok(pb::TelemetryValueType::I64),
                Some(pb::telemetry_value::Kind::I64Value(_))
            ) | (
                Ok(pb::TelemetryValueType::Bool),
                Some(pb::telemetry_value::Kind::BoolValue(_))
            )
        );
        if !valid {
            return Err(StoreError::InvalidData(format!(
                "telemetry field {} has a mismatched value type",
                field.field_id
            )));
        }
    }
    Ok(())
}

#[derive(Debug, Clone, Copy)]
enum TimelineEntryKind {
    State,
    Event,
}

fn page_slice<T: Clone>(items: &[T], offset: usize, limit: usize) -> StorePage<T> {
    let total = items.len();
    let start = offset.min(total);
    let end = start.saturating_add(limit).min(total);
    StorePage {
        items: items[start..end].to_vec(),
        total,
        offset,
        limit,
    }
}

fn aircraft_time_range(series: &AircraftTimeSeries) -> Option<(f64, f64)> {
    let first = series
        .states
        .first()
        .map(|sample| sample.timestamp_secs)
        .into_iter()
        .chain(series.events.first().map(|event| event.timestamp_secs))
        .chain(series.telemetry.first().map(|frame| frame.timestamp_secs))
        .min_by(f64::total_cmp)?;
    let last = series
        .states
        .last()
        .map(|sample| sample.timestamp_secs)
        .into_iter()
        .chain(series.events.last().map(|event| event.timestamp_secs))
        .chain(series.telemetry.last().map(|frame| frame.timestamp_secs))
        .max_by(f64::total_cmp)?;
    Some((first, last))
}

fn read_unpoisoned<T>(lock: &RwLock<T>) -> RwLockReadGuard<'_, T> {
    lock.read().unwrap_or_else(|poisoned| poisoned.into_inner())
}

fn write_unpoisoned<T>(lock: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
    lock.write()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

fn as_string_array<'a>(
    array: &'a Arc<dyn Array>,
    name: &str,
) -> Result<&'a StringArray, StoreError> {
    array
        .as_any()
        .downcast_ref::<StringArray>()
        .ok_or_else(|| StoreError::InvalidData(format!("{name} column type mismatch")))
}

fn as_f64_array<'a>(array: &'a Arc<dyn Array>, name: &str) -> Result<&'a Float64Array, StoreError> {
    array
        .as_any()
        .downcast_ref::<Float64Array>()
        .ok_or_else(|| StoreError::InvalidData(format!("{name} column type mismatch")))
}

fn as_binary_array<'a>(
    array: &'a Arc<dyn Array>,
    name: &str,
) -> Result<&'a BinaryArray, StoreError> {
    array
        .as_any()
        .downcast_ref::<BinaryArray>()
        .ok_or_else(|| StoreError::InvalidData(format!("{name} column type mismatch")))
}

fn encode_event(event: &Event) -> (String, Vec<u8>) {
    match event {
        Event::Spawn(spawn) => ("spawn".to_string(), spawn.encode_to_vec()),
        Event::Despawn(despawn) => ("despawn".to_string(), despawn.encode_to_vec()),
        Event::Custom(custom) => ("custom".to_string(), custom.as_bytes().to_vec()),
    }
}

fn decode_event(kind: &str, payload: &[u8]) -> Result<Event, StoreError> {
    match kind {
        "spawn" => Ok(Event::Spawn(Box::new(pb::AircraftSpawnInfo::decode(
            payload,
        )?))),
        "despawn" => Ok(Event::Despawn(pb::DespawnInfo::decode(payload)?)),
        "custom" => Ok(Event::Custom(String::from_utf8(payload.to_vec()).map_err(
            |e| StoreError::InvalidData(format!("invalid utf8 custom event: {e}")),
        )?)),
        _ => Err(StoreError::InvalidData(format!(
            "unknown event type: {kind}"
        ))),
    }
}

/// Return the total number of events across all aircraft.
pub fn event_count_for(store: &TimeSeriesStore) -> usize {
    let data = read_unpoisoned(&store.data);
    data.iter().map(|entry| entry.value().events.len()).sum()
}

/// Return the total number of state samples across all aircraft.
pub fn state_count_for(store: &TimeSeriesStore) -> usize {
    let data = read_unpoisoned(&store.data);
    data.iter().map(|entry| entry.value().states.len()).sum()
}

/// Return the total number of telemetry frames across all aircraft.
pub fn telemetry_count_for(store: &TimeSeriesStore) -> usize {
    let data = read_unpoisoned(&store.data);
    data.iter().map(|entry| entry.value().telemetry.len()).sum()
}

/// Return the number of distinct aircraft currently in the store.
pub fn aircraft_count_for(store: &TimeSeriesStore) -> usize {
    read_unpoisoned(&store.data).iter().count()
}

/// Return the global minimum and maximum state/event timestamps.
pub fn active_time_bounds(store: &TimeSeriesStore) -> Option<(f64, f64)> {
    let mut min_start: Option<f64> = None;
    let mut max_end: Option<f64> = None;

    let data = read_unpoisoned(&store.data);
    for entry in &*data {
        let series = entry.value();
        let first = series
            .states
            .first()
            .map(|state| state.timestamp_secs)
            .into_iter()
            .chain(series.events.first().map(|event| event.timestamp_secs))
            .chain(series.telemetry.first().map(|frame| frame.timestamp_secs))
            .min_by(f64::total_cmp);
        let last = series
            .states
            .last()
            .map(|state| state.timestamp_secs)
            .into_iter()
            .chain(series.events.last().map(|event| event.timestamp_secs))
            .chain(series.telemetry.last().map(|frame| frame.timestamp_secs))
            .max_by(f64::total_cmp);
        if let (Some(first), Some(last)) = (first, last) {
            min_start = Some(match min_start {
                Some(current) => current.min(first),
                None => first,
            });
            max_end = Some(match max_end {
                Some(current) => current.max(last),
                None => last,
            });
        }
    }

    Some((min_start?, max_end?))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn mk_state(x: f64) -> pb::AircraftState {
        pb::AircraftState {
            position: Some(pb::Vector3 { x, y: 0.0, z: 0.0 }),
            velocity: Some(pb::Vector3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            }),
            attitude: Some(pb::Quaternion {
                w: 1.0,
                x: 0.0,
                y: 0.0,
                z: 0.0,
            }),
            angular_velocity: Some(pb::Vector3 {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            }),
            derived: None,
            control_surfaces: None,
            linear_acceleration_body: None,
            propulsors: vec![],
        }
    }

    fn state_message(timestamp: f64, state: pb::AircraftState) -> pb::Message {
        pb::Message {
            envelope: Some(pb::message::Envelope::Request(pb::Request {
                id: None,
                timestamp,
                command: Some(pb::RequestCommand {
                    kind: Some(pb::request_command::Kind::AircraftEvent(
                        pb::AircraftEvent {
                            aircraft_id: Some(pb::Uuid {
                                value: vec![0x11; 16],
                            }),
                            info: Some(pb::AircraftCommandInfo {
                                kind: Some(pb::aircraft_command_info::Kind::StateUpdate(state)),
                            }),
                        },
                    )),
                }),
            })),
        }
    }

    #[test]
    fn append_and_query_range_works() {
        let store = TimeSeriesStore::new();
        store.append_state("a1".to_string(), 1.0, mk_state(1.0));
        store.append_state("a1".to_string(), 2.0, mk_state(2.0));
        store.append_state("a1".to_string(), 3.0, mk_state(3.0));

        let latest = store.get_latest(&"a1".to_string()).unwrap();
        assert_eq!(latest.timestamp_secs, 3.0);

        let range = store.get_states_range(&"a1".to_string(), 1.5, 3.0).unwrap();
        assert_eq!(range.len(), 2);
        assert_eq!(range[0].timestamp_secs, 2.0);
    }

    #[test]
    fn live_freshness_uses_receipt_time_not_source_timeline() {
        let store = TimeSeriesStore::new();
        let id = "11".repeat(16);
        store.append_message(state_message(0.0, mk_state(1.0)));

        assert!(!store.live_state_is_stale(&id, Duration::from_secs(60)));
        assert_eq!(store.get_latest(&id).unwrap().timestamp_secs, 0.0);

        store.clear();
        assert!(store.live_state_is_stale(&id, Duration::from_secs(60)));
    }

    #[test]
    fn non_finite_source_timestamp_does_not_create_live_freshness() {
        let store = TimeSeriesStore::new();
        let id = "11".repeat(16);
        store.append_message(state_message(f64::NAN, mk_state(1.0)));
        store.append_state(id.clone(), f64::INFINITY, mk_state(2.0));
        store.append_event(
            id.clone(),
            f64::NEG_INFINITY,
            Event::Custom("bad".to_string()),
        );

        assert!(store.get_latest(&id).is_none());
        assert!(store
            .get_events_range(&id, f64::NEG_INFINITY, f64::INFINITY)
            .is_none());
        assert!(store.live_state_age(&id).is_none());
    }

    #[test]
    fn telemetry_schema_and_frame_validation_are_strict() {
        let duplicate = pb::TelemetryStreamSchema {
            stream_id: "controller".to_string(),
            name: String::new(),
            nominal_rate_hz: Some(100.0),
            fields: vec![
                pb::TelemetryField {
                    field_id: "controller.error".to_string(),
                    value_type: pb::TelemetryValueType::F64 as i32,
                    ..Default::default()
                },
                pb::TelemetryField {
                    field_id: "controller.error".to_string(),
                    value_type: pb::TelemetryValueType::F64 as i32,
                    ..Default::default()
                },
            ],
        };
        assert!(validate_telemetry_schemas(&[duplicate]).is_err());

        let store = TimeSeriesStore::new();
        store.append_event(
            "a1".to_string(),
            0.0,
            Event::Spawn(Box::new(pb::AircraftSpawnInfo {
                name: "test".to_string(),
                toml_config: String::new(),
                initial_state: None,
                telemetry_schemas: vec![pb::TelemetryStreamSchema {
                    stream_id: "runtime".to_string(),
                    name: String::new(),
                    nominal_rate_hz: None,
                    fields: vec![pb::TelemetryField {
                        field_id: "runtime.healthy".to_string(),
                        value_type: pb::TelemetryValueType::Bool as i32,
                        ..Default::default()
                    }],
                }],
            })),
        );
        let wrong_type = pb::TelemetryFrame {
            stream_id: "runtime".to_string(),
            sequence: 1,
            values: vec![pb::TelemetryValue {
                kind: Some(pb::telemetry_value::Kind::F64Value(1.0)),
            }],
        };
        assert!(store
            .append_telemetry("a1".to_string(), 1.0, wrong_type)
            .is_err());
        let unknown = pb::TelemetryFrame {
            stream_id: "unknown".to_string(),
            sequence: 1,
            values: Vec::new(),
        };
        assert!(store
            .append_telemetry("a1".to_string(), 1.0, unknown)
            .is_err());
    }

    #[test]
    fn save_and_load_roundtrip_works() {
        let store = TimeSeriesStore::new();
        store.append_state("a1".to_string(), 1.0, mk_state(10.0));
        store.append_event("a1".to_string(), 1.5, Event::Custom("evt".to_string()));
        store.append_event(
            "a1".to_string(),
            0.5,
            Event::Spawn(Box::new(pb::AircraftSpawnInfo {
                name: "test".to_string(),
                toml_config: String::new(),
                initial_state: None,
                telemetry_schemas: vec![pb::TelemetryStreamSchema {
                    stream_id: "runtime".to_string(),
                    name: "Runtime".to_string(),
                    nominal_rate_hz: None,
                    fields: vec![pb::TelemetryField {
                        field_id: "runtime.realtime_factor".to_string(),
                        label: String::new(),
                        group: String::new(),
                        unit: String::new(),
                        description: String::new(),
                        value_type: pb::TelemetryValueType::F64 as i32,
                    }],
                }],
            })),
        );
        store
            .append_telemetry(
                "a1".to_string(),
                1.25,
                pb::TelemetryFrame {
                    stream_id: "runtime".to_string(),
                    sequence: 1,
                    values: vec![pb::TelemetryValue {
                        kind: Some(pb::telemetry_value::Kind::F64Value(1.0)),
                    }],
                },
            )
            .unwrap();

        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("fly_ruler_store_test_{nanos}"));

        store.save_to_disk(&dir).unwrap();

        let restored = TimeSeriesStore::new();
        restored.load_from_disk(&dir).unwrap();

        assert_eq!(state_count_for(&restored), 1);
        assert_eq!(event_count_for(&restored), 2);
        assert_eq!(telemetry_count_for(&restored), 1);
        assert_eq!(aircraft_count_for(&restored), 1);

        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn out_of_order_state_insert_keeps_sorted_order() {
        let store = TimeSeriesStore::new();
        store.append_state("a1".to_string(), 3.0, mk_state(3.0));
        store.append_state("a1".to_string(), 1.0, mk_state(1.0));
        store.append_state("a1".to_string(), 2.0, mk_state(2.0));

        let states = store
            .get_states_range(&"a1".to_string(), 0.0, 10.0)
            .unwrap();
        assert_eq!(states.len(), 3);
        assert_eq!(states[0].timestamp_secs, 1.0);
        assert_eq!(states[1].timestamp_secs, 2.0);
        assert_eq!(states[2].timestamp_secs, 3.0);
    }

    #[test]
    fn adjacent_global_timestamps_deduplicate_and_clamp_to_available_entries() {
        let store = TimeSeriesStore::new();
        for timestamp in [1.0, 2.0, 4.0] {
            store.append_state("a".to_string(), timestamp, mk_state(timestamp));
        }
        for timestamp in [2.0, 3.0, 5.0] {
            store.append_state("b".to_string(), timestamp, mk_state(timestamp));
        }
        store.append_event("a".to_string(), 1.5, Event::Custom("a".to_string()));
        store.append_event("b".to_string(), 3.5, Event::Custom("b".to_string()));

        assert_eq!(store.next_global_state_timestamp(1.0, 1), Some(2.0));
        assert_eq!(store.next_global_state_timestamp(1.0, 2), Some(3.0));
        assert_eq!(store.next_global_state_timestamp(1.0, 99), Some(5.0));
        assert_eq!(store.previous_global_state_timestamp(5.0, 2), Some(3.0));
        assert_eq!(store.previous_global_event_timestamp(4.0, 1), Some(3.5));
        assert_eq!(store.next_global_event_timestamp(0.0, 99), Some(3.5));
    }

    #[test]
    fn spawn_event_populates_aircraft_config() {
        let store = TimeSeriesStore::new();
        let spawn = pb::AircraftSpawnInfo {
            name: "F-16".to_string(),
            toml_config: "[aircraft]\nname='F-16'".to_string(),
            initial_state: Some(mk_state(0.0)),
            telemetry_schemas: Vec::new(),
        };
        store.append_event("a1".to_string(), 1.0, Event::Spawn(Box::new(spawn)));

        let data = read_unpoisoned(&store.data);
        let entry = data.get("a1").unwrap();
        let config = entry.config.as_ref().unwrap();
        assert_eq!(config.name, "F-16");
        assert!(config.toml_config.contains("aircraft"));
    }

    #[test]
    fn clear_removes_all_in_memory_data() {
        let store = TimeSeriesStore::new();
        store.append_state("a1".to_string(), 1.0, mk_state(1.0));
        store.append_event("a1".to_string(), 1.2, Event::Custom("x".to_string()));
        assert_eq!(aircraft_count_for(&store), 1);

        store.clear();

        assert_eq!(aircraft_count_for(&store), 0);
        assert_eq!(state_count_for(&store), 0);
        assert_eq!(event_count_for(&store), 0);
    }

    #[test]
    fn active_time_bounds_returns_global_min_max() {
        let store = TimeSeriesStore::new();
        store.append_state("a1".to_string(), 10.0, mk_state(1.0));
        store.append_state("a1".to_string(), 20.0, mk_state(2.0));
        store.append_state("a2".to_string(), 5.0, mk_state(3.0));
        store.append_state("a2".to_string(), 25.0, mk_state(4.0));
        store.append_event("a1".to_string(), 30.0, Event::Custom("end".to_string()));
        store.append_event("a2".to_string(), 1.0, Event::Custom("begin".to_string()));

        let bounds = active_time_bounds(&store).unwrap();
        assert_eq!(bounds.0, 1.0);
        assert_eq!(bounds.1, 30.0);
    }

    #[test]
    fn state_at_or_before_uses_last_duplicate() {
        let store = TimeSeriesStore::new();
        store.append_state("a1".to_string(), 1.0, mk_state(1.0));
        store.append_state("a1".to_string(), 1.0, mk_state(2.0));
        store.append_state("a1".to_string(), 2.0, mk_state(3.0));

        let state = store
            .get_state_at_or_before(&"a1".to_string(), 1.0)
            .unwrap();
        assert_eq!(state.state.position.unwrap().x, 2.0);
        assert!(store
            .get_state_at_or_before(&"a1".to_string(), 0.5)
            .is_none());
    }

    #[test]
    fn paginated_ranges_report_total() {
        let store = TimeSeriesStore::new();
        for timestamp in 0..5 {
            store.append_state(
                "a1".to_string(),
                timestamp as f64,
                mk_state(timestamp as f64),
            );
        }
        let page = store
            .get_states_page(&"a1".to_string(), 1.0, 4.0, 1, 2)
            .unwrap();
        assert_eq!(page.total, 4);
        assert_eq!(page.items.len(), 2);
        assert_eq!(page.items[0].timestamp_secs, 2.0);
    }

    #[test]
    fn global_event_page_is_sorted_and_paginated() {
        let store = TimeSeriesStore::new();
        store.append_event("b".to_string(), 2.0, Event::Custom("b2".to_string()));
        store.append_event("a".to_string(), 1.0, Event::Custom("a1".to_string()));
        store.append_event("b".to_string(), 1.0, Event::Custom("b1".to_string()));
        store.append_event("a".to_string(), 3.0, Event::Custom("a3".to_string()));

        let page = store.get_global_events_page(1.0, 3.0, 1, 2);
        assert_eq!(page.total, 4);
        assert_eq!(page.items.len(), 2);
        assert_eq!(page.items[0].aircraft_id, "b");
        assert_eq!(page.items[0].timestamp_secs, 1.0);
        assert_eq!(page.items[1].aircraft_id, "b");
        assert_eq!(page.items[1].timestamp_secs, 2.0);
    }

    #[test]
    fn snapshot_replace_and_lifecycle_queries_work() {
        let store = TimeSeriesStore::new();
        store.append_event("a1".to_string(), 1.0, Event::Spawn(Box::default()));
        store.append_event(
            "a1".to_string(),
            3.0,
            Event::Despawn(pb::DespawnInfo::default()),
        );
        assert!(store.is_spawned_at(&"a1".to_string(), 2.0));
        assert!(!store.is_spawned_at(&"a1".to_string(), 4.0));

        let snapshot = store.snapshot_clone();
        store.clear();
        store.replace_from(&snapshot);
        assert_eq!(store.aircraft_summaries().len(), 1);
    }
}