lumen-format 1.0.0

Reference encoder, decoder and validator for the LUMEN resin print file format (v1.0)
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
//! Conformance against the corpus in `test-vectors/`.
//!
//! Three things are checked, and they are different claims:
//!
//! 1. **The validator agrees with the corpus.** Every valid vector passes at both
//!    levels, and every invalid vector fails the check its manifest entry names -
//!    and fails *that* check first, which is what the corpus's `expected_failure`
//!    contract means. Vectors marked `strict_only` must pass a loose read and fail
//!    a strict one.
//! 2. **The decoder agrees with the encoder that wrote the corpus.** The golden
//!    values in `manifest.json` - chunk layout, the `LAYR` chunk set, the `LTBL`
//!    entries, per-layer hashes and Merkle root, the decompressed bytes of every
//!    layer - are recomputed from this crate's own parse of the same files.
//! 3. **The layer pipeline agrees with the corpus' resolved timing.** For every
//!    valid vector and every sampled `(layer, sector)` point its manifest entry
//!    records, [`LumenFile::timing_for`] reproduces all sixteen numbers the
//!    manifest pins: the `META` base values, the sector substitutions, the bottom
//!    and transition blending, the `(layer, sector)`'s own `LROV` payload, and
//!    the absent-field defaults of section 4.2. Those expectations were written
//!    by the corpus generator, not by this crate.
//!
//! The corpus is generated by `make_vectors` and checked by
//! `verify_vectors`, which share no code. Agreement here is therefore evidence
//! about the specification, not self-consistency: three independent readings of
//! the spec now produce the same bytes.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use lumen::check::Check;
use lumen::container::{self, ChunkType};
use lumen::crypto::{self, SessionKey};
use lumen::reader::LumenFile;
use lumen::validate::{self, Level};
use serde::Deserialize;
use sha2::{Digest, Sha256};

#[derive(Deserialize)]
struct Manifest {
    valid: Vec<ValidEntry>,
    invalid: Vec<InvalidEntry>,
}

#[derive(Deserialize)]
struct ValidEntry {
    name: String,
    file: String,
    file_size: u64,
    file_sha256: String,
    chunk_count: u32,
    dir_offset: u64,
    header_flags: u32,
    total_uncompressed_size: u64,
    trailer_crc32c: String,
    display_width_px: u32,
    display_height_px: u32,
    layer_height_um: u32,
    total_layers: u32,
    multi_sector: bool,
    /// One record per `LAYR` chunk, in directory order.
    layr_chunks: Vec<LayrChunkRecord>,
    /// One record per `LTBL` entry, in table order.
    ltbl: Vec<LtblRecord>,
    dict: DictRecord,
    layers: Vec<LayerRecord>,
    merkle_root: String,
    #[serde(default)]
    crypto: Option<CryptoRecord>,
    /// The pipeline values the corpus records for a sample of `(layer, sector)`
    /// points, sorted by `(layer, sector)`.
    ///
    /// Defaulted so that a manifest written before the corpus carried resolved
    /// timing still parses, and the claim it belongs to can say what is missing;
    /// [`resolved_timing_matches_the_manifest`] refuses to pass on an absent or
    /// empty list, so the default is never a way of checking nothing.
    #[serde(default)]
    resolved_timing: Vec<ResolvedTimingPoint>,
}

/// One `(layer, sector)` point of [`ValidEntry::resolved_timing`].
#[derive(Deserialize)]
struct ResolvedTimingPoint {
    layer: u32,
    sector: u32,
    layer_height_um: u32,
    exposure_ms: u32,
    light_pwm: u32,
    lift_slow_distance_um: u32,
    lift_slow_speed_um_min: u32,
    lift_fast_distance_um: u32,
    lift_fast_speed_um_min: u32,
    retract_fast_distance_um: u32,
    retract_fast_speed_um_min: u32,
    retract_slow_distance_um: u32,
    retract_slow_speed_um_min: u32,
    wait_time_before_cure_ms: u32,
    wait_time_after_cure_ms: u32,
    wait_time_after_lift_ms: u32,
}

/// One `LAYR` chunk as the corpus' encoder planned it and wrote it.
#[derive(Deserialize)]
struct LayrChunkRecord {
    /// Directory index, which is what an `LTBL` entry names.
    index: u32,
    /// The sector whose masks the chunk holds.
    sector_id: u32,
    /// The first layer the chunk spans.
    first_layer: u32,
    /// How many layers it spans.
    layer_count: u32,
    version: u32,
    /// The dictionary the frame reports, `0` when it used none.
    dict_id: u32,
    /// The output length the frame declares.
    content_size: u64,
    /// The stored frame's bytes, AEAD framing included when it is sealed.
    frame_size: u64,
    /// The container's byte length, which is the descriptor's
    /// `size_uncompressed`.
    stored_len: u64,
    sealed: bool,
}

/// One `LTBL` entry.
#[derive(Deserialize)]
struct LtblRecord {
    entry_index: u32,
    layer: u32,
    sector_id: u32,
    data_size: u32,
    first_lrov: u32,
    first_layr: u32,
    additional_sector_count: u32,
    data_offset: u64,
}

#[derive(Deserialize)]
struct DictRecord {
    present: bool,
    dict_id: u32,
    dict_size: u32,
}

/// One layer, as the corpus records it.
#[derive(Deserialize)]
struct LayerRecord {
    index: u32,
    /// Whether every entry of the layer carries no data.
    empty: bool,
    /// How many `LTBL` entries the layer has, sector 0's included.
    sector_count: u32,
    /// The tag of the layer's sector 0 slice, or `null` when it holds no data.
    #[serde(default)]
    tag: Option<u8>,
    /// The tag of each entry's slice, in table order, `null` for an entry with
    /// no data.
    #[serde(default)]
    sector_tags: Vec<Option<u8>>,
    /// SHA-256 of the layer's slices concatenated in ascending `sector_id`.
    decompressed_sha256: String,
    lhas_leaf: String,
}

#[derive(Deserialize)]
struct CryptoRecord {
    cipher_id: String,
    auth_version: u32,
    mode: u32,
    #[serde(default)]
    password_utf8: Option<String>,
    #[serde(default)]
    local_recipient_private_key: Option<String>,
}

#[derive(Deserialize)]
struct InvalidEntry {
    name: String,
    file: String,
    /// The valid vector this one was derived from, when it has one. The corpus
    /// writes `null` for a vector built from scratch, and the field is the only
    /// route to the credentials of an encrypted base.
    #[serde(default)]
    base_vector: Option<String>,
    /// The credentials of an encrypted vector built from scratch: a vector with
    /// no base carries its own, and without it a keyed read has no key.
    #[serde(default)]
    crypto: Option<CryptoRecord>,
    expected_failure: String,
    #[serde(default)]
    strict_only: bool,
    file_sha256: String,
}

fn vectors_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test-vectors")
}

/// Load the corpus.
///
/// The corpus ships with the *specification*, not with this crate. A run from a
/// published `.crate` therefore has nothing to check - and it says so by failing,
/// rather than passing without checking anything.
fn load() -> (Manifest, PathBuf) {
    let dir = vectors_dir();
    let text = std::fs::read_to_string(dir.join("manifest.json")).unwrap_or_else(|_| {
        panic!(
            "no conformance corpus at {}.\n\
             The corpus lives beside the specification, not inside this crate: run these tests \
             from a checkout of https://github.com/Open-Resin-Alliance/LumenFormat.\n\
             Verifying a published .crate in isolation cannot establish conformance, so this \
             test refuses to pass on the strength of not having looked.",
            dir.display()
        )
    });
    (
        serde_json::from_str(&text).expect("the corpus manifest must parse"),
        dir,
    )
}

fn sha256_hex(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex::encode(hasher.finalize())
}

fn hex_bytes32(text: &str) -> [u8; 32] {
    let mut out = [0u8; 32];
    hex::decode_to_slice(text, &mut out).expect("a 32-byte hex value");
    out
}

/// Recover the session key a vector's `crypto` block describes.
///
/// Returns `None` when there is no key to recover. That is not a failure: some
/// invalid vectors deliberately damage the `AUTH` chunk - an unknown cipher, an
/// empty mode - so their named check is reported without one, which is the point
/// of those vectors.
fn session_key(bytes: &[u8], crypto: &CryptoRecord) -> Option<SessionKey> {
    let header = container::FileHeader::parse(bytes).ok()?;
    let directory = container::parse_directory(bytes, &header).ok()?;
    let descriptor = directory.find(ChunkType::AUTH)?;
    let payload = &bytes
        [descriptor.offset as usize..descriptor.offset as usize + descriptor.stored_len() as usize];
    let auth = crypto::parse_auth(payload).ok()?;
    if let Some(password) = crypto.password_utf8.as_deref() {
        return crypto::unwrap_password(&auth, password).ok();
    }
    let private = crypto.local_recipient_private_key.as_deref()?;
    crypto::unwrap_machine(&auth, &hex_bytes32(private)).ok()
}

/// Open a valid vector through the public reader.
///
/// `key` is the one [`session_key`] recovered, passed in rather than derived
/// again here: recovering it costs an Argon2 run, and every caller wants the
/// same file.
fn open_vector<'a>(
    name: &str,
    bytes: &'a [u8],
    entry: &ValidEntry,
    key: Option<SessionKey>,
) -> LumenFile<'a> {
    match entry.crypto.as_ref() {
        None => LumenFile::open(bytes, Level::Strict),
        Some(crypto_record) => {
            let key = key.unwrap_or_else(|| panic!("{name}: an encrypted vector has a key"));
            match crypto_record.password_utf8.as_deref() {
                Some(password) => LumenFile::open_with_password(bytes, Level::Strict, password),
                None => {
                    let private = hex_bytes32(
                        crypto_record
                            .local_recipient_private_key
                            .as_deref()
                            .expect("a recipient key"),
                    );
                    LumenFile::open_with_machine_key(bytes, Level::Strict, &private)
                        .or_else(|_| LumenFile::open_with_key(bytes, Level::Strict, key))
                }
            }
        }
    }
    .unwrap_or_else(|e| panic!("{name}: opening must succeed: {e}"))
}

/// The stored bytes of one layer, read back through the public reader: its
/// sectors' slices, concatenated in ascending `sector_id`.
fn layer_data(file: &LumenFile<'_>, index: usize) -> Vec<u8> {
    let mut out = Vec::new();
    for entry in file.layer_table().layer_entries(index as u32) {
        if entry.is_empty() {
            continue;
        }
        let chunk = file
            .layr_chunk_data(entry.first_layr)
            .unwrap_or_else(|e| panic!("layer {index}: chunk {} must read: {e}", entry.first_layr));
        let start = entry.data_offset as usize;
        out.extend_from_slice(&chunk[start..start + entry.data_size as usize]);
    }
    out
}

/// The first byte of one `LTBL` entry's slice, which is its REE tag.
fn slice_tag(file: &LumenFile<'_>, entry: &lumen::chunks::ltbl::LayerEntry) -> Option<u8> {
    if entry.is_empty() {
        return None;
    }
    let chunk = file
        .layr_chunk_data(entry.first_layr)
        .expect("a readable chunk");
    Some(chunk[entry.data_offset as usize])
}

/// The layer whose entries begin at `index`, walking the table's own chain.
fn layer_of(table: &lumen::chunks::ltbl::LayerTable, index: usize) -> u32 {
    let mut cursor = 0usize;
    let mut layer = 0u32;
    // Walk to the last layer whose entries begin at or before `index`: an entry
    // that is not a layer's first still belongs to the layer that started before
    // it, so the loop must not step past `index` and count another layer.
    while cursor + 1 + table.entries[cursor].additional_sector_count as usize <= index {
        cursor += 1 + table.entries[cursor].additional_sector_count as usize;
        layer += 1;
    }
    layer
}

/// The plaintext frame of the `LAYR` chunk at directory index `index`.
fn frame_of(bytes: &[u8], file: &LumenFile<'_>, index: u32, key: Option<&SessionKey>) -> Vec<u8> {
    let descriptor = &file.directory().descriptors[index as usize];
    assert_eq!(
        descriptor.chunk_type,
        ChunkType::LAYR,
        "directory index {index} is a LAYR chunk"
    );
    let start = descriptor.offset as usize;
    let stored = &bytes[start..start + descriptor.stored_len() as usize];
    let frame = lumen::chunks::layr::frame(stored).expect("a LAYR container");
    if !descriptor.is_encrypted() {
        return frame.to_vec();
    }
    // The frame is the sealed unit, and its associated data binds it to the
    // chunk's directory index rather than to slot zero.
    let cipher = file.auth().expect("a sealed file carries AUTH").cipher;
    let key = key.expect("a readable sealed vector has a key");
    lumen::crypto::open(cipher, key, ChunkType::LAYR, index, frame)
        .expect("the frame authenticates under its directory index")
}

#[test]
fn valid_vectors_pass_and_match_golden_data() {
    let (manifest, dir) = load();
    assert!(!manifest.valid.is_empty(), "the corpus has valid vectors");

    for entry in &manifest.valid {
        let bytes = std::fs::read(dir.join(&entry.file)).expect("a readable vector");
        let name = &entry.name;

        assert_eq!(bytes.len() as u64, entry.file_size, "{name}: file size");
        assert_eq!(sha256_hex(&bytes), entry.file_sha256, "{name}: file hash");

        // A loose and a strict read both accept it, with and without a key: the
        // checks that need decrypted content simply do not run without one.
        validate::validate(&bytes, Level::Loose)
            .unwrap_or_else(|e| panic!("{name}: a loose read must accept it: {e}"));
        validate::validate(&bytes, Level::Strict)
            .unwrap_or_else(|e| panic!("{name}: a strict read must accept it: {e}"));

        let key = entry.crypto.as_ref().and_then(|c| session_key(&bytes, c));
        if let Some(key) = key {
            validate::validate_with_key(&bytes, Level::Strict, key)
                .unwrap_or_else(|e| panic!("{name}: unlocking must accept it: {e}"));
        }

        let file = open_vector(name, &bytes, entry, key);

        // Container goldens.
        if let Some(crypto_record) = entry.crypto.as_ref() {
            let auth = file.auth().expect("an encrypted vector carries AUTH");
            assert_eq!(
                String::from_utf8_lossy(&auth.cipher.id()),
                crypto_record.cipher_id,
                "{name}: cipher_id"
            );
            assert_eq!(
                auth.auth_version, crypto_record.auth_version,
                "{name}: auth_version"
            );
            assert_eq!(auth.mode, crypto_record.mode, "{name}: AUTH mode");
        }
        assert_eq!(
            file.header().chunk_count,
            entry.chunk_count,
            "{name}: chunk count"
        );
        assert_eq!(
            file.header().dir_offset,
            entry.dir_offset,
            "{name}: dir offset"
        );
        assert_eq!(
            file.header().flags,
            entry.header_flags,
            "{name}: header flags"
        );
        assert_eq!(
            file.header().total_uncompressed_size,
            entry.total_uncompressed_size,
            "{name}: total uncompressed size"
        );
        assert_eq!(
            container::parse_trailer(&bytes).unwrap(),
            u32::from_str_radix(entry.trailer_crc32c.trim_start_matches("0x"), 16).unwrap(),
            "{name}: trailer CRC-32C"
        );
        assert_eq!(
            file.head().display_width_px,
            entry.display_width_px,
            "{name}: width"
        );
        assert_eq!(
            file.head().display_height_px,
            entry.display_height_px,
            "{name}: height"
        );
        assert_eq!(
            file.head().layer_height_um,
            entry.layer_height_um,
            "{name}: layer height"
        );
        assert_eq!(
            file.layer_count(),
            entry.total_layers,
            "{name}: layer count"
        );
        assert_eq!(
            file.multi_sector(),
            entry.multi_sector,
            "{name}: multi-sector flag"
        );

        // LAYR goldens: one chunk per (sector, layer group) that holds data.
        assert_eq!(
            file.layr_chunks().len(),
            entry.layr_chunks.len(),
            "{name}: LAYR chunk count"
        );
        for (k, chunk) in entry.layr_chunks.iter().enumerate() {
            let got = file.layr_chunks()[k];
            assert_eq!(got.index, chunk.index, "{name}: LAYR chunk {k} index");
            let descriptor = &file.directory().descriptors[chunk.index as usize];
            assert_eq!(
                descriptor.stored_len(),
                chunk.stored_len,
                "{name}: LAYR chunk {k} stored length"
            );
            assert_eq!(
                descriptor.is_encrypted(),
                chunk.sealed,
                "{name}: LAYR chunk {k} sealed bit"
            );
            let frame = frame_of(&bytes, &file, chunk.index, key.as_ref());
            assert_eq!(
                frame.len() as u64,
                chunk.frame_size - if chunk.sealed { 28 } else { 0 },
                "{name}: LAYR chunk {k} frame size"
            );
            assert_eq!(
                lumen::chunks::frame_content_size(&frame).expect("a frame with its content size"),
                chunk.content_size,
                "{name}: LAYR chunk {k} content size"
            );
            assert_eq!(
                lumen::chunks::frame_dict_id(&frame).expect("a frame header"),
                chunk.dict_id,
                "{name}: LAYR chunk {k} dictionary ID"
            );
            assert_eq!(
                lumen::chunks::layr::parse(
                    &bytes[descriptor.offset as usize
                        ..descriptor.offset as usize + descriptor.stored_len() as usize]
                )
                .expect("a LAYR container")
                .1,
                chunk.version,
                "{name}: LAYR chunk {k} version"
            );

            // The plan the manifest records must be what the table says: this
            // chunk holds one slice of each layer in its range, all for one
            // sector.
            let holders: Vec<(usize, &lumen::chunks::ltbl::LayerEntry)> = file
                .layer_table()
                .entries
                .iter()
                .enumerate()
                .filter(|(_, e)| e.first_layr == chunk.index)
                .collect();
            // A chunk's frame covers a run of layers, and only the layers in that
            // run which carry data for its sector contribute a slice: a layer with
            // nothing to store in this sector has no entry pointing here. A chunk
            // no entry points into is therefore allowed, but it must then carry
            // nothing - an empty frame for a group with no data in this sector.
            if holders.is_empty() {
                assert_eq!(
                    chunk.content_size, 0,
                    "{name}: LAYR chunk {k} holds no slice yet carries {} bytes",
                    chunk.content_size
                );
            }
            assert!(
                holders.len() as u64 <= u64::from(chunk.layer_count),
                "{name}: LAYR chunk {k} holds {} slices for a range of {} layers",
                holders.len(),
                chunk.layer_count
            );
            assert!(
                holders.iter().all(|(_, e)| e.sector_id == chunk.sector_id),
                "{name}: LAYR chunk {k} holds only sector {}",
                chunk.sector_id
            );
            for (position, _) in holders {
                let layer = layer_of(file.layer_table(), position);
                assert!(
                    (chunk.first_layer..chunk.first_layer + chunk.layer_count).contains(&layer),
                    "{name}: LAYR chunk {k} names layer {layer} outside {}..{}",
                    chunk.first_layer,
                    chunk.first_layer + chunk.layer_count
                );
            }
        }

        // LTBL goldens: one entry per (layer, sector), in table order.
        assert_eq!(
            file.layer_table().entries.len(),
            entry.ltbl.len(),
            "{name}: LTBL entry count"
        );
        assert_eq!(
            file.layer_table().entry_count,
            entry.ltbl.len() as u32,
            "{name}: LTBL header entry_count"
        );
        assert_eq!(
            file.layer_table().layer_count,
            entry.total_layers,
            "{name}: LTBL layer count"
        );
        for (i, golden) in entry.ltbl.iter().enumerate() {
            assert_eq!(golden.entry_index as usize, i, "{name}: entry {i} index");
            let got = &file.layer_table().entries[i];
            assert_eq!(got.sector_id, golden.sector_id, "{name}: entry {i} sector");
            assert_eq!(got.data_size, golden.data_size, "{name}: entry {i} size");
            assert_eq!(
                got.first_lrov, golden.first_lrov,
                "{name}: entry {i} overrides"
            );
            assert_eq!(got.first_layr, golden.first_layr, "{name}: entry {i} chunk");
            assert_eq!(
                got.additional_sector_count, golden.additional_sector_count,
                "{name}: entry {i} further entries"
            );
            assert_eq!(
                got.data_offset, golden.data_offset,
                "{name}: entry {i} offset"
            );
            assert_eq!(
                layer_of(file.layer_table(), i),
                golden.layer,
                "{name}: entry {i} belongs to layer {}",
                golden.layer
            );
        }

        // Dictionary goldens.
        assert_eq!(
            file.dictionary().is_some(),
            entry.dict.present,
            "{name}: dictionary presence"
        );
        if let Some(dictionary) = file.dictionary() {
            assert_eq!(
                dictionary.dict_id, entry.dict.dict_id,
                "{name}: dictionary ID"
            );
            assert_eq!(
                dictionary.dict_bytes.len(),
                entry.dict.dict_size as usize,
                "{name}: dictionary size"
            );
        }

        // Per-layer goldens: the data this reader reconstructs must be the data
        // the corpus' encoder wrote.
        for layer in &entry.layers {
            let index = layer.index as usize;
            let entries = file.layer_table().layer_entries(layer.index);
            assert_eq!(
                entries.len(),
                layer.sector_count as usize,
                "{name}: layer {index} entry count"
            );
            assert_eq!(
                entries.iter().all(|e| e.is_empty()),
                layer.empty,
                "{name}: layer {index} empty"
            );
            assert_eq!(
                entries.first().and_then(|e| slice_tag(&file, e)),
                layer.tag,
                "{name}: layer {index} sector 0 tag"
            );
            if !layer.sector_tags.is_empty() {
                let tags: Vec<Option<u8>> = entries.iter().map(|e| slice_tag(&file, e)).collect();
                assert_eq!(tags, layer.sector_tags, "{name}: layer {index} sector tags");
            }
            let data = layer_data(&file, index);
            assert_eq!(
                sha256_hex(&data),
                layer.decompressed_sha256,
                "{name}: layer {index} decompressed bytes"
            );
            let mut hasher = Sha256::new();
            hasher.update([0u8]);
            hasher.update(&data);
            assert_eq!(
                hex::encode(hasher.finalize()),
                layer.lhas_leaf,
                "{name}: layer {index} leaf hash"
            );
        }

        // Integrity tree, and the whole-file verification path.
        let hashes = file.layer_hashes().expect("the corpus vectors carry LHAS");
        assert_eq!(
            hex::encode(hashes.merkle_root),
            entry.merkle_root,
            "{name}: Merkle root"
        );
        file.verify_all()
            .unwrap_or_else(|e| panic!("{name}: verify_all must accept a valid file: {e}"));

        // Timing resolves for every layer of every sector without error.
        for index in 0..file.layer_count() {
            let sector_ids: Vec<u32> = if file.multi_sector() {
                file.layer_sectors(index)
                    .unwrap_or_else(|e| panic!("{name}: layer {index} sectors: {e}"))
                    .into_iter()
                    .map(|s| s.sector_id)
                    .collect()
            } else {
                vec![0]
            };
            for sector_id in sector_ids {
                file.timing_for(index, sector_id)
                    .unwrap_or_else(|e| panic!("{name}: layer {index} sector {sector_id}: {e}"));
            }
        }
    }
}

/// The pipeline this crate owes a file is the pipeline the corpus records.
///
/// A conforming reader resolves `(layer, sector)` timing from the `META` base
/// values, the sector's `META.sectors` substitutions, the bottom and transition
/// blending, the `(layer, sector)`'s own `LROV` payload, and the absent-field
/// defaults of section 4.2. For every valid vector, every point the manifest
/// samples - each branch of the pipeline: bottom layers, the first transition
/// step, the first fully-normal layer, every override boundary and its
/// neighbours, and every sector with an entry or an override - must come out
/// of [`LumenFile::timing_for`] as the generator computed it. The expectations
/// are the generator's, not this crate's.
#[test]
fn resolved_timing_matches_the_manifest() {
    let (manifest, dir) = load();
    let mut checked = 0usize;

    for entry in &manifest.valid {
        let bytes = std::fs::read(dir.join(&entry.file)).expect("a readable vector");
        let name = &entry.name;
        let key = entry.crypto.as_ref().and_then(|c| session_key(&bytes, c));
        let file = open_vector(name, &bytes, entry, key);

        // The sampling rule always yields at least `(0, 0)`, so a vector with no
        // points records nothing to check and must not pass unnoticed.
        assert!(
            !entry.resolved_timing.is_empty(),
            "{name}: the manifest records resolved timing for every valid vector"
        );

        for point in &entry.resolved_timing {
            let (layer, sector) = (point.layer, point.sector);
            let resolved = file.timing_for(layer, sector).unwrap_or_else(|e| {
                panic!("{name}: layer {layer} sector {sector} must resolve: {e}")
            });

            // Every pinned field, `<field>`, expected from the manifest and
            // produced by this crate.
            let fields = [
                (
                    "layer_height_um",
                    point.layer_height_um,
                    resolved.layer_height_um,
                ),
                ("exposure_ms", point.exposure_ms, resolved.exposure_ms),
                ("light_pwm", point.light_pwm, resolved.light_pwm),
                (
                    "lift_slow_distance_um",
                    point.lift_slow_distance_um,
                    resolved.lift_slow_distance_um,
                ),
                (
                    "lift_slow_speed_um_min",
                    point.lift_slow_speed_um_min,
                    resolved.lift_slow_speed_um_min,
                ),
                (
                    "lift_fast_distance_um",
                    point.lift_fast_distance_um,
                    resolved.lift_fast_distance_um,
                ),
                (
                    "lift_fast_speed_um_min",
                    point.lift_fast_speed_um_min,
                    resolved.lift_fast_speed_um_min,
                ),
                (
                    "retract_fast_distance_um",
                    point.retract_fast_distance_um,
                    resolved.retract_fast_distance_um,
                ),
                (
                    "retract_fast_speed_um_min",
                    point.retract_fast_speed_um_min,
                    resolved.retract_fast_speed_um_min,
                ),
                (
                    "retract_slow_distance_um",
                    point.retract_slow_distance_um,
                    resolved.retract_slow_distance_um,
                ),
                (
                    "retract_slow_speed_um_min",
                    point.retract_slow_speed_um_min,
                    resolved.retract_slow_speed_um_min,
                ),
                (
                    "wait_time_before_cure_ms",
                    point.wait_time_before_cure_ms,
                    resolved.wait_time_before_cure_ms,
                ),
                (
                    "wait_time_after_cure_ms",
                    point.wait_time_after_cure_ms,
                    resolved.wait_time_after_cure_ms,
                ),
                (
                    "wait_time_after_lift_ms",
                    point.wait_time_after_lift_ms,
                    resolved.wait_time_after_lift_ms,
                ),
            ];
            for (field, expected, actual) in fields {
                assert_eq!(
                    actual, expected,
                    "{name}: layer {layer} sector {sector}: {field}"
                );
            }
            checked += 1;
        }
    }

    // The claim is exercised, and by how much, rather than vacuously true.
    assert!(checked > 0, "the corpus records resolved timing to check");
}

#[test]
fn invalid_vectors_fail_the_check_they_pin() {
    let (manifest, dir) = load();
    assert!(
        !manifest.invalid.is_empty(),
        "the corpus has invalid vectors"
    );

    let valid: HashMap<&str, &ValidEntry> = manifest
        .valid
        .iter()
        .map(|v| (v.name.as_str(), v))
        .collect();

    for entry in &manifest.invalid {
        let bytes = std::fs::read(dir.join(&entry.file)).expect("a readable vector");
        let name = &entry.name;
        assert_eq!(sha256_hex(&bytes), entry.file_sha256, "{name}: file hash");
        if check_by_name(&entry.expected_failure).is_none() {
            panic!("{name}: unknown expected check {}", entry.expected_failure);
        }
        let crypto_record = entry.crypto.as_ref().or_else(|| {
            entry
                .base_vector
                .as_deref()
                .and_then(|base| valid.get(base).copied())
                .and_then(|base| base.crypto.as_ref())
        });
        let key = crypto_record.and_then(|record| session_key(&bytes, record));

        // A reader that holds the key verifies AEAD tags in both modes: an
        // unauthenticated payload is not a strict-only defect.
        let check = |level: Level| match key {
            Some(key) => validate::validate_with_key(&bytes, level, key),
            None => validate::validate(&bytes, level),
        };

        if entry.strict_only {
            // The defect is invisible to a loose reader, and the corpus says so.
            if let Err(e) = check(Level::Loose) {
                panic!("{name}: a loose read must accept it, got {e}");
            }
        } else {
            let err = check(Level::Loose)
                .err()
                .unwrap_or_else(|| panic!("{name}: a loose read must reject it"));
            assert_eq!(
                err.check_name(),
                entry.expected_failure,
                "{name}: failed check"
            );
        }

        let err = check(Level::Strict)
            .err()
            .unwrap_or_else(|| panic!("{name}: a strict read must reject it"));
        assert_eq!(
            err.check_name(),
            entry.expected_failure,
            "{name}: failed check"
        );
    }
}

/// Look a check up by its corpus name.
///
/// Built from a table rather than by scanning [`Check`], because the enum is
/// deliberately non-exhaustive and has no reflection.
fn check_by_name(name: &str) -> Option<Check> {
    const NAMES: &[(&str, Check)] = &[
        ("trailer.magic", Check::TrailerMagic),
        ("trailer.crc32c", Check::TrailerCrc32c),
        ("header.flags_reserved", Check::HeaderFlagsReserved),
        ("presence.auth", Check::PresenceAuth),
        ("presence.zdic", Check::PresenceZdic),
        ("presence.ltbl", Check::PresenceLtbl),
        ("auth.cipher_known", Check::AuthCipherKnown),
        ("crypt.mode_empty", Check::CryptModeEmpty),
        ("crypt.password_section_len", Check::CryptPasswordSectionLen),
        ("crypt.machine_section_len", Check::CryptMachineSectionLen),
        ("crypt.argon2_budget", Check::CryptArgon2Budget),
        ("crypt.chunk_flags", Check::CryptChunkFlags),
        ("crypt.tag_verify", Check::CryptTagVerify),
        ("crypt.unit_index_binding", Check::CryptUnitIndexBinding),
        ("meta.time_integer", Check::MetaTimeInteger),
        ("pwm.range", Check::PwmRange),
        ("meta.sectors_shape", Check::MetaSectorsShape),
        ("meta.sector_material_index", Check::MetaSectorMaterialIndex),
        ("prof.profile_type", Check::ProfProfileType),
        ("prof.profile_identity", Check::ProfProfileIdentity),
        ("prof.settings_time_integer", Check::ProfSettingsTimeInteger),
        ("prof.settings_exposure", Check::ProfSettingsExposure),
        ("prof.settings_layer_height", Check::ProfSettingsLayerHeight),
        ("prof.cure_curve", Check::ProfCureCurve),
        ("prof.profile_uuid", Check::ProfProfileUuid),
        ("prof.materials_shape", Check::ProfMaterialsShape),
        ("lrov.json", Check::LrovJson),
        ("lrov.time_integer", Check::LrovTimeInteger),
        ("lrov.orphan", Check::LrovOrphan),
        ("prev.flags", Check::PrevFlags),
        ("prev.png_signature", Check::PrevPngSignature),
        ("voxl.signature", Check::VoxlSignature),
        ("extd.frame", Check::ExtdFrame),
        ("extd.ext_type", Check::ExtdExtType),
        ("extd.flags", Check::ExtdFlags),
        ("extd.critical", Check::ExtdCritical),
        ("ltbl.version", Check::LtblVersion),
        ("ltbl.layer_count", Check::LtblLayerCount),
        ("ltbl.entry_size", Check::LtblEntrySize),
        ("ltbl.entry_count", Check::LtblEntryCount),
        ("ltbl.layer_index_range", Check::LtblLayerIndexRange),
        ("ltbl.sector_ids_ascending", Check::LtblSectorIdsAscending),
        ("ltbl.sector_id_unique", Check::LtblSectorIdUnique),
        (
            "ltbl.first_entry_is_sector_zero",
            Check::LtblFirstEntryIsSectorZero,
        ),
        ("ltbl.first_layr_in_range", Check::LtblFirstLayrInRange),
        ("ltbl.first_lrov_null", Check::LtblFirstLrovNull),
        ("ltbl.first_lrov_in_range", Check::LtblFirstLrovInRange),
        ("ltbl.offset_within_chunk", Check::LtblOffsetWithinChunk),
        ("ltbl.slices_disjoint", Check::LtblSlicesDisjoint),
        ("layr.version", Check::LayrVersion),
        ("layr.content_size_present", Check::LayrContentSizePresent),
        (
            "layr.frame_decompressed_size",
            Check::LayrFrameDecompressedSize,
        ),
        ("frame.allocation_bound", Check::FrameAllocationBound),
        ("layr.dict_id_match", Check::LayrDictIdMatch),
        ("layr.dict_id_absent", Check::LayrDictIdAbsent),
        ("head.frame", Check::HeadFrame),
        ("head.multi_sector_flag", Check::HeadMultiSectorFlag),
        ("zdic.dict_size", Check::ZdicDictSize),
        ("zdic.dict_id_match", Check::ZdicDictIdMatch),
        ("zdic.single", Check::ZdicSingle),
        ("zdic.dict_size", Check::ZdicDictSize),
        ("zdic.dict_id_match", Check::ZdicDictIdMatch),
        ("zdic.single", Check::ZdicSingle),
        ("lhas.frame", Check::LhasFrame),
        ("lhas.hash_algorithm", Check::LhasHashAlgorithm),
        ("lhas.layer_count", Check::LhasLayerCount),
        ("lhas.root_recompute", Check::LhasRootRecompute),
        ("lhas.leaf_match", Check::LhasLeafMatch),
        ("ree.tag", Check::ReeTag),
        ("ree.varint", Check::ReeVarint),
        ("ree.first_value", Check::ReeFirstValue),
        ("ree.no_run_count_zero", Check::ReeNoRunCountZero),
        ("ree.run_lengths", Check::ReeRunLengths),
        ("ree.grayscale_runs", Check::ReeGrayscaleRuns),
        ("ree.grayscale_all_binary", Check::ReeGrayscaleAllBinary),
        ("ree.split_all_binary", Check::ReeSplitAllBinary),
        ("ree.split_threshold", Check::ReeSplitThreshold),
        ("ree.split_positions", Check::ReeSplitPositions),
        ("ree.attach_positions", Check::ReeAttachPositions),
        ("ree.attach_count", Check::ReeAttachCount),
        ("ree.attach_bits", Check::ReeAttachBits),
        ("ree.attach_threshold", Check::ReeAttachThreshold),
        ("ree.end_positions", Check::ReeEndPositions),
        ("ree.data_size", Check::ReeDataSize),
        ("sector.partition", Check::SectorPartition),
        ("crypt.key_unwrap", Check::CryptKeyUnwrap),
        ("crypt.recipient_entry", Check::CryptRecipientEntry),
        ("crypt.low_order_point", Check::CryptLowOrderPoint),
        ("crypt.no_key", Check::CryptNoKey),
    ];
    NAMES
        .iter()
        .find(|(candidate, _)| *candidate == name)
        .map(|(_, check)| *check)
}

/// Every name in the corpus' own table must resolve, so a renamed check cannot
/// silently stop being exercised.
#[test]
fn every_corpus_check_name_resolves() {
    let (manifest, _) = load();
    for entry in &manifest.invalid {
        assert!(
            check_by_name(&entry.expected_failure).is_some(),
            "the corpus names {} and this crate does not know it",
            entry.expected_failure
        );
    }
}