matra 0.3.0

NLP library: UDPipe structured parse, base text metrics, summarization, keyphrase extraction. Rust core with Python bindings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
//! UDPipe adapter. Implements NlpProvider using the udpipe-rs crate.
//! This file is the ONLY place that imports udpipe_rs.

use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime};

use udpipe_rs::Model;

use crate::config::Config;
use crate::digest::sha256_hex;
use crate::domain::Error;
use crate::domain::{Identity, ProvisionNotice, Span, Token};

use super::NlpProvider;

/// Expected SHA-256 of the English UD-EWT 2.5 (release 191206) UDPipe model.
/// Refresh with `scripts/fetch-model-hash.sh` when updating the model version.
const ENGLISH_MODEL_SHA256: &str =
    "784bd0fa85e3d831fd02a55290d0acfd05c953159dc38cc33d52e1b28add9957";

/// The pinned model's name: the release's own, which the upstream
/// distribution uses, and what `provenance.parser.model` reports.
const ENGLISH_MODEL_NAME: &str = "english-ewt-ud-2.5-191206";

/// Expected size in bytes, checked before hashing as a fast-fail guard.
const ENGLISH_MODEL_SIZE: u64 = 16_309_608;

/// Direct download URL for the pinned model, fetched by [`fetch_capped`].
/// LINDAT migrated the bitstream endpoint from
/// `/repository/xmlui/bitstream/...` (now a 200 HTML preview) to
/// `/repository/server/api/core/bitstreams/...` (the actual binary), so
/// the URL is pinned here in its working form rather than derived from a
/// model name.
const ENGLISH_MODEL_URL: &str = "https://lindat.mff.cuni.cz/repository/server/api/core/bitstreams/handle/11234/1-3131/english-ewt-ud-2.5-191206.udpipe?sequence=17&isAllowed=y";

/// The pinned model's license, as its LINDAT record
/// (<https://hdl.handle.net/11234/1-3131>) states it: Creative Commons
/// Attribution-NonCommercial-ShareAlike 4.0 International. matra's code
/// is MIT; this file is a separate work with its own terms, and the
/// download notice carries them so the command line can say so. Beside
/// the URL because a new model means checking both.
const ENGLISH_MODEL_LICENSE: &str = "CC BY-NC-SA 4.0 (non-commercial)";

/// Where the full text of [`ENGLISH_MODEL_LICENSE`] is published.
const ENGLISH_MODEL_LICENSE_URL: &str = "https://creativecommons.org/licenses/by-nc-sa/4.0/";

/// The pinned English model as one record, so the provisioning path
/// takes the pin whole rather than six loose arguments.
const ENGLISH_MODEL: Pin<'static> = Pin {
    filename: ENGLISH_MODEL_FILENAME,
    size: ENGLISH_MODEL_SIZE,
    sha256: ENGLISH_MODEL_SHA256,
    url: ENGLISH_MODEL_URL,
    license: ENGLISH_MODEL_LICENSE,
    license_url: ENGLISH_MODEL_LICENSE_URL,
};

/// A pinned artifact: what it is called on disk, what it must measure,
/// where it comes from, and the terms it is published under. A test pins
/// a fixture of its own through the same shape.
#[derive(Debug, Clone, Copy)]
struct Pin<'a> {
    filename: &'a str,
    size: u64,
    sha256: &'a str,
    url: &'a str,
    license: &'a str,
    license_url: &'a str,
}

/// Ceiling on the downloaded model, past which [`Error::InputTooLarge`]
/// has `what` set to `"parser_model_download"`:
/// [`limits::MAX_DOWNLOAD_BYTES`](crate::domain::limits::MAX_DOWNLOAD_BYTES),
/// the number the embedding adapter uses, because it is the same question.
use crate::domain::limits::MAX_DOWNLOAD_BYTES as MAX_MODEL_BYTES;

/// Ceiling on the fetch, DNS lookup through the last byte of the body.
/// The pinned model is 16.3 MB, which needs this whole budget only on a
/// link under 0.5 Mbit/s, so the margin is generous for a slow
/// connection and still finite: a stalled or black-holed transfer fails
/// instead of holding the caller for as long as the socket stays open.
/// Before this existed, 90 seconds against an unreachable host produced
/// zero bytes with the process still running, unbounded.
const FETCH_TIMEOUT: Duration = Duration::from_secs(300);

/// Ceiling on establishing the connection, socket and TLS handshake
/// included. Separate from [`FETCH_TIMEOUT`] so an unreachable host
/// fails in seconds rather than consuming the whole transfer budget.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

/// Age past which a temporary download directory cannot belong to a
/// live provisioning call, so it is a leftover and this call reclaims
/// it.
///
/// Twice [`FETCH_TIMEOUT`]. A fetch cannot outlive that budget, and the
/// directory is created after the bytes are already in memory, so its
/// modification time is within milliseconds of the write that follows.
/// Anything older than ten minutes is therefore an orphan from a killed
/// process, not a peer. The margin is what protects a concurrent cold
/// start: three processes racing on one empty model directory each see
/// the others' directories as minutes-fresh and leave them alone.
const STALE_TEMP_AGE: Duration = Duration::from_secs(600);

/// Prefix of the temporary directory a download lands in. Shared by the
/// creation and the reclaim, so the sweep cannot look for a name the
/// writer does not use.
const TEMP_DIR_PREFIX: &str = ".tmp.download.";

/// The name every UDPipe-backed parse reports in its identity.
const PARSER_NAME: &str = "udpipe";

/// UDPipe adapter. Validated at construction: if the model is invalid,
/// construction fails. After construction, parse calls are trusted.
pub(crate) struct Udpipe {
    model: Model,
    /// Derived once, from the loaded bytes, at construction.
    identity: Identity,
}

impl std::fmt::Debug for Udpipe {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Udpipe").finish_non_exhaustive()
    }
}

impl Udpipe {
    /// Load from bytes (e.g. embedded via include_bytes!).
    ///
    /// The identity is derived from the bytes: their SHA-256 always, and
    /// the model's name and licence when the digest is the pinned
    /// model's. A model matra does not pin reports `None` for both.
    pub(crate) fn from_bytes(data: &[u8]) -> crate::domain::Result<Self> {
        let model =
            Model::load_from_memory(data).map_err(|e| Error::ModelInvalid(e.to_string()))?;
        Ok(Self {
            model,
            identity: identity_of(data),
        })
    }

    /// Download and load the English model, verifying its SHA-256 against
    /// a pinned constant in the source.
    ///
    /// Silent. [`Udpipe::english_with_notice`] is the same call with a
    /// say-so before the download, which is what the command line uses.
    ///
    /// The bytes are fetched into memory, verified there, and only then
    /// written: nothing that failed the digest ever reaches the model
    /// directory, and a run interrupted during the transfer leaves
    /// nothing behind at all.
    ///
    /// A model directory that lacks the file, or holds one that fails
    /// verification, costs a download, and a response that fails the
    /// digest costs one more: at most two downloads per call. A cached file
    /// that fails verification is never deleted. It is replaced only when
    /// bytes that verify arrive, by an atomic rename onto its name, so a
    /// refetch that fails, at the network or at the digest, leaves it
    /// byte-identical. Two responses that both fail the digest return
    /// [`Error::ModelInvalid`] without loading anything, because a
    /// mismatched model is untrusted. A transport failure is not retried.
    ///
    /// **No TOCTOU window.** The bytes that match the SHA-256 are the
    /// same bytes loaded into the model. There is no second disk read
    /// between verify and load, so an attacker with write access to
    /// `model_dir` who swaps the file after verification cannot affect
    /// the loaded model.
    ///
    /// `model_dir` is used as given and created if it is missing. A `~`
    /// in it is not expanded, so `"~/models"` names a directory literally
    /// called `~` under the working directory. Pass a directory you own:
    /// a shared one such as `/tmp` is writable by anybody on the machine.
    /// [`Udpipe::from_config`] resolves the configured model directory
    /// instead.
    ///
    /// To refresh the pinned hash when the model version changes, run
    /// `scripts/fetch-model-hash.sh` and paste the output into this file.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if the model directory cannot be created, if the
    /// download fails at the transport or answers with a non-2xx status
    /// (the message names the URL, and the `io::ErrorKind` separates a
    /// timeout from an unreachable host), or if the verified bytes
    /// cannot be written. [`Error::InputTooLarge`] with `what` set to
    /// `"parser_model_download"` if the response exceeds
    /// [`MAX_MODEL_BYTES`](self). [`Error::ModelInvalid`] if two
    /// downloads in a row fail the digest, or if the verified bytes do not
    /// load.
    pub(crate) fn english(model_dir: impl AsRef<Path>) -> crate::domain::Result<Self> {
        Self::english_with_notice(model_dir, |_| {})
    }

    /// [`Udpipe::english`], with `notice` called once before each fetch
    /// and not at all when the model is already on disk.
    ///
    /// The first run downloads 16 MB from a university server in Prague.
    /// Measured cold starts ran from 3 to 35 seconds with nothing on
    /// screen, which reads as a hung process. The library renders
    /// nothing itself, so this is the seam a caller renders through,
    /// reached from outside the crate as `Engine::from_config_with_notice`.
    ///
    /// # Errors
    ///
    /// Whatever [`Udpipe::english`] returns.
    pub(crate) fn english_with_notice(
        model_dir: impl AsRef<Path>,
        mut notice: impl FnMut(&ProvisionNotice),
    ) -> crate::domain::Result<Self> {
        let bytes = provision(
            model_dir.as_ref(),
            ENGLISH_MODEL,
            &mut notice,
            &fetch_capped,
        )?;
        Self::from_bytes(&bytes)
    }

    /// [`Udpipe::english`] over the model directory a [`Config`] resolved:
    /// what `Engine::new` and `Engine::from_config` wire.
    ///
    /// # Errors
    ///
    /// Whatever [`Udpipe::english`] returns.
    pub(crate) fn from_config(cfg: &Config) -> crate::domain::Result<Self> {
        Self::english(cfg.model_dir())
    }

    /// [`Udpipe::from_config`] with the say-so
    /// [`Udpipe::english_with_notice`] takes: what
    /// `Engine::from_config_with_notice` wires.
    ///
    /// # Errors
    ///
    /// Whatever [`Udpipe::english`] returns.
    pub(crate) fn from_config_with_notice(
        cfg: &Config,
        notice: impl FnMut(&ProvisionNotice),
    ) -> crate::domain::Result<Self> {
        Self::english_with_notice(cfg.model_dir(), notice)
    }
}

/// Filename the pinned model is cached under inside the model directory.
/// It is the release's own name, the one the upstream distribution uses,
/// so a hand-placed download lands under it without renaming.
const ENGLISH_MODEL_FILENAME: &str = "english-ewt-ud-2.5-191206.udpipe";

/// Obtain the pinned artifact's verified bytes, downloading it if the
/// model directory does not already hold it.
///
/// The pin, the URL and the fetcher are arguments rather than constants
/// read from scope, on the precedent the embedding adapter set: a test
/// can then pin a fixture of its own, and what is under test is what the
/// digest decides rather than what the fetcher returns.
///
/// The order is deliberate. Bytes are fetched into memory, checked
/// against the pinned size and digest there, and only then written, so
/// nothing that failed verification ever reaches the model directory and
/// an interrupted transfer leaves nothing behind. The bytes returned are
/// the bytes that satisfied the digest, which is what closes the TOCTOU
/// window: the loader never reads the disk again.
///
/// A cached file that is not the pinned model is never removed. It is
/// replaced when [`install`] renames verified bytes onto its name, which
/// `fs::rename` does over an existing destination, and left byte-identical
/// when no verified bytes arrive. Removing it before the refetch used to
/// cost an offline user the only copy they had.
fn provision(
    dir: &Path,
    pin: Pin<'_>,
    notice: &mut dyn FnMut(&ProvisionNotice),
    fetch: &dyn Fn(&str) -> crate::domain::Result<Vec<u8>>,
) -> crate::domain::Result<Vec<u8>> {
    create_model_dir(dir)?;
    let path = dir.join(pin.filename);

    if path.exists() {
        // A cached file that is not the pinned model is not removed here.
        // `install` lands through a rename, which replaces the destination,
        // so an unlink first would buy nothing and cost three things: it
        // would falsify the guarantee below that the rename is the only
        // operation touching the final path, it would let a failed remove
        // abort a run whose fetch had already succeeded, and it would open
        // a window in which the file does not exist, so a concurrent
        // process would see no cache and pay a redundant 16 MB fetch.
        // Leaving it also means a refetch that cannot reach the network
        // leaves the user their old file rather than nothing.
        if let Some(bytes) = read_and_verify(&path, pin.size, pin.sha256)? {
            return Ok(bytes);
        }
    }

    let bytes = fetch_verified(dir, pin, notice, fetch)?;
    install(dir, pin.filename, &bytes)?;
    Ok(bytes)
}

/// Fetch the artifact and return it only if it is the pinned one.
///
/// Two attempts. A first response that fails the digest is most often a
/// truncated or intercepted transfer rather than a changed upstream, and
/// one retry costs a bounded read; a second failure is not a transient,
/// so it returns [`Error::ModelInvalid`] and nothing is written.
///
/// The size cap is enforced here rather than inside the fetcher, at the
/// one place every response passes through: the fetcher is replaceable
/// and the bound is not.
fn fetch_verified(
    dir: &Path,
    pin: Pin<'_>,
    notice: &mut dyn FnMut(&ProvisionNotice),
    fetch: &dyn Fn(&str) -> crate::domain::Result<Vec<u8>>,
) -> crate::domain::Result<Vec<u8>> {
    for _ in 0..2 {
        notice(&ProvisionNotice {
            artifact: pin.filename.to_string(),
            bytes: pin.size,
            destination: dir.to_path_buf(),
            license: pin.license.to_string(),
            license_url: pin.license_url.to_string(),
        });
        let bytes = fetch(pin.url)?;
        if bytes.len() > MAX_MODEL_BYTES {
            return Err(Error::InputTooLarge {
                limit: MAX_MODEL_BYTES,
                actual: bytes.len(),
                what: "parser_model_download",
            });
        }
        if verified(&bytes, pin.size, pin.sha256) {
            return Ok(bytes);
        }
    }
    Err(Error::ModelInvalid(format!(
        "SHA-256 mismatch after re-download from {}",
        pin.url
    )))
}

/// Write verified bytes into the model directory atomically.
///
/// The bytes land in a temporary subdirectory of `dir` and arrive at
/// their final name under one rename. `std::fs::rename` is atomic on one
/// filesystem (POSIX `rename(2)`; Windows `MoveFileExW` with
/// `MOVEFILE_REPLACE_EXISTING`), so no reader sees a partial model and
/// two processes provisioning into the same directory cannot interleave:
/// each writes inside its own subdirectory and the rename is the only
/// operation that touches the final path.
///
/// The temporary is opened with `create_new`, which is `O_EXCL`: a path
/// already there, symlink or not, fails the open rather than being
/// written through.
fn install(dir: &Path, filename: &str, bytes: &[u8]) -> crate::domain::Result<()> {
    use std::io::Write;

    with_temp_subdir(dir, |tmp_dir| {
        let tmp_file = tmp_dir.join(filename);
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp_file)
            .map_err(|e| io_at("create the temporary file", &tmp_file, &e))?;
        file.write_all(bytes)
            .map_err(|e| io_at("write the model to", &tmp_file, &e))?;
        drop(file);
        let final_path = dir.join(filename);
        std::fs::rename(&tmp_file, &final_path)
            .map_err(|e| io_at("move the model into place at", &final_path, &e))
    })
}

/// Fetch one URL into memory, reading at most one byte past
/// [`MAX_MODEL_BYTES`].
///
/// Stopping one byte over is what lets the caller tell "at the cap" from
/// "over it" while keeping the read bounded: an endless or misdirected
/// response costs 64 MiB and a rejection, not the machine's memory.
///
/// `ureq` treats a non-2xx status as an error by default, so an HTML
/// error page never reaches the digest.
///
/// The call is bounded in time as well as in size, [`FETCH_TIMEOUT`] end
/// to end and [`CONNECT_TIMEOUT`] on the connection, because `ureq` sets
/// no timeout of its own: every timeout in its default configuration is
/// `None`, and a socket that accepts and then says nothing would
/// otherwise block the caller for as long as it stays open. That is what
/// the fetch through `udpipe_rs::download_model_from_url` did before
/// this function existed.
fn fetch_capped(url: &str) -> crate::domain::Result<Vec<u8>> {
    use std::io::Read;

    let response = download_agent()
        .get(url)
        .call()
        .map_err(|e| transport_failure(url, &e))?;
    let mut bytes = Vec::new();
    response
        .into_body()
        .into_reader()
        .take(MAX_MODEL_BYTES as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| body_failure(url, e))?;
    Ok(bytes)
}

/// The client [`fetch_capped`] downloads through.
///
/// A function rather than an inline builder so a test can assert the
/// configuration without a network. `https_only` is the part worth
/// asserting: `ureq` follows up to ten redirects by default, so without
/// it an `https` URL that redirects to `http` is fetched in cleartext.
/// The pinned digest means that cannot change which bytes load, so this
/// is confidentiality rather than integrity, but a redirect is not the
/// user's decision to make and the pinned URLs are all `https`.
fn download_agent() -> ureq::Agent {
    ureq::Agent::config_builder()
        .timeout_global(Some(FETCH_TIMEOUT))
        .timeout_connect(Some(CONNECT_TIMEOUT))
        .https_only(true)
        .build()
        .into()
}

/// Map a failure part-way through reading the response body.
///
/// The body reader hands back an `io::Error`, and `ureq` builds that one
/// with `Error::into_io`, which returns the inner error only for
/// `Error::Io` and wraps everything else, `Timeout` included, in
/// `io::Error::other`. Reading `kind()` straight off it therefore gives
/// `Other`, so a fetch that ran past [`FETCH_TIMEOUT`] mid-transfer
/// reported `Other` where `site/content/reference/errors.md` and RFC-0015
/// both promise `TimedOut`. `From<io::Error> for ureq::Error` unwraps
/// the wrapped error again, which recovers the kind and also gives a
/// mid-stream certificate rejection the sentence [`download_message`]
/// writes. An `io::Error` that was never a `ureq::Error` comes back as
/// `Error::Io` and keeps its own kind.
fn body_failure(url: &str, error: std::io::Error) -> Error {
    transport_failure(url, &ureq::Error::from(error))
}

/// Map a `ureq` failure to [`Error::Io`].
///
/// A download that never arrives is a transport failure, not an invalid
/// model: [`Error::ModelInvalid`] is reserved for bytes that did arrive
/// and then failed the digest or the loader. A non-2xx status belongs on
/// this side too, because what came back was a server's answer about the
/// request rather than a model. The `io::ErrorKind` is preserved where
/// `ureq` knows it, so a caller can tell a timeout from an unreachable
/// host without reading the message. RFC-0015 records the classification
/// and what it replaced. The failure is marked retryable (EPR-0006):
/// nothing was written, so the same call can be made again. A rejected
/// certificate is the exception, since its message names a remedy no
/// retry supplies.
fn transport_failure(url: &str, error: &ureq::Error) -> Error {
    use std::io::ErrorKind;

    let kind = match error {
        ureq::Error::Io(e) => e.kind(),
        ureq::Error::Timeout(_) => ErrorKind::TimedOut,
        ureq::Error::ConnectionFailed | ureq::Error::HostNotFound => ErrorKind::NotConnected,
        _ => ErrorKind::Other,
    };
    let retryable = !is_certificate_rejection(&error.to_string(), error);
    Error::Io(crate::domain::IoContext::download(
        kind,
        url,
        download_message(url, error),
        retryable,
    ))
}

/// What the user reads when a download fails.
///
/// A rejected certificate gets a sentence instead of a `Debug` rendering
/// of a `rustls` enum. `invalid peer certificate: Other(OtherError(
/// CaUsedAsEndEntity))` is what someone behind a TLS-intercepting
/// corporate proxy saw, and it says nothing about why matra cannot be
/// made to trust their proxy: matra verifies against root certificates
/// compiled into the binary and never reads the system trust store,
/// which is why it needs no `ca-certificates` package and also why
/// adding one to the system store changes nothing. The raw failure is
/// kept at the end, because a bug report needs it.
fn download_message(url: &str, error: &ureq::Error) -> String {
    let detail = error.to_string();
    if !is_certificate_rejection(&detail, error) {
        return format!("download {url}: {detail}");
    }
    format!(
        "download {url}: the TLS certificate offered for {} was rejected. matra verifies \
         TLS against root certificates compiled into it and never reads the system trust \
         store, so a proxy that re-signs TLS cannot be trusted by installing its CA. \
         Fetch {} by hand and put it in the model directory instead. Underlying failure: {detail}",
        host_of(url),
        ENGLISH_MODEL_FILENAME,
    )
}

/// Whether a transport failure is the peer's certificate being refused.
///
/// `ureq` surfaces a `rustls` handshake failure as `Error::Io` wrapping
/// an `io::Error` whose message is the `rustls` error, so the variant
/// alone does not say. The rendered text does, and `Error::Tls` is
/// checked as well for a bespoke transport that reports it directly.
fn is_certificate_rejection(detail: &str, error: &ureq::Error) -> bool {
    if matches!(error, ureq::Error::Tls(_)) {
        return true;
    }
    let lowered = detail.to_ascii_lowercase();
    lowered.contains("certificate") || lowered.contains("rustls")
}

/// The host in an absolute URL, or the whole URL when it has no
/// recognisable authority. Enough for a message; not a URL parser.
fn host_of(url: &str) -> &str {
    let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
    let authority = after_scheme
        .split(['/', '?', '#'])
        .next()
        .unwrap_or(after_scheme);
    // Strip userinfo and any port.
    let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
    host.split(':').next().unwrap_or(host)
}

/// A filesystem failure that names the operation and the path.
///
/// `io error: Permission denied (os error 13)` was the whole message a
/// user got when the model directory could not be created, with the
/// directory sitting in a variable one line away. The sentence is written
/// once, in `IoContext::cannot`, which also carries the path as a detail.
fn io_at(operation: &str, path: &Path, error: &std::io::Error) -> Error {
    Error::Io(crate::domain::IoContext::cannot(operation, path, error))
}

fn create_model_dir(dir: &Path) -> crate::domain::Result<()> {
    std::fs::create_dir_all(dir).map_err(|e| io_at("create the model directory", dir, &e))
}

/// Whether these bytes are the pinned artifact: the size first, as a
/// fast-fail, then the digest.
fn verified(bytes: &[u8], expected_size: u64, expected_hash: &str) -> bool {
    if bytes.len() as u64 != expected_size {
        return false;
    }
    sha256_hex(bytes).eq_ignore_ascii_case(expected_hash)
}

/// Run a closure with a temporary subdirectory inside `parent`, removing
/// the subdirectory on scope exit (success or panic). The subdirectory
/// name is unique per call ([`temp_stamp`]), so concurrent calls cannot
/// collide even when they share a process id.
///
/// `Drop` does not run on `SIGINT`, so cleanup on scope exit cannot be
/// the whole answer: a run killed between the create and the rename
/// leaves the directory behind. Two things bound that. The bytes are
/// already in memory by the time this is called, so the window is the
/// length of one write rather than the length of a download, and every
/// leftover older than [`STALE_TEMP_AGE`] is reclaimed here before a new
/// one is made. The previous reclaim matched only the current process's
/// own pid, which on a real machine never recurs, so an orphan was
/// permanent.
fn with_temp_subdir<F, T>(parent: &Path, f: F) -> crate::domain::Result<T>
where
    F: FnOnce(&Path) -> crate::domain::Result<T>,
{
    struct Cleanup<'a>(&'a Path);
    impl Drop for Cleanup<'_> {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(self.0);
        }
    }

    reclaim_stale_temp_dirs(parent, SystemTime::now());

    let tmp_dir = parent.join(format!("{TEMP_DIR_PREFIX}{}", temp_stamp()));
    // `create_dir`, not `create_dir_all`: this name is this call's alone,
    // so anything already sitting under it is a surprise to fail on
    // rather than a directory to write into. Nothing is removed by name
    // here either, because a name that looks like this call's may be a
    // peer's: age is the only thing that says a directory is a leftover.
    std::fs::create_dir(&tmp_dir)
        .map_err(|e| io_at("create the temporary directory", &tmp_dir, &e))?;
    let _cleanup = Cleanup(&tmp_dir);
    f(&tmp_dir)
}

/// A name fragment no call in flight will pick twice: the process id,
/// the wall clock in nanoseconds, and a counter for two calls in one
/// process that read the same nanosecond.
///
/// The process id alone was the previous answer and it is not unique. In
/// a container every process is pid 1, so two cold starts sharing a
/// bind-mounted model directory choose the same name, and the removal
/// that used to precede the create would delete a live peer's download.
/// Uniqueness here is what leaves age as the only rule that reclaims
/// anything.
fn temp_stamp() -> String {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let nanos = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos() as u64);
    format!(
        "{}.{nanos:x}.{:x}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    )
}

/// Remove every temporary download directory in `parent` that is too old
/// to belong to a running provisioning call.
///
/// `now` is a parameter so the rule is testable without touching
/// modification times on disk. A directory whose modification time is in
/// the future (a clock that moved, a copied tree) is left alone: an
/// unexplained timestamp is a reason not to delete, not a reason to.
///
/// Failures are ignored throughout. Reclaiming a leftover is tidying,
/// and a directory that cannot be listed or removed must not turn a
/// working download into an error.
fn reclaim_stale_temp_dirs(parent: &Path, now: SystemTime) {
    let Ok(entries) = std::fs::read_dir(parent) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(name) = name.to_str() else { continue };
        if !name.starts_with(TEMP_DIR_PREFIX) {
            continue;
        }
        let stale = entry
            .metadata()
            .and_then(|m| m.modified())
            .ok()
            .and_then(|modified| now.duration_since(modified).ok())
            .is_some_and(|age| age >= STALE_TEMP_AGE);
        if stale {
            let _ = std::fs::remove_dir_all(entry.path());
        }
    }
}

/// Read a file and verify its SHA-256 in a single read.
///
/// Returns:
/// - `Ok(Some(bytes))` when size and hash both match — the returned bytes
///   are the *exact* bytes that were hashed; the caller can pass them
///   directly to a from-memory loader without a second disk read.
/// - `Ok(None)` when size mismatches (fast-fail, no read of contents)
///   or hash mismatches.
/// - `Err` when the file cannot be read.
///
/// This shape closes the TOCTOU window the previous `verify_file` had:
/// previously the caller hashed the file then re-read it via
/// `Model::load(path)`, giving an attacker with directory write access
/// a window to swap the file between verify and load.
fn read_and_verify(
    path: &Path,
    expected_size: u64,
    expected_hash: &str,
) -> crate::domain::Result<Option<Vec<u8>>> {
    let meta = std::fs::metadata(path).map_err(|e| io_at("read", path, &e))?;
    if meta.len() != expected_size {
        return Ok(None);
    }
    let bytes = std::fs::read(path).map_err(|e| io_at("read", path, &e))?;
    if verified(&bytes, expected_size, expected_hash) {
        Ok(Some(bytes))
    } else {
        Ok(None)
    }
}

/// The identity of a model loaded from `bytes`. Recognised by digest,
/// not by how it was loaded, so the pinned model loaded from a path
/// names itself exactly as the provisioned one does.
fn identity_of(bytes: &[u8]) -> Identity {
    let sha256 = sha256_hex(bytes);
    let pinned = sha256.eq_ignore_ascii_case(ENGLISH_MODEL.sha256);
    Identity::new(
        PARSER_NAME,
        pinned.then(|| ENGLISH_MODEL_NAME.to_string()),
        Some(sha256),
        pinned.then(|| ENGLISH_MODEL.license.to_string()),
    )
}

/// Run a closure that may panic inside the `udpipe-rs` C/C++ boundary,
/// catching any panic and converting it into [`Error::ParseFailed`]. This
/// keeps a process-aborting C-side bug (Taleb #1: SPOF with no panic
/// boundary) from taking down the host. Without this wrapper, a panic
/// inside `Model::parse` aborts the host process; in Python it manifests
/// as interpreter death, in WASM as a trap.
fn catch_parse_panic<F, T>(f: F) -> crate::domain::Result<T>
where
    F: FnOnce() -> crate::domain::Result<T>,
{
    use std::panic::{AssertUnwindSafe, catch_unwind};
    match catch_unwind(AssertUnwindSafe(f)) {
        Ok(result) => result,
        Err(payload) => {
            let message = payload
                .downcast_ref::<&'static str>()
                .map(|s| (*s).to_string())
                .or_else(|| payload.downcast_ref::<String>().cloned())
                .unwrap_or_else(|| "udpipe panic (no message captured)".to_string());
            Err(Error::ParseFailed {
                reason: None,
                cause: format!("udpipe panicked: {message}"),
            })
        }
    }
}

impl NlpProvider for Udpipe {
    fn parse(&self, text: &str) -> crate::domain::Result<Vec<Vec<Token>>> {
        let words = catch_parse_panic(|| {
            self.model.parse(text).map_err(|e| Error::ParseFailed {
                reason: None,
                cause: e.to_string(),
            })
        })?;

        let mut by_sentence: HashMap<i32, Vec<&udpipe_rs::Word>> = HashMap::new();
        for word in &words {
            by_sentence.entry(word.sentence_id).or_default().push(word);
        }

        let mut ids: Vec<i32> = by_sentence.keys().copied().collect();
        ids.sort();

        // The tokens follow the text in order across sentences, so one
        // cursor walks the text once to give every token its span.
        let mut cursor = 0;
        ids.into_iter()
            .map(|id| {
                let mut tokens = by_sentence[&id]
                    .iter()
                    .map(|w| token_of(w))
                    .collect::<crate::domain::Result<Vec<Token>>>()?;
                for token in &mut tokens {
                    let (start, end) = locate(text, cursor, &token.text)
                        .ok_or_else(|| unplaced(token, id + 1, cursor))?;
                    token.span = Span::new(start, end);
                    cursor = end;
                }
                Ok(tokens)
            })
            .collect()
    }

    fn identity(&self) -> Identity {
        self.identity.clone()
    }
}

/// Where `form` lies in `text`, starting at the first character at or
/// after `cursor` that is not whitespace, as `(start, end)` in bytes.
///
/// The form must match the text there exactly, except that a run of
/// whitespace inside the form matches any run of whitespace in the text
/// (a token the tokenizer read across a line break). `None` when it does
/// not match: the caller reports that rather than guess a span. UDPipe's
/// tokenizer copies forms from the text it was given, so `None` means a
/// form the tokenizer rewrote, which the English model is not known to
/// do.
fn locate(text: &str, cursor: usize, form: &str) -> Option<(usize, usize)> {
    let rest = text.get(cursor..)?;
    let start = cursor + (rest.len() - rest.trim_start().len());
    let end = crate::domain::form_end(text, start, form)?;
    Some((start, end))
}

/// The token UDPipe emitted as `word`, its span not yet placed. A
/// negative id or head, which `udpipe_rs` types as `i32`, is a failure
/// rather than a wrapped number.
fn token_of(word: &udpipe_rs::Word) -> crate::domain::Result<Token> {
    let id = usize::try_from(word.id).map_err(|_| Error::ParseFailed {
        reason: None,
        cause: format!(
            "invalid token id {} in sentence {}",
            word.id, word.sentence_id
        ),
    })?;
    let head = usize::try_from(word.head).map_err(|_| Error::ParseFailed {
        reason: None,
        cause: format!(
            "invalid head {} for token {} in sentence {}",
            word.head, word.id, word.sentence_id
        ),
    })?;
    Ok(Token {
        id,
        span: Span::default(),
        text: word.form.clone(),
        lemma: word.lemma.clone(),
        pos: word.upostag.clone(),
        xpos: word.xpostag.clone(),
        features: crate::domain::features_from_conllu(&word.feats),
        dep: word.deprel.clone(),
        head,
        deps: String::from("_"),
        misc: word.misc.clone(),
        is_punct: word.is_punct(),
    })
}

/// The failure for a token whose form is not in the text at or after
/// `cursor`: reported rather than given a guessed span.
fn unplaced(token: &Token, sentence: i32, cursor: usize) -> Error {
    Error::ParseFailed {
        reason: None,
        cause: format!(
            "token {} ({:?}) of sentence {sentence} is not in the parsed text at or after byte {cursor}, so it has no span",
            token.id, token.text
        ),
    }
}

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

    #[test]
    fn locate_skips_leading_whitespace_and_matches_exactly() {
        let text = "  Hello, wörld.";
        assert_eq!(locate(text, 0, "Hello"), Some((2, 7)));
        assert_eq!(locate(text, 7, ","), Some((7, 8)));
        assert_eq!(locate(text, 8, "wörld"), Some((9, 15)));
        assert_eq!(locate(text, 8, "world"), None);
    }

    #[test]
    fn locate_lets_whitespace_in_a_form_match_any_whitespace() {
        let text = "e.\r\n g. done";
        assert_eq!(locate(text, 0, "e. g."), Some((0, 7)));
    }

    #[test]
    fn locate_is_none_past_the_end() {
        assert_eq!(locate("abc", 3, "d"), None);
        assert_eq!(locate("abc", 9, "a"), None);
    }

    /// A model matra does not pin is named by its digest alone: the
    /// name and licence of the pinned model must not be claimed for it.
    #[test]
    fn an_unpinned_model_reports_its_digest_and_no_name() {
        let id = identity_of(b"hello");
        assert_eq!(id.name, "udpipe");
        assert_eq!(id.sha256.as_deref(), Some(HELLO_HASH));
        assert_eq!(id.model, None);
        assert_eq!(id.license, None);
    }

    /// Validates the catch_parse_panic technique against an arbitrary
    /// panicking closure. We can't easily make the real `Model::parse`
    /// panic in a unit test without an injected fault, so this test
    /// covers the wrapper's contract: a panic inside the closure
    /// becomes Err(ParseFailed) instead of aborting the test process.
    #[test]
    fn catch_parse_panic_converts_str_panic_to_parse_failed() {
        let result: crate::domain::Result<()> = catch_parse_panic(|| {
            panic!("simulated udpipe-rs panic");
        });
        match result {
            Err(Error::ParseFailed { cause: msg, .. }) => {
                assert!(
                    msg.contains("udpipe panicked"),
                    "expected wrapper prefix in: {msg}"
                );
                assert!(
                    msg.contains("simulated udpipe-rs panic"),
                    "expected payload in: {msg}"
                );
            }
            other => panic!("expected ParseFailed, got {other:?}"),
        }
    }

    #[test]
    fn catch_parse_panic_converts_string_panic_to_parse_failed() {
        let result: crate::domain::Result<()> =
            catch_parse_panic(|| panic!("{}", "owned string panic"));
        match result {
            Err(Error::ParseFailed { cause: msg, .. }) => {
                assert!(
                    msg.contains("owned string panic"),
                    "expected payload in: {msg}"
                );
            }
            other => panic!("expected ParseFailed, got {other:?}"),
        }
    }

    #[test]
    fn catch_parse_panic_passes_through_non_panic_results() {
        let ok: crate::domain::Result<i32> = catch_parse_panic(|| Ok(42));
        assert_eq!(ok.unwrap(), 42);

        let err: crate::domain::Result<i32> = catch_parse_panic(|| {
            Err(Error::ParseFailed {
                reason: None,
                cause: "boring failure".into(),
            })
        });
        match err {
            Err(Error::ParseFailed { cause: msg, .. }) => assert_eq!(msg, "boring failure"),
            other => panic!("expected pass-through ParseFailed, got {other:?}"),
        }
    }

    /// SHA-256 of "hello" computed offline. Tied to the literal payload below.
    const HELLO_HASH: &str = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";

    #[test]
    fn read_and_verify_returns_bytes_on_match() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hello.bin");
        std::fs::write(&path, b"hello").unwrap();

        let result = read_and_verify(&path, 5, HELLO_HASH).unwrap();
        assert_eq!(result.as_deref(), Some(b"hello".as_slice()));
    }

    #[test]
    fn read_and_verify_returns_none_on_size_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hello.bin");
        std::fs::write(&path, b"hello").unwrap();

        // Wrong expected size — fast-fail before hashing.
        let result = read_and_verify(&path, 6, HELLO_HASH).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn read_and_verify_returns_none_on_hash_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("five.bin");
        std::fs::write(&path, b"world").unwrap(); // size matches "hello" but bytes differ

        let result = read_and_verify(&path, 5, HELLO_HASH).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn with_temp_subdir_creates_and_cleans_up_on_success() {
        let parent = tempfile::tempdir().unwrap();
        let mut captured: Option<std::path::PathBuf> = None;

        let _ = with_temp_subdir(parent.path(), |tmp| {
            assert!(tmp.exists(), "temp subdir should exist inside the closure");
            assert!(
                tmp.starts_with(parent.path()),
                "temp subdir should be inside parent"
            );
            captured = Some(tmp.to_path_buf());
            Ok(())
        });

        let tmp_path = captured.unwrap();
        assert!(
            !tmp_path.exists(),
            "temp subdir should be removed after the closure returns"
        );
    }

    #[test]
    fn with_temp_subdir_cleans_up_on_error() {
        let parent = tempfile::tempdir().unwrap();
        let mut captured: Option<std::path::PathBuf> = None;

        let _ = with_temp_subdir(parent.path(), |tmp| {
            captured = Some(tmp.to_path_buf());
            Err::<(), Error>(Error::ModelInvalid("synthetic".into()))
        });

        let tmp_path = captured.unwrap();
        assert!(
            !tmp_path.exists(),
            "temp subdir should be removed even when the closure returns Err"
        );
    }

    // -----------------------------------------------------------------
    // Provisioning
    //
    // Every test below runs offline against an injected fetcher and a
    // fixture pin, which is why `provision` takes the pin, the URL and
    // the fetcher as arguments. What is under test is what the digest
    // decides, not what the fetcher returns.
    // -----------------------------------------------------------------

    const FIXTURE: &[u8] = b"hello";
    const FIXTURE_NAME: &str = "fixture.udpipe";
    const FIXTURE_URL: &str = "https://models.example/fixture.udpipe";
    const FIXTURE_LICENSE: &str = "Fixture License 1.0";
    const FIXTURE_LICENSE_URL: &str = "https://licenses.example/fixture";

    /// Records what the fetcher was asked for and what the notice said.
    struct Recorder {
        notices: Vec<ProvisionNotice>,
        fetches: usize,
    }

    fn provision_fixture(
        dir: &Path,
        recorder: &mut Recorder,
        body: &dyn Fn() -> crate::domain::Result<Vec<u8>>,
    ) -> crate::domain::Result<Vec<u8>> {
        let fetches = std::cell::Cell::new(0usize);
        let fetch = |_: &str| {
            fetches.set(fetches.get() + 1);
            body()
        };
        let mut notice = |n: &ProvisionNotice| recorder.notices.push(n.clone());
        let pin = Pin {
            filename: FIXTURE_NAME,
            size: FIXTURE.len() as u64,
            sha256: HELLO_HASH,
            url: FIXTURE_URL,
            license: FIXTURE_LICENSE,
            license_url: FIXTURE_LICENSE_URL,
        };
        let result = provision(dir, pin, &mut notice, &fetch);
        recorder.fetches += fetches.get();
        result
    }

    fn recorder() -> Recorder {
        Recorder {
            notices: Vec::new(),
            fetches: 0,
        }
    }

    /// Regression (report H1): a cold run says what it is fetching, how
    /// big it is, and where it is going, before the transfer starts. The
    /// first run used to write zero bytes to either stream for 3 to 35
    /// seconds.
    #[test]
    fn a_cold_run_announces_the_download_once() {
        let dir = tempfile::tempdir().unwrap();
        let mut rec = recorder();
        let bytes = provision_fixture(dir.path(), &mut rec, &|| Ok(FIXTURE.to_vec())).unwrap();

        assert_eq!(bytes, FIXTURE);
        assert_eq!(rec.notices.len(), 1, "one notice per fetch, one fetch");
        assert_eq!(rec.notices[0].artifact, FIXTURE_NAME);
        assert_eq!(rec.notices[0].bytes, FIXTURE.len() as u64);
        assert_eq!(rec.notices[0].destination, dir.path());
        assert_eq!(rec.notices[0].license, FIXTURE_LICENSE);
        assert_eq!(rec.notices[0].license_url, FIXTURE_LICENSE_URL);
        assert_eq!(
            std::fs::read(dir.path().join(FIXTURE_NAME)).unwrap(),
            FIXTURE
        );
    }

    /// The other half of H1: a warm run is silent and touches nothing.
    /// A notice on every run would be noise, and noise gets filtered.
    #[test]
    fn a_warm_run_announces_nothing_and_fetches_nothing() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(FIXTURE_NAME), FIXTURE).unwrap();

        let mut rec = recorder();
        let bytes = provision_fixture(dir.path(), &mut rec, &|| {
            panic!("a cached, verified model must not be refetched")
        })
        .unwrap();

        assert_eq!(bytes, FIXTURE);
        assert!(rec.notices.is_empty(), "nothing to announce");
        assert_eq!(rec.fetches, 0);
    }

    /// Bytes that fail the digest are refetched once and never written.
    /// Verification happens in memory, so an untrusted response does not
    /// reach the model directory even briefly.
    #[test]
    fn bytes_that_fail_the_digest_are_refetched_once_then_refused() {
        let dir = tempfile::tempdir().unwrap();
        let mut rec = recorder();
        let err = provision_fixture(dir.path(), &mut rec, &|| Ok(b"WORLD".to_vec()))
            .expect_err("wrong bytes are refused");

        match err {
            Error::ModelInvalid(msg) => {
                assert!(msg.contains("SHA-256 mismatch after re-download"), "{msg}");
                assert!(
                    msg.contains(FIXTURE_URL),
                    "the message names the URL: {msg}"
                );
            }
            other => panic!("expected ModelInvalid, got {other:?}"),
        }
        assert_eq!(rec.fetches, 2, "one retry, not more");
        assert!(
            !dir.path().join(FIXTURE_NAME).exists(),
            "nothing that failed the digest is written"
        );
        assert!(leftovers(dir.path()).is_empty(), "no temporary directory");
    }

    /// A good response after a bad one lands. The retry exists for a
    /// truncated transfer, so it has to be able to succeed.
    #[test]
    fn a_retry_that_succeeds_lands_the_model() {
        let dir = tempfile::tempdir().unwrap();
        let attempts = std::cell::Cell::new(0usize);
        let mut rec = recorder();
        let bytes = provision_fixture(dir.path(), &mut rec, &|| {
            attempts.set(attempts.get() + 1);
            if attempts.get() == 1 {
                Ok(b"WORLD".to_vec())
            } else {
                Ok(FIXTURE.to_vec())
            }
        })
        .unwrap();

        assert_eq!(bytes, FIXTURE);
        assert_eq!(rec.notices.len(), 2, "a notice per fetch");
        assert_eq!(
            std::fs::read(dir.path().join(FIXTURE_NAME)).unwrap(),
            FIXTURE
        );
    }

    /// A cached file that is not the pinned model is replaced, which is
    /// the self-heal a truncated or corrupted cache needs.
    #[test]
    fn a_corrupt_cache_is_replaced() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(FIXTURE_NAME), b"junk").unwrap();

        let mut rec = recorder();
        let bytes = provision_fixture(dir.path(), &mut rec, &|| Ok(FIXTURE.to_vec())).unwrap();

        assert_eq!(bytes, FIXTURE);
        assert_eq!(rec.fetches, 1);
        assert_eq!(
            std::fs::read(dir.path().join(FIXTURE_NAME)).unwrap(),
            FIXTURE
        );
    }

    /// Regression (review of #77, M1): a cached file that fails
    /// verification is never removed, so a refetch that fails leaves it
    /// byte-identical. A removal used to run before the refetch, so a
    /// user who was offline with a corrupt cache lost the file they had
    /// and got nothing back, and the removal bought nothing: the install
    /// lands through a rename, which replaces an existing destination.
    #[test]
    fn a_corrupt_cache_outlives_a_failed_refetch() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(FIXTURE_NAME);
        std::fs::write(&path, b"junk").unwrap();

        let mut rec = recorder();
        let err = provision_fixture(dir.path(), &mut rec, &|| {
            Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "download https://models.example/fixture.udpipe: host not found",
            )))
        })
        .unwrap_err();

        assert!(matches!(err, Error::Io(_)), "got {err:?}");
        assert_eq!(std::fs::read(&path).unwrap(), b"junk");
    }

    /// Regression (report H4): a transport failure travels as the error
    /// the fetcher produced. It is not relabelled as an invalid model,
    /// because no model arrived.
    #[test]
    fn a_transport_failure_is_not_an_invalid_model() {
        let dir = tempfile::tempdir().unwrap();
        let mut rec = recorder();
        let err = provision_fixture(dir.path(), &mut rec, &|| {
            Err(Error::Io(std::io::Error::new(
                std::io::ErrorKind::NotConnected,
                "download https://models.example/fixture.udpipe: host not found",
            )))
        })
        .expect_err("an unreachable host fails");

        assert_eq!(err.kind(), "io", "{err}");
        assert!(err.to_string().contains("models.example"), "{err}");
        assert!(leftovers(dir.path()).is_empty());
    }

    /// A response past the cap is rejected by size before anything is
    /// hashed or written, and it names the gate so a consumer can route
    /// it. The cap lives at the one place every response passes through.
    #[test]
    fn a_response_over_the_cap_is_refused_by_size() {
        let dir = tempfile::tempdir().unwrap();
        let mut rec = recorder();
        let err = provision_fixture(dir.path(), &mut rec, &|| Ok(vec![0u8; MAX_MODEL_BYTES + 1]))
            .expect_err("over the cap");

        match err {
            Error::InputTooLarge {
                limit,
                actual,
                what,
            } => {
                assert_eq!(limit, MAX_MODEL_BYTES);
                assert_eq!(actual, MAX_MODEL_BYTES + 1);
                assert_eq!(what, "parser_model_download");
            }
            other => panic!("expected InputTooLarge, got {other:?}"),
        }
        assert_eq!(rec.fetches, 1, "the cap fails the call, it does not retry");
    }

    /// Regression (report H6): a filesystem failure names the operation
    /// and the path. `io error: Permission denied (os error 13)` was the
    /// whole message, with the directory one line away in a variable.
    #[test]
    fn a_filesystem_failure_names_the_operation_and_the_path() {
        // A file where a directory has to be: the create fails, and it
        // fails before anything reaches the network.
        let parent = tempfile::tempdir().unwrap();
        let blocked = parent.path().join("not-a-directory");
        std::fs::write(&blocked, b"x").unwrap();
        let dir = blocked.join("models");

        let mut rec = recorder();
        let err = provision_fixture(&dir, &mut rec, &|| {
            panic!("the directory must fail before any fetch")
        })
        .expect_err("cannot create the model directory");

        assert_eq!(err.kind(), "io");
        let message = err.to_string();
        assert!(
            message.contains("create the model directory"),
            "names the operation: {message}"
        );
        assert!(
            message.contains(&dir.display().to_string()),
            "names the path: {message}"
        );
        assert_eq!(
            err.details().get("path"),
            Some(&DetailValue::Text(dir.display().to_string())),
            "the path is data, not only words in the message"
        );
    }

    /// Regression (report H3): a temporary directory left by a killed
    /// process is reclaimed. The previous sweep matched only the current
    /// process's own pid, which on a real machine never recurs, so a
    /// 15.5 MB orphan was permanent.
    #[test]
    fn an_aged_orphan_temp_directory_is_reclaimed() {
        let dir = tempfile::tempdir().unwrap();
        let orphan = dir.path().join(format!("{TEMP_DIR_PREFIX}424242"));
        std::fs::create_dir_all(&orphan).unwrap();
        std::fs::write(orphan.join("partial.udpipe"), b"half a model").unwrap();

        // The clock is a parameter so the rule is exercised without
        // touching modification times on disk.
        reclaim_stale_temp_dirs(
            dir.path(),
            SystemTime::now() + STALE_TEMP_AGE + Duration::from_secs(1),
        );

        assert!(!orphan.exists(), "an aged leftover is reclaimed");
    }

    /// The constraint on that sweep: a concurrent cold start's directory
    /// is minutes fresh, and reclaiming it would delete another live
    /// process's download. The test plants one fresh peer directory and
    /// checks that neither a direct sweep nor a full provision in the same
    /// model directory removes it. It does not race processes.
    #[test]
    fn a_live_concurrent_temp_directory_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        let peer = dir.path().join(format!("{TEMP_DIR_PREFIX}424242"));
        std::fs::create_dir_all(&peer).unwrap();
        std::fs::write(peer.join("partial.udpipe"), b"in flight").unwrap();

        reclaim_stale_temp_dirs(dir.path(), SystemTime::now());
        assert!(peer.exists(), "a fresh peer is not this call's to remove");

        // And the sweep runs on the real path too, without touching it.
        let mut rec = recorder();
        provision_fixture(dir.path(), &mut rec, &|| Ok(FIXTURE.to_vec())).unwrap();
        assert!(peer.exists(), "a download does not evict a live peer");
    }

    /// A directory whose modification time is in the future is not
    /// reclaimed. An unexplained timestamp is a reason not to delete.
    #[test]
    fn a_temp_directory_from_the_future_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        let odd = dir.path().join(format!("{TEMP_DIR_PREFIX}7"));
        std::fs::create_dir_all(&odd).unwrap();

        reclaim_stale_temp_dirs(dir.path(), SystemTime::now() - Duration::from_secs(3600));
        assert!(odd.exists());
    }

    /// The sweep only ever looks at its own names. Anything else in the
    /// model directory, including a hand-placed model, is untouched.
    #[test]
    fn the_sweep_only_matches_its_own_temporary_names() {
        let dir = tempfile::tempdir().unwrap();
        let model = dir.path().join("english-ewt-ud-2.5-191206.udpipe");
        std::fs::write(&model, b"a hand-placed model").unwrap();
        let other = dir.path().join("potion-base-8M");
        std::fs::create_dir_all(&other).unwrap();

        reclaim_stale_temp_dirs(dir.path(), SystemTime::now() + Duration::from_secs(86_400));

        assert!(model.exists(), "a model is not a temporary directory");
        assert!(other.exists(), "another model's directory is not either");
    }

    /// Every entry in `dir` whose name marks it as this module's
    /// temporary working space.
    fn leftovers(dir: &Path) -> Vec<String> {
        std::fs::read_dir(dir)
            .expect("list")
            .filter_map(Result::ok)
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .filter(|name| name.starts_with(TEMP_DIR_PREFIX))
            .collect()
    }

    #[test]
    fn a_url_yields_the_host_a_message_should_name() {
        assert_eq!(host_of(ENGLISH_MODEL_URL), "lindat.mff.cuni.cz");
        assert_eq!(host_of("https://example.org:8443/a/b?c=d"), "example.org");
        assert_eq!(host_of("https://user@example.org/a"), "example.org");
        assert_eq!(host_of("not a url"), "not a url");
    }

    /// Regression (report H5 / finding 5): a rejected certificate is a
    /// sentence naming the host, not `invalid peer certificate:
    /// Other(OtherError(CaUsedAsEndEntity))`. The raw failure is kept at
    /// the end because a bug report needs it.
    #[test]
    fn a_rejected_certificate_reads_as_a_sentence() {
        let error = ureq::Error::Io(std::io::Error::other(
            "invalid peer certificate: Other(OtherError(CaUsedAsEndEntity))",
        ));
        let message = download_message(ENGLISH_MODEL_URL, &error);

        assert!(message.contains("lindat.mff.cuni.cz"), "{message}");
        assert!(message.contains("system trust store"), "{message}");
        assert!(message.contains(ENGLISH_MODEL_FILENAME), "{message}");
        assert!(
            message.contains("CaUsedAsEndEntity"),
            "the underlying failure survives: {message}"
        );
        let mapped = transport_failure(ENGLISH_MODEL_URL, &error);
        assert_eq!(mapped.kind(), "io");
        assert_eq!(
            mapped.details().get("retryable"),
            Some(&DetailValue::Bool(false)),
            "the message says to fetch by hand, so a retry is not offered"
        );
    }

    /// A download that did not arrive says so as data (EPR-0006): its
    /// URL, and that the same call may succeed when made again, since a
    /// failed fetch writes nothing.
    #[test]
    fn a_transport_failure_is_retryable_and_names_its_url() {
        for error in [
            ureq::Error::HostNotFound,
            ureq::Error::ConnectionFailed,
            ureq::Error::Timeout(ureq::Timeout::Global),
            ureq::Error::StatusCode(503),
        ] {
            let details = transport_failure(ENGLISH_MODEL_URL, &error).details();
            assert_eq!(
                details.get("url"),
                Some(&DetailValue::Text(ENGLISH_MODEL_URL.to_string())),
                "{error}"
            );
            assert_eq!(
                details.get("retryable"),
                Some(&DetailValue::Bool(true)),
                "{error}"
            );
        }
    }

    /// A failure that is not about certificates keeps its own words.
    #[test]
    fn an_ordinary_transport_failure_is_reported_plainly() {
        let error = ureq::Error::HostNotFound;
        let message = download_message(ENGLISH_MODEL_URL, &error);
        assert!(message.starts_with("download https://lindat"), "{message}");
        assert!(!message.contains("trust store"), "{message}");

        let mapped = transport_failure(ENGLISH_MODEL_URL, &error);
        match mapped {
            Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::NotConnected),
            other => panic!("expected Io, got {other:?}"),
        }
    }

    /// Regression (review of #77): a timeout while reading the body
    /// reports `TimedOut`, which is what `site/content/reference/errors.md`
    /// and RFC-0015's decision table both promise. `ureq`'s body reader
    /// builds its `io::Error` with `Error::into_io`, which wraps
    /// everything that is not already an `io::Error` in
    /// `io::Error::other`, so reading `kind()` off it gave `Other` for
    /// every body-phase failure. The connect phase was always right;
    /// only this one was wrong.
    #[test]
    fn a_timeout_while_reading_the_body_is_reported_as_a_timeout() {
        // Exactly the shape `ureq` hands the body reader for a transfer
        // that runs past the global budget after the response begins.
        let from_ureq = std::io::Error::other(ureq::Error::Timeout(ureq::Timeout::Global));
        assert_eq!(
            from_ureq.kind(),
            std::io::ErrorKind::Other,
            "the wrapping this test exists to undo"
        );

        match body_failure(ENGLISH_MODEL_URL, from_ureq) {
            Error::Io(e) => {
                assert_eq!(e.kind(), std::io::ErrorKind::TimedOut);
                assert!(e.to_string().contains(ENGLISH_MODEL_URL), "{e}");
                assert!(e.to_string().contains("timeout"), "{e}");
            }
            other => panic!("expected Io(TimedOut), got {other:?}"),
        }
    }

    /// The other half: an `io::Error` that never was a `ureq::Error`
    /// keeps its own kind, so unwrapping costs nothing on the ordinary
    /// path.
    #[test]
    fn a_plain_body_read_failure_keeps_its_own_kind() {
        let raw = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "peer disconnected");

        match body_failure(ENGLISH_MODEL_URL, raw) {
            Error::Io(e) => {
                assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
                assert!(e.to_string().contains(ENGLISH_MODEL_URL), "{e}");
            }
            other => panic!("expected Io(UnexpectedEof), got {other:?}"),
        }
    }

    /// A mid-stream certificate rejection reaches the same sentence the
    /// connect phase gets. It used to be wrapped by hand and lost it.
    #[test]
    fn a_certificate_rejected_mid_stream_still_reads_as_a_sentence() {
        let from_ureq = std::io::Error::other(ureq::Error::Io(std::io::Error::other(
            "invalid peer certificate: Other(OtherError(CaUsedAsEndEntity))",
        )));

        match body_failure(ENGLISH_MODEL_URL, from_ureq) {
            Error::Io(e) => {
                let message = e.to_string();
                assert!(message.contains("lindat.mff.cuni.cz"), "{message}");
                assert!(message.contains("system trust store"), "{message}");
            }
            other => panic!("expected Io, got {other:?}"),
        }
    }

    /// `ureq` follows up to ten redirects, so without `https_only` an
    /// `https` URL that redirects to `http` is fetched in cleartext. The
    /// digest pin keeps that from changing which bytes load, so this is
    /// confidentiality only, and it is still not the redirect's call.
    #[test]
    fn the_download_agent_refuses_to_leave_https() {
        let agent = download_agent();
        assert!(agent.config().https_only());
        assert!(
            agent.config().max_redirects() > 0,
            "the redirect following that makes https_only load-bearing"
        );
    }

    /// Regression (review of #77): a temporary directory carrying this
    /// process's own pid may be a live peer's. In a container every
    /// process is pid 1, so two cold starts sharing a bind-mounted model
    /// directory pick the same pid, and the unconditional removal that
    /// used to precede the create deleted the peer's download.
    #[test]
    fn a_peer_temp_directory_bearing_this_pid_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        let peer = dir
            .path()
            .join(format!("{TEMP_DIR_PREFIX}{}", std::process::id()));
        std::fs::create_dir_all(&peer).unwrap();
        std::fs::write(peer.join("partial.udpipe"), b"in flight").unwrap();

        let mut rec = recorder();
        provision_fixture(dir.path(), &mut rec, &|| Ok(FIXTURE.to_vec())).unwrap();

        assert!(
            peer.exists(),
            "a fresh directory under this pid is a peer's, not this call's"
        );
        assert_eq!(
            std::fs::read(peer.join("partial.udpipe")).unwrap(),
            b"in flight"
        );
    }

    /// And the name that makes that hold: two calls in one process never
    /// choose the same temporary.
    #[test]
    fn two_temporary_names_in_one_process_differ() {
        assert_ne!(temp_stamp(), temp_stamp());
    }

    #[test]
    fn read_and_verify_returned_bytes_are_what_was_hashed() {
        // The TOCTOU-closing property: callers can use the returned bytes
        // directly. Even if an attacker swaps the file after this call,
        // the in-memory bytes (which are what the loader uses) match the
        // verified hash.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hello.bin");
        std::fs::write(&path, b"hello").unwrap();

        let bytes = read_and_verify(&path, 5, HELLO_HASH).unwrap().unwrap();

        // Simulate the attack: swap the file with different content.
        std::fs::write(&path, b"WORLD").unwrap();

        // The bytes we got are still the original "hello" — the verified ones.
        // A loader using these bytes is unaffected by the on-disk swap.
        assert_eq!(&bytes, b"hello");
    }
}