Skip to content

fix(layout): loop instead of recursing, so deep documents render - #461

Merged
Tim81 merged 2 commits into
mainfrom
fix/layout-pagination-recursion
Sep 10, 2026
Merged

Tim81 merged 2 commits into
mainfrom
fix/layout-pagination-recursion

Conversation

@Tim81

@Tim81 Tim81 commented Sep 9, 2026 •

Copy link
Copy Markdown
Owner

DocumentRenderer recursed once per page continuation, so a single element spanning more than about
4,250 pages exhausted the CLR stack and killed the process. A stack overflow cannot be caught, so a
caller had no way to turn it into a message.

Reported against the shipped VellumPdf.Layout 2.3.0 with measurements. The report found one of the
two recursive methods; the counting pass recurses the same way and runs first whenever a header or
footer is set, so a document with a running band crashes one pass earlier.

Evidence

Five reproductions, each run as its own process so an overflow yields a readable exit code. Case 5 is
the running-band variant the original report did not reach.

Exit codes are as Git Bash reports them; the underlying Windows status is 0xC00000FD.

Case Before After
1 — 36pt page, 100,000 characters exit 127 exit 0, 1,304 ms
2 — 200pt page, wide glyphs exit 127 exit 0, 1,242 ms
3 — 20,000 x 200pt page, 4,950 list entries exit 127, 4,356 PlaceRenderer frames exit 0, 345 ms
4 — element indent, zero page margins exit 127 exit 0, 419 ms
5 — case 3 with a footer exit 127, 4,181 CountPlaceRenderer frames exit 0, 384 ms

Cases 3 and 5 are the same document. The frame counts show the crash moving between the two methods
depending on whether a running band is set.

What changed

Both methods are loops. Every recursive call sat in tail position, so no local outlived it and every
value crossing a continuation already lived in a field; the number, order and arguments of the
Layout and Draw calls are unchanged. The Nothing branch still issues its three Layout calls
per turn, including the probe whose result is discarded.

Each element is bounded at 50,000 continuations. Document.Add(IRenderer) takes any implementation
and LayoutResult.Partial accepts any overflow renderer; one that never advances used to be stopped
by the stack running out, and without a bound it would page until memory ran out instead. The bound
is also a ceiling on how many pages one element may span, and the library's own renderers can reach
it: measured on a 420x400pt page laid out one row to a page, 50,001 rows render and 50,002 throw,
having made progress on every page. So the message names both causes. Under the default JIT nothing
For some callers the cap is a new limit. How deep the old recursion could go was never a property
of this library: it was the thread's stack size and whether the JIT emitted a tail call. On the
default stack with tiered compilation on it died below 4,000 continuations, which is where 50,000
was pitched, but the same document renders 50,002 pages on a 24MB thread under that same JIT, and
again on the default stack with DOTNET_TieredCompilation=0 or under Native AOT.

The counting pass also skipped an element too tall to fit while the drawing pass threw on it, so the
two disagreed about the same document. Both now throw the same message from one shared constant. One
visible consequence: with a running band the throw moves to the counting pass, which creates no page
objects, so a caller that catches it finds an empty PdfDocument rather than one holding the two
blank pages the drawing pass had already committed.

That half was split out of #312, which keeps the image fit modes it also asked for. Those need new
public API on LayoutImage and somewhere to report an automatic rescale, which #304 is the closest
existing candidate for.

No public API changes, so PublicAPI.Unshipped.txt is untouched.

Tests

PaginationDepthTests is new, at sixteen cases. Every test was checked against a faithfully
reintroduced defect, one mutation at a time in a throwaway worktree, with build success asserted
before each result was believed.

Mutation Test that fails
PlaceRenderer back to recursion PlaceRenderer_manyContinuations_stackDepthStaysFlat
CountPlaceRenderer back to recursion CountPlaceRenderer_manyContinuations_stackDepthStaysFlat
counting pass returns instead of throwing on a too-tall element CountPlaceRenderer_tooTallElement_throwsInvalidOperation
cap check removed from PlaceRenderer only PlaceRenderer_nonAdvancingOverflow_throwsAfterCap, by named timeout
cap raised to 500,000, or lowered to 5,000 both *_nonAdvancingOverflow_throwsAfterCap cases
pages++ removed from the counting pass's Nothing branch CountPlaceRenderer_nothingThenFitsOnFreshPage_pagesTokenMatchesActualCount
pages++ removed from the counting pass's Partial branch CountPlaceRenderer_splittingElement_pagesTokenMatchesActualCount
cursor reset removed from that same branch CountPlaceRenderer_splittingElement_pagesTokenMatchesActualCount
counting pass skipped for header-only documents PlaceRenderer_headerOnlyDocument_resolvesPagesToken
last page left unfinished before the too-tall throw PlaceRenderer_tooTallElement_throwsInvalidOperation
last page left unfinished before the cap throw PlaceRenderer_nonAdvancingOverflowViaNothingBranch_finishesLastPageBeforeCapThrows
cap boundary fenceposted, > to >= both *_continuationCap_boundaryIsExact
Partial draws the element instead of its split part PlaceRenderer_partialResult_drawsSplitRendererNotTheOriginal

Five review rounds ran, each on three disjoint lenses, and each found real defects in the previous
round's fixes. Round one found four tests that did not discriminate. Round two found four more gaps.
Rounds three to five found no defect in the loops themselves and a series of false claims in the
comments about them, each of which is now either measured or replaced by a statement of the
configuration actually tested. The
too-tall test asserted only the exception message, which both passes share by design, so restoring
the defect still produced the same text from the other pass. The cap assertion used a substring, so
"500000" still contained "50000". PlaceRenderer's cap had no test at all, which is the
unguarded path for the common case since a document without a running band never runs the counting
pass. And removing the cap hung the suite rather than failing it, now bounded by a 10-second timeout
that was verified to fire rather than assumed to.

The two stack-depth tests count pagination frames on the stack at each Layout call and assert
exactly one, so a recursion regression fails as a named test rather than by killing the host. The
ten-thousand-page render is the end-to-end guard; under the counting-pass mutation it dies at exit
127 with 2,680 frames, which is why it is not relied on as the detector.

DocumentRenderer_tooTallElement_throwsInvalidOperation is deleted from LayoutFixTests. It was
named for a throw it never asserted, as its own comment conceded, and its paragraph paginated fine
without reaching the throw.

Also here

CI triggered only on main and v1.7-conformance. Every patch tag so far, v1.5.1 through v1.8.2,
was an ancestor of main and collected its CI as an ordinary push, which hid the gap. A patch cut
from an older tag never touches main, and release.yml fires on any v* tag and pushes to NuGet
after a restore, a build and a pack, running none of the gates in ci.yml: not the clean-room
check, the vulnerable-package scan, the pinned-oracle and invocation-floor asserts, the tests, the
coverage threshold, the format check or the AOT smoke. GitHub reads the workflow from the branch
being pushed, so the trigger must also be cherry-picked onto a branch cut from an older tag, which
CONTRIBUTING now says alongside the exception to "target main".

Local gates

Build, full suite (6,825 tests, 0 failed, 319 skipped on the missing-oracle baseline), dotnet format --verify-no-changes, clean-room and the AOT smoke all pass.

This carries two logical changes against CONTRIBUTING's "one logical change per PR". The CI trigger
is here because 2.3.1 cannot be verified without it, and it has to be cherry-picked onto the release
branch either way; splitting it would not change that, so it is disclosed rather than separated.

Found while reviewing, filed rather than fixed here

#463 (an element sized exactly to the content area can paginate to the cap, because the loop's area
box is computed as Bottom - currentY while the retry probe passes ContentArea itself, and those
are not always bitwise equal. A pie chart compares heights with no epsilon, so a shipped renderer
reaches it; the issue carries two measured triggering documents. It is not a regression: both measured
cases died of an uncatchable stack overflow before this change, and the loop preserves the
arithmetic exactly, which is what makes the conversion equivalent. Fixing it means changing layout
arithmetic, so it wants its own review rather than a patch release.)

#464: a heading that splits across a page boundary registers its outline destination at the page top
rather than where it starts, because HeadingRenderer's split copy never receives _occupied. Also
pre-existing, and unrelated to pagination depth. It surfaced as the counterexample to a claim in
this PR that drawing the split half rather than the element is unobservable with built-in renderers.

Follow-up before the tag

All three entries sit under ## [Unreleased], which is what CONTRIBUTING requires. release.yml
extracts notes by exact ## [2.3.1] heading match, so the release branch needs that heading and its
link reference, and main needs the same rather than announcing these fixes again as 2.4.0 content.

Closes #459
Closes #460
Closes #462

DocumentRenderer recursed once per page continuation, in the pass that
counts pages as well as the pass that draws them. A single element
spanning more than about 4,250 pages exhausted the CLR stack, and a stack
overflow cannot be caught, so a caller had no way to turn it into a
message the way every other malformed-input failure here can be.

Measured on one 4,950-entry list, Release build: the drawing pass died at about
4,356 PlaceRenderer frames, and adding a footer moved the crash to about 4,181
CountPlaceRenderer frames, because a running band makes the counting pass run
first. A Debug build fails sooner, around 2,456 and 2,825, with the two passes
in the opposite order. The report that prompted this only found the drawing
pass.

Both are now loops. Every recursive call sat in tail position, so no local
outlived it and every value crossing a continuation already lived in a
field. The number, order and arguments of the Layout and Draw calls are
unchanged.

Bound each element at 50,000 continuations. Document.Add takes any
IRenderer, and one whose overflow never advances used to be stopped only
by the stack running out; with the recursion gone it would page until
memory ran out instead. The bound doubles as a per-element page ceiling
the library's own renderers can reach: 50,002 table rows laid out one to
a page throw, having made progress on every page. For some callers that is
a new limit. How deep the old recursion could go was never a property of
this library: it was the thread's stack size and whether the JIT emitted
a tail call. On the default stack with tiered compilation on it died
below 4,000 continuations, but the same document renders 50,002 pages on
a 24MB thread under that same JIT, and again on the default stack with
DOTNET_TieredCompilation=0 or under Native AOT.

Filed alongside: #463, an element sized exactly to the content area can
paginate to the cap, because the loop's area box and the retry probe's
differ by one ULP. Pre-existing and preserved exactly here, so fixing it
would break this patch's equivalence argument.

The counting pass also skipped an element too tall to fit while the
drawing pass threw on it, so the two disagreed about the same document.
Both now throw the same message, read from one constant. With a running
band the throw therefore moves to the counting pass, which creates no page
objects, so a caller that catches it finds an empty PdfDocument rather than
one holding two blank pages.

Closes #459
Closes #460
CI triggers only on main and v1.7-conformance. Every patch tag so far, v1.5.1
through v1.8.2, was an ancestor of main and collected its CI as an ordinary
push, which hid the gap. A patch cut from an older tag never touches main, and
release.yml fires on any v* tag and pushes to NuGet after a restore, a build and
a pack, running none of ci.yml's gates: not the clean-room check, the
vulnerable-package scan, the pinned-oracle and invocation-floor asserts, the
tests, the coverage threshold, the format check or the AOT smoke. A
published version is immutable.

GitHub reads the workflow from the branch being pushed, so the trigger has to be
cherry-picked onto any release branch cut from an earlier tag.

CONTRIBUTING said only "Target main" and described no path for a patch cut from
a tag; it now names the exception.

Closes #462
@Tim81
Tim81 force-pushed the fix/layout-pagination-recursion branch from 0022a41 to 12ce0e0 Compare September 10, 2026 07:01
@Tim81
Tim81 merged commit 68a4979 into main Sep 10, 2026
4 checks passed
@Tim81 Tim81 mentioned this pull request Nov 18, 2026
6 tasks done
@Tim81
Tim81 deleted the fix/layout-pagination-recursion branch November 21, 2026 06:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant