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
//! Reconstructs missing PAR2 input slices from available recovery blocks.
//!
//! [`RecoveryDecoder`] implements the algorithm described in `ROADMAP.md`
//! Phase 22: subtract every known input slice's contribution from a chosen
//! set of recovery blocks (one per missing slice), invert the resulting
//! reduced matrix, and multiply through to recover the missing data. See
//! [`crate::matrix`] for the matrix algebra and [`crate::gf16_mac`] for the
//! multiply-accumulate primitive both steps share.
//!
//! This decoder is independent of file layout: it works entirely in terms
//! of global input-slice indices (the same indexing `RecoveryEncoder` uses)
//! and asks its caller for bytes via a callback, so it never has to know
//! about paths, `RecoverySet`, or on-disk formats. [`crate::repair`] is
//! where those pieces meet.
use crate::gf16::{input_logbases, Gf16};
use crate::gf16_mac::mac;
use crate::matrix::Gf16Matrix;
use anyhow::{bail, Context, Result};
use rayon::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
/// Reconstructs a set of missing PAR2 input slices.
pub struct RecoveryDecoder {
gf: Gf16,
slice_size: usize,
logbases: Vec<u32>,
total_input_slices: usize,
missing: Vec<usize>,
}
impl RecoveryDecoder {
/// Build a decoder for `total_input_slices` input slices of `slice_size`
/// bytes each, where the global indices listed in `missing` need
/// reconstruction.
///
/// # Panics
///
/// Panics if `missing` is empty or any index in it is
/// `>= total_input_slices`.
pub fn new(slice_size: usize, total_input_slices: usize, mut missing: Vec<usize>) -> Self {
assert!(
!missing.is_empty(),
"RecoveryDecoder: nothing to reconstruct"
);
missing.sort_unstable();
missing.dedup();
assert!(
*missing.last().unwrap() < total_input_slices,
"RecoveryDecoder: missing index {} is out of range for {total_input_slices} slices",
missing.last().unwrap()
);
Self {
gf: Gf16::new(),
slice_size,
logbases: input_logbases(total_input_slices),
total_input_slices,
missing,
}
}
/// Global indices this decoder will reconstruct, ascending.
pub fn missing(&self) -> &[usize] {
&self.missing
}
/// Reconstruct every missing slice.
///
/// `known_slice(i)` must return the padded, slice-sized bytes of known
/// (non-missing) global input slice `i`. It is called exactly once per
/// known slice, in ascending order — a caller reading from disk pays for
/// one sequential pass over the surviving data, not one pass per missing
/// slice.
///
/// `recovery_blocks` must hold at least `self.missing().len()` entries;
/// the lowest-exponent blocks available are used first (an arbitrary but
/// deterministic choice). Consecutive exponents always form an invertible
/// matrix; a non-consecutive selection, left after some recovery blocks
/// were lost, can be singular (see the [`crate::matrix`] module docs).
///
/// Returns `(global_index, slice_bytes)` pairs, one per entry of
/// [`missing`](Self::missing), in the same order.
pub fn reconstruct(
&self,
mut known_slice: impl FnMut(usize) -> Result<Vec<u8>>,
recovery_blocks: &BTreeMap<u32, Vec<u8>>,
) -> Result<Vec<(usize, Vec<u8>)>> {
let m = self.missing.len();
if recovery_blocks.len() < m {
bail!(
"not enough recovery blocks to repair {m} missing slice(s): only {} available",
recovery_blocks.len()
);
}
let exponents: Vec<u32> = recovery_blocks.keys().take(m).copied().collect();
let bases: Vec<u16> = self
.missing
.iter()
.map(|&i| self.gf.exp(self.logbases[i]))
.collect();
let mut adjusted: Vec<Vec<u8>> = Vec::with_capacity(m);
for e in &exponents {
let block = &recovery_blocks[e];
anyhow::ensure!(
block.len() == self.slice_size,
"recovery block (exponent {e}) has the wrong length: expected {}, got {}",
self.slice_size,
block.len()
);
adjusted.push(block.clone());
}
// Subtract each known slice's contribution from every selected
// recovery block in one pass, so the caller's `known_slice` reads
// each surviving slice from disk exactly once regardless of how
// many blocks are being reconstructed.
//
// The outer loop over `j` stays strictly sequential: `known_slice` is
// an `FnMut` and callers (see `crate::repair::SliceReader`) rely on
// ascending, one-at-a-time calls to keep a single file handle open
// across reads rather than reopening per slice. What *is*
// embarrassingly parallel is the inner loop: `m` (missing-slice
// count) independent `mac`s, one per row of `adjusted`, each writing
// to its own disjoint buffer from the one just-read `known_bytes`.
// On a repair with many missing slices — the case that dominates
// wall time, since this loop runs `total_input_slices` times — that
// inner width is real parallelism `par_iter_mut` can use without
// touching the I/O ordering at all. `Gf16` and `mac` are pure over
// `&self`/read-only `src`, so sharing `&self.gf` across the rayon
// pool here needs no synchronization.
let missing_set: BTreeSet<usize> = self.missing.iter().copied().collect();
for j in 0..self.total_input_slices {
if missing_set.contains(&j) {
continue;
}
let known_bytes =
known_slice(j).with_context(|| format!("reading known input slice {j}"))?;
anyhow::ensure!(
known_bytes.len() == self.slice_size,
"known slice {j} has the wrong length: expected {}, got {}",
self.slice_size,
known_bytes.len()
);
let base_j = self.gf.exp(self.logbases[j]);
adjusted
.par_iter_mut()
.zip(exponents.par_iter())
.for_each(|(row, &e)| {
let coeff = self.gf.pow(base_j, e);
mac(&self.gf, row, &known_bytes, coeff);
});
}
let a = Gf16Matrix::build_reduced(&self.gf, &bases, &exponents);
let inv = a
.invert(&self.gf)
.map_err(|e| anyhow::anyhow!("{e}"))
.context(
"the selected recovery/missing blocks produced a singular matrix \
(PAR2 does not guarantee an inverse when the available recovery \
blocks are not consecutive)",
)?;
// Each output slice `c` is an independent linear combination of the
// (shared, read-only at this point) `adjusted` rows — disjoint
// writes again, so this parallelizes the same way as the loop above.
let results: Vec<(usize, Vec<u8>)> = self
.missing
.par_iter()
.enumerate()
.map(|(c, &global_index)| {
let mut out = vec![0u8; self.slice_size];
for (r, adjusted_row) in adjusted.iter().enumerate() {
let coeff = inv.get(c, r);
if coeff != 0 {
mac(&self.gf, &mut out, adjusted_row, coeff);
}
}
(global_index, out)
})
.collect();
Ok(results)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::encoder::RecoveryEncoder;
fn make_slice(slice_size: usize, seed: u8) -> Vec<u8> {
(0..slice_size)
.map(|i| seed.wrapping_add(i as u8))
.collect()
}
fn encode(
slices: &[Vec<u8>],
slice_size: usize,
recovery_count: usize,
) -> BTreeMap<u32, Vec<u8>> {
let mut enc = RecoveryEncoder::new(slice_size, slices.len(), 0, recovery_count);
for s in slices {
enc.add_slice(s.clone());
}
let (recovery_slices, _checksums) = enc.finish();
recovery_slices
.into_iter()
.map(|s| (s.exponent, s.data))
.collect()
}
#[test]
fn reconstructs_a_single_missing_slice() {
let slice_size = 64;
let n = 5;
let slices: Vec<Vec<u8>> = (0..n)
.map(|i| make_slice(slice_size, (i as u8).wrapping_mul(17).wrapping_add(3)))
.collect();
let recovery_blocks = encode(&slices, slice_size, n);
let missing_index = 2;
let dec = RecoveryDecoder::new(slice_size, n, vec![missing_index]);
let result = dec
.reconstruct(|j| Ok(slices[j].clone()), &recovery_blocks)
.unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].0, missing_index);
assert_eq!(result[0].1, slices[missing_index]);
}
#[test]
fn reconstructs_multiple_missing_slices_using_exactly_enough_recovery_blocks() {
let slice_size = 64;
let n = 10;
let slices: Vec<Vec<u8>> = (0..n)
.map(|i| make_slice(slice_size, (i as u8).wrapping_mul(31).wrapping_add(7)))
.collect();
let recovery_count = 4;
let recovery_blocks = encode(&slices, slice_size, recovery_count);
let missing = vec![1usize, 4, 7, 9];
let dec = RecoveryDecoder::new(slice_size, n, missing.clone());
let result = dec
.reconstruct(
|j| {
assert!(
!missing.contains(&j),
"decoder must never ask for a missing slice's bytes"
);
Ok(slices[j].clone())
},
&recovery_blocks,
)
.unwrap();
let got: BTreeMap<usize, Vec<u8>> = result.into_iter().collect();
for &idx in &missing {
assert_eq!(got[&idx], slices[idx], "slice {idx} mismatch");
}
}
#[test]
fn reconstructs_correctly_with_surplus_recovery_blocks() {
// More recovery blocks are available than are strictly needed; the
// decoder should still pick exactly `m` of them and succeed.
let slice_size = 32;
let n = 8;
let slices: Vec<Vec<u8>> = (0..n)
.map(|i| make_slice(slice_size, (i as u8).wrapping_mul(5).wrapping_add(1)))
.collect();
let recovery_blocks = encode(&slices, slice_size, 6); // n=8 missing=1, way more than needed
let missing_index = 3;
let dec = RecoveryDecoder::new(slice_size, n, vec![missing_index]);
let result = dec
.reconstruct(|j| Ok(slices[j].clone()), &recovery_blocks)
.unwrap();
assert_eq!(result[0].1, slices[missing_index]);
}
#[test]
fn errors_cleanly_when_not_enough_recovery_blocks() {
let slice_size = 64;
let n = 5;
let slices: Vec<Vec<u8>> = (0..n).map(|i| make_slice(slice_size, i as u8)).collect();
let recovery_blocks = encode(&slices, slice_size, 1);
let dec = RecoveryDecoder::new(slice_size, n, vec![0, 1]);
let result = dec.reconstruct(|j| Ok(slices[j].clone()), &recovery_blocks);
assert!(result.is_err());
}
#[test]
fn reconstructing_every_slice_at_once_still_works() {
let slice_size = 32;
let n = 6;
let slices: Vec<Vec<u8>> = (0..n)
.map(|i| make_slice(slice_size, (i as u8).wrapping_mul(41).wrapping_add(2)))
.collect();
let recovery_blocks = encode(&slices, slice_size, n);
let missing: Vec<usize> = (0..n).collect();
let dec = RecoveryDecoder::new(slice_size, n, missing.clone());
let result = dec
.reconstruct(
|_| unreachable!("no known slices exist in this test"),
&recovery_blocks,
)
.unwrap();
let got: BTreeMap<usize, Vec<u8>> = result.into_iter().collect();
for i in 0..n {
assert_eq!(got[&i], slices[i]);
}
}
mod props {
use super::*;
use proptest::prelude::*;
fn distinct_below(seed: u64, count: usize, bound: usize) -> Vec<usize> {
let mut lcg = seed | 1;
let mut set = std::collections::BTreeSet::new();
while set.len() < count {
lcg = lcg
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
set.insert((lcg >> 32) as usize % bound);
}
set.into_iter().collect()
}
fn pseudo_random_bytes(seed: u64, len: usize) -> Vec<u8> {
let mut lcg = seed | 1;
(0..len)
.map(|_| {
lcg = lcg
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(lcg >> 56) as u8
})
.collect()
}
// Pinned regression check for the known CI-failing minimal inputs
// from issue #51. Across 9 observed CI failures (3 originally
// reported + 6 found later by scanning CI history), only these 3
// distinct (n, recovery_count) pairs have ever appeared, always with
// seed = 0 — despite the property covering n in 2..25 and
// recovery_count in 1..15 (360 combinations), and 9 independent
// proptest runs (each exploring 96 random cases) never landing on
// any *other* failing input. All 3 share a structural trait: `m =
// recovery_count.min(n) == n` (every input slice is missing — the
// "reconstruct everything" edge) *and* recovery_count > n (surplus
// recovery blocks are available, so `reconstruct` only uses the
// first n by exponent — see `exponents: ... .take(m)` above).
// recovery_count % 4 == 3 in all 3 known cases too, but that may be
// coincidental rather than essential — see the broader sweep below.
// Never reproduced locally so far — this exists to make each new
// investigation attempt (different core count, RAYON_NUM_THREADS,
// toolchain) trivially re-checkable without waiting on proptest to
// land on the same inputs by chance.
#[test]
fn known_ci_failing_inputs_from_issue_51() {
for (n, recovery_count) in [(2usize, 3usize), (5, 7), (9, 11)] {
let seed = 0u64;
let slice_size = 16;
let m = recovery_count.min(n);
let missing = distinct_below(seed, m, n);
let slices: Vec<Vec<u8>> = (0..n)
.map(|i| pseudo_random_bytes(seed ^ 0x9E3779B9 ^ (i as u64), slice_size))
.collect();
let recovery_blocks = encode(&slices, slice_size, recovery_count);
let dec = RecoveryDecoder::new(slice_size, n, missing.clone());
let result = dec
.reconstruct(|j| Ok(slices[j].clone()), &recovery_blocks)
.unwrap();
assert_eq!(
result.len(),
missing.len(),
"n={n} recovery_count={recovery_count}"
);
for (idx, data) in result {
assert_eq!(
data,
slices[idx].clone(),
"slice {idx} mismatch (n={n}, recovery_count={recovery_count}, missing={missing:?})"
);
}
}
}
// Exhaustively sweeps the structural condition every known CI
// failure shares — "reconstruct everything" (m == n) with surplus
// recovery blocks (recovery_count > n) — across n and surplus far
// beyond the 3 known points, and several seeds per point (not just
// 0), to check whether the trigger is that structural condition
// alone or something narrower (e.g. recovery_count % 4 == 3
// specifically, or seed == 0 specifically). Proptest's default 96
// cases per run, spread over the *entire* n/recovery_count/seed
// space, apparently doesn't sample this particular corner densely
// enough to hit it reliably even when it exists — this targets it
// directly instead of hoping general-purpose exploration finds it.
//
// Ran once (~200s, 960 real PAR2 encode/decode round trips) with
// zero mismatches found — the structural condition alone isn't
// sufficient to reproduce locally. `#[ignore]`d rather than run on
// every `cargo test`: too slow for routine/CI use, kept as an
// on-demand tool for the next investigation attempt
// (`cargo test -- --ignored everything_missing_with_surplus`).
#[test]
#[ignore]
fn everything_missing_with_surplus_recovery_blocks_sweep() {
let mut failures = Vec::new();
for n in 1usize..=20 {
for surplus in 1usize..=8 {
let recovery_count = n + surplus;
for seed in [0u64, 1, 2, 42, 12345, u64::MAX] {
let slice_size = 16;
let missing: Vec<usize> = (0..n).collect();
let slices: Vec<Vec<u8>> = (0..n)
.map(|i| {
pseudo_random_bytes(seed ^ 0x9E3779B9 ^ (i as u64), slice_size)
})
.collect();
let recovery_blocks = encode(&slices, slice_size, recovery_count);
let dec = RecoveryDecoder::new(slice_size, n, missing.clone());
let result = dec
.reconstruct(|j| Ok(slices[j].clone()), &recovery_blocks)
.unwrap();
for (idx, data) in result {
if data != slices[idx] {
failures.push((n, recovery_count, seed, idx));
}
}
}
}
}
assert!(
failures.is_empty(),
"{} mismatch(es) found: {:?}",
failures.len(),
&failures[..failures.len().min(20)]
);
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(96))]
/// End-to-end: real `RecoveryEncoder` output, an arbitrary valid
/// subset of slices treated as missing, `RecoveryDecoder`
/// reconstructs every one of them bit-exact — across randomly
/// chosen slice counts, recovery counts, and which slices are
/// missing (including the "reconstruct everything" edge and
/// "just enough recovery blocks" edge).
#[test]
fn round_trip_reconstructs_arbitrary_missing_sets(
n in 2usize..25,
recovery_count in 1usize..15,
seed in any::<u64>(),
) {
let slice_size = 16;
let m = recovery_count.min(n);
let missing = distinct_below(seed, m, n);
let slices: Vec<Vec<u8>> = (0..n)
.map(|i| pseudo_random_bytes(seed ^ 0x9E3779B9 ^ (i as u64), slice_size))
.collect();
let recovery_blocks = encode(&slices, slice_size, recovery_count);
let dec = RecoveryDecoder::new(slice_size, n, missing.clone());
let result = dec
.reconstruct(|j| Ok(slices[j].clone()), &recovery_blocks)
.unwrap();
let mismatched = result.iter().any(|(idx, data)| data != &slices[*idx]);
if mismatched {
// Diagnostic capture for issue #51: this failure has
// reproduced on CI 9 times and never once locally across
// three investigation rounds. Before failing, gather the
// two things the plain "minimal failing input" report
// never has: (1) whether it's a genuine data race (some
// retries of the *identical* inputs pass) or a
// deterministic environment-specific bug (every retry
// fails the same way), and (2) which SIMD tier and
// thread count this machine actually used, since that's
// exactly what differs between CI and every local
// attempt so far.
eprintln!(
"issue #51 diagnostic: mismatch at n={n} recovery_count={recovery_count} seed={seed}"
);
eprintln!(
" simd={} gfni={} nproc={}",
crate::detect_simd(),
{
#[cfg(target_arch = "x86_64")]
{ std::is_x86_feature_detected!("gfni") }
#[cfg(not(target_arch = "x86_64"))]
{ false }
},
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0),
);
for attempt in 1..=5 {
let retry = dec
.reconstruct(|j| Ok(slices[j].clone()), &recovery_blocks)
.unwrap();
let retry_mismatched =
retry.iter().any(|(idx, data)| data != &slices[*idx]);
eprintln!(
" retry {attempt} (same recovery_blocks): {}",
if retry_mismatched { "mismatch" } else { "MATCH (non-deterministic!)" }
);
}
// Encode fresh from the same slices too, in case the bug
// is in `encode` producing different bytes run-to-run
// (e.g. rayon scheduling) rather than in `reconstruct`.
let re_encoded = encode(&slices, slice_size, recovery_count);
eprintln!(
" re-encode produced identical recovery blocks: {}",
re_encoded == recovery_blocks
);
}
prop_assert_eq!(result.len(), missing.len());
for (idx, data) in result {
prop_assert_eq!(data, slices[idx].clone(), "slice {} mismatch", idx);
}
}
}
}
}