Skip to content

Autoresearch round 1: Improve performance - #70

Merged
letmutex merged 14 commits into
mainfrom
autoresearch-r1
Mar 15, 2026
Merged

letmutex merged 14 commits into
mainfrom
autoresearch-r1

Conversation

@letmutex

@letmutex letmutex commented Mar 15, 2026 •

Copy link
Copy Markdown
Owner

Stole Karpathy's autoresearch
progress

Summary by CodeRabbit

  • New Features

    • Bench runner script to repeat Criterion runs and summarize metrics; TSV-to-SVG results plotting tool.
  • Documentation

    • Added autonomous benchmarking workflow guide and updated bench README with new results.
  • Tests

    • New link handling test ensuring spaces in URLs/titles are preserved.
  • Refactor

    • Simplified internal output accumulation for HTML→Markdown conversion.
  • Chores

    • Broadened .gitignore for generated artifacts; added Python bench project metadata and minor bench tooling updates.

@coderabbitai

coderabbitai Bot commented Mar 15, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds benchmarking tooling and docs, a bench-run aggregation script and plotting utility, and refactors the HTML→Markdown pipeline to use a single String output (changing walk_node/walk_children signatures and anchor handlers).

Changes

Cohort / File(s) Summary
Repo config & bench infra
/.gitignore, benches/pyproject.toml, benches/package.json
Updated ignore patterns (added *.svg, *.log, *.estimates.json), added Python deps manifest, and removed toml devDependency from benches package.json.
Benchmark runner script
benches/bench_avg.sh
New Bash script to run Criterion benchmarks multiple times with optional warmups, locate per-run estimates.json, copy them to prefixN.estimates.json, and compute mean/median, stddev, and CV.
Benchmark harness & config
benches/convert_bench.rs, benches/bench.ts, benches/README.md, benches/bench.ts, benches/bench.ts
Increased Criterion warmup/measurement/sample_size settings; switched bench frontend to import Cargo.toml manifest statically; updated README benchmark results and version.
Bench docs & visualization
benches/program.md, benches/plot_results.py
Added autonomous benchmarking program doc and a new Python module to parse TSV results and render a Karpathy-style SVG progress chart (CLI: input/output).
HTML→Markdown core refactor
src/dom_walker.rs, src/lib.rs, src/element_handler/mod.rs
Replaced Vec<String> accumulation with a single String output across traversal; updated call sites to pass &mut String; renamed/added helpers (append_normalized_content, trim_output_end*, is_plain_text, escape_pre_text_if_needed).
Anchor handling updates
src/element_handler/anchor.rs
Changed build_inlined_anchor signature to accept &str/Option<&str>, added escape_link_destination and process_title, and reworked anchor construction to avoid owned concat helpers.
Tests
tests/link_tests.rs
Added links_with_spaces_in_destination_and_title test validating link escaping for URLs with spaces and a title.

Sequence Diagram(s)

sequenceDiagram
  participant User as User
  participant Script as bench_avg.sh
  participant Cargo as cargo bench (Criterion)
  participant FS as FileSystem
  participant Py as InlinePython

  User->>Script: invoke (bench_name, count, warmup, prefix)
  Script->>Cargo: run warmup runs (discard)
  Script->>Cargo: run N benchmark runs
  Cargo-->>FS: write logs (prefixN.log) and Criterion artifacts (estimates.json)
  Script->>FS: scan log for full_id -> locate corresponding estimates.json
  Script->>FS: copy found estimates.json -> prefixN.estimates.json
  Script->>Py: read each estimates.json and extract metric (ms)
  Py-->>Script: return metric values
  Script->>Script: aggregate stats (avg, stddev, CV)
  Script-->>User: print tabular summary
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped through strings where buffers used to be,
I warmed up runs and counted each degree,
Estimates lined up, medians in a row,
I plot the progress where the speed seeds grow,
🥕✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Autoresearch round 1: Improve performance' directly corresponds to the PR's main objective of implementing an autoresearch workflow to improve benchmark performance, as evidenced by the new program.md, benchmarking utilities, and performance improvements shown in README.md.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch autoresearch-r1
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.gitignore:
- Around line 6-7: The .gitignore currently un-ignores benches/results.tsv (the
line '!benches/results.tsv') which contradicts the workflow doc that says this
file must remain untracked; remove the '!benches/results.tsv' entry (or
alternatively align the documentation if you intend to track it) so that the
'results.tsv' ignore rule and the documented workflow are consistent—look for
the 'results.tsv' and '!benches/results.tsv' lines in the .gitignore and delete
the un-ignore line.

In `@benches/bench_avg.sh`:
- Around line 83-84: The current check "if not point_estimate:" treats 0.0 as
missing; change it to an explicit None check by using "if point_estimate is
None:" so the fallback to estimates["mean"]["point_estimate"] only happens when
point_estimate is actually absent, preserving valid zero values.

In `@benches/plot_results.py`:
- Around line 38-43: The current y-axis calculation ties y_max to baseline and
can clip slower runs; update the y-axis bounds in the plotting code (variables
baseline, best, y_pad, y_min, y_max) to ensure y_max covers the largest runtime
in the data (consider kept and valid runtime_ms) rather than only baseline;
compute the max_runtime = max(baseline, valid["runtime_ms"].max(),
kept["runtime_ms"].max() if not kept.empty else baseline), then compute y_pad
(e.g., a fraction of max_runtime - best with a minimum) and set y_max =
max_runtime + y_pad and y_min = best - y_pad so no slower runs are clipped.

In `@src/dom_walker.rs`:
- Around line 44-55: The fast-path in dom_walker where is_plain_text(text)
returns true appends text directly (via output.push_str) and skips
escape_if_needed, which allows raw '&' and '>' to slip through; update the
branch in the is_plain_text handling (and the analogous block later around the
code at lines 117-143) to run the trimmed/selected text through escape_if_needed
(or an equivalent escape function that converts '&' and '>' to safe HTML
entities) before pushing to output, preserving the existing trim_start_matches
and empty-string check and still returning markdown_translated as before.

In `@src/element_handler/anchor.rs`:
- Around line 117-128: The closing angle bracket is emitted after the title for
spaced destinations, producing invalid output; in the link rendering code
(variables: has_spaces_in_link, result, link, title) move the closing '>' so it
is pushed immediately after result.push_str(link) when has_spaces_in_link is
true, and then append the optional title (the code that does result.push_str("
\""); result.push_str(title); result.push('"');) afterwards; ensure the opening
'<' remains before the link and that spacing/quotes around the title remain
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d1ad1a2d-469e-4bbb-aa5b-3af732b86c51

📥 Commits

Reviewing files that changed from the base of the PR and between 48cbdeb and 8916da7.

⛔ Files ignored due to path filters (3)
  • Cargo.lock is excluded by !**/*.lock
  • benches/results.tsv is excluded by !**/*.tsv
  • benches/uv.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • .gitignore
  • benches/bench_avg.sh
  • benches/convert_bench.rs
  • benches/plot_results.py
  • benches/program.md
  • benches/pyproject.toml
  • src/dom_walker.rs
  • src/element_handler/anchor.rs
  • src/element_handler/mod.rs
  • src/lib.rs

Comment thread .gitignore Outdated
Comment on lines +6 to +7
results.tsv
!benches/results.tsv

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

benches/results.tsv tracking rule conflicts with the documented workflow.

Line 7 un-ignores benches/results.tsv, but the workflow doc says this file should remain untracked. This inconsistency will lead to accidental commits.

Proposed fix
 results.tsv
-!benches/results.tsv
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
results.tsv
!benches/results.tsv
results.tsv
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.gitignore around lines 6 - 7, The .gitignore currently un-ignores
benches/results.tsv (the line '!benches/results.tsv') which contradicts the
workflow doc that says this file must remain untracked; remove the
'!benches/results.tsv' entry (or alternatively align the documentation if you
intend to track it) so that the 'results.tsv' ignore rule and the documented
workflow are consistent—look for the 'results.tsv' and '!benches/results.tsv'
lines in the .gitignore and delete the un-ignore line.

Comment thread benches/bench_avg.sh Resolved
Comment thread benches/plot_results.py
Comment on lines +38 to +43
baseline = float(valid.iloc[0]["runtime_ms"])
best = float(kept["runtime_ms"].min() if not kept.empty else valid["runtime_ms"].min())
y_pad = max((baseline - best) * 0.15, 0.05)
y_min = best - y_pad
y_max = baseline + y_pad
if y_max <= y_min:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Y-axis can clip slower runs and hide data points.

y_max is tied to baseline, so any later run slower than baseline may render outside the visible range.

Proposed fix
     baseline = float(valid.iloc[0]["runtime_ms"])
     best = float(kept["runtime_ms"].min() if not kept.empty else valid["runtime_ms"].min())
-    y_pad = max((baseline - best) * 0.15, 0.05)
+    worst = float(valid["runtime_ms"].max())
+    y_pad = max((worst - best) * 0.15, 0.05)
     y_min = best - y_pad
-    y_max = baseline + y_pad
+    y_max = worst + y_pad
     if y_max <= y_min:
         y_max = y_min + 1.0
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
baseline = float(valid.iloc[0]["runtime_ms"])
best = float(kept["runtime_ms"].min() if not kept.empty else valid["runtime_ms"].min())
y_pad = max((baseline - best) * 0.15, 0.05)
y_min = best - y_pad
y_max = baseline + y_pad
if y_max <= y_min:
baseline = float(valid.iloc[0]["runtime_ms"])
best = float(kept["runtime_ms"].min() if not kept.empty else valid["runtime_ms"].min())
worst = float(valid["runtime_ms"].max())
y_pad = max((worst - best) * 0.15, 0.05)
y_min = best - y_pad
y_max = worst + y_pad
if y_max <= y_min:
y_max = y_min + 1.0
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@benches/plot_results.py` around lines 38 - 43, The current y-axis calculation
ties y_max to baseline and can clip slower runs; update the y-axis bounds in the
plotting code (variables baseline, best, y_pad, y_min, y_max) to ensure y_max
covers the largest runtime in the data (consider kept and valid runtime_ms)
rather than only baseline; compute the max_runtime = max(baseline,
valid["runtime_ms"].max(), kept["runtime_ms"].max() if not kept.empty else
baseline), then compute y_pad (e.g., a fraction of max_runtime - best with a
minimum) and set y_max = max_runtime + y_pad and y_min = best - y_pad so no
slower runs are clipped.

Comment thread src/dom_walker.rs
Comment on lines +44 to +55
if is_plain_text(text) {
let text = if trim_leading_spaces || (text.starts_with(' ') && last_ends_with_space)
{
text.trim_start_matches(' ')
} else {
text
};
if !text.is_empty() {
output.push_str(text);
}
return markdown_translated;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Plain-text fast path can bypass required escaping for &/>.

When is_plain_text() returns true, text is appended directly and skips escape_if_needed(); currently & (and internal >) are not excluded, which can alter output semantics.

Proposed fix
-            b'\\' | b'*' | b'_' | b'`' | b'[' | b']' | b'<' => return false,
+            b'\\' | b'*' | b'_' | b'`' | b'[' | b']' | b'<' | b'>' | b'&' => return false,

Also applies to: 117-143

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/dom_walker.rs` around lines 44 - 55, The fast-path in dom_walker where
is_plain_text(text) returns true appends text directly (via output.push_str) and
skips escape_if_needed, which allows raw '&' and '>' to slip through; update the
branch in the is_plain_text handling (and the analogous block later around the
code at lines 117-143) to run the trimmed/selected text through escape_if_needed
(or an equivalent escape function that converts '&' and '>' to safe HTML
entities) before pushing to output, preserving the existing trim_start_matches
and empty-string check and still returning markdown_translated as before.

Comment thread src/element_handler/anchor.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/element_handler/anchor.rs (1)

144-162: ⚠️ Potential issue | 🟠 Major

Wrap spaced destinations in reference-style link definitions.

Reference output currently writes bare destinations. If the destination contains spaces, the definition must use <...> to remain valid.

Proposed fix
         AnchorElementHandler::LINKS.with(|links| {
+            let destination = if link.contains(' ') {
+                format!("<{link}>")
+            } else {
+                link
+            };
             let title = title
                 .as_deref()
                 .map_or(String::new(), |t| format!(" \"{t}\""));
             let (current, append) = match style {
                 LinkReferenceStyle::Full => {
                     let index = links.borrow().len() + 1;
                     (
                         concat_strings!("[", content, "][", index.to_string(), "]"),
-                        concat_strings!("[", index.to_string(), "]: ", link, title),
+                        concat_strings!("[", index.to_string(), "]: ", &destination, title),
                     )
                 }
                 LinkReferenceStyle::Collapsed => (
                     concat_strings!("[", content, "][]"),
-                    concat_strings!("[", content, "]: ", link, title),
+                    concat_strings!("[", content, "]: ", &destination, title),
                 ),
                 LinkReferenceStyle::Shortcut => (
                     concat_strings!("[", content, "]"),
-                    concat_strings!("[", content, "]: ", link, title),
+                    concat_strings!("[", content, "]: ", &destination, title),
                 ),
             };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/element_handler/anchor.rs` around lines 144 - 162, The reference-style
link definition currently emits the raw destination string `link` into the
`append` value (constructed in the match across
`LinkReferenceStyle::Full/Collapsed/Shortcut`), which breaks validity when the
destination contains spaces; update the construction of `append` to wrap `link`
in angle brackets when it contains whitespace (but do not double-wrap if it
already starts with '<' and ends with '>'). Concretely, introduce a small helper
or inline check before building `append` (e.g., compute `let dest = if
link.contains(char::is_whitespace) && !(link.starts_with('<') &&
link.ends_with('>')) { format!("<{}>", link) } else { link.to_string() };`),
then use `dest` in the `concat_strings!` calls that produce `append` for the
`LinkReferenceStyle` arms (`Full`, `Collapsed`, `Shortcut`) so spaced
destinations are emitted as `<...>`.
🧹 Nitpick comments (1)
tests/link_tests.rs (1)

20-26: Add regression cases for the other affected link-style branches.

This test is solid for default inlined mode. Please also add cases for:

  1. LinkStyle::Referenced with a spaced destination, and
  2. LinkStyle::InlinedPreferAutolinks where content == href and title exists.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/link_tests.rs` around lines 20 - 26, Add two regression tests to cover
the other link-style branches: 1) a test similar to
links_with_spaces_in_destination_and_title but set LinkStyle::Referenced (use
the same input anchor string with href containing a space and a title) and
assert the expected referenced-style output; 2) a test for
LinkStyle::InlinedPreferAutolinks where the link text equals the href and a
title exists (use an anchor where content == href and title is present) and
assert that the converter produces the inlined-prefer-autolinks form including
the title. Use the same convert(...) helper and naming pattern as the existing
test to locate where to add them.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/element_handler/anchor.rs`:
- Around line 97-103: The autolink fast path in anchor handling (the block that
checks prefer_autolinks && content == link and builds "<...>") drops any title;
modify the branch condition to only take the autolink fast path when there is no
title (e.g., check that title is empty or None) so titles are preserved, leaving
the rest of the anchor-rendering logic to handle cases with a title; update the
condition referencing prefer_autolinks, content, link and title accordingly.

---

Outside diff comments:
In `@src/element_handler/anchor.rs`:
- Around line 144-162: The reference-style link definition currently emits the
raw destination string `link` into the `append` value (constructed in the match
across `LinkReferenceStyle::Full/Collapsed/Shortcut`), which breaks validity
when the destination contains spaces; update the construction of `append` to
wrap `link` in angle brackets when it contains whitespace (but do not
double-wrap if it already starts with '<' and ends with '>'). Concretely,
introduce a small helper or inline check before building `append` (e.g., compute
`let dest = if link.contains(char::is_whitespace) && !(link.starts_with('<') &&
link.ends_with('>')) { format!("<{}>", link) } else { link.to_string() };`),
then use `dest` in the `concat_strings!` calls that produce `append` for the
`LinkReferenceStyle` arms (`Full`, `Collapsed`, `Shortcut`) so spaced
destinations are emitted as `<...>`.

---

Nitpick comments:
In `@tests/link_tests.rs`:
- Around line 20-26: Add two regression tests to cover the other link-style
branches: 1) a test similar to links_with_spaces_in_destination_and_title but
set LinkStyle::Referenced (use the same input anchor string with href containing
a space and a title) and assert the expected referenced-style output; 2) a test
for LinkStyle::InlinedPreferAutolinks where the link text equals the href and a
title exists (use an anchor where content == href and title is present) and
assert that the converter produces the inlined-prefer-autolinks form including
the title. Use the same convert(...) helper and naming pattern as the existing
test to locate where to add them.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ac9de0d4-4ecb-4322-a962-26f5b41e1d25

📥 Commits

Reviewing files that changed from the base of the PR and between 8916da7 and 6a85493.

📒 Files selected for processing (2)
  • src/element_handler/anchor.rs
  • tests/link_tests.rs

Comment on lines 97 to 103
if prefer_autolinks && content == link {
return concat_strings!("<", link, ">");
let mut result = String::with_capacity(link.len() + 2);
result.push('<');
result.push_str(link);
result.push('>');
return result;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Prevent title loss in the autolink fast path.

When prefer_autolinks is true and text equals destination, this branch emits <...> and drops title. Only autolink when no title is present.

Proposed fix
-        if prefer_autolinks && content == link {
+        if prefer_autolinks && title.is_none() && content == link {
             let mut result = String::with_capacity(link.len() + 2);
             result.push('<');
             result.push_str(link);
             result.push('>');
             return result;
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if prefer_autolinks && content == link {
return concat_strings!("<", link, ">");
let mut result = String::with_capacity(link.len() + 2);
result.push('<');
result.push_str(link);
result.push('>');
return result;
}
if prefer_autolinks && title.is_none() && content == link {
let mut result = String::with_capacity(link.len() + 2);
result.push('<');
result.push_str(link);
result.push('>');
return result;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/element_handler/anchor.rs` around lines 97 - 103, The autolink fast path
in anchor handling (the block that checks prefer_autolinks && content == link
and builds "<...>") drops any title; modify the branch condition to only take
the autolink fast path when there is no title (e.g., check that title is empty
or None) so titles are preserved, leaving the rest of the anchor-rendering logic
to handle cases with a title; update the condition referencing prefer_autolinks,
content, link and title accordingly.

@letmutex letmutex changed the title Autoresearch round 1 Autoresearch round 1: Improve Performance Mar 15, 2026
@letmutex letmutex changed the title Autoresearch round 1: Improve Performance Autoresearch round 1: Improve performance Mar 15, 2026
@letmutex
letmutex merged commit 37d86eb into main Mar 15, 2026
1 check passed
@letmutex
letmutex deleted the autoresearch-r1 branch March 15, 2026 03:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant