Repository navigation
Conversation
WalkthroughThe Markdown reference-definition path was refactored to remove the standalone hashtable builder, consume reference definitions while closing eligible blocks, and add a regression test for duplicate labels before setext headings. ChangesReference definition parser refactor
Sequence Diagram(s)sequenceDiagram
participant Parser
participant Blocks
participant RefDefs
Parser->>Blocks: end_current_block
Blocks->>Blocks: check paragraph or setext heading
Blocks->>RefDefs: consume_ref_defs_from_current_block
RefDefs->>RefDefs: normalize label and insert first match
RefDefs->>Blocks: mark block ref-def-only when needed
Compact metadata: Rust parser refactor + JS regression test, +25/-24 lines in parser/blocks and +76 lines in tests. Related issues: None specified. Related PRs: None specified. Suggested labels: markdown, parser, refactor, tests Suggested reviewers: Maintainers familiar with A header meets a hidden chain, 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 4:56 PM PT - Jul 4th, 2026
❌ @robobun, your commit 067b08e has 3 failures in
🧪 To try this PR locally: bunx bun-pr 32291That installs a local version of the PR into your bun-32291 --bun |
There was a problem hiding this comment.
LGTM — straightforward allocation cleanup mirroring the sibling loop in ref_defs.rs.
Extended reasoning...
Overview
This PR touches one function, consume_ref_defs_from_current_block in src/md/blocks.rs, and adds a regression test in test/js/bun/md/md-edge-cases.test.ts. The change defers Box::from(result.dest)/Box::from(result.title) until after the duplicate-label check, and drops the unused raw_label box and the end_pos local entirely. The resulting loop body is now byte-for-byte identical to the established sibling in build_ref_def_hashtable (ref_defs.rs:408-446), including the comment text.
Correctness
The original early boxing was a defensive workaround ("Capture borrowed result fields before &mut self calls") that is unnecessary here: ParsedRefDef<'a> borrows from the merged local (moved out of self.buffer via mem::take), not from self, so normalize_label(&mut self, ...) and ref_def_labels.insert do not invalidate result. result.end_pos is usize: Copy, so reading it after the &mut self calls is fine. Behavior is unchanged — only the timing of two allocations moves, and they are skipped on the duplicate-label and empty-label paths.
Security risks
None. This is markdown ref-definition bookkeeping with no auth, crypto, I/O, or unsafe blocks involved; the change only removes redundant heap allocations on a rarely-hit path.
Level of scrutiny
Low. The diff is ~15 lines, purely mechanical, and converges two copies of the same loop to the same shape. The full md spec suite (792), GFM compat (62), and edge-case suite (80) all pass per the PR description, and the added test exercises exactly the modified path (duplicate ref-defs before a setext underline, first-definition-wins, underline-only → paragraph fallback).
Other factors
No bugs were flagged by the bug-hunting system, there are no outstanding human reviewer comments, and the change matches both the Zig reference and the existing Rust sibling. Approving.
f1aa921 to
ad38157
Compare
|
Note Superseded. This comment described the PR as it stood at Original commentRebased onto Local verification on the new base:
One thing worth flagging for whoever picks this up: this is an allocation-only change, so it has no fail-before test. The boxes being removed were dropped unused, the rendered output is byte-identical, and the timing delta is inside noise (40k duplicate definitions with 800-byte dest/title, a 64 MB document: 2,826 ms unfixed vs 2,615 ms on debug+ASAN). Details are in the PR description. The test added here locks in the observable behavior of the touched loop rather than proving the regression. |
There was a problem hiding this comment.
LGTM — straightforward allocation cleanup that matches the sibling pattern in build_ref_def_hashtable.
Extended reasoning...
Overview
This PR touches one function in src/md/blocks.rs (consume_ref_defs_from_current_block, the setext-heading ref-def path) and adds one coverage test to test/js/bun/md/md-edge-cases.test.ts. The change moves Box::from(result.dest) and Box::from(result.title) from before the label-normalize/dedup check to inside the !contains branch, and drops the never-stored raw_label box entirely. result.end_pos is now read directly instead of via a local. Net: three fewer throwaway heap allocations per duplicate/rejected ref-def; no observable behavior change.
Correctness
The old "capture borrowed result fields before &mut self calls" comment was stale defensive code. parse_ref_def<'a>(&self, text: &'a [u8], ...) ties the returned slices' lifetime to text (here &merged), not to self, and merged was already mem::take'd out of self.buffer before the loop. So result.label/dest/title/end_pos remain valid across the &mut self calls to normalize_label and ref_def_labels.contains/insert — the borrow checker confirms it (this compiles), and nothing in those calls can reach merged. This now mirrors the sibling loop in ref_defs.rs::build_ref_def_hashtable, which already dupes only inside the !contains branch.
Security risks
None. No user-facing surface change, no new parsing logic, no bounds arithmetic altered. Pure allocation reordering in safe Rust.
Level of scrutiny
Low. ~15 lines net in a cold path (setext headings with leading ref-defs), behavior-preserving, matches an existing in-tree pattern. The PR description is honest that the added test is coverage-only (won't fail on main) since the win is unmeasurable transient allocations. The full md test suites (edge-cases, spec, gfm-compat) were run and pass.
Other factors
The bug hunter flagged one pre-existing CommonMark ordering quirk (setext ref-defs beat earlier paragraph ref-defs) that this PR neither introduces nor touches — it's an architectural ordering issue between the line-loop insert and the post-pass build_ref_def_hashtable, out of scope for an allocation-only change. No prior reviewer comments to address.
A link reference definition inside a setext-heading block beat an earlier
definition of the same label in a plain paragraph:
[a]: /first
[a]: /second
h
===
[a]
resolved to /second. CommonMark 4.7 says the first definition in document
order wins.
Setext-heading definitions were collected by consume_ref_defs_from_current_block
as the block closed, during the line loop. Paragraph definitions were collected
by build_ref_def_hashtable, a pass that ran after the whole document was parsed.
Both enforce first-definition-wins against the shared ref_def_labels set, so
whichever pass ran first claimed the label no matter where its definition sat in
the source.
end_current_block now takes leading ref defs from paragraphs as well as setext
headings, matching md4c's md_end_current_block. Every definition lands in
ref_defs in document order and build_ref_def_hashtable is deleted. A block whose
lines are all ref defs is flagged BLOCK_REF_DEF_ONLY by
consume_ref_defs_from_current_block, so a paragraph that is nothing but
definitions still renders as nothing rather than an empty <p></p>; the setext
arm that used to set that flag goes with it.
Also dupe dest and title only when the definition is stored, and drop the raw
label box that was never stored. Repeated definitions paid three throwaway
allocations each.
ad38157 to
0918e54
Compare
|
Good catch on the precedence bug, and it turned out to be worth pulling into this PR rather than leaving for later. I'd opened this as an allocation-only change, which meant it had no test that could fail without it. The ordering bug lives on the exact insert this PR was reordering, and it is observable, so fixing both together gives the change something to prove. The PR has been retitled and rewritten around the bug fix; the allocation cleanup rides along. Confirmed the diagnosis: setext definitions were collected during the line loop while paragraph definitions were collected in Two things your analysis didn't cover that turned up while implementing:
Verification beyond the suites: a 4000-document differential fuzz against the unfixed build shows zero output differences, and a targeted 54-case corpus permuting definition placement shows 18 differences, every one of them the intended class. Details are in the PR description. |
|
Warning Superseded and partly wrong. The claim below that Original commentCI on
|
| annotation | tests | |
|---|---|---|
warning (flaky) |
bake/dev-and-prod, cli/install/bun-install, spawn/spawn-pipe-leak |
Windows / spawn, unrelated |
error (hard) |
js/node/tls/tls-syscall-fault |
see below |
The one hard failure is a pre-existing break on main
test/js/node/tls/tls-syscall-fault.test.ts landed two commits before this branch's base, in c7ae04c (#33326). It asserts:
const outOfMemory = stderr.includes("Bun ran out of memory");There are two OOM strings in src/crash_handler/lib.rs, and they are not the same sentence:
lib.rs:691—CrashReason::OutOfMemory => writer.write_str("Bun ran out of memory")lib.rs:1208—"Bun has run out of memory.\n\nTo send a redacted crash report..."
On the x64-asan lane the fixture emits only the second one, so includes("Bun ran out of memory") is false and the assertion fails on outOfMemory. The behavior actually under test is fine: markers came back as ["ARMED"], meaning no TLS socket survived the failed allocation and nothing faulted inside SSL_read. Only the string match failed.
It passes on this branch locally on debug+ASAN (11 pass, including that test), because the debug path does print the lib.rs:691 wording. That makes it a build-config-dependent string mismatch rather than a race, so it should reproduce on any PR that runs the asan lane, and a re-trigger will not clear it. I have not pushed a ci: retrigger for that reason; it would burn a build without changing the outcome. Whether lib.rs:1208 should also print the crash reason, or the test should match the banner, is a call for whoever owns #33326.
State of this PR
- diff is green on every lane that exercises it
MERGEABLE, no unresolved review threadsreference definition precedence across block kindsfails onmainand passes here, so the fail-before coverage is real
Handing off. Happy to rebase onto a main that has the TLS test fixed if that is preferred to merging through it.
tls-syscall-fault.test.ts failed on one x64-asan shard of build 68356. It passes locally on the release-asan profile both on this branch and on main, so the failure is load-dependent rather than a property of this diff or of main.
Correction: my previous CI analysis was wrongI said the The mistake was the experiment I ran. I reproduced on the debug-ASAN profile ( Rebuilt both trees on the actual
It passes on For the record, I have pushed one Nothing about the diff itself has changed: |
Status: the diff is green, CI is flaky across unrelated lanesBuild #68372 has now finished. Updating this comment since my earlier version was written mid-build and understated the failures. The retrigger commit (067b08e) is empty. Its tree is byte-identical to
The two failure sets do not overlap at all, on identical source. That is flakiness in CI, not a property of this diff. Specifics from the finished build:
No markdown test appears in any annotation, in either build. I have used my one re-roll, and another would just reshuffle which unrelated lane happens to be red, so I am not pushing again. What this PR is, for whoever picks it upA CommonMark 4.7 fix. A reference definition inside a setext-heading block beat an earlier definition of the same label in a plain paragraph: resolved to Verification: 792 CommonMark spec tests, plus gfm-compat, md-react, md-render-callback, md-heading-ids and Ready for review. |
|
Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-04, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main. |
A link reference definition inside a setext-heading block beat an earlier definition of the same label in a plain paragraph. CommonMark 4.7: "When there are multiple matching link reference definitions, the first is used."
Repro
bun -e 'process.stdout.write(Bun.markdown.html("[a]: /first\n\n[a]: /second\nh\n===\n\n[a]\n"))'cmark and commonmark.js both resolve
/first. Bun already got this right when both definitions sat in plain paragraphs (that is spec example 8205, which passes); only the setext-block case was wrong.Cause
Definitions were collected by two passes that ran at different times, and both enforce first-definition-wins against the same
ref_def_labelsset:consume_ref_defs_from_current_block, called fromend_current_blockas the block closes, during the line loop.build_ref_def_hashtable, a pass over the finishedblock_bytesthat ran after the whole document was parsed.So every setext definition was inserted before every paragraph definition, and the
containsguard on either side then dropped the paragraph one. Whichever pass ran first claimed the label, regardless of where its definition sat in the source. Document order never entered into it.md4c's
md_end_current_blockconsumes ref defs fromMD_BLOCK_Pand setextMD_BLOCK_Halike; the split into a post-pass is where the port diverged.Fix
end_current_blocknow takes leading ref defs from paragraphs as well as setext headings, so every definition lands inref_defsin document order as its block closes. That makesbuild_ref_def_hashtabledead, and it is deleted (-156 lines).Two details that came with it:
BLOCK_REF_DEF_ONLYinsideconsume_ref_defs_from_current_block. Without that, a paragraph that is nothing but definitions would render as an empty<p></p>, sinceprocess_all_blocksonly skips on the flag, not onn_lines == 0. The setext arm that used to set the flag is gone with it.beg=1, end=0); the new path removes them fromcurrent_block_linesbefore they are ever serialized, which is equivalent (process_leaf_blockskipsbeg > end) and does not rely on onlyPblocks being reachable.Also in
consume_ref_defs_from_current_block:destandtitleare now duped only when the definition is actually stored, and the raw-label box that was never stored is gone. Repeated definitions previously paid three throwawayBox<[u8]>allocations each.Verification
bun bd test test/js/bun/md/, all suites:md-spec(CommonMark + GFM)md-edge-casesgfm-compatmd-reactmd-render-callbackmd-heading-idstest/cli/run/markdown-entrypointThe new tests in
md-edge-cases.test.tsfail onmainand pass here. Two of the four pass both ways on purpose: they guard behavior the restructure could have broken (a definition-only paragraph emitting no markup, an earlier setext definition still winning).Differential checks against the unfixed build
html()andansi(), zero throws.return Ok(())path that keeps a converted setext block open (so a paragraph reachesend_current_blocktwice and must not double-consume), definitions adjacent to code fences / HTML blocks / tables / indented code, and 500 distinct labels interleaved with a setext block to confirmref_def_labels' insertion index stays 1:1 withref_defs.