rsinter 0.3.0

Experimental parallel sampling and decoder benchmark harness for RustQEC
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
use std::fs::{self, File};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;

use rstim::dem::DetectorErrorModel;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[cfg(any(
    feature = "rbposd-runner",
    feature = "rmatching-runner",
    feature = "ilp-runner"
))]
use serde_json::json;
use sha2::{Digest, Sha256};

use crate::decode::Decoder;

#[derive(Debug, Clone)]
pub struct ReplayOptions {
    pub dem: PathBuf,
    pub dets: PathBuf,
    pub decoder: String,
    pub decoder_config: Option<PathBuf>,
    pub predictions_out: PathBuf,
    pub stats_out: PathBuf,
    pub batch_size: usize,
    pub shots: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplayStats {
    pub schema_version: u32,
    pub decoder: String,
    pub decoder_config: Value,
    pub num_shots: usize,
    pub num_detectors: usize,
    pub num_observables: usize,
    pub batch_size: usize,
    pub batches: usize,
    pub compile_seconds: f64,
    pub decode_seconds: f64,
    pub shots_per_second: f64,
    pub detector_bytes: u64,
    pub prediction_bytes: u64,
    pub dem_sha256: String,
    pub detectors_sha256: String,
    pub predictions_sha256: String,
}

pub fn run_replay(options: &ReplayOptions) -> Result<ReplayStats, String> {
    validate_options(options)?;

    let dem_bytes = fs::read(&options.dem)
        .map_err(|error| format!("failed to read DEM {}: {error}", options.dem.display()))?;
    let dem_text = std::str::from_utf8(&dem_bytes)
        .map_err(|error| format!("DEM {} is not UTF-8: {error}", options.dem.display()))?;
    let dem = DetectorErrorModel::parse(dem_text)
        .map_err(|error| format!("failed to parse DEM {}: {error}", options.dem.display()))?;
    let num_detectors = dem.effective_num_detectors();
    let num_observables = dem.num_observables();
    let detector_row_bytes = num_detectors.div_ceil(8);
    let prediction_row_bytes = num_observables.div_ceil(8);

    let detector_file = File::open(&options.dets).map_err(|error| {
        format!(
            "failed to open detectors {}: {error}",
            options.dets.display()
        )
    })?;
    let detector_bytes = detector_file
        .metadata()
        .map_err(|error| {
            format!(
                "failed to stat open detectors {}: {error}",
                options.dets.display()
            )
        })?
        .len();
    let num_shots = infer_num_shots(detector_bytes, detector_row_bytes, options.shots)?;

    let config_text = match &options.decoder_config {
        Some(path) => fs::read_to_string(path).map_err(|error| {
            format!("failed to read decoder config {}: {error}", path.display())
        })?,
        None => String::new(),
    };
    let (decoder, normalized_config) = build_decoder(&options.decoder, &config_text)?;
    let compile_started = Instant::now();
    let compiled = decoder
        .compile_for_dem(&dem)
        .map_err(|error| format!("failed to compile {} decoder: {error}", options.decoder))?;
    let compile_seconds = compile_started.elapsed().as_secs_f64();

    let prediction_parent = parent_dir(&options.predictions_out);
    let stats_parent = parent_dir(&options.stats_out);
    fs::create_dir_all(prediction_parent).map_err(|error| {
        format!(
            "failed to create output directory {}: {error}",
            prediction_parent.display()
        )
    })?;
    fs::create_dir_all(stats_parent).map_err(|error| {
        format!(
            "failed to create output directory {}: {error}",
            stats_parent.display()
        )
    })?;

    let mut prediction_temp = tempfile::NamedTempFile::new_in(prediction_parent)
        .map_err(|error| format!("failed to create prediction temp file: {error}"))?;
    let mut detector_reader = BufReader::new(detector_file);
    let mut prediction_writer = BufWriter::new(prediction_temp.as_file_mut());
    let mut detector_hasher = Sha256::new();
    let mut prediction_hasher = Sha256::new();
    let mut batches = 0usize;
    let mut shots_completed = 0usize;
    let mut decode_seconds = 0.0f64;

    while shots_completed < num_shots {
        let batch_shots = options.batch_size.min(num_shots - shots_completed);
        let batch_bytes = batch_shots
            .checked_mul(detector_row_bytes)
            .ok_or_else(|| "detector batch size overflow".to_string())?;
        let mut detector_batch = vec![0u8; batch_bytes];
        detector_reader
            .read_exact(&mut detector_batch)
            .map_err(|error| {
                format!("failed to read detector batch at shot {shots_completed}: {error}")
            })?;
        validate_padding(
            &detector_batch,
            batch_shots,
            num_detectors,
            "detector input",
            shots_completed,
        )?;
        detector_hasher.update(&detector_batch);

        let decode_started = Instant::now();
        let predictions = compiled
            .decode_shots_bit_packed(&detector_batch, batch_shots, num_detectors, num_observables)
            .map_err(|error| format!("decoder failed at shot {shots_completed}: {error}"))?;
        decode_seconds += decode_started.elapsed().as_secs_f64();
        let expected = batch_shots
            .checked_mul(prediction_row_bytes)
            .ok_or_else(|| "prediction batch size overflow".to_string())?;
        if predictions.len() != expected {
            return Err(format!(
                "decoder returned {} prediction bytes, expected {expected}",
                predictions.len()
            ));
        }
        validate_padding(
            &predictions,
            batch_shots,
            num_observables,
            "decoder predictions",
            shots_completed,
        )?;
        prediction_hasher.update(&predictions);
        prediction_writer
            .write_all(&predictions)
            .map_err(|error| format!("failed to write predictions: {error}"))?;
        shots_completed += batch_shots;
        batches += 1;
    }
    let mut trailing = [0u8; 1];
    if detector_reader
        .read(&mut trailing)
        .map_err(|error| format!("failed to finish detector input: {error}"))?
        != 0
    {
        return Err("detector input changed while replaying or contains trailing bytes".into());
    }
    prediction_writer
        .flush()
        .map_err(|error| format!("failed to flush predictions: {error}"))?;
    drop(prediction_writer);

    let prediction_bytes = u64::try_from(num_shots)
        .ok()
        .and_then(|shots| shots.checked_mul(prediction_row_bytes as u64))
        .ok_or_else(|| "prediction byte count overflow".to_string())?;
    let stats = ReplayStats {
        schema_version: 1,
        decoder: options.decoder.clone(),
        decoder_config: normalized_config,
        num_shots,
        num_detectors,
        num_observables,
        batch_size: options.batch_size,
        batches,
        compile_seconds,
        decode_seconds,
        shots_per_second: if decode_seconds > 0.0 {
            num_shots as f64 / decode_seconds
        } else {
            0.0
        },
        detector_bytes,
        prediction_bytes,
        dem_sha256: sha256_hex(&dem_bytes),
        detectors_sha256: digest_hex(detector_hasher.finalize()),
        predictions_sha256: digest_hex(prediction_hasher.finalize()),
    };

    let mut stats_temp = tempfile::NamedTempFile::new_in(stats_parent)
        .map_err(|error| format!("failed to create stats temp file: {error}"))?;
    serde_json::to_writer_pretty(stats_temp.as_file_mut(), &stats)
        .map_err(|error| format!("failed to serialize replay stats: {error}"))?;
    stats_temp
        .as_file_mut()
        .write_all(b"\n")
        .map_err(|error| format!("failed to finish replay stats: {error}"))?;
    stats_temp
        .as_file_mut()
        .sync_all()
        .map_err(|error| format!("failed to sync replay stats: {error}"))?;
    prediction_temp
        .as_file()
        .sync_all()
        .map_err(|error| format!("failed to sync predictions: {error}"))?;

    prediction_temp
        .persist(&options.predictions_out)
        .map_err(|error| format!("failed to install predictions: {}", error.error))?;
    stats_temp
        .persist(&options.stats_out)
        .map_err(|error| format!("failed to install replay stats: {}", error.error))?;
    Ok(stats)
}

fn validate_options(options: &ReplayOptions) -> Result<(), String> {
    if options.batch_size == 0 {
        return Err("batch_size must be positive".into());
    }
    let mut paths = vec![
        (&options.dem, "DEM input"),
        (&options.dets, "detector input"),
        (&options.predictions_out, "prediction output"),
        (&options.stats_out, "stats output"),
    ];
    if let Some(config) = &options.decoder_config {
        paths.push((config, "decoder config input"));
    }
    for left in 0..paths.len() {
        for right in left + 1..paths.len() {
            if same_path(paths[left].0, paths[right].0)? {
                return Err(format!(
                    "{} and {} must use different paths",
                    paths[left].1, paths[right].1
                ));
            }
        }
    }
    Ok(())
}

fn same_path(left: &Path, right: &Path) -> Result<bool, String> {
    Ok(resolve_for_comparison(left)? == resolve_for_comparison(right)?)
}

fn resolve_for_comparison(path: &Path) -> Result<PathBuf, String> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|error| format!("failed to resolve current directory: {error}"))?
            .join(path)
    };
    let mut resolved = PathBuf::new();
    for component in absolute.components() {
        match component {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                resolved.pop();
            }
            other => {
                resolved.push(other.as_os_str());
                if resolved.exists() {
                    resolved = fs::canonicalize(&resolved).map_err(|error| {
                        format!("failed to canonicalize {}: {error}", resolved.display())
                    })?;
                }
            }
        }
    }
    Ok(resolved)
}

fn infer_num_shots(
    detector_bytes: u64,
    row_bytes: usize,
    requested: Option<usize>,
) -> Result<usize, String> {
    if row_bytes == 0 {
        if detector_bytes != 0 {
            return Err(format!(
                "zero-detector DEM requires an empty detector input, got {detector_bytes} bytes"
            ));
        }
        return requested
            .ok_or_else(|| "--shots is required when the DEM declares zero detectors".to_string());
    }
    let row_bytes = row_bytes as u64;
    if detector_bytes % row_bytes != 0 {
        return Err(format!(
            "detector input has {detector_bytes} bytes, not divisible by row width {row_bytes}"
        ));
    }
    let inferred = usize::try_from(detector_bytes / row_bytes)
        .map_err(|_| "detector shot count exceeds usize".to_string())?;
    if let Some(requested) = requested {
        if requested != inferred {
            return Err(format!(
                "--shots={requested} does not match {inferred} rows in detector input"
            ));
        }
    }
    Ok(inferred)
}

fn validate_padding(
    bytes: &[u8],
    shots: usize,
    bits_per_shot: usize,
    label: &str,
    shot_offset: usize,
) -> Result<(), String> {
    let remainder = bits_per_shot % 8;
    if remainder == 0 || bits_per_shot == 0 {
        return Ok(());
    }
    let row_bytes = bits_per_shot.div_ceil(8);
    let padding_mask = !((1u8 << remainder) - 1);
    for shot in 0..shots {
        let byte = bytes[shot * row_bytes + row_bytes - 1];
        if byte & padding_mask != 0 {
            return Err(format!(
                "{label} has non-zero b8 padding bits at shot {}",
                shot_offset + shot
            ));
        }
    }
    Ok(())
}

fn parent_dir(path: &Path) -> &Path {
    path.parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or(Path::new("."))
}

fn sha256_hex(bytes: &[u8]) -> String {
    digest_hex(Sha256::digest(bytes))
}

fn digest_hex(bytes: impl AsRef<[u8]>) -> String {
    bytes
        .as_ref()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

#[cfg(feature = "rbposd-runner")]
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RbposdConfigFile {
    bp_method: Option<String>,
    bp_schedule: Option<String>,
    max_bp_iterations: Option<usize>,
    early_stop: Option<bool>,
    osd_method: Option<String>,
    osd_order: Option<usize>,
}

#[cfg(feature = "rbposd-runner")]
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RbplsdConfigFile {
    bp_method: Option<String>,
    bp_schedule: Option<String>,
    max_bp_iterations: Option<usize>,
    early_stop: Option<bool>,
    lsd_method: Option<String>,
    lsd_order: Option<usize>,
}

#[cfg(feature = "rmatching-runner")]
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RmatchingConfigFile {}

#[cfg(feature = "ilp-runner")]
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RilpqecConfigFile {
    backend: Option<String>,
    time_limit_s: Option<f64>,
    mip_gap: Option<f64>,
    threads: Option<u32>,
    verbose: Option<bool>,
}

fn build_decoder(name: &str, config: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    match name {
        "rbposd" => build_rbposd(config),
        "rbplsd" => build_rbplsd(config),
        "rmatching" => build_rmatching(config),
        "rilpqec" => build_rilpqec(config),
        other => Err(format!(
            "unknown decoder {other:?}; expected rbposd, rbplsd, rmatching, or rilpqec"
        )),
    }
}

#[cfg(any(
    feature = "rbposd-runner",
    feature = "rmatching-runner",
    feature = "ilp-runner"
))]
fn parse_config<T>(text: &str, decoder: &str) -> Result<T, String>
where
    T: for<'de> Deserialize<'de> + Default,
{
    if text.trim().is_empty() {
        Ok(T::default())
    } else {
        toml::from_str(text).map_err(|error| format!("invalid {decoder} decoder config: {error}"))
    }
}

#[cfg(feature = "rbposd-runner")]
fn bp_config(
    method: Option<String>,
    schedule: Option<String>,
    iterations: Option<usize>,
    early_stop: Option<bool>,
) -> Result<(rbposd::DecoderConfig, Value), String> {
    use rbposd::{BpVariant, DecoderConfig, Schedule};
    let mut config = DecoderConfig::default();
    let method = method.unwrap_or_else(|| "minimum_sum".into());
    config.bp_variant = match method.as_str() {
        "minimum_sum" => BpVariant::MinimumSum,
        "product_sum" => BpVariant::ProductSum,
        _ => return Err(format!("unknown bp_method {method:?}")),
    };
    let schedule = schedule.unwrap_or_else(|| "parallel".into());
    config.schedule = match schedule.as_str() {
        "parallel" => Schedule::Parallel,
        "serial" => Schedule::Serial,
        _ => return Err(format!("unknown bp_schedule {schedule:?}")),
    };
    config.max_bp_iterations = iterations.unwrap_or(config.max_bp_iterations);
    config.early_stop = early_stop.unwrap_or(config.early_stop);
    Ok((
        config,
        json!({
            "bp_method": method,
            "bp_schedule": schedule,
            "max_bp_iterations": config.max_bp_iterations,
            "early_stop": config.early_stop,
        }),
    ))
}

#[cfg(feature = "rbposd-runner")]
fn build_rbposd(text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    use crate::decode::RbposdDemDecoder;
    use rbposd::OsdVariant;
    let file: RbposdConfigFile = parse_config(text, "rbposd")?;
    let (mut config, mut normalized) = bp_config(
        file.bp_method,
        file.bp_schedule,
        file.max_bp_iterations,
        file.early_stop,
    )?;
    let requested_method = file.osd_method.unwrap_or_else(|| "osd0".into());
    let (variant, method) = match requested_method.as_str() {
        "osd0" => (OsdVariant::Osd0, "osd0"),
        "combination_sweep" | "legacy_combination_sweep" => (
            OsdVariant::LegacyCombinationSweep,
            "legacy_combination_sweep",
        ),
        "ldpc_osd_cs" | "osd_cs" => (OsdVariant::LdpcCombinationSweep, "ldpc_osd_cs"),
        _ => return Err(format!("unknown osd_method {requested_method:?}")),
    };
    config.osd_variant = variant;
    config.osd_order = file.osd_order.unwrap_or(config.osd_order);
    if config.osd_variant == OsdVariant::Osd0 && config.osd_order != 0 {
        return Err("osd_method=\"osd0\" requires osd_order=0".into());
    }
    normalized["osd_method"] = json!(method);
    normalized["osd_order"] = json!(config.osd_order);
    Ok((Box::new(RbposdDemDecoder::new(config)), normalized))
}

#[cfg(not(feature = "rbposd-runner"))]
fn build_rbposd(_text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    Err("decoder rbposd requires Cargo feature 'rbposd-runner'".into())
}

#[cfg(feature = "rbposd-runner")]
fn build_rbplsd(text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    use crate::decode::RbposdLsdDemDecoder;
    use rbposd::{LsdConfig, LsdMethod};
    let file: RbplsdConfigFile = parse_config(text, "rbplsd")?;
    let (bp, mut normalized) = bp_config(
        file.bp_method,
        file.bp_schedule,
        file.max_bp_iterations,
        file.early_stop,
    )?;
    let method = file
        .lsd_method
        .unwrap_or_else(|| "localized_statistics".into());
    if method != "localized_statistics" {
        return Err(format!("unknown lsd_method {method:?}"));
    }
    let order = file.lsd_order.unwrap_or(0);
    if order > 1 {
        return Err(format!("lsd_order must be 0 or 1, got {order}"));
    }
    normalized["lsd_method"] = json!(method);
    normalized["lsd_order"] = json!(order);
    Ok((
        Box::new(RbposdLsdDemDecoder::with_bp_config(
            LsdConfig {
                method: LsdMethod::LocalizedStatistics,
                lsd_order: order,
            },
            bp,
        )),
        normalized,
    ))
}

#[cfg(not(feature = "rbposd-runner"))]
fn build_rbplsd(_text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    Err("decoder rbplsd requires Cargo feature 'rbposd-runner'".into())
}

#[cfg(feature = "rmatching-runner")]
fn build_rmatching(text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    use crate::decode::RmatchingDemDecoder;
    let _: RmatchingConfigFile = parse_config(text, "rmatching")?;
    Ok((Box::new(RmatchingDemDecoder), json!({})))
}

#[cfg(not(feature = "rmatching-runner"))]
fn build_rmatching(_text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    Err("decoder rmatching requires Cargo feature 'rmatching-runner'".into())
}

#[cfg(feature = "ilp-runner")]
fn build_rilpqec(text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    use crate::decode::IlpDemDecoder;
    use qec_ilp_core::BackendKind;
    use rilpqec::IlpDecoderConfig;
    let file: RilpqecConfigFile = parse_config(text, "rilpqec")?;
    let backend = file.backend.unwrap_or_else(|| "auto".into());
    let mut config = IlpDecoderConfig::default();
    config.backend.kind = match backend.as_str() {
        "auto" => BackendKind::Auto,
        "highs" => BackendKind::Highs,
        "gurobi" => BackendKind::Gurobi,
        _ => return Err(format!("unknown rilpqec backend {backend:?}")),
    };
    if file
        .time_limit_s
        .is_some_and(|value| !value.is_finite() || value <= 0.0)
    {
        return Err("time_limit_s must be positive and finite".into());
    }
    if file
        .mip_gap
        .is_some_and(|value| !value.is_finite() || !(0.0..1.0).contains(&value))
    {
        return Err("mip_gap must be finite and in [0, 1)".into());
    }
    if file.threads == Some(0) {
        return Err("threads must be positive".into());
    }
    config.backend.time_limit_seconds = file.time_limit_s;
    config.backend.mip_gap = file.mip_gap;
    config.backend.threads = file.threads;
    config.backend.verbose = file.verbose.unwrap_or(false);
    let normalized = json!({
        "backend": backend,
        "time_limit_s": config.backend.time_limit_seconds,
        "mip_gap": config.backend.mip_gap,
        "threads": config.backend.threads,
        "verbose": config.backend.verbose,
    });
    Ok((Box::new(IlpDemDecoder::new(config)), normalized))
}

#[cfg(not(feature = "ilp-runner"))]
fn build_rilpqec(_text: &str) -> Result<(Box<dyn Decoder>, Value), String> {
    Err("decoder rilpqec requires Cargo feature 'ilp-runner'".into())
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::{build_decoder, same_path};

    #[cfg(feature = "rbposd-runner")]
    #[test]
    fn rbposd_and_rbplsd_configs_are_normalized() {
        let (_, osd) = build_decoder(
            "rbposd",
            "bp_method = \"product_sum\"\nbp_schedule = \"serial\"\nosd_method = \"ldpc_osd_cs\"\nosd_order = 3\n",
        )
        .unwrap();
        assert_eq!(osd["bp_method"], "product_sum");
        assert_eq!(osd["bp_schedule"], "serial");
        assert_eq!(osd["osd_method"], "ldpc_osd_cs");
        assert_eq!(osd["osd_order"], 3);

        let (_, legacy) = build_decoder("rbposd", "osd_method = \"combination_sweep\"\n").unwrap();
        assert_eq!(legacy["osd_method"], "legacy_combination_sweep");

        let (_, lsd) = build_decoder("rbplsd", "lsd_order = 1\n").unwrap();
        assert_eq!(lsd["lsd_method"], "localized_statistics");
        assert_eq!(lsd["lsd_order"], 1);
    }

    #[test]
    fn decoder_configs_reject_invalid_values_and_unknown_names() {
        #[cfg(feature = "rbposd-runner")]
        assert!(
            build_decoder("rbposd", "bp_method = \"sum_product\"\n")
                .err()
                .unwrap()
                .contains("unknown bp_method")
        );
        #[cfg(feature = "rbposd-runner")]
        assert!(
            build_decoder("rbposd", "bp_schedule = \"random\"\n")
                .err()
                .unwrap()
                .contains("unknown bp_schedule")
        );
        #[cfg(feature = "rbposd-runner")]
        assert!(
            build_decoder("rbposd", "osd_method = \"mystery\"\n")
                .err()
                .unwrap()
                .contains("unknown osd_method")
        );
        #[cfg(feature = "rbposd-runner")]
        assert!(
            build_decoder("rbplsd", "lsd_method = \"mystery\"\n")
                .err()
                .unwrap()
                .contains("unknown lsd_method")
        );
        #[cfg(feature = "rbposd-runner")]
        assert!(
            build_decoder("rbplsd", "lsd_order = 2\n")
                .err()
                .unwrap()
                .contains("0 or 1")
        );
        #[cfg(feature = "rbposd-runner")]
        assert!(
            build_decoder("rbposd", "osd_method = \"osd0\"\nosd_order = 1\n")
                .err()
                .unwrap()
                .contains("requires osd_order=0")
        );
        #[cfg(feature = "ilp-runner")]
        assert!(
            build_decoder("rilpqec", "mip_gap = 1.0\n")
                .err()
                .unwrap()
                .contains("[0, 1)")
        );
        #[cfg(feature = "ilp-runner")]
        assert!(
            build_decoder("rilpqec", "backend = \"mystery\"\n")
                .err()
                .unwrap()
                .contains("unknown rilpqec backend")
        );
        #[cfg(feature = "ilp-runner")]
        assert!(
            build_decoder("rilpqec", "time_limit_s = 0.0\n")
                .err()
                .unwrap()
                .contains("positive and finite")
        );
        #[cfg(feature = "ilp-runner")]
        assert!(
            build_decoder("rilpqec", "threads = 0\n")
                .err()
                .unwrap()
                .contains("threads must be positive")
        );
        #[cfg(feature = "ilp-runner")]
        for backend in ["highs", "gurobi"] {
            let (_, normalized) = build_decoder(
                "rilpqec",
                &format!(
                    "backend = \"{backend}\"\ntime_limit_s = 1.0\nmip_gap = 0.25\nthreads = 1\nverbose = true\n"
                ),
            )
            .unwrap();
            assert_eq!(normalized["backend"], backend);
            assert_eq!(normalized["threads"], 1);
        }
        assert!(
            build_decoder("mystery", "")
                .err()
                .unwrap()
                .contains("unknown decoder")
        );
    }

    #[test]
    fn path_comparison_normalizes_relative_parent_components() {
        assert!(same_path(Path::new("replay/a/../out"), Path::new("replay/out")).unwrap());
        assert!(!same_path(Path::new("replay/left"), Path::new("replay/right")).unwrap());
    }

    #[cfg(unix)]
    #[test]
    fn path_comparison_resolves_symlinked_existing_ancestors() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().unwrap();
        let real = temp.path().join("real");
        let alias = temp.path().join("alias");
        std::fs::create_dir(&real).unwrap();
        symlink(&real, &alias).unwrap();

        assert!(same_path(&real.join("result"), &alias.join("result")).unwrap());
        let nested = temp.path().join("nested");
        std::fs::create_dir(&nested).unwrap();
        let nested_alias = temp.path().join("nested-alias");
        symlink(&nested, &nested_alias).unwrap();
        assert!(
            same_path(
                &nested_alias.join("..").join("result"),
                &temp.path().join("result")
            )
            .unwrap()
        );
    }
}