Repository navigation
Autoresearch round 1: Improve performance - #70
Conversation
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
📝 Coding Plan
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. Comment |
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (3)
Cargo.lockis excluded by!**/*.lockbenches/results.tsvis excluded by!**/*.tsvbenches/uv.lockis excluded by!**/*.lock
📒 Files selected for processing (10)
.gitignorebenches/bench_avg.shbenches/convert_bench.rsbenches/plot_results.pybenches/program.mdbenches/pyproject.tomlsrc/dom_walker.rssrc/element_handler/anchor.rssrc/element_handler/mod.rssrc/lib.rs
| results.tsv | ||
| !benches/results.tsv |
There was a problem hiding this comment.
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.
| 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.
| 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: |
There was a problem hiding this comment.
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.
| 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.
| 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; | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 | 🟠 MajorWrap 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:
LinkStyle::Referencedwith a spaced destination, andLinkStyle::InlinedPreferAutolinkswherecontent == hrefandtitleexists.🤖 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
📒 Files selected for processing (2)
src/element_handler/anchor.rstests/link_tests.rs
| 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; | ||
| } |
There was a problem hiding this comment.
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.
| 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.
Stole Karpathy's autoresearch

Summary by CodeRabbit
New Features
Documentation
Tests
Refactor
Chores