chtypes 0.1.2

ClickHouse's own type system, schema validation, DEFAULT/TTL semantics and coercion, per ClickHouse version, over the frozen chs_* C ABI
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
//! The fetch suite — `docs/guides/fetch.md` §9, against the shared miniature releases
//! in `tests/fixtures/fetch/` (generated in the core repository, never edited
//! by hand). Every fixture must produce the spec's verdict and code, through
//! the library (`chtypes::ensure`) and through the `chtypes` binary, whose exit
//! codes are §6's.
//!
//! Offline by construction: every source is a `file://` URL, and the one test
//! that names an HTTP source points at a closed port to prove it was never
//! contacted. Verdicts are read from the fixtures' own `expected.json`, so a
//! regenerated fixture set re-states what this suite must see.
//!
//! Nothing here mutates the process environment: cases that depend on
//! `CHTYPES_*` variables run the binary, or re-exec this test binary with an
//! isolated environment (`rerun`). The fixtures' libraries are a few bytes of
//! text, so a lazy registry that autofetches one ends in `Error::Load` — which
//! is exactly the proof that the fetch ran first.
//!
//! Skips are LOUD: without the fixtures every test announces itself on the
//! real stderr and returns; a suite that silently tests nothing looks exactly
//! like one that passes.

use std::path::{Path, PathBuf};
use std::process::Command;

use chtypes::fetch::{
    self, Action, EnsureOptions, LockFile, RELEASE_PUBLIC_KEY_HEX, lock_key, sha256_file,
};
use chtypes::{Error, Registry, RegistryOptions};
use serde_json::Value as Json;

/// A platform this Mac (or any dev host) has no real artifacts for, so the
/// §1 search path beyond `--dest` cannot shadow a fixture install.
/// A platform that is never this host's: the test asserts that a foreign
/// platform's search path skips `$CHTYPES_REGISTRY`, which is only true when
/// the platform really is foreign — a fixed "linux-amd64" was the host itself
/// on the amd64 CI runner and the assertion contradicted itself there.
fn foreign() -> &'static str {
    if chtypes::host_platform() == "linux-amd64" {
        "darwin-arm64"
    } else {
        "linux-amd64"
    }
}

fn announce(message: &str) {
    use std::io::Write;
    let _ = std::io::stderr().write_all(message.as_bytes());
    let _ = std::io::stderr().flush();
}

fn fixtures_dir() -> Option<PathBuf> {
    let dir = std::env::var_os("CHTYPES_FETCH_FIXTURES")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../tests/fixtures/fetch")
        });
    let dir = dir.canonicalize().unwrap_or(dir);
    if !dir.join("expected.json").is_file() {
        announce(&format!(
            "\nSKIP: no fetch fixtures at {} (tests/fixtures/fetch, generated by the core \
             repository; set $CHTYPES_FETCH_FIXTURES). This test is skipped.\n",
            dir.display()
        ));
        return None;
    }
    let fp = foreign();
    if chtypes::cache_dir_for(fp).is_dir()
        || chtypes::SYSTEM_ARTIFACT_ROOTS
            .iter()
            .any(|r| Path::new(r).join(fp).is_dir())
    {
        announce(&format!(
            "\nSKIP: this host has a {fp} artifact directory on the §1 search path, which \
             would shadow the fixture installs. This test is skipped.\n"
        ));
        return None;
    }
    Some(dir)
}

macro_rules! fixtures {
    () => {
        match fixtures_dir() {
            Some(d) => d,
            None => return,
        }
    };
}

fn expected(fx: &Path) -> Json {
    let doc: Json = serde_json::from_slice(&std::fs::read(fx.join("expected.json")).unwrap())
        .expect("expected.json parses");
    assert_eq!(doc["schema"], 1, "this suite reads expected.json schema 1");
    doc
}

fn test_key(fx: &Path) -> String {
    std::fs::read_to_string(fx.join("test-key/public.hex"))
        .expect("test-key/public.hex")
        .trim()
        .to_string()
}

fn file_url(fx: &Path, fixture: &str) -> String {
    format!("file://{}", fx.join(fixture).display())
}

fn tmp(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("chtypes-rs-fetch-{}-{name}", std::process::id()));
    std::fs::remove_dir_all(&dir).ok();
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn opts(fx: &Path, fixture: &str, dest: &Path) -> EnsureOptions {
    EnsureOptions {
        dest: Some(dest.to_path_buf()),
        platform: Some(foreign().into()),
        url: Some(file_url(fx, fixture)),
        trusted_keys: Some(vec![test_key(fx)]),
        allow_unsigned: Some(false),
        ..Default::default()
    }
}

fn index_row(index: &Json, platform: &str, minor: &str) -> Json {
    let (os, arch) = platform.split_once('-').unwrap();
    index["artifacts"]
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["os"] == os && r["arch"] == arch && r["clickhouse_minor"] == minor)
        .cloned()
        .unwrap_or_else(|| panic!("no index row for {platform}/{minor}"))
}

fn signed_index(fx: &Path) -> Json {
    serde_json::from_slice(&std::fs::read(fx.join("signed/index.json")).unwrap()).unwrap()
}

/// Every `expected.json` verdict, through the library. The proof of an
/// install is the installed library hashing to what the release's index
/// recorded — never the `Ok`.
#[test]
fn every_fixture_verdict_matches_expected_json_through_ensure() {
    let fx = fixtures!();
    let doc = expected(&fx);
    let verdicts = doc["verdicts"].as_array().unwrap();
    assert!(!verdicts.is_empty(), "expected.json lists no verdicts");
    let mut checked = 0;
    for v in verdicts {
        let fixture = v["fixture"].as_str().unwrap();
        let dest = tmp(&format!("ensure-{fixture}-{}", checked));
        let mut o = opts(&fx, fixture, &dest);
        o.trusted_keys = Some(vec![match v["trusted_keys"].as_str().unwrap() {
            "test" => test_key(&fx),
            "release" => RELEASE_PUBLIC_KEY_HEX.to_string(),
            other => panic!("unknown trusted_keys spelling {other:?}"),
        }]);
        o.allow_unsigned = Some(v["allow_unsigned"].as_bool().unwrap());
        let ctx = format!("{fixture} ({})", v["why"]);
        match (fetch::ensure("25.8", &o), v["code"].as_str()) {
            (Ok(installed), None) => {
                assert_eq!(installed.action, Action::Installed, "{ctx}");
                assert_eq!(installed.line, "25.8", "{ctx}");
                assert_eq!(installed.dir, dest.join("25.8"), "{ctx}");
                let row = index_row(&signed_index(&fx), foreign(), "25.8");
                assert_eq!(installed.version, row["clickhouse_version"], "{ctx}");
                assert_eq!(
                    installed.library,
                    dest.join("25.8").join(row["library"].as_str().unwrap()),
                    "{ctx}"
                );
                assert_eq!(
                    sha256_file(&installed.library).unwrap(),
                    row["library_sha256"].as_str().unwrap(),
                    "{ctx}: the installed library must hash as the index says"
                );
                assert_eq!(installed.library_sha256, row["library_sha256"], "{ctx}");
                assert_eq!(
                    installed
                        .asset
                        .as_ref()
                        .map(|(f, s)| (f.as_str(), s.as_str())),
                    Some((
                        row["file"].as_str().unwrap(),
                        row["sha256"].as_str().unwrap()
                    )),
                    "{ctx}"
                );
                for extra in ["manifest.json", "CH_VERSION", "unsafe_families.txt"] {
                    assert!(
                        dest.join("25.8").join(extra).is_file(),
                        "{ctx}: {extra} missing"
                    );
                }
                // Nothing but the line was left behind: no temp sibling, no tarball.
                let leftovers: Vec<String> = std::fs::read_dir(&dest)
                    .unwrap()
                    .filter_map(|e| e.ok())
                    .map(|e| e.file_name().to_string_lossy().into_owned())
                    .filter(|n| n != "25.8")
                    .collect();
                assert!(leftovers.is_empty(), "{ctx}: leftovers {leftovers:?}");
            }
            (Err(err), Some(code)) => {
                assert_eq!(err.artifact_code(), Some(code), "{ctx}: got {err}");
                assert!(
                    !dest.join("25.8").exists(),
                    "{ctx}: a refused fetch must install nothing"
                );
                assert!(
                    std::fs::read_dir(&dest).map(|d| d.count()).unwrap_or(0) == 0,
                    "{ctx}: a refused fetch must leave nothing behind"
                );
            }
            (Ok(_), Some(code)) => panic!("{ctx}: installed, but the spec says {code}"),
            (Err(err), None) => panic!("{ctx}: the spec says installs, got {err}"),
        }
        checked += 1;
        std::fs::remove_dir_all(&dest).ok();
    }
    assert_eq!(checked, verdicts.len());
}

/// §6: `ensure` is idempotent, and installed-and-verified never touches the
/// network — proven with a source at a closed port.
#[test]
fn installed_and_verified_downloads_nothing_and_offline_reads_no_source() {
    let fx = fixtures!();
    let dest = tmp("idempotent");
    let first = fetch::ensure("25.8", &opts(&fx, "signed", &dest)).unwrap();
    assert_eq!(first.action, Action::Installed);

    // §3: installed and hashing what the signed release says — the three
    // small files are read, the tarball is not (docs/guides/fetch.md, Decisions).
    let again = fetch::ensure("25.8", &opts(&fx, "signed", &dest)).unwrap();
    assert_eq!(again.action, Action::AlreadyInstalled);
    assert_eq!(again.dir, first.dir);
    assert_eq!(again.library_sha256, first.library_sha256);
    assert!(again.asset.is_some(), "the release was consulted");

    // Without a reachable source there is no signed listing to check an
    // install against: SOURCE_UNREACHABLE, never a silent local pass.
    let dead = EnsureOptions {
        url: Some("http://127.0.0.1:1/never".into()),
        ..opts(&fx, "signed", &dest)
    };
    let err = fetch::ensure("25.8", &dead).unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_SOURCE_UNREACHABLE"),
        "{err}"
    );

    // --offline is the one no-source path: an installed line verified against
    // its own manifest is the answer.
    let offline = EnsureOptions {
        offline: true,
        ..dead.clone()
    };
    let local = fetch::ensure("25.8", &offline).unwrap();
    assert_eq!(local.action, Action::AlreadyInstalled);
    assert_eq!(local.asset, None, "no release was consulted");
    // An exact patch that IS installed is satisfied the same way; one that is
    // not is a hard requirement and would need the source.
    assert_eq!(
        fetch::ensure("25.8.28.1-lts", &offline).unwrap().action,
        Action::AlreadyInstalled
    );
    let other = fetch::ensure("25.8.30.16-lts", &offline).unwrap_err();
    assert_eq!(
        other.artifact_code(),
        Some("CHTYPES_SOURCE_UNREACHABLE"),
        "{other}"
    );

    // --force re-downloads, which the dead source cannot serve.
    let forced = EnsureOptions {
        force: true,
        ..dead.clone()
    };
    let err = fetch::ensure("25.8", &forced).unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_SOURCE_UNREACHABLE"),
        "{err}"
    );
    assert!(
        err.to_string().contains("127.0.0.1:1"),
        "the message names the source: {err}"
    );
    // The failed forced fetch left the good install alone.
    assert_eq!(sha256_file(&first.library).unwrap(), first.library_sha256);

    // --force against the real fixture replaces in place.
    let forced_ok = EnsureOptions {
        force: true,
        ..opts(&fx, "signed", &dest)
    };
    assert_eq!(
        fetch::ensure("25.8", &forced_ok).unwrap().action,
        Action::Replaced
    );
    std::fs::remove_dir_all(&dest).ok();
}

/// §3: a present-but-corrupt install is replaced when the source is there,
/// and reported as CORRUPT — never used — when it is not.
#[test]
fn a_corrupt_install_is_replaced_or_reported_never_trusted() {
    let fx = fixtures!();
    let dest = tmp("corrupt");
    let first = fetch::ensure("25.8", &opts(&fx, "signed", &dest)).unwrap();
    std::fs::write(&first.library, b"not the library any more").unwrap();

    let offline = EnsureOptions {
        offline: true,
        ..opts(&fx, "signed", &dest)
    };
    let err = fetch::ensure("25.8", &offline).unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_ARTIFACT_CORRUPT"),
        "{err}"
    );

    let bad: Vec<_> = fetch::verify_installed(&dest)
        .into_iter()
        .filter(|v| v.result.is_err())
        .map(|v| v.line)
        .collect();
    assert_eq!(
        bad,
        vec!["25.8".to_string()],
        "verify must name the corrupt line"
    );

    let replaced = fetch::ensure("25.8", &opts(&fx, "signed", &dest)).unwrap();
    assert_eq!(replaced.action, Action::Replaced);
    assert_eq!(
        sha256_file(&replaced.library).unwrap(),
        first.library_sha256
    );
    assert!(
        fetch::verify_installed(&dest)
            .iter()
            .all(|v| v.result.is_ok())
    );
    std::fs::remove_dir_all(&dest).ok();
}

/// §2: what the release does not publish is UNPUBLISHED — the line, the
/// platform, and an exact patch (a hard requirement, never nearest-matched).
#[test]
fn unpublished_lines_platforms_and_patches_are_refused() {
    let fx = fixtures!();
    let doc = expected(&fx);
    let u = &doc["unpublished"];
    let code = u["code"].as_str().unwrap();
    let dest = tmp("unpublished");
    let base = opts(&fx, "signed", &dest);

    for (what, o) in [
        ("line", fetch::ensure(u["line"].as_str().unwrap(), &base)),
        ("patch", fetch::ensure(u["patch"].as_str().unwrap(), &base)),
        (
            "platform",
            fetch::ensure(
                "25.8",
                &EnsureOptions {
                    platform: Some(u["platform"].as_str().unwrap().into()),
                    ..base.clone()
                },
            ),
        ),
    ] {
        let err = o.unwrap_err();
        assert_eq!(err.artifact_code(), Some(code), "{what}: {err}");
        assert!(
            matches!(err, Error::ArtifactUnpublished { .. }),
            "{what}: {err:?}"
        );
    }
    // The exact patch that IS published installs; spelled without its
    // channel it still does; `v` is tolerated.
    let row = index_row(&signed_index(&fx), foreign(), "25.8");
    let exact = row["clickhouse_version"].as_str().unwrap();
    assert_eq!(fetch::ensure(exact, &base).unwrap().version, exact);
    let bare = exact.rsplit_once('-').map(|(b, _)| b).unwrap_or(exact);
    assert_eq!(fetch::ensure(bare, &base).unwrap().version, exact);
    assert_eq!(
        fetch::ensure(&format!("v{exact}"), &base).unwrap().version,
        exact
    );
    assert!(fetch::ensure("latest", &base).is_err());
    std::fs::remove_dir_all(&dest).ok();
}

/// §5: `--lock` records what was installed; `--frozen` refuses anything else
/// with PINNED — a drifted sha256, a renamed asset, or an unpinned line.
#[test]
fn the_lock_file_records_and_frozen_refuses_drift() {
    let fx = fixtures!();
    let dest = tmp("lock");
    let lock_path = dest.join("new.lock");

    // Record.
    let o = EnsureOptions {
        lock: Some(lock_path.clone()),
        ..opts(&fx, "signed", &dest)
    };
    let installed = fetch::ensure("25.8", &o).unwrap();
    let lock = LockFile::load(&lock_path, true).unwrap();
    let key = lock_key(foreign(), "25.8");
    let (file, sha) = installed.asset.clone().unwrap();
    assert_eq!(lock.artifacts[&key].file, file);
    assert_eq!(lock.artifacts[&key].sha256, sha);
    assert_eq!(lock.schema, 1);
    // What it records is exactly the fixtures' own lock for this row.
    let spec_lock = LockFile::load(&fx.join("chtypes.lock"), true).unwrap();
    assert_eq!(spec_lock.artifacts[&key], lock.artifacts[&key]);

    // Frozen with the fixtures' lock: installs (here: already installed, and
    // the release is consulted so the pin is checked).
    let frozen = EnsureOptions {
        lock: Some(fx.join("chtypes.lock")),
        frozen: true,
        ..opts(&fx, "signed", &dest)
    };
    assert_eq!(
        fetch::ensure("25.8", &frozen).unwrap().action,
        Action::AlreadyInstalled
    );
    let fresh = tmp("lock-fresh");
    let frozen_fresh = EnsureOptions {
        dest: Some(fresh.clone()),
        ..frozen.clone()
    };
    assert_eq!(
        fetch::ensure("26.7", &frozen_fresh).unwrap().action,
        Action::Installed
    );

    // A copy whose sha256 differs: PINNED, and nothing installed.
    let drifted = dest.join("drift.lock");
    let text = std::fs::read_to_string(fx.join("chtypes.lock")).unwrap();
    assert!(text.contains(&sha), "the spec lock pins this row");
    std::fs::write(&drifted, text.replace(&sha, &"0".repeat(64))).unwrap();
    let scratch = tmp("lock-drift");
    let err = fetch::ensure(
        "25.8",
        &EnsureOptions {
            dest: Some(scratch.clone()),
            lock: Some(drifted.clone()),
            frozen: true,
            ..opts(&fx, "signed", &dest)
        },
    )
    .unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_ARTIFACT_PINNED"),
        "{err}"
    );
    assert!(!scratch.join("25.8").exists());

    // A lock without the line: PINNED too (frozen refuses anything unpinned).
    let sparse = dest.join("sparse.lock");
    std::fs::write(&sparse, r#"{"schema":1,"artifacts":{}}"#).unwrap();
    let err = fetch::ensure(
        "25.8",
        &EnsureOptions {
            lock: Some(sparse),
            frozen: true,
            ..opts(&fx, "signed", &dest)
        },
    )
    .unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_ARTIFACT_PINNED"),
        "{err}"
    );

    // Frozen needs a lock that exists.
    let err = fetch::ensure(
        "25.8",
        &EnsureOptions {
            lock: Some(dest.join("absent.lock")),
            frozen: true,
            ..opts(&fx, "signed", &dest)
        },
    )
    .unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_ARTIFACT_PINNED"),
        "no lock file pins nothing: {err}"
    );

    for d in [dest, fresh, scratch] {
        std::fs::remove_dir_all(&d).ok();
    }
}

/// `--offline` answers SOURCE_UNREACHABLE before any connection is attempted:
/// a closed port would say "connection refused"; offline says "offline".
#[test]
fn offline_is_source_unreachable_without_touching_the_network() {
    let dest = tmp("offline");
    for url in [Some("http://127.0.0.1:1/never".to_string()), None] {
        let err = fetch::ensure(
            "25.8",
            &EnsureOptions {
                dest: Some(dest.clone()),
                platform: Some(foreign().into()),
                url,
                offline: true,
                ..Default::default()
            },
        )
        .unwrap_err();
        assert_eq!(
            err.artifact_code(),
            Some("CHTYPES_SOURCE_UNREACHABLE"),
            "{err}"
        );
        assert!(matches!(err, Error::SourceUnreachable { .. }));
        assert!(err.to_string().contains("offline"), "{err}");
        assert!(!err.to_string().contains("refused"), "{err}");
    }
    std::fs::remove_dir_all(&dest).ok();
}

/// `--all`: every line the release publishes for the platform, each verified.
#[test]
fn ensure_all_installs_every_published_line() {
    let fx = fixtures!();
    let doc = expected(&fx);
    let dest = tmp("all");
    let installed = fetch::ensure_all(&opts(&fx, "signed", &dest)).unwrap();
    let mut lines: Vec<String> = installed.iter().map(|i| i.line.clone()).collect();
    lines.sort();
    let mut want: Vec<String> = doc["lines"].as_object().unwrap().keys().cloned().collect();
    want.sort();
    assert_eq!(lines, want);
    for i in &installed {
        assert_eq!(i.action, Action::Installed);
        assert_eq!(i.version, doc["lines"][&i.line]);
        assert_eq!(sha256_file(&i.library).unwrap(), i.library_sha256);
    }
    // A second pass confirms rather than re-downloads.
    let again = fetch::ensure_all(&opts(&fx, "signed", &dest)).unwrap();
    assert!(again.iter().all(|i| i.action == Action::AlreadyInstalled));
    // The listing is the same release, signed by the test key.
    let info = fetch::release_info(&opts(&fx, "signed", &dest)).unwrap();
    assert_eq!(info.signed_by.as_deref(), doc["key_id"].as_str());
    assert_eq!(info.license, "Elastic-2.0");
    assert_eq!(
        info.artifacts.len(),
        signed_index(&fx)["artifacts"].as_array().unwrap().len()
    );
    std::fs::remove_dir_all(&dest).ok();
}

/// §7 through the search-path registry: a line found nowhere is
/// `Error::ArtifactMissing`, the message verbatim, naming every directory.
#[test]
fn a_search_path_registry_reports_a_missing_line_with_the_spec_message() {
    let dest = tmp("missing");
    let reg = Registry::from_search_path_with(RegistryOptions {
        dir: Some(dest.clone()),
        autofetch: Some(false),
        ..Default::default()
    });
    assert!(!reg.autofetch());
    assert_eq!(reg.search_path()[0], dest);
    assert_eq!(reg.dir(), dest, "fetch writes to the explicit directory");
    assert!(
        reg.libraries().is_empty(),
        "nothing is loaded until asked for"
    );

    let err = reg.for_version("99.9").unwrap_err();
    let Error::ArtifactMissing {
        line,
        platform,
        looked_in,
    } = &err
    else {
        panic!("expected ArtifactMissing, got {err:?}");
    };
    assert_eq!(line, "99.9");
    assert_eq!(platform, &chtypes::host_platform());
    assert_eq!(looked_in, reg.search_path());
    assert_eq!(err.artifact_code(), Some("CHTYPES_ARTIFACT_MISSING"));
    let dirs: Vec<String> = looked_in.iter().map(|d| d.display().to_string()).collect();
    assert_eq!(
        err.to_string(),
        format!(
            "chtypes: no artifact for ClickHouse 99.9 ({platform}). Looked in: {}.\n\
             Install it:  cargo install chtypes && chtypes fetch 99.9\n\
             or set CHTYPES_AUTOFETCH=1 to fetch on first use.",
            dirs.join(", ")
        )
    );
    // An exact patch that is missing reports its line.
    let err = reg.for_version("99.9.1.1-lts").unwrap_err();
    assert!(matches!(err, Error::ArtifactMissing { ref line, .. } if line == "99.9"));
    std::fs::remove_dir_all(&dest).ok();
}

/// The search path itself, `docs/guides/fetch.md` §1, in order.
#[test]
fn the_search_path_is_the_spec_s_order() {
    let explicit = PathBuf::from("/explicit/reg");
    let path = chtypes::registry_search_path(Some(&explicit));
    let host = chtypes::host_platform();
    assert_eq!(path[0], explicit);
    let tail: Vec<PathBuf> = path[path.len() - 2..].to_vec();
    assert_eq!(
        tail,
        vec![
            PathBuf::from("/usr/local/share/chtypes/artifacts").join(&host),
            PathBuf::from("/opt/chtypes/artifacts").join(&host),
        ]
    );
    assert!(path.contains(&chtypes::default_registry_dir()));
    assert_eq!(chtypes::install_dir(Some(&explicit)), explicit);
    // A foreign platform never sees $CHTYPES_REGISTRY, and installs in its own cache.
    let fpath = chtypes::search_path_for(foreign(), None);
    assert_eq!(fpath[0], chtypes::cache_dir_for(foreign()));
    assert_eq!(
        chtypes::install_dir_for(foreign(), None),
        chtypes::cache_dir_for(foreign())
    );
    assert!(fpath.iter().all(|p| p.ends_with(foreign())));
}

// ------------------------------------------------------------ the binary

fn bin() -> Command {
    let mut c = Command::new(env!("CARGO_BIN_EXE_chtypes"));
    c.env_remove("CHTYPES_REGISTRY")
        .env_remove("CHTYPES_TRUSTED_KEYS")
        .env_remove("CHTYPES_ALLOW_UNSIGNED")
        .env_remove("CHTYPES_ARTIFACTS_URL")
        .env_remove("CHTYPES_AUTOFETCH")
        .env_remove("CHTYPES_DOWNLOAD_TOKEN");
    c
}

struct Run {
    code: i32,
    stdout: String,
    stderr: String,
}

fn run(mut c: Command) -> Run {
    let out = c.output().expect("the chtypes binary runs");
    Run {
        code: out.status.code().expect("an exit code, not a signal"),
        stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
    }
}

/// Every `expected.json` verdict through the binary: exit code, the code
/// string on stderr, the installed directory alone on stdout — and the
/// environment variables (`CHTYPES_TRUSTED_KEYS`, `CHTYPES_ALLOW_UNSIGNED`)
/// doing what §4 says.
#[test]
fn the_binary_matches_every_verdict_and_exit_code() {
    let fx = fixtures!();
    let doc = expected(&fx);
    let cache = tmp("bin-cache");
    let platform = doc["platforms"][0].as_str().unwrap();
    let mut checked = 0;
    for v in doc["verdicts"].as_array().unwrap() {
        let fixture = v["fixture"].as_str().unwrap();
        let dest = tmp(&format!("bin-{fixture}-{checked}"));
        let mut c = bin();
        c.args(["fetch", "25.8", "--platform", platform, "--dest"])
            .arg(&dest)
            .arg("--url")
            .arg(file_url(&fx, fixture))
            .env("XDG_CACHE_HOME", &cache);
        match v["trusted_keys"].as_str().unwrap() {
            "test" => {
                c.env("CHTYPES_TRUSTED_KEYS", test_key(&fx));
            }
            "release" => {} // the embedded key, nothing set
            other => panic!("unknown trusted_keys spelling {other:?}"),
        }
        if v["allow_unsigned"].as_bool().unwrap() {
            c.env("CHTYPES_ALLOW_UNSIGNED", "1");
        }
        let r = run(c);
        let ctx = format!("{fixture} ({}): stderr:\n{}", v["why"], r.stderr);
        assert_eq!(r.code, v["exit"].as_i64().unwrap() as i32, "{ctx}");
        match v["code"].as_str() {
            None => {
                assert_eq!(
                    r.stdout.trim_end(),
                    dest.join("25.8").display().to_string(),
                    "{ctx}: stdout is the installed directory alone"
                );
                let row = index_row(&signed_index(&fx), platform, "25.8");
                assert_eq!(
                    sha256_file(&dest.join("25.8").join(row["library"].as_str().unwrap())).unwrap(),
                    row["library_sha256"].as_str().unwrap(),
                    "{ctx}"
                );
                if v["allow_unsigned"].as_bool().unwrap() {
                    let warnings: Vec<&str> =
                        r.stderr.lines().filter(|l| l.contains("WARNING")).collect();
                    assert_eq!(warnings.len(), 1, "{ctx}: exactly one loud warning");
                    assert!(
                        warnings[0].contains(&file_url(&fx, fixture)),
                        "{ctx}: the warning names the source"
                    );
                } else {
                    assert!(!r.stderr.contains("WARNING"), "{ctx}");
                    assert!(
                        r.stderr.contains(doc["key_id"].as_str().unwrap()),
                        "{ctx}: progress names the key that verified"
                    );
                }
            }
            Some(code) => {
                assert!(
                    r.stdout.is_empty(),
                    "{ctx}: nothing on stdout: {:?}",
                    r.stdout
                );
                assert!(r.stderr.contains(code), "{ctx}: stderr carries {code}");
                assert!(!dest.join("25.8").exists(), "{ctx}: nothing installed");
            }
        }
        checked += 1;
        std::fs::remove_dir_all(&dest).ok();
    }
    assert_eq!(checked, doc["verdicts"].as_array().unwrap().len());
    std::fs::remove_dir_all(&cache).ok();
}

#[test]
fn the_binary_s_other_exit_codes_and_commands() {
    let fx = fixtures!();
    let doc = expected(&fx);
    let cache = tmp("bin2-cache");
    let dest = tmp("bin2-dest");
    let platform = doc["platforms"][0].as_str().unwrap();
    let key = test_key(&fx);
    let signed = file_url(&fx, "signed");

    // 4: unpublished (line, patch, platform).
    let u = &doc["unpublished"];
    for args in [
        vec!["fetch", u["line"].as_str().unwrap(), "--platform", platform],
        vec![
            "fetch",
            u["patch"].as_str().unwrap(),
            "--platform",
            platform,
        ],
        vec![
            "fetch",
            "25.8",
            "--platform",
            u["platform"].as_str().unwrap(),
        ],
    ] {
        let mut c = bin();
        c.args(&args)
            .arg("--dest")
            .arg(&dest)
            .arg("--url")
            .arg(&signed);
        c.env("CHTYPES_TRUSTED_KEYS", &key)
            .env("XDG_CACHE_HOME", &cache);
        let r = run(c);
        assert_eq!(
            r.code,
            u["exit"].as_i64().unwrap() as i32,
            "{args:?}: {}",
            r.stderr
        );
        assert!(
            r.stderr.contains(u["code"].as_str().unwrap()),
            "{args:?}: {}",
            r.stderr
        );
        assert!(r.stdout.is_empty());
    }

    // 3: unreachable — offline (no connection attempted) and a closed port.
    for extra in [vec!["--offline"], vec!["--url", "http://127.0.0.1:1/never"]] {
        let mut c = bin();
        c.args(["fetch", "25.8", "--platform", platform, "--dest"])
            .arg(&dest)
            .args(&extra)
            .env("XDG_CACHE_HOME", &cache);
        let r = run(c);
        assert_eq!(r.code, 3, "{extra:?}: {}", r.stderr);
        assert!(
            r.stderr.contains("CHTYPES_SOURCE_UNREACHABLE"),
            "{}",
            r.stderr
        );
    }

    // 2: usage.
    for args in [
        vec![],
        vec!["fetch"],
        vec!["fetch", "latest"],
        vec!["fetch", "25.8", "--bogus"],
        vec!["fetch", "25.8", "--tag", "v1", "--url", "x"],
        vec!["fetch", "25.8", "--all"],
        vec!["fetch", "25.8", "--platform", "plan9-mips"],
        vec!["fetch", "25.8", "--dest"],
        vec!["frobnicate"],
    ] {
        let mut c = bin();
        c.args(&args).env("XDG_CACHE_HOME", &cache);
        let r = run(c);
        assert_eq!(r.code, 2, "{args:?}: {}", r.stderr);
        assert!(r.stdout.is_empty(), "{args:?}");
    }

    // A bad spelling among several lines is refused before ANY fetch.
    let mut c = bin();
    c.args(["fetch", "25.8", "nope", "--platform", platform, "--dest"])
        .arg(&dest)
        .arg("--url")
        .arg(&signed)
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 2, "{}", r.stderr);
    assert!(
        !dest.join("25.8").exists(),
        "nothing was fetched before the usage error"
    );

    // where: the explicit dir, else $CHTYPES_REGISTRY, else the cache; never a
    // system location. The directory is alone on the FIRST line — the
    // scriptable contract — and the served golden set follows it.
    let first = |s: String| s.lines().next().unwrap_or_default().to_string();
    let mut c = bin();
    c.args(["where", "--dest"]).arg(&dest);
    assert_eq!(first(run(c).stdout), dest.display().to_string());
    let mut c = bin();
    c.arg("where")
        .env("CHTYPES_REGISTRY", "/some/registry")
        .env("XDG_CACHE_HOME", &cache);
    assert_eq!(first(run(c).stdout), "/some/registry");
    let mut c = bin();
    c.arg("where").env("XDG_CACHE_HOME", &cache);
    assert_eq!(
        first(run(c).stdout),
        cache
            .join("chtypes/artifacts")
            .join(chtypes::host_platform())
            .display()
            .to_string()
    );

    // "Already installed" is the search path without --dest, and dest alone
    // with it: a line in the (isolated) cache satisfies a plain fetch, but a
    // fetch that names a destination installs there.
    let mut c = bin();
    c.args(["fetch", "26.7", "--platform", platform, "--url"])
        .arg(&signed)
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 0, "{}", r.stderr);
    let in_cache = cache.join("chtypes/artifacts").join(platform).join("26.7");
    assert_eq!(r.stdout.trim_end(), in_cache.display().to_string());
    assert!(in_cache.join("manifest.json").is_file());
    let mut c = bin();
    c.args(["fetch", "26.7", "--platform", platform, "--url"])
        .arg(&signed)
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(
        r.code, 0,
        "installed in the cache satisfies a plain fetch: {}",
        r.stderr
    );
    assert!(r.stderr.contains("already installed"), "{}", r.stderr);
    // --offline is the no-source path: the cached line answers with no URL
    // reachable at all (docs/guides/fetch.md, Decisions).
    let mut c = bin();
    c.args([
        "fetch",
        "26.7",
        "--platform",
        platform,
        "--offline",
        "--url",
    ])
    .arg("http://127.0.0.1:1/never")
    .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 0, "offline, installed in the cache: {}", r.stderr);
    assert!(r.stderr.contains("already installed"), "{}", r.stderr);
    let elsewhere = tmp("bin2-elsewhere");
    let mut c = bin();
    c.args(["fetch", "26.7", "--platform", platform, "--dest"])
        .arg(&elsewhere)
        .arg("--url")
        .arg(&signed)
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 0, "{}", r.stderr);
    assert_eq!(
        r.stdout.trim_end(),
        elsewhere.join("26.7").display().to_string(),
        "--dest is where the line must be, whatever the cache holds"
    );
    assert!(elsewhere.join("26.7/manifest.json").is_file());
    assert!(!r.stderr.contains("already installed"), "{}", r.stderr);
    std::fs::remove_dir_all(&elsewhere).ok();

    // fetch two lines, --lock, then --frozen against the fixtures' lock.
    let lock = dest.join("chtypes.lock");
    let mut c = bin();
    c.args(["fetch", "25.8", "26.7", "--platform", platform, "--dest"])
        .arg(&dest)
        .arg("--url")
        .arg(&signed)
        .arg("--lock")
        .arg(&lock)
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 0, "{}", r.stderr);
    assert_eq!(
        r.stdout.lines().collect::<Vec<_>>(),
        vec![
            dest.join("25.8").display().to_string(),
            dest.join("26.7").display().to_string()
        ]
    );
    let written = LockFile::load(&lock, true).unwrap();
    let spec_lock = LockFile::load(&fx.join("chtypes.lock"), true).unwrap();
    for minor in ["25.8", "26.7"] {
        let k = lock_key(platform, minor);
        assert_eq!(written.artifacts[&k], spec_lock.artifacts[&k], "{k}");
    }
    let mut c = bin();
    c.args(["fetch", "--all", "--platform", platform, "--dest"])
        .arg(&dest)
        .arg("--url")
        .arg(&signed)
        .arg("--lock")
        .arg(fx.join("chtypes.lock"))
        .arg("--frozen")
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 0, "{}", r.stderr);
    assert_eq!(r.stdout.lines().count(), 2);

    // A drifted lock: exit 1, PINNED.
    let drifted = dest.join("drift.lock");
    let text = std::fs::read_to_string(fx.join("chtypes.lock")).unwrap();
    let row = index_row(&signed_index(&fx), platform, "25.8");
    std::fs::write(
        &drifted,
        text.replace(row["sha256"].as_str().unwrap(), &"0".repeat(64)),
    )
    .unwrap();
    let scratch = tmp("bin2-drift");
    let mut c = bin();
    c.args(["fetch", "25.8", "--platform", platform, "--dest"])
        .arg(&scratch)
        .arg("--url")
        .arg(&signed)
        .arg("--lock")
        .arg(&drifted)
        .arg("--frozen")
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 1, "{}", r.stderr);
    assert!(r.stderr.contains("CHTYPES_ARTIFACT_PINNED"), "{}", r.stderr);
    assert!(r.stdout.is_empty());

    // verify: ok, then a flipped byte is CORRUPT with exit 1.
    let mut c = bin();
    c.args(["verify", "--platform", platform, "--dest"])
        .arg(&dest)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 0, "{}", r.stderr);
    assert_eq!(
        r.stdout.lines().filter(|l| l.starts_with("ok ")).count(),
        2,
        "{}",
        r.stdout
    );
    std::fs::write(
        dest.join("26.7").join(row["library"].as_str().unwrap()),
        b"flipped",
    )
    .unwrap();
    let mut c = bin();
    c.args(["verify", "--platform", platform, "--dest"])
        .arg(&dest)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 1, "{}", r.stderr);
    assert_eq!(
        r.stdout
            .lines()
            .filter(|l| l.starts_with("CORRUPT "))
            .count(),
        1,
        "{}",
        r.stdout
    );
    assert!(r.stdout.contains("26.7"));

    // list: installed lines, then the release, signed by the test key.
    let mut c = bin();
    c.args(["list", "--platform", platform, "--dest"])
        .arg(&dest)
        .arg("--url")
        .arg(&signed)
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 0, "{}", r.stderr);
    assert!(r.stdout.contains("installed"), "{}", r.stdout);
    assert!(
        r.stdout.contains(doc["key_id"].as_str().unwrap()),
        "{}",
        r.stdout
    );
    assert!(r.stdout.contains("(installed)"), "{}", r.stdout);
    // list refuses an untrusted listing exactly as fetch would.
    let mut c = bin();
    c.args(["list", "--platform", platform, "--dest"])
        .arg(&dest)
        .arg("--url")
        .arg(file_url(&fx, "bad-signature"))
        .env("CHTYPES_TRUSTED_KEYS", &key)
        .env("XDG_CACHE_HOME", &cache);
    let r = run(c);
    assert_eq!(r.code, 1, "{}", r.stderr);
    assert!(
        r.stderr.contains("CHTYPES_ARTIFACT_UNTRUSTED"),
        "{}",
        r.stderr
    );

    for d in [cache, dest, scratch] {
        std::fs::remove_dir_all(&d).ok();
    }
}

// ------------------------------------------------- autofetch, re-executed

/// Run one `inner_*` test of this binary in an isolated environment and
/// return its output. The inner test is a no-op unless `CHTYPES_TEST_INNER`
/// is set, so the outer suite never runs it directly.
fn rerun(inner: &str, envs: &[(&str, &str)]) -> Run {
    let mut c = Command::new(std::env::current_exe().unwrap());
    c.args(["--exact", inner, "--nocapture", "--test-threads=1"]);
    c.env_remove("CHTYPES_REGISTRY")
        .env_remove("CHTYPES_TRUSTED_KEYS")
        .env_remove("CHTYPES_ALLOW_UNSIGNED")
        .env_remove("CHTYPES_ARTIFACTS_URL")
        .env_remove("CHTYPES_AUTOFETCH")
        .env("CHTYPES_TEST_INNER", "1");
    for (k, v) in envs {
        c.env(k, v);
    }
    run(c)
}

fn inner() -> bool {
    std::env::var_os("CHTYPES_TEST_INNER").is_some()
}

/// §6: with `CHTYPES_AUTOFETCH=1` (and, equally, the registry option),
/// opening a missing line runs `ensure` first. The fixtures' libraries do not
/// `dlopen`, so success here is `Error::Load` AFTER the line has been
/// installed — and a refused fetch is attempted once per process per line.
#[test]
fn inner_autofetch_runs_ensure_once_per_line() {
    if !inner() {
        return;
    }
    let fx = PathBuf::from(std::env::var("CHTYPES_FETCH_FIXTURES").unwrap());
    let dest = PathBuf::from(std::env::var("CHTYPES_TEST_DEST").unwrap());
    let key = test_key(&fx);

    // 1. The environment variable alone: URL, key and autofetch all from env.
    let reg = Registry::from_search_path_with(RegistryOptions {
        dir: Some(dest.clone()),
        ..Default::default()
    });
    assert!(reg.autofetch(), "CHTYPES_AUTOFETCH=1 turns it on");
    assert!(!dest.join("25.8").exists());
    let err = reg.for_version("25.8").unwrap_err();
    assert!(
        matches!(err, Error::Load { .. }),
        "the fixture was fetched and then failed to dlopen (it is text): {err:?}"
    );
    assert!(
        dest.join("25.8/manifest.json").is_file(),
        "autofetch installed the line"
    );
    let installed_at = std::fs::metadata(dest.join("25.8/manifest.json"))
        .unwrap()
        .modified()
        .unwrap();
    // A second open finds it on disk and does not fetch again.
    let err = reg.for_version("25.8").unwrap_err();
    assert!(matches!(err, Error::Load { .. }), "{err:?}");
    assert_eq!(
        std::fs::metadata(dest.join("25.8/manifest.json"))
            .unwrap()
            .modified()
            .unwrap(),
        installed_at,
        "no re-fetch of an installed line"
    );

    // 2. The registry option with explicit fetch options, against a release
    //    that is refused: the fetch error surfaces once, then the guard.
    let reg = Registry::from_search_path_with(RegistryOptions {
        dir: Some(dest.clone()),
        autofetch: Some(true),
        fetch: EnsureOptions {
            url: Some(file_url(&fx, "unsigned")),
            trusted_keys: Some(vec![key.clone()]),
            allow_unsigned: Some(false),
            ..Default::default()
        },
        ..Default::default()
    });
    let err = reg.for_version("26.7").unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_ARTIFACT_UNTRUSTED"),
        "{err}"
    );
    assert!(!dest.join("26.7").exists());
    let err = reg.for_version("26.7").unwrap_err();
    assert_eq!(
        err.artifact_code(),
        Some("CHTYPES_ARTIFACT_MISSING"),
        "once per process per line: the second open does not fetch again: {err}"
    );

    // 3. Autofetch off: the §7 error, and nothing fetched.
    let reg = Registry::from_search_path_with(RegistryOptions {
        dir: Some(dest.clone()),
        autofetch: Some(false),
        ..Default::default()
    });
    let err = reg.for_version("99.9").unwrap_err();
    assert_eq!(err.artifact_code(), Some("CHTYPES_ARTIFACT_MISSING"));
    println!("INNER-OK autofetch");
}

#[test]
fn autofetch_runs_ensure_once_per_line() {
    let fx = fixtures!();
    let cache = tmp("autofetch-cache");
    let dest = tmp("autofetch-dest");
    // $CHTYPES_ARTIFACTS_URL names a HOST; the rolling tag `artifacts` is
    // appended (§2). A host directory whose `artifacts/` is the signed
    // fixture stands in for artifacts.wavehouse.dev.
    let host = tmp("autofetch-host");
    std::os::unix::fs::symlink(fx.join("signed"), host.join("artifacts")).unwrap();
    let r = rerun(
        "inner_autofetch_runs_ensure_once_per_line",
        &[
            ("XDG_CACHE_HOME", cache.to_str().unwrap()),
            ("CHTYPES_AUTOFETCH", "1"),
            (
                "CHTYPES_ARTIFACTS_URL",
                &format!("file://{}", host.display()),
            ),
            ("CHTYPES_TRUSTED_KEYS", &test_key(&fx)),
            ("CHTYPES_FETCH_FIXTURES", fx.to_str().unwrap()),
            ("CHTYPES_TEST_DEST", dest.to_str().unwrap()),
        ],
    );
    assert_eq!(r.code, 0, "inner run failed:\n{}\n{}", r.stdout, r.stderr);
    assert!(r.stdout.contains("INNER-OK autofetch"), "{}", r.stdout);
    assert!(
        r.stdout.contains("test result: ok. 1 passed"),
        "{}",
        r.stdout
    );
    for d in [cache, dest, host] {
        std::fs::remove_dir_all(&d).ok();
    }
}

// --------------------------------------------- a real registry, if present

/// The lazy registry over a real artifact directory: nothing loads until a
/// line is asked for, then exactly that line. Skips without artifacts.
#[test]
fn a_search_path_registry_opens_one_line_lazily() {
    let dir = match std::env::var_os(chtypes::REGISTRY_ENV) {
        Some(d) => PathBuf::from(d),
        None => chtypes::default_registry_dir(),
    };
    let lines = chtypes::installed_lines(std::slice::from_ref(&dir));
    let Some((line, _)) = lines.first() else {
        announce(&format!(
            "\nSKIP a_search_path_registry_opens_one_line_lazily: no installed artifact under {} \
             — fetch one with scripts/fetch.sh 25.8 (docs/guides/fetch.md)\n",
            dir.display()
        ));
        return;
    };
    let reg = Registry::from_search_path_with(RegistryOptions {
        dir: Some(dir.clone()),
        autofetch: Some(false),
        ..Default::default()
    });
    assert!(reg.libraries().is_empty());
    assert!(
        reg.versions().contains(line),
        "versions() lists what is installed: {:?}",
        reg.versions()
    );
    let lib = reg.for_version(line).unwrap();
    assert_eq!(lib.minor(), line);
    assert_eq!(
        reg.libraries().len(),
        1,
        "exactly the line asked for is loaded"
    );
    let again = reg.for_version(lib.version()).unwrap();
    assert!(
        std::sync::Arc::ptr_eq(&lib, &again),
        "the exact patch resolves to the same load"
    );
    assert_eq!(reg.libraries().len(), 1);
}

/// `expected.json`'s `builds.cases`, against the `two-builds/` fixture: one
/// ClickHouse version published twice, which is the shape a rebuild leaves
/// behind and the shape the live release has carried since builds existed.
///
/// Resolving a line is therefore not a question about the ClickHouse version
/// alone — among rows of the newest version the highest build wins. Until this,
/// nothing in any of the four suites covered that; the rule was pinned only by
/// unit tests of the comparator itself.
///
/// The proof is the installed library's own bytes. Both rows carry the same
/// `clickhouse_version`, so a manifest check cannot separate them; their
/// `library_sha256` differs. An implementation that took the first matching row,
/// or the older build, fails here instead of passing quietly.
#[test]
fn a_rebuild_installs_the_highest_build() {
    let fx = fixtures!();
    let doc = expected(&fx);
    let cases = doc["builds"]["cases"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    assert!(
        !cases.is_empty(),
        "expected.json carries no builds.cases — regenerate the fixtures \
         from the release pipeline"
    );

    let index: Json = serde_json::from_slice(
        &std::fs::read(fx.join("two-builds").join("index.json")).expect("two-builds/index.json"),
    )
    .expect("two-builds/index.json parses");
    let row_for = |file: &str| -> Json {
        index["artifacts"]
            .as_array()
            .unwrap()
            .iter()
            .find(|a| a["file"] == file)
            .unwrap_or_else(|| panic!("two-builds/index.json has no row for {file}"))
            .clone()
    };

    for (i, c) in cases.iter().enumerate() {
        let platform = c["platform"].as_str().unwrap();
        let line = c["line"].as_str().unwrap();
        let ctx = format!("{platform} {line}");
        let want = row_for(c["install"]["file"].as_str().unwrap());
        let other = row_for(c["superseded"]["file"].as_str().unwrap());

        // The fixture must actually pose the question: same version, two builds.
        assert_eq!(
            want["clickhouse_version"], other["clickhouse_version"],
            "{ctx}: the two rows are different versions, so this proves nothing about builds"
        );
        let (wb, ob) = (
            want["build"].as_u64().unwrap_or(0),
            other["build"].as_u64().unwrap_or(0),
        );
        assert!(wb > ob, "{ctx}: the fixture's own case is upside down");

        let dest = tmp(&format!("two-builds-{i}"));
        let mut o = opts(&fx, "two-builds", &dest);
        o.platform = Some(platform.to_string());
        let installed = fetch::ensure(line, &o).unwrap_or_else(|e| panic!("{ctx}: {e}"));

        let on_disk = sha256_file(&installed.library).expect("hash the installed library");
        assert_eq!(
            on_disk,
            want["library_sha256"].as_str().unwrap(),
            "{ctx}: installed library is not build {wb}"
        );
        assert_ne!(
            on_disk,
            other["library_sha256"].as_str().unwrap(),
            "{ctx}: the SUPERSEDED build {ob} is what landed"
        );
    }
}