tensogram 0.22.0

Fast binary N-tensor message format for scientific data — encode, decode, file I/O, streaming
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
// (C) Copyright 2026- ECMWF and individual contributors.
//
// This software is licensed under the terms of the Apache Licence Version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation nor
// does it submit to any jurisdiction.

use std::collections::BTreeMap;
use tensogram::*;

fn make_simple_float32_pair(shape: Vec<u64>) -> (GlobalMetadata, DataObjectDescriptor) {
    let strides: Vec<u64> = if shape.is_empty() {
        vec![]
    } else {
        let mut s = vec![1u64; shape.len()];
        for i in (0..shape.len() - 1).rev() {
            s[i] = s[i + 1] * shape[i + 1];
        }
        s
    };
    let global = GlobalMetadata {
        extra: BTreeMap::new(),
        ..Default::default()
    };
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: shape.len() as u64,
        shape,
        strides,
        dtype: Dtype::Float32,
        byte_order: ByteOrder::Big,
        encoding: "none".to_string(),
        filter: "none".to_string(),
        compression: "none".to_string(),
        params: BTreeMap::new(),
        masks: None,
    };
    (global, desc)
}

fn make_shuffle_pair(shape: Vec<u64>, element_size: u64) -> (GlobalMetadata, DataObjectDescriptor) {
    let strides: Vec<u64> = if shape.is_empty() {
        vec![]
    } else {
        let mut s = vec![1u64; shape.len()];
        for i in (0..shape.len() - 1).rev() {
            s[i] = s[i + 1] * shape[i + 1];
        }
        s
    };
    let mut params = BTreeMap::new();
    params.insert(
        "shuffle_element_size".to_string(),
        ciborium::Value::Integer(element_size.into()),
    );
    let global = GlobalMetadata {
        extra: BTreeMap::new(),
        ..Default::default()
    };
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: shape.len() as u64,
        shape,
        strides,
        dtype: Dtype::Float32,
        byte_order: ByteOrder::Big,
        encoding: "none".to_string(),
        filter: "shuffle".to_string(),
        compression: "none".to_string(),
        params,
        masks: None,
    };
    (global, desc)
}

// --- Adversarial wire-level tests ---
// The v1 BinaryHeader / TERMINATOR / OBJS / OBJE markers no longer exist in v2.
// These tests exercise the same validation behaviors using truncated or corrupted
// v2 buffers produced by the normal encoder.

#[test]
fn test_adversarial_truncated_message_rejected() {
    // A legitimately encoded message, truncated to half its length, must be rejected.
    let (global, desc) = make_simple_float32_pair(vec![4]);
    let data = vec![0u8; 4 * 4];
    let encoded = encode(&global, &[(&desc, &data)], &EncodeOptions::default()).unwrap();

    let truncated = &encoded[..encoded.len() / 2];
    let result = decode(truncated, &DecodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for truncated message but got Ok: {:?}",
        result
    );
}

#[test]
fn test_adversarial_wrong_magic_rejected() {
    // Overwrite the first 8 bytes (magic) to produce invalid magic.
    let (global, desc) = make_simple_float32_pair(vec![4]);
    let data = vec![0u8; 4 * 4];
    let mut encoded = encode(&global, &[(&desc, &data)], &EncodeOptions::default()).unwrap();

    encoded[0..8].copy_from_slice(b"BADMAGIC");
    let result = decode(&encoded, &DecodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for wrong magic but got Ok: {:?}",
        result
    );
}

#[test]
fn test_adversarial_corrupted_end_magic_rejected() {
    // Overwrite the last 8 bytes (end magic) to trigger postamble validation failure.
    let (global, desc) = make_simple_float32_pair(vec![4]);
    let data = vec![0u8; 4 * 4];
    let mut encoded = encode(&global, &[(&desc, &data)], &EncodeOptions::default()).unwrap();

    let len = encoded.len();
    encoded[len - 8..].copy_from_slice(b"BADMAGIC");
    let result = decode(&encoded, &DecodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for corrupted end magic but got Ok: {:?}",
        result
    );
}

#[test]
fn test_adversarial_empty_buffer_rejected() {
    let result = decode(&[], &DecodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for empty buffer but got Ok: {:?}",
        result
    );
}

#[test]
fn test_adversarial_negative_cbor_int_wraps() {
    let below_i32_min: i64 = i32::MIN as i64 - 1;
    let mut params = BTreeMap::new();
    params.insert(
        "sp_reference_value".to_string(),
        ciborium::Value::Float(0.0),
    );
    params.insert(
        "sp_binary_scale_factor".to_string(),
        ciborium::Value::Integer(below_i32_min.into()),
    );
    params.insert(
        "sp_decimal_scale_factor".to_string(),
        ciborium::Value::Integer(0.into()),
    );
    params.insert(
        "sp_bits_per_value".to_string(),
        ciborium::Value::Integer(16.into()),
    );

    let global = GlobalMetadata {
        extra: BTreeMap::new(),
        ..Default::default()
    };
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: 1,
        shape: vec![4],
        strides: vec![1],
        dtype: Dtype::Float64,
        byte_order: ByteOrder::Big,
        encoding: "simple_packing".to_string(),
        filter: "none".to_string(),
        compression: "none".to_string(),
        params,
        masks: None,
    };

    let data = vec![0u8; 4 * 8];
    let result = encode(&global, &[(&desc, &data)], &EncodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for out-of-range binary_scale_factor but got Ok: {:?}",
        result
    );
    let msg = result.unwrap_err().to_string();
    // Error quotes the `PackingError::InvalidParams.field` — that's the
    // Rust struct field name (internal), not the wire-format `sp_*` key.
    assert!(
        msg.contains("binary_scale_factor"),
        "expected 'binary_scale_factor' in error message, got: {msg}"
    );
}

#[test]
fn test_adversarial_non_f64_simple_packing() {
    let mut params = BTreeMap::new();
    params.insert(
        "sp_reference_value".to_string(),
        ciborium::Value::Float(0.0),
    );
    params.insert(
        "sp_binary_scale_factor".to_string(),
        ciborium::Value::Integer(0.into()),
    );
    params.insert(
        "sp_decimal_scale_factor".to_string(),
        ciborium::Value::Integer(0.into()),
    );
    params.insert(
        "sp_bits_per_value".to_string(),
        ciborium::Value::Integer(16.into()),
    );

    let global = GlobalMetadata {
        extra: BTreeMap::new(),
        ..Default::default()
    };
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: 1,
        shape: vec![10],
        strides: vec![1],
        dtype: Dtype::Float32,
        byte_order: ByteOrder::Big,
        encoding: "simple_packing".to_string(),
        filter: "none".to_string(),
        compression: "none".to_string(),
        params,
        masks: None,
    };

    let data = vec![0u8; 10 * 4];
    let result = encode(&global, &[(&desc, &data)], &EncodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for simple_packing with Float32 but got Ok: {:?}",
        result
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("simple_packing") || msg.contains("float64") || msg.contains("f64"),
        "expected 'simple_packing' or 'float64' in error message, got: {msg}"
    );
}

#[test]
fn test_adversarial_shuffle_element_size_zero() {
    let (global, desc) = make_shuffle_pair(vec![10], 0);
    let data = vec![0u8; 10 * 4];
    let result = encode(&global, &[(&desc, &data)], &EncodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for shuffle_element_size=0 but got Ok: {:?}",
        result
    );
}

#[test]
fn test_adversarial_shuffle_misaligned() {
    let float32_byte_width: usize = 4;
    let num_elements: usize = 10;
    let element_size_that_doesnt_divide_40: u64 = 3;

    let (global, desc) = make_shuffle_pair(
        vec![num_elements as u64],
        element_size_that_doesnt_divide_40,
    );
    let data = vec![0u8; num_elements * float32_byte_width];
    let result = encode(&global, &[(&desc, &data)], &EncodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for misaligned shuffle (element_size=3 on 40-byte Float32 data) but got Ok: {:?}",
        result
    );
}

#[test]
fn test_adversarial_decode_range_with_shuffle() {
    let float32_element_size: u64 = 4;
    let (global, desc) = make_shuffle_pair(vec![10], float32_element_size);
    let data: Vec<u8> = (0u8..40).collect();

    let encoded = encode(&global, &[(&desc, &data)], &EncodeOptions::default())
        .expect("encode with shuffle must succeed for this test");

    let result = decode_range(&encoded, 0, &[(0, 5)], &DecodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for decode_range on shuffled payload but got Ok: {:?}",
        result
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("shuffle") || msg.contains("filter"),
        "expected 'shuffle' or 'filter' in error message, got: {msg}"
    );
}

#[test]
fn test_adversarial_shape_product_overflow() {
    let global = GlobalMetadata {
        extra: BTreeMap::new(),
        ..Default::default()
    };
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: 2,
        shape: vec![u64::MAX, 2],
        strides: vec![2, 1],
        dtype: Dtype::Float32,
        byte_order: ByteOrder::Big,
        encoding: "none".to_string(),
        filter: "none".to_string(),
        compression: "none".to_string(),
        params: BTreeMap::new(),
        masks: None,
    };

    let data = vec![0u8; 64];
    let result = encode(&global, &[(&desc, &data)], &EncodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for shape product overflow but got Ok: {:?}",
        result
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("overflow"),
        "expected 'overflow' in error message, got: {msg}"
    );
}

#[test]
fn test_adversarial_empty_obj_type() {
    let (global, mut desc) = make_simple_float32_pair(vec![4]);
    desc.obj_type = String::new();

    let data = vec![0u8; 4 * 4];
    let result = encode(&global, &[(&desc, &data)], &EncodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for empty obj_type but got Ok: {:?}",
        result
    );
}

#[test]
fn test_adversarial_ndim_mismatch() {
    let global = GlobalMetadata {
        extra: BTreeMap::new(),
        ..Default::default()
    };
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: 5,
        shape: vec![4, 5],
        strides: vec![5, 1],
        dtype: Dtype::Float32,
        byte_order: ByteOrder::Big,
        encoding: "none".to_string(),
        filter: "none".to_string(),
        compression: "none".to_string(),
        params: BTreeMap::new(),
        masks: None,
    };

    let data = vec![0u8; 4 * 5 * 4];
    let result = encode(&global, &[(&desc, &data)], &EncodeOptions::default());
    assert!(
        result.is_err(),
        "expected Err for ndim/shape mismatch but got Ok: {:?}",
        result
    );
}

// ── Phase 2: postamble integrity (v3) ───────────────────────────────────────

/// A message whose preamble says one total_length but whose postamble
/// mirrors a different value must be rejected.  Pins the v3 §7 contract
/// that the two `total_length` slots agree whenever both are non-zero.
#[test]
fn postamble_total_length_mismatch_fails() {
    let (global, desc) = make_simple_float32_pair(vec![2, 3]);
    let payload = vec![0u8; 4 * 2 * 3];
    let mut msg = encode(&global, &[(&desc, &payload)], &EncodeOptions::default()).unwrap();

    // The postamble's total_length lives at bytes [len-16, len-8).
    // Tamper with it to be one byte shorter than the real length.
    let msg_len = msg.len() as u64;
    let fake = msg_len - 1;
    let slot_start = msg.len() - 16;
    msg[slot_start..slot_start + 8].copy_from_slice(&fake.to_be_bytes());

    let result = framing::decode_message(&msg);
    assert!(
        result.is_err(),
        "expected postamble/preamble total_length mismatch to fail decode"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("postamble total_length") && err.contains("preamble total_length"),
        "expected mismatch error, got: {err}"
    );
}

/// Postamble `total_length = 0` must remain valid — the streaming
/// non-seekable-sink case produces this and readers fall back to
/// forward scan (see v3 §9.2).
#[test]
fn postamble_zero_total_length_accepted() {
    let (global, desc) = make_simple_float32_pair(vec![2]);
    let payload = vec![0u8; 4 * 2];
    let mut msg = encode(&global, &[(&desc, &payload)], &EncodeOptions::default()).unwrap();

    // Zero the postamble total_length slot — as a non-seekable
    // streaming producer would have written it.
    let slot_start = msg.len() - 16;
    msg[slot_start..slot_start + 8].copy_from_slice(&0u64.to_be_bytes());

    // Decode must succeed — zero is the documented "unknown" signal.
    let decoded = framing::decode_message(&msg).unwrap();
    assert_eq!(decoded.objects.len(), 1);
}

/// Postamble is 24 B in v3.  Pins the wire-size invariant.
#[test]
fn postamble_is_24_bytes() {
    let (global, desc) = make_simple_float32_pair(vec![1]);
    let payload = vec![0u8; 4];
    let msg = encode(&global, &[(&desc, &payload)], &EncodeOptions::default()).unwrap();

    // Last 8 bytes are the END_MAGIC; bytes [-24 .. -16) and
    // [-16 .. -8) are the two u64 fields.  Confirm magic placement.
    assert_eq!(&msg[msg.len() - 8..], b"39277777");
    // The postamble's total_length (bytes [-16..-8)) equals the full
    // message length — buffered mode always back-fills.
    let pa_total = u64::from_be_bytes(msg[msg.len() - 16..msg.len() - 8].try_into().unwrap());
    assert_eq!(pa_total, msg.len() as u64);
}

// ── Phase 4: type 4 (obsolete v2 NTensorFrame) is reserved ─────────────────

/// Hand-constructed type-4 frame embedded in an otherwise valid
/// message must fail decode with a reserved-type error.  Pins the
/// v3 contract that type 4 is rejected at the registry lookup.
#[test]
fn frame_type_4_is_rejected() {
    // Build a syntactically-valid frame but with type=4 in the
    // header.  The frame body doesn't matter — registry rejection
    // fires at the FrameType::from_u16 stage inside
    // FrameHeader::read_from.
    use tensogram::wire::{FRAME_END, FRAME_HEADER_SIZE, FRAME_MAGIC};

    let body = vec![0u8; 32];
    let total_length = (FRAME_HEADER_SIZE + body.len() + FRAME_END.len()) as u64;
    let mut frame = Vec::new();
    frame.extend_from_slice(FRAME_MAGIC);
    frame.extend_from_slice(&4u16.to_be_bytes()); // type = 4 (reserved)
    frame.extend_from_slice(&1u16.to_be_bytes()); // version
    frame.extend_from_slice(&0u16.to_be_bytes()); // flags
    frame.extend_from_slice(&total_length.to_be_bytes());
    frame.extend_from_slice(&body);
    frame.extend_from_slice(FRAME_END);

    // Try to parse the frame header — must fail with reserved-type
    // message.
    let err = tensogram::wire::FrameHeader::read_from(&frame).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("reserved frame type 4"),
        "expected reserved-type-4 error, got: {msg}"
    );
    assert!(
        msg.contains("obsolete v2"),
        "expected 'obsolete v2' in the error, got: {msg}"
    );
}

/// SEC-001 (HIGH, found by `fuzz_decode`): a message whose preamble
/// `total_length` is non-zero but smaller than `PREAMBLE_SIZE +
/// POSTAMBLE_SIZE` used to underflow `total_len - POSTAMBLE_SIZE`,
/// panicking with "attempt to subtract with overflow" — a process-
/// killing DoS under `panic = "abort"`.  It must now be a clean
/// structured error.
///
/// The bytes below are the exact reproducer libFuzzer minimised: valid
/// `TENSOGRM` magic, version 3, and `total_length = 10` (< 48).
#[test]
fn sec001_undersized_total_length_is_rejected_not_panic() {
    let crash_input: &[u8] = &[
        84, 69, 78, 83, 79, 71, 82, 77, // "TENSOGRM"
        0, 3, // version = 3
        0, 0, // flags
        82, 77, 0, 3, // reserved (irrelevant)
        0, 0, 0, 0, 0, 0, 0, 10, // total_length = 10  (< 48)
        // trailing junk from the original reproducer
        0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 10,
    ];
    // Must not panic; must return a structured framing error.
    let err = decode(crash_input, &DecodeOptions::default())
        .expect_err("undersized total_length must be rejected");
    assert!(
        matches!(err, TensogramError::Framing(_)),
        "expected a Framing error, got: {err:?}"
    );

    // Sweep every non-zero total_length below the minimum to pin the
    // whole boundary, not just the one fuzzer sample.  None may panic.
    use tensogram::wire::{MAGIC, POSTAMBLE_SIZE, PREAMBLE_SIZE, WIRE_VERSION};
    for bad_total in 1..(PREAMBLE_SIZE + POSTAMBLE_SIZE) as u64 {
        let mut buf = Vec::with_capacity(PREAMBLE_SIZE + POSTAMBLE_SIZE);
        buf.extend_from_slice(MAGIC);
        buf.extend_from_slice(&WIRE_VERSION.to_be_bytes());
        buf.extend_from_slice(&0u16.to_be_bytes()); // flags
        buf.extend_from_slice(&0u32.to_be_bytes()); // reserved
        buf.extend_from_slice(&bad_total.to_be_bytes()); // total_length
        // Pad the buffer so the failure is the length check, not a
        // generic too-short-buffer error.
        buf.resize(PREAMBLE_SIZE + POSTAMBLE_SIZE, 0);
        let err = decode(&buf, &DecodeOptions::default())
            .expect_err("total_length below minimum must be rejected");
        assert!(
            matches!(err, TensogramError::Framing(_)),
            "total_length={bad_total} expected Framing error, got: {err:?}"
        );
    }
}

/// SEC-002 (HIGH, found by `fuzz_scan`): the in-memory scanner computed
/// `pos + total` where `total` is an attacker-controlled `u64`.  A
/// near-`usize::MAX` `total_length` overflowed the addition and
/// panicked ("attempt to add with overflow") — a DoS in `scan`,
/// reachable from any multi-message read.  It must now scan cleanly
/// (returning no spurious message) without panicking.
#[test]
fn sec002_scan_huge_total_length_does_not_overflow() {
    use tensogram::wire::{MAGIC, WIRE_VERSION};
    let mut buf = Vec::new();
    buf.extend_from_slice(MAGIC);
    buf.extend_from_slice(&WIRE_VERSION.to_be_bytes());
    buf.extend_from_slice(&0u16.to_be_bytes()); // flags
    buf.extend_from_slice(&0u32.to_be_bytes()); // reserved
    buf.extend_from_slice(&u64::MAX.to_be_bytes()); // total_length = usize::MAX-ish
    buf.resize(64, 0); // some trailing bytes
    // Must not panic; a hostile total_length yields no valid message.
    let found = scan(&buf);
    assert!(
        found.is_empty(),
        "a preamble with total_length=u64::MAX must not yield a message"
    );

    // Sweep a range of large values near the overflow boundary.
    for total in [
        u64::MAX,
        u64::MAX - 1,
        u64::MAX - 7,
        (usize::MAX as u64) - 3,
    ] {
        let mut b = Vec::new();
        b.extend_from_slice(MAGIC);
        b.extend_from_slice(&WIRE_VERSION.to_be_bytes());
        b.extend_from_slice(&0u16.to_be_bytes());
        b.extend_from_slice(&0u32.to_be_bytes());
        b.extend_from_slice(&total.to_be_bytes());
        b.resize(64, 0);
        let _ = scan(&b); // must not panic for any of these
    }
}

/// SEC-004 (HIGH, same class as SEC-002): `data_object_inline_hashes`
/// walked frames with `pos + frame_total` where `frame_total` is an
/// attacker-controlled `u64`.  A near-`usize::MAX` frame `total_length`
/// overflowed and panicked.  It must now return a structured error
/// instead.
#[test]
fn sec004_inline_hash_walk_huge_frame_total_does_not_overflow() {
    use tensogram::wire::{
        FRAME_HEADER_SIZE, FRAME_MAGIC, MAGIC, POSTAMBLE_SIZE, PREAMBLE_SIZE, WIRE_VERSION,
    };
    // Build a message whose preamble total_length is valid (so the
    // hash walk runs) but whose first frame claims a huge total_length.
    let msg_total = (PREAMBLE_SIZE + FRAME_HEADER_SIZE + POSTAMBLE_SIZE) as u64;
    let mut buf = Vec::new();
    buf.extend_from_slice(MAGIC);
    buf.extend_from_slice(&WIRE_VERSION.to_be_bytes());
    buf.extend_from_slice(&((1u16) << 7).to_be_bytes()); // HASHES_PRESENT advisory
    buf.extend_from_slice(&0u32.to_be_bytes());
    buf.extend_from_slice(&msg_total.to_be_bytes());
    // One frame header with a hostile total_length = u64::MAX.
    buf.extend_from_slice(FRAME_MAGIC);
    buf.extend_from_slice(&9u16.to_be_bytes()); // NTensorFrame
    buf.extend_from_slice(&1u16.to_be_bytes()); // version
    buf.extend_from_slice(&0u16.to_be_bytes()); // flags
    buf.extend_from_slice(&u64::MAX.to_be_bytes()); // frame total_length
    buf.resize(msg_total as usize, 0);
    // Must not panic — a structured error or a clean empty result.
    let _ = tensogram::data_object_inline_hashes(&buf);
}

/// SEC-005 (HIGH, found by `fuzz_scan`): the bidirectional scanner's
/// backward hop computed `msg_start = bound_end - total` and then
/// sliced `buf[msg_start..msg_start + MAGIC.len()]`.  A tiny postamble
/// `total_length` (below the preamble size) put `msg_start` too close
/// to the end, so the 8-byte MAGIC slice ran out of bounds and
/// panicked.  Scanning must now be panic-free.
#[test]
fn sec005_backward_scan_tiny_total_no_oob() {
    // Exact libFuzzer reproducer.
    let crash_input: &[u8] = &[
        164, 164, 164, 164, 195, 195, 195, 195, 195, 195, 195, 195, 195, 0, 0, 0, 0, 84, 69, 78,
        83, 79, 71, 82, 77, 0, 3, 0, 0, 237, 197, 197, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42,
        0, 0, 0, 0, 0, 71, 51, 57, 50, 55, 55, 55, 55, 55, 197, 0, 0, 0, 0, 0, 0, 0, 69, 78, 83,
        79, 71, 197, 0, 3, 237, 82, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        2, 37, 0, 0, 0, 0, 0, 0, 0, 4, 51, 57, 50,
    ];
    // Must not panic.
    let _ = scan(crash_input);

    // Also directly stress a synthetic buffer ending in END_MAGIC with a
    // tiny mirrored total_length in the postamble.
    use tensogram::wire::{END_MAGIC, POSTAMBLE_SIZE};
    for tiny_total in [1u64, 2, 7, 8, 23, (POSTAMBLE_SIZE as u64) - 1] {
        let mut b = vec![0u8; 128];
        // Put END_MAGIC at the very end and a tiny total_length 8 bytes
        // before it (postamble layout: [first_footer(8)][total(8)][magic(8)]).
        let n = b.len();
        b[n - 8..].copy_from_slice(END_MAGIC);
        b[n - 16..n - 8].copy_from_slice(&tiny_total.to_be_bytes());
        let _ = scan(&b); // must not panic
    }
}

/// SEC-006 (HIGH, found by `fuzz_decode_metadata`): the metadata-skip
/// loop did `pos += frame_total` with an attacker-controlled
/// `frame_total` (`u64` up to usize::MAX) → add-overflow panic.  A
/// zero/sub-header `frame_total` could also spin the loop (no
/// progress).  `decode_metadata` must now reject or skip cleanly
/// without panicking or hanging.
#[test]
fn sec006_decode_metadata_huge_skip_frame_no_overflow() {
    // Exact libFuzzer reproducer.
    let crash_input: &[u8] = &[
        84, 69, 78, 83, 79, 71, 82, 77, 0, 3, 82, 77, 0, 82, 77, 3, 71, 70, 70, 70, 139, 139, 139,
        139, 139, 139, 139, 139, 70, 82, 0, 3, 70, 70, 70, 246, 255, 255, 255, 255, 255, 255, 255,
        255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
        255, 255, 255, 255, 255, 255,
    ];
    let _ = decode_metadata(crash_input); // must not panic / hang
}

/// SEC-007 (HIGH): `scan_file`'s bidirectional walker added a
/// preamble's attacker-controlled `total` to `fwd_pos` without an
/// overflow check (`fwd_pos + total <= bwd_end`) and computed
/// `fwd_pos + total - 8`.  A huge or tiny `total_length` in a hostile
/// on-disk `.tgm` could overflow/underflow and panic.  `scan_file`
/// must scan hostile files without panicking.
#[test]
fn sec007_scan_file_huge_and_tiny_total_no_overflow() {
    use std::io::Cursor;
    use tensogram::wire::{END_MAGIC, MAGIC, WIRE_VERSION};

    // (a) Forward preamble with total_length = u64::MAX.
    let mut buf = Vec::new();
    buf.extend_from_slice(MAGIC);
    buf.extend_from_slice(&WIRE_VERSION.to_be_bytes());
    buf.extend_from_slice(&0u16.to_be_bytes());
    buf.extend_from_slice(&0u32.to_be_bytes());
    buf.extend_from_slice(&u64::MAX.to_be_bytes());
    buf.resize(128, 0);
    buf[120..].copy_from_slice(END_MAGIC); // give the backward walker bait
    let mut cur = Cursor::new(buf);
    let _ = tensogram::scan_file(&mut cur); // must not panic

    // (b) Postamble with a tiny mirrored total_length.
    let mut buf2 = vec![0u8; 96];
    let n = buf2.len();
    buf2[..MAGIC.len()].copy_from_slice(MAGIC);
    buf2[n - 8..].copy_from_slice(END_MAGIC);
    buf2[n - 16..n - 8].copy_from_slice(&3u64.to_be_bytes()); // tiny total
    let mut cur2 = Cursor::new(buf2);
    let _ = tensogram::scan_file(&mut cur2); // must not panic
}

/// SEC-008 (verified-secure invariant, kept as a no-regression guard):
/// a CBOR recursion bomb (deeply-nested arrays) in the metadata frame
/// must NOT exhaust the stack.  `ciborium::from_reader` applies a
/// default recursion limit (256), so 10k-deep nesting returns a clean
/// `Err` rather than a stack-overflow abort.  This test pins that the
/// metadata decoder uses the recursion-limited parser path.
#[test]
fn sec008_cbor_recursion_bomb_is_rejected_not_stack_overflow() {
    // `0x81` = "array of 1 item"; repeating it N times encodes an
    // N-deep nested array.  N far exceeds ciborium's 256 limit.
    let depth = 10_000usize;
    let mut bomb = vec![0x81u8; depth];
    bomb.push(0x00); // innermost value: integer 0
    let err = tensogram::metadata::cbor_to_global_metadata(&bomb)
        .expect_err("a 10k-deep CBOR nesting must be rejected, not overflow the stack");
    // Any structured error is acceptable; the point is that it returns
    // instead of crashing.  It is routed through the Metadata category.
    assert!(
        matches!(err, TensogramError::Metadata(_)),
        "expected Metadata error, got: {err:?}"
    );
}

// ── Boundary-pinning regression tests for the SEC-00x guards ───────────────
//
// The hostile-input tests above pin the *negative* path (sub-minimum /
// overflowing lengths are rejected without panicking).  On their own they
// leave the exact comparison operators in the new guards unverified: a
// mutation that loosens `<` to `<=`/`==`/`>`, flips the alignment `&` to
// `|`, or turns the hash-slot `+` into `-` still rejects the hostile input
// and so survives.  The tests below pin the *positive* path — a real,
// minimally-sized valid message must round-trip with the correct metadata
// and the correct inline hash — which forces every one of those operators
// to its exact value.  (Found as MISSED mutants by the CI `cargo-mutants`
// diff job on framing.rs:895/1148/1154/1245.)

/// A legitimately-encoded message must decode through the *exact* minimum-
/// size guard at `framing.rs:895` (`total_len < PREAMBLE_SIZE +
/// POSTAMBLE_SIZE`).  If that `<` is widened to `<=`, the smallest valid
/// messages are wrongly rejected.  Encoding the smallest object we can
/// build and asserting it decodes back pins the boundary as *inclusive of
/// the minimum, exclusive below it* (the sub-minimum half is pinned by
/// `sec001_…`).
#[test]
fn sec001_minimum_size_message_is_accepted() {
    // Smallest payload: a 0-D scalar (shape []) float32 → 4 bytes.
    let (global, desc) = make_simple_float32_pair(vec![]);
    let data = vec![0u8; 4];
    let encoded = encode(&global, &[(&desc, &data)], &EncodeOptions::default()).unwrap();

    // It must decode cleanly: the minimum-size guard must let it through.
    let (_md, objs) = decode(&encoded, &DecodeOptions::default())
        .expect("a legitimately-encoded minimal message must decode, not hit the min-size floor");
    assert_eq!(objs.len(), 1, "expected exactly one decoded object");

    // Pin the guard threshold itself: total_length equals the encoded
    // length and must be >= the minimum, and a message exactly at the
    // minimum boundary must NOT be rejected by the floor.
    use tensogram::wire::{MAGIC, POSTAMBLE_SIZE, PREAMBLE_SIZE, WIRE_VERSION};
    assert!(
        encoded.len() >= PREAMBLE_SIZE + POSTAMBLE_SIZE,
        "encoded length {} must be at least the minimum message size {}",
        encoded.len(),
        PREAMBLE_SIZE + POSTAMBLE_SIZE
    );

    // Pin the EXACT boundary `total_len < MIN` (not `<=`): a buffer whose
    // `total_length` is exactly PREAMBLE_SIZE + POSTAMBLE_SIZE describes a
    // zero-frame message — structurally degenerate, but it must pass the
    // minimum-size *floor* (the floor only rejects strictly-smaller
    // values).  A `< → <=` mutation makes the floor reject this exact-
    // minimum buffer with the distinctive "smaller than the minimum
    // message size" error; assert that specific error never fires here.
    let min = (PREAMBLE_SIZE + POSTAMBLE_SIZE) as u64;
    let mut buf = Vec::with_capacity(min as usize);
    buf.extend_from_slice(MAGIC);
    buf.extend_from_slice(&WIRE_VERSION.to_be_bytes());
    buf.extend_from_slice(&0u16.to_be_bytes()); // flags
    buf.extend_from_slice(&0u32.to_be_bytes()); // reserved
    buf.extend_from_slice(&min.to_be_bytes()); // total_length == MIN exactly
    buf.resize(min as usize, 0); // zeroed postamble region
    let res = decode(&buf, &DecodeOptions::default());
    // It may still error for other reasons (no metadata frame, bad
    // postamble magic) — that's fine.  What must NOT happen is rejection
    // by the minimum-size floor, whose message is unique.
    if let Err(TensogramError::Framing(msg)) = &res {
        assert!(
            !msg.contains("smaller than the minimum message size"),
            "total_length exactly at the minimum must pass the size floor; \
             got floor rejection: {msg}"
        );
    }
}

/// `decode_metadata_only` must walk past the data-object frame(s) and
/// return the real metadata of a *valid* message.  This exercises the
/// frame-skip guard at `framing.rs:1148` (`frame_total < FRAME_HEADER_SIZE`)
/// and the alignment step at `framing.rs:1154` (`pos.saturating_add(7) &
/// !7`): if the comparison is mutated (`< → ==`/`>`/`<=`) or the alignment
/// mask is flipped (`& → |`, `delete !`), the loop mis-advances and either
/// fails to find the metadata frame or reads the wrong one.  A valid
/// round-trip with a non-trivial global-metadata field that we can assert
/// pins all of those operators.
#[test]
fn sec006_decode_metadata_returns_valid_metadata() {
    use ciborium::Value;

    // Build a message with a couple of objects and a distinctive global
    // metadata entry so the metadata-skip loop has frames to walk past.
    let (mut global, desc) = make_simple_float32_pair(vec![4]);
    global.extra.insert(
        "producer".to_string(),
        Value::Text("sec006-pin".to_string()),
    );
    let data = vec![1u8; 4 * 4];
    let encoded = encode(
        &global,
        &[(&desc, &data), (&desc, &data)],
        &EncodeOptions::default(),
    )
    .unwrap();

    // decode_metadata must skip the data-object frames (each at least a
    // header, aligned to 8) and return the metadata frame's contents.
    let md = decode_metadata(&encoded)
        .expect("decode_metadata must return the metadata of a valid multi-object message");
    assert_eq!(
        md.extra.get("producer"),
        Some(&Value::Text("sec006-pin".to_string())),
        "decode_metadata must recover the exact global metadata after \
         correctly skipping the (header-sized, 8-byte-aligned) data frames"
    );
}

/// `data_object_inline_hashes` must return one hash slot per data-object
/// frame, read from the *exact* offset `frame_end - FRAME_COMMON_FOOTER_SIZE`.
/// This pins the minimum-frame-size guard at `framing.rs:1245`
/// (`frame_total < FRAME_HEADER_SIZE + FRAME_COMMON_FOOTER_SIZE`) and the
/// `frame_end = pos + frame_total` arithmetic: a `+ → -` mutation or a
/// loosened comparison would read the slot at the wrong offset and yield a
/// different (or no) hash.  We encode with hashing enabled and assert the
/// recovered inline hash equals the hash the verifier computes from the
/// frame bytes — only the correct operators reproduce it.
#[test]
fn sec004_inline_hashes_match_on_valid_hashed_message() {
    // A normally-encoded object carries a non-zero inline xxh3-64 hash in
    // its common footer.  `data_object_inline_hashes` must recover it from
    // the exact `frame_end - FRAME_COMMON_FOOTER_SIZE` offset.
    let (global, desc) = make_simple_float32_pair(vec![8]);
    let data: Vec<u8> = (0..8 * 4).map(|i| i as u8).collect();
    let encoded = encode(&global, &[(&desc, &data)], &EncodeOptions::default()).unwrap();

    let hashes = tensogram::data_object_inline_hashes(&encoded)
        .expect("inline-hash walk must succeed on a valid message");
    assert_eq!(
        hashes.len(),
        1,
        "expected exactly one data-object hash slot"
    );
    let recovered = hashes[0].expect("a normally-encoded object carries a non-zero inline hash");

    // Pin the slot OFFSET arithmetic (`frame_end = pos + frame_total`,
    // slot at `frame_end - footer`).  If `+ → -` or the min-frame-size
    // comparison is mutated, the walker reads the slot from the wrong
    // place.  Cross-check the recovered value against an independent
    // verify-hash decode of the same bytes: decoding with `verify_hash`
    // recomputes xxh3 over the body and checks it against the very slot we
    // read here, so a successful verified decode proves our offset is
    // correct.
    let verify = DecodeOptions {
        verify_hash: true,
        ..DecodeOptions::default()
    };
    decode(&encoded, &verify)
        .expect("verify_hash decode must succeed, confirming the inline hash slot is well-located");

    // And pin that the slot is read from real frame data, not a constant:
    // a different (finite) payload must produce a different recovered hash.
    // Build it from valid little-batch float32 values so the strict-NaN
    // encoder check passes.
    let other_f32: Vec<f32> = (0..8).map(|i| i as f32 * 1.5).collect();
    let mut other = Vec::with_capacity(8 * 4);
    for v in &other_f32 {
        other.extend_from_slice(&v.to_be_bytes());
    }
    let encoded2 = encode(&global, &[(&desc, &other)], &EncodeOptions::default()).unwrap();
    let recovered2 = tensogram::data_object_inline_hashes(&encoded2)
        .expect("inline-hash walk must succeed")[0]
        .expect("non-zero inline hash");
    assert_ne!(
        recovered, recovered2,
        "distinct payloads must yield distinct inline hashes — proves the \
         slot offset reads real frame bytes, not a fixed location"
    );
}