← Back to Pull requests

Register interpreter benchmarks from the python/ directory #1057

Merged
samuelcolvin merged 153 files (1843 lines) on Oct 17, 2026 20:21 UTC
View on GitHub
samuelcolvin samuelcolvin commented on Oct 16, 2026 15:10 UTC
Author

Follows #1055, which moved the scripts into benches/python/ but kept each benchmark's expected value, inputs and variants in main.rs.

Now the scripts are plain Python and main.rs registers them by reading the directory: adding a .py file adds a benchmark, with no Rust change.

  • Self-checking scripts. The last expression of each script became an assert on its old expected value (assert len(v) == 77), so any Python implementation can run the file and fail loudly if the result is wrong.

  • # bench: header for what Rust used to hard-code: data=<path> binds DATA to a file's contents, mount binds it to the mounted scan tree (overlay adds an overlay-mount variant), limits adds a resource-limits variant. Unknown options panic.

  • Registered from the directory: every top-level benches/python/.py, plus test_cases/bench__.py, so the kitchen sink stays shared with the datatest suite. Its # Return=373 became assert result == 373.

  • Names unchanged, so CodSpeed history carries over: fib_25.py was renamed to fib.py to keep fib__monty. The same benchmarks register as before: 63 locally and 36 under the codspeed feature.

  • CPython now runs each compiled module at module scope, in fresh globals, as Monty does, replacing wrap_for_cpython's text rewrite into def main(). Module-scope variable access is slower in CPython than locals, so the local __cpython numbers will rise. The comparison is now like for like.

  • The csv_read / csv_write benchmarks from #1018 are converted too. Their CPython variants were gated on cfg(not(codspeed)), which walltime and memory builds never set, so they were running in CodSpeed CI. Every CPython benchmark is now gated on the codspeed feature.

  • pool.rs's scripts moved to python/pool/, since they need a host to answer their calls. end_to_end now parses add_two.py.
  • The Rust-API benchmarks (parse_1k_assigns, clone_module, repl_feed_after_2k_snippets, session_dump/load) stay in Rust, because their code is generated.

    Checked: -- --test passes with and without the codspeed feature, a wrong expected value fails the benchmark with the script's traceback, and the bench__kitchen_sink datatest passes.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_016t3CWLMcgDnRzncyejqP6T

    <!-- This is an auto-generated description by cubic. -->
    ---

    Summary by cubic


    Registers interpreter benchmarks by reading the benches/python/ directory, so adding a .py file adds a benchmark without a Rust change. Each script checks its own result with an assert.

    The new monty-fixture crate parses a # /// monty PEP 723 block of TOML shared by test cases and benchmark scripts. The datatest harness's old # call-external-style markers became header keys. The block must sit in the file's leading comments, so a string or later comment can't configure a fixture, and a misspelled key, wrong type, or malformed block panics instead of silently dropping the setting, with errors naming the line the header opens on. The header stays in the code, so TRACEBACK line numbers in test cases were updated to count its lines.

  • Scripts assert their own expected result; the old # bench: options became the header's [bench] table (data, mount, overlay, limits), and non-[bench] keys are rejected.

  • Both interpreters receive the script's real file name, so tracebacks match the file.

  • DATA is bound in limits runs too, and only loop_mod_13 keeps a limits variant now that the csv ones are dropped.

  • CPython runs each compiled module at module scope in fresh globals, matching Monty, so local __cpython numbers will shift as module-scope variable access is slower than the old main()-wrapped locals.

  • pool.rs's scripts moved to python/pool/ so the directory scan doesn't pick them up as standalone benchmarks.
  • <sup>Written for commit b69fd14ec0d74843b707d2917997ac101a883370. Summary will update on new commits.</sup>

    <a href="https://cubic.dev/pr/pydantic/monty/pull/1057?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/pydantic/monty/1057?returnTo=https%3A%2F%2Fgithub.com%2Fpydantic%2Fmonty%2Fpull%2F1057&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

    <!-- End of auto-generated description by cubic. -->

    Diff: 1843 lines (+1097 / -746) across 153 files Reviewer: samuelcolvin Review duration: 1750m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.86) × (1 − Review Confidence (0.80)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 1843 lines diff across 153 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.81 · 5 substantive comment(s)
    0.81
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    79%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    34 items
    github-actions[bot] github-actions[bot] commented on Oct 16, 2026 15:11 UTC
    Bot

    <!-- branch-diff -->

    Branch diff: bench-scripts-from-directory

    | Commit | Message | Production | Test | Docs | Other |
    | --- | --- | --: | --: | --: | --: |
    | 67d44f272 | Register interpreter benchmar… | +0 -0 | +328 -477 | +0 -0 | +0 -0 |
    | b73de20d2 | Bind DATA in limits runs and … | +0 -0 | +43 -26 | +0 -0 | +0 -0 |
    | 0b3a5ef06 | Drop the csv limits benchmark… | +0 -0 | +0 -2 | +0 -0 | +0 -0 |
    | 751465a7a | Share one # /// monty heade… | +157 -0 | +471 -313 | +0 -0 | +57 -11 |
    | 0474d9385 | Convert match__async.py fro… | +0 -0 | +3 -1 | +0 -0 | +0 -0 |
    | b69fd14ec | Address review: confine the h… | +28 -18 | +119 -11 | +0 -0 | +4 -0 |
    | | TOTAL | +167 -0 | +869 -735 | +0 -0 | +61 -11 |

    macroscopeapp[bot] macroscopeapp[bot] commented on code on Oct 16, 2026 15:12 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));
    +        for option in header
    +            .filter_map(|line| line.strip_prefix("# bench:"))
    +            .flat_map(str::split_whitespace)
    +        {
    +            match option.split_once('=') {
    +                Some(("data", data)) => {
    +                    let data_path = path.parent().unwrap().join(data);
    +                    script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                }
    +                _ => match option {
    +                    "mount" => script.input = Input::Mount,
    +                    "overlay" => script.overlay = true,
    +                    "limits" => script.limits = true,
    +                    _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                },
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());
    +        script.code = code;
    +        script
    +    }
    +
    +    /// Registers this script's benchmarks; `tree` is the host root of the scan tree.
    +    fn register(&self, c: &mut Criterion, tree: &Path) {
    +        let name = &self.name;
    +        let code = self.code.as_str();
    +        let filename = format!("{name}.py");
    +        let data = match &self.input {
    +            Input::None => None,
    +            Input::Data(data) => Some(data.as_str()),
    +            Input::Mount => None,
    +        };
    +        if matches!(self.input, Input::Mount) {
    +            c.bench_function(&format!("{name}__monty"), |b| {
    +                run_monty_mounted(b, code, &filename, tree, MountMode::ReadOnly);
    +            });
    +            if self.overlay {
    +                c.bench_function(&format!("{name}_overlay__monty"), |b| {
    +                    let mode = MountMode::OverlayMemory(OverlayState::new());
    +                    run_monty_mounted(b, code, &filename, tree, mode);
    +                });
    +            }
    +        } else {
    +            c.bench_function(&format!("{name}__monty"), |b| run_monty(b, code, &filename, data));
    +            if self.limits {
    +                c.bench_function(&format!("{name}_limits__monty"), |b| {

    🟡 Medium benches/main.rs:161

    A script declaring both data=... and limits fails with undefined DATA in its limits benchmark, because this call drops the script's input and run_monty_limits runs with no input names or values. Pass data through and bind DATA in the limits run, as the normal variant does.

    <details>
    <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>

    In file @crates/monty-bench/benches/main.rs around line 161:
    
    A script declaring both `data=...` and `limits` fails with undefined `DATA` in its limits benchmark, because this call drops the script's input and `run_monty_limits` runs with no input names or values. Pass `data` through and bind `DATA` in the limits run, as the normal variant does.
    

    </details>
    <!-- macroscope-meta: {"kind":"code_review","variant":"50d9a9128a918cceace09f2512c6481c"} -->

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 16, 2026 15:12 UTC
    Reviewer

    <!-- macroscope-meta: {"kind":"code_review","variant":"50d9a9128a918cceace09f2512c6481c"} -->

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 16, 2026 15:13 UTC
    Reviewer

    <!-- Macroscope (Approvability) review body marker -->
    <!-- MURMUR_IGNORE -->
    <!-- macroscope-meta: {"kind":"approvability"} -->

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 16, 2026 15:13 UTC
    Bot

    <!-- MURMUR_IGNORE -->

    Approvability

    Verdict: Approved at b69fd14

    Macroscope's review found this PR approvable — The PR changes only fixture/test harnesses and benchmark registration, adding no production request-path behavior or protected API, sandbox, protocol, snapshot, or release changes. The large file count is mainly mechanical fixture migration and benchmark-script reorganization.

    Notes:

  • Your custom eligibility rules tell Macroscope not to weigh correctness findings, so they do not block approval.
  • <sup>You can add or adjust custom eligibility rules. Learn more.</sup>
    <!-- macroscope-meta: {"kind":"approvability"} -->

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 16, 2026 15:15 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));

    <!-- cubic:v=dd097b88-99c6-45a7-addd-d3bd11c79fe7 -->
    <!-- cubic:review-run=1ede845d-10b1-51ef-8a94-6cc5a725ce0c -->
    <!-- metadata:{"confidence":5} -->
    P2: Header lines that do not match # bench: exactly are ignored silently, so a typo drops the option without an error. Panic on any leading comment that starts with bench but does not match the expected form.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-bench/benches/main.rs, line 109:
    
    <comment>Header lines that do not match `# bench:` exactly are ignored silently, so a typo drops the option without an error. Panic on any leading comment that starts with `bench` but does not match the expected form.</comment>
    
    <file context>
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));
    +        for option in header
    +            .filter_map(|line| line.strip_prefix("# bench:"))
    </file context>
    

    </details>

    ✅ Addressed in 6697bfa

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 16, 2026 15:15 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));
    +        for option in header
    +            .filter_map(|line| line.strip_prefix("# bench:"))
    +            .flat_map(str::split_whitespace)
    +        {
    +            match option.split_once('=') {
    +                Some(("data", data)) => {
    +                    let data_path = path.parent().unwrap().join(data);
    +                    script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                }
    +                _ => match option {
    +                    "mount" => script.input = Input::Mount,
    +                    "overlay" => script.overlay = true,
    +                    "limits" => script.limits = true,
    +                    _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                },
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());

    <!-- cubic:v=ae788889-eca5-45d3-bd81-763a2fe063e5 -->
    <!-- cubic:review-run=1ede845d-10b1-51ef-8a94-6cc5a725ce0c -->
    <!-- metadata:{"confidence":6} -->
    P2: limits with data= registers a benchmark that never binds DATA, so it panics at run time. Reject the combination when the header is parsed, or pass the data through run_monty_limits.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-bench/benches/main.rs, line 133:
    
    <comment>`limits` with `data=` registers a benchmark that never binds `DATA`, so it panics at run time. Reject the combination when the header is parsed, or pass the data through `run_monty_limits`.</comment>
    
    <file context>
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());
    +        script.code = code;
    +        script
    </file context>
    

    </details>

            assert!(!script.limits || matches!(script.input, Input::None), "{}: `limits` with `data` or `mount`", path.display());
    

    <a href="https://www.cubic.dev/action/fix/violation/ae788889-eca5-45d3-bd81-763a2fe063e5" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
    <img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
    </picture>
    </a>

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 16, 2026 15:15 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));
    +        for option in header
    +            .filter_map(|line| line.strip_prefix("# bench:"))
    +            .flat_map(str::split_whitespace)
    +        {
    +            match option.split_once('=') {
    +                Some(("data", data)) => {
    +                    let data_path = path.parent().unwrap().join(data);
    +                    script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                }
    +                _ => match option {
    +                    "mount" => script.input = Input::Mount,
    +                    "overlay" => script.overlay = true,
    +                    "limits" => script.limits = true,
    +                    _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                },
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());
    +        script.code = code;
    +        script
    +    }
    +
    +    /// Registers this script's benchmarks; `tree` is the host root of the scan tree.
    +    fn register(&self, c: &mut Criterion, tree: &Path) {
    +        let name = &self.name;
    +        let code = self.code.as_str();
    +        let filename = format!("{name}.py");
    +        let data = match &self.input {
    +            Input::None => None,
    +            Input::Data(data) => Some(data.as_str()),
    +            Input::Mount => None,
    +        };
    +        if matches!(self.input, Input::Mount) {
    +            c.bench_function(&format!("{name}__monty"), |b| {
    +                run_monty_mounted(b, code, &filename, tree, MountMode::ReadOnly);
    +            });
    +            if self.overlay {
    +                c.bench_function(&format!("{name}_overlay__monty"), |b| {
    +                    let mode = MountMode::OverlayMemory(OverlayState::new());
    +                    run_monty_mounted(b, code, &filename, tree, mode);
    +                });
    +            }
    +        } else {
    +            c.bench_function(&format!("{name}__monty"), |b| run_monty(b, code, &filename, data));
    +            if self.limits {
    +                c.bench_function(&format!("{name}_limits__monty"), |b| {
    +                    run_monty_limits(b, code, &filename);
    +                });
    +            }
    +        }
    +        #[cfg(not(feature = "codspeed"))]
    +        {
    +            let host_root = tree.to_str().expect("temporary directories have UTF-8 paths");
    +            let data = if matches!(self.input, Input::Mount) {
    +                Some(host_root)
    +            } else {
    +                data
    +            };
    +            c.bench_function(&format!("{name}__cpython"), |b| run_cpython(b, code, &filename, data));
    +        }
    +    }
    +}
    +
    +/// The `.py` files directly in `dir`.
    +fn python_files(dir: &str) -> impl Iterator<Item = PathBuf> {
    +    fs::read_dir(dir)
    +        .unwrap_or_else(|err| panic!("reading {dir}: {err}"))
    +        .map(|entry| entry.unwrap().path())
    +        .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "py"))
    +}
    +
    +/// A path's file stem, which every script path has.
    +fn file_stem(path: &Path) -> &str {
    +    path.file_stem().and_then(|stem| stem.to_str()).unwrap()
    +}
    +
    +/// Parses once, then benchmarks repeated execution, binding `DATA` when `data` is given.
    +fn run_monty(bench: &mut Bencher, code: &str, filename: &str, data: Option<&str>) {
    +    let input_names = data.map(|_| vec!["DATA".to_owned()]).unwrap_or_default();
    +    let mut ex = MontyRun::new(code.to_owned(), filename, input_names, CompileOptions::default()).unwrap();
    +    let inputs = || {
    +        data.map(|data| vec![MontyObject::string(data.to_owned())])
    +            .unwrap_or_default()
    +    };
    +    bench.iter(|| black_box(ex.run_no_limits(inputs()).unwrap()));

    <!-- cubic:v=912dfc10-e198-4d76-adb7-0f719c44d7f2 -->
    <!-- cubic:review-run=1ede845d-10b1-51ef-8a94-6cc5a725ce0c -->
    <!-- metadata:{"confidence":9} -->
    P2: run_monty now discards the result and relies on script assertions, but add_two.py only evaluates 1 + 2 and gc_collect.py ends with gc.collect(); neither asserts an expected value. Add assertions so these benchmarks still detect incorrect results.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-bench/benches/main.rs, line 200:
    
    <comment>`run_monty` now discards the result and relies on script assertions, but `add_two.py` only evaluates `1 + 2` and `gc_collect.py` ends with `gc.collect()`; neither asserts an expected value. Add assertions so these benchmarks still detect incorrect results.</comment>
    
    <file context>
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
    +        data.map(|data| vec![MontyObject::string(data.to_owned())])
    +            .unwrap_or_default()
    +    };
    +    bench.iter(|| black_box(ex.run_no_limits(inputs()).unwrap()));
    +}
    +
    </file context>
    

    </details>

    <a href="https://www.cubic.dev/action/fix/violation/912dfc10-e198-4d76-adb7-0f719c44d7f2" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
    <img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
    </picture>
    </a>

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 16, 2026 15:15 UTC
    Reviewer

    <!-- cubic:review-summary:start -->
    All reported issues were addressed across 28 files
    <!-- cubic:review-summary:end -->

    <sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Turn on auto-fix | Re-trigger cubic</sub>

    <!-- cubic:review-post:ai_pr_review_github_delivery_740615448c3c3ea60bee962b2fb544f0feab5c6334f8e1670b624cfe15f89d10:3a05139e8844d6539da0e1d0a5525657fd53b7ae:1ede845d-10b1-51ef-8a94-6cc5a725ce0c -->

    github-actions[bot] github-actions[bot] commented on Oct 16, 2026 15:19 UTC
    Bot

    <!-- codecov-action-results -->

    Coverage Results 📊

    :x: Patch coverage is 76.06% (54 of 71 changed executable lines covered; target 80%).
    Project statement coverage is 64.38% (unchanged from base (dafc9a0) to head (b69fd14)).

    <details>
    <summary>Changed files with executable lines (2)</summary>

    | File | Patch coverage | Changed executable lines |
    |------|----------------|--------------------------|
    | crates/monty-fixture/src/lib.rs | 71.19% | 42/59 covered; missed: 98, 99, 100, 120, 122, 124, 129, 146, 149, 150, 151, 152, 153, 158, 159, 160, 161; partial branches: 57, 59, 119, 126, 148 |
    | crates/monty-datatest/src/main.rs | 100.00% | 12/12 covered; partial branches: 210, 228 |

    </details>

    <details>
    <summary>Coverage diff</summary>

    @@            Coverage Diff             @@
    ##          main     #1057       +/-##
    ==========================================
      Coverage    64.38%    64.38%        —%
    ==========================================
      Files          574       575        +1
      Tracked lines    150861    150894       +33
      Branches    323706    323722       +16
    ==========================================
    + Hits         97124     97140       +16
    - Misses       53737     53754       +17
    - Partials      6616      6620        +4
    

    </details>

    ---
    Generated by Coverage Action

    codecov[bot] codecov[bot] commented on Oct 16, 2026 15:19 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 66.19718% with 24 lines in your changes missing coverage. Please review.
    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | crates/monty-fixture/src/lib.rs | 62.71% | 17 Missing and 5 partials :warning: |
    | crates/monty-datatest/src/main.rs | 83.33% | 0 Missing and 2 partials :warning: |

    :loudspeaker: Thoughts on this report? Let us know!

    samuelcolvin samuelcolvin commented on code on Oct 16, 2026 15:21 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));
    +        for option in header
    +            .filter_map(|line| line.strip_prefix("# bench:"))
    +            .flat_map(str::split_whitespace)
    +        {
    +            match option.split_once('=') {
    +                Some(("data", data)) => {
    +                    let data_path = path.parent().unwrap().join(data);
    +                    script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                }
    +                _ => match option {
    +                    "mount" => script.input = Input::Mount,
    +                    "overlay" => script.overlay = true,
    +                    "limits" => script.limits = true,
    +                    _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                },
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());
    +        script.code = code;
    +        script
    +    }
    +
    +    /// Registers this script's benchmarks; `tree` is the host root of the scan tree.
    +    fn register(&self, c: &mut Criterion, tree: &Path) {
    +        let name = &self.name;
    +        let code = self.code.as_str();
    +        let filename = format!("{name}.py");
    +        let data = match &self.input {
    +            Input::None => None,
    +            Input::Data(data) => Some(data.as_str()),
    +            Input::Mount => None,
    +        };
    +        if matches!(self.input, Input::Mount) {
    +            c.bench_function(&format!("{name}__monty"), |b| {
    +                run_monty_mounted(b, code, &filename, tree, MountMode::ReadOnly);
    +            });
    +            if self.overlay {
    +                c.bench_function(&format!("{name}_overlay__monty"), |b| {
    +                    let mode = MountMode::OverlayMemory(OverlayState::new());
    +                    run_monty_mounted(b, code, &filename, tree, mode);
    +                });
    +            }
    +        } else {
    +            c.bench_function(&format!("{name}__monty"), |b| run_monty(b, code, &filename, data));
    +            if self.limits {
    +                c.bench_function(&format!("{name}_limits__monty"), |b| {

    _Auto response from Claude Opus 5.5 (Claude Code) running fix-pr-comments:_

    Valid, though latent: no script combines data= and limits today. Fixed by passing data through: run_monty_limits now declares and binds DATA the same way run_monty does, via shared parse_with_data / data_inputs helpers. Checked by temporarily adding limits to json_loads.py: json_loads_limits__monty runs and passes.

    samuelcolvin samuelcolvin commented on code on Oct 16, 2026 15:21 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));
    +        for option in header
    +            .filter_map(|line| line.strip_prefix("# bench:"))
    +            .flat_map(str::split_whitespace)
    +        {
    +            match option.split_once('=') {
    +                Some(("data", data)) => {
    +                    let data_path = path.parent().unwrap().join(data);
    +                    script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                }
    +                _ => match option {
    +                    "mount" => script.input = Input::Mount,
    +                    "overlay" => script.overlay = true,
    +                    "limits" => script.limits = true,
    +                    _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                },
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());

    _Auto response from Claude Opus 5.5 (Claude Code) running fix-pr-comments:_

    Valid; same bug as the macroscope thread on line 161. I passed the data through instead of rejecting the combination, so data=... limits now registers a working <name>_limits__monty.

    samuelcolvin samuelcolvin commented on code on Oct 16, 2026 15:21 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));

    _Auto response from Claude Opus 5.5 (Claude Code) running fix-pr-comments:_

    Valid. A leading comment that reads as a header but is not exactly # bench: (#bench:, # Bench:, # bench :) now panics with the file and line. Descriptions that only start with a longer word, such as # Benchmarks ..., are still allowed. Checked by temporarily prefixing add_two.py with #bench: limits, which panics with malformed #bench: limits``.

    samuelcolvin samuelcolvin commented on code on Oct 16, 2026 15:21 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,217 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
     
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        let header = code.lines().take_while(|line| line.starts_with('#'));
    +        for option in header
    +            .filter_map(|line| line.strip_prefix("# bench:"))
    +            .flat_map(str::split_whitespace)
    +        {
    +            match option.split_once('=') {
    +                Some(("data", data)) => {
    +                    let data_path = path.parent().unwrap().join(data);
    +                    script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                }
    +                _ => match option {
    +                    "mount" => script.input = Input::Mount,
    +                    "overlay" => script.overlay = true,
    +                    "limits" => script.limits = true,
    +                    _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                },
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());
    +        script.code = code;
    +        script
    +    }
    +
    +    /// Registers this script's benchmarks; `tree` is the host root of the scan tree.
    +    fn register(&self, c: &mut Criterion, tree: &Path) {
    +        let name = &self.name;
    +        let code = self.code.as_str();
    +        let filename = format!("{name}.py");
    +        let data = match &self.input {
    +            Input::None => None,
    +            Input::Data(data) => Some(data.as_str()),
    +            Input::Mount => None,
    +        };
    +        if matches!(self.input, Input::Mount) {
    +            c.bench_function(&format!("{name}__monty"), |b| {
    +                run_monty_mounted(b, code, &filename, tree, MountMode::ReadOnly);
    +            });
    +            if self.overlay {
    +                c.bench_function(&format!("{name}_overlay__monty"), |b| {
    +                    let mode = MountMode::OverlayMemory(OverlayState::new());
    +                    run_monty_mounted(b, code, &filename, tree, mode);
    +                });
    +            }
    +        } else {
    +            c.bench_function(&format!("{name}__monty"), |b| run_monty(b, code, &filename, data));
    +            if self.limits {
    +                c.bench_function(&format!("{name}_limits__monty"), |b| {
    +                    run_monty_limits(b, code, &filename);
    +                });
    +            }
    +        }
    +        #[cfg(not(feature = "codspeed"))]
    +        {
    +            let host_root = tree.to_str().expect("temporary directories have UTF-8 paths");
    +            let data = if matches!(self.input, Input::Mount) {
    +                Some(host_root)
    +            } else {
    +                data
    +            };
    +            c.bench_function(&format!("{name}__cpython"), |b| run_cpython(b, code, &filename, data));
    +        }
    +    }
    +}
    +
    +/// The `.py` files directly in `dir`.
    +fn python_files(dir: &str) -> impl Iterator<Item = PathBuf> {
    +    fs::read_dir(dir)
    +        .unwrap_or_else(|err| panic!("reading {dir}: {err}"))
    +        .map(|entry| entry.unwrap().path())
    +        .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "py"))
    +}
    +
    +/// A path's file stem, which every script path has.
    +fn file_stem(path: &Path) -> &str {
    +    path.file_stem().and_then(|stem| stem.to_str()).unwrap()
    +}
    +
    +/// Parses once, then benchmarks repeated execution, binding `DATA` when `data` is given.
    +fn run_monty(bench: &mut Bencher, code: &str, filename: &str, data: Option<&str>) {
    +    let input_names = data.map(|_| vec!["DATA".to_owned()]).unwrap_or_default();
    +    let mut ex = MontyRun::new(code.to_owned(), filename, input_names, CompileOptions::default()).unwrap();
    +    let inputs = || {
    +        data.map(|data| vec![MontyObject::string(data.to_owned())])
    +            .unwrap_or_default()
    +    };
    +    bench.iter(|| black_box(ex.run_no_limits(inputs()).unwrap()));

    _Auto response from Claude Opus 5.5 (Claude Code) running fix-pr-comments:_

    Not changing this. add_two measures fixed run overhead for one constant addition, and an assert inside the timed loop would add a comparison and jump that change what it measures. Its old check of 3 ran once, outside the loop, on arithmetic the test suite already covers. gc_collect had no real check before: it returned a dummy 0 because Monty and CPython report different gc.collect() counts, so asserting a value would break the CPython side. Every other script asserts its result.

    codspeed[bot] codspeed[bot] commented on Oct 16, 2026 15:36 UTC
    Bot

    <!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

    Merging this PR will degrade performance by 20.81%

    ❌ 1 (👁 1) regressed benchmark
    ✅ 95 untouched benchmarks
    ⏩ 78 skipped benchmarks[^skipped]

    Performance Changes

    | | Mode | Benchmark | BASE | HEAD | Efficiency |
    | --- | ---- | --------- | ------ | ------ | ---------- |
    | 👁 | WallTime | ` add_two__monty ` | 1.9 µs | 2.4 µs | -20.81% |

    ---

    <sub>Comparing <code>bench-scripts-from-directory</code> (b69fd14) with <code>main</code> (dafc9a0)</sub>

    <a href="https://app.codspeed.io/pydantic/monty/branches/bench-scripts-from-directory?utm_source=github&utm_medium=comment-v2&utm_content=button">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
    <source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
    <img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
    </picture>
    </a>

    [^skipped]: 78 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 16, 2026 15:47 UTC
    Reviewer

    <!-- Macroscope (Approvability) review body marker -->
    <!-- MURMUR_IGNORE -->
    <!-- macroscope-meta: {"kind":"approvability"} -->

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 16, 2026 16:25 UTC
    Reviewer

    <!-- Macroscope (Approvability) review body marker -->
    <!-- MURMUR_IGNORE -->
    <!-- macroscope-meta: {"kind":"approvability"} -->

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 16, 2026 16:33 UTC
    Reviewer

    <!-- Macroscope (Approvability) review body marker -->
    <!-- MURMUR_IGNORE -->
    <!-- macroscope-meta: {"kind":"approvability"} -->

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 16, 2026 16:35 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,234 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
    +
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        for line in code.lines().take_while(|line| line.starts_with('#')) {
    +            let Some(options) = line.strip_prefix("# bench:") else {
    +                assert!(!is_misspelled_header(line), "{}: malformed `{line}`", path.display());
    +                continue;
    +            };
    +            for option in options.split_whitespace() {
    +                match option.split_once('=') {
    +                    Some(("data", data)) => {
    +                        let data_path = path.parent().unwrap().join(data);
    +                        script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                    }
    +                    _ => match option {
    +                        "mount" => script.input = Input::Mount,
    +                        "overlay" => script.overlay = true,
    +                        "limits" => script.limits = true,
    +                        _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                    },
    +                }
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());
    +        script.code = code;
    +        script
    +    }
    +
    +    /// Registers this script's benchmarks; `tree` is the host root of the scan tree.
    +    fn register(&self, c: &mut Criterion, tree: &Path) {
    +        let name = &self.name;
    +        let code = self.code.as_str();
    +        let filename = format!("{name}.py");

    <!-- cubic:v=ddf7f12e-9281-474b-b74f-bb1f5dbb3d10 -->
    <!-- cubic:review-run=f0f770b7-dc48-5d59-9f9f-6641d4c4ca1e -->
    <!-- metadata:{"confidence":5} -->
    P3: The script filename is derived from the stripped benchmark name, so a bench__kitchen_sink.py failure reports kitchen_sink.py, a file that doesn't exist. Store the real file name on Script and pass it to MontyRun::new and compile.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-bench/benches/main.rs, line 144:
    
    <comment>The script filename is derived from the stripped benchmark name, so a `bench__kitchen_sink.py` failure reports `kitchen_sink.py`, a file that doesn't exist. Store the real file name on `Script` and pass it to `MontyRun::new` and `compile`.</comment>
    
    <file context>
    @@ -25,82 +39,234 @@ use tempfile::TempDir;
    +    fn register(&self, c: &mut Criterion, tree: &Path) {
    +        let name = &self.name;
    +        let code = self.code.as_str();
    +        let filename = format!("{name}.py");
    +        let data = match &self.input {
    +            Input::None => None,
    </file context>
    

    </details>

    ✅ Addressed in b69fd14

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 16, 2026 16:35 UTC
    Reviewer

    <!-- cubic:review-summary:start -->
    All reported issues were addressed across 30 files
    <!-- cubic:review-summary:end -->

    <sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Turn on auto-fix | Re-trigger cubic</sub>

    <!-- cubic:review-post:ai_pr_review_github_delivery_8ddc3a8b16c70a9e885095b9e7a4d50bd4750e62e18799d3e5837b9b841db2dd:21bd779e02790758f9508f0c1c348d6c87de0dd2:f0f770b7-dc48-5d59-9f9f-6641d4c4ca1e -->

    jaheba jaheba commented on code on Oct 17, 2026 11:49 UTC
    Code Review
    crates/monty-bench/benches/python/json_dumps.py:1
    @@ -1,7 +1,10 @@
    +# Serializes the parsed `medium_response.json` 1,000 times.
    +# bench: data=../medium_response.json

    Could these bench: comments be a bit more explicit in syntax? This currently looks to much like a normal comment to me. Something like "#@bench:# would make it more clear, that the comment is controlling how the benchmark is executed.

    jaheba jaheba commented on Oct 17, 2026 11:52 UTC
    Reviewer

    Nice!

    Something I was thinking: Would it make sense to have different suits of benchmarks? E.g. we could have a set of memory-usage oriented benchmarks, where we don't really care that much about runtime. Or, just have a selected set for PRs to ensure that there are no regressions, and run the full suit on main?

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 17, 2026 16:43 UTC
    Reviewer

    <!-- Macroscope (Approvability) review body marker -->
    <!-- MURMUR_IGNORE -->
    <!-- macroscope-meta: {"kind":"approvability"} -->

    macroscopeapp[bot] macroscopeapp[bot] commented on Oct 17, 2026 17:02 UTC
    Reviewer

    <!-- Macroscope (Approvability) review body marker -->
    <!-- MURMUR_IGNORE -->
    <!-- macroscope-meta: {"kind":"approvability"} -->

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 17, 2026 17:06 UTC
    Reviewer

    <!-- cubic:review-summary:start -->
    All reported issues were addressed across 128 files (changes from recent commits).
    <!-- cubic:review-summary:end -->

    <sub>Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.</sub>

    <sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Turn on auto-fix | Re-trigger cubic</sub>

    <!-- cubic:review-post:ai_pr_review_github_delivery_e0d12bdd43a5f892f7acdc0e62a66cb0767696753889f3650fbc97da6eef4a65:751465a7a87e43fa2409b91e8e2052681776e9c4:56be5511-4500-5e94-8062-9b2e4dbb9bc3 -->

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 17, 2026 17:06 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +40,212 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its header's `[bench]` table.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
    +
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on a malformed header or inconsistent options.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let header = Header::parse(&code).unwrap_or_else(|err| panic!("{}: {err}", path.display()));

    <!-- cubic:v=3c0f272b-e17e-4f8b-bd7a-11d1c8c30609 -->
    <!-- cubic:review-run=56be5511-4500-5e94-8062-9b2e4dbb9bc3 -->
    <!-- metadata:{"confidence":6} -->
    P2: Script::parse reads only header.bench, so test-only keys such as gc-interval, mount-fs, xfail or timezone in a benchmark's # /// monty header are accepted and silently ignored. Reject any non-default top-level Header field here so a misplaced option fails loudly.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-bench/benches/main.rs, line 102:
    
    <comment>`Script::parse` reads only `header.bench`, so test-only keys such as `gc-interval`, `mount-fs`, `xfail` or `timezone` in a benchmark's `# /// monty` header are accepted and silently ignored. Reject any non-default top-level `Header` field here so a misplaced option fails loudly.</comment>
    
    <file context>
    @@ -95,46 +96,32 @@ impl Script {
    +    /// Reads one script and its header, panicking on a malformed header or inconsistent options.
         fn parse(path: &Path) -> Self {
             let code = fs::read_to_string(path).unwrap();
    +        let header = Header::parse(&code).unwrap_or_else(|err| panic!("{}: {err}", path.display()));
    +        let Bench {
    +            data,
    </file context>
    

    </details>

    ✅ Addressed in b69fd14

    cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 17, 2026 17:06 UTC
    Code Review
    crates/monty-fixture/src/lib.rs:1
    @@ -0,0 +1,157 @@
    +//! The `# /// monty` header that configures a test case (`crates/monty/test_cases/`) or a
    +//! benchmark script (`crates/monty-bench/benches/python/`).
    +//!
    +//! The header is a [PEP 723](https://peps.python.org/pep-0723/) comment block of TOML, so
    +//! both the datatest harness and the benchmarks read it through one strict parser:
    +//!
    +//! ```python
    +//! # /// monty
    +//! # call-external = true
    +//! # xfail = ['cpython']
    +//! # [bench]
    +//! # limits = true
    +//! # ///
    +//! ```
    +
    +use std::{error::Error, fmt};
    +
    +use serde::Deserialize;
    +
    +/// The line that opens a monty header block.
    +const BLOCK_START: &str = "# /// monty";
    +/// The line that closes any PEP 723 block.
    +const BLOCK_END: &str = "# ///";
    +
    +/// A fixture's settings; every field defaults to off, so a file without a header gets
    +/// `Header::default()`. Unknown keys are errors, so a typo can't silently drop a setting.
    +#[derive(Debug, Default, Deserialize)]
    +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
    +#[expect(clippy::struct_excessive_bools, reason = "one bool per TOML flag")]
    +pub struct Header {
    +    /// Run with external-function support, driving `RunProgress` suspensions.
    +    pub call_external: bool,
    +    /// Wrap the code in an async context for CPython, allowing top-level `await`.
    +    pub run_async: bool,
    +    /// Mount a fixture directory: `/mnt` for Monty, a real path for CPython.
    +    pub mount_fs: bool,
    +    /// Skip the CPython side on Windows, for POSIX path semantics only Monty provides there.
    +    pub skip_cpython_windows: bool,
    +    /// Set `__name__ = '__main__'` for CPython only.
    +    pub cpython_main_module: bool,
    +    /// Interpreters the case must fail on (strict: passing there is an error).
    +    pub xfail: Vec<Interpreter>,
    +    /// Overrides the GC interval of the case's resource limits.
    +    pub gc_interval: Option<usize>,
    +    /// IANA zone both sides run in, instead of UTC.
    +    pub timezone: Option<String>,
    +    /// Benchmark options, read only by `monty-bench`.
    +    pub bench: Bench,
    +}
    +
    +impl Header {
    +    /// Reads the `# /// monty` block from `source`, or returns the default header if there is none.
    +    ///
    +    /// Errors on malformed TOML, unknown keys, an unterminated or repeated block, and any other
    +    /// `# ///` line, such as a misspelt block type.
    +    pub fn parse(source: &str) -> Result<Self, HeaderError> {
    +        match extract_block(source)? {
    +            Some(toml) => toml::from_str(&toml).map_err(|err| HeaderError(err.to_string())),
    +            None => Ok(Self::default()),
    +        }
    +    }
    +
    +    /// Whether the case is expected to fail on `interpreter`.
    +    #[must_use]
    +    pub fn xfails(&self, interpreter: Interpreter) -> bool {
    +        self.xfail.contains(&interpreter)
    +    }
    +}
    +
    +/// An interpreter a test case runs on, as named by `xfail`.
    +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
    +#[serde(rename_all = "lowercase")]
    +pub enum Interpreter {
    +    Monty,
    +    Cpython,
    +}
    +
    +/// The `[bench]` table: how `monty-bench` runs a script.
    +#[derive(Debug, Default, Deserialize)]
    +#[serde(default, deny_unknown_fields)]
    +pub struct Bench {
    +    /// Bind `DATA` to the contents of this file, relative to the script.
    +    pub data: Option<String>,
    +    /// Bind `DATA` to the root of the benchmarks' mounted scan tree.
    +    pub mount: bool,
    +    /// With `mount`, also benchmark over an overlay mount.
    +    pub overlay: bool,
    +    /// Also benchmark with resource limits armed.
    +    pub limits: bool,
    +}
    +
    +/// Why a header couldn't be read.
    +#[derive(Debug)]
    +pub struct HeaderError(String);
    +
    +impl fmt::Display for HeaderError {
    +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    +        f.write_str(&self.0)
    +    }
    +}
    +
    +impl Error for HeaderError {}
    +
    +/// Returns the TOML inside the `# /// monty` block, with each line's `#` prefix removed.
    +fn extract_block(source: &str) -> Result<Option<String>, HeaderError> {
    +    let mut block: Option<String> = None;
    +    let mut lines = source.lines().enumerate();
    +    while let Some((index, line)) = lines.next() {

    <!-- cubic:v=b269052a-5f77-43fe-8517-fb4d08c2283a -->
    <!-- cubic:review-run=56be5511-4500-5e94-8062-9b2e4dbb9bc3 -->
    <!-- metadata:{"confidence":8} -->
    P2: extract_block accepts a matching block anywhere in the Python source, so a later comment or multiline-string content can change fixture settings or cause parsing to fail. Restrict discovery to the leading metadata area before code.

    <details>
    <summary>Prompt for AI agents</summary>

    Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-fixture/src/lib.rs, line 108:
    
    <comment>`extract_block` accepts a matching block anywhere in the Python source, so a later comment or multiline-string content can change fixture settings or cause parsing to fail. Restrict discovery to the leading metadata area before code.</comment>
    
    <file context>
    @@ -0,0 +1,157 @@
    +fn extract_block(source: &str) -> Result<Option<String>, HeaderError> {
    +    let mut block: Option<String> = None;
    +    let mut lines = source.lines().enumerate();
    +    while let Some((index, line)) = lines.next() {
    +        if line == BLOCK_START {
    +            if block.is_some() {
    </file context>
    

    </details>

    ✅ Addressed in b69fd14

    samuelcolvin samuelcolvin commented on code on Oct 17, 2026 19:28 UTC
    Code Review
    crates/monty-bench/benches/python/json_dumps.py:1
    @@ -1,7 +1,10 @@
    +# Serializes the parsed `medium_response.json` 1,000 times.
    +# bench: data=../medium_response.json

    done, used PEP 723

    samuelcolvin samuelcolvin commented on code on Oct 17, 2026 19:31 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +39,234 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its `# bench:` header.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
    +
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on an unknown or inconsistent option.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let stem = file_stem(path);
    +        let mut script = Self {
    +            name: stem.strip_prefix("bench__").unwrap_or(stem).to_owned(),
    +            code: String::new(),
    +            input: Input::None,
    +            limits: false,
    +            overlay: false,
    +        };
    +        for line in code.lines().take_while(|line| line.starts_with('#')) {
    +            let Some(options) = line.strip_prefix("# bench:") else {
    +                assert!(!is_misspelled_header(line), "{}: malformed `{line}`", path.display());
    +                continue;
    +            };
    +            for option in options.split_whitespace() {
    +                match option.split_once('=') {
    +                    Some(("data", data)) => {
    +                        let data_path = path.parent().unwrap().join(data);
    +                        script.input = Input::Data(fs::read_to_string(data_path).unwrap());
    +                    }
    +                    _ => match option {
    +                        "mount" => script.input = Input::Mount,
    +                        "overlay" => script.overlay = true,
    +                        "limits" => script.limits = true,
    +                        _ => panic!("{}: unknown `# bench:` option `{option}`", path.display()),
    +                    },
    +                }
    +            }
    +        }
    +        let mounted = matches!(script.input, Input::Mount);
    +        assert!(
    +            !script.overlay || mounted,
    +            "{}: `overlay` needs `mount`",
    +            path.display()
    +        );
    +        assert!(!script.limits || !mounted, "{}: `limits` with `mount`", path.display());
    +        script.code = code;
    +        script
    +    }
    +
    +    /// Registers this script's benchmarks; `tree` is the host root of the scan tree.
    +    fn register(&self, c: &mut Criterion, tree: &Path) {
    +        let name = &self.name;
    +        let code = self.code.as_str();
    +        let filename = format!("{name}.py");

    _Auto response from Claude Opus 5.5 (Claude Code) running fix-pr-comments:_

    Valid, fixed. Script now stores the real file name (bench__kitchen_sink.py) and passes it to MontyRun::new and CPython's compile. The stripped name is still used for the benchmark IDs.

    samuelcolvin samuelcolvin commented on code on Oct 17, 2026 19:32 UTC
    Code Review
    crates/monty-bench/benches/main.rs:1
    @@ -25,82 +40,212 @@ use tempfile::TempDir;
     #[global_allocator]
     static ALLOC: monty_alloc::LimitedAllocator = monty_alloc::LimitedAllocator;
     
    -/// Runs a benchmark using the Monty interpreter.
    -/// Parses once, then benchmarks repeated execution.
    -fn run_monty(bench: &mut Bencher, code: &str, expected: i64) {
    -    let mut ex = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
    -    let r = ex.run_no_limits(vec![]).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// The benchmark scripts. Subdirectories (`pool/`) hold scripts other benches drive.
    +const SCRIPTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/benches/python");
     
    -    bench.iter(|| {
    -        let r = ex.run_no_limits(vec![]).unwrap();
    -        let int_value: i64 = r.as_ref().try_into().unwrap();
    -        black_box(int_value);
    -    });
    +/// The interpreter test cases, whose `bench__*.py` files are also benchmarks.
    +const TEST_CASES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../monty/test_cases");
    +
    +/// Source of the `end_to_end` benchmarks, which parse inside the timed loop.
    +const ADD_TWO: &str = include_str!("python/add_two.py");
    +
    +/// Registers every script benchmark, then the Rust-API benchmarks.
    +fn criterion_benchmark(c: &mut Criterion) {
    +    let tree = scan_tree();
    +    for script in Script::load_all() {
    +        script.register(c, tree.path());
    +    }
    +
    +    c.bench_function("end_to_end__monty", end_to_end_monty);
    +    #[cfg(not(feature = "codspeed"))]
    +    c.bench_function("end_to_end__cpython", end_to_end_cpython);
    +    c.bench_function("parse_1k_assigns__monty", parse_1k_assigns);
    +    c.bench_function("clone_module__monty", clone_module);
    +    c.bench_function("repl_feed_after_2k_snippets__monty", repl_feed_after_2k_snippets);
    +    c.bench_function("session_dump__monty", session_dump);
    +    c.bench_function("session_load__monty", session_load);
     }
     
    -/// Runs a benchmark using the Monty interpreter with a single string input bound to `DATA`.
    -/// Parses once, then benchmarks repeated execution with the same input.
    -fn run_monty_with_data(bench: &mut Bencher, code: &str, data: &str, expected: i64) {
    -    let mut ex = MontyRun::new(
    -        code.to_owned(),
    -        "test.py",
    -        vec!["DATA".to_owned()],
    -        CompileOptions::default(),
    -    )
    -    .unwrap();
    -    let make_input = || vec![MontyObject::string(data.to_owned())];
    -    let r = ex.run_no_limits(make_input()).unwrap();
    -    let int_value: i64 = r.as_ref().try_into().unwrap();
    -    assert_eq!(int_value, expected);
    +/// A benchmark script with the options from its header's `[bench]` table.
    +struct Script {
    +    /// The file stem, without a test case's `bench__` prefix.
    +    name: String,
    +    code: String,
    +    input: Input,
    +    /// Also benchmark with resource limits armed.
    +    limits: bool,
    +    /// Also benchmark over an overlay mount; requires [`Input::Mount`].
    +    overlay: bool,
    +}
    +
    +/// What a script's `DATA` global is bound to.
    +enum Input {
    +    None,
    +    /// The contents of a file, from `data=<path>`.
    +    Data(String),
    +    /// The scan tree's root: `/data` for Monty's mount, the host path for CPython.
    +    Mount,
    +}
    +
    +impl Script {
    +    /// Reads every script, sorted by path so benchmarks register in a stable order.
    +    fn load_all() -> Vec<Self> {
    +        let mut paths: Vec<PathBuf> = python_files(SCRIPTS_DIR).collect();
    +        paths.extend(python_files(TEST_CASES_DIR).filter(|path| file_stem(path).starts_with("bench__")));
    +        paths.sort();
    +        paths.iter().map(|path| Self::parse(path)).collect()
    +    }
    +
    +    /// Reads one script and its header, panicking on a malformed header or inconsistent options.
    +    fn parse(path: &Path) -> Self {
    +        let code = fs::read_to_string(path).unwrap();
    +        let header = Header::parse(&code).unwrap_or_else(|err| panic!("{}: {err}", path.display()));

    _Auto response from Claude Opus 5.5 (Claude Code) running fix-pr-comments:_

    Valid, fixed. Script::parse takes the [bench] table out of the header and asserts that what's left equals Header::default(). A test-case key such as gc-interval in a benchmark script now panics with `only [bench] options apply to benchmarks (checked by hand). Header and Bench derive PartialEq` for this.

    samuelcolvin samuelcolvin commented on code on Oct 17, 2026 19:32 UTC
    Code Review
    crates/monty-fixture/src/lib.rs:1
    @@ -0,0 +1,157 @@
    +//! The `# /// monty` header that configures a test case (`crates/monty/test_cases/`) or a
    +//! benchmark script (`crates/monty-bench/benches/python/`).
    +//!
    +//! The header is a [PEP 723](https://peps.python.org/pep-0723/) comment block of TOML, so
    +//! both the datatest harness and the benchmarks read it through one strict parser:
    +//!
    +//! ```python
    +//! # /// monty
    +//! # call-external = true
    +//! # xfail = ['cpython']
    +//! # [bench]
    +//! # limits = true
    +//! # ///
    +//! ```
    +
    +use std::{error::Error, fmt};
    +
    +use serde::Deserialize;
    +
    +/// The line that opens a monty header block.
    +const BLOCK_START: &str = "# /// monty";
    +/// The line that closes any PEP 723 block.
    +const BLOCK_END: &str = "# ///";
    +
    +/// A fixture's settings; every field defaults to off, so a file without a header gets
    +/// `Header::default()`. Unknown keys are errors, so a typo can't silently drop a setting.
    +#[derive(Debug, Default, Deserialize)]
    +#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
    +#[expect(clippy::struct_excessive_bools, reason = "one bool per TOML flag")]
    +pub struct Header {
    +    /// Run with external-function support, driving `RunProgress` suspensions.
    +    pub call_external: bool,
    +    /// Wrap the code in an async context for CPython, allowing top-level `await`.
    +    pub run_async: bool,
    +    /// Mount a fixture directory: `/mnt` for Monty, a real path for CPython.
    +    pub mount_fs: bool,
    +    /// Skip the CPython side on Windows, for POSIX path semantics only Monty provides there.
    +    pub skip_cpython_windows: bool,
    +    /// Set `__name__ = '__main__'` for CPython only.
    +    pub cpython_main_module: bool,
    +    /// Interpreters the case must fail on (strict: passing there is an error).
    +    pub xfail: Vec<Interpreter>,
    +    /// Overrides the GC interval of the case's resource limits.
    +    pub gc_interval: Option<usize>,
    +    /// IANA zone both sides run in, instead of UTC.
    +    pub timezone: Option<String>,
    +    /// Benchmark options, read only by `monty-bench`.
    +    pub bench: Bench,
    +}
    +
    +impl Header {
    +    /// Reads the `# /// monty` block from `source`, or returns the default header if there is none.
    +    ///
    +    /// Errors on malformed TOML, unknown keys, an unterminated or repeated block, and any other
    +    /// `# ///` line, such as a misspelt block type.
    +    pub fn parse(source: &str) -> Result<Self, HeaderError> {
    +        match extract_block(source)? {
    +            Some(toml) => toml::from_str(&toml).map_err(|err| HeaderError(err.to_string())),
    +            None => Ok(Self::default()),
    +        }
    +    }
    +
    +    /// Whether the case is expected to fail on `interpreter`.
    +    #[must_use]
    +    pub fn xfails(&self, interpreter: Interpreter) -> bool {
    +        self.xfail.contains(&interpreter)
    +    }
    +}
    +
    +/// An interpreter a test case runs on, as named by `xfail`.
    +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
    +#[serde(rename_all = "lowercase")]
    +pub enum Interpreter {
    +    Monty,
    +    Cpython,
    +}
    +
    +/// The `[bench]` table: how `monty-bench` runs a script.
    +#[derive(Debug, Default, Deserialize)]
    +#[serde(default, deny_unknown_fields)]
    +pub struct Bench {
    +    /// Bind `DATA` to the contents of this file, relative to the script.
    +    pub data: Option<String>,
    +    /// Bind `DATA` to the root of the benchmarks' mounted scan tree.
    +    pub mount: bool,
    +    /// With `mount`, also benchmark over an overlay mount.
    +    pub overlay: bool,
    +    /// Also benchmark with resource limits armed.
    +    pub limits: bool,
    +}
    +
    +/// Why a header couldn't be read.
    +#[derive(Debug)]
    +pub struct HeaderError(String);
    +
    +impl fmt::Display for HeaderError {
    +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    +        f.write_str(&self.0)
    +    }
    +}
    +
    +impl Error for HeaderError {}
    +
    +/// Returns the TOML inside the `# /// monty` block, with each line's `#` prefix removed.
    +fn extract_block(source: &str) -> Result<Option<String>, HeaderError> {
    +    let mut block: Option<String> = None;
    +    let mut lines = source.lines().enumerate();
    +    while let Some((index, line)) = lines.next() {

    _Auto response from Claude Opus 5.5 (Claude Code) running fix-pr-comments:_

    Valid, fixed. extract_block only accepts the block in the file's leading comment and blank lines. A # /// monty line after code, including one inside a string, is now an error (must come before any code) instead of being ignored or applied. New tests in crates/monty-fixture/tests/header.rs cover this and the other rejection paths. TOML errors now also name the file line the header opens on, since TOML's own line numbers are relative to the block.

    macroscopeapp[bot] macroscopeapp[bot] approved these changes on Oct 17, 2026 19:38 UTC
    Approved Reviewer

    <!-- Macroscope (Approvability) review body marker -->
    <!-- MURMUR_IGNORE -->
    <!-- macroscope-meta: {"kind":"approvability"} -->

    Reviewers
    Assignees
    samuelcolvin samuelcolvin
    Labels
    risk: low confidence: 79.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 79.7% · Lower = rushed or shallow review
    79.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.3% · Safe to merge
    17.3%
    Repository