rapid-structure-rs 1.0.0

Rust document-structure engine for PaddleOCR-family ONNX models: text detection/recognition (PP-OCRv6), table structure (SLANet-plus) and formula recognition (PP-FormulaNet) on Windows x64 via ONNX Runtime.
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
//! 文件身份键控的 SHA-256 校验缓存(**唯一**实现)。
//!
//! # 为什么需要一个缓存(根因)
//!
//! `ModelFileSpec::state_in`(`/api/models` 的逐文件状态)与三条域的模型加载路径
//! (经 [`VerifiedModel::verify`] 的文本 / 公式 / 表格会话)
//! 问的是**同一个问题**:"这个文件的内容是不是声明的那一份"。
//!
//! 1. 566 MB 的公式识别模型在**每次 `/api/models`**(页面每 8 s 轮询一次就绪状态)
//!    都被完整重读一遍——持续磁盘 I/O 与秒级延迟;
//! 2. 更重要的是,"报告的状态"与"加载时校验的文件"是两次独立的读盘:判定的不是
//!    同一份证据。
//!
//! 这里把这三次调用收口到**一个**进程级缓存上:键是文件的**身份**
//! (路径 + 体积 + mtime + 首尾各 64 KiB 的局部摘要),值是上一次真正算出来的 SHA-256。
//! 同一份身份只算一次,身份变了(文件被替换、被截断、被改写)就重新计算。因此:
//!
//! - 冷验证(第一次见到某个身份)真的读盘并哈希,成本如实记账([`VerificationStats`]);
//! - 命中只花一次 `stat` + 一次 128 KiB 局部读 + 一次内存比较,与文件大小无关;
//! - 每一次调用都能回答"**这一次**我到底算没算"([`VerificationOutcome::computed`]),
//!   以及"为什么算"([`VerificationOutcome::cause`]);
//! - 需要"忽略缓存、现在就读盘"时用 [`force_verify_file`](`--reverify-models` 与
//!   `POST /api/models/reverify` 的语义),它不留任何"其实还是命中"的余地。
//!
//! # 为什么是进程级而不是"传一个缓存句柄"
//!
//! 调用点分布在三处、其中两处在库的深层加载路径里,而 [`crate::api::FormulaPolicy`]
//! 是进 `OcrRequest` 的**可序列化协议类型**:把一个缓存句柄塞进协议类型会让它无法
//! 序列化,也会让"要不要校验"变成请求方可选的行为。进程级缓存让"同一进程看到的同一个
//! 文件只有一种结论"成为一个结构性事实,而不是各调用点各自记得传参。
//!
//! # 身份的第二半:首尾各 64 KiB 的局部摘要(B)
//!
//! `(size, mtime)` 单独作为身份有一个实测过代价的盲区:**同体积、同 mtime** 的内容替换
//! (`SetFileTime` 把时间戳写回原值,或在同一时间戳粒度内原地改写)不会被识别为"变了",
//! 缓存会继续返回旧摘要。加一次 **128 KiB** 的局部读(首 64 KiB + 尾 64 KiB,各算一次
//! SHA-256)把窗口收窄到:
//!
//! > **同体积、同 mtime,且首尾各 64 KiB 逐字节相同**的替换才不被发现。
//!
//! 这是**启发式收窄,不是安全边界**:能写这个文件的攻击者同样能把首尾保持原样
//! (把改动放在中间即可)。它降低的是"误把改过的文件当成没改"的概率,不是"防住能写文件的人"。
//!
//! ## 小于 128 KiB 的文件(首尾重叠,规则明确)
//!
//! 首块 = 前 `min(size, 64 KiB)` 字节,尾块 = 后 `min(size, 64 KiB)` 字节。因此:
//!
//! - `size <= 128 KiB` 时两个切片**重叠甚至重合**,局部摘要实际覆盖了**整个文件内容**
//!   (此时"首尾相同"就等于"内容相同",盲区对这类文件不存在);
//! - `size == 0` 时两块都退化为 64 字节的零哈希域分隔编码,规则仍然唯一确定。
//!
//! ## 成本
//!
//! 每个文件每次检查多读 128 KiB:对本项目的模型集(5 个文件、其中 566 MB 一个)是
//! 0.6 MiB 量级的顺序读,命中路径仍然是毫秒级;**完整重哈希只在局部摘要或
//! stat 身份变化时发生**,且这一次重哈希的原因是可见的([`ReverifyCause`])。
//!
//! # 如实的盲区(**必须与缓存一起被理解**)
//!
//! 局部摘要把盲区收窄成"同体积 + 同 mtime + 首尾 64 KiB 相同",但它**不是**安全边界:
//! 能写文件的人可以保留首尾、只改中间;`mtime` 不可得(文件系统不提供)时身份里是
//! `None`,这类文件之间的同体积替换同样落在盲区里。
//! 缓存**只**用来省掉重复的完整读取;它不改变任何一个调用点的判定语义。
//! 需要**确定性地**排除缓存影响时用 [`force_verify_file`]。
//!
//! ## "状态"是什么、不是什么(复审 P1/P2 定下的口径)
//!
//! 命中缓存时报告的是**上一次完整校验留下的那一份摘要**,外加一条"此后没有观察到身份
//! 变化"的证据。它是存在性 + 身份的高频结论,**不是当前磁盘内容的确定性证明**:
//! 落在上面盲区里的修改,缓存会继续报告旧摘要。任何把命中时的状态说成"已按磁盘当前
//! 内容核实"的表述都是越界的(本 crate 的 API 文档与 `/api/models` 的文档都按这条口径
//! 写)。要拿到确定性结论只有两条路:[`force_verify_file`](现在就读盘),或者让加载
//! 路径自己把完整摘要算出来 —— 见下一节。
//!
//! ## 加载期证伪:磁盘推翻了缓存时,不留一条陈旧的 `present`
//!
//! [`VerifiedModel::verify`] 是每条模型加载路径的必经出口,而它**本来就必须**读完全部字节
//! 才能绑定内容,于是它手上握着一条比身份更强的证据:这次读到的字节的完整摘要。摘要与
//! 缓存条目不符时那条缓存结论已被证伪,`verify` 会**删除**该条目(为什么删而不覆盖:见
//! `invalidate_if_falsified` 的说明)。效果:
//!
//! - 下一次 [`verify_file`] 必定回到冷验证,报告当前磁盘的真实摘要(收敛);
//! - 不匹配([`crate::error::RapidOcrError::HashMismatch`])也先作废再报错 —— 否则会留下
//!   "加载拒绝、状态仍报告 present"的分叉,那比盲区本身更容易误导运维;
//! - 没有期望摘要的凭证(`expected = None`)根本不计算摘要,因此没有证伪的证据,缓存
//!   原样保留(这条限制被钉成测试)。
//!
//! 它把"报告的状态与实际加载结果分叉"从**无限期**收窄到**至多到下一次加载**:文件只要真的
//! 被带可信摘要地加载过一次,陈旧结论就活不过那一次。它仍然不改变"命中不等于当前内容"——
//! 那只有冷验证能证明。
//!
//! 作废只管**状态**,不管**已建好的会话**:会话缓存(`ocr::pipeline`)同样按身份判定是否
//! 重建,所以同身份的中段替换不会把已存在的会话拆掉 —— 凭证的内容快照只在**新建会话**那一刻
//! 起作用。运行期要确实性地同时刷新"报告的状态"与"内存里的会话",仍只有
//! `POST /api/models/reverify`(清缓存 → 冷验证 → 重建引擎)那一条路。

use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Instant, SystemTime};

use sha2::{Digest, Sha256};

use crate::error::{RapidOcrError, Result};
use crate::model_store::sha256_file;

/// 局部摘要覆盖的文件头/尾长度(各 64 KiB;合起来 128 KiB)。
///
/// 它是"每次检查多读多少"的唯一旋钮:调大收窄盲区、调大也提高轮询成本。
/// 128 KiB 相对于本项目 5 个模型文件(含 566 MB 那个)是可以忽略的顺序读。
pub const PARTIAL_DIGEST_WINDOW_BYTES: u64 = 64 * 1024;

/// 局部摘要:文件的**首 64 KiB** 与**尾 64 KiB**各一次 SHA-256。
///
/// 与 [`FileIdentity`] 一起构成"命中还需要内容对上"的第二半判据。它**不是**内容摘要:
/// 中段没有任何一个字节进入这里(见模块文档的盲区一节)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartialDigest {
    size: u64,
    head: [u8; 32],
    tail: [u8; 32],
}

impl PartialDigest {
    /// 一次 `open` + 两次定位读(首 64 KiB、尾 64 KiB)。
    ///
    /// `size` 由调用方的 [`FileIdentity::of`] 提供,因此这里**不**再 `stat` 一次:
    /// 身份与局部摘要必须描述同一次观察到的文件。
    pub fn compute(path: &Path, size: u64) -> Result<Self> {
        let mut file = std::fs::File::open(path)?;
        let head = read_window(&mut file, 0, size)?;
        let tail_start = size.saturating_sub(PARTIAL_DIGEST_WINDOW_BYTES);
        let tail = read_window(&mut file, tail_start, size)?;
        Ok(Self {
            size,
            head: Sha256::digest(&head).into(),
            tail: Sha256::digest(&tail).into(),
        })
    }

    /// 文件体积(参与编码:两个不同体积、相同首尾内容各自有不同摘要)。
    pub fn size(&self) -> u64 {
        self.size
    }

    fn head(&self) -> &[u8; 32] {
        &self.head
    }

    fn tail(&self) -> &[u8; 32] {
        &self.tail
    }

    /// 日志/错误文案用的简述(体积 + 首尾摘要的前 16 位十六进制)。
    pub fn describe(&self) -> String {
        format!(
            "size={} B, head={}, tail={}",
            self.size,
            hex16(self.head()),
            hex16(self.tail())
        )
    }
}

/// 从 `offset` 起最多读 `PARTIAL_DIGEST_WINDOW_BYTES` 字节,且**不越过** `size`。
///
/// 显式限制在 `size` 内(而不是"读到 EOF"):`FileIdentity::of` 的 `size` 是这次观察
/// 到的体积,局部摘要必须描述同一个快照;文件在两次读之间被别的进程追加时,
/// 尾窗口不会因此带上新字节(那会让摘要描述一个从未存在过的文件)。
fn read_window(file: &mut std::fs::File, offset: u64, size: u64) -> Result<Vec<u8>> {
    if size == 0 || offset >= size {
        return Ok(Vec::new());
    }
    let wanted = (size - offset).min(PARTIAL_DIGEST_WINDOW_BYTES);
    file.seek(SeekFrom::Start(offset))?;
    let mut window = Vec::with_capacity(wanted as usize);
    file.take(wanted).read_to_end(&mut window)?;
    Ok(window)
}

/// 一个文件的**身份**:路径 + 体积 + mtime + 首尾各 64 KiB 的局部摘要。
///
/// 相等 = **没有观察到变化**,不等于"内容就是这次观察到的那份字节"。
///
/// 任何一项(路径、体积、mtime、首尾局部摘要)变化都会让身份不等,于是下一次校验重新读盘;
/// 这是它能做的全部事。它**不是内容完整性证明**(本模块文档把局部摘要登记为启发式):
/// 能写这个文件的人可以保留首尾、只改中段,并把体积与 mtime 写回原值,此时身份相等而内容
/// 已变。要把"被校验的"与"被使用的"钉成同一份字节必须走 [`VerifiedModel`],它持有校验时
/// 读入的字节快照,会话一律从那份快照打开。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileIdentity {
    path: PathBuf,
    size: u64,
    modified: Option<SystemTime>,
    /// 首尾各 64 KiB 的局部摘要。`size <= 128 KiB` 时它覆盖**整个内容**(见模块文档)。
    partial: PartialDigest,
}

impl FileIdentity {
    /// 读取当前身份(一次 `metadata` + 128 KiB 局部读,不做完整哈希)。
    pub fn of(path: &Path) -> Result<Self> {
        let metadata = std::fs::metadata(path)?;
        let size = metadata.len();
        Ok(Self {
            path: path.to_path_buf(),
            size,
            modified: metadata.modified().ok(),
            partial: PartialDigest::compute(path, size)?,
        })
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn size(&self) -> u64 {
        self.size
    }

    pub fn modified(&self) -> Option<SystemTime> {
        self.modified
    }

    /// 首尾 64 KiB 的局部摘要(见 [`PartialDigest`])。
    pub fn partial(&self) -> &PartialDigest {
        &self.partial
    }

    /// 日志/错误文案用的简述(不含绝对路径)。
    pub fn describe(&self) -> String {
        format!(
            "size={} B, mtime={}, {}",
            self.size,
            match self.modified {
                Some(value) => format!("{value:?}"),
                None => "<unavailable>".to_string(),
            },
            self.partial.describe()
        )
    }
}

/// **这一次**为什么重新计算了完整摘要(或为什么命中)。
///
/// 它是"为什么又读了一遍 566 MB"的唯一证据来源:运维从启动日志与
/// `POST /api/models/reverify` 的响应里直接读到它,而不是靠计数器差值猜。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReverifyCause {
    /// 缓存里没有这个身份(第一次见到这个文件,或路径此前没被校验过)。
    ///
    /// 除了"真的第一次",还有第二条到达这里的路:缓存条目被**加载期证伪**删除之后
    /// (见 [`VerifiedModel::verify`] 与模块文档的证伪一节)。因此 `first_sight` 的含义是
    /// "此刻没有可复用的结论",不必然是"这个文件此前没被读过"。
    FirstSight,
    /// 体积或 mtime 变了:文件被替换/改写,身份不再是同一个。
    StatChanged,
    /// **stat 身份完全相同**(体积 + mtime),但首尾 64 KiB 的局部摘要变了。
    ///
    /// 这正是"同体积、同 mtime 的内容替换"被局部摘要抓住的那一半:缓存必须作废并重算。
    ContentChanged,
    /// 命中:身份与局部摘要都与上一次真正验过的那一份相同,没有重新哈希。
    CacheHit,
}

impl ReverifyCause {
    /// 稳定的机器可读取值(进 `/api/models/reverify` 的响应与日志)。
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::FirstSight => "first_sight",
            Self::StatChanged => "stat_changed",
            Self::ContentChanged => "content_changed",
            Self::CacheHit => "cache_hit",
        }
    }

    /// 这一次是否真的读了整个文件并算了摘要。
    pub const fn computed(self) -> bool {
        !matches!(self, Self::CacheHit)
    }
}

/// 一次校验的结论。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerificationOutcome {
    /// 文件的 SHA-256(小写十六进制)。
    pub sha256: String,
    /// `true` = **这一次**真的读了盘并计算;`false` = 由身份键控的缓存直接回答。
    ///
    /// 这是"命中不重新哈希"的唯一证据来源:它是**单次调用**的属性,不受同一进程里
    /// 其它线程/其它测试的并发影响(进程级累计计数器做不到这一点)。
    pub computed: bool,
    /// 本次校验针对的文件身份(路径 + 体积 + mtime + 首尾 64 KiB 局部摘要)。
    pub identity: FileIdentity,
    /// 为什么会这样(`computed = cause.computed()`,两者由同一次判定同时给出)。
    pub cause: ReverifyCause,
}

/// 一条缓存记录。
#[derive(Debug, Clone)]
struct CachedDigest {
    size: u64,
    modified: Option<SystemTime>,
    /// 算这份摘要时文件的局部摘要:stat 相同但局部摘要不同 = 内容变了。
    partial: PartialDigest,
    sha256: String,
}

/// 校验缓存的成本账(`/api/models` 的 `verification` 块与测试的计数器)。
///
/// `cache_hits` / `cold_verifications` / `partial_mismatches` / `partial_reads` 是**累计**值
/// (进程启动以来):它们回答"这台机器到目前为止为校验花了多少次完整读盘、多少次局部读"。
/// 而"**这一次**算没算、为什么算"由 [`VerificationOutcome::computed`] /
/// [`VerificationOutcome::cause`] 回答。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VerificationStats {
    /// 真正读盘并计算完整 SHA-256 的次数(累计)。
    pub cold_verifications: u64,
    /// 由缓存直接回答的次数(累计;做了一次 `stat` + 一次 128 KiB 局部读)。
    pub cache_hits: u64,
    /// stat 身份相同、局部摘要不同的次数(累计)——"内容变了"被抓住的次数。
    pub partial_mismatches: u64,
    /// 局部摘要(首尾各 64 KiB)的读取次数(累计;每次校验恰好一次)。
    pub partial_reads: u64,
    /// 最近一次冷验证的耗时(微秒);还没有冷验证时为 `None`。
    pub last_cold_micros: Option<u64>,
    /// 最近一次冷验证读取的字节数。
    pub last_cold_bytes: u64,
    /// 缓存里当前的记录数。
    pub entries: usize,
}

impl VerificationStats {
    /// 最近一次冷验证的毫秒数(报告用;保留小数)。
    pub fn last_cold_ms(&self) -> Option<f64> {
        self.last_cold_micros.map(|micros| micros as f64 / 1000.0)
    }
}

fn cache() -> &'static Mutex<HashMap<PathBuf, CachedDigest>> {
    static CACHE: OnceLock<Mutex<HashMap<PathBuf, CachedDigest>>> = OnceLock::new();
    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

static COLD_VERIFICATIONS: AtomicU64 = AtomicU64::new(0);
static CACHE_HITS: AtomicU64 = AtomicU64::new(0);
static PARTIAL_MISMATCHES: AtomicU64 = AtomicU64::new(0);
static PARTIAL_READS: AtomicU64 = AtomicU64::new(0);
static LAST_COLD_MICROS: AtomicU64 = AtomicU64::new(0);
static LAST_COLD_BYTES: AtomicU64 = AtomicU64::new(0);
static HAVE_COLD: AtomicU64 = AtomicU64::new(0);

/// 文件的 SHA-256;**同一个身份只计算一次**。
///
/// 语义与 [`sha256_file`] 完全一致(同一个摘要、同一套 IO 错误),区别只是重复询问
/// 同一个身份时复用上一次的结果,并回答"这一次算没算、为什么算"。文件不存在/读不出来时
/// 返回错误,**不**缓存失败。
///
/// 命中需要**两个**条件同时成立:stat 身份(体积 + mtime)相同 **且** 首尾各 64 KiB 的
/// 局部摘要相同。stat 相同而局部摘要不同时会重新哈希,并如实留下
/// [`ReverifyCause::ContentChanged`](见 [`VerificationStats::partial_mismatches`])。
pub fn verify_file(path: &Path) -> Result<VerificationOutcome> {
    let identity = FileIdentity::of(path)?;
    return_with_cache(path, identity, false)
}

/// **冷验证**:忽略缓存,现在就读盘重算摘要(`--reverify-models` 与
/// `POST /api/models/reverify` 的语义)。
///
/// 与 [`verify_file`] 的区别只有一条:它**不**查缓存。命中的记录会被这次的新结论覆盖,
/// 因此它同时是"清掉这条记录的陈旧结论"的动作;没有任何调用点可以因此绕过哈希。
pub fn force_verify_file(path: &Path) -> Result<VerificationOutcome> {
    let identity = FileIdentity::of(path)?;
    return_with_cache(path, identity, true)
}

/// [`verify_file`] / [`force_verify_file`] 的唯一实现:
/// `force = false` 时先查缓存,`force = true` 时无条件重算。
fn return_with_cache(
    path: &Path,
    identity: FileIdentity,
    force: bool,
) -> Result<VerificationOutcome> {
    PARTIAL_READS.fetch_add(1, Ordering::Relaxed);
    if !force {
        match lookup(&identity) {
            Lookup::Hit(sha256) => {
                CACHE_HITS.fetch_add(1, Ordering::Relaxed);
                refresh_stat_identity(&identity);
                return Ok(VerificationOutcome {
                    sha256,
                    computed: false,
                    identity,
                    cause: ReverifyCause::CacheHit,
                });
            }
            Lookup::Miss(cause) => {
                if cause == ReverifyCause::ContentChanged {
                    PARTIAL_MISMATCHES.fetch_add(1, Ordering::Relaxed);
                }
                return hashed(path, identity, cause);
            }
        }
    }
    hashed(path, identity, ReverifyCause::FirstSight)
}

/// 真正读盘并记录成本账(冷验证的**唯一**出口)。
fn hashed(
    path: &Path,
    identity: FileIdentity,
    cause: ReverifyCause,
) -> Result<VerificationOutcome> {
    let started = Instant::now();
    let sha256 = sha256_file(path)?;
    let elapsed = started.elapsed();

    store(&identity, &sha256);
    COLD_VERIFICATIONS.fetch_add(1, Ordering::Relaxed);
    LAST_COLD_MICROS.store(
        u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX),
        Ordering::Relaxed,
    );
    LAST_COLD_BYTES.store(identity.size, Ordering::Relaxed);
    HAVE_COLD.store(1, Ordering::Relaxed);
    Ok(VerificationOutcome {
        sha256,
        computed: true,
        identity,
        cause,
    })
}

/// [`verify_file`] 的摘要部分(最常见的调用形状)。
pub fn sha256_file_cached(path: &Path) -> Result<String> {
    Ok(verify_file(path)?.sha256)
}

/// 期望摘要存在时校验它,返回实际摘要(供调用方继续使用)。
///
/// 不匹配是**可定位**错误 [`RapidOcrError::HashMismatch`](路径 + 期望 + 实际),
/// 绝不静默加载。
pub fn verify_sha256(path: &Path, expected: Option<&str>) -> Result<Option<String>> {
    let Some(expected) = expected else {
        return Ok(None);
    };
    let outcome = verify_file(path)?;
    if !outcome.sha256.eq_ignore_ascii_case(expected) {
        return Err(RapidOcrError::HashMismatch {
            path: path.to_path_buf(),
            expected: expected.to_string(),
            actual: outcome.sha256,
        });
    }
    Ok(Some(outcome.sha256))
}

/// 期望摘要的**键规范化**:只做 [`VerifiedModel::verify`] 实际接受的等价变换。
///
/// 存在的理由是"摘要进了缓存键就必须与判定同形"。会话缓存(`ocr::pipeline`)把调用方
/// 声明的期望摘要纳入键,于是"两个写法是否算同一个声明"必须与校验判定给出**同样**的答案:
///
/// - [`VerifiedModel::verify`] 用 `eq_ignore_ascii_case` 比较,所以**大小写**是唯一不影响
///   判定的差异,这里折叠它;
/// - 这里**不** trim、**不**去 `sha256-` 前缀、**不**做长度校验。那些写法在 verify 里
///   本来就会失败(失败也是"给出摘要即校验"的一部分);若把它们折叠成同一个键,
///   第二个错误声明会因为命中缓存而**根本不参与比对** —— 那正是需要关闭的漏洞。
pub fn normalize_expected_sha256(expected: &str) -> String {
    expected.to_ascii_lowercase()
}

/// 模型文件的完整性**凭证**(P0-3 / I-3;审核点 1:内容绑定)。
///
/// 校验强度由“调用方是否持有可信摘要”决定,而不是由调用路径决定:任何模型文件进入
/// ONNX 会话之前都必须先经 [`VerifiedModel::verify`],于是“忘记校验”在结构上不成立。
///
/// # 凭证绑定的是**内容**,不是路径
///
/// 凭证把校验那一刻读到的全部字节存为快照([`Self::content`]),会话必须用
/// [`crate::runtime::session::OrtSession::open_verified`] 从这份字节打开 ——
/// “被校验的”与“被交给 ONNX Runtime 的”因此是同一份字节。如果会话仍然按路径二次开卷,
/// 校验与打开之间文件被替换时,凭证证明的是旧内容而会话加载的是新内容(TOCTOU);
/// 快照绑定把这扇时间窗从设计上关死。
///
/// # 与读盘缓存的关系(如实)
///
/// [`verify_file`] 的“同一身份只哈希一次”缓存不适用于凭证路径:凭证**本来就必须**读完
/// 全部字节才能绑定内容,读都读了,不重算摘要才是说谎。代价是每次构造凭证一次全量读 +
/// 一次哈希(每会话构造至多一次);换来的是摘要结论与内容快照出自同一次读取,
/// 而不是两次可能不一致的观察。
///
/// 反方向同样有动作(复审 P1/P2):凭证算出的完整摘要与缓存条目不符时,那条结论已被
/// **磁盘上的当前内容证伪**,于是该条目被删除(包括比对失败、凭证根本没有被构造成的那条
/// 错误路径)。凭证因此不只是“加载前的门禁”,也是状态缓存的**收敛信号**:一条被盲区修改
/// 骗过的 `present` 活不过一次带可信摘要的加载。没带可信摘要时(`expected = None`)
/// 不算摘要、也就没有证据,缓存原样保留 —— 这种凭证本来也不得声称内容已被验证。
#[derive(Clone)]
pub struct VerifiedModel {
    path: PathBuf,
    /// 期望摘要:来自清单 / 模型集 / CLI 的部署声明;`None` = 没有可信期望。
    expected_sha256: Option<String>,
    /// 实际摘要:对内容快照计算的结果;`None` = 未校验(无期望)。
    actual_sha256: Option<String>,
    /// 校验那一刻的文件内容快照。会话从这份字节打开,而不是重新按 [`Self::path`] 开卷。
    content: Arc<[u8]>,
}

/// `content` 是模型体积量级的字节,**绝不**进 `Debug`(否则 566 MB 的公式模型会把一次
/// 调试输出变成一场灾难);只报告长度,足以定位“哪一份文件、多大”。
impl core::fmt::Debug for VerifiedModel {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("VerifiedModel")
            .field("path", &self.path)
            .field("expected_sha256", &self.expected_sha256)
            .field("actual_sha256", &self.actual_sha256)
            .field("content_bytes", &self.content.len())
            .finish()
    }
}

impl VerifiedModel {
    /// 唯一的构造入口:**任何模型文件进入 ONNX 会话之前都经过它**。
    ///
    /// - `expected = Some(_)`:对**内存快照**计算摘要并与期望比对,不匹配返回可定位的
    ///   [`RapidOcrError::HashMismatch`](路径 + 期望 + 实际),凭证**不会**被构造出来,
    ///   因此会话也不会被创建。
    /// - `expected = None`:调用方没有可信摘要——**不报错**,但如实记录为“未校验”
    ///   ([`Self::is_verified`] 返回 `false`)。注意这只豁免**摘要比对**:存在性照查、
    ///   内容照绑定,“文件内容已被验证完整性”**不是**这种凭证可以说出口的话。
    ///
    /// 无论有没有期望,**存在性都是第一个判定**:缺失的文件必须先返回可定位的
    /// [`RapidOcrError::FileNotFound`],不能因为“摘要也算不出来”而退化成一个含混错误。
    /// 这条不变量此前分散在各域构造器里,现在单点收口到凭证。
    ///
    /// 只要算了完整摘要(= 期望在场),结论都会反哺状态缓存:与缓存条目不符就删除它,
    /// **匹配与不匹配两条分支都如此**(不匹配时先作废、再报错)。否则同一次磁盘修改会
    /// 一边让加载拒绝、一边让 `/api/models` 继续拿着旧摘要回答 `present`(复审 P1/P2)。
    pub fn verify(path: &Path, expected: Option<&str>) -> Result<Self> {
        if !path.is_file() {
            return Err(RapidOcrError::FileNotFound(path.to_path_buf()));
        }
        // 先读**全部**内容再做任何判定:哈希与加载必须消费同一份字节,
        // “先哈希、后按路径二次开卷”会把校验与打开之间的替换留在盲区里。
        let content: Arc<[u8]> = std::fs::read(path)?.into();
        let actual_sha256 = expected
            .map(|expected| {
                let actual = format!("{:x}", Sha256::digest(&content));
                // 这一次读取就是比“身份没变”更强的证据:它若与缓存里那条“上一次完整
                // 校验”的结论不符,那条已经错了。先作废再判定,使**比对失败的那一条
                // 请求也照样收敛状态**,不会留下“加载拒绝、状态仍是 present”的分叉。
                invalidate_if_falsified(path, &actual);
                if !actual.eq_ignore_ascii_case(expected) {
                    return Err(RapidOcrError::HashMismatch {
                        path: path.to_path_buf(),
                        expected: expected.to_string(),
                        actual,
                    });
                }
                Ok(actual)
            })
            .transpose()?;
        Ok(Self {
            path: path.to_path_buf(),
            expected_sha256: expected.map(|value| value.to_string()),
            actual_sha256,
            content,
        })
    }

    /// 凭证指向的模型文件路径(诊断与报告用;**加载路径不经过它**,见 [`Self::content`])。
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// 校验那一刻绑定的模型内容。会话构造器必须把这份字节交给 ONNX Runtime,
    /// 而不是重新打开 [`Self::path`] —— 这是“校验对象 = 加载对象”的唯一保证。
    pub fn content(&self) -> &[u8] {
        &self.content
    }

    pub(crate) fn content_arc(&self) -> Arc<[u8]> {
        Arc::clone(&self.content)
    }

    /// 部署声明的期望摘要;`None` = 调用方没有可信期望。
    pub fn expected_sha256(&self) -> Option<&str> {
        self.expected_sha256.as_deref()
    }

    /// 校验通过时算出的实际摘要;`None` = 未校验(无期望)。
    pub fn actual_sha256(&self) -> Option<&str> {
        self.actual_sha256.as_deref()
    }

    /// `true` = 实际摘要已对内容快照算出并与期望对上(即 `expected` 在场且匹配);
    /// `false` = 无期望,按“未校验”如实记录(存在性与内容绑定仍然成立)。
    pub fn is_verified(&self) -> bool {
        self.actual_sha256.is_some()
    }
}

/// “策略启用但缺 `model_path`”的**单点**文案(P0-3 / I-3)。
///
/// 四个调用点(`api.rs` 的 formula/table `validate`、`rapid_structure.rs` 的
/// formula/table 懒加载)此前各写各的,同一条件出现两条不同文案。它们必须给出
/// **逐字节相同**的错误,所以收口到这里;`domain` 取 `"formula"` / `"table"`。
pub(crate) fn missing_model_path_error(domain: &str) -> RapidOcrError {
    RapidOcrError::InvalidInput(format!(
        "{domain} policy requires `model_path` when enabled"
    ))
}

/// 当前成本账(累计)。
pub fn verification_stats() -> VerificationStats {
    let entries = cache().lock().map(|guard| guard.len()).unwrap_or_default();
    VerificationStats {
        cold_verifications: COLD_VERIFICATIONS.load(Ordering::Relaxed),
        cache_hits: CACHE_HITS.load(Ordering::Relaxed),
        partial_mismatches: PARTIAL_MISMATCHES.load(Ordering::Relaxed),
        partial_reads: PARTIAL_READS.load(Ordering::Relaxed),
        last_cold_micros: (HAVE_COLD.load(Ordering::Relaxed) == 1)
            .then(|| LAST_COLD_MICROS.load(Ordering::Relaxed)),
        last_cold_bytes: LAST_COLD_BYTES.load(Ordering::Relaxed),
        entries,
    }
}

/// 清空缓存与累计账(诊断与测试用)。
///
/// 生产路径里它的语义是"下一次校验必须重新读盘"(`POST /api/models/reverify` 的第一步);
/// 它本身不改变任何结论,只改变"要不要重新读盘"。
pub fn clear_verification_cache() {
    if let Ok(mut guard) = cache().lock() {
        guard.clear();
    }
    COLD_VERIFICATIONS.store(0, Ordering::Relaxed);
    CACHE_HITS.store(0, Ordering::Relaxed);
    PARTIAL_MISMATCHES.store(0, Ordering::Relaxed);
    PARTIAL_READS.store(0, Ordering::Relaxed);
    LAST_COLD_MICROS.store(0, Ordering::Relaxed);
    LAST_COLD_BYTES.store(0, Ordering::Relaxed);
    HAVE_COLD.store(0, Ordering::Relaxed);
}

/// 查缓存的结论:命中给摘要,未命中给**原因**(`FirstSight` / `StatChanged` /
/// `ContentChanged`)。
enum Lookup {
    Hit(String),
    Miss(ReverifyCause),
}

fn lookup(identity: &FileIdentity) -> Lookup {
    let Ok(guard) = cache().lock() else {
        return Lookup::Miss(ReverifyCause::FirstSight);
    };
    let Some(entry) = guard.get(&identity.path) else {
        return Lookup::Miss(ReverifyCause::FirstSight);
    };
    if entry.size != identity.size {
        // 体积变了:文件被整体换掉(旧摘要描述的是另一个长度的文件)。
        return Lookup::Miss(ReverifyCause::StatChanged);
    }
    if entry.partial != identity.partial {
        // **stat 身份相同而首尾 64 KiB 变了**:内容换了。这一条就是局部摘要的全部价值,
        // 也是"缓存不会拿旧摘要回答一个改过的文件"的证据(见模块文档的盲区一节)。
        // `mtime` 只是元数据(复制文件、`SetFileTime` 都能改它),因此它单独变化**不**算
        // 内容变化——那种情况是缓存命中,但下面会如实升级本地那份 stat 身份。
        return Lookup::Miss(ReverifyCause::ContentChanged);
    }
    Lookup::Hit(entry.sha256.clone())
}

/// 命中时把本地那份 stat 身份对齐到当前观察值。
///
/// 存在的理由:命中判据是 `(size, 首尾摘要)`,而 `mtime` 只是元数据。文件被**原样**
/// 复制(体积与内容都不变、mtime 变新)时命中是正确的结论,但如果不同步,下一次
/// stat 身份变化就会得到 [`ReverifyCause::StatChanged`] 这个**错误的原因**
/// (内容一个字节都没变)。这里用一次加锁把身份对齐,代价与一次比较同量级。
fn refresh_stat_identity(identity: &FileIdentity) {
    let Ok(mut guard) = cache().lock() else {
        return;
    };
    if let Some(entry) = guard.get_mut(&identity.path) {
        entry.size = identity.size;
        entry.modified = identity.modified;
    }
}

/// 写入缓存(哈希在锁外完成:一个 566 MB 的冷验证不允许挡住其它文件的查询)。
fn store(identity: &FileIdentity, sha256: &str) {
    let Ok(mut guard) = cache().lock() else {
        return;
    };
    guard.insert(
        identity.path.clone(),
        CachedDigest {
            size: identity.size,
            modified: identity.modified,
            partial: identity.partial.clone(),
            sha256: sha256.to_string(),
        },
    );
}

/// **证伪即作废**:本次完整摘要与缓存条目不符时删除该条目(返回是否真的删掉了一条)。
///
/// 只有 [`VerifiedModel::verify`] 有资格调用它:它手上的摘要来自刚刚读完的全部字节,
/// 强于“身份没观察到变化”,因此足以判定本地那一条结论是**错的**。冷验证走的是
/// [`store`](直接覆盖),不需要这里。
///
/// 为什么是删除而不是覆盖成这次的新摘要:这条路径上没有任何一次观察把“当前身份”与
/// “当前摘要”一起取过来 —— `verify` 读的是内容,它不取 [`FileIdentity`](取也只能是读盘
/// **之后**的另一个时刻)。用读前或读后的身份配上这次的摘要,会写进一条从未被一起观察过
/// 的记录:文件正被改写的中间状态也可能被钉成“已验证”。删除只放弃一次加速机会(下一次
/// 冷验证重新读盘),换来的是一条不会被误用的账。
///
/// 键就是 [`store`] 写入时用的那个路径值,不做规范化:两个写法不同的路径在缓存里本来就是
/// 两条独立记录(与命中规则一致),这里不去猜测它们是否指向同一个文件。
fn invalidate_if_falsified(path: &Path, actual_sha256: &str) -> bool {
    let Ok(mut guard) = cache().lock() else {
        return false;
    };
    let Some(entry) = guard.get(path) else {
        return false;
    };
    if entry.sha256.eq_ignore_ascii_case(actual_sha256) {
        // 磁盘现状与缓存结论一致:条目描述的就是当前内容,保留它(它省下的是下一次读盘)。
        return false;
    }
    guard.remove(path);
    true
}

/// 摘要前 8 字节的十六进制(日志用;完整摘要太长)。
fn hex16(bytes: &[u8; 32]) -> String {
    bytes[..8]
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// 测试专用的**观察**入口:直接问缓存"现在会命中吗、为什么"。
///
/// `verify_file` 的返回值已经带了 `cause`,但"不调用校验函数也能问出原因"这一点让
/// "`mtime` 变了但内容没变仍然命中(且不重新哈希)"这类断言不必依赖计数器
/// (进程级计数器会被同一进程里其它并行测试的校验干扰,见 `tests::serial` 的说明)。
#[cfg(test)]
fn lookup_for_test(path: &Path) -> std::result::Result<ReverifyCause, RapidOcrError> {
    let identity = FileIdentity::of(path)?;
    Ok(match lookup(&identity) {
        Lookup::Hit(_) => ReverifyCause::CacheHit,
        Lookup::Miss(cause) => cause,
    })
}

#[cfg(test)]
mod tests {
    use std::io::{Seek, SeekFrom, Write};
    use std::path::Path;

    use super::{
        FileIdentity, PARTIAL_DIGEST_WINDOW_BYTES, PartialDigest, ReverifyCause, VerifiedModel,
        clear_verification_cache, force_verify_file, invalidate_if_falsified, lookup_for_test,
        normalize_expected_sha256, sha256_file_cached, verification_stats, verify_file,
        verify_sha256,
    };
    use crate::error::RapidOcrError;
    use crate::model_store::sha256_file;
    use crate::test_support::TempDir;

    /// "hello" 的 SHA-256(与 `model_store`/`model_set` 的既有测试同值)。
    const HELLO_SHA256: &str = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";

    /// 这组用例共享**库级的单一缓存与累计账**(生产路径刻意如此:同一进程看到的同一个
    /// 文件只有一种结论),而 `cargo test` 默认并行跑测试。因此每个用例在自己的进程锁里
    /// 清一次账,让"这一轮算了几个摘要"这类断言不会被别的用例的校验计数污染。
    ///
    /// **只能锁一个**:`std::sync::Mutex` 不可重入,被锁住的用例里再调一次就自锁。
    fn serial() -> std::sync::MutexGuard<'static, ()> {
        static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
        clear_verification_cache();
        guard
    }

    /// 一个内容由 `(位置, 体积)` 唯一决定的字节串:任何位置被改写都会改变完整摘要。
    fn pattern(len: usize, tag: u8) -> Vec<u8> {
        (0..len)
            .map(|index| index.wrapping_mul(7).wrapping_add(tag as usize) as u8)
            .collect()
    }

    fn write(path: &Path, bytes: &[u8]) {
        std::fs::write(path, bytes).expect("write the fixture");
    }

    /// 改写 `[offset, offset + replacement.len())` 并把 mtime **写回原值**,
    /// 于是身份里的 `(size, mtime)` 完全不变——这正是局部摘要存在的理由。
    fn rewrite_same_identity(
        path: &Path,
        offset: usize,
        replacement: &[u8],
    ) -> std::time::SystemTime {
        let before = std::fs::metadata(path)
            .expect("metadata")
            .modified()
            .expect("mtime");
        {
            let mut file = std::fs::OpenOptions::new()
                .write(true)
                .open(path)
                .expect("open for rewrite");
            file.seek(SeekFrom::Start(offset as u64))
                .expect("seek to the edit");
            file.write_all(replacement).expect("rewrite in place");
            file.flush().expect("flush");
        }
        let file = std::fs::OpenOptions::new()
            .write(true)
            .open(path)
            .expect("open to restore the timestamp");
        file.set_modified(before).expect("write the old mtime back");
        drop(file);
        std::fs::metadata(path)
            .expect("metadata")
            .modified()
            .expect("mtime")
    }

    /// 第一次真的算,之后**同一个身份**只从缓存回答——证据是**单次调用**的
    /// `computed` 标志(进程级累计计数器会被并行测试干扰,因此不作为判据)。
    #[test]
    fn the_cached_digest_equals_the_uncached_one_and_is_only_computed_once() {
        let _serial = serial();
        let dir = TempDir::new("verify-once");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");

        let first = verify_file(&path).expect("hash");
        assert_eq!(first.sha256, HELLO_SHA256);
        assert_eq!(
            first.sha256,
            sha256_file(&path).expect("the uncached digest")
        );
        assert!(first.computed, "the first ask must hash");
        assert_eq!(first.cause, ReverifyCause::FirstSight);
        assert_eq!(first.identity.size(), 5);
        // 小文件:首尾窗口重叠,局部摘要覆盖整个内容。
        assert_eq!(first.identity.partial().size(), 5);

        for _ in 0..5 {
            let again = verify_file(&path).expect("hash");
            assert_eq!(again.sha256, HELLO_SHA256);
            assert!(
                !again.computed,
                "a cache hit must not re-hash (the per-call flag is the instrumentation)"
            );
            assert_eq!(again.cause, ReverifyCause::CacheHit);
            assert_eq!(again.identity, first.identity);
        }
        assert_eq!(sha256_file_cached(&path).expect("hash"), HELLO_SHA256);
    }

    /// 体积变化(内容替换的常见形态)→ 身份不等 → 重新哈希,原因是 `stat_changed`。
    #[test]
    fn a_size_change_forces_a_reverification() {
        let _serial = serial();
        let dir = TempDir::new("verify-size");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        assert!(verify_file(&path).expect("hash").computed);

        std::fs::write(&path, b"hello world").expect("replace with a longer body");
        let replaced = verify_file(&path).expect("hash");
        assert_eq!(replaced.sha256, sha256_file(&path).expect("uncached"));
        assert_ne!(replaced.sha256, HELLO_SHA256);
        assert!(replaced.computed, "a new identity must re-hash");
        assert_eq!(replaced.cause, ReverifyCause::StatChanged);
    }

    /// **同体积**但内容与 mtime 都变了 → 重新哈希,且上报的原因必须是**真实原因**。
    ///
    /// 这里刻意用一个 5 字节的文件:小于 128 KiB 时首尾窗口覆盖整个内容(见模块文档),
    /// 因此"内容变了"这一条会先于 stat 判据成立,上报 `content_changed`。
    /// mtime 变化本身**不**使身份失效(见
    /// [`an_mtime_only_change_still_hits_and_is_not_reported_as_a_content_change`]),
    /// 它只是解释"为什么这个文件值得重新看一眼"的元数据之一。
    #[test]
    fn a_mtime_change_forces_a_reverification() {
        let _serial = serial();
        let dir = TempDir::new("verify-mtime");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        let before = FileIdentity::of(&path).expect("identity");
        assert!(verify_file(&path).expect("hash").computed);

        // 同一个体积、不同内容,mtime 也随之前进。
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .open(&path)
            .expect("open for rewrite");
        file.write_all(b"HELLO").expect("rewrite the same length");
        file.set_modified(before.modified().expect("mtime") + std::time::Duration::from_secs(5))
            .expect("bump mtime");
        drop(file);

        let after = FileIdentity::of(&path).expect("identity");
        assert_eq!(after.size(), before.size(), "the size must be unchanged");
        assert_ne!(after, before, "the identity must differ");
        let digest = verify_file(&path).expect("hash");
        assert_eq!(digest.sha256, sha256_file(&path).expect("uncached"));
        assert!(digest.computed, "a changed identity must re-hash");
        assert_eq!(
            digest.cause,
            ReverifyCause::ContentChanged,
            "the content really changed, and that is the reason to report"
        );
    }

    #[test]
    fn a_mismatch_is_a_locating_error_and_a_match_passes_through() {
        let dir = TempDir::new("verify-mismatch");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");

        verify_sha256(&path, None).expect("no expectation is allowed and records as unverified");
        assert_eq!(
            verify_sha256(&path, Some(HELLO_SHA256)).expect("match"),
            Some(HELLO_SHA256.to_string())
        );
        let error = verify_sha256(&path, Some("deadbeef")).expect_err("a mismatch must fail");
        match error {
            RapidOcrError::HashMismatch {
                path: reported,
                expected,
                actual,
            } => {
                assert_eq!(reported, path);
                assert_eq!(expected, "deadbeef");
                assert_eq!(actual, HELLO_SHA256);
            }
            other => panic!("expected HashMismatch, got {other:?}"),
        }
    }

    /// 凭证正例:摘要一致 → `is_verified()`,且同时记下期望与实际。
    #[test]
    fn a_credential_matches_and_records_the_actual_digest() {
        let dir = TempDir::new("credential-match");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        let credential = VerifiedModel::verify(&path, Some(HELLO_SHA256)).expect("match");
        assert!(credential.is_verified());
        assert_eq!(credential.expected_sha256(), Some(HELLO_SHA256));
        assert_eq!(credential.actual_sha256(), Some(HELLO_SHA256));
        assert_eq!(credential.path(), path);
    }

    /// 凭证负例:不一致 → 可定位的 `HashMismatch`,**不返回凭证**(因而会话不会创建)。
    #[test]
    fn a_credential_mismatch_is_locating_and_yields_no_credential() {
        let dir = TempDir::new("credential-mismatch");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        let error = VerifiedModel::verify(&path, Some("deadbeef")).expect_err("mismatch must fail");
        match error {
            RapidOcrError::HashMismatch {
                path: reported,
                expected,
                actual,
            } => {
                assert_eq!(reported, path);
                assert_eq!(expected, "deadbeef");
                assert_eq!(actual, HELLO_SHA256);
            }
            other => panic!("expected HashMismatch, got {other:?}"),
        }
    }

    /// 无期望凭证:**允许构造**,但如实记录为“未校验”(`is_verified() == false`)。
    #[test]
    fn a_credential_without_an_expectation_is_recorded_as_unverified() {
        let dir = TempDir::new("credential-unverified");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        let credential = VerifiedModel::verify(&path, None).expect("no expectation is allowed");
        assert!(
            !credential.is_verified(),
            "no expectation => recorded as unverified"
        );
        assert_eq!(credential.expected_sha256(), None);
        assert_eq!(credential.actual_sha256(), None);
        assert_eq!(credential.path(), path);
        // 无期望也不豁免内容绑定:会话仍从这份快照打开,“加载的就是读到的”。
        assert_eq!(credential.content(), b"hello");
    }

    /// 键规范化与校验判定**同形**(复审 P1-1 的支撑单点):只折叠 verify 本来接受的差异。
    ///
    /// 会话缓存把声明摘要并入键,于是“两个写法算不算同一个声明”必须与校验给出同样的答案:
    /// 大小写折叠后的写法仍能被 `verify` 接受(不折叠也不会误拒),而带空白的写法在 `verify`
    /// 里是**另一个判定**(失败),因此必须留在键里当成另一个声明,而不是被 trim 掉。
    #[test]
    fn the_key_normalization_only_folds_what_verification_accepts() {
        assert_eq!(normalize_expected_sha256(HELLO_SHA256), HELLO_SHA256);
        let upper = HELLO_SHA256.to_uppercase();
        assert_ne!(upper, HELLO_SHA256, "the two spellings differ in case");
        assert_eq!(normalize_expected_sha256(&upper), HELLO_SHA256);

        let dir = TempDir::new("normalize-credential");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        let normalized = normalize_expected_sha256(&upper);
        VerifiedModel::verify(&path, Some(&normalized))
            .expect("the normalized spelling must still verify");

        let padded = format!(" {HELLO_SHA256}");
        assert_ne!(
            normalize_expected_sha256(HELLO_SHA256),
            normalize_expected_sha256(&padded),
            "a padded declaration must not fold onto the clean one"
        );
        let error = VerifiedModel::verify(&path, Some(&padded))
            .expect_err("a padded declaration is a different, failing expectation");
        assert!(
            matches!(error, RapidOcrError::HashMismatch { .. }),
            "{error}"
        );
    }

    /// 凭证绑定的是**校验那一刻的内容**(审核点 1 的回归守卫):构造之后文件被替换,
    /// 凭证携带的字节不变;而重新走一次凭证构造必须被摘要不匹配拦住。两者合起来说明
    /// “校验对象 = 加载对象”不依赖路径的稳定性。
    #[test]
    fn the_credential_snapshots_the_content_it_verified() {
        let dir = TempDir::new("credential-snapshot");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        let credential = VerifiedModel::verify(&path, Some(HELLO_SHA256)).expect("match");
        assert_eq!(credential.content(), b"hello");

        std::fs::write(&path, b"totally different bytes").expect("replace after construction");
        assert_eq!(
            credential.content(),
            b"hello",
            "the bound content must be the bytes that were verified, not whatever the path holds now"
        );

        let error = VerifiedModel::verify(&path, Some(HELLO_SHA256))
            .expect_err("a re-verification after replacement must refuse");
        assert!(
            matches!(error, RapidOcrError::HashMismatch { .. }),
            "{error}"
        );
    }

    /// 存在性优先:即使带期望摘要,缺失的文件也必须先返回 `FileNotFound`(而不是
    /// “算不出摘要”的含混错误)——这是会话构造器不再各自检查 `is_file` 后、
    /// 由凭证统一保住的不变量。
    #[test]
    fn a_missing_file_is_file_not_found_even_with_an_expectation() {
        let dir = TempDir::new("credential-missing");
        let path = dir.path().join("no_such_model.onnx");
        for expected in [None, Some(HELLO_SHA256)] {
            let error = VerifiedModel::verify(&path, expected)
                .expect_err("a missing file must fail regardless of the expectation");
            assert!(
                matches!(error, RapidOcrError::FileNotFound(_)),
                "expected FileNotFound, got {error}"
            );
        }
    }

    /// 文案单点:四个调用点中两个“启用但缺路径”的校验入口,必须与
    /// `missing_model_path_error` 给出逐字节相同的错误。
    #[test]
    fn the_missing_model_path_message_is_a_single_point() {
        use super::missing_model_path_error;
        use crate::api::{FormulaPolicy, TablePolicy};

        let formula = FormulaPolicy {
            enabled: true,
            model_path: None,
            ..Default::default()
        };
        assert_eq!(
            formula.validate().unwrap_err().to_string(),
            missing_model_path_error("formula").to_string(),
        );

        let table = TablePolicy {
            enabled: true,
            model_path: None,
            ..Default::default()
        };
        assert_eq!(
            table.validate().unwrap_err().to_string(),
            missing_model_path_error("table").to_string(),
        );
    }

    #[test]
    fn a_missing_file_is_an_error_and_is_not_cached() {
        let dir = TempDir::new("verify-missing");
        let path = dir.path().join("not-here.onnx");
        assert!(verify_file(&path).is_err());
        assert!(sha256_file_cached(&path).is_err());
        assert!(force_verify_file(&path).is_err());
        // 失败不进缓存:同一个路径被创建出来之后必须真的读它。
        dir.write("not-here.onnx", b"hello");
        let outcome = verify_file(&path).expect("hash after the file appears");
        assert_eq!(outcome.sha256, HELLO_SHA256);
        assert!(outcome.computed);
    }

    /// `clear_verification_cache` 只影响"要不要重新读盘",不影响任何结论。
    #[test]
    fn clearing_the_cache_only_costs_another_read() {
        let _serial = serial();
        let dir = TempDir::new("verify-clear");
        dir.write("model.onnx", b"hello");
        let path = dir.path().join("model.onnx");
        assert!(verify_file(&path).expect("hash").computed);
        clear_verification_cache();
        let after = verify_file(&path).expect("hash");
        assert_eq!(after.sha256, HELLO_SHA256);
        assert!(after.computed, "a cleared cache must re-read");
        let stats = verification_stats();
        assert!(stats.last_cold_ms().is_some());
        assert_eq!(stats.last_cold_bytes, 5);
    }

    /// **B 的核心用例(1a)**:同体积 + 同 mtime,只有**头部** 64 KiB 里的一个字节变了。
    ///
    /// 旧身份 `(path, size, mtime)` 对这个文件判"没变",缓存会返回旧摘要;局部摘要必须
    /// 抓住它,并给出 `content_changed` 这个原因。
    #[test]
    fn a_same_size_same_mtime_edit_in_the_head_is_detected_and_rehashed() {
        let _serial = serial();
        let dir = TempDir::new("verify-head-edit");
        let path = dir.path().join("model.onnx");
        let size = 256 * 1024;
        write(&path, &pattern(size, 1));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);
        let stale = first.sha256.clone();

        let _restored = rewrite_same_identity(&path, 4096, b"\xff\xff\xff\xff");
        let after = FileIdentity::of(&path).expect("identity");
        assert_eq!(after.size(), first.identity.size(), "the size is unchanged");
        assert_eq!(
            after.modified(),
            first.identity.modified(),
            "the mtime was written back: the stat identity is unchanged"
        );
        assert_ne!(
            after.partial(),
            first.identity.partial(),
            "the head window must notice the edit"
        );

        let second = verify_file(&path).expect("hash");
        assert!(second.computed, "the cache must be invalidated");
        assert_eq!(second.cause, ReverifyCause::ContentChanged);
        assert_ne!(second.sha256, stale, "the stale digest must not be reused");
        assert_eq!(
            second.sha256,
            sha256_file(&path).expect("uncached"),
            "the fresh digest must be the real one"
        );
    }

    /// **B 的核心用例(1b)**:同上,但改动落在**尾部** 64 KiB 里。
    #[test]
    fn a_same_size_same_mtime_edit_in_the_tail_is_detected_and_rehashed() {
        let _serial = serial();
        let dir = TempDir::new("verify-tail-edit");
        let path = dir.path().join("model.onnx");
        let size = 256 * 1024;
        write(&path, &pattern(size, 2));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);

        let restored = rewrite_same_identity(&path, size - 8192, b"\x00\x00\x00\x00");
        let after = FileIdentity::of(&path).expect("identity");
        assert_eq!(after.size(), first.identity.size());
        assert_eq!(
            after.modified(),
            first.identity.modified(),
            "the stat identity is unchanged"
        );
        assert_eq!(after.modified(), Some(restored));
        assert_ne!(
            after.partial(),
            first.identity.partial(),
            "the tail window must notice the edit"
        );

        let second = verify_file(&path).expect("hash");
        assert!(second.computed);
        assert_eq!(second.cause, ReverifyCause::ContentChanged);
        assert_eq!(second.sha256, sha256_file(&path).expect("uncached"));
    }

    /// **B 的核心用例(2)**:改动只落在**中段**(首尾 64 KiB 之外),同体积同 mtime。
    ///
    /// 这一条**刻意断言限制**:局部摘要是启发式,不是安全边界,也不是完整内容校验。
    /// 它被钉成测试(而不是只写在文档里),这样"把窗口当成保证"的改动会让它失败。
    #[test]
    fn a_same_size_same_mtime_edit_confined_to_the_middle_is_not_detected() {
        let _serial = serial();
        let dir = TempDir::new("verify-middle-edit");
        let path = dir.path().join("model.onnx");
        let size = 256 * 1024;
        write(&path, &pattern(size, 3));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);
        let stale = first.sha256.clone();

        // 中段:偏移 [64 KiB, size − 64 KiB) 之内。
        let offset = (PARTIAL_DIGEST_WINDOW_BYTES + 1024) as usize;
        rewrite_same_identity(&path, offset, b"\xaa\xbb\xcc\xdd");
        let after = FileIdentity::of(&path).expect("identity");
        assert_eq!(after.size(), first.identity.size());
        assert_eq!(after.modified(), first.identity.modified());
        assert_eq!(
            after.partial(),
            first.identity.partial(),
            "the head and tail windows are byte-identical by construction"
        );
        assert_ne!(
            sha256_file(&path).expect("uncached"),
            stale,
            "the file content really did change (the full digest differs)"
        );

        let second = verify_file(&path).expect("hash");
        assert!(
            !second.computed,
            "DOCUMENTED LIMITATION: a middle-only edit with an identical stat identity and \
             identical head/tail windows is deliberately not detected"
        );
        assert_eq!(second.cause, ReverifyCause::CacheHit);
        assert_eq!(
            second.sha256, stale,
            "the cache answers with the digest of the previous content: this is the narrowed \
             blind spot, not a bug"
        );

        // 确定性逃生口:强制冷验证必须给出真实摘要并纠正缓存。
        let forced = force_verify_file(&path).expect("hash");
        assert!(
            forced.computed,
            "force_verify_file never consults the cache"
        );
        assert_eq!(forced.cause, ReverifyCause::FirstSight);
        assert_eq!(forced.sha256, sha256_file(&path).expect("uncached"));
        assert_eq!(
            verify_file(&path).expect("hash").sha256,
            forced.sha256,
            "the forced re-verification corrected the cached conclusion"
        );
    }

    /// **证伪收敛(复审 P1/P2)**:盲区里的中段修改骗得过身份,骗不过一次真实的加载。
    ///
    /// 上一条用例钉的是“身份看不出这次修改”;这一条钉的是“谁看得出”:凭证路径本来就必须
    /// 读完全部字节才能绑定内容,它手上的那份完整摘要足以证伪缓存条目。作废之后状态必须
    /// 重新读盘并给出当前磁盘的真实摘要 —— “报告的状态”与“实际加载结果”的分叉不再是无限期。
    #[test]
    fn a_middle_only_edit_is_falsified_by_a_verified_load_and_the_next_status_rehashes() {
        let _serial = serial();
        let dir = TempDir::new("verify-falsify-on-load");
        let path = dir.path().join("model.onnx");
        let size = 256 * 1024;
        write(&path, &pattern(size, 11));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);
        let stale = first.sha256.clone();

        let offset = (PARTIAL_DIGEST_WINDOW_BYTES + 1024) as usize;
        rewrite_same_identity(&path, offset, b"\x10\x20\x30\x40");
        assert_eq!(
            lookup_for_test(&path).expect("the cache answers"),
            ReverifyCause::CacheHit,
            "the identity still cannot see this edit — that is the previous case's point"
        );

        let current = sha256_file(&path).expect("uncached");
        assert_ne!(current, stale, "the content really did change");
        let credential = VerifiedModel::verify(&path, Some(&current))
            .expect("the load-time verification sees the current content");
        assert_eq!(credential.actual_sha256(), Some(current.as_str()));

        let second = verify_file(&path).expect("hash");
        assert!(
            second.computed,
            "a load that falsified the cached digest must not leave a hot entry behind"
        );
        assert_eq!(second.cause, ReverifyCause::FirstSight);
        assert_eq!(
            second.sha256, current,
            "the reported state now matches the disk"
        );

        let third = verify_file(&path).expect("hash");
        assert!(
            !third.computed,
            "the convergence is not a one-shot invalidation loop"
        );
        assert_eq!(third.sha256, current);
    }

    /// **失败路径同样负责收敛**:比对失败就是在说“磁盘不是声明的那一份”,于是那条
    /// 陈旧的 `present` 也同样是错的。只让“加载成功”负责作废缓存会留下一个更误导人的洞:
    /// 加载已经拒绝、`/api/models` 却还在报告上一个摘要与 `present`。
    #[test]
    fn a_refused_load_also_falsifies_the_stale_cache_entry() {
        let _serial = serial();
        let dir = TempDir::new("verify-falsify-on-refusal");
        let path = dir.path().join("model.onnx");
        let size = 256 * 1024;
        write(&path, &pattern(size, 12));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);
        let stale = first.sha256.clone();

        let offset = (PARTIAL_DIGEST_WINDOW_BYTES + 2048) as usize;
        rewrite_same_identity(&path, offset, b"\x01\x02\x03\x04\x05\x06");

        let error = VerifiedModel::verify(&path, Some(&stale))
            .expect_err("the current content is not the declared one");
        match error {
            RapidOcrError::HashMismatch {
                expected, actual, ..
            } => {
                assert_eq!(expected, stale);
                assert_ne!(actual, stale, "the mismatch is a real content change");
            }
            other => panic!("expected a hash mismatch, got {other:?}"),
        }

        let second = verify_file(&path).expect("hash");
        assert!(
            second.computed,
            "a refused load falsifies the entry all the same"
        );
        assert_eq!(second.sha256, sha256_file(&path).expect("uncached"));
    }

    /// **如实钉住限制**:`expected = None` 的凭证不计算摘要,因此没有证伪的证据,缓存
    /// 原样保留。这不是漏改,是设计:没有“当前内容应当是什么”的声明,就没有“缓存错了”
    /// 的判定依据。把未校验的一次读取说成完整性证据,正是复审要排除的那类越界声明。
    #[test]
    fn an_unverified_credential_leaves_the_cache_alone() {
        let _serial = serial();
        let dir = TempDir::new("verify-unverified-keeps-cache");
        let path = dir.path().join("model.onnx");
        let size = 256 * 1024;
        write(&path, &pattern(size, 13));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);

        let offset = (PARTIAL_DIGEST_WINDOW_BYTES + 512) as usize;
        rewrite_same_identity(&path, offset, b"\x7f\x7e");
        let credential = VerifiedModel::verify(&path, None).expect("no expectation is allowed");
        assert!(!credential.is_verified());

        assert_eq!(
            lookup_for_test(&path).expect("the cache answers"),
            ReverifyCause::CacheHit,
            "DOCUMENTED LIMITATION: an unverified load produces no digest and is not evidence"
        );
        let second = verify_file(&path).expect("hash");
        assert!(!second.computed);
        assert_eq!(second.sha256, first.sha256);
    }

    /// 证伪只在**真不符**时发生:一次与缓存一致的加载不得把后续状态查询全部打回冷验证
    /// (否则缓存就没了)。“相符保留 / 不符删除 / 无条目不动作”三态在这里直接钉住。
    #[test]
    fn falsification_only_removes_an_entry_the_full_digest_contradicts() {
        let _serial = serial();
        let dir = TempDir::new("verify-falsify-rule");
        let path = dir.path().join("model.onnx");
        write(&path, b"hello");
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);
        assert_eq!(first.sha256, HELLO_SHA256);

        let unrelated = dir.path().join("absent.onnx");
        assert!(
            !invalidate_if_falsified(&unrelated, HELLO_SHA256),
            "there is no entry for a path that was never verified"
        );
        assert!(
            !invalidate_if_falsified(&path, &first.sha256.to_uppercase()),
            "an agreeing digest leaves the entry alone, case-insensitively like the verdict"
        );
        assert_eq!(
            lookup_for_test(&path).expect("the cache answers"),
            ReverifyCause::CacheHit
        );

        assert!(
            invalidate_if_falsified(&path, "deadbeef"),
            "a contradicting digest drops the entry"
        );
        assert_eq!(
            lookup_for_test(&path).expect("the cache answers"),
            ReverifyCause::FirstSight,
            "the entry is gone, not overwritten with a never-observed identity"
        );
        assert!(
            !invalidate_if_falsified(&path, "deadbeef"),
            "there is nothing left to drop the second time"
        );
    }

    /// **B 的核心用例(3)**:小文件的规则是"首尾重叠 ⇒ 局部摘要覆盖整个内容"。
    ///
    /// 小于 128 KiB:任何改动都在首块或尾块里 → 必定被抓到(与中段用例形成对照)。
    #[test]
    fn a_file_smaller_than_the_window_is_fully_covered_by_the_partial_digest() {
        let _serial = serial();
        let dir = TempDir::new("verify-small-file");
        let path = dir.path().join("small.onnx");
        let size = 1024;
        write(&path, &pattern(size, 4));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);

        // 文件正中间——对 128 KiB 以上的文件正是盲区所在,对小文件却不是。
        rewrite_same_identity(&path, size / 2, b"\x11\x22");
        let after = FileIdentity::of(&path).expect("identity");
        assert_eq!(after.size(), first.identity.size());
        assert_eq!(after.modified(), first.identity.modified());
        assert_ne!(
            after.partial(),
            first.identity.partial(),
            "for size <= 128 KiB the head and tail windows overlap and cover the whole file"
        );

        let second = verify_file(&path).expect("hash");
        assert!(second.computed);
        assert_eq!(second.cause, ReverifyCause::ContentChanged);
        assert_eq!(second.sha256, sha256_file(&path).expect("uncached"));
    }

    /// 命中判据是 `(size, 首尾 64 KiB)`,`mtime` 只是元数据:**内容没变**时把 mtime 改掉
    /// 仍然是命中(不重新哈希整个文件),原因是 `cache_hit` 而不是"内容变了"。
    ///
    /// 这一条把"上报的原因必须是真实原因"钉住:`SetFileTime`、复制文件都会改 mtime,
    /// 把它们报成 `content_changed` 会误导运维("磁盘上的模型被换过"是另一件事)。
    #[test]
    fn an_mtime_only_change_still_hits_and_is_not_reported_as_a_content_change() {
        let _serial = serial();
        let dir = TempDir::new("verify-mtime-only");
        let path = dir.path().join("model.onnx");
        write(&path, &pattern(4096, 8));
        let first = verify_file(&path).expect("hash");
        assert!(first.computed);
        let before = verification_stats();
        assert_eq!(before.partial_mismatches, 0);

        // 只碰时间戳:内容与体积一个字节都没动。
        let file = std::fs::OpenOptions::new()
            .write(true)
            .open(&path)
            .expect("open to touch the timestamp");
        file.set_modified(
            first.identity.modified().expect("mtime") + std::time::Duration::from_secs(7),
        )
        .expect("bump mtime");
        drop(file);

        assert_eq!(
            lookup_for_test(&path).expect("the cache answers"),
            ReverifyCause::CacheHit,
            "metadata alone must not invalidate a digest whose content windows are identical"
        );
        let second = verify_file(&path).expect("hash");
        assert!(!second.computed, "no full hash for a metadata-only change");
        assert_eq!(second.cause, ReverifyCause::CacheHit);
        assert_eq!(second.sha256, first.sha256);
        let after = verification_stats();
        assert_eq!(
            after.partial_mismatches, 0,
            "a metadata-only change is not a content change"
        );
        assert_eq!(
            after.cold_verifications, before.cold_verifications,
            "no full hash happened"
        );

        // 命中时本地那份 stat 身份被对齐到当前观察值,因此**下一次**真实的内容替换
        // 报的是"内容变了",而不是被 mtime 的差异抢先报成"文件被换掉"。
        rewrite_same_identity(&path, 1024, b"\x99");
        assert_eq!(
            lookup_for_test(&path).expect("the cache answers"),
            ReverifyCause::ContentChanged,
            "the recorded cause must describe the real reason"
        );
    }

    /// 边界:空文件与正好等于窗口的长度都必须是**良定义**的。
    ///
    /// 与"小于窗口"那条用同一套规则,但这里断言的是**边界处没有空隙**:
    /// 正好 128 KiB 时首块覆盖 `[0,64K)`、尾块覆盖 `[64K,128K)`,合起来是整个文件。
    #[test]
    fn empty_and_exactly_window_sized_files_are_well_defined() {
        let _serial = serial();
        let dir = TempDir::new("verify-boundary");
        let empty = dir.path().join("empty.onnx");
        dir.write("empty.onnx", b"");
        let identity = FileIdentity::of(&empty).expect("identity of an empty file");
        assert_eq!(identity.size(), 0);
        assert_eq!(identity.partial().size(), 0);
        assert_eq!(
            identity.partial(),
            &PartialDigest::compute(&empty, 0).expect("again")
        );
        assert!(verify_file(&empty).expect("hash").computed);

        let exact = dir.path().join("exact.onnx");
        let size = (2 * PARTIAL_DIGEST_WINDOW_BYTES) as usize;
        write(&exact, &pattern(size, 5));
        let before = FileIdentity::of(&exact).expect("identity");
        assert_eq!(before.size(), size as u64);
        // 正好 128 KiB:首块 = 前 64 KiB,尾块 = 后 64 KiB,无重叠也无空隙。
        rewrite_same_identity(&exact, 0, b"\x01");
        let head_changed = FileIdentity::of(&exact).expect("identity");
        assert_ne!(head_changed.partial(), before.partial());
        rewrite_same_identity(&exact, size - 1, b"\x02");
        let tail_changed = FileIdentity::of(&exact).expect("identity");
        assert_ne!(tail_changed.partial(), head_changed.partial());
        // 中段(第 64 KiB 个字节起)对 128 KiB 的文件仍是首块/尾块之外吗?
        // 不是:`size == 128 KiB` 时首块覆盖 [0,64K)、尾块覆盖 [64K,128K),合起来是全部。
        // 因此再改中段同样必须被发现——这正是"边界处无空隙"的断言。
        rewrite_same_identity(&exact, (PARTIAL_DIGEST_WINDOW_BYTES as usize) + 8, b"\x03");
        let middle_changed = FileIdentity::of(&exact).expect("identity");
        assert_ne!(middle_changed.partial(), tail_changed.partial());
    }

    /// **B 的核心用例(4)**:命中路径只花一次 `stat` + 一次 128 KiB 局部读,
    /// **不**完整哈希(`computed = false`,且摘要仍然是第一次算出来的那一份)。
    ///
    /// 证据必须是**单次调用**的属性:进程级的累计计数器会被**另一个测试二进制的并行测试**
    /// 干扰(`cargo test --all-targets` 同时跑 `--lib` 与 `serve` 的 bin 测试,而缓存与账本
    /// 都是进程级/静态的),因此这里不用"计数器没变"来论证,而是用
    /// [`VerificationOutcome::computed`]("这一次算没算")与摘要本身。
    #[test]
    fn a_cache_hit_reads_only_the_windows_and_never_rehashes() {
        let _serial = serial();
        let dir = TempDir::new("verify-hit-cost");
        let path = dir.path().join("model.onnx");
        write(&path, &pattern(64 * 1024, 6));

        let cold = verify_file(&path).expect("hash");
        assert!(cold.computed);
        assert_eq!(verification_stats().last_cold_bytes, 64 * 1024);

        for _ in 0..3 {
            let hit = verify_file(&path).expect("hash");
            assert!(
                !hit.computed,
                "DOCUMENTED COST: a hit must not perform a full hash"
            );
            assert_eq!(hit.cause, ReverifyCause::CacheHit);
            assert_eq!(
                hit.sha256, cold.sha256,
                "a hit must answer with the digest that was actually computed"
            );
            assert_eq!(hit.identity, cold.identity);
        }
    }

    /// 局部摘要本身的性质:首尾任一字节变化都改变它,中段不改变它(同体积)。
    #[test]
    fn the_partial_digest_binds_the_first_and_last_window_only() {
        let _serial = serial();
        let dir = TempDir::new("verify-partial-binds");
        let path = dir.path().join("model.onnx");
        let size = 200 * 1024;
        write(&path, &pattern(size, 7));
        let base = PartialDigest::compute(&path, size as u64).expect("partial");

        rewrite_same_identity(&path, 0, b"\x7f");
        let head = PartialDigest::compute(&path, size as u64).expect("partial");
        assert_ne!(head, base, "the first byte is inside the head window");

        rewrite_same_identity(&path, size - 1, b"\x7e");
        let tail = PartialDigest::compute(&path, size as u64).expect("partial");
        assert_ne!(tail, head, "the last byte is inside the tail window");

        let full_before_middle = sha256_file(&path).expect("uncached");
        rewrite_same_identity(&path, size / 2, b"\x7d");
        let middle = PartialDigest::compute(&path, size as u64).expect("partial");
        assert_eq!(
            middle, tail,
            "a middle-only edit does not move the partial digest (the documented heuristic)"
        );
        assert_ne!(
            sha256_file(&path).expect("uncached"),
            full_before_middle,
            "the full digest must have changed, otherwise the assertion above proves nothing"
        );
    }
}