Skip to content

md: collect paragraph reference definitions in document order - #32291

Closed
robobun wants to merge 2 commits into
mainfrom
farm/d45eed8b/md-ref-def-setext-alloc
Closed

robobun wants to merge 2 commits into
mainfrom
farm/d45eed8b/md-ref-def-setext-alloc

Conversation

@robobun

@robobun robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

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"))'
before:  <h1>h</h1>\n<p><a href="/second">a</a></p>
after:   <h1>h</h1>\n<p><a href="/first">a</a></p>

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_labels set:

  • setext-heading definitions: consume_ref_defs_from_current_block, called from end_current_block as the block closes, during the line loop.
  • paragraph definitions: build_ref_def_hashtable, a pass over the finished block_bytes that ran after the whole document was parsed.

So every setext definition was inserted before every paragraph definition, and the contains guard 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_block consumes ref defs from MD_BLOCK_P and setext MD_BLOCK_H alike; the split into a post-pass is where the port diverged.

Fix

end_current_block now takes leading ref defs from paragraphs as well as setext headings, so every definition lands in ref_defs in document order as its block closes. That makes build_ref_def_hashtable dead, and it is deleted (-156 lines).

Two details that came with it:

  • A block consumed entirely by definitions is flagged BLOCK_REF_DEF_ONLY inside consume_ref_defs_from_current_block. Without that, a paragraph that is nothing but definitions would render as an empty <p></p>, since process_all_blocks only skips on the flag, not on n_lines == 0. The setext arm that used to set the flag is gone with it.
  • The old post-pass poisoned consumed lines in place (beg=1, end=0); the new path removes them from current_block_lines before they are ever serialized, which is equivalent (process_leaf_block skips beg > end) and does not rely on only P blocks being reachable.

Also in consume_ref_defs_from_current_block: dest and title are 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 throwaway Box<[u8]> allocations each.

Verification

bun bd test test/js/bun/md/, all suites:

suite
md-spec (CommonMark + GFM) 792 pass
md-edge-cases 87 pass
gfm-compat 62 pass
md-react 72 pass
md-render-callback 40 pass
md-heading-ids 17 pass
test/cli/run/markdown-entrypoint 29 pass

The new tests in md-edge-cases.test.ts fail on main and 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
  • 4000 randomly generated documents heavy in ref-defs, setext underlines, block quotes and lists: zero output differences on both html() and ansi(), zero throws.
  • A 54-case targeted corpus permuting definition placement across paragraph/setext/blockquote: 18 differ, and every one is the intended class (the definition earlier in the document now wins). The 36 that do not differ are the cases that were already correct.
  • Probes of the paths this restructure could plausibly break, all byte-identical to the unfixed build: the return Ok(()) path that keeps a converted setext block open (so a paragraph reaches end_current_block twice 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 confirm ref_def_labels' insertion index stays 1:1 with ref_defs.

@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The 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.

Changes

Reference definition parser refactor

Layer / File(s) Summary
Remove standalone hashtable build step
src/md/blocks.rs, src/md/parser.rs, src/md/ref_defs.rs
process_doc no longer calls build_ref_def_hashtable; the method is removed from ref_defs.rs, its imports are trimmed, and the doc-comment method list is updated.
Consume ref defs during block close
src/md/blocks.rs
end_current_block now decides whether to consume reference definitions from paragraph or setext-heading blocks, and the consumer updates label normalization, first-wins insertion, line counting, and ref-def-only block marking.
Regression test for duplicate ref defs before setext heading
test/js/bun/md/md-edge-cases.test.ts
New regression coverage verifies duplicate labels, first-definition-wins behavior, and paragraph fallback when reference definitions exhaust the content before the setext underline.

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
Loading

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 src/md/blocks.rs and reference-definition parsing.


A header meets a hidden chain,
Old table gone, new flows remain,
Labels first, then lines are counted,
Setext edges are re-accounted,
Tests guard the path through text again.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly matches the main change: moving reference definitions into document order.
Description check ✅ Passed The description explains the bug, fix, and verification, covering both required template sections.

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

@robobun

robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 4:56 PM PT - Jul 4th, 2026

❌ @robobun, your commit 067b08e has 3 failures in Build #68372 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32291

That installs a local version of the PR into your bun-32291 executable, so you can run:

bun-32291 --bun

@claude claude 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.

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.

@robobun
robobun force-pushed the farm/d45eed8b/md-ref-def-setext-alloc branch from f1aa921 to ad38157 Compare July 4, 2026 19:42
@robobun

robobun commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Note

Superseded. This comment described the PR as it stood at ad38157, when it was an allocation-only change with no fail-before test. Since then the PR was rewritten around a CommonMark 4.7 bug fix (see the PR description and 0918e541): reference definitions from paragraph blocks are now collected in document order, build_ref_def_hashtable is deleted, and the reference definition precedence across block kinds suite fails on main. The text below is kept for history and no longer describes the diff.


Original comment

Rebased onto main (ad38157). The only conflict was in test/js/bun/md/md-edge-cases.test.ts, where main had appended a test to the same describe("pathological reference definition inputs") block; both tests are kept. src/md/blocks.rs merged cleanly and is unchanged from the original diff.

Local verification on the new base:

  • test/js/bun/md/md-edge-cases.test.ts 83 pass
  • test/js/bun/md/md-spec.test.ts 792 pass
  • test/js/bun/md/gfm-compat.test.ts 62 pass

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.

@claude claude 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.

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.

Comment thread src/md/blocks.rs Resolved
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.
@robobun
robobun force-pushed the farm/d45eed8b/md-ref-def-setext-alloc branch from ad38157 to 0918e54 Compare July 4, 2026 20:59
@robobun robobun changed the title md: only dupe ref-def dest/title when storing a new definition in the setext path md: collect paragraph reference definitions in document order Jul 4, 2026
@robobun

robobun commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

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 build_ref_def_hashtable after the document was parsed, so the pass that ran first claimed the label. What made the fix straightforward is that md4c's md_end_current_block already consumes ref defs from MD_BLOCK_P and setext MD_BLOCK_H alike. Splitting paragraphs into a post-pass is where the port diverged, so restoring parity also deletes the post-pass (-156 lines).

Two things your analysis didn't cover that turned up while implementing:

  • Routing paragraphs through consume_ref_defs_from_current_block meant a definition-only paragraph came out as BlockType::P with n_lines == 0 and no BLOCK_REF_DEF_ONLY, which process_all_blocks renders as an empty <p></p>. The flag now gets set where the lines are consumed, which also retires the setext arm that used to set it.
  • The early return Ok(()) that keeps a converted setext block open means a paragraph can reach end_current_block twice. It does not double-consume, because the only line left at that point is the underline and the guard tests for a leading [, but I probed it explicitly rather than relying on the reasoning.

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.

Comment thread src/md/blocks.rs Resolved
@robobun

robobun commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Warning

Superseded and partly wrong. The claim below that tls-syscall-fault is a deterministic, pre-existing break on main does not hold: it was based on a debug-ASAN reproduction, while the red lane is release-ASAN. On the release-asan profile the test passes on both main and this branch, so it is a flaky test, not a main bug, and #33326 is not at fault. See the correction below this comment. Kept for history.


Original comment

CI on 0918e541 (build #68356)

None of the failures touch this diff, which is src/md/{blocks,parser,ref_defs}.rs plus one md test file. No markdown test appears in any annotation, on any lane, including linux-x64-asan.

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 threads
  • reference definition precedence across block kinds fails on main and 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.
@robobun

robobun commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Correction: my previous CI analysis was wrong

I said the tls-syscall-fault failure was a deterministic, pre-existing break on main caused by a string mismatch in the crash handler, and that a re-trigger could not clear it. That was wrong on all three counts, and it pointed at #33326 as the owner of a bug that does not exist. Apologies to whoever was about to go look.

The mistake was the experiment I ran. I reproduced on the debug-ASAN profile (bun bd) and concluded from it, but CI's failing lane is release-ASAN. Those take different paths through the crash handler, so a debug pass said nothing about the lane that was red.

Rebuilt both trees on the actual release-asan profile:

tree tls-syscall-fault.test.ts @ release-asan
main (08c5bc9) 11 pass, 0 fail
this branch (0918e54) 11 pass, 0 fail

It passes on main, and it passes here, on the same profile CI runs. The failure is load-dependent and does not reproduce on either tree, so it is a flaky test rather than a property of main or of this diff. What made me doubt myself first was the CI shape: of the 20 x64-asan shards on build #68356, 19 passed and exactly one failed, and other unrelated PRs show the same 19/1 split on different tests.

For the record, main does not run the asan lane at all (55 jobs, none of them asan; PR builds get 287 including 20 asan shards), so flakes there surface only on PRs and never get caught on main. That is worth knowing independently of this PR.

I have pushed one ci: retrigger (067b08e) on the strength of that evidence. If the asan shard comes back red on the same test, the flake is worth a real issue rather than another re-roll from me.

Nothing about the diff itself has changed: src/md/ only, and no markdown test appears in any annotation on any lane.

@robobun

robobun commented Jul 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: the diff is green, CI is flaky across unrelated lanes

Build #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 0918e541. So these two builds compiled exactly the same source:

build hard failures
#68356 (0918e541) js/node/tls/tls-syscall-fault
#68372 (067b08e, same tree) cli/init, integration/next-pages/dev-server, cli/install/test-dev-peer-dependency-priority, plus darwin 26 aarch64 infra

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:

  • all 20 x64-asan shards passed. tls-syscall-fault is gone, confirming it was a flaky test and not the main regression I wrongly reported two comments up.
  • darwin 26 aarch64 - test-bun failed and then timed out without running a single test: buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun'.
  • the three error annotations are in bun init, a Next.js dev-server integration test, and a peer-dependency resolution test. None of them parse markdown. (init.test.ts reads and writes files named README.md/CLAUDE.md, but never calls Bun.markdown; it also notes that whether bun init emits CLAUDE.md depends on a claude binary being on PATH, which is environment-dependent by construction.)
  • ten further warning-style retried flakes across bake, http, net, install and webview.

No markdown test appears in any annotation, in either build. test/cli/run/markdown-entrypoint.test.ts, the one CI test that exercises Bun.markdown, passed in both. This diff is src/md/{blocks,parser,ref_defs}.rs plus one md test file.

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 up

A CommonMark 4.7 fix. A 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; the spec says the first definition in document order wins. Setext definitions were collected as blocks closed, paragraph definitions in a pass that ran after the whole document was parsed, and both enforce first-wins against the same label set, so whichever pass ran first claimed the label. end_current_block now takes definitions from paragraphs too, which is what md4c's md_end_current_block already did, and the post-pass is deleted.

Verification: 792 CommonMark spec tests, plus gfm-compat, md-react, md-render-callback, md-heading-ids and markdown-entrypoint, all green. A 4000-document differential fuzz against the unfixed build shows zero output differences; a targeted 54-case corpus shows 18, every one the intended class. The reference definition precedence across block kinds suite fails on main and passes here.

Ready for review.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@robobun robobun closed this Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant