Junjie
18 小时以前 42ce1f4b6f9df984d14e29f9d9ff188de7f3c6d7
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
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
package com.zy.asrs.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.zy.asrs.domain.replay.DeviceReplayChunkMeta;
import com.zy.asrs.domain.replay.DeviceReplayManifest;
import com.zy.asrs.domain.replay.DeviceReplayState;
import com.zy.asrs.domain.replay.DeviceReplayStreamKey;
import com.zy.asrs.domain.replay.ReplayChunk;
import com.zy.asrs.domain.replay.ReplayFrameSummary;
import com.zy.asrs.domain.replay.ReplaySeekResult;
import com.zy.asrs.domain.replay.ReplaySessionContext;
import com.zy.asrs.entity.DeviceDataLog;
import com.zy.asrs.service.DeviceLogReplayManifestService;
import com.zy.asrs.service.DeviceLogReplayNormalizer;
import com.zy.asrs.service.DeviceLogReplayService;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
 
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
@Slf4j
@Service
public class DeviceLogReplayServiceImpl implements DeviceLogReplayService {
 
    private static final long CURRENT_DAY_MANIFEST_REFRESH_INTERVAL_MS = 2_000L;
    private static final long DEFAULT_REPLAY_WINDOW_HALF_MS = 15L * 60L * 1000L;
    private static final long DAY_END_OFFSET_MS = 24L * 60L * 60L * 1000L - 1L;
    private static final String REPLAY_WINDOW_MISSING = "REPLAY_WINDOW_MISSING";
    private static final String REPLAY_WINDOW_INVALID = "REPLAY_WINDOW_INVALID";
    private static final String REPLAY_WINDOW_CROSS_DAY = "REPLAY_WINDOW_CROSS_DAY";
    private static final String REPLAY_WINDOW_TOO_LARGE = "REPLAY_WINDOW_TOO_LARGE";
    private static final String REPLAY_SEEK_OUT_OF_WINDOW = "REPLAY_SEEK_OUT_OF_WINDOW";
 
    private final DeviceLogReplayManifestService manifestService;
    private final DeviceLogReplayNormalizer replayNormalizer;
 
    private final ConcurrentHashMap<String, ReplaySessionContext> sessions = new ConcurrentHashMap<>();
    private final ExecutorService replayWarmupExecutor = Executors.newSingleThreadExecutor(runnable -> {
        Thread thread = new Thread(runnable, "replay-tail-checkpoint-warmup");
        thread.setDaemon(true);
        return thread;
    });
 
    @Value("${deviceLogStorage.type}")
    private String storageType;
    @Value("${deviceLogStorage.loggingPath}")
    private String loggingPath;
    @Value("${deviceReplay.chunkSampleSize:400}")
    private Integer chunkSampleSize;
    @Value("${deviceReplay.maxChunkFrames:32}")
    private Integer maxChunkFrames;
    @Value("${deviceReplay.timelineBucketSeconds:20}")
    private Integer timelineBucketSeconds;
    @Value("${deviceReplay.maxWindowMinutes:240}")
    private Integer maxWindowMinutes;
    @Value("${deviceReplay.maxConcurrentSessions:4}")
    private Integer maxConcurrentSessions;
    @Value("${deviceReplay.maxPrefetchChunks:3}")
    private Integer maxPrefetchChunks;
    @Value("${deviceReplay.maxChunkCacheEntries:128}")
    private Integer maxChunkCacheEntries;
    @Value("${deviceReplay.sessionTtlSeconds:1800}")
    private Integer sessionTtlSeconds;
 
    public DeviceLogReplayServiceImpl(DeviceLogReplayManifestService manifestService,
                                      DeviceLogReplayNormalizer replayNormalizer) {
        this.manifestService = manifestService;
        this.replayNormalizer = replayNormalizer;
    }
 
    @Override
    public Map<String, Object> createSession(String day,
                                             String type,
                                             Integer deviceNo,
                                             Integer stationId,
                                             Long targetTimestamp,
                                             Long windowStartTimeMs,
                                             Long windowEndTimeMs) {
        ensureFileMode();
        ReplayWindow replayWindow = resolveReplayWindow(day, targetTimestamp, windowStartTimeMs, windowEndTimeMs);
        cleanupExpiredSessions();
        if (sessions.size() >= safePositive(maxConcurrentSessions, 4)) {
            throw new IllegalStateException("历史回放会话已满,请先关闭未使用的回放页面");
        }
        boolean currentReplayDay = isCurrentReplayDay(day);
        if (type != null && !type.isBlank() && deviceNo != null) {
            warmupEntryManifest(day, type, deviceNo, stationId);
        }
        List<DeviceReplayManifest> manifests = loadSessionManifests(day, currentReplayDay, true);
        if (manifests.isEmpty()) {
            throw new IllegalArgumentException("当天没有可回放清单,请确认该日期日志已生成 replay manifest");
        }
        TimelineChunkSnapshotData timelineSnapshot = buildTimelineChunkSnapshot(manifests, replayWindow.startTimeMs, replayWindow.endTimeMs);
        ReplaySessionContext session = new ReplaySessionContext();
        session.setSessionId(UUID.randomUUID().toString().replace("-", ""));
        session.setDay(day);
        session.setCreatedAtMs(System.currentTimeMillis());
        session.setLastAccessAtMs(session.getCreatedAtMs());
        session.setWindowStartTimeMs(replayWindow.startTimeMs);
        session.setWindowEndTimeMs(replayWindow.endTimeMs);
        session.setStartTimeMs(replayWindow.startTimeMs);
        session.setEndTimeMs(replayWindow.endTimeMs);
        session.setTimelineChunks(timelineSnapshot.timelineChunks);
        session.setChunkStreamIdsByChunk(timelineSnapshot.chunkStreamIdsByChunk);
        session.setLastManifestRefreshAtMs(System.currentTimeMillis());
        session.setManifestSnapshotKey(buildManifestSnapshotKey(manifests));
        session.setManifestByStream(buildManifestSnapshot(manifests));
        sessions.put(session.getSessionId(), session);
        if (currentReplayDay) {
            manifestService.scheduleDayManifestRefresh(day);
            scheduleTailCheckpointWarmup(session.getSessionId());
        }
 
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("sessionId", session.getSessionId());
        data.put("day", day);
        data.put("startTimeMs", session.getStartTimeMs());
        data.put("endTimeMs", session.getEndTimeMs());
        data.put("windowStartTimeMs", session.getWindowStartTimeMs());
        data.put("windowEndTimeMs", session.getWindowEndTimeMs());
        data.put("chunkCount", session.getTimelineChunks().size());
        data.put("streamCount", session.getManifestByStream().size());
        data.put("entryType", type);
        data.put("entryDeviceNo", deviceNo);
        data.put("entryStationId", stationId);
        data.put("maxPrefetchChunks", safePositive(maxPrefetchChunks, 3));
        return data;
    }
 
    @Override
    public Map<String, Object> loadTimeline(String sessionId) {
        ReplaySessionContext session = requireSession(sessionId);
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("sessionId", session.getSessionId());
        data.put("day", session.getDay());
        data.put("startTimeMs", session.getStartTimeMs());
        data.put("endTimeMs", session.getEndTimeMs());
        data.put("windowStartTimeMs", session.getWindowStartTimeMs());
        data.put("windowEndTimeMs", session.getWindowEndTimeMs());
        data.put("chunks", session.getTimelineChunks());
        data.put("maxPrefetchChunks", safePositive(maxPrefetchChunks, 3));
        return data;
    }
 
    @Override
    public Map<String, Object> loadTimelineSummary(String sessionId, Integer bucketCount) {
        ReplaySessionContext session = requireSession(sessionId);
        int effectiveBucketCount = resolveSummaryBucketCount(session, bucketCount);
        synchronized (session.getTimelineSummaryCache()) {
            Map<String, Object> cachedSummary = session.getTimelineSummaryCache().get(effectiveBucketCount);
            if (cachedSummary != null) {
                return cachedSummary;
            }
        }
        TimelineSummarySnapshot summarySnapshot = buildTimelineSummarySnapshot(session);
        Map<String, Object> summary = buildTimelineSummary(summarySnapshot, effectiveBucketCount);
        synchronized (session.getTimelineSummaryCache()) {
            Map<String, Object> cachedSummary = session.getTimelineSummaryCache().get(effectiveBucketCount);
            if (cachedSummary != null) {
                return cachedSummary;
            }
            session.getTimelineSummaryCache().put(effectiveBucketCount, summary);
            return summary;
        }
    }
 
    private TimelineSummarySnapshot buildTimelineSummarySnapshot(ReplaySessionContext session) {
        TimelineSummarySnapshot snapshot = new TimelineSummarySnapshot();
        synchronized (session) {
            snapshot.sessionId = session.getSessionId();
            snapshot.day = session.getDay();
            snapshot.startTimeMs = safeLong(session.getStartTimeMs());
            snapshot.endTimeMs = safeLong(session.getEndTimeMs());
            snapshot.windowStartTimeMs = safeLong(session.getWindowStartTimeMs());
            snapshot.windowEndTimeMs = safeLong(session.getWindowEndTimeMs());
            snapshot.timelineChunks = new ArrayList<>(session.getTimelineChunks());
            snapshot.manifests = new ArrayList<>(session.getManifestByStream().values());
        }
        return snapshot;
    }
 
    private Map<String, Object> buildTimelineSummary(TimelineSummarySnapshot snapshot, int bucketCount) {
        Map<String, Object> summary = new LinkedHashMap<>();
        List<Map<String, Object>> buckets = new ArrayList<>();
        if (bucketCount <= 0 || snapshot.timelineChunks.isEmpty()) {
            summary.put("sessionId", snapshot.sessionId);
            summary.put("day", snapshot.day);
            summary.put("bucketCount", 0);
            summary.put("startTimeMs", snapshot.startTimeMs);
            summary.put("endTimeMs", snapshot.endTimeMs);
            summary.put("buckets", buckets);
            return summary;
        }
 
        long totalDurationMs = Math.max(1L, snapshot.endTimeMs - snapshot.startTimeMs + 1L);
        long bucketDurationMs = Math.max(1L, (long) Math.ceil(totalDurationMs / (double) bucketCount));
        for (int bucketIndex = 0; bucketIndex < bucketCount; bucketIndex++) {
            long bucketStartTime = snapshot.startTimeMs + bucketIndex * bucketDurationMs;
            if (bucketStartTime > snapshot.endTimeMs) {
                bucketStartTime = snapshot.endTimeMs;
            }
            long bucketEndTime = Math.min(snapshot.endTimeMs, bucketStartTime + bucketDurationMs - 1L);
            int startChunkIndex = resolveChunkIndex(snapshot.timelineChunks, bucketStartTime, 0L);
            int endChunkIndex = resolveChunkIndex(snapshot.timelineChunks, bucketEndTime, 0L);
            if (endChunkIndex < startChunkIndex) {
                endChunkIndex = startChunkIndex;
            }
            buckets.add(buildSummaryBucket(snapshot, bucketIndex, bucketStartTime, bucketEndTime, startChunkIndex, endChunkIndex));
        }
        summary.put("sessionId", snapshot.sessionId);
        summary.put("day", snapshot.day);
        summary.put("bucketCount", bucketCount);
        summary.put("startTimeMs", snapshot.startTimeMs);
        summary.put("endTimeMs", snapshot.endTimeMs);
        summary.put("buckets", buckets);
        return summary;
    }
 
    private Map<String, Object> buildSummaryBucket(TimelineSummarySnapshot snapshot,
                                                   int bucketIndex,
                                                   long bucketStartTime,
                                                   long bucketEndTime,
                                                   int startChunkIndex,
                                                   int endChunkIndex) {
        Map<String, Object> bucket = new LinkedHashMap<>();
        bucket.put("bucketIndex", bucketIndex);
        bucket.put("startTimeMs", clampTimestampToWindow(snapshot, bucketStartTime));
        bucket.put("endTimeMs", clampTimestampToWindow(snapshot, bucketEndTime));
 
        int firstDataChunkIndex = -1;
        int anchorChunkIndex = -1;
        int anchorFrameIndex = -1;
        int firstAbnormalChunkIndex = -1;
        int firstAbnormalFrameIndex = -1;
        String topEventType = "";
        int bucketEstimatedSamples = 0;
 
        for (int chunkIndex = startChunkIndex; chunkIndex <= endChunkIndex; chunkIndex++) {
            Map<String, Object> chunkMeta = resolveTimelineChunk(snapshot.timelineChunks, chunkIndex);
            int estimatedSamples = intValue(chunkMeta.get("estimatedSamples"));
            bucketEstimatedSamples += Math.max(0, estimatedSamples);
            if (firstDataChunkIndex >= 0 || estimatedSamples <= 0) {
                continue;
            }
            firstDataChunkIndex = chunkIndex;
        }
 
        boolean hasReplayData = bucketEstimatedSamples > 0 && firstDataChunkIndex >= 0;
        int activityScore = hasReplayData ? 100 : 0;
        int abnormalCount = 0;
        int errorCount = 0;
        int blockCount = 0;
        boolean hasCrnData = false;
        boolean hasStationData = false;
        boolean hasRgvData = false;
 
        if (hasReplayData) {
            long visibleBucketStartTime = clampTimestampToWindow(snapshot, bucketStartTime);
            long visibleBucketEndTime = clampTimestampToWindow(snapshot, bucketEndTime);
            for (DeviceReplayManifest manifest : snapshot.manifests) {
                if (manifest == null) {
                    continue;
                }
                long manifestStartTime = safeLong(manifest.getFirstSampleTimeMs());
                long manifestEndTime = safeLong(manifest.getLastSampleTimeMs());
                if (manifestEndTime < visibleBucketStartTime || manifestStartTime > visibleBucketEndTime) {
                    continue;
                }
                if ("Devp".equalsIgnoreCase(manifest.getType())) {
                    hasStationData = true;
                } else if ("Rgv".equalsIgnoreCase(manifest.getType())) {
                    hasRgvData = true;
                } else if ("Crn".equalsIgnoreCase(manifest.getType()) || "DualCrn".equalsIgnoreCase(manifest.getType())) {
                    hasCrnData = true;
                }
            }
        }
 
        if (hasReplayData && anchorChunkIndex < 0) {
            anchorChunkIndex = firstDataChunkIndex;
            anchorFrameIndex = 0;
        }
 
        bucket.put("activityScore", activityScore);
        bucket.put("abnormalCount", abnormalCount);
        bucket.put("errorCount", errorCount);
        bucket.put("blockCount", blockCount);
        bucket.put("hasReplayData", hasReplayData);
        bucket.put("hasCrnData", hasCrnData);
        bucket.put("hasStationData", hasStationData);
        bucket.put("hasRgvData", hasRgvData);
        bucket.put("anchorChunkIndex", anchorChunkIndex);
        bucket.put("anchorFrameIndex", anchorFrameIndex);
        bucket.put("firstAbnormalChunkIndex", firstAbnormalChunkIndex);
        bucket.put("firstAbnormalFrameIndex", firstAbnormalFrameIndex);
        bucket.put("topEventType", topEventType);
        return bucket;
    }
 
    @Override
    public ReplayChunk loadChunk(String sessionId, Integer chunkIndex) {
        ReplaySessionContext session = requireSession(sessionId);
        return projectChunkForClient(session, loadFullChunk(session, chunkIndex));
    }
 
    private ReplayChunk loadFullChunk(ReplaySessionContext session, Integer chunkIndex) {
        ReplayChunk cachedChunk = getCachedChunk(session, chunkIndex, true);
        if (cachedChunk != null) {
            return cachedChunk;
        }
        String manifestSnapshotKey = session.getManifestSnapshotKey();
        ReplayChunk chunk = buildChunk(session, chunkIndex, true);
        if (isSameManifestSnapshot(session, manifestSnapshotKey)) {
            cacheChunk(session, chunkIndex, chunk, true);
        } else {
            chunk = buildChunk(session, chunkIndex, true);
        }
        return chunk;
    }
 
    @Override
    public ReplayChunk loadChunk(String sessionId, Integer chunkIndex, boolean fullFrames) {
        ReplaySessionContext session = requireSession(sessionId);
        ReplayChunk cachedChunk = getCachedChunk(session, chunkIndex, fullFrames);
        if (cachedChunk != null) {
            return projectChunkForClient(session, cachedChunk);
        }
        String manifestSnapshotKey = session.getManifestSnapshotKey();
        ReplayChunk chunk = fullFrames
                ? buildChunk(session, chunkIndex, true)
                : buildCompactChunk(session, chunkIndex);
        if (isSameManifestSnapshot(session, manifestSnapshotKey)) {
            cacheChunk(session, chunkIndex, chunk, fullFrames);
        } else {
            chunk = fullFrames
                    ? buildChunk(session, chunkIndex, true)
                    : buildCompactChunk(session, chunkIndex);
        }
        return projectChunkForClient(session, chunk);
    }
 
    private ReplayChunk buildCompactChunk(ReplaySessionContext session, Integer chunkIndex) {
        Map<String, Object> chunkMeta = resolveTimelineChunk(session, chunkIndex);
        long startTime = numberValue(chunkMeta.get("startTimeMs"));
        long endTime = numberValue(chunkMeta.get("endTimeMs"));
        long sampleSeq = numberValue(chunkMeta.get("lastSampleSeq"));
 
        ReplayChunk chunk = new ReplayChunk();
        chunk.setChunkIndex(chunkIndex);
        chunk.setStartTimeMs(startTime);
        chunk.setEndTimeMs(endTime);
 
        Map<String, Object> summary = new LinkedHashMap<>();
        summary.put("stationCount", 0);
        summary.put("crnCount", 0);
        summary.put("dualCrnCount", 0);
        summary.put("rgvCount", 0);
        summary.put("abnormalCount", 0);
        summary.put("errorCount", 0);
        summary.put("blockCount", 0);
        summary.put("estimatedSamples", intValue(chunkMeta.get("estimatedSamples")));
 
        Map<String, Object> frame = new LinkedHashMap<>();
        frame.put("timestamp", endTime > 0 ? endTime : startTime);
        frame.put("sampleSeq", sampleSeq > 0 ? sampleSeq : 0L);
        frame.put("abnormalList", new ArrayList<>());
        frame.put("summary", summary);
        appendFrame(chunk, frame);
        chunk.setFrameCount(chunk.getFrames().size());
        return chunk;
    }
 
    private ReplayChunk buildChunk(ReplaySessionContext session, Integer chunkIndex, boolean fullFrames) {
        String manifestSnapshotKey = session.getManifestSnapshotKey();
        Map<String, Object> chunkMeta = resolveTimelineChunk(session, chunkIndex);
        long startTime = numberValue(chunkMeta.get("startTimeMs"));
        long endTime = numberValue(chunkMeta.get("endTimeMs"));
 
        Map<String, Object> currentStateByStream = new LinkedHashMap<>();
        List<DeviceReplayState> eventList = new ArrayList<>();
        ChunkCheckpointSeed checkpointSeed = resolveCheckpointSeed(session, chunkIndex);
        boolean enableBaselineRecovery = fullFrames || checkpointSeed != null;
        if (checkpointSeed != null && checkpointSeed.stateByStream != null) {
            currentStateByStream.putAll(checkpointSeed.stateByStream);
        }
        long scanStartExclusiveTimeMs = checkpointSeed == null ? 0L : checkpointSeed.scanStartExclusiveTimeMs;
        boolean allowBaselineLookup = fullFrames && checkpointSeed == null;
 
        for (DeviceReplayManifest manifest : resolveChunkManifests(session, chunkIndex)) {
            StreamReplayScanResult scanResult = scanManifestRange(
                    manifest,
                    startTime,
                    endTime,
                    allowBaselineLookup,
                    scanStartExclusiveTimeMs);
            if (enableBaselineRecovery && scanResult.baselineState != null) {
                currentStateByStream.put(manifest.getStreamId(), scanResult.baselineState);
            }
            eventList.addAll(scanResult.eventList);
        }
        eventList.sort(Comparator
                .comparing(DeviceReplayState::getTimestamp, Comparator.nullsLast(Long::compareTo))
                .thenComparing(DeviceReplayState::getSampleSeq, Comparator.nullsLast(Long::compareTo))
                .thenComparing(DeviceReplayState::getType, Comparator.nullsLast(String::compareTo))
                .thenComparing(DeviceReplayState::getDeviceNo, Comparator.nullsLast(Integer::compareTo))
                .thenComparing(DeviceReplayState::getStationId, Comparator.nullsLast(Integer::compareTo)));
 
        ReplayChunk chunk = new ReplayChunk();
        chunk.setChunkIndex(chunkIndex);
        chunk.setStartTimeMs(startTime);
        chunk.setEndTimeMs(endTime);
 
        if (fullFrames && !currentStateByStream.isEmpty()) {
            Map<String, Object> baseState = replayNormalizer.buildFrame(startTime, 0L, currentStateByStream);
            chunk.setBaseState(baseState);
            appendFrame(chunk, baseState);
        }
 
        List<Integer> keptGroupIndexes = fullFrames ? null : resolveCompactGroupIndexes(eventList);
        int groupIndex = -1;
        int cursor = 0;
        while (cursor < eventList.size()) {
            groupIndex++;
            DeviceReplayState currentEvent = eventList.get(cursor);
            Long frameTime = currentEvent.getTimestamp();
            Long frameSeq = currentEvent.getSampleSeq();
            while (cursor < eventList.size()) {
                DeviceReplayState nextEvent = eventList.get(cursor);
                if (!equalsLong(frameTime, nextEvent.getTimestamp())
                        || !equalsLong(frameSeq, nextEvent.getSampleSeq())) {
                    break;
                }
                String streamId = buildStreamId(session.getDay(), nextEvent.getType(), nextEvent.getDeviceNo(), nextEvent.getStationId());
                currentStateByStream.put(streamId, nextEvent.getPayload());
                frameSeq = nextEvent.getSampleSeq();
                cursor++;
            }
            if (fullFrames || keptGroupIndexes.contains(groupIndex)) {
                Map<String, Object> frame = fullFrames
                        ? replayNormalizer.buildFrame(frameTime, frameSeq, currentStateByStream)
                        : replayNormalizer.buildCompactFrame(frameTime, frameSeq, currentStateByStream);
                appendFrame(chunk, frame);
            }
        }
 
        if (chunk.getFrames().isEmpty()) {
            Map<String, Object> emptyFrame = fullFrames
                    ? replayNormalizer.buildFrame(startTime, 0L, currentStateByStream)
                    : replayNormalizer.buildCompactFrame(startTime, 0L, currentStateByStream);
            appendFrame(chunk, emptyFrame);
        }
        if (fullFrames) {
            chunk.setFullFrames(new ArrayList<>(chunk.getFrames()));
            chunk.setFullFrameSummaryList(new ArrayList<>(chunk.getFrameSummaryList()));
            shrinkChunkFrames(chunk);
        }
        chunk.setFrameCount(chunk.getFrames().size());
        if (fullFrames && !currentStateByStream.isEmpty() && isSameManifestSnapshot(session, manifestSnapshotKey)) {
            cacheChunkCheckpoint(session, chunkIndex, currentStateByStream);
        }
        return chunk;
    }
 
    private ReplayChunk projectChunkForClient(ReplaySessionContext session, ReplayChunk sourceChunk) {
        ReplayChunk chunk = new ReplayChunk();
        chunk.setChunkIndex(sourceChunk.getChunkIndex());
        chunk.setStartTimeMs(clampTimestampToWindow(session, safeLong(sourceChunk.getStartTimeMs())));
        chunk.setEndTimeMs(clampTimestampToWindow(session, safeLong(sourceChunk.getEndTimeMs())));
        chunk.setBaseState(copyObjectForClient(sourceChunk.getBaseState()));
        copyVisibleFrames(sourceChunk, chunk);
        chunk.setFrameCount(chunk.getFrames().size());
        return chunk;
    }
 
    @SuppressWarnings("unchecked")
    private Map<String, Object> copyObjectForClient(Map<String, Object> sourceMap) {
        if (sourceMap == null) {
            return null;
        }
        return (Map<String, Object>) copyValueForClient(sourceMap);
    }
 
    @SuppressWarnings("unchecked")
    private Object copyValueForClient(Object sourceValue) {
        if (sourceValue instanceof Map<?, ?> sourceMap) {
            Map<String, Object> copiedMap = new LinkedHashMap<>();
            for (Map.Entry<?, ?> entry : sourceMap.entrySet()) {
                copiedMap.put(String.valueOf(entry.getKey()), copyValueForClient(entry.getValue()));
            }
            return copiedMap;
        }
        if (sourceValue instanceof List<?> sourceList) {
            List<Object> copiedList = new ArrayList<>(sourceList.size());
            for (Object item : sourceList) {
                copiedList.add(copyValueForClient(item));
            }
            return copiedList;
        }
        return sourceValue;
    }
 
    private void copyVisibleFrames(ReplayChunk sourceChunk, ReplayChunk targetChunk) {
        List<Map<String, Object>> sourceFrames = resolveFullFrameList(sourceChunk);
        List<ReplayFrameSummary> sourceSummaries = resolveFullFrameSummaryList(sourceChunk);
        long startTime = safeLong(targetChunk.getStartTimeMs());
        long endTime = safeLong(targetChunk.getEndTimeMs());
        for (int frameIndex = 0; frameIndex < sourceFrames.size(); frameIndex++) {
            Map<String, Object> frame = sourceFrames.get(frameIndex);
            long frameTime = numberValue(frame.get("timestamp"));
            if (frameTime < startTime || frameTime > endTime) {
                continue;
            }
            targetChunk.getFrames().add(copyObjectForClient(frame));
            ReplayFrameSummary summary = frameIndex < sourceSummaries.size() ? sourceSummaries.get(frameIndex) : null;
            targetChunk.getFrameSummaryList().add(copyFrameSummary(summary, targetChunk.getFrameSummaryList().size(), frameTime));
        }
    }
 
    private List<ReplayFrameSummary> resolveFullFrameSummaryList(ReplayChunk replayChunk) {
        if (replayChunk == null) {
            return new ArrayList<>();
        }
        if (replayChunk.getFullFrameSummaryList() != null && !replayChunk.getFullFrameSummaryList().isEmpty()) {
            return replayChunk.getFullFrameSummaryList();
        }
        return replayChunk.getFrameSummaryList();
    }
 
    private ReplayFrameSummary copyFrameSummary(ReplayFrameSummary sourceSummary, int frameIndex, long frameTime) {
        ReplayFrameSummary summary = new ReplayFrameSummary();
        summary.setFrameIndex(frameIndex);
        summary.setTimestamp(frameTime);
        summary.setAbnormalCount(sourceSummary == null ? 0 : sourceSummary.getAbnormalCount());
        summary.setErrorCount(sourceSummary == null ? 0 : sourceSummary.getErrorCount());
        summary.setBlockCount(sourceSummary == null ? 0 : sourceSummary.getBlockCount());
        summary.setManualCount(sourceSummary == null ? 0 : sourceSummary.getManualCount());
        return summary;
    }
 
    private List<Map<String, Object>> resolveFullFrameList(ReplayChunk replayChunk) {
        if (replayChunk == null) {
            return new ArrayList<>();
        }
        if (replayChunk.getFullFrames() != null && !replayChunk.getFullFrames().isEmpty()) {
            return replayChunk.getFullFrames();
        }
        return replayChunk.getFrames();
    }
 
    private void shrinkChunkFrames(ReplayChunk chunk) {
        if (chunk == null || chunk.getFrames() == null || chunk.getFrames().isEmpty()) {
            return;
        }
        int frameLimit = Math.max(16, safePositive(maxChunkFrames, 32));
        if (chunk.getFrames().size() <= frameLimit) {
            return;
        }
 
        LinkedHashSet<Integer> keptIndexes = new LinkedHashSet<>();
        keptIndexes.add(0);
        keptIndexes.add(chunk.getFrames().size() - 1);
 
        for (int index = 0; index < chunk.getFrameSummaryList().size(); index++) {
            ReplayFrameSummary frameSummary = chunk.getFrameSummaryList().get(index);
            if (frameSummary != null && safeSummaryActivity(frameSummary) > 0) {
                keptIndexes.add(index);
            }
        }
 
        int remainingSlots = Math.max(0, frameLimit - keptIndexes.size());
        if (remainingSlots > 0) {
            double step = (chunk.getFrames().size() - 1D) / Math.max(1D, remainingSlots);
            for (int slot = 1; slot <= remainingSlots; slot++) {
                int sampledIndex = (int) Math.round(slot * step);
                sampledIndex = Math.max(0, Math.min(chunk.getFrames().size() - 1, sampledIndex));
                keptIndexes.add(sampledIndex);
                if (keptIndexes.size() >= frameLimit) {
                    break;
                }
            }
        }
 
        List<Integer> orderedIndexes = new ArrayList<>(keptIndexes);
        orderedIndexes.sort(Integer::compareTo);
 
        List<Map<String, Object>> compactFrames = new ArrayList<>(orderedIndexes.size());
        List<ReplayFrameSummary> compactSummaryList = new ArrayList<>(orderedIndexes.size());
        for (int compactIndex = 0; compactIndex < orderedIndexes.size(); compactIndex++) {
            int originalIndex = orderedIndexes.get(compactIndex);
            compactFrames.add(chunk.getFrames().get(originalIndex));
            ReplayFrameSummary originalSummary = originalIndex < chunk.getFrameSummaryList().size()
                    ? chunk.getFrameSummaryList().get(originalIndex)
                    : null;
            if (originalSummary == null) {
                originalSummary = new ReplayFrameSummary();
            }
            ReplayFrameSummary compactSummary = new ReplayFrameSummary();
            compactSummary.setFrameIndex(compactIndex);
            compactSummary.setTimestamp(originalSummary.getTimestamp());
            compactSummary.setAbnormalCount(originalSummary.getAbnormalCount());
            compactSummary.setErrorCount(originalSummary.getErrorCount());
            compactSummary.setBlockCount(originalSummary.getBlockCount());
            compactSummary.setManualCount(originalSummary.getManualCount());
            compactSummaryList.add(compactSummary);
        }
        chunk.setFrames(compactFrames);
        chunk.setFrameSummaryList(compactSummaryList);
    }
 
    private List<Integer> resolveCompactGroupIndexes(List<DeviceReplayState> eventList) {
        List<Integer> keptIndexes = new ArrayList<>();
        if (eventList == null || eventList.isEmpty()) {
            return keptIndexes;
        }
        int groupCount = 0;
        int cursor = 0;
        while (cursor < eventList.size()) {
            DeviceReplayState currentEvent = eventList.get(cursor);
            Long frameTime = currentEvent.getTimestamp();
            Long frameSeq = currentEvent.getSampleSeq();
            while (cursor < eventList.size()) {
                DeviceReplayState nextEvent = eventList.get(cursor);
                if (!equalsLong(frameTime, nextEvent.getTimestamp())
                        || !equalsLong(frameSeq, nextEvent.getSampleSeq())) {
                    break;
                }
                cursor++;
            }
            groupCount++;
        }
        int compactFrameLimit = Math.max(8, safePositive(maxChunkFrames, 32));
        if (groupCount <= compactFrameLimit) {
            for (int index = 0; index < groupCount; index++) {
                keptIndexes.add(index);
            }
            return keptIndexes;
        }
        keptIndexes.add(0);
        keptIndexes.add(groupCount - 1);
        int remainingSlots = Math.max(0, compactFrameLimit - keptIndexes.size());
        double step = (groupCount - 1D) / Math.max(1D, remainingSlots);
        for (int slot = 1; slot <= remainingSlots; slot++) {
            int sampledIndex = (int) Math.round(slot * step);
            sampledIndex = Math.max(0, Math.min(groupCount - 1, sampledIndex));
            if (!keptIndexes.contains(sampledIndex)) {
                keptIndexes.add(sampledIndex);
            }
        }
        keptIndexes.sort(Integer::compareTo);
        return keptIndexes;
    }
 
    private int safeSummaryActivity(ReplayFrameSummary frameSummary) {
        if (frameSummary == null) {
            return 0;
        }
        return intValue(frameSummary.getAbnormalCount())
                + intValue(frameSummary.getErrorCount())
                + intValue(frameSummary.getBlockCount());
    }
 
    @Override
    public ReplaySeekResult seek(String sessionId, Long timestamp, Long sampleSeq) {
        ReplaySessionContext session = requireSession(sessionId);
        long requestTime = timestamp == null || timestamp <= 0 ? session.getStartTimeMs() : timestamp;
        rejectTimestampOutsideWindow(session, requestTime, "seek 目标时间不在当前回放窗口内");
        long requestSeq = sampleSeq == null || sampleSeq <= 0 ? 0L : sampleSeq;
        rejectSampleSeqOutsideWindow(session, requestSeq);
        int initialChunkIndex = resolveChunkIndex(session, requestTime, requestSeq);
        if (requestSeq <= 0) {
            ReplaySeekResult result = new ReplaySeekResult();
            result.setChunkIndex(initialChunkIndex);
            result.setFrameIndex(0);
            result.setRequestedTimestamp(requestTime);
            result.setResolvedTimestamp(requestTime);
            result.setRequestedSampleSeq(null);
            result.setResolvedSampleSeq(null);
            result.setDriftMs(0L);
            result.setResolvedFrame(null);
            return result;
        }
        ResolvedSeekFrame resolvedSeekFrame = findNearestSeekFrame(session, sessionId, initialChunkIndex, requestTime, requestSeq);
        int chunkIndex = resolvedSeekFrame == null ? initialChunkIndex : resolvedSeekFrame.chunkIndex;
        ReplayChunk chunk = resolvedSeekFrame == null ? loadFullChunk(session, chunkIndex) : resolvedSeekFrame.chunk;
        long resolvedTime = resolvedSeekFrame == null ? requestTime : numberValue(resolvedSeekFrame.frame.get("timestamp"));
        long resolvedSeq = resolvedSeekFrame == null ? requestSeq : numberValue(resolvedSeekFrame.frame.get("sampleSeq"));
        int displayFrameIndex = findNearestDisplayFrameIndex(chunk, resolvedTime);
        ReplaySeekResult result = new ReplaySeekResult();
        result.setChunkIndex(chunkIndex);
        result.setFrameIndex(displayFrameIndex);
        result.setRequestedTimestamp(requestTime);
        result.setResolvedTimestamp(resolvedTime);
        result.setRequestedSampleSeq(requestSeq > 0 ? requestSeq : null);
        result.setResolvedSampleSeq(resolvedSeq > 0 ? resolvedSeq : null);
        result.setDriftMs(requestSeq > 0
                ? Math.abs(resolvedSeq - requestSeq)
                : Math.abs(resolvedTime - requestTime));
        result.setResolvedFrame(resolvedSeekFrame == null ? null : resolvedSeekFrame.frame);
        return result;
    }
 
    private ResolvedSeekFrame findNearestSeekFrame(ReplaySessionContext session,
                                                   String sessionId,
                                                   int initialChunkIndex,
                                                   long requestTime,
                                                   long requestSeq) {
        ResolvedSeekFrame bestMatch = evaluateSeekChunk(session, initialChunkIndex, requestTime, requestSeq);
        long bestDrift = bestMatch == null ? Long.MAX_VALUE : bestMatch.drift;
        int maxSearchDistance = Math.min(session.getTimelineChunks().size(), 512);
 
        for (int distance = 1; distance < maxSearchDistance; distance++) {
            boolean checkedAny = false;
 
            int leftChunkIndex = initialChunkIndex - distance;
            if (leftChunkIndex >= 0) {
                long lowerBoundDrift = resolveChunkBoundaryDrift(session, leftChunkIndex, requestTime);
                if (lowerBoundDrift <= bestDrift) {
                    ResolvedSeekFrame leftMatch = evaluateSeekChunk(session, leftChunkIndex, requestTime, requestSeq);
                    bestMatch = chooseBetterSeekFrame(bestMatch, leftMatch);
                    bestDrift = bestMatch == null ? Long.MAX_VALUE : bestMatch.drift;
                    checkedAny = true;
                }
            }
 
            int rightChunkIndex = initialChunkIndex + distance;
            if (rightChunkIndex < session.getTimelineChunks().size()) {
                long lowerBoundDrift = resolveChunkBoundaryDrift(session, rightChunkIndex, requestTime);
                if (lowerBoundDrift <= bestDrift) {
                    ResolvedSeekFrame rightMatch = evaluateSeekChunk(session, rightChunkIndex, requestTime, requestSeq);
                    bestMatch = chooseBetterSeekFrame(bestMatch, rightMatch);
                    bestDrift = bestMatch == null ? Long.MAX_VALUE : bestMatch.drift;
                    checkedAny = true;
                }
            }
 
            if (!checkedAny && bestMatch != null) {
                break;
            }
        }
        return bestMatch;
    }
 
    private ResolvedSeekFrame evaluateSeekChunk(ReplaySessionContext session, int chunkIndex, long requestTime, long requestSeq) {
        if (chunkIndex < 0) {
            return null;
        }
        ReplayChunk chunk = loadFullChunk(session, chunkIndex);
        List<Map<String, Object>> seekFrames = chunk.getFullFrames() == null || chunk.getFullFrames().isEmpty()
                ? chunk.getFrames()
                : chunk.getFullFrames();
        if (seekFrames == null || seekFrames.isEmpty()) {
            return null;
        }
 
        Map<String, Object> bestFrame = null;
        long bestDrift = Long.MAX_VALUE;
        for (Map<String, Object> frame : seekFrames) {
            long drift = requestSeq > 0
                    ? Math.abs(numberValue(frame.get("sampleSeq")) - requestSeq)
                    : Math.abs(numberValue(frame.get("timestamp")) - requestTime);
            if (drift <= bestDrift) {
                bestDrift = drift;
                bestFrame = frame;
            }
        }
        if (bestFrame == null) {
            return null;
        }
 
        ResolvedSeekFrame resolvedSeekFrame = new ResolvedSeekFrame();
        resolvedSeekFrame.chunkIndex = chunkIndex;
        resolvedSeekFrame.chunk = chunk;
        resolvedSeekFrame.frame = bestFrame;
        resolvedSeekFrame.drift = bestDrift;
        return resolvedSeekFrame;
    }
 
    private ResolvedSeekFrame chooseBetterSeekFrame(ResolvedSeekFrame currentBest, ResolvedSeekFrame challenger) {
        if (challenger == null) {
            return currentBest;
        }
        if (currentBest == null || challenger.drift <= currentBest.drift) {
            return challenger;
        }
        return currentBest;
    }
 
    private long resolveChunkBoundaryDrift(ReplaySessionContext session, int chunkIndex, long requestTime) {
        Map<String, Object> chunkMeta = resolveTimelineChunk(session, chunkIndex);
        long chunkStartTime = numberValue(chunkMeta.get("startTimeMs"));
        long chunkEndTime = numberValue(chunkMeta.get("endTimeMs"));
        if (requestTime < chunkStartTime) {
            return chunkStartTime - requestTime;
        }
        if (requestTime > chunkEndTime) {
            return requestTime - chunkEndTime;
        }
        return 0L;
    }
 
    private int findNearestDisplayFrameIndex(ReplayChunk chunk, long resolvedTime) {
        List<Map<String, Object>> displayFrames = chunk.getFrames();
        if (displayFrames == null || displayFrames.isEmpty()) {
            return 0;
        }
        int matchedIndex = 0;
        long bestDrift = Long.MAX_VALUE;
        for (int index = 0; index < displayFrames.size(); index++) {
            Map<String, Object> frame = displayFrames.get(index);
            long drift = Math.abs(numberValue(frame.get("timestamp")) - resolvedTime);
            if (drift <= bestDrift) {
                bestDrift = drift;
                matchedIndex = index;
            }
        }
        return matchedIndex;
    }
 
    @Override
    public Map<String, Object> resolveDevice(String sessionId, String type, Integer deviceNo, Integer stationId, Long timestamp) {
        ReplaySessionContext session = requireSession(sessionId);
        DeviceReplayManifest manifest = resolveDeviceManifest(session, type, deviceNo, stationId);
        if (manifest == null) {
            throw new IllegalArgumentException("未找到对应设备的历史日志");
        }
        long targetTimestamp = timestamp == null || timestamp <= 0 ? session.getStartTimeMs() : timestamp;
        rejectTimestampOutsideWindow(session, targetTimestamp, "设备详情时间不在当前回放窗口内");
        Object resolvedState = resolveDeviceStateAt(manifest, targetTimestamp);
        if (resolvedState == null) {
            throw new IllegalArgumentException("当前时间没有该设备的历史详情");
        }
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("day", session.getDay());
        data.put("type", type);
        data.put("deviceNo", deviceNo);
        data.put("stationId", stationId);
        data.put("timestamp", targetTimestamp);
        data.put("detail", JSON.parseObject(JSON.toJSONString(resolvedState)));
        return data;
    }
 
    private DeviceReplayManifest resolveDeviceManifest(ReplaySessionContext session, String type, Integer deviceNo, Integer stationId) {
        String manifestKey = buildStreamId(session.getDay(), type, deviceNo, stationId);
        DeviceReplayManifest manifest = session.getManifestByStream().get(manifestKey);
        if (manifest != null) {
            return manifest;
        }
        if (!"Devp".equalsIgnoreCase(type) || stationId == null) {
            return null;
        }
        for (DeviceReplayManifest currentManifest : session.getManifestByStream().values()) {
            if (currentManifest == null) {
                continue;
            }
            if (!"Devp".equalsIgnoreCase(currentManifest.getType())) {
                continue;
            }
            if (stationId.equals(currentManifest.getStationId())) {
                return currentManifest;
            }
        }
        return null;
    }
 
    @Override
    public void closeSession(String sessionId) {
        if (sessionId != null) {
            sessions.remove(sessionId);
        }
    }
 
    @PreDestroy
    public void shutdownReplayWarmupExecutor() {
        replayWarmupExecutor.shutdownNow();
    }
 
    private TimelineChunkSnapshotData buildTimelineChunkSnapshot(List<DeviceReplayManifest> manifests,
                                                                 long windowStartTimeMs,
                                                                 long windowEndTimeMs) {
        List<ChunkWindowMeta> allChunkMetas = collectTimelineChunkMetas(manifests, windowStartTimeMs, windowEndTimeMs);
        if (allChunkMetas.isEmpty() || windowEndTimeMs < windowStartTimeMs) {
            return TimelineChunkSnapshotData.empty();
        }
 
        List<Map<String, Object>> chunks = new ArrayList<>();
        Map<Integer, List<String>> chunkStreamIdsByChunk = new LinkedHashMap<>();
 
        long maxWindowMs = safePositive(maxWindowMinutes, 240) * 60L * 1000L;
        long bucketWindowMs = safePositive(timelineBucketSeconds, 20) * 1000L;
        if (maxWindowMs > 0) {
            bucketWindowMs = Math.min(bucketWindowMs, maxWindowMs);
        }
        bucketWindowMs = Math.max(1_000L, bucketWindowMs);
 
        int chunkIndex = 0;
        for (long windowStart = windowStartTimeMs; windowStart <= windowEndTimeMs; windowStart += bucketWindowMs) {
            long windowEnd = Math.min(windowEndTimeMs, windowStart + bucketWindowMs - 1);
            int estimatedSamples = estimateWindowSamples(allChunkMetas, windowStart, windowEnd);
            int targetChunkSampleSize = Math.max(1, safePositive(chunkSampleSize, 400));
            int desiredSplitCount = Math.max(1, (int) Math.ceil(estimatedSamples / (double) targetChunkSampleSize));
            int splitCount = Math.min(128, desiredSplitCount);
            long windowDurationMs = Math.max(1L, windowEnd - windowStart + 1L);
            long splitDurationMs = Math.max(1L, (long) Math.ceil(windowDurationMs / (double) splitCount));
 
            for (int splitIndex = 0; splitIndex < splitCount; splitIndex++) {
                long splitStartTime = windowStart + splitIndex * splitDurationMs;
                if (splitStartTime > windowEnd) {
                    break;
                }
                long splitEndTime = Math.min(windowEnd, splitStartTime + splitDurationMs - 1L);
                int splitEstimatedSamples = estimateWindowSamples(allChunkMetas, splitStartTime, splitEndTime);
                long firstSampleSeq = resolveWindowFirstSampleSeq(allChunkMetas, splitStartTime, splitEndTime);
                long lastSampleSeq = resolveWindowLastSampleSeq(allChunkMetas, splitStartTime, splitEndTime);
                List<String> activeStreamIds = resolveWindowStreamIds(allChunkMetas, splitStartTime, splitEndTime);
                chunks.add(buildChunkMeta(
                        chunkIndex++,
                        splitStartTime,
                        splitEndTime,
                        splitEstimatedSamples,
                        firstSampleSeq,
                        lastSampleSeq));
                chunkStreamIdsByChunk.put(chunkIndex - 1, activeStreamIds);
            }
        }
        TimelineChunkSnapshotData snapshotData = new TimelineChunkSnapshotData();
        snapshotData.timelineChunks = Collections.unmodifiableList(new ArrayList<>(chunks));
        snapshotData.chunkStreamIdsByChunk = Collections.unmodifiableMap(new LinkedHashMap<>(chunkStreamIdsByChunk));
        return snapshotData;
    }
 
    private Map<String, DeviceReplayManifest> buildManifestSnapshot(List<DeviceReplayManifest> manifests) {
        Map<String, DeviceReplayManifest> manifestByStream = new LinkedHashMap<>();
        for (DeviceReplayManifest manifest : manifests) {
            manifestByStream.put(manifest.getStreamId(), manifest);
        }
        return Collections.unmodifiableMap(manifestByStream);
    }
 
    private int estimateWindowSamples(List<ChunkWindowMeta> chunkMetas, long windowStart, long windowEnd) {
        int estimatedSamples = 0;
        for (ChunkWindowMeta chunkWindowMeta : chunkMetas) {
            DeviceReplayChunkMeta chunkMeta = chunkWindowMeta.chunkMeta;
            long chunkStartTime = safeLong(chunkMeta.getFirstSampleTimeMs());
            long chunkEndTime = safeLong(chunkMeta.getLastSampleTimeMs());
            if (chunkEndTime < windowStart || chunkStartTime > windowEnd) {
                continue;
            }
            estimatedSamples += Math.max(1, chunkMeta.getSampleCount() == null ? 1 : chunkMeta.getSampleCount());
        }
        return estimatedSamples;
    }
 
    private StreamReplayScanResult scanManifestRange(DeviceReplayManifest manifest,
                                                    long startTime,
                                                    long endTime,
                                                    boolean allowBaselineLookup,
                                                    long scanStartExclusiveTimeMs) {
        StreamReplayScanResult result = new StreamReplayScanResult();
        List<DeviceReplayChunkMeta> candidates = new ArrayList<>();
        DeviceReplayChunkMeta baselineChunk = null;
        for (DeviceReplayChunkMeta chunkMeta : manifest.getChunks()) {
            long chunkStart = safeLong(chunkMeta.getFirstSampleTimeMs());
            long chunkEnd = safeLong(chunkMeta.getLastSampleTimeMs());
            if (allowBaselineLookup && chunkEnd < startTime) {
                baselineChunk = chunkMeta;
                continue;
            }
            if (chunkEnd <= scanStartExclusiveTimeMs) {
                continue;
            }
            if (chunkStart > endTime) {
                break;
            }
            candidates.add(chunkMeta);
        }
        if (allowBaselineLookup && baselineChunk != null) {
            candidates.add(0, baselineChunk);
        }
        for (DeviceReplayChunkMeta chunkMeta : candidates) {
            Path logPath = resolveLogPath(manifest, chunkMeta);
            if (!Files.exists(logPath)) {
                continue;
            }
            try (BufferedReader reader = Files.newBufferedReader(logPath, StandardCharsets.UTF_8)) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line == null || line.isBlank()) {
                        continue;
                    }
                    DeviceDataLog logItem;
                    try {
                        logItem = JSON.parseObject(line, DeviceDataLog.class);
                    } catch (Exception parseError) {
                        log.debug("跳过损坏的 replay 日志行, path={}", logPath, parseError);
                        continue;
                    }
                    if (logItem == null) {
                        continue;
                    }
                    long sampleTime = resolveSampleTime(logItem);
                    Object normalizedState = replayNormalizer.normalizeState(logItem);
                    if (normalizedState == null) {
                        continue;
                    }
                    if (allowBaselineLookup && sampleTime < startTime) {
                        result.baselineState = normalizedState;
                        continue;
                    }
                    if (sampleTime <= scanStartExclusiveTimeMs) {
                        continue;
                    }
                    if (sampleTime > endTime) {
                        break;
                    }
                    DeviceReplayState replayState = new DeviceReplayState();
                    replayState.setType(manifest.getType());
                    replayState.setDeviceNo(manifest.getDeviceNo());
                    replayState.setStationId(manifest.getStationId());
                    replayState.setTimestamp(sampleTime);
                    replayState.setSampleSeq(resolveSampleSeq(logItem));
                    replayState.setPayload(normalizedState);
                    result.eventList.add(replayState);
                }
            } catch (Exception e) {
                log.warn("读取 replay chunk 失败, path={}", logPath, e);
            }
        }
        return result;
    }
 
    private Object resolveDeviceStateAt(DeviceReplayManifest manifest, long targetTimestamp) {
        Object latestState = null;
        for (DeviceReplayChunkMeta chunkMeta : manifest.getChunks()) {
            long chunkStart = safeLong(chunkMeta.getFirstSampleTimeMs());
            if (chunkStart > targetTimestamp) {
                break;
            }
            Path logPath = resolveLogPath(manifest, chunkMeta);
            if (!Files.exists(logPath)) {
                continue;
            }
            try (BufferedReader reader = Files.newBufferedReader(logPath, StandardCharsets.UTF_8)) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line == null || line.isBlank()) {
                        continue;
                    }
                    DeviceDataLog logItem;
                    try {
                        logItem = JSON.parseObject(line, DeviceDataLog.class);
                    } catch (Exception parseError) {
                        log.debug("跳过损坏的回放设备详情日志行, path={}", logPath, parseError);
                        continue;
                    }
                    if (logItem == null) {
                        continue;
                    }
                    long sampleTime = resolveSampleTime(logItem);
                    if (sampleTime > targetTimestamp) {
                        return latestState;
                    }
                    Object normalizedState = replayNormalizer.normalizeState(logItem);
                    if (normalizedState != null) {
                        latestState = normalizedState;
                    }
                }
            } catch (Exception e) {
                log.warn("读取回放设备详情失败, path={}", logPath, e);
            }
        }
        return latestState;
    }
 
    private ChunkCheckpointSeed resolveCheckpointSeed(ReplaySessionContext session, Integer chunkIndex) {
        if (session == null || chunkIndex == null || chunkIndex <= 0) {
            return null;
        }
        ChunkCheckpointSeed hotCheckpoint = resolveCheckpointSeed(session.getChunkStateCheckpointCache(), session, chunkIndex);
        if (hotCheckpoint != null) {
            return hotCheckpoint;
        }
        return resolveCheckpointSeed(session.getSparseChunkStateCheckpointCache(), session, chunkIndex);
    }
 
    private ChunkCheckpointSeed resolveCheckpointSeed(Map<Integer, Map<String, Object>> checkpointCache,
                                                      ReplaySessionContext session,
                                                      Integer chunkIndex) {
        synchronized (checkpointCache) {
            for (int checkpointChunkIndex = chunkIndex - 1; checkpointChunkIndex >= 0; checkpointChunkIndex--) {
                Map<String, Object> checkpointState = checkpointCache.get(checkpointChunkIndex);
                if (checkpointState == null || checkpointState.isEmpty()) {
                    continue;
                }
                Map<String, Object> checkpointChunkMeta = resolveTimelineChunk(session, checkpointChunkIndex);
                ChunkCheckpointSeed checkpointSeed = new ChunkCheckpointSeed();
                checkpointSeed.chunkIndex = checkpointChunkIndex;
                checkpointSeed.scanStartExclusiveTimeMs = numberValue(checkpointChunkMeta.get("endTimeMs"));
                checkpointSeed.stateByStream = new LinkedHashMap<>(checkpointState);
                return checkpointSeed;
            }
        }
        return null;
    }
 
    private void appendFrame(ReplayChunk chunk, Map<String, Object> frame) {
        int frameIndex = chunk.getFrames().size();
        chunk.getFrames().add(frame);
        ReplayFrameSummary summary = new ReplayFrameSummary();
        summary.setFrameIndex(frameIndex);
        summary.setTimestamp(numberValue(frame.get("timestamp")));
        Map<String, Object> frameSummary = frame.get("summary") instanceof Map
                ? (Map<String, Object>) frame.get("summary")
                : new LinkedHashMap<>();
        summary.setAbnormalCount(intValue(frameSummary.get("abnormalCount")));
        summary.setErrorCount(intValue(frameSummary.get("errorCount")));
        summary.setBlockCount(intValue(frameSummary.get("blockCount")));
        summary.setManualCount(0);
        chunk.getFrameSummaryList().add(summary);
    }
 
    private Map<String, Object> resolveTimelineChunk(ReplaySessionContext session, Integer chunkIndex) {
        return resolveTimelineChunk(session.getTimelineChunks(), chunkIndex);
    }
 
    private Map<String, Object> resolveTimelineChunk(List<Map<String, Object>> timelineChunks, Integer chunkIndex) {
        if (chunkIndex == null || chunkIndex < 0 || chunkIndex >= timelineChunks.size()) {
            throw new IllegalArgumentException("回放分片不存在");
        }
        return timelineChunks.get(chunkIndex);
    }
 
    private int resolveChunkIndex(ReplaySessionContext session, long timestamp, long sampleSeq) {
        return resolveChunkIndex(session.getTimelineChunks(), timestamp, sampleSeq);
    }
 
    private int resolveChunkIndex(List<Map<String, Object>> timelineChunks, long timestamp, long sampleSeq) {
        if (sampleSeq > 0) {
            for (int i = 0; i < timelineChunks.size(); i++) {
                Map<String, Object> chunkMeta = timelineChunks.get(i);
                long firstSampleSeq = numberValue(chunkMeta.get("firstSampleSeq"));
                long lastSampleSeq = numberValue(chunkMeta.get("lastSampleSeq"));
                if (sampleSeq >= firstSampleSeq && sampleSeq <= lastSampleSeq) {
                    return i;
                }
            }
        }
        for (int i = 0; i < timelineChunks.size(); i++) {
            Map<String, Object> chunkMeta = timelineChunks.get(i);
            long startTime = numberValue(chunkMeta.get("startTimeMs"));
            long endTime = numberValue(chunkMeta.get("endTimeMs"));
            if (timestamp >= startTime && timestamp <= endTime) {
                return i;
            }
        }
        return Math.max(0, timelineChunks.size() - 1);
    }
 
    private int resolveSummaryBucketCount(ReplaySessionContext session, Integer bucketCount) {
        int totalChunkCount = session.getTimelineChunks().size();
        if (totalChunkCount <= 0) {
            return 0;
        }
        int defaultBucketCount = Math.min(totalChunkCount, 96);
        int safeBucketCount = bucketCount == null || bucketCount <= 0 ? defaultBucketCount : bucketCount;
        return Math.max(1, Math.min(totalChunkCount, safeBucketCount));
    }
 
    private Map<String, Object> buildChunkMeta(int chunkIndex,
                                               long startTimeMs,
                                               long endTimeMs,
                                               int estimatedSamples,
                                               long firstSampleSeq,
                                               long lastSampleSeq) {
        Map<String, Object> chunkMeta = new LinkedHashMap<>();
        chunkMeta.put("chunkIndex", chunkIndex);
        chunkMeta.put("startTimeMs", startTimeMs);
        chunkMeta.put("endTimeMs", endTimeMs);
        chunkMeta.put("estimatedSamples", estimatedSamples);
        chunkMeta.put("firstSampleSeq", firstSampleSeq);
        chunkMeta.put("lastSampleSeq", lastSampleSeq);
        return chunkMeta;
    }
 
    private long resolveWindowFirstSampleSeq(List<ChunkWindowMeta> chunkMetas, long windowStart, long windowEnd) {
        long firstSampleSeq = Long.MAX_VALUE;
        for (ChunkWindowMeta chunkWindowMeta : chunkMetas) {
            DeviceReplayChunkMeta chunkMeta = chunkWindowMeta.chunkMeta;
            long chunkStartTime = safeLong(chunkMeta.getFirstSampleTimeMs());
            long chunkEndTime = safeLong(chunkMeta.getLastSampleTimeMs());
            if (chunkEndTime < windowStart || chunkStartTime > windowEnd) {
                continue;
            }
            long candidate = safeLong(chunkMeta.getFirstSampleSeq());
            if (candidate > 0) {
                firstSampleSeq = Math.min(firstSampleSeq, candidate);
            }
        }
        return firstSampleSeq == Long.MAX_VALUE ? 0L : firstSampleSeq;
    }
 
    private long resolveWindowLastSampleSeq(List<ChunkWindowMeta> chunkMetas, long windowStart, long windowEnd) {
        long lastSampleSeq = 0L;
        for (ChunkWindowMeta chunkWindowMeta : chunkMetas) {
            DeviceReplayChunkMeta chunkMeta = chunkWindowMeta.chunkMeta;
            long chunkStartTime = safeLong(chunkMeta.getFirstSampleTimeMs());
            long chunkEndTime = safeLong(chunkMeta.getLastSampleTimeMs());
            if (chunkEndTime < windowStart || chunkStartTime > windowEnd) {
                continue;
            }
            lastSampleSeq = Math.max(lastSampleSeq, safeLong(chunkMeta.getLastSampleSeq()));
        }
        return lastSampleSeq;
    }
 
    private List<DeviceReplayManifest> resolveChunkManifests(ReplaySessionContext session, Integer chunkIndex) {
        if (session == null || chunkIndex == null) {
            return new ArrayList<>();
        }
        List<String> streamIds = session.getChunkStreamIdsByChunk().get(chunkIndex);
        if (streamIds == null) {
            return new ArrayList<>(session.getManifestByStream().values());
        }
        List<DeviceReplayManifest> manifests = new ArrayList<>(streamIds.size());
        for (String streamId : streamIds) {
            DeviceReplayManifest manifest = session.getManifestByStream().get(streamId);
            if (manifest != null) {
                manifests.add(manifest);
            }
        }
        return manifests;
    }
 
    private List<ChunkWindowMeta> collectTimelineChunkMetas(List<DeviceReplayManifest> manifests,
                                                            long windowStartTimeMs,
                                                            long windowEndTimeMs) {
        List<ChunkWindowMeta> chunkMetas = new ArrayList<>();
        for (DeviceReplayManifest manifest : manifests) {
            if (manifest == null || manifest.getChunks() == null || manifest.getChunks().isEmpty()) {
                continue;
            }
            for (DeviceReplayChunkMeta chunkMeta : manifest.getChunks()) {
                long chunkStartTime = safeLong(chunkMeta.getFirstSampleTimeMs());
                long chunkEndTime = safeLong(chunkMeta.getLastSampleTimeMs());
                if (chunkStartTime <= 0 || chunkEndTime < chunkStartTime) {
                    continue;
                }
                if (chunkEndTime < windowStartTimeMs || chunkStartTime > windowEndTimeMs) {
                    continue;
                }
                ChunkWindowMeta chunkWindowMeta = new ChunkWindowMeta();
                chunkWindowMeta.streamId = manifest.getStreamId();
                chunkWindowMeta.chunkMeta = chunkMeta;
                chunkMetas.add(chunkWindowMeta);
            }
        }
        return chunkMetas;
    }
 
    private List<String> resolveWindowStreamIds(List<ChunkWindowMeta> chunkMetas,
                                                long windowStartTimeMs,
                                                long windowEndTimeMs) {
        LinkedHashSet<String> streamIds = new LinkedHashSet<>();
        for (ChunkWindowMeta chunkWindowMeta : chunkMetas) {
            DeviceReplayChunkMeta chunkMeta = chunkWindowMeta.chunkMeta;
            long chunkStartTime = safeLong(chunkMeta.getFirstSampleTimeMs());
            long chunkEndTime = safeLong(chunkMeta.getLastSampleTimeMs());
            if (chunkEndTime < windowStartTimeMs || chunkStartTime > windowEndTimeMs) {
                continue;
            }
            streamIds.add(chunkWindowMeta.streamId);
        }
        return new ArrayList<>(streamIds);
    }
 
    private long clampTimestampToWindow(ReplaySessionContext session, long timestamp) {
        long windowStartTimeMs = safeLong(session.getWindowStartTimeMs());
        long windowEndTimeMs = safeLong(session.getWindowEndTimeMs());
        if (timestamp < windowStartTimeMs) {
            return windowStartTimeMs;
        }
        if (timestamp > windowEndTimeMs) {
            return windowEndTimeMs;
        }
        return timestamp;
    }
 
    private long clampTimestampToWindow(TimelineSummarySnapshot snapshot, long timestamp) {
        if (timestamp < snapshot.windowStartTimeMs) {
            return snapshot.windowStartTimeMs;
        }
        if (timestamp > snapshot.windowEndTimeMs) {
            return snapshot.windowEndTimeMs;
        }
        return timestamp;
    }
 
    private void rejectTimestampOutsideWindow(ReplaySessionContext session, long timestamp, String message) {
        long windowStartTimeMs = safeLong(session.getWindowStartTimeMs());
        long windowEndTimeMs = safeLong(session.getWindowEndTimeMs());
        if (timestamp < windowStartTimeMs || timestamp > windowEndTimeMs) {
            throwReplayWindowException(REPLAY_SEEK_OUT_OF_WINDOW, message);
        }
    }
 
    private void rejectSampleSeqOutsideWindow(ReplaySessionContext session, long sampleSeq) {
        if (sampleSeq <= 0) {
            return;
        }
        long firstWindowSampleSeq = Long.MAX_VALUE;
        long lastWindowSampleSeq = 0L;
        for (Map<String, Object> chunkMeta : session.getTimelineChunks()) {
            long firstSampleSeq = numberValue(chunkMeta.get("firstSampleSeq"));
            long lastSampleSeq = numberValue(chunkMeta.get("lastSampleSeq"));
            if (firstSampleSeq <= 0 || lastSampleSeq <= 0) {
                continue;
            }
            firstWindowSampleSeq = Math.min(firstWindowSampleSeq, firstSampleSeq);
            lastWindowSampleSeq = Math.max(lastWindowSampleSeq, lastSampleSeq);
        }
        if (firstWindowSampleSeq == Long.MAX_VALUE || lastWindowSampleSeq <= 0) {
            return;
        }
        if (sampleSeq < firstWindowSampleSeq || sampleSeq > lastWindowSampleSeq) {
            throwReplayWindowException(REPLAY_SEEK_OUT_OF_WINDOW, "seek 采样序号不在当前回放窗口内");
        }
    }
 
    private boolean isSameManifestSnapshot(ReplaySessionContext session, String manifestSnapshotKey) {
        if (session == null) {
            return false;
        }
        String currentManifestSnapshotKey = session.getManifestSnapshotKey();
        return manifestSnapshotKey == null
                ? currentManifestSnapshotKey == null
                : manifestSnapshotKey.equals(currentManifestSnapshotKey);
    }
 
    private ReplaySessionContext requireSession(String sessionId) {
        cleanupExpiredSessions();
        ReplaySessionContext session = sessions.get(sessionId);
        if (session == null) {
            throw new IllegalArgumentException("回放会话不存在或已过期");
        }
        session.setLastAccessAtMs(System.currentTimeMillis());
        refreshCurrentDaySessionIfNeeded(session);
        return session;
    }
 
    private void refreshCurrentDaySessionIfNeeded(ReplaySessionContext session) {
        if (session == null || !isCurrentReplayDay(session.getDay())) {
            return;
        }
        long now = System.currentTimeMillis();
        Long lastRefreshAtMs = session.getLastManifestRefreshAtMs();
        if (lastRefreshAtMs != null && (now - lastRefreshAtMs) < CURRENT_DAY_MANIFEST_REFRESH_INTERVAL_MS) {
            return;
        }
 
        String sessionDay = session.getDay();
        long windowStartTimeMs = safeLong(session.getWindowStartTimeMs());
        long windowEndTimeMs = safeLong(session.getWindowEndTimeMs());
        List<DeviceReplayManifest> manifests = loadSessionManifests(sessionDay, true, false);
        if (manifests.isEmpty()) {
            manifestService.scheduleDayManifestRefresh(sessionDay);
            synchronized (session) {
                long currentTime = System.currentTimeMillis();
                Long currentLastRefreshAtMs = session.getLastManifestRefreshAtMs();
                if (currentLastRefreshAtMs != null
                        && (currentTime - currentLastRefreshAtMs) < CURRENT_DAY_MANIFEST_REFRESH_INTERVAL_MS) {
                    return;
                }
                session.setLastManifestRefreshAtMs(currentTime);
            }
            return;
        }
 
        boolean manifestChanged;
        String manifestSnapshotKey = manifests.isEmpty() ? "" : buildManifestSnapshotKey(manifests);
        Map<String, DeviceReplayManifest> manifestByStream = manifests.isEmpty()
                ? Collections.emptyMap()
                : buildManifestSnapshot(manifests);
        TimelineChunkSnapshotData timelineSnapshot = manifests.isEmpty()
                ? TimelineChunkSnapshotData.empty()
                : buildTimelineChunkSnapshot(manifests, windowStartTimeMs, windowEndTimeMs);
        synchronized (session) {
            long currentTime = System.currentTimeMillis();
            Long currentLastRefreshAtMs = session.getLastManifestRefreshAtMs();
            if (currentLastRefreshAtMs != null
                    && (currentTime - currentLastRefreshAtMs) < CURRENT_DAY_MANIFEST_REFRESH_INTERVAL_MS) {
                return;
            }
            manifestChanged = !manifests.isEmpty() && !manifestSnapshotKey.equals(session.getManifestSnapshotKey());
            if (manifestChanged) {
                session.setManifestByStream(manifestByStream);
                session.setTimelineChunks(timelineSnapshot.timelineChunks);
                session.setChunkStreamIdsByChunk(timelineSnapshot.chunkStreamIdsByChunk);
                session.setStartTimeMs(windowStartTimeMs);
                session.setEndTimeMs(windowEndTimeMs);
                session.setManifestSnapshotKey(manifestSnapshotKey);
                session.setTailCheckpointWarmupScheduled(false);
                clearSessionCaches(session);
            }
            session.setLastManifestRefreshAtMs(currentTime);
        }
 
        manifestService.scheduleDayManifestRefresh(sessionDay);
        if (manifestChanged) {
            scheduleTailCheckpointWarmup(session.getSessionId());
        }
    }
 
    private List<DeviceReplayManifest> loadSessionManifests(String day,
                                                            boolean currentReplayDay,
                                                            boolean allowBuildIfMissing) {
        List<DeviceReplayManifest> manifests = manifestService.loadDayManifests(day, false);
        if (!manifests.isEmpty()) {
            return manifests;
        }
        if (allowBuildIfMissing) {
            return manifestService.loadDayManifests(day, true);
        }
        if (!currentReplayDay) {
            return manifests;
        }
        return manifests;
    }
 
    private void applyManifestSnapshot(ReplaySessionContext session,
                                       List<DeviceReplayManifest> manifests,
                                       String manifestSnapshotKey) {
        if (session == null || manifests == null || manifests.isEmpty()) {
            return;
        }
        long windowStartTimeMs = safeLong(session.getWindowStartTimeMs());
        long windowEndTimeMs = safeLong(session.getWindowEndTimeMs());
        Map<String, DeviceReplayManifest> manifestByStream = buildManifestSnapshot(manifests);
        TimelineChunkSnapshotData timelineSnapshot = buildTimelineChunkSnapshot(manifests, windowStartTimeMs, windowEndTimeMs);
        synchronized (session) {
            session.setManifestByStream(manifestByStream);
            session.setTimelineChunks(timelineSnapshot.timelineChunks);
            session.setChunkStreamIdsByChunk(timelineSnapshot.chunkStreamIdsByChunk);
            session.setStartTimeMs(windowStartTimeMs);
            session.setEndTimeMs(windowEndTimeMs);
            session.setManifestSnapshotKey(manifestSnapshotKey);
            session.setTailCheckpointWarmupScheduled(false);
            clearSessionCaches(session);
        }
    }
 
    private void clearSessionCaches(ReplaySessionContext session) {
        synchronized (session.getChunkCache()) {
            session.getChunkCache().clear();
        }
        synchronized (session.getCompactChunkCache()) {
            session.getCompactChunkCache().clear();
        }
        synchronized (session.getChunkStateCheckpointCache()) {
            session.getChunkStateCheckpointCache().clear();
        }
        synchronized (session.getSparseChunkStateCheckpointCache()) {
            session.getSparseChunkStateCheckpointCache().clear();
        }
        synchronized (session.getTimelineSummaryCache()) {
            session.getTimelineSummaryCache().clear();
        }
    }
 
    private ReplayChunk getCachedChunk(ReplaySessionContext session, Integer chunkIndex, boolean fullFrames) {
        if (session == null || chunkIndex == null) {
            return null;
        }
        Map<Integer, ReplayChunk> cache = fullFrames ? session.getChunkCache() : session.getCompactChunkCache();
        synchronized (cache) {
            return cache.get(chunkIndex);
        }
    }
 
    private void cacheChunk(ReplaySessionContext session, Integer chunkIndex, ReplayChunk chunk, boolean fullFrames) {
        if (session == null || chunkIndex == null || chunk == null) {
            return;
        }
        Map<Integer, ReplayChunk> cache = fullFrames ? session.getChunkCache() : session.getCompactChunkCache();
        int configuredMaxCacheSize = safePositive(maxChunkCacheEntries, 128);
        int minimumWarmCacheSize = Math.max(fullFrames ? 24 : 48, safePositive(maxPrefetchChunks, 3) + 8);
        int maxCacheSize = Math.max(minimumWarmCacheSize, configuredMaxCacheSize);
        synchronized (cache) {
            cache.remove(chunkIndex);
            cache.put(chunkIndex, chunk);
            while (cache.size() > maxCacheSize) {
                Integer eldestKey = cache.keySet().iterator().next();
                cache.remove(eldestKey);
            }
        }
    }
 
    private void cacheChunkCheckpoint(ReplaySessionContext session, Integer chunkIndex, Map<String, Object> currentStateByStream) {
        if (session == null || chunkIndex == null || currentStateByStream == null || currentStateByStream.isEmpty()) {
            return;
        }
        Map<Integer, Map<String, Object>> cache = session.getChunkStateCheckpointCache();
        int configuredMaxCacheSize = safePositive(maxChunkCacheEntries, 128);
        int maxCacheSize = Math.max(32, configuredMaxCacheSize);
        synchronized (cache) {
            cache.remove(chunkIndex);
            cache.put(chunkIndex, new LinkedHashMap<>(currentStateByStream));
            while (cache.size() > maxCacheSize) {
                Integer eldestKey = cache.keySet().iterator().next();
                cache.remove(eldestKey);
            }
        }
        Map<Integer, Map<String, Object>> sparseCache = session.getSparseChunkStateCheckpointCache();
        int sparseMaxCacheSize = Math.max(512, safePositive(maxChunkCacheEntries, 128) * 8);
        synchronized (sparseCache) {
            sparseCache.remove(chunkIndex);
            sparseCache.put(chunkIndex, new LinkedHashMap<>(currentStateByStream));
            while (sparseCache.size() > sparseMaxCacheSize) {
                Integer eldestKey = sparseCache.keySet().iterator().next();
                sparseCache.remove(eldestKey);
            }
        }
    }
 
    private boolean isCurrentReplayDay(String day) {
        if (day == null || day.isBlank()) {
            return false;
        }
        return day.equals(LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));
    }
 
    private ReplayWindow resolveReplayWindow(String day,
                                             Long targetTimestamp,
                                             Long windowStartTimeMs,
                                             Long windowEndTimeMs) {
        DayBoundary dayBoundary = resolveDayBoundary(day);
        boolean hasTargetTimestamp = targetTimestamp != null;
        boolean hasWindowStart = windowStartTimeMs != null;
        boolean hasWindowEnd = windowEndTimeMs != null;
 
        if (!hasTargetTimestamp && !hasWindowStart && !hasWindowEnd) {
            throwReplayWindowException(REPLAY_WINDOW_MISSING, "请选择历史回放目标时间或时间窗口");
        }
        if (hasWindowStart != hasWindowEnd) {
            throwReplayWindowException(REPLAY_WINDOW_INVALID, "历史回放时间窗口开始和结束时间必须同时传入");
        }
        if (hasWindowStart) {
            return validateExplicitReplayWindow(dayBoundary, windowStartTimeMs, windowEndTimeMs);
        }
        return resolveTargetReplayWindow(dayBoundary, targetTimestamp);
    }
 
    private DayBoundary resolveDayBoundary(String day) {
        try {
            LocalDate replayDay = LocalDate.parse(day, DateTimeFormatter.BASIC_ISO_DATE);
            long dayStartTimeMs = replayDay.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
            return new DayBoundary(dayStartTimeMs, dayStartTimeMs + DAY_END_OFFSET_MS);
        } catch (DateTimeParseException e) {
            throwReplayWindowException(REPLAY_WINDOW_INVALID, "历史回放日期格式无效");
            return null;
        }
    }
 
    private ReplayWindow validateExplicitReplayWindow(DayBoundary dayBoundary,
                                                      Long windowStartTimeMs,
                                                      Long windowEndTimeMs) {
        if (windowStartTimeMs >= windowEndTimeMs) {
            throwReplayWindowException(REPLAY_WINDOW_INVALID, "历史回放时间窗口开始时间必须早于结束时间");
        }
        if (!isWithinDay(dayBoundary, windowStartTimeMs) || !isWithinDay(dayBoundary, windowEndTimeMs)) {
            throwReplayWindowException(REPLAY_WINDOW_CROSS_DAY, "历史回放时间窗口不能跨自然日");
        }
        validateReplayWindowSize(windowStartTimeMs, windowEndTimeMs);
        return new ReplayWindow(windowStartTimeMs, windowEndTimeMs);
    }
 
    private ReplayWindow resolveTargetReplayWindow(DayBoundary dayBoundary, Long targetTimestamp) {
        if (!isWithinDay(dayBoundary, targetTimestamp)) {
            throwReplayWindowException(REPLAY_WINDOW_CROSS_DAY, "历史回放目标时间不在所选日期内");
        }
        long windowStartTimeMs = Math.max(dayBoundary.startTimeMs, targetTimestamp - DEFAULT_REPLAY_WINDOW_HALF_MS);
        long windowEndTimeMs = Math.min(dayBoundary.endTimeMs, targetTimestamp + DEFAULT_REPLAY_WINDOW_HALF_MS);
        if (windowStartTimeMs >= windowEndTimeMs) {
            throwReplayWindowException(REPLAY_WINDOW_INVALID, "历史回放时间窗口无效");
        }
        validateReplayWindowSize(windowStartTimeMs, windowEndTimeMs);
        return new ReplayWindow(windowStartTimeMs, windowEndTimeMs);
    }
 
    private boolean isWithinDay(DayBoundary dayBoundary, Long timestamp) {
        return dayBoundary != null
                && timestamp != null
                && timestamp >= dayBoundary.startTimeMs
                && timestamp <= dayBoundary.endTimeMs;
    }
 
    private void validateReplayWindowSize(long windowStartTimeMs, long windowEndTimeMs) {
        long maxWindowMs = safePositive(maxWindowMinutes, 240) * 60L * 1000L;
        if ((windowEndTimeMs - windowStartTimeMs) > maxWindowMs) {
            throwReplayWindowException(REPLAY_WINDOW_TOO_LARGE, "历史回放时间窗口超过最大允许范围");
        }
    }
 
    private void throwReplayWindowException(String errorCode, String message) {
        throw new DeviceLogReplayService.ReplayWindowException(errorCode, message);
    }
 
    private static class DayBoundary {
        private final long startTimeMs;
        private final long endTimeMs;
 
        private DayBoundary(long startTimeMs, long endTimeMs) {
            this.startTimeMs = startTimeMs;
            this.endTimeMs = endTimeMs;
        }
    }
 
    private static class ReplayWindow {
        private final long startTimeMs;
        private final long endTimeMs;
 
        private ReplayWindow(long startTimeMs, long endTimeMs) {
            this.startTimeMs = startTimeMs;
            this.endTimeMs = endTimeMs;
        }
    }
 
    private void scheduleTailCheckpointWarmup(String sessionId) {
        ReplaySessionContext session = sessions.get(sessionId);
        if (session == null) {
            return;
        }
        synchronized (session) {
            if (session.isTailCheckpointWarmupScheduled()) {
                return;
            }
            session.setTailCheckpointWarmupScheduled(true);
        }
        replayWarmupExecutor.submit(() -> warmupTailCheckpoints(sessionId));
    }
 
    private void warmupTailCheckpoints(String sessionId) {
        ReplaySessionContext session = sessions.get(sessionId);
        if (session == null || session.getTimelineChunks() == null || session.getTimelineChunks().isEmpty()) {
            return;
        }
        int chunkCount = session.getTimelineChunks().size();
        int warmupSpan = Math.min(chunkCount, 2048);
        int warmupStep = 32;
        int startChunkIndex = Math.max(0, chunkCount - warmupSpan);
        for (int chunkIndex = startChunkIndex; chunkIndex < chunkCount; chunkIndex += warmupStep) {
            if (!sessions.containsKey(sessionId)) {
                return;
            }
            try {
                loadFullChunk(session, chunkIndex);
            } catch (Exception e) {
                log.debug("预热 replay 尾部 checkpoint 失败, sessionId={}, chunkIndex={}", sessionId, chunkIndex, e);
            }
        }
    }
 
    private void cleanupExpiredSessions() {
        long ttlMs = safePositive(sessionTtlSeconds, 1800) * 1000L;
        long now = System.currentTimeMillis();
        for (Map.Entry<String, ReplaySessionContext> entry : sessions.entrySet()) {
            ReplaySessionContext session = entry.getValue();
            if (session == null || session.getLastAccessAtMs() == null || (now - session.getLastAccessAtMs()) > ttlMs) {
                sessions.remove(entry.getKey());
            }
        }
    }
 
    private void ensureFileMode() {
        if (!"file".equalsIgnoreCase(storageType)) {
            throw new IllegalStateException("当前仅支持 file 模式历史回放");
        }
    }
 
    private Path resolveLogPath(DeviceReplayManifest manifest, DeviceReplayChunkMeta chunkMeta) {
        return Paths.get(loggingPath, manifest.getDay(), chunkMeta.getRelativePath());
    }
 
    private long resolveSampleTime(DeviceDataLog logItem) {
        if (logItem.getSampleTimeMs() != null && logItem.getSampleTimeMs() > 0) {
            return logItem.getSampleTimeMs();
        }
        if (logItem.getCreateTime() != null) {
            return logItem.getCreateTime().getTime();
        }
        return 0L;
    }
 
    private long resolveSampleSeq(DeviceDataLog logItem) {
        if (logItem.getSampleSeq() != null && logItem.getSampleSeq() > 0) {
            return logItem.getSampleSeq();
        }
        return resolveSampleTime(logItem);
    }
 
    private long safeLong(Long value) {
        return value == null ? 0L : value;
    }
 
    private int safePositive(Integer value, int fallback) {
        return value == null || value <= 0 ? fallback : value;
    }
 
    private long numberValue(Object value) {
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        if (value == null) {
            return 0L;
        }
        try {
            return Long.parseLong(String.valueOf(value));
        } catch (Exception e) {
            return 0L;
        }
    }
 
    private int intValue(Object value) {
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        if (value == null) {
            return 0;
        }
        try {
            return Integer.parseInt(String.valueOf(value));
        } catch (Exception e) {
            return 0;
        }
    }
 
    private String stringValue(Object value) {
        return value == null ? "" : String.valueOf(value);
    }
 
    private int resolveAbnormalPriority(String level) {
        if ("ERROR".equalsIgnoreCase(level)) {
            return 0;
        }
        if ("BLOCK".equalsIgnoreCase(level)) {
            return 1;
        }
        return 2;
    }
 
    private void warmupEntryManifest(String day, String type, Integer deviceNo, Integer stationId) {
        if (day == null || type == null || type.isBlank() || deviceNo == null) {
            return;
        }
        manifestService.loadManifest(DeviceReplayStreamKey.of(day, type, deviceNo, stationId), true);
    }
 
    private String buildManifestSnapshotKey(List<DeviceReplayManifest> manifests) {
        if (manifests == null || manifests.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (DeviceReplayManifest manifest : manifests) {
            if (manifest == null) {
                continue;
            }
            builder.append(manifest.getStreamId())
                    .append('#')
                    .append(manifest.getChunks() == null ? 0 : manifest.getChunks().size())
                    .append('#')
                    .append(safeLong(manifest.getFirstSampleSeq()))
                    .append('#')
                    .append(safeLong(manifest.getLastSampleSeq()))
                    .append('#')
                    .append(safeLong(manifest.getFirstSampleTimeMs()))
                    .append('#')
                    .append(safeLong(manifest.getLastSampleTimeMs()))
                    .append(';');
        }
        return builder.toString();
    }
 
    private boolean equalsLong(Long left, Long right) {
        if (left == null) {
            return right == null;
        }
        return left.equals(right);
    }
 
    private String buildStreamId(String day, String type, Integer deviceNo, Integer stationId) {
        StringBuilder builder = new StringBuilder();
        if (day != null) {
            builder.append(day).append('|');
        }
        builder.append(type == null ? "" : type)
                .append('|')
                .append(deviceNo == null ? "" : deviceNo);
        if (stationId != null) {
            builder.append('|').append(stationId);
        }
        return builder.toString();
    }
 
    private static class StreamReplayScanResult {
        private Object baselineState;
        private List<DeviceReplayState> eventList = new ArrayList<>();
    }
 
    private static class TimelineSummarySnapshot {
        private String sessionId;
        private String day;
        private long startTimeMs;
        private long endTimeMs;
        private long windowStartTimeMs;
        private long windowEndTimeMs;
        private List<Map<String, Object>> timelineChunks = new ArrayList<>();
        private List<DeviceReplayManifest> manifests = new ArrayList<>();
    }
 
    private static class ChunkCheckpointSeed {
        private Integer chunkIndex;
        private long scanStartExclusiveTimeMs;
        private Map<String, Object> stateByStream;
    }
 
    private static class ChunkWindowMeta {
        private String streamId;
        private DeviceReplayChunkMeta chunkMeta;
    }
 
    private static class TimelineChunkSnapshotData {
        private List<Map<String, Object>> timelineChunks = Collections.emptyList();
        private Map<Integer, List<String>> chunkStreamIdsByChunk = Collections.emptyMap();
 
        private static TimelineChunkSnapshotData empty() {
            return new TimelineChunkSnapshotData();
        }
    }
 
    private static class ResolvedSeekFrame {
        private Integer chunkIndex;
        private ReplayChunk chunk;
        private Map<String, Object> frame;
        private long drift;
    }
}