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
// (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.

//! 6-cell matrix tests for `DecodeOptions::verify_hash` on
//! `decode` and `decode_object`.
//!
//! The matrix (per the plan,
//! `PLAN_DECODE_HASH_VERIFICATION.md` §5.2):
//!
//! | Cell | Input                                      | Option              | Expected                                  |
//! |------|--------------------------------------------|---------------------|-------------------------------------------|
//! | A    | `hash_xxh3.tgm`                            | `verify_hash=False` | success                                   |
//! | B    | `hash_xxh3.tgm`                            | `verify_hash=True`  | success                                   |
//! | C    | `simple_f32.tgm` (no per-frame hash)       | `verify_hash=True`  | `MissingHash { object_index: 0 }`         |
//! | D    | `hash_xxh3.tgm` + flipped hash byte        | `verify_hash=True`  | `HashMismatch { object_index: Some(0) }`  |
//! | E    | `hash_xxh3.tgm` + flipped payload byte     | `verify_hash=True`  | `HashMismatch { object_index: Some(0) }`  |
//! | F    | `multi_object_xxh3.tgm` + tampered obj 1   | `verify_hash=True`  | `HashMismatch { object_index: Some(1) }`  |
//!
//! Plus negative tests asserting `decode_range` ignores the flag
//! (the `verify_hash` field's docstring is the contract; here we
//! pin the runtime behaviour).

use std::collections::BTreeMap;
use std::path::PathBuf;

use tensogram::decode::{
    DecodeOptions, decode, decode_object, decode_object_from_frame, decode_range,
    decode_range_from_frame,
};
use tensogram::encode::{EncodeOptions, encode};
use tensogram::types::{ByteOrder, DataObjectDescriptor, GlobalMetadata};
use tensogram::{Dtype, TensogramError, framing, wire};

fn golden_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden")
}

fn read_golden(name: &str) -> Vec<u8> {
    std::fs::read(golden_dir().join(name)).unwrap_or_else(|e| panic!("{name}: {e}"))
}

fn opts_no_verify() -> DecodeOptions {
    DecodeOptions {
        verify_hash: false,
        ..DecodeOptions::default()
    }
}

fn opts_verify() -> DecodeOptions {
    DecodeOptions {
        verify_hash: true,
        ..DecodeOptions::default()
    }
}

/// Build a minimal single-object message with the encoder's
/// hashing path **disabled** — every frame's `HASH_PRESENT` bit
/// is clear.  Cell C ("verify on hashless message → MissingHash")
/// fixture.
fn build_unhashed_single_object_message() -> Vec<u8> {
    let meta = GlobalMetadata::default();
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: 1,
        shape: vec![4],
        strides: vec![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 mut payload = Vec::new();
    for v in [1.0f32, 2.0, 3.0, 4.0] {
        payload.extend_from_slice(&v.to_be_bytes());
    }
    let opts = EncodeOptions {
        hashing: false,
        ..Default::default()
    };
    encode(&meta, &[(&desc, &payload)], &opts).unwrap()
}

/// Locate the byte offset within the message buffer of the i-th
/// data-object frame, plus the offset within that frame of the
/// inline hash slot.  Used by tampering tests so they don't have
/// to rebuild the message bytes from scratch.
fn locate_object_frame(buf: &[u8], object_index: usize) -> (usize, usize) {
    let messages = framing::scan(buf);
    assert_eq!(
        messages.len(),
        1,
        "this test helper assumes single-message buffers"
    );
    let (msg_offset, msg_len) = messages[0];
    let msg = &buf[msg_offset..msg_offset + msg_len];
    let mut pos = 24; // past preamble
    let mut found_objects = 0;
    while pos + wire::FRAME_HEADER_SIZE <= msg.len() {
        if &msg[pos..pos + 2] != b"FR" {
            pos += 1;
            continue;
        }
        let fh = wire::FrameHeader::read_from(&msg[pos..]).unwrap();
        if fh.frame_type.is_data_object() {
            if found_objects == object_index {
                let frame_start = msg_offset + pos;
                let frame_len = fh.total_length as usize;
                // Inline hash slot lives at `frame_end - 12`.
                let slot_offset_within_frame = frame_len - wire::FRAME_COMMON_FOOTER_SIZE;
                return (frame_start, slot_offset_within_frame);
            }
            found_objects += 1;
        }
        let aligned = (pos + fh.total_length as usize + 7) & !7;
        pos = aligned.min(msg.len());
    }
    panic!(
        "data-object frame index {object_index} not found in buffer (have {found_objects} objects)"
    );
}

/// Locate the start of the *payload region* (the bytes covered by
/// the inline hash) of the i-th data-object frame.  The payload
/// region begins immediately after the 16-byte frame header;
/// flipping a byte there is guaranteed to perturb the recomputed
/// digest.
fn locate_payload_start(buf: &[u8], object_index: usize) -> usize {
    let (frame_start, _) = locate_object_frame(buf, object_index);
    frame_start + wire::FRAME_HEADER_SIZE
}

// ── Cells A & B — `hash_xxh3.tgm`, single object, both flag values ────

#[test]
fn cell_a_decode_no_verify_succeeds_on_hashed_message() {
    let data = read_golden("hash_xxh3.tgm");
    let (_, objects) = decode(&data, &opts_no_verify()).unwrap();
    assert_eq!(objects.len(), 1);
}

#[test]
fn cell_b_decode_with_verify_succeeds_on_hashed_message() {
    let data = read_golden("hash_xxh3.tgm");
    let (_, objects) = decode(&data, &opts_verify()).unwrap();
    assert_eq!(objects.len(), 1);
}

#[test]
fn cell_b_decode_object_with_verify_succeeds_on_hashed_message() {
    let data = read_golden("hash_xxh3.tgm");
    let (_, _, _) = decode_object(&data, 0, &opts_verify()).unwrap();
}

// ── Cell C — hashless message, verify=true ────────────────────────────

#[test]
fn cell_c_decode_verify_on_unhashed_message_returns_missing_hash() {
    // Built in-test rather than read from a golden because every
    // committed `.tgm` fixture is encoded with the default
    // `hashing=true`.  See `build_unhashed_single_object_message`.
    let data = build_unhashed_single_object_message();
    let err = decode(&data, &opts_verify()).unwrap_err();
    match err {
        TensogramError::MissingHash { object_index } => {
            assert_eq!(
                object_index, 0,
                "single-object message must surface index 0"
            );
        }
        other => panic!("expected MissingHash, got: {other:?}"),
    }
}

#[test]
fn cell_c_decode_object_verify_on_unhashed_message_returns_missing_hash() {
    let data = build_unhashed_single_object_message();
    let err = decode_object(&data, 0, &opts_verify()).unwrap_err();
    match err {
        TensogramError::MissingHash { object_index } => {
            assert_eq!(object_index, 0);
        }
        other => panic!("expected MissingHash, got: {other:?}"),
    }
}

#[test]
fn cell_c_no_verify_silently_decodes_unhashed_message() {
    // Documents the asymmetry: without `verify_hash` the decoder
    // never looks at the flag, so an unhashed message is
    // perfectly decodable.
    let data = build_unhashed_single_object_message();
    let (_, objects) = decode(&data, &opts_no_verify()).unwrap();
    assert_eq!(objects.len(), 1);
}

// ── Cell D — tampered hash slot (flag set, slot wrong) ────────────────

#[test]
fn cell_d_decode_verify_reports_hash_mismatch_on_tampered_slot() {
    let mut data = read_golden("hash_xxh3.tgm");
    let (frame_start, slot_offset) = locate_object_frame(&data, 0);
    // Flip one byte of the inline slot; flag bit is unchanged.
    data[frame_start + slot_offset] ^= 0xFF;

    let err = decode(&data, &opts_verify()).unwrap_err();
    match err {
        TensogramError::HashMismatch {
            object_index,
            expected,
            actual,
        } => {
            assert_eq!(object_index, Some(0));
            assert_ne!(expected, actual);
        }
        other => panic!("expected HashMismatch, got: {other:?}"),
    }
}

#[test]
fn cell_d_decode_object_verify_reports_hash_mismatch_on_tampered_slot() {
    let mut data = read_golden("hash_xxh3.tgm");
    let (frame_start, slot_offset) = locate_object_frame(&data, 0);
    data[frame_start + slot_offset] ^= 0xFF;

    let err = decode_object(&data, 0, &opts_verify()).unwrap_err();
    match err {
        TensogramError::HashMismatch {
            object_index,
            expected,
            actual,
        } => {
            assert_eq!(object_index, Some(0));
            assert_ne!(expected, actual);
        }
        other => panic!("expected HashMismatch, got: {other:?}"),
    }
}

// ── Cell E — tampered payload byte (flag set, slot intact) ────────────

#[test]
fn cell_e_decode_verify_reports_hash_mismatch_on_tampered_payload() {
    let mut data = read_golden("hash_xxh3.tgm");
    let payload_start = locate_payload_start(&data, 0);
    // Flip one byte at the start of the hashed payload region.
    data[payload_start] ^= 0xFF;

    let err = decode(&data, &opts_verify()).unwrap_err();
    match err {
        TensogramError::HashMismatch {
            object_index,
            expected,
            actual,
        } => {
            assert_eq!(object_index, Some(0));
            assert_ne!(expected, actual);
        }
        other => panic!("expected HashMismatch, got: {other:?}"),
    }
}

// ── Cell F — multi-object: tamper object 1, expect index 1 ────────────

#[test]
fn cell_f_decode_verify_reports_correct_object_index_on_multi_object() {
    let mut data = read_golden("multi_object_xxh3.tgm");
    let payload_start = locate_payload_start(&data, 1);
    data[payload_start] ^= 0xFF;

    let err = decode(&data, &opts_verify()).unwrap_err();
    match err {
        TensogramError::HashMismatch {
            object_index,
            expected,
            actual,
        } => {
            assert_eq!(
                object_index,
                Some(1),
                "must surface the *tampered* object's index, not 0"
            );
            assert_ne!(expected, actual);
        }
        other => panic!("expected HashMismatch on object 1, got: {other:?}"),
    }
}

#[test]
fn cell_f_decode_object_verify_targets_specific_object() {
    let mut data = read_golden("multi_object_xxh3.tgm");
    let payload_start = locate_payload_start(&data, 1);
    data[payload_start] ^= 0xFF;

    // Decoding object 0 still works (its hash is intact).
    decode_object(&data, 0, &opts_verify()).unwrap();
    decode_object(&data, 2, &opts_verify()).unwrap();

    // Decoding object 1 (the tampered one) reports HashMismatch.
    let err = decode_object(&data, 1, &opts_verify()).unwrap_err();
    match err {
        TensogramError::HashMismatch { object_index, .. } => {
            assert_eq!(object_index, Some(1));
        }
        other => panic!("expected HashMismatch, got: {other:?}"),
    }
}

#[test]
fn cell_f_clearing_per_frame_flag_yields_missing_hash_with_correct_index() {
    // Cross-flag-consistency case from the plan §10:
    // tampered fixture with HASHES_PRESENT=1 in preamble but
    // HASH_PRESENT=0 on object 1 → MissingHash { object_index: 1 }.
    let mut data = read_golden("multi_object_xxh3.tgm");
    let (frame_start, _) = locate_object_frame(&data, 1);
    // Frame header `flags` u16 lives at offset +6 within the frame.
    // Clear bit 1 (HASH_PRESENT) — leave bit 0 (CBOR_AFTER_PAYLOAD) alone.
    let flags_offset = frame_start + 6;
    let mut flags = u16::from_be_bytes(data[flags_offset..flags_offset + 2].try_into().unwrap());
    flags &= !wire::FrameFlags::HASH_PRESENT;
    data[flags_offset..flags_offset + 2].copy_from_slice(&flags.to_be_bytes());

    // Other objects unaffected.
    decode_object(&data, 0, &opts_verify()).unwrap();
    decode_object(&data, 2, &opts_verify()).unwrap();

    let err = decode(&data, &opts_verify()).unwrap_err();
    match err {
        TensogramError::MissingHash { object_index } => {
            assert_eq!(object_index, 1);
        }
        other => panic!("expected MissingHash on object 1, got: {other:?}"),
    }
}

// ── Negative tests: decode_range ignores verify_hash ─────────────────

#[test]
fn decode_range_ignores_verify_hash_on_unhashed_message() {
    // `simple_f32.tgm` has no per-frame hashes.  Calling
    // decode_range with `verify_hash=true` does NOT error
    // (verify_hash is silently ignored — see the doc-comment on
    // `DecodeOptions::verify_hash`).
    let data = read_golden("simple_f32.tgm");
    let (_, parts) = decode_range(&data, 0, &[(0, 4)], &opts_verify()).unwrap();
    assert_eq!(parts.len(), 1);
}

#[test]
fn decode_range_ignores_verify_hash_on_tampered_payload() {
    // Even with HASH_PRESENT set + corrupted payload, decode_range
    // does not verify and returns successfully.  This is the
    // documented contract: integrity-conscious callers must use
    // `decode_object` with `verify_hash=true`.
    let mut data = read_golden("hash_xxh3.tgm");
    let payload_start = locate_payload_start(&data, 0);
    data[payload_start] ^= 0xFF;

    let result = decode_range(&data, 0, &[(0, 1)], &opts_verify());
    // Either succeeds with corrupted bytes, or fails for a
    // non-hash reason (e.g. compression-codec error).  In every
    // case, the failure is NOT a HashMismatch / MissingHash —
    // those are the verifications we explicitly opted out of.
    match result {
        Ok(_) => (),
        Err(TensogramError::HashMismatch { .. }) | Err(TensogramError::MissingHash { .. }) => {
            panic!(
                "decode_range must not surface verify_hash errors — verify_hash is documented as ignored"
            );
        }
        Err(_) => (),
    }
}

// ── Verify-first ordering regression (Pass 5+) ────────────────────────

#[test]
fn cell_e_variant_decode_verify_reports_hash_mismatch_on_tampered_cbor() {
    // Body-tamper variant of Cell E that targets a byte INSIDE
    // the CBOR descriptor region rather than the encoded-tensor
    // region.  Pre-Pass-5, `decode` would parse the broken CBOR
    // before running the hash check and surface
    // `TensogramError::Metadata`; under verify-first ordering
    // the corruption surfaces as `HashMismatch` regardless of
    // where it lands inside the hashed body.
    //
    // The buffered encoder writes `[payload][CBOR][cbor_offset]
    // [hash][ENDF]` for `simple_f32`-style fixtures; the CBOR
    // descriptor sits between the encoded payload (16 B for a
    // 4-element f32 tensor) and the 20-byte type-specific
    // footer.  Flipping `frame_end - 32` lands inside the CBOR
    // for any descriptor at least ~12 B wide (the minimum for a
    // valid `ntensor` descriptor) — well outside the encoded
    // payload.
    let mut data = read_golden("hash_xxh3.tgm");
    let (frame_start, slot_offset_within_frame) = locate_object_frame(&data, 0);
    let frame_end =
        frame_start + slot_offset_within_frame + tensogram::wire::FRAME_COMMON_FOOTER_SIZE;
    let cbor_byte = frame_end - 32;
    assert!(
        cbor_byte > frame_start + tensogram::wire::FRAME_HEADER_SIZE + 16,
        "tamper offset must land past the 16-byte encoded f32 payload region"
    );
    data[cbor_byte] ^= 0xff;

    let err = decode(&data, &opts_verify()).unwrap_err();
    match err {
        TensogramError::HashMismatch { object_index, .. } => {
            assert_eq!(object_index, Some(0));
        }
        other => panic!(
            "expected HashMismatch (verify-first ordering) on tampered \
             CBOR byte, got: {other:?}"
        ),
    }
}

// ── Multi-message bound regression (Pass 7) ──────────────────────────
//
// `verify_data_object_frames` must respect the first message's
// `Preamble.total_length` boundary, the same way
// `framing::decode_message` does.  Without this bound, a
// concatenated `[msgA][msgB]` buffer would have its msgB frames
// hashed by the verify pre-pass even though `decode` only ever
// returns msgA's contents — producing spurious failures when
// msgB has a different hashing posture from msgA.
//
// Found in Copilot review of PR #111 (rust/tensogram/src/decode.rs:252).

#[test]
fn decode_verify_respects_first_message_total_length_on_concat() {
    // The committed `hash_xxh3.tgm` golden is hashed (HASH_PRESENT
    // set on every data-object frame); the in-process helper
    // builds an explicitly-hashless single-object message
    // (HASH_PRESENT clear).  Concatenating them produces a
    // `[hashed][unhashed]` buffer whose first message decodes
    // cleanly under `verify_hash=true` and whose second message
    // would fail `MissingHash` if the verify pre-pass leaked
    // past `Preamble.total_length`.
    let hashed = read_golden("hash_xxh3.tgm");
    let unhashed = build_unhashed_single_object_message();

    // Sanity baseline: each message verifies independently as
    // expected (hashed → Ok, unhashed → MissingHash on object 0).
    decode(&hashed, &opts_verify()).expect("hashed message verifies");
    let unhashed_err = decode(&unhashed, &opts_verify()).unwrap_err();
    assert!(
        matches!(
            unhashed_err,
            TensogramError::MissingHash { object_index: 0 }
        ),
        "baseline: unhashed message must fail verify with MissingHash, got {unhashed_err:?}"
    );

    // Concatenation: `[hashed][unhashed]`.  `decode` returns only
    // msg1's contents (one object), and verification must honour
    // that same scope — msg2's hashless frames must NOT cause
    // `MissingHash`.
    let mut concat = hashed.clone();
    concat.extend_from_slice(&unhashed);
    let (_meta, objects) = decode(&concat, &opts_verify()).unwrap_or_else(|e| {
        panic!(
            "decode(concat[hashed,unhashed], verify_hash=true) must \
             not leak into msg2: {e:?}"
        )
    });
    assert_eq!(
        objects.len(),
        1,
        "decode is bounded to first message; helper must match"
    );
}

#[test]
fn decode_object_verify_respects_first_message_total_length_on_concat() {
    // Same regression, exercised through the targeted-decode
    // surface — `decode_object` uses the same pre-pass helper
    // with `target_index = Some(i)`, but the message-end bound
    // is independent of which target index is requested.
    let hashed = read_golden("hash_xxh3.tgm");
    let unhashed = build_unhashed_single_object_message();
    let mut concat = hashed.clone();
    concat.extend_from_slice(&unhashed);

    // Object 0 is in msg1 and is hashed → must succeed.
    decode_object(&concat, 0, &opts_verify())
        .expect("decode_object(0) on concat must verify msg1's first object");
}

// ── verify_hash on buffer shorter than preamble ──────────────────────
//
// Catches mutations of the `buf.len() < PREAMBLE_SIZE` guard in
// `verify_data_object_frames` (line 188).

#[test]
fn verify_hash_on_buffer_shorter_than_preamble_returns_framing_error() {
    // A buffer shorter than PREAMBLE_SIZE (24 bytes) must fail with
    // a Framing error when verify_hash is true.
    let tiny = vec![0u8; 10];
    let err = decode(&tiny, &opts_verify()).unwrap_err();
    match &err {
        TensogramError::Framing(msg) => {
            assert!(
                msg.contains("preamble") || msg.contains("too short"),
                "expected preamble/too-short error, got: {msg}"
            );
        }
        other => panic!("expected Framing error, got: {other:?}"),
    }
}

#[test]
fn verify_hash_on_empty_buffer_returns_framing_error() {
    let empty: Vec<u8> = vec![];
    let err = decode(&empty, &opts_verify()).unwrap_err();
    assert!(
        matches!(&err, TensogramError::Framing(_)),
        "expected Framing error on empty buffer, got: {err:?}"
    );
}

// ── decode_object_from_frame with verify_hash ────────────────────────
//
// Catches mutations of the `!check_frame_hash(...)` guard (line 596)
// and the `total < FRAME_HEADER_SIZE || total > frame_bytes.len()`
// bounds check (line 588) in `decode_object_from_frame`.

/// Extract the raw bytes of the i-th data-object frame from a message.
fn extract_raw_object_frame(buf: &[u8], object_index: usize) -> Vec<u8> {
    let (frame_start, slot_offset) = locate_object_frame(buf, object_index);
    let frame_len = slot_offset + wire::FRAME_COMMON_FOOTER_SIZE;
    buf[frame_start..frame_start + frame_len].to_vec()
}

#[test]
fn decode_object_from_frame_verify_hash_succeeds_on_hashed_frame() {
    let data = read_golden("hash_xxh3.tgm");
    let frame = extract_raw_object_frame(&data, 0);
    let (desc, decoded) = decode_object_from_frame(&frame, &opts_verify())
        .expect("verify_hash on a valid hashed frame must succeed");
    assert_eq!(desc.shape, vec![4]);
    assert!(!decoded.is_empty());
}

#[test]
fn decode_object_from_frame_verify_hash_rejects_unhashed_frame() {
    let data = build_unhashed_single_object_message();
    let frame = extract_raw_object_frame(&data, 0);
    let err = decode_object_from_frame(&frame, &opts_verify()).unwrap_err();
    match err {
        TensogramError::MissingHash { object_index } => {
            assert_eq!(object_index, 0);
        }
        other => panic!("expected MissingHash, got: {other:?}"),
    }
}

#[test]
fn decode_object_from_frame_verify_hash_rejects_tampered_payload() {
    let data = read_golden("hash_xxh3.tgm");
    let mut frame = extract_raw_object_frame(&data, 0);
    // Flip a byte in the payload region (right after the frame header).
    frame[wire::FRAME_HEADER_SIZE] ^= 0xFF;
    let err = decode_object_from_frame(&frame, &opts_verify()).unwrap_err();
    // `decode_object_from_frame` calls `check_frame_hash` directly
    // (not via the pre-pass helper), so the error carries
    // `object_index: None` from the hash module.
    assert!(
        matches!(err, TensogramError::HashMismatch { .. }),
        "expected HashMismatch, got: {err:?}"
    );
}

#[test]
fn decode_object_from_frame_no_verify_succeeds_on_unhashed_frame() {
    // Without verify_hash, an unhashed frame decodes fine.
    let data = build_unhashed_single_object_message();
    let frame = extract_raw_object_frame(&data, 0);
    let (desc, decoded) = decode_object_from_frame(&frame, &opts_no_verify())
        .expect("no-verify on unhashed frame must succeed");
    assert_eq!(desc.shape, vec![4]);
    assert!(!decoded.is_empty());
}

// ── decode_range_from_frame with masks ───────────────────────────────
//
// Catches the `&& → ||` mutation on line 658:
// `options.restore_non_finite && desc.masks.is_some()`.

#[test]
fn decode_range_from_frame_restores_non_finite_masks() {
    // Encode a message with NaN values so masks are present.
    let values: Vec<f64> = vec![1.0, f64::NAN, 3.0, f64::INFINITY, 5.0, 6.0, 7.0, 8.0];
    let data: Vec<u8> = values.iter().flat_map(|v| v.to_ne_bytes()).collect();
    let desc = DataObjectDescriptor {
        obj_type: "ntensor".to_string(),
        ndim: 1,
        shape: vec![8],
        strides: vec![1],
        dtype: Dtype::Float64,
        byte_order: ByteOrder::native(),
        encoding: "none".to_string(),
        filter: "none".to_string(),
        compression: "none".to_string(),
        params: std::collections::BTreeMap::new(),
        masks: None,
    };
    let enc_opts = EncodeOptions {
        allow_nan: true,
        allow_inf: true,
        hashing: true,
        small_mask_threshold_bytes: 0,
        ..Default::default()
    };
    let msg = encode(&GlobalMetadata::default(), &[(&desc, &data)], &enc_opts).unwrap();

    // Extract the frame bytes.
    let frame = extract_raw_object_frame(&msg, 0);

    // Decode range [0..4] with restore_non_finite=true.
    let opts_restore = DecodeOptions {
        restore_non_finite: true,
        ..Default::default()
    };
    let (ret_desc, parts) = decode_range_from_frame(&frame, &[(0, 4)], &opts_restore).unwrap();
    assert_eq!(parts.len(), 1);
    // The range covers elements [1.0, NaN, 3.0, Inf].
    let decoded: Vec<f64> = parts[0]
        .chunks_exact(8)
        .map(|c| f64::from_ne_bytes(c.try_into().unwrap()))
        .collect();
    assert_eq!(decoded[0], 1.0);
    assert!(decoded[1].is_nan(), "NaN must be restored");
    assert_eq!(decoded[2], 3.0);
    assert!(
        decoded[3].is_infinite() && decoded[3] > 0.0,
        "+Inf must be restored"
    );

    // With restore_non_finite=false, NaN/Inf positions should be 0.0.
    let opts_no_restore = DecodeOptions {
        restore_non_finite: false,
        ..Default::default()
    };
    let (_, parts_no) = decode_range_from_frame(&frame, &[(0, 4)], &opts_no_restore).unwrap();
    let decoded_no: Vec<f64> = parts_no[0]
        .chunks_exact(8)
        .map(|c| f64::from_ne_bytes(c.try_into().unwrap()))
        .collect();
    assert_eq!(decoded_no[0], 1.0);
    assert_eq!(decoded_no[1], 0.0, "NaN should be 0.0 when restore is off");
    assert_eq!(decoded_no[2], 3.0);
    assert_eq!(decoded_no[3], 0.0, "Inf should be 0.0 when restore is off");

    // Also verify the descriptor reports masks.
    assert!(
        ret_desc.masks.is_some(),
        "descriptor must carry masks for NaN/Inf data"
    );
}