Skip to content

Fix FindClosestBlock/FindBlockAtPosition with definition groups (#677) - #962

Merged
xoofx merged 1 commit into
xoofx:mainfrom
ybai08:fix/find-closest-block-groups
Oct 19, 2026
Merged

xoofx merged 1 commit into
xoofx:mainfrom
ybai08:fix/find-closest-block-groups

Conversation

@ybai08

@ybai08 ybai08 commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #677

Problem

LinkReferenceDefinitionGroup and FootnoteGroup are added to the MarkdownDocument by the parsers with Line == 0 and a span starting at 0:

  • the LinkReferenceDefinitionGroup is inserted where the first [label]: url definition is parsed, i.e. in the middle of the document;
  • the FootnoteGroup is moved to the end of the document.

FindClosestBlock and FindBlockAtPosition binary-search the children of a container and assume they are ordered by line / position, so these groups break the search.

The exact repro in the issue (auto-identifiers only) no longer triggers on main, because AutoIdentifierExtension now registers its definitions with addGroup: false. The root cause is still there, though, whenever the document has a real link reference definition or a footnote. Output on main (ccb9d85):

"Para a\n\nPara b\n\n[foo]: /url\n\nPara c\n\nPara d\n\nPara e"
blocks: ParagraphBlock@0, ParagraphBlock@2, LinkReferenceDefinitionGroup@0, ParagraphBlock@6, ...
FindClosestBlock(0) -> LinkReferenceDefinitionGroup@0   (expected ParagraphBlock@0)
FindClosestBlock(2) -> LinkReferenceDefinition@4        (expected ParagraphBlock@2)

"Text[^1]\n\n[^1]: note\n\n- item1\n- item2"
FindClosestBlock(5) -> ParagraphBlock@2 (footnote content)   (expected ListItemBlock@5)

"Para a\n\nPara b\n\n[foo]: /url\n\nPara c\n\n[^1]: note\n\nPara d[^1]"
FindBlockAtPosition(0)  ('P' of "Para a") -> LinkReferenceDefinitionGroup
FindBlockAtPosition(32) ('a' of "Para c") -> LinkReferenceDefinitionGroup
FindBlockAtPosition(44) ('o' of "note")   -> MarkdownDocument

Fix

In BlockExtensions, the binary searches of FindClosestBlock and FindBlockAtPosition keep their existing shape. When the container is a MarkdownDocument and the probed child is a LinkReferenceDefinitionGroup or FootnoteGroup, the search compares the nearest child in the current [lower, upper] range that is not a group. If the range contains only groups, the search stops there. A document has at most one group of each kind, so the searches stay O(log N) and don't allocate. Nested containers never contain these groups, and their search is unchanged.

The definitions inside the groups are only used as a fallback:

  • FindClosestBlock returns a definition only on an exact line match. Otherwise it returns the closest block from the other children.
  • FindBlockAtPosition checks the group children only when no other child contains the position, for example when the position is inside [foo]: /url or inside a footnote's text.

The fallback finds the groups without scanning the document. The LinkReferenceDefinitionGroup comes from the document data through a new internal GetLinkReferenceDefinitionGroupOrNull() in LinkReferenceDefinitionExtensions, and it is used only when it is attached to the document (it is not attached when tracking trivia). The FootnoteGroup is document.LastChild, because FootnoteParser moves it to the end. The fallback walks the groups' children linearly, because they are not in line order: auto-identifier heading definitions are appended with line 0, and footnotes are sorted by reference order. If a document contains only groups, FindClosestBlock searches them as regular children, as before.

This follows the direction suggested in the issue (special-casing LinkReferenceDefinitionGroup in FindClosestBlock). Handling only the last block isn't enough: the link reference group can sit in the middle of the document, and FootnoteGroup and FindBlockAtPosition have the same problem.

No public API is added, and the parsers, the groups' Line/Span and the renderers are unchanged.

Tests

New tests in src/Markdig.Tests/TestPragmaLines.cs, next to the existing FindClosestLine tests:

  • TestFindClosestWithLinkReferenceDefinition
  • TestFindClosestWithFootnotes
  • TestFindBlockAtPositionWithLinkReferenceDefinitionAndFootnotes

All three fail on main:

Failed TestFindBlockAtPositionWithLinkReferenceDefinitionAndFootnotes
  Expected: instance of <Markdig.Syntax.ParagraphBlock>
  But was:  <Markdig.Syntax.LinkReferenceDefinitionGroup>
Failed TestFindClosestWithFootnotes
  Expected: 5
  But was:  2
Failed TestFindClosestWithLinkReferenceDefinition
  Expected: 2
  But was:  4

All three pass with the fix.

What was run locally (macOS arm64, .NET SDK 10.0.401, .NET 8.0.31 runtime):

  • cd src && dotnet build markdig.slnx -c Release: 0 warnings, 0 errors (net462, netstandard2.0, netstandard2.1, net8.0, net10.0)
  • dotnet test Markdig.Tests -c Release -f net10.0: 7345 passed, 1 skipped (main: 7342 passed, 1 skipped)
  • dotnet test Markdig.Tests -f net8.0 (with RunConfiguration.DotNetHostPath pointing at a host that has the .NET 8 runtime): 7345 passed, 1 skipped
  • the Test netstandard workflow steps, run locally for netstandard2.0 and netstandard2.1 in Debug and Release with -p:MarkdigNoRuneTests=true: 7282 passed, 1 skipped on net8.0 and net10.0

Not run: the dotnet-releaser CI action (pack/publish) and the net462 test path (the tests do not target net462).

@MihaZupan

Copy link
Copy Markdown
Collaborator

This is turning log(N) searches into very expensive N allocations + N scans, I don't think it's an acceptable approach for a fix in this case - have you looked at any alternatives?

…x#677)

LinkReferenceDefinitionGroup and FootnoteGroup are added to the document
by the parsers with Line 0 and a span starting at 0, at a position that
does not follow the source order (the footnote group is even moved to
the end of the document). The binary searches in FindClosestBlock and
FindBlockAtPosition expect children ordered by line/position, so they
could return the group, a definition, or the document itself instead
of the block at the requested line/position.

When a binary search on a document probes one of these groups, compare
the nearest other block within the search range instead, so the search
stays logarithmic and does not allocate. The definitions collected by
the groups are only considered when nothing else matches; the groups
are then taken from the document data (link reference definitions) and
from the last child of the document (footnotes) instead of scanning the
document.
@ybai08
ybai08 force-pushed the fix/find-closest-block-groups branch from f65bf9c to 98ed892 Compare October 17, 2026 15:49
@ybai08

ybai08 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

You're right, that approach cost far too much. I've reworked it and pushed it as a single commit again:

  • The binary searches still work as before. On a MarkdownDocument, if the probed child is a LinkReferenceDefinitionGroup or FootnoteGroup, the search compares against the nearest child in the current [lower, upper] range that isn't a group. A document has at most one group of each kind, so this is still O(log N), with at most a couple of extra steps and no allocations. Nested containers aren't affected.
  • The definitions inside the groups are still only used as a fallback: on an exact line match in FindClosestBlock, and in FindBlockAtPosition only when no ordered child contains the position. Finding the groups is O(1) and doesn't scan the document. The link reference group comes from the document data, through a new internal GetLinkReferenceDefinitionGroupOrNull next to the existing private key. The footnote group is document.LastChild, because FootnoteParser moves it there. Only this fallback walks the groups' children, and it does so linearly. Their children aren't in line order: auto-identifier heading definitions are appended with line 0, and footnotes are sorted by reference order.

Numbers come from a quick local loop using Stopwatch and GC.GetAllocatedBytesForCurrentThread, not BenchmarkDotNet. Setup: net10.0, DOTNET_TieredCompilation=0, 200k calls per row. The test document has 1002 top-level blocks and 210 definitions in the two groups. Note that main returns wrong blocks on this document.

main previous version of this PR now
FindClosestBlock, line of a paragraph 12 ns, 0 B 10.2 µs, 8160 B 18 ns, 0 B
FindClosestBlock, blank line (goes through the fallback) 18 ns, 0 B 11.0 µs, 8160 B 1.08 µs, 0 B
FindBlockAtPosition, inside a paragraph 15 ns, 0 B 10.1 µs, 8160 B 21 ns, 0 B

On the same document without any definitions, main takes 11 / 18 / 14 ns and this version takes 15 / 29 / 17 ns, with 0 B in every case.

The ~1 µs blank-line case is the linear walk over the 210 definitions. If you'd rather not pay that on a miss, FindClosestBlock could stop returning definitions. The new tests would then need to drop the LinkReferenceDefinition/footnote-line assertions.

I also compared this version against the previous one on 3000 generated documents, about 520k FindClosestBlock/FindBlockAtPosition calls in total. The results were identical except in two cases:

  • Documents that contain only groups. Here a definition or the document is now returned instead of the group itself.
  • Trivia-mode documents where two siblings share the same line. Each version returns one of the two, and both are equally valid.

@xoofx

xoofx commented Oct 19, 2026

Copy link
Copy Markdown
Owner

Thanks @ybai08 for the thorough write-up and fix! 🙏

Besides the new tests, I ran a randomized check: 5000 generated documents mixing paragraphs, link reference definitions, footnotes, lists, quotes and headings. For every line, FindClosestBlock must return a block on that exact line when one exists, and for every position, FindBlockAtPosition must return the block containing it and never a group. On main this check had ~144k failures, and with your PR it has 0. Documents made only of definitions behave as before, as described. The binary search stays O(log N), and the linear fallbacks only run on a miss, so there is no perf concern for these editor-facing APIs. Merging.

Review done via CodeAlta / Opus 5.5.

@xoofx
xoofx merged commit 6a41039 into xoofx:main Oct 19, 2026
3 checks passed
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.

FindClosestBlock incorrectly returns LinkReferenceDefinitionGroup

3 participants