Skip to content

refactor(layout): place elements through one loop and report heading placements - #644

Merged
Tim81 merged 10 commits into
mainfrom
feat/layout-position-map
Nov 21, 2026
Merged

Tim81 merged 10 commits into
mainfrom
feat/layout-position-map

Conversation

@Tim81

@Tim81 Tim81 commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Closes #288

What changed

The page-counting pass and the drawing pass were two copies of the same branching (CountPlaceRenderer, PlaceRenderer). One routine, PlaceRenderer, now runs both. The too-tall refusal, the 50,000-continuation cap and every later placement rule are written once. Each pass keeps its own side effects at the points it had them: the drawing pass commits the open page before a too-tall or cap throw, the counting pass creates no page and starts at one page.

Internal only, no PublicAPI change, no output change.

  • IPlacementSource (internal, implemented explicitly): a renderer reports a key and a box. The loop calls it on the renderer whose result it accepted (Full the renderer, Partial its split piece), in both passes, before the cursor moves. Only HeadingRenderer reports; the key is the Heading, the y is the one its outline entry uses.
  • Reports are collected only when something reads them: a plan-dependent renderer is present, or a test sets RecordPlacements. Without either, nothing is collected. Measured warm, 1,000 headings saved through Document.Save allocate 128 bytes more than on main without a band and 528 bytes more with a footer. That is under one byte per heading, so it is not an allocation per heading; other document sizes were not measured.
  • Page index is 0-based from this layout's first page and counted by the loop, not from _pdf.Pages.Count.
  • PaginationPlan (target to page and y, page count, LabelOf) and IPlanDependent (Resolve(plan), plus TargetName and ResolvedText for the refusal message).
  • Measuring loop: with a dependent, run 1 resolves against a placeholder (every target on page 0), later runs against the run before, at least two runs, then the draw. MaxMeasureRuns = 5. Past it the save throws InvalidOperationException naming up to three unstable targets and their strings per run, or the page counts when no dependent changed in the last run. The throw comes after the layout started, so a Document that raised it cannot be saved again.
  • The determinism guard (the drawing pass compared with the last measuring run) runs only when a dependent exists, so a custom renderer that answers differently per call is still saved as before.
  • Counters read by tests: MeasureRuns, LayoutCalls, ParagraphRenderer.WrapCalls. Document.CreateRenderer is now internal so a test can read the plans of a generated document.
  • Removed DocumentRenderer.PendingBookmarks and BookmarkEntry. git grep over src tests docs README.md finds no other use and no AddBookmark.

No public renderer is a dependent, so no existing document reaches the five-run cap or the guard.

Merge with the diagnostics channel (#642)

The two changes touched the same loop, so the merge is part of this review.

Hunk Resolution
_sink in DocumentRenderer The diagnostics sink keeps _sink; the placement collector is _placements.
Diagnostics location (element kind, index) Set inside the loop's drawing pass only, per top-level renderer, where the old drawing loop set it, then reset to the document before the last page is finished. The measuring pass does not touch the sink.
Band truncation reports ReportBandTruncations() runs after the drawing pass, as before.
ParagraphRenderer.Layout Keeps the out parameter of WordWrap and its field, and counts a wrap only when one is made, so a paragraph still wraps once with a footer.
CHANGELOG.md Main's lines are unchanged byte for byte (git diff origin/main -- CHANGELOG.md has no removed line); this entry sits after main's entries under Changed.

A test (MeasuringRunsReportNoDiagnostics_soACutFooterIsReportedOnce) pins that a cut footer is reported once, with a count of one, whether or not a dependent forces three measuring runs.

Commits

Pins recorded on the base, the loop, tests for the new internals, review fixes, the merge of main, and a diagnostics test. git log origin/main.. lists them.

Evidence

Heads: before the merge e3a55cd, after it the head of this branch. Both assemblies were printed with different md5s in every probe and runner run.

Pins recorded on base, unchanged on head (net10.0 and net11.0). Normalised bytes and a hash of the order and areas of every Layout call for: plain, footer, header and footer with {pages}, a caller-owned PdfDocument with an existing page and a footer, a custom renderer that answers differently per call with a band. Too-tall and cap messages and the pages left in the caller's PdfDocument after a caught Render, in each pass.

PDF/A-2u pin and the operating system. The document is saved on a Windows machine and a Linux CI runner, and the embedded font's ToUnicode map has CR LF line ends on Windows (#630). The pin hashes with CR LF folded to LF inside every Flate stream whose inflated text contains begincmap, which in this document is the one ToUnicode stream; the fold does nothing once #647 merges. Proof: CI on Linux printed FBA23BB8...E21A for the previous document; the same previous document, hashed here on Windows with the fold, prints the same 64 digits. The new pin (DD46E610...) was recorded on the base commit and holds on head, on both target frameworks. The document's second heading now really splits: pdftotext -layout shows it across pages 1 and 2.

Measured pages against drawn pages. GeneratedDocuments_measureTheSamePagesAndPlacementsAsTheyDraw lays out 200 seeded documents from the existing generator (built-in elements, a footer on every one, a heading at the end) and asserts equal page counts and equal placements; refusals are counted, and more than half must lay out.

Differential runner (net10.0), base = main with #642, head = this branch.

Run Rows Difference after dropping # lines and the commit in paths
seed 1, 400 fuzz, all jobs 28,630 verdict rows 3 rows, none from this change: two cancellation timing scans and one encrypted file whose hash changes between runs; verdicts otherwise equal row for row; 20 violations on both sides
seed 2, 1,500 fuzz 1,500 none

The fuzz row that earlier differed from 2.3.3 is a heading split over two pages whose outline destination is now at the heading top (/XYZ 0 841.89 becomes /XYZ 0 769.89); the CHANGELOG entry for #464 declares it, and the comparison against 2.3.3 now treats it as deliberate.

Probe, base against head (public API, 27 rows, 2.3.3 is not compared again because main moved). Equal on all rows: call count and order, a renderer that answers differently per call with and without a band, too-tall and cap in each pass (message, pages left, unfinished pages, saving the caller's PdfDocument afterwards), a NaN draw followed by a too-tall element, layout-validation refusals first and later, an existing page with a footer, the retry rows, and three rows that print Document.Diagnostics in order (a cut footer with unencodable characters, headings with unencodable characters).

Cost (GC.GetAllocatedBytesForCurrentThread, warm, from the probe; bytes):

base head
1,000 paragraphs, no band 12,066,864 12,066,904
1,000 paragraphs, footer 12,285,712 12,285,792
1,000 headings via Document.Save, no band 4,266,328 4,266,456
1,000 headings via Document.Save, footer 4,436,248 4,436,416

Layout calls on 1,000 paragraphs: 1,076 without a band, 2,116 with a footer, on both. Measuring runs: 0 without a band, 1 with a footer. A review measured +1.57% (no band) and +3.06% (footer) for 1,000 headings before reports were made conditional; the table above is after. Table allocation with a footer is about twice that without in both builds (1.96 measured by a reviewer without a logging wrapper, 2.00 by the probe's table render); table cost belongs to #517.

Mutations (each run in a detached worktree, restored afterwards; full Layout suite for the three re-run this round)

Mutation Failing tests
report only in the drawing pass 7 (heading plan with a band, measure vs draw plan, plan indices with existing pages, qpdf outlines, settling dependent, both oscillation tests)
dependents resolved only in run 1 4
test dependent keeps its stale cache 2
cap one run fewer / one more 1 each
no measuring runs when a dependent exists 6
a Nothing retry reported as a placement 2
no FinishCurrentPage before the drawing-pass too-tall throw 2 (the open-page test and PaginationDepthTests.PlaceRenderer_tooTallElement_throwsInvalidOperation)
guard runs without a dependent 1
HasStartedLayout set after the measuring runs 3 (retry after a measuring failure, oscillation through Document, SaveLifecycleTests.TooTallElementWithAHeader_isRefusedByTheCountingPass_andTheRetryIsRefusedToo)
page index from _pdf.Pages.Count 10
reported y plus 1 4
guard ignores the page index 1
counters not reset at the start of RunLayout 1 (LayoutCallsAndMeasureRuns_startOverOnEveryRunLayout, which now lays out twice)

Review round (two reviews of e3a55cd and CI)

Finding Resolution
CI: PDF/A-2u pin differs on Linux Fold CR LF in the CMap stream only; proof above.
Measured against drawn pages had no test Added, above.
"split heading" was not split Fixed and confirmed with pdftotext -layout; pin re-recorded on base.
Private labels in code and this text Removed. The comment says what the rule is.
Counter reset not pinned Test lays out twice; mutation above.
Reports cost allocation with no reader Collected only when a dependent or a test needs them.
Tests and comments named the removed counting method Renamed; the stack-depth probe counts the one loop.
Empty target list in the refusal message Names the page counts.
"the passes alternate" "keep changing it".
"cannot be saved again" untrue through DocumentRenderer The messages say the renderers have measured and to lay the content out again with a new Document; the Document test still sees its own message on a second save.
"naming up to three" had no test Four dependents name three, a settled dependent beside a moving one is not named, the page-count cause is named.
Table ratio did not reproduce Both figures and their harnesses are above.
Wording of the plan summary, Placement.Y, the guard message Made true.
Mutation counts understated Corrected above.

Gates

Release solution build 0 warnings; the full Layout suite in Release on net10.0 and net11.0 (1,199 tests, 0 failed, 2 skipped: the named-pipe tests, which skip on Windows) and in Debug on net10.0, with oracles required (REQUIRE_ORACLES, REQUIRE_VERAPDF: veraPDF 1.30.4 2u, qpdf 12.4.2 --check and --json, pdftotext -layout); the diagnostics tests (65) run on both frameworks; dotnet format --verify-no-changes, clean-room check and generate-roadmap.py --check exit 0.

Not done

  • Native AOT smoke not run locally; CI ran it on three operating systems and all three jobs passed on the current head.
  • Tables, lists and images do not report yet; anchors need that and come with the work that adds them.
  • Dependents are found among the renderers added to the document, not inside a renderer.
  • The PDF/A-2u pin was not run on Linux; the equivalence is argued from the identical hash above.

…e merging the passes (#288)

Records the normalised bytes, the order and areas of every Layout call, the pages a caller-owned PdfDocument holds after a caught too-tall or cap exception, and the call counts of a 1,000 paragraph and a 1,000 row document, on the commit before the placement loop changes. Each value was recorded on the base commit, on net10.0 and net11.0.
…placements (#288)

The counting pass and the drawing pass were two copies of the same branching. One routine now runs both, so the too-tall refusal, the continuation cap and later placement rules exist once; each pass keeps its own side effects at the points it had them.

Headings report where they landed from the loop, in both passes, into a plan that dependent renderers resolve against over at most five counting runs. No public renderer is such a dependent yet, so no existing document is affected. Removes PendingBookmarks and BookmarkEntry, which nothing used.
…ring cap (#288)

Headings plan against the outline destinations the drawing pass writes, in both passes and with a split heading; counters pin the layout calls and measuring runs; a test dependent pins convergence, the five-run refusal and the determinism guard; retries through Document; qpdf and pdftotext check the file.
…ge is committed (#288)

A heading that answers Nothing is planned where the retry placed it, and a too-tall refusal in the drawing pass leaves every page finished.
…er review (#288)

Makes the PDF/A-2u pin independent of the operating system by folding CR LF to LF inside ToUnicode streams only (#630), and makes its second heading really split across two pages. Adds a seeded generated-document check that measured and drawn pages agree, the counter reset check, the four-dependents and settled-beside-moving cases, and the page-count cause. Reports are collected only when a dependent or a test reads them. The refusal messages no longer say the passes alternate or that a DocumentRenderer cannot be saved again, and the stack-depth tests name the single loop.
The placement collector is now _placements, beside the diagnostics sink _sink. The diagnostics location is set inside the loop's drawing pass only, and the band truncation reports follow that pass, as in the loop this branch replaced; the measuring pass reports nothing. ParagraphRenderer keeps the nullStyleRuns out parameter and counts successful wraps.
A cut footer is reported once with a dependent that forces three measuring runs, as with one run.
The measuring-pass comments said reports come from the drawing pass only when only diagnostics do, and described a check as future work while the code below it already walks the elements. The two refusal messages assumed a Document, which a direct renderer caller does not have. Comment lines added by #288 are rewrapped to 100 columns.
@Tim81
Tim81 merged commit 0a3be08 into main Nov 21, 2026
4 checks passed
@Tim81
Tim81 deleted the feat/layout-position-map 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

Development

Successfully merging this pull request may close these issues.

Layout: pass 1 counts pages but records no positions

1 participant