viterbi 0.2.0

Pure-Rust, no-unsafe convolutional encoder + Viterbi (MLSE) decoder — CCSDS inner FEC: hard & soft-decision (LLR), rate 1/2 & 1/3, puncturing (2/3–7/8), generic constraint length K<=9.
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
// Author: BolivarTech
// Version: 1.0.0
// Date: 2026-07-05
//! Comprehensive edge-case & robustness sweep across every v0.2.x feature (R14).
//!
//! A single, systematic, cross-feature file so no boundary cell is missed. It sweeps the
//! feature set (hard / soft / rate-1/3 / K=9 / puncturing) against the edge set (minimal
//! inputs, payload extremes, soft-LLR extremes, capacity boundary, resource limits, every
//! error variant, determinism, long-stream renorm, K=9 at realistic scale). Most cells
//! **characterize already-correct behaviour** (they pass immediately); together they make
//! the suite sufficient to guarantee correctness rather than "seems to work".
//!
//! ## Reserved-but-unreachable error variants (documented, not forced)
//! Two declared domain-error variants have **no producing code path by design** and are
//! therefore intentionally not provoked here (the plan's Task-12 reach list omits both):
//! - [`viterbi::ParamError::KUnsupported`] — `validate()` rejects `k ∉ 1..=9` with
//!   `KOutOfRange`; every `k ∈ 1..=9` at a supported rate is *accepted*, so no path emits
//!   `KUnsupported`. It is a reserved variant kept for a future increment that restricts K.
//! - [`viterbi::PunctureError::RowCountMismatch`] — the puncture layer reports an `n` mismatch
//!   as [`viterbi::PunctureError::NMismatch`] (matrix-`n` vs code-`n`); `RowCountMismatch` is a
//!   reserved alias never raised. Both are covered by their reachable siblings below.
//!
//! Two more variants (`ConfigError::AllocationFailed`, `DecodeError::AllocationFailed`,
//! `PunctureError::AllocationFailed`, `EncodeError::AllocationFailed`) fire **only** on a real
//! `try_reserve` OOM, which cannot be provoked deterministically in a unit test without an
//! allocator hook; they are exercised structurally (every allocation is fallible) and left to
//! the milestone fuzz/miri gate rather than forced here.

use viterbi::puncture::{DePuncturer, Puncturer};
use viterbi::{
    CcsdsSoftDecoder, CcsdsViterbiDecoder, CodeParams, CodeProfile, CodedBlock, ConfigError,
    DecodeError, EncodeError, HardHamming, ParamError, PunctureError, PunctureMatrix,
    PunctureOrder, PuncturedRate, SoftLlr, ViterbiDecoder, ViterbiEncoder, MAX_SUPPORTED_INFO_BITS,
};

mod common;

// ---------------------------------------------------------------------------
// Helpers (MSB-first, mirroring the crate's internal packing convention).
// ---------------------------------------------------------------------------

/// MSB-first coded bit at index `i` (bit 7 of byte 0 is index 0).
fn bit(bytes: &[u8], i: usize) -> u8 {
    (bytes[i / 8] >> (7 - (i % 8))) & 1
}

/// Every coded bit of `cb` as a `HardHamming` 0/1 sample.
fn coded_bits_hard(cb: &CodedBlock) -> Vec<u8> {
    (0..cb.nbits).map(|i| bit(&cb.bytes, i)).collect()
}

/// Every coded bit of `cb` as a confident soft LLR (`bit 0 → +64`, `bit 1 → -64`; λ>0 ⇒ bit 0).
fn coded_bits_soft(cb: &CodedBlock) -> Vec<i8> {
    (0..cb.nbits)
        .map(|i| if bit(&cb.bytes, i) == 0 { 64 } else { -64 })
        .collect()
}

/// Pack the first `nbits` MSB-first bits of `data` (final byte zero-padded) — the expected
/// `DecodedBlock::bytes` for a non-byte-aligned payload.
fn pack_first(data: &[u8], nbits: usize) -> Vec<u8> {
    let mut out = vec![0u8; nbits.div_ceil(8)];
    for i in 0..nbits {
        if bit(data, i) == 1 {
            out[i / 8] |= 1 << (7 - (i % 8));
        }
    }
    out
}

/// Flip the MSB-first coded bit at index `i`.
fn flip_bit(bytes: &mut [u8], i: usize) {
    bytes[i / 8] ^= 1 << (7 - (i % 8));
}

// ===========================================================================
// 1. Minimal inputs — empty, 1-bit, 1-byte round-trip for every feature.
// ===========================================================================

// The existing minimal-input tests (kept from v0.0.x) — hard block path.

#[test]
fn empty_and_minimal_inputs_round_trip() {
    let (enc, mut dec) = common::codec();
    for raw in [vec![], vec![0x00], vec![0xFF], vec![0x80]] {
        let coded = enc.encode(&raw).unwrap();
        assert_eq!(dec.decode_block(&coded).unwrap().bytes, raw);
    }
}

/// R14 (empty-payload boundary): an empty payload `&[]` round-trips to an empty decoded block —
/// zero info bits, no bytes — with no panic or off-by-one, even though the encoder still emits the
/// `M = 6` zero-tail stages. Asserted explicitly (bytes *and* `nbits == 0`).
#[test]
fn empty_payload_round_trips_to_empty_block() {
    let (enc, mut dec) = common::codec();
    let coded = enc.encode(&[]).unwrap();
    let decoded = dec.decode_block(&coded).unwrap();
    assert!(
        decoded.bytes.is_empty(),
        "empty payload must decode to no bytes"
    );
    assert_eq!(
        decoded.nbits, 0,
        "empty payload must decode to zero info bits"
    );
}

/// Minimal 1-bit and 1-byte payloads round-trip on the **soft** path (LLR metric), including the
/// empty block (12 tail samples, zero info bits).
#[test]
fn soft_minimal_inputs_round_trip() {
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    let mut dec = CcsdsSoftDecoder::new(CodeParams::ccsds_r1_2(), 1_000).unwrap();
    // Empty payload.
    let coded = enc.encode_bits(&[], 0).unwrap();
    let out = dec.decode(&coded_bits_soft(&coded), 0).unwrap();
    assert!(out.bytes.is_empty());
    assert_eq!(out.nbits, 0);
    // 1 bit.
    let coded = enc.encode_bits(&[0x80], 1).unwrap();
    let out = dec.decode(&coded_bits_soft(&coded), 1).unwrap();
    assert_eq!(out.nbits, 1);
    assert_eq!(out.bytes, pack_first(&[0x80], 1));
    // 1 byte.
    let coded = enc.encode(&[0xC3]).unwrap();
    let out = dec.decode(&coded_bits_soft(&coded), 8).unwrap();
    assert_eq!(out.bytes, vec![0xC3]);
}

/// Minimal inputs round-trip on the **rate-1/3** path (hard samples, `n = 3`).
#[test]
fn rate_1_3_minimal_inputs_round_trip() {
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_3()).unwrap();
    let mut dec = ViterbiDecoder::<64, HardHamming>::new(CodeParams::ccsds_r1_3(), 1_000).unwrap();
    // Empty.
    let coded = enc.encode_bits(&[], 0).unwrap();
    let out = dec.decode(&coded_bits_hard(&coded), 0).unwrap();
    assert!(out.bytes.is_empty());
    assert_eq!(out.nbits, 0);
    // 1 bit and 1 byte.
    let coded = enc.encode_bits(&[0x80], 1).unwrap();
    assert_eq!(dec.decode(&coded_bits_hard(&coded), 1).unwrap().nbits, 1);
    let coded = enc.encode(&[0x5A]).unwrap();
    assert_eq!(
        dec.decode(&coded_bits_hard(&coded), 8).unwrap().bytes,
        vec![0x5A]
    );
}

/// Minimal inputs round-trip on the **K=9** path (`S = 256`, tail `m = 8`).
#[test]
fn k9_minimal_inputs_round_trip() {
    let params = CodeProfile::K9R1_2.params();
    let enc = ViterbiEncoder::new(params.clone()).unwrap();
    let mut dec = ViterbiDecoder::<256, HardHamming>::new(params, 1_000).unwrap();
    for raw in [vec![], vec![0x00], vec![0xFF], vec![0x80]] {
        let coded = enc.encode(&raw).unwrap();
        let out = dec.decode_block(&coded).unwrap();
        assert_eq!(out.bytes, raw);
        assert_eq!(out.nbits, raw.len() * 8);
    }
}

// ===========================================================================
// 2. Payload extremes — all-zeros, all-ones, non-byte-aligned nbits.
// ===========================================================================

/// The existing all-zeros / all-ones max-block cell (kept from v0.0.x), hard path.
#[test]
fn all_zeros_and_all_ones_max_block() {
    let (enc, mut dec) = common::codec();
    for raw in [vec![0x00; 512], vec![0xFF; 512]] {
        let coded = enc.encode(&raw).unwrap();
        assert_eq!(dec.decode_block(&coded).unwrap().bytes, raw);
    }
}

/// All-zeros and all-ones round-trip on the **soft** and **rate-1/3** paths — the two payload
/// extremes on every metric/rate combination.
#[test]
fn payload_extremes_round_trip_soft_and_rate_1_3() {
    // Soft, rate 1/2.
    let enc2 = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    let mut soft = CcsdsSoftDecoder::new(CodeParams::ccsds_r1_2(), 4_096).unwrap();
    for raw in [vec![0x00u8; 64], vec![0xFFu8; 64]] {
        let coded = enc2.encode(&raw).unwrap();
        assert_eq!(
            soft.decode(&coded_bits_soft(&coded), raw.len() * 8)
                .unwrap()
                .bytes,
            raw
        );
    }
    // Rate 1/3, hard.
    let enc3 = ViterbiEncoder::new(CodeParams::ccsds_r1_3()).unwrap();
    let mut dec3 = ViterbiDecoder::<64, HardHamming>::new(CodeParams::ccsds_r1_3(), 4_096).unwrap();
    for raw in [vec![0x00u8; 64], vec![0xFFu8; 64]] {
        let coded = enc3.encode(&raw).unwrap();
        assert_eq!(
            dec3.decode(&coded_bits_hard(&coded), raw.len() * 8)
                .unwrap()
                .bytes,
            raw
        );
    }
}

/// Non-byte-aligned `nbits` round-trips exactly (payload bit count not a multiple of 8), on hard
/// and soft — the final byte's unused low bits are zero-padded and must match.
#[test]
fn non_byte_aligned_nbits_round_trip() {
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    let mut hard = CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), 4_096).unwrap();
    let mut soft = CcsdsSoftDecoder::new(CodeParams::ccsds_r1_2(), 4_096).unwrap();
    let data = [0b1011_0010u8, 0b1110_0001, 0b0101_1010];
    for &nbits in &[1usize, 3, 7, 9, 13, 17, 23] {
        let coded = enc.encode_bits(&data, nbits).unwrap();
        let expected = pack_first(&data, nbits);
        // Hard.
        let out = hard.decode(&coded_bits_hard(&coded), nbits).unwrap();
        assert_eq!(out.nbits, nbits, "hard nbits mismatch for nbits={nbits}");
        assert_eq!(
            out.bytes, expected,
            "hard payload mismatch for nbits={nbits}"
        );
        // Soft.
        let out = soft.decode(&coded_bits_soft(&coded), nbits).unwrap();
        assert_eq!(out.nbits, nbits, "soft nbits mismatch for nbits={nbits}");
        assert_eq!(
            out.bytes, expected,
            "soft payload mismatch for nbits={nbits}"
        );
    }
}

// ===========================================================================
// 3. Soft LLR extremes (deterministic, fixed, non-random).
// ===========================================================================

/// A full block of `i8::MIN` (-128) LLRs and a full block of `i8::MAX` decode WITHOUT panic —
/// exercises the `unsigned_abs` magnitude-128 edge (`(-128i8).abs()` would overflow-panic) on
/// every branch of every stage, in a fixed non-random test. Only the no-panic + shape guarantee
/// is asserted (the content is meaningless).
#[test]
fn soft_extreme_llr_saturated_samples_never_panic() {
    let nbits = 64usize;
    let mut dec = CcsdsSoftDecoder::new(CodeParams::ccsds_r1_2(), 1_000).unwrap();
    let len = (nbits + 6) * 2; // (nbits + m) * n, rate 1/2
    for &fill in &[i8::MIN, i8::MAX] {
        let samples = vec![fill; len];
        let out = dec.decode(&samples, nbits).unwrap();
        assert_eq!(
            out.nbits, nbits,
            "extreme-LLR fill {fill} must yield a full-length block"
        );
        assert_eq!(out.bytes.len(), nbits / 8);
    }
}

/// A full block of `0` (all-erasure) LLRs decodes to a low-confidence best-effort output with no
/// panic — every branch costs zero, so every survivor ties; the decode must still terminate and
/// return a well-formed block (content unspecified).
#[test]
fn soft_all_erasure_llr_decodes_best_effort() {
    let nbits = 64usize;
    let mut dec = CcsdsSoftDecoder::new(CodeParams::ccsds_r1_2(), 1_000).unwrap();
    let samples = vec![0i8; (nbits + 6) * 2];
    let out = dec.decode(&samples, nbits).unwrap();
    assert_eq!(out.nbits, nbits);
    assert_eq!(out.bytes.len(), nbits / 8);
}

// ===========================================================================
// 4. Capacity boundary — rate-1/2 (t = 4) and rate-1/3 (t = 6).
// ===========================================================================

/// Rate-1/2 (`d_free = 10`, `t = ⌊9/2⌋ = 4`): exactly 4 well-spaced single-bit errors recover
/// exactly; a denser cluster beyond capability decodes best-effort without panicking.
#[test]
fn rate_1_2_capacity_boundary() {
    let (enc, mut dec) = common::codec();
    let raw: Vec<u8> = (0..64).collect();

    // t = 4 spaced errors (> ~14-coded-bit constraint span apart) → exact recovery.
    let mut coded = enc.encode(&raw).unwrap();
    for &i in &[50usize, 300, 550, 800] {
        flip_bit(&mut coded.bytes, i);
    }
    assert_eq!(
        dec.decode_block(&coded).unwrap().bytes,
        raw,
        "4 well-spaced errors are within rate-1/2 (t=4) capability"
    );

    // t + 1 clustered inside one span → best-effort, no panic (correctness NOT asserted).
    let (enc, mut dec) = common::codec();
    let mut coded = enc.encode(&raw).unwrap();
    for i in 500..=505 {
        flip_bit(&mut coded.bytes, i);
    }
    let out = dec.decode_block(&coded).unwrap();
    assert_eq!(
        out.nbits,
        raw.len() * 8,
        "beyond-capacity decode must still return a full block"
    );
}

/// Rate-1/3 (`d_free = 14`, `t = ⌊13/2⌋ = 6`): 6 well-spaced errors recover; a denser cluster
/// decodes best-effort without panicking.
#[test]
fn rate_1_3_capacity_boundary() {
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_3()).unwrap();
    let raw = vec![0xA5u8; 16]; // 128 info bits ⇒ (128+6)*3 = 402 coded bits
    let nbits = raw.len() * 8;

    // t = 6 spaced errors → exact recovery.
    let coded = enc.encode(&raw).unwrap();
    let mut samples = coded_bits_hard(&coded);
    let span = samples.len() / 6;
    for e in 0..6 {
        samples[e * span] ^= 1;
    }
    let mut dec = ViterbiDecoder::<64, HardHamming>::new(CodeParams::ccsds_r1_3(), 4096).unwrap();
    assert_eq!(
        dec.decode(&samples, nbits).unwrap().bytes,
        raw,
        "6 well-spaced errors are within rate-1/3 (t=6) capability"
    );

    // Beyond capability: every third coded bit flipped → best-effort, no panic.
    let mut samples = coded_bits_hard(&coded);
    for i in (0..samples.len()).step_by(3) {
        samples[i] ^= 1;
    }
    let out = dec.decode(&samples, nbits).unwrap();
    assert_eq!(
        out.nbits, nbits,
        "beyond-capacity rate-1/3 decode must still return a full block"
    );
}

// ===========================================================================
// 5. Resource limits.
// ===========================================================================

/// A block of exactly `max_info_bits` decodes (the upper boundary is inclusive); one info bit
/// beyond the configured cap → `DecodeError::InputTooLong`.
#[test]
fn max_info_bits_boundary_decodes_and_rejects_beyond() {
    let cap = 256usize;
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    let mut dec = CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), cap).unwrap();

    // Exactly `cap` info bits (32 bytes) decodes.
    let raw: Vec<u8> = (0..(cap / 8) as u32)
        .map(|i| (i as u8).wrapping_mul(31))
        .collect();
    let coded = enc.encode(&raw).unwrap();
    assert_eq!(dec.decode_block(&coded).unwrap().bytes, raw);

    // One info bit over the cap → InputTooLong (the nbits check fires before any length check,
    // so an empty sample slice suffices).
    assert!(matches!(
        dec.decode(&[], cap + 1),
        Err(DecodeError::InputTooLong { max_bits, got_bits })
            if max_bits == cap && got_bits == cap + 1
    ));
}

/// `max_info_bits = 0` → `ConfigError::MaxBlockZero`; over the hard cap → `MaxBlockTooLarge`.
#[test]
fn config_max_info_bits_zero_and_over_cap_rejected() {
    assert_eq!(
        CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), 0)
            .err()
            .unwrap(),
        ConfigError::MaxBlockZero
    );
    assert!(matches!(
        CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), MAX_SUPPORTED_INFO_BITS + 1),
        Err(ConfigError::MaxBlockTooLarge { cap, got })
            if cap == MAX_SUPPORTED_INFO_BITS && got == MAX_SUPPORTED_INFO_BITS + 1
    ));
}

/// The encoder mirrors the decoder's payload cap: over `MAX_SUPPORTED_INFO_BITS` →
/// `EncodeError::PayloadTooLarge`; `nbits` beyond the input slice → `NbitsExceedsData`.
#[test]
fn encode_resource_limits_rejected() {
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    // PayloadTooLarge: one byte over the cap.
    let big = vec![0u8; MAX_SUPPORTED_INFO_BITS / 8 + 1];
    assert!(matches!(
        enc.encode(&big),
        Err(EncodeError::PayloadTooLarge { .. })
    ));
    // NbitsExceedsData: request 9 bits from a 1-byte slice.
    assert_eq!(
        enc.encode_bits(&[0x00], 9),
        Err(EncodeError::NbitsExceedsData {
            nbits: 9,
            available: 8
        })
    );
}

// ===========================================================================
// 6. Every reachable error variant provoked (no panic on any).
// ===========================================================================

/// Every reachable [`ParamError`] variant is provoked and returns `Err` (no panic). `KUnsupported`
/// is a reserved variant with no producing path (see module docs) — intentionally omitted.
#[test]
fn every_reachable_param_error_variant() {
    // ZeroGenerator.
    assert_eq!(
        CodeParams::new(7, vec![0o171, 0], vec![false, true]),
        Err(ParamError::ZeroGenerator)
    );
    // GeneratorOutOfRange (K=3 ⇒ generators must be < 8; 0b1000 = 8 is one past range).
    assert_eq!(
        CodeParams::new(3, vec![0b1000, 0b101], vec![false, false]),
        Err(ParamError::GeneratorOutOfRange { g: 0b1000, k: 3 })
    );
    // KOutOfRange.
    assert_eq!(
        CodeParams::new(10, vec![1, 1], vec![false, false]),
        Err(ParamError::KOutOfRange { k: 10 })
    );
    // InconsistentLengths (generator/inversion length mismatch).
    assert_eq!(
        CodeParams::new(7, vec![0o171, 0o133], vec![false]),
        Err(ParamError::InconsistentLengths)
    );
    // Catastrophic (identical generators share every factor).
    assert_eq!(
        CodeParams::new(7, vec![0o171, 0o171], vec![false, false]),
        Err(ParamError::Catastrophic)
    );
    // RateUnsupported (n = 1: a single monomial generator 0o100 = x^6, non-catastrophic).
    let n1 = CodeParams::new(7, vec![0o100], vec![false]).unwrap();
    assert_eq!(
        ViterbiEncoder::new(n1).err().unwrap(),
        ParamError::RateUnsupported { n: 1 }
    );
    // StateCountMismatch (surfaced through ConfigError::Param): K=3 params with the K=7 const S=64.
    let k3 = CodeParams::new(3, vec![0b101, 0b111], vec![false, false]).unwrap();
    assert!(matches!(
        ViterbiDecoder::<64, HardHamming>::new(k3, 64),
        Err(ConfigError::Param(ParamError::StateCountMismatch {
            states: 64,
            k: 3
        }))
    ));
}

/// Every reachable [`ConfigError`] variant is provoked (no panic). `AllocationFailed` fires only on
/// a real OOM `try_reserve` and is not deterministically forceable (see module docs).
#[test]
fn every_reachable_config_error_variant() {
    // MaxBlockZero.
    assert_eq!(
        CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), 0)
            .err()
            .unwrap(),
        ConfigError::MaxBlockZero
    );
    // MaxBlockTooLarge.
    assert!(matches!(
        CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), MAX_SUPPORTED_INFO_BITS + 1),
        Err(ConfigError::MaxBlockTooLarge { .. })
    ));
    // Param (wraps RateUnsupported here — n = 1 reaches the decoder rate guard).
    let n1 = CodeParams::new(7, vec![0o100], vec![false]).unwrap();
    assert!(matches!(
        ViterbiDecoder::<64, HardHamming>::new(n1, 64),
        Err(ConfigError::Param(ParamError::RateUnsupported { n: 1 }))
    ));
}

/// Every reachable [`DecodeError`] variant is provoked (no panic). `AllocationFailed` is OOM-only.
#[test]
fn every_reachable_decode_error_variant() {
    let mut dec = CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), 8).unwrap();
    // InputTooLong.
    assert!(matches!(
        dec.decode(&[], 16),
        Err(DecodeError::InputTooLong {
            max_bits: 8,
            got_bits: 16
        })
    ));
    // LengthMismatch via decode_block (nbits not a multiple of N=2).
    assert!(matches!(
        dec.decode_block(&CodedBlock {
            bytes: vec![0; 4],
            nbits: 15
        }),
        Err(DecodeError::LengthMismatch)
    ));
    // LengthMismatch via the raw decode path (received length inconsistent with nbits).
    let expected = (4 + 6) * 2; // (nbits + m) * n
    assert!(matches!(
        dec.decode(&vec![0u8; expected + 1], 4),
        Err(DecodeError::LengthMismatch)
    ));
}

/// Every reachable [`PunctureError`] variant is provoked (no panic). `RowCountMismatch` and
/// `AllocationFailed` are reserved / OOM-only (see module docs).
#[test]
fn every_reachable_puncture_error_variant() {
    // EmptyPattern (no rows).
    assert_eq!(
        PunctureMatrix::new(vec![], PunctureOrder::ByColumn).unwrap_err(),
        PunctureError::EmptyPattern
    );
    // EmptyPattern (a zero-length row).
    assert_eq!(
        PunctureMatrix::new(vec![vec![], vec![]], PunctureOrder::ByColumn).unwrap_err(),
        PunctureError::EmptyPattern
    );
    // RaggedRows (rows of differing length).
    assert_eq!(
        PunctureMatrix::new(vec![vec![true, false], vec![true]], PunctureOrder::ByColumn)
            .unwrap_err(),
        PunctureError::RaggedRows
    );
    // PeriodTooLarge (period > MAX_PERIOD = 128).
    let long_row = vec![true; viterbi::puncture::MAX_PERIOD + 1];
    assert!(matches!(
        PunctureMatrix::new(vec![long_row.clone(), long_row], PunctureOrder::ByColumn),
        Err(PunctureError::PeriodTooLarge { period, cap })
            if period == viterbi::puncture::MAX_PERIOD + 1 && cap == viterbi::puncture::MAX_PERIOD
    ));
    // AllVoidPeriod (a column with no kept bit in any row).
    assert_eq!(
        PunctureMatrix::new(
            vec![vec![true, false], vec![true, false]],
            PunctureOrder::ByColumn
        )
        .unwrap_err(),
        PunctureError::AllVoidPeriod
    );
    // UnsupportedRate (no standard n=3 punctured family).
    assert_eq!(
        PunctureMatrix::ccsds_rate(3, PuncturedRate::R2_3).unwrap_err(),
        PunctureError::UnsupportedRate
    );
    // Catastrophic (keep C1 = 0o171 non-monomial, puncture all of C2 → single-generator reduction).
    let cat = PunctureMatrix::new(
        vec![vec![true, true], vec![false, false]],
        PunctureOrder::ByColumn,
    )
    .unwrap();
    assert_eq!(
        Puncturer::new(cat.clone(), &CodeParams::ccsds_r1_2()).unwrap_err(),
        PunctureError::Catastrophic
    );
    assert_eq!(
        DePuncturer::<HardHamming>::new(cat, &CodeParams::ccsds_r1_2()).unwrap_err(),
        PunctureError::Catastrophic
    );
    // NMismatch (a rate-1/2 matrix over a rate-1/3 code).
    let m2 = PunctureMatrix::ccsds_rate(2, PuncturedRate::R2_3).unwrap();
    assert!(matches!(
        Puncturer::new(m2, &CodeParams::ccsds_r1_3()),
        Err(PunctureError::NMismatch {
            matrix_n: 2,
            params_n: 3
        })
    ));
    // MisalignedInput (puncture TX: coded length inconsistent with nbits).
    let good = PunctureMatrix::ccsds_rate(2, PuncturedRate::R2_3).unwrap();
    let punc = Puncturer::new(good.clone(), &CodeParams::ccsds_r1_2()).unwrap();
    let bad_coded = CodedBlock {
        bytes: vec![0u8; 4],
        nbits: 7,
    };
    assert!(matches!(
        punc.puncture(&bad_coded, 8),
        Err(PunctureError::MisalignedInput { .. })
    ));
    // MisalignedInput (depuncture RX: received length ≠ expected_punctured_len).
    let dp = DePuncturer::<HardHamming>::new(good, &CodeParams::ccsds_r1_2()).unwrap();
    let expected = dp.expected_punctured_len(16).unwrap();
    assert!(matches!(
        dp.depuncture(&vec![0u8; expected + 1], 16),
        Err(PunctureError::MisalignedInput { got, .. }) if got == expected + 1
    ));
}

// ===========================================================================
// 7. Determinism — decode-twice-identical for each feature.
// ===========================================================================

/// Decoding the same input twice yields bit-identical output on every path (hard, soft, rate-1/3,
/// K=9) — the crate's determinism invariant (R10).
#[test]
fn decode_is_deterministic_across_features() {
    // Hard, rate 1/2.
    let (enc, mut dec) = common::codec();
    let coded = enc.encode(b"deterministic hard").unwrap();
    assert_eq!(
        dec.decode_block(&coded).unwrap(),
        dec.decode_block(&coded).unwrap()
    );

    // Soft, rate 1/2.
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    let coded = enc.encode(b"deterministic soft").unwrap();
    let llrs = coded_bits_soft(&coded);
    let mut soft = CcsdsSoftDecoder::new(CodeParams::ccsds_r1_2(), 1_000).unwrap();
    assert_eq!(
        soft.decode(&llrs, coded.nbits / 2 - 6).unwrap(),
        soft.decode(&llrs, coded.nbits / 2 - 6).unwrap()
    );

    // Rate 1/3, hard.
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_3()).unwrap();
    let raw = b"deterministic r13";
    let coded = enc.encode(raw).unwrap();
    let samples = coded_bits_hard(&coded);
    let mut dec3 = ViterbiDecoder::<64, HardHamming>::new(CodeParams::ccsds_r1_3(), 1_000).unwrap();
    assert_eq!(
        dec3.decode(&samples, raw.len() * 8).unwrap(),
        dec3.decode(&samples, raw.len() * 8).unwrap()
    );

    // K=9, hard.
    let params = CodeProfile::K9R1_2.params();
    let enc = ViterbiEncoder::new(params.clone()).unwrap();
    let coded = enc.encode(b"deterministic k9").unwrap();
    let mut dec9 = ViterbiDecoder::<256, HardHamming>::new(params, 1_000).unwrap();
    assert_eq!(
        dec9.decode_block(&coded).unwrap(),
        dec9.decode_block(&coded).unwrap()
    );
}

// ===========================================================================
// 8. Long-stream renorm stress — hard AND soft, block ≫ constraint span.
// ===========================================================================

/// A block far larger than the constraint span on the **hard** path: the every-stage subtract-min
/// renormalization keeps the metric spread bounded (the ACS `debug_assert!` `min == 0 && max ≤ B`
/// is active in the test build), so the run completes with an exact round-trip and no overflow.
#[test]
fn long_stream_hard_round_trip_exercises_renorm() {
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    let raw: Vec<u8> = (0..1_500u32).map(|i| (i as u8).wrapping_mul(53)).collect(); // 12_000 info bits
    let coded = enc.encode(&raw).unwrap();
    let mut dec = CcsdsViterbiDecoder::new(CodeParams::ccsds_r1_2(), 20_000).unwrap();
    assert_eq!(dec.decode_block(&coded).unwrap().bytes, raw);
}

/// The same long-stream renorm stress on the **soft** path (`|λ| = 64` per bit), so the
/// bounded-spread invariant is exercised for the LLR metric too.
#[test]
fn long_stream_soft_round_trip_exercises_renorm() {
    let enc = ViterbiEncoder::new(CodeParams::ccsds_r1_2()).unwrap();
    let raw: Vec<u8> = (0..1_500u32).map(|i| (i as u8).wrapping_mul(37)).collect(); // 12_000 info bits
    let coded = enc.encode(&raw).unwrap();
    let llrs = coded_bits_soft(&coded);
    let mut dec = CcsdsSoftDecoder::new(CodeParams::ccsds_r1_2(), 20_000).unwrap();
    assert_eq!(dec.decode(&llrs, raw.len() * 8).unwrap().bytes, raw);
}

// ===========================================================================
// 9. K=9 at realistic scale (≥ 10_000-bit block through S = 256).
// ===========================================================================

/// A ≥ 10_000-bit block through the K=9 (`S = 256`) survivor path: a clean round-trip plus a single
/// correctable error both recover. This exercises the larger-`S` survivor memory (≈ 320 KB) at a
/// non-toy size, confirming the const-generic path has no scaling defect at K=9.
#[test]
fn k9_realistic_scale_round_trip_and_correction() {
    let params = CodeProfile::K9R1_2.params();
    let enc = ViterbiEncoder::new(params.clone()).unwrap();
    let mut dec = ViterbiDecoder::<256, HardHamming>::new(params, 20_000).unwrap();

    // 1_250 bytes = 10_000 info bits (≥ 10_000).
    let raw: Vec<u8> = (0..1_250u32)
        .map(|i| (i as u8).wrapping_mul(29).wrapping_add(7))
        .collect();
    let coded = enc.encode(&raw).unwrap();

    // Clean round-trip.
    assert_eq!(dec.decode_block(&coded).unwrap().bytes, raw);

    // One correctable coded-bit error (well within the K=9 d_free = 12, t = 5 capability).
    let mut corrupted = coded.clone();
    flip_bit(&mut corrupted.bytes, 4_321);
    assert_eq!(
        dec.decode_block(&corrupted).unwrap().bytes,
        raw,
        "a single K=9 coded-bit error must recover at 10k-bit scale"
    );
}

// ===========================================================================
// 10. K=9 + puncturing combination (re-run of the Task-11 cell for completeness).
// ===========================================================================

/// K=9 (`m = 8`, `n = 2`) over a rate-2/3 puncture matrix round-trips, and the verbatim tail is
/// exactly `m·n = 16` samples — the one cell that catches an `M = 6` stray in `puncture.rs` for
/// K ≠ 7. Mirrors the Task-11 combination test so the full matrix is exercised in one place.
#[test]
fn k9_with_puncturing_round_trips_with_m_times_n_tail() {
    let params = CodeProfile::K9R1_2.params();
    let enc = ViterbiEncoder::new(params.clone()).unwrap();
    let matrix = PunctureMatrix::ccsds_rate(2, PuncturedRate::R2_3).unwrap();
    let punc = Puncturer::new(matrix.clone(), &params).unwrap();
    let dp = DePuncturer::<HardHamming>::new(matrix.clone(), &params).unwrap();

    let raw = b"pk9"; // 24 info bits, period-aligned
    let nbits = raw.len() * 8;

    let coded = enc.encode(raw).unwrap();
    assert_eq!(
        coded.nbits,
        (nbits + 8) * 2,
        "K=9 encode tail must use m = 8"
    );

    let punctured = punc.puncture(&coded, nbits).unwrap();
    let kept_body = (nbits / matrix.period()) * matrix.kept_per_period();
    assert_eq!(
        punctured.nbits,
        kept_body + 8 * 2,
        "punctured tail must be m·n = 16 (K=9)"
    );
    assert_eq!(dp.expected_punctured_len(nbits), Some(kept_body + 8 * 2));

    let full = dp.depuncture(&coded_bits_hard(&punctured), nbits).unwrap();
    let mut dec = ViterbiDecoder::<256, HardHamming>::new(params, 4096).unwrap();
    assert_eq!(dec.decode(&full, nbits).unwrap().bytes, raw.to_vec());
}

// ===========================================================================
// 11. Punctured soft round-trip — exercises depuncture erasure insertion + soft decode together.
// ===========================================================================

/// A rate-3/4 punctured round-trip on the **soft** path: TX punctures, RX re-inserts `SoftLlr`
/// erasures (`λ = 0`) and decodes. Confirms the puncture layer composes with the soft metric with
/// no channel errors (clean recovery), covering the puncture × soft cell of the matrix.
#[test]
fn punctured_soft_round_trip_clean_channel() {
    let params = CodeParams::ccsds_r1_2();
    let enc = ViterbiEncoder::new(params.clone()).unwrap();
    let matrix = PunctureMatrix::ccsds_rate(2, PuncturedRate::R3_4).unwrap();
    let punc = Puncturer::new(matrix.clone(), &params).unwrap();
    let dp = DePuncturer::<SoftLlr>::new(matrix, &params).unwrap();

    let raw = b"punctured soft ok"; // period 3 not aligned to 136 bits — exercises cyclic prefix
    let nbits = raw.len() * 8;
    let coded = enc.encode(raw).unwrap();
    let punctured = punc.puncture(&coded, nbits).unwrap();

    // On-air soft LLRs, then de-puncture (erasures at punctured positions) + decode.
    let on_air = coded_bits_soft(&punctured);
    let full = dp.depuncture(&on_air, nbits).unwrap();
    let mut dec = ViterbiDecoder::<64, SoftLlr>::new(params, 4096).unwrap();
    assert_eq!(dec.decode(&full, nbits).unwrap().bytes, raw.to_vec());
}