From 361f9fb1a32e790bf723e6d6d7db2ef8dc955e0c Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 03:56:34 +0000 Subject: [PATCH 1/2] test(python): differential fuzz Monty against CPython python_diff_fuzz runs grammar-generated programs through the Monty fork and the CPython wasm runtime and fails on any stdout difference. First runs found Monty evaluates method-call arguments before the method lookup (excluded from the grammar, documented). python_fuzz never set BASHKIT_ALLOW_INPROCESS_PYTHON, so it only fuzzed the opt-in refusal. Both targets now opt in and assert python3 runs. --- .github/workflows/ci.yml | 1 + .github/workflows/fuzz.yml | 3 +- crates/bashkit/fuzz/Cargo.lock | 1 + crates/bashkit/fuzz/Cargo.toml | 8 + .../fuzz/fuzz_targets/python_diff_fuzz.rs | 379 ++++++++++++++++++ .../bashkit/fuzz/fuzz_targets/python_fuzz.rs | 15 + knowledge/log.md | 1 + knowledge/runtimes/python-builtin.md | 16 + 8 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b5d9f395f..686fbe59b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -676,6 +676,7 @@ jobs: cargo +nightly-2026-10-30 fuzz build --features cpython cpython_fuzz cargo +nightly-2026-10-30 fuzz build --features cpython cpython_http_fuzz cargo +nightly-2026-10-30 fuzz build --features python python_fuzz + cargo +nightly-2026-10-30 fuzz build --features python,cpython python_diff_fuzz # Gate job for branch protection — name must stay "Check" check: diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 8f904d539..22f8051c3 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -26,7 +26,7 @@ jobs: strategy: fail-fast: false matrix: - target: [parser_fuzz, lexer_fuzz, analyze_fuzz, arithmetic_fuzz, glob_fuzz, cpython_fuzz, cpython_http_fuzz, python_fuzz] + target: [parser_fuzz, lexer_fuzz, analyze_fuzz, arithmetic_fuzz, glob_fuzz, cpython_fuzz, cpython_http_fuzz, python_fuzz, python_diff_fuzz] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -67,6 +67,7 @@ jobs: fi features=() case "${{ matrix.target }}" in + python_diff_fuzz) features=(--features python,cpython) ;; cpython_*) features=(--features cpython) ;; python_*) features=(--features python) ;; esac diff --git a/crates/bashkit/fuzz/Cargo.lock b/crates/bashkit/fuzz/Cargo.lock index f700e5e32..5c457e6ff 100644 --- a/crates/bashkit/fuzz/Cargo.lock +++ b/crates/bashkit/fuzz/Cargo.lock @@ -199,6 +199,7 @@ dependencies = [ "serde_norway", "sha1", "sha2 0.11.1", + "stacker", "thiserror", "tokio", "tower", diff --git a/crates/bashkit/fuzz/Cargo.toml b/crates/bashkit/fuzz/Cargo.toml index cabfbcf62..edfe05e03 100644 --- a/crates/bashkit/fuzz/Cargo.toml +++ b/crates/bashkit/fuzz/Cargo.toml @@ -183,3 +183,11 @@ required-features = ["python"] test = false doc = false bench = false + +[[bin]] +name = "python_diff_fuzz" +path = "fuzz_targets/python_diff_fuzz.rs" +required-features = ["python", "cpython"] +test = false +doc = false +bench = false diff --git a/crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs b/crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs new file mode 100644 index 000000000..cd0189eb4 --- /dev/null +++ b/crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs @@ -0,0 +1,379 @@ +//! Differential fuzz target: Monty python3 (bashkit-monty fork) vs CPython +//! +//! Builds a small Python program from the fuzz bytes, runs it through both +//! embedded runtimes, and fails when their stdout differs. Catches semantic +//! bugs in the fork (wrong results, wrong exception types) that crash-only +//! fuzzing cannot see, and regressions from local fork edits or re-syncs. +//! +//! Decision: programs come from a grammar, not raw bytes. Raw text is almost +//! always a SyntaxError, and syntax error messages legitimately differ +//! between the two parsers. Every generated statement is wrapped in +//! `try/except Exception` that prints the exception type, so one error does +//! not end the run and exception types are compared too. +//! +//! Decision: the grammar covers the subset Monty documents as supported +//! (ints, floats, str, list, tuple, dict, bool, None, operators, builtins, +//! str/list methods, slicing, f-strings, comprehensions, conditionals). Known +//! intentional differences are left out of the grammar rather than filtered +//! from output, see `KNOWN GAPS` below, so a mismatch is always a finding. +//! +//! KNOWN GAPS (not generated): +//! - `obj.method(arg)` evaluation order: CPython looks up `obj.method` +//! before evaluating `arg` (`0 .append(len(0))` raises AttributeError); +//! Monty evaluates the arguments first (TypeError). Found by this target; +//! method-call arguments are bound to a temporary first +//! - sets and set ordering, `hash()`, `id()`: implementation-defined +//! - big repetition (`'a' * 10**20`): the two runtimes have different memory +//! limits; MemoryError/OverflowError runs are skipped below +//! +//! Comparison is skipped when either side does not exit 0 (time or memory +//! limit, which the two runtimes enforce differently) or its output hit the +//! stdout cap. +//! +//! Run with: +//! cargo +nightly fuzz run python_diff_fuzz --features python,cpython -- -max_total_time=300 + +#![no_main] + +use libfuzzer_sys::fuzz_target; +use std::fmt::Write as _; +use std::time::Duration; + +#[global_allocator] +static ALLOC: bashkit::MeteredAllocator = bashkit::MeteredAllocator; + +const MAX_STDOUT: usize = 8192; +const MAX_DEPTH: u32 = 3; +const MAX_STATEMENTS: usize = 8; +const VARS: [&str; 3] = ["a", "b", "c"]; +const INTS: [&str; 12] = [ + "0", "1", "2", "3", "7", "-1", "-5", "10", "255", "2**31", "10**20", "-(2**64)", +]; +const FLOATS: [&str; 6] = ["0.5", "1.0", "-2.25", "3.14159", "1e10", "0.1"]; +const STRS: [&str; 10] = [ + "''", + "'a'", + "'ab'", + "'Hello'", + "' x y '", + "'a,b,,c'", + "'\\u00e9t\\u00e9'", + "'42'", + "'-7'", + "'A1b2'", +]; +const STR_METHODS: [&str; 16] = [ + ".upper()", + ".lower()", + ".strip()", + ".split(',')", + ".split()", + ".replace('a', 'XY')", + ".find('b')", + ".startswith('a')", + ".endswith('b')", + ".count('a')", + ".isdigit()", + ".title()", + ".lstrip(' a')", + ".partition(',')", + ".zfill(5)", + ".capitalize()", +]; + +/// Reads choices from the fuzz input; exhausted input yields zeros, so every +/// input produces a finite, valid program. +struct Gen<'a> { + data: &'a [u8], + pos: usize, +} + +impl Gen<'_> { + fn byte(&mut self) -> u8 { + let b = self.data.get(self.pos).copied().unwrap_or(0); + self.pos += 1; + b + } + + fn pick<'s>(&mut self, items: &[&'s str]) -> &'s str { + items[self.byte() as usize % items.len()] + } + + fn small(&mut self, n: u8) -> u8 { + self.byte() % n + } + + fn exhausted(&self) -> bool { + self.pos >= self.data.len() + } + + fn atom(&mut self, out: &mut String) { + match self.small(6) { + 0 => out.push_str(self.pick(&INTS)), + 1 => out.push_str(self.pick(&FLOATS)), + 2 => out.push_str(self.pick(&STRS)), + 3 => out.push_str(self.pick(&["True", "False", "None"])), + _ => out.push_str(self.pick(&VARS)), + } + } + + fn expr(&mut self, out: &mut String, depth: u32) { + if depth >= MAX_DEPTH || self.exhausted() { + return self.atom(out); + } + let d = depth + 1; + match self.small(18) { + 0 | 1 => self.atom(out), + 2 | 3 => { + let op = self.pick(&[ + "+", "-", "*", "/", "//", "%", "==", "!=", "<", "<=", ">", ">=", "and", "or", + "in", "not in", "&", "|", "^", + ]); + out.push('('); + self.expr(out, d); + let _ = write!(out, " {op} "); + self.expr(out, d); + out.push(')'); + } + 4 => { + // Bounded power: literal exponent only. + out.push('('); + self.expr(out, d); + let _ = write!(out, " ** {})", self.small(10)); + } + 5 => { + out.push_str(self.pick(&["(-", "(not ", "(+", "(~"])); + self.expr(out, d); + out.push(')'); + } + 6 => { + let f = self.pick(&[ + "len", + "abs", + "str", + "int", + "float", + "bool", + "sorted", + "min", + "max", + "sum", + "list", + "repr", + "tuple", + "reversed", + "enumerate", + "type", + ]); + let wrap = matches!(f, "reversed" | "enumerate"); + if wrap { + out.push_str("list("); + } + let _ = write!(out, "{f}("); + self.expr(out, d); + out.push(')'); + if wrap { + out.push(')'); + } + } + 7 => { + self.expr(out, d); + out.push_str(self.pick(&STR_METHODS)); + } + 8 => { + out.push('['); + for i in 0..self.small(4) { + if i > 0 { + out.push_str(", "); + } + self.expr(out, d); + } + out.push(']'); + } + 9 => { + out.push('('); + self.expr(out, d); + out.push_str(", "); + self.expr(out, d); + out.push(')'); + } + 10 => { + out.push_str("{'k': "); + self.expr(out, d); + out.push_str(", 'j': "); + self.expr(out, d); + out.push('}'); + } + 11 => { + self.expr(out, d); + out.push('['); + self.expr(out, d); + out.push(']'); + } + 12 => { + self.expr(out, d); + let lo = self.pick(&["", "0", "1", "-1", "-2", "5"]); + let hi = self.pick(&["", "0", "2", "-1", "10"]); + let step = self.pick(&["", "", "1", "2", "-1", "-2"]); + if step.is_empty() { + let _ = write!(out, "[{lo}:{hi}]"); + } else { + let _ = write!(out, "[{lo}:{hi}:{step}]"); + } + } + 13 => { + out.push_str(self.pick(&["f'<{", "f'{"])); + self.expr(out, d); + out.push_str(self.pick(&["}>'", "!r}'", ":>6}'", "}'"])); + } + 14 => { + out.push('('); + self.expr(out, d); + out.push_str(" if "); + self.expr(out, d); + out.push_str(" else "); + self.expr(out, d); + out.push(')'); + } + 15 => { + out.push('['); + out.push_str(self.pick(&["x", "x * 2", "str(x)", "(x, x)", "repr(x)"])); + out.push_str(" for x in "); + self.expr(out, d); + if self.small(2) == 0 { + out.push_str(" if x"); + } + out.push(']'); + } + 16 => { + let _ = write!(out, "list(range({}, {}))", self.small(5), self.small(12)); + } + _ => { + out.push_str(self.pick(&["', '.join(", "'-'.join(", "''.join("])); + self.expr(out, d); + out.push(')'); + } + } + } + + fn statement(&mut self, out: &mut String) { + out.push_str("try:\n "); + match self.small(6) { + 0 => { + let v = self.pick(&VARS); + let _ = write!(out, "{v} = "); + self.expr(out, 0); + let _ = write!(out, "\n print(repr({v}))"); + } + 1 => { + let v = self.pick(&VARS); + // Argument evaluated first on purpose, see KNOWN GAPS. + out.push_str("t = "); + self.expr(out, 0); + let _ = write!(out, "\n {v}.append(t)\n print(repr({v}))"); + } + 2 => { + let v = self.pick(&VARS); + let _ = write!(out, "for x in "); + self.expr(out, 1); + let _ = write!(out, ":\n {v} = ({v}, x)\n print(repr({v}))"); + } + _ => { + out.push_str("print(repr("); + self.expr(out, 0); + out.push_str("))"); + } + } + out.push_str("\nexcept Exception as e:\n print(type(e).__name__)\n"); + } + + fn program(&mut self) -> String { + let mut out = String::from("a = [1, 2, 3]\nb = 'abc'\nc = 0\n"); + let n = 1 + self.small(MAX_STATEMENTS as u8) as usize; + for _ in 0..n { + self.statement(&mut out); + } + out + } +} + +fn limits() -> bashkit::ExecutionLimits { + bashkit::ExecutionLimits::new() + .max_commands(20) + .max_stdout_bytes(MAX_STDOUT) + .max_stderr_bytes(4096) + .timeout(Duration::from_secs(5)) +} + +async fn run(mut bash: bashkit::Bash, program: &str) -> Option { + bash.fs() + .write_file(std::path::Path::new("/p.py"), program.as_bytes()) + .await + .ok()?; + let r = bash.exec("python3 /p.py").await.ok()?; + let out = r.stdout.to_string(); + // A refused run compares nothing; fail loudly instead of passing vacuously. + assert!( + !r.stderr.contains("disabled by default"), + "[python_diff_fuzz] python3 refused to run: {}", + r.stderr + ); + // Limits differ between runtimes; only clean, uncapped runs compare. + if r.exit_code != 0 + || out.len() >= MAX_STDOUT + || out.contains("MemoryError") + || out.contains("OverflowError") + || out.contains("RecursionError") + { + return None; + } + Some(out) +} + +fuzz_target!(|data: &[u8]| { + let program = Gen { data, pos: 0 }.program(); + + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + + rt.block_on(async { + bashkit::testing::fuzz_init(); + let monty = bashkit::Bash::builder() + // Monty is opt-in per shell; without this every run hits the refusal path. + .env("BASHKIT_ALLOW_INPROCESS_PYTHON", "1") + .python_with_limits( + bashkit::PythonLimits::default() + .max_duration(Duration::from_secs(1)) + .max_memory(64 * 1024 * 1024), + ) + .limits(limits()) + .build(); + let cpython = bashkit::Bash::builder() + .cpython_with_limits( + bashkit::CPythonLimits::default() + .max_duration(Duration::from_secs(2)) + .max_memory(256 * 1024 * 1024) + .max_output(MAX_STDOUT), + ) + .limits(limits()) + .build(); + + let (Some(m), Some(c)) = (run(monty, &program).await, run(cpython, &program).await) else { + return; + }; + if m != c { + let diff = m + .lines() + .zip(c.lines()) + .position(|(a, b)| a != b) + .unwrap_or_else(|| m.lines().count().min(c.lines().count())); + panic!( + "[python_diff_fuzz] Monty and CPython disagree at output line {}\n\ + --- program ---\n{program}\n--- monty ---\n{m}\n--- cpython ---\n{c}", + diff + 1 + ); + } + }); +}); diff --git a/crates/bashkit/fuzz/fuzz_targets/python_fuzz.rs b/crates/bashkit/fuzz/fuzz_targets/python_fuzz.rs index 888812f55..65af7c7e5 100644 --- a/crates/bashkit/fuzz/fuzz_targets/python_fuzz.rs +++ b/crates/bashkit/fuzz/fuzz_targets/python_fuzz.rs @@ -43,6 +43,8 @@ fuzz_target!(|data: &[u8]| { rt.block_on(async { bashkit::testing::fuzz_init(); let mut bash = bashkit::Bash::builder() + // Monty is opt-in per shell; without this every run hits the refusal path. + .env("BASHKIT_ALLOW_INPROCESS_PYTHON", "1") .python_with_limits( bashkit::PythonLimits::default() .max_duration(Duration::from_millis(500)) @@ -74,6 +76,19 @@ fuzz_target!(|data: &[u8]| { // Input as a command line (CLI option parsing). format!("python3 '{quoted}' -c 'print(1)'"), ]; + // Once per process: prove python3 really runs, so the target cannot + // silently fuzz only the opt-in refusal path again. + static CANARY: std::sync::Once = std::sync::Once::new(); + let mut canary_ok = true; + if !CANARY.is_completed() { + let r = bash.exec("python3 -c 'print(6*7)'").await.unwrap(); + canary_ok = r.stdout.to_string() == "42\n"; + CANARY.call_once(|| {}); + } + assert!( + canary_ok, + "[python_fuzz] python3 does not run; check the opt-in env" + ); for script in &scripts { let start = Instant::now(); bashkit::testing::fuzz_exec(&mut bash, script, "python_fuzz", &[]).await; diff --git a/knowledge/log.md b/knowledge/log.md index c71a4999a..a54a0c3f7 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -3,6 +3,7 @@ ## 2026-11-07 * **Monty upstream watch**: the forks are renamed crates, so cargo audit/deny and Dependabot never see upstream `monty` releases or advisories. `scripts/check_monty_upstream.py` (daily `monty-upstream.yml`) fails when crates.io has a newer stable `monty`/`monty-types` than the fork base or OSV lists an advisory for `monty`, `monty-types` or PyPI `pydantic-monty` at that version. First run: 1.5.0 is out, base is 1.4.0. See [Dependencies](operations/dependencies.md#monty-forks). +* **Monty vs CPython differential fuzz**: `python_diff_fuzz` runs grammar-generated programs through both embedded runtimes and fails on any stdout difference. First runs (~9k programs) found one class: Monty evaluates method-call arguments before the method lookup (error type differs from CPython). Writing it showed `python_fuzz` (#2853) never set `BASHKIT_ALLOW_INPROCESS_PYTHON`, so its runs only hit the opt-in refusal; both targets now opt in and assert `python3` really runs. See [Python Builtin](runtimes/python-builtin.md). ## 2026-11-06 diff --git a/knowledge/runtimes/python-builtin.md b/knowledge/runtimes/python-builtin.md index f1151d9d8..099c951af 100644 --- a/knowledge/runtimes/python-builtin.md +++ b/knowledge/runtimes/python-builtin.md @@ -323,6 +323,22 @@ is where inherited interpreter bugs show up. cargo +nightly-2026-10-30 fuzz run --features python python_fuzz -- -max_total_time=300 ``` +Both Monty fuzz targets set `BASHKIT_ALLOW_INPROCESS_PYTHON=1` and fail if +`python3` refuses to run: until 2026-11-07 `python_fuzz` lacked the opt-in and +fuzzed only the refusal message. + +Differential fuzzing: `python_diff_fuzz` (features `python,cpython`, nightly +in `fuzz.yml`) builds small programs from a grammar of the Monty-supported +subset (ints, floats, str, list, tuple, dict, operators, builtins, str/list +methods, slicing, f-strings, comprehensions), runs each through Monty and the +CPython wasm runtime, and fails when stdout differs. Every statement is wrapped +in `try/except` printing the exception type, so exception types are compared +too. Runs that hit a limit (non-zero exit, MemoryError, OverflowError, +RecursionError, stdout cap) are skipped, since the two runtimes enforce limits +differently. Known divergence, excluded from the grammar: Monty evaluates +`obj.method(arg)` arguments before looking up `obj.method`, so the error type +differs when both fail (CPython: AttributeError, Monty: TypeError). + Stress: `tests/integration/python_tenant_stress_tests.rs` runs 20 tenants on 4 worker threads per round, mixing memory bombs, runaway loops, unbounded recursion and well-behaved scripts; it also drops calls mid-run and then checks From febc1da72e30832195e57fc4121c1364250027a4 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 04:14:09 +0000 Subject: [PATCH 2/2] test(python): compare OverflowError in the diff fuzzer --- crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs | 4 ++-- knowledge/runtimes/python-builtin.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs b/crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs index cd0189eb4..0ad45e576 100644 --- a/crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs +++ b/crates/bashkit/fuzz/fuzz_targets/python_diff_fuzz.rs @@ -24,7 +24,8 @@ //! method-call arguments are bound to a temporary first //! - sets and set ordering, `hash()`, `id()`: implementation-defined //! - big repetition (`'a' * 10**20`): the two runtimes have different memory -//! limits; MemoryError/OverflowError runs are skipped below +//! limits; MemoryError runs are skipped below (OverflowError is language +//! semantics, e.g. float `**` overflow, and is compared) //! //! Comparison is skipped when either side does not exit 0 (time or memory //! limit, which the two runtimes enforce differently) or its output hit the @@ -322,7 +323,6 @@ async fn run(mut bash: bashkit::Bash, program: &str) -> Option { if r.exit_code != 0 || out.len() >= MAX_STDOUT || out.contains("MemoryError") - || out.contains("OverflowError") || out.contains("RecursionError") { return None; diff --git a/knowledge/runtimes/python-builtin.md b/knowledge/runtimes/python-builtin.md index 099c951af..83c432be0 100644 --- a/knowledge/runtimes/python-builtin.md +++ b/knowledge/runtimes/python-builtin.md @@ -333,8 +333,8 @@ subset (ints, floats, str, list, tuple, dict, operators, builtins, str/list methods, slicing, f-strings, comprehensions), runs each through Monty and the CPython wasm runtime, and fails when stdout differs. Every statement is wrapped in `try/except` printing the exception type, so exception types are compared -too. Runs that hit a limit (non-zero exit, MemoryError, OverflowError, -RecursionError, stdout cap) are skipped, since the two runtimes enforce limits +too. Runs that hit a limit (non-zero exit, MemoryError, RecursionError, +stdout cap) are skipped; OverflowError is language semantics and is compared, since the two runtimes enforce limits differently. Known divergence, excluded from the grammar: Monty evaluates `obj.method(arg)` arguments before looking up `obj.method`, so the error type differs when both fail (CPython: AttributeError, Monty: TypeError).