Register interpreter benchmarks from the python/ directory #1057
<!-- 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 |
🟡 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"} -->
<!-- macroscope-meta: {"kind":"code_review","variant":"50d9a9128a918cceace09f2512c6481c"} -->
<!-- Macroscope (Approvability) review body marker -->
<!-- MURMUR_IGNORE -->
<!-- macroscope-meta: {"kind":"approvability"} -->
<!-- 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:
<sup>You can add or adjust custom eligibility rules. Learn more.</sup>
<!-- macroscope-meta: {"kind":"approvability"} -->
<!-- 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: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: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: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 -->
<!-- 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 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!
_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.
_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.
_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``.
_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_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.
<!-- Macroscope (Approvability) review body marker -->
<!-- MURMUR_IGNORE -->
<!-- macroscope-meta: {"kind":"approvability"} -->
<!-- Macroscope (Approvability) review body marker -->
<!-- MURMUR_IGNORE -->
<!-- macroscope-meta: {"kind":"approvability"} -->
<!-- Macroscope (Approvability) review body marker -->
<!-- MURMUR_IGNORE -->
<!-- macroscope-meta: {"kind":"approvability"} -->
<!-- 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: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 -->
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.
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?
<!-- Macroscope (Approvability) review body marker -->
<!-- MURMUR_IGNORE -->
<!-- macroscope-meta: {"kind":"approvability"} -->
<!-- Macroscope (Approvability) review body marker -->
<!-- MURMUR_IGNORE -->
<!-- macroscope-meta: {"kind":"approvability"} -->
<!-- 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: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: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
done, used PEP 723
_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.
_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.
_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.
<!-- Macroscope (Approvability) review body marker -->
<!-- MURMUR_IGNORE -->
<!-- macroscope-meta: {"kind":"approvability"} -->
samuelcolvin
Follows #1055, which moved the scripts into
benches/python/but kept each benchmark's expected value, inputs and variants inmain.rs.Now the scripts are plain Python and
main.rsregisters them by reading the directory: adding a.pyfile adds a benchmark, with no Rust change.asserton 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>bindsDATAto a file's contents,mountbinds it to the mounted scan tree (overlayadds an overlay-mount variant),limitsadds a resource-limits variant. Unknown options panic.benches/python/.py, plustest_cases/bench__.py, so the kitchen sink stays shared with the datatest suite. Its# Return=373becameassert result == 373.fib_25.pywas renamed tofib.pyto keepfib__monty. The same benchmarks register as before: 63 locally and 36 under thecodspeedfeature.wrap_for_cpython's text rewrite intodef main(). Module-scope variable access is slower in CPython than locals, so the local__cpythonnumbers will rise. The comparison is now like for like.csv_read/csv_writebenchmarks from #1018 are converted too. Their CPython variants were gated oncfg(not(codspeed)), which walltime and memory builds never set, so they were running in CodSpeed CI. Every CPython benchmark is now gated on thecodspeedfeature.pool.rs's scripts moved topython/pool/, since they need a host to answer their calls.end_to_endnow parsesadd_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:
-- --testpasses with and without thecodspeedfeature, a wrong expected value fails the benchmark with the script's traceback, and thebench__kitchen_sinkdatatest 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.pyfile adds a benchmark without a Rust change. Each script checks its own result with anassert.The new
monty-fixturecrate parses a# /// montyPEP 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, soTRACEBACKline numbers in test cases were updated to count its lines.# bench:options became the header's[bench]table (data,mount,overlay,limits), and non-[bench]keys are rejected.DATAis bound in limits runs too, and onlyloop_mod_13keeps a limits variant now that the csv ones are dropped.__cpythonnumbers will shift as module-scope variable access is slower than the oldmain()-wrapped locals.pool.rs's scripts moved topython/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. -->