xpile 0.1.0

Polyglot transpile workbench (Python/C/C++/Rust/Ruchy/Lean ↔ Rust/Ruchy/PTX/WGSL/SPIR-V) with provable contracts at every layer.
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
//! Differential execution check (PMAT-018 / XPILE-DIFF-001 +
//! XPILE-DIFF-002 + XPILE-DIFF-003).
//!
//! For each fixture in the curated set, generate N deterministic
//! inputs inside the fast-path domain, run both:
//!   (a) CPython directly on the .py source
//!   (b) The transpiled Rust binary compiled by rustc -O
//! and assert the outputs agree.
//!
//! This is xpile's analog of ruchy 5.0 §14.10.4. It generalises the
//! 11 hand-authored runtime-verified fixtures from a few hand-picked
//! values to N machine-generated values per function — closing the
//! "fixture overfitting" caveat from audit-design.md §4
//! quantitatively rather than by adding more hand-authored cases.
//!
//! Scope at v0.1.0:
//!   * 1-arg and 2-arg i64-returning fixtures (XPILE-DIFF-001/002).
//!   * Hardcoded per-fixture input range so generated inputs stay
//!     inside the C-PY-INT-ARITH fast-path domain (no i64 overflow
//!     panics).
//!   * **XPILE-DIFF-003**: optional per-fixture `overflow_args` ranges
//!     where the i64 fast path *must* overflow. CPython promotes to
//!     BigInt and returns the mathematical result; xpile's emit (in
//!     non-BigInt mode) `.checked_*().expect(...)`-panics with a
//!     message citing `C-PY-INT-ARITH`. The gate interprets that
//!     panic as a *documented promotion gap* and counts it under
//!     `promotion_gaps`. Test failure modes (vs. the gap):
//!       - Rust exits zero with a value that diverges from Python
//!         → silent miscompile, hard fail.
//!       - Rust panics without naming `C-PY-INT-ARITH` → off-contract
//!         crash, hard fail.
//!   * N = 10 inputs per fixture for both fast-path and overflow
//!     phases. Deterministic via a fixed-seed LCG.
//!
//! Skip behaviour: if `python3` or `rustc` is missing from PATH, the
//! test prints a warning and exits OK — same posture as the existing
//! `assert_rustc_runs` helper. CI environments that have both still
//! run the gate.

use std::path::{Path, PathBuf};
use std::process::Command;

fn fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name)
}

fn xpile_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_xpile"))
}

// Curated set of fixtures + per-arg [min, max] input ranges that stay
// inside the C-PY-INT-ARITH fast path (no overflow panics). Each entry
// is (file, entry-function, fast-path-range[], overflow-range[]). The
// slice length is the function's arity. XPILE-DIFF-002 extended from
// single-arg to 2-arg; XPILE-DIFF-003 adds the optional `overflow_args`
// slice for inputs that intentionally overflow the i64 fast path.
struct FixtureCfg {
    file: &'static str,
    entry: &'static str,
    // Per-arg `(min, max)` (inclusive). Slice length is the arity.
    args: &'static [(i64, i64)],
    // XPILE-DIFF-003: per-arg overflow range. If non-empty, the gate
    // additionally runs INPUTS_PER_FIXTURE inputs from this domain
    // and *expects* the Rust binary to panic citing C-PY-INT-ARITH
    // (the documented promotion gap). If the slice is empty, the
    // fixture has no overflow demo and only the fast-path phase
    // runs. Slice length, when non-empty, must match `args.len()`.
    overflow_args: &'static [(i64, i64)],
}

const FIXTURES: &[FixtureCfg] = &[
    // ── 1-arg fixtures (carried over from XPILE-DIFF-001) ────────
    FixtureCfg {
        file: "factorial.py",
        entry: "factorial",
        // 13! overflows i64 if accumulated naively; 21! definitely
        // overflows.
        args: &[(0, 12)],
        // XPILE-DIFF-003: factorial(n) for n ≥ 21 always overflows
        // i64. Python promotes; xpile's i64 emit panics with
        // C-PY-INT-ARITH cited.
        overflow_args: &[(21, 30)],
    },
    FixtureCfg {
        file: "fib.py",
        entry: "fib",
        // F(30) = 832040, safe; F(94) is the i64 limit but tree-
        // recursion makes large n painfully slow.
        args: &[(0, 30)],
        overflow_args: &[],
    },
    FixtureCfg {
        file: "abs_val.py",
        entry: "abs_val",
        args: &[(-1_000_000, 1_000_000)],
        overflow_args: &[],
    },
    FixtureCfg {
        file: "sign.py",
        entry: "sign",
        args: &[(-1_000_000_000, 1_000_000_000)],
        overflow_args: &[],
    },
    FixtureCfg {
        file: "sum_to.py",
        entry: "sum_to",
        // sum(1..65535) ≈ 2.1e9, well under i64
        args: &[(0, 65_535)],
        overflow_args: &[],
    },
    FixtureCfg {
        file: "for_sum.py",
        entry: "for_sum",
        args: &[(0, 65_535)],
        overflow_args: &[],
    },
    FixtureCfg {
        file: "countdown.py",
        entry: "factorial_iter",
        args: &[(0, 12)],
        // XPILE-DIFF-003: same overflow story as recursive factorial.
        overflow_args: &[(21, 30)],
    },
    // ── 2-arg fixtures (added XPILE-DIFF-002) ────────────────────
    FixtureCfg {
        file: "gcd.py",
        entry: "gcd",
        // gcd handles 0 and 0 correctly (returns 0 in both Python
        // and our emission). Negative inputs work but Python's
        // math.gcd convention is non-negative result — easier to
        // restrict to non-negative inputs and avoid that asymmetry.
        args: &[(0, 1_000_000), (0, 1_000_000)],
        // gcd is non-expanding (output ≤ min(|a|, |b|)) so it never
        // overflows. No overflow demo.
        overflow_args: &[],
    },
    FixtureCfg {
        file: "multi_branch.py",
        entry: "range_size",
        // range_size = abs(a - b); inputs bounded so the difference
        // can't overflow i64.
        args: &[
            (-1_000_000_000, 1_000_000_000),
            (-1_000_000_000, 1_000_000_000),
        ],
        overflow_args: &[],
    },
    FixtureCfg {
        file: "bits.py",
        entry: "bits",
        // bits.py: `((a & b) | (a ^ b)) << 2 >> 1`. The constant-shift-
        // by-2 means inputs must stay in [-2^61, 2^61) to avoid
        // overflow on the left-shift, and the inner ops don't widen.
        args: &[
            (-i64::pow(2, 61) + 1, i64::pow(2, 61) - 1),
            (-i64::pow(2, 61) + 1, i64::pow(2, 61) - 1),
        ],
        overflow_args: &[],
    },
];

/// Deterministic LCG (numerical recipes constants). Seeded once per
/// test for reproducibility; not crypto, just for input variety.
struct Lcg(u64);
impl Lcg {
    fn new(seed: u64) -> Self {
        Lcg(seed)
    }
    fn next_u64(&mut self) -> u64 {
        self.0 = self
            .0
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        self.0
    }
    /// Pick an i64 uniformly in `[lo, hi]` (inclusive).
    fn next_i64_in(&mut self, lo: i64, hi: i64) -> i64 {
        assert!(lo <= hi);
        let span = (hi - lo) as u64 + 1;
        let r = self.next_u64() % span;
        lo + r as i64
    }
}

/// Check tool availability. Returns false if either python3 or rustc
/// is missing — test caller short-circuits with a warning print.
fn have_python_and_rustc() -> bool {
    let py = Command::new("python3").arg("--version").output().is_ok();
    let rs = Command::new("rustc").arg("--version").output().is_ok();
    py && rs
}

/// Build the transpiled-Rust binary for an N-arg fixture. The synth
/// driver reads N i64s from CLI argv and calls `entry(a0, a1, ...)`.
///
/// XPILE-DIFF-002 generalised this from 1-arg only.
/// PMAT-036 (XPILE-DIFF-003 follow-up): when the transpile output
/// references `xpile_bigint::BigInt` (PMAT-013 implicit-promotion
/// path), we build via a tiny temp Cargo project that depends on the
/// workspace's `xpile-bigint` crate. Otherwise we keep the fast
/// standalone-rustc path. This is the architectural payoff for
/// closing the DIFF-003 documented gaps: the runner can now
/// validate BigInt-mode emit end-to-end against CPython on
/// overflow inputs without a hand-rolled shim.
fn build_rust_binary(
    fixture_path: &Path,
    entry: &str,
    arity: usize,
    out_dir: &Path,
) -> Result<PathBuf, String> {
    // Transpile via the xpile binary so we exercise the real CLI path.
    let out = Command::new(xpile_bin())
        .args([
            "transpile",
            fixture_path.to_str().unwrap(),
            "--target",
            "rust",
        ])
        .output()
        .map_err(|e| format!("spawn xpile: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "xpile transpile failed: {}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    let transpiled = String::from_utf8(out.stdout).map_err(|e| format!("utf8: {e}"))?;
    let uses_bigint = transpiled.contains("xpile_bigint::BigInt");

    if uses_bigint {
        build_rust_binary_bigint(&transpiled, entry, arity, out_dir)
    } else {
        build_rust_binary_i64(&transpiled, entry, arity, out_dir)
    }
}

/// Standalone-rustc fast path for fixtures that don't use BigInt.
fn build_rust_binary_i64(
    transpiled: &str,
    entry: &str,
    arity: usize,
    out_dir: &Path,
) -> Result<PathBuf, String> {
    let call_args: Vec<String> = (0..arity).map(|i| format!("argv[{i}]")).collect();
    let call = format!("{entry}({})", call_args.join(", "));
    let driver = format!(
        r#"
fn main() {{
    let argv: Vec<i64> = std::env::args()
        .skip(1)
        .map(|s| s.parse::<i64>().expect("parse i64"))
        .collect();
    assert_eq!(argv.len(), {arity}, "expected {arity} args");
    println!("{{}}", {call});
}}
"#
    );
    let merged = format!("{transpiled}\n{driver}\n");

    let rs_file = out_dir.join(format!("{entry}.rs"));
    std::fs::write(&rs_file, &merged).map_err(|e| format!("write rs: {e}"))?;

    let bin_path = out_dir.join(entry);
    let compile = Command::new("rustc")
        .args([
            "--edition=2021",
            "-O",
            "-o",
            bin_path.to_str().unwrap(),
            rs_file.to_str().unwrap(),
        ])
        .output()
        .map_err(|e| format!("spawn rustc: {e}"))?;
    if !compile.status.success() {
        return Err(format!(
            "rustc failed:\n=== source ===\n{merged}\n=== stderr ===\n{}",
            String::from_utf8_lossy(&compile.stderr)
        ));
    }
    Ok(bin_path)
}

/// Cargo-based build path for fixtures whose transpile output uses
/// `xpile_bigint::BigInt`. Materialises a one-shot Cargo project that
/// depends on the in-workspace `xpile-bigint` crate (path dep), so
/// the produced binary has access to the real `num_bigint::BigInt`
/// via the re-export — including `Display` for the driver's
/// `println!("{{}}", entry(...))`, which is what gets compared to
/// CPython's stdout.
fn build_rust_binary_bigint(
    transpiled: &str,
    entry: &str,
    arity: usize,
    out_dir: &Path,
) -> Result<PathBuf, String> {
    // Argv parses i64 strings (the gate's input domain is i64); each
    // is lifted into `xpile_bigint::BigInt`. Then the entry call sites
    // need `.clone()`-friendly inputs since BigInt isn't Copy.
    let call_args: Vec<String> = (0..arity).map(|i| format!("argv[{i}].clone()")).collect();
    let call = format!("{entry}({})", call_args.join(", "));
    let driver = format!(
        r#"
fn main() {{
    let argv: Vec<xpile_bigint::BigInt> = std::env::args()
        .skip(1)
        .map(|s| {{
            let n: i64 = s.parse().expect("parse i64");
            xpile_bigint::BigInt::from(n)
        }})
        .collect();
    assert_eq!(argv.len(), {arity}, "expected {arity} args");
    println!("{{}}", {call});
}}
"#
    );
    let merged = format!("{transpiled}\n{driver}\n");

    // Resolve the path to the in-workspace xpile-bigint crate. The
    // test crate's CARGO_MANIFEST_DIR is `<workspace>/crates/xpile`;
    // xpile-bigint is at `<workspace>/crates/xpile-bigint`.
    let xpile_bigint_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("crates/")
        .join("xpile-bigint");

    let pkg_dir = out_dir.join(format!("{entry}-cargo"));
    let src_dir = pkg_dir.join("src");
    std::fs::create_dir_all(&src_dir).map_err(|e| format!("create dir: {e}"))?;

    // The crate name uses underscores; Cargo's [package].name uses
    // hyphens. The binary on disk will end up as `<entry>`.
    let cargo_toml = format!(
        r#"[package]
name = "{entry}-bin"
version = "0.0.0"
edition = "2021"

[[bin]]
name = "{entry}"
path = "src/main.rs"

[dependencies]
xpile-bigint = {{ path = "{}" }}
"#,
        xpile_bigint_dir.display()
    );
    std::fs::write(pkg_dir.join("Cargo.toml"), &cargo_toml)
        .map_err(|e| format!("write Cargo.toml: {e}"))?;
    std::fs::write(src_dir.join("main.rs"), &merged).map_err(|e| format!("write main.rs: {e}"))?;

    // Pin --target-dir to the temp package's own subdir so the build
    // output is at a path we control, regardless of any global
    // `CARGO_TARGET_DIR` env or `.cargo/config.toml` setting.
    let target_dir = pkg_dir.join("target");
    let build = Command::new("cargo")
        .args([
            "build",
            "--release",
            "--quiet",
            "--manifest-path",
            pkg_dir.join("Cargo.toml").to_str().unwrap(),
            "--target-dir",
            target_dir.to_str().unwrap(),
        ])
        .output()
        .map_err(|e| format!("spawn cargo: {e}"))?;
    if !build.status.success() {
        return Err(format!(
            "cargo build (BigInt path) failed:\n=== source ===\n{merged}\n=== stderr ===\n{}",
            String::from_utf8_lossy(&build.stderr)
        ));
    }
    Ok(target_dir.join("release").join(entry))
}

/// Run the compiled Rust binary with N i64 args. Returns stdout
/// trimmed.
fn run_rust(bin: &Path, args: &[i64]) -> Result<String, String> {
    let mut cmd = Command::new(bin);
    for a in args {
        cmd.arg(a.to_string());
    }
    let out = cmd.output().map_err(|e| format!("spawn rust bin: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "rust bin exited non-zero (overflow? input out of declared range?):\n  stderr: {}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// XPILE-DIFF-003: outcome of running the Rust binary on an input
/// from a fixture's `overflow_args` range. We classify each result
/// into one of three buckets:
///
/// * `Promoted(value)` — Rust exited zero with a value. This means
///   either the function is in BigInt mode (no overflow possible) or
///   the overflow didn't actually trip for this specific input.
///   `value` is the stdout trimmed; the caller compares it to
///   CPython's output.
/// * `DocumentedGap` — Rust panicked AND the panic message cites
///   `C-PY-INT-ARITH`. This is the *expected* outcome: the i64 fast
///   path overflowed and bailed out with the contract reference,
///   exactly as Layer-1 `C-PY-INT-ARITH` requires. Not a test
///   failure — counts under `promotion_gaps`.
/// * `OffContractCrash(stderr)` — Rust exited non-zero but the
///   stderr doesn't mention the contract. That's a bug: either an
///   unrelated panic or a regression that lost the contract
///   citation. Hard test failure.
#[derive(Debug)]
enum OverflowOutcome {
    Promoted(String),
    DocumentedGap,
    OffContractCrash(String),
}

/// Run the compiled Rust binary the same way as `run_rust` but
/// classify a non-zero exit by inspecting the panic message rather
/// than treating it as a generic failure. See [`OverflowOutcome`].
fn run_rust_expecting_overflow(bin: &Path, args: &[i64]) -> OverflowOutcome {
    let mut cmd = Command::new(bin);
    for a in args {
        cmd.arg(a.to_string());
    }
    let out = match cmd.output() {
        Ok(o) => o,
        Err(e) => return OverflowOutcome::OffContractCrash(format!("spawn failed: {e}")),
    };
    if out.status.success() {
        return OverflowOutcome::Promoted(String::from_utf8_lossy(&out.stdout).trim().to_string());
    }
    let stderr = String::from_utf8_lossy(&out.stderr);
    // Rust panic format: stderr contains `panicked at ...` plus the
    // panic message. We look for the contract citation anywhere in
    // stderr — the `emit_checked*` codegen embeds it in the
    // `.expect(...)` literal so it always appears on the panic line.
    if stderr.contains("C-PY-INT-ARITH") {
        OverflowOutcome::DocumentedGap
    } else {
        OverflowOutcome::OffContractCrash(stderr.to_string())
    }
}

/// Run the Python fixture directly via CPython with N i64 args.
/// Returns stdout trimmed.
fn run_python(fixture_path: &Path, entry: &str, args: &[i64]) -> Result<String, String> {
    let src_path = fixture_path.to_str().ok_or("non-utf8 fixture path")?;
    let call_args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
    let prog = format!(
        "exec(open(r'{src_path}').read()); print({entry}({}))",
        call_args.join(", ")
    );
    let out = Command::new("python3")
        .args(["-c", &prog])
        .output()
        .map_err(|e| format!("spawn python: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "python failed: {}",
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

const INPUTS_PER_FIXTURE: usize = 10;
const LCG_SEED: u64 = 0x00C0_FFEE_FACE_FEEDu64; // deterministic, see header doc

/// The load-bearing CI gate. For each curated fixture, generate
/// INPUTS_PER_FIXTURE deterministic i64 inputs in the declared
/// fast-path range; for each, run CPython + transpiled Rust and
/// assert their outputs agree.
#[test]
fn differential_execution_cpython_vs_transpiled_rust() {
    if !have_python_and_rustc() {
        eprintln!(
            "warning: skipping XPILE-DIFF-001 — python3 and/or rustc not on PATH. \
             CI environments with both will still run this gate."
        );
        return;
    }

    let out_dir = std::env::temp_dir().join("xpile-diff-exec");
    let _ = std::fs::remove_dir_all(&out_dir);
    std::fs::create_dir_all(&out_dir).expect("create temp dir");

    let mut rng = Lcg::new(LCG_SEED);
    let mut total_checks = 0;
    let mut mismatches: Vec<(String, Vec<i64>, String, String)> = Vec::new();
    // XPILE-DIFF-003 metrics + failure buckets.
    let mut overflow_checks = 0;
    let mut promotion_gaps = 0;
    let mut overflow_promoted_ok = 0;
    let mut overflow_promoted_mismatches: Vec<(String, Vec<i64>, String, String)> = Vec::new();
    let mut off_contract_crashes: Vec<(String, Vec<i64>, String)> = Vec::new();

    for cfg in FIXTURES {
        let py_path = fixture(cfg.file);
        let bin = match build_rust_binary(&py_path, cfg.entry, cfg.args.len(), &out_dir) {
            Ok(b) => b,
            Err(e) => {
                panic!(
                    "build failed for fixture `{}` entry `{}`:\n  {e}",
                    cfg.file, cfg.entry
                );
            }
        };

        // ── Fast-path phase (XPILE-DIFF-001/002). ────────────────
        for _ in 0..INPUTS_PER_FIXTURE {
            let args: Vec<i64> = cfg
                .args
                .iter()
                .map(|(lo, hi)| rng.next_i64_in(*lo, *hi))
                .collect();
            let py = run_python(&py_path, cfg.entry, &args)
                .unwrap_or_else(|e| panic!("python {}({args:?}): {e}", cfg.file));
            let rs = run_rust(&bin, &args)
                .unwrap_or_else(|e| panic!("rust {}({args:?}): {e}", cfg.file));
            total_checks += 1;
            if py != rs {
                mismatches.push((cfg.file.to_string(), args, py, rs));
            }
        }

        // ── Overflow phase (XPILE-DIFF-003). ─────────────────────
        // Skip if the fixture declared no overflow domain.
        if cfg.overflow_args.is_empty() {
            continue;
        }
        assert_eq!(
            cfg.overflow_args.len(),
            cfg.args.len(),
            "fixture `{}`: overflow_args length must match arity",
            cfg.file
        );
        for _ in 0..INPUTS_PER_FIXTURE {
            let args: Vec<i64> = cfg
                .overflow_args
                .iter()
                .map(|(lo, hi)| rng.next_i64_in(*lo, *hi))
                .collect();
            // Python *always* produces a value here (it promotes).
            let py = run_python(&py_path, cfg.entry, &args)
                .unwrap_or_else(|e| panic!("python {}({args:?}): {e}", cfg.file));
            overflow_checks += 1;
            match run_rust_expecting_overflow(&bin, &args) {
                OverflowOutcome::DocumentedGap => {
                    // Expected: Rust panicked citing C-PY-INT-ARITH.
                    promotion_gaps += 1;
                }
                OverflowOutcome::Promoted(rs) => {
                    // Rust didn't panic — either the function is in
                    // BigInt mode (which would be a pleasant
                    // surprise here) or the specific input didn't
                    // actually overflow. Compare against Python; if
                    // they agree we count it as a success (BigInt
                    // mode is *the* desired outcome long-term), if
                    // they diverge it's a silent miscompile.
                    if py == rs {
                        overflow_promoted_ok += 1;
                    } else {
                        overflow_promoted_mismatches.push((cfg.file.to_string(), args, py, rs));
                    }
                }
                OverflowOutcome::OffContractCrash(stderr) => {
                    // Rust panicked but the message didn't cite the
                    // contract. That's either an unrelated bug or a
                    // regression that dropped the citation. Hard fail.
                    off_contract_crashes.push((cfg.file.to_string(), args, stderr));
                }
            }
        }
    }

    let mut fatal = String::new();
    if !mismatches.is_empty() {
        fatal.push_str(&format!(
            "Differential execution disagreement (XPILE-DIFF-001/002):\n\
             {} of {} fast-path input-comparisons diverged between CPython and the transpiled \
             Rust binary. Either the codegen miscompiles the construct OR the fixture's \
             declared input range needs tightening to stay inside the C-PY-INT-ARITH fast-path \
             domain.\n\n",
            mismatches.len(),
            total_checks
        ));
        for (fx, args, py, rs) in &mismatches {
            fatal.push_str(&format!(
                "  - {fx} args={args:?}\n      python: {py}\n      rust:   {rs}\n"
            ));
        }
    }
    if !overflow_promoted_mismatches.is_empty() {
        fatal.push_str(&format!(
            "\nOverflow-phase silent miscompile (XPILE-DIFF-003):\n\
             {} input(s) where Rust returned a value that diverged from Python's BigInt-promoted \
             result. This is worse than the documented promotion gap — Rust produced a *wrong* \
             answer instead of panicking.\n\n",
            overflow_promoted_mismatches.len(),
        ));
        for (fx, args, py, rs) in &overflow_promoted_mismatches {
            fatal.push_str(&format!(
                "  - {fx} args={args:?}\n      python: {py}\n      rust:   {rs}\n"
            ));
        }
    }
    if !off_contract_crashes.is_empty() {
        fatal.push_str(&format!(
            "\nOff-contract crashes (XPILE-DIFF-003):\n\
             {} input(s) where Rust panicked but the panic message did NOT cite \
             `C-PY-INT-ARITH`. Either codegen regressed (dropped the contract citation) or the \
             panic comes from an unrelated path. Either way, the gate can't classify the \
             outcome as a documented gap.\n\n",
            off_contract_crashes.len(),
        ));
        for (fx, args, stderr) in &off_contract_crashes {
            fatal.push_str(&format!(
                "  - {fx} args={args:?}\n      stderr: {}\n",
                stderr.trim().lines().next().unwrap_or("(no stderr line)")
            ));
        }
    }
    if !fatal.is_empty() {
        panic!("{fatal}");
    }

    eprintln!(
        "XPILE-DIFF-001/002: {total_checks} fast-path differential checks across {} fixtures — \
         all green.",
        FIXTURES.len()
    );
    if overflow_checks > 0 {
        let n_overflow_fixtures = FIXTURES
            .iter()
            .filter(|c| !c.overflow_args.is_empty())
            .count();
        eprintln!(
            "XPILE-DIFF-003: {overflow_checks} overflow-phase checks across {n_overflow_fixtures} \
             fixture(s) — {promotion_gaps} documented promotion gaps, {overflow_promoted_ok} \
             promoted-and-agreed (BigInt-mode would land here)."
        );
    }
}

// LCG self-test — guard against drift in the deterministic generator
// so a future "fix" doesn't silently change which inputs the gate
// tests. The first three outputs are pinned.
#[test]
fn lcg_is_deterministic_with_seed() {
    let mut rng = Lcg::new(LCG_SEED);
    let a = rng.next_u64();
    let b = rng.next_u64();
    let c = rng.next_u64();
    let mut rng2 = Lcg::new(LCG_SEED);
    assert_eq!(rng2.next_u64(), a);
    assert_eq!(rng2.next_u64(), b);
    assert_eq!(rng2.next_u64(), c);
    // Range bounding stays inside [lo, hi].
    let mut rng3 = Lcg::new(LCG_SEED);
    for _ in 0..1000 {
        let v = rng3.next_i64_in(-100, 100);
        assert!(
            (-100..=100).contains(&v),
            "LCG produced {v} outside [-100, 100]"
        );
    }
}