Skip to content

feat(layout): one diagnostics channel and an opt-in strict mode (#607) - #642

Merged
Tim81 merged 11 commits into
mainfrom
feat/layout-diagnostics
Nov 20, 2026
Merged

Tim81 merged 11 commits into
mainfrom
feat/layout-diagnostics

Conversation

@Tim81

@Tim81 Tim81 commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Closes #607

What changed

Document gains one diagnostics channel and an opt-in strict switch, in VellumPdf.Layout only.

  • Document.Diagnostics lists LayoutDiagnostic items (Code, Severity, Message, Clause,
    ElementKind, ElementIndex, PageNumber, Count), one per code and subject, replaced by each
    save that succeeds. It is a read-only view. A strict refusal also fills it, because that layout is
    the document's only one.
  • This PR reports NullTextRunStyle (101), UnencodableCharacter (103, mirrors
    TextEncodingWarnings), NullGrandchildText (201), NullGrandchild (202), BandTruncated (401,
    mirrors BandTruncations, severity Error) and the sentinel DiagnosticsDropped (901, Warning).
    The enum comment reserves 102, 104, 105, 203-206, 301, 302, 402, 601, one 7xx and the 8xx block.
    LayoutElementKind and the code enum have explicit values and say not to switch exhaustively, so
    Preformatted and later codes append.
  • The channel stores at most 1,000 distinct items, then DiagnosticsDropped when it dropped any, whose
    Count is the number of occurrences dropped. A repeat of a stored item adds to its count and, on the
    encoding path, allocates nothing.
  • Document.StrictDiagnostics (default false) refuses a save that would report an error item, with
    InvalidOperationException, after the layout and before anything is written, from every save
    overload and from signing. The check is one private method called inside the try of both layout
    helpers, so the failure marks the document as failed and the two SaveAsync overloads are covered.
  • TextEncodingWarnings and BandTruncations keep their content and order. The two "not an error"
    sentences about band truncation are rewritten.
  • The list walk below the second level uses an explicit stack and one visited set per save
    (ListWalkState, owned by the diagnostics sink). Each list item below the first level is visited at
    most once per save, so the work is linear in the items and child links the caller built.
    A.AddChild(A) and a graph with 2^40 paths save and terminate. The walk runs when a list is drawn,
    and only for a list the document draws from its first item, so a list that starts at a later item, or
    that a caller's renderer measures and does not draw, leaves its items for the list that reports. A
    null text or null child is counted once in the save, under the first such list in drawing order, so
    the total does not depend on their order.
  • Library-written text (a list marker) is not listed as an unencodable character when the document
    draws the list.
  • The "no diagnostics channel" sentences this PR fulfils (TextRun, ListItem) now name the codes.
    Two Kernel sentences that promised a report now state current behaviour only.

No default output changes, and nothing that saved on 2.3.3 starts throwing unless a caller sets the
new switch.

Evidence

Default bytes, whole file. A document with a null-style run, U+26B9, a level-3 null text and a cut
footer, saved with the switch off and a pinned timestamp and id, hashes to
8C5E33CA07812BF9C03B8974108D011FF136A6EB9AF019AD9DF981D43FD7D988 over the whole file on this branch
(net10.0 and net11.0) and on 2027421 (assembly 2.3.3+2027421a3be1574b9b0cfaab235d7840f23c93e5). The
test pins it.

Font probe, base against head (PDF/A-2u document with embedded DejaVu, pinned timestamp and id):

Row 2027421 head
G1 PdfA2u, DejaVu on every element 82,181 bytes, E317A2C267FE05C9 82,181 bytes, E317A2C267FE05C9
G2 no conformance, default Helvetica 1,627 bytes, A21068F44E914D0B 1,627 bytes, A21068F44E914D0B
G3 PdfA2u, default font DejaVu, list and table 82,256 bytes, 370B0E4ED284DE29 82,256 bytes, 370B0E4ED284DE29
D, Helvetica, n = 1,000 / 10,000 / 100,000 U+26B9 TextEncodingWarnings 1,000 / 10,000 / 100,000 same

The Standard 14 allocation for 100,000 characters is 44,339,864 bytes on 2027421 and 44,341,680 on head.

Cost of the walk. Timings of one save with strict off, measured at 65d09f6 (where the walk still
ran at layout time; it has since moved to draw time and was not re-timed, and the tests pin its work),
for the five shapes the third review measured (a list's chain below its second level has 100,000 items):

Shape Time Allocated
one list added 1,000 times 197 ms 19 MB
200 lists, each its own top item, one shared chain 34 ms 12 MB
one list, 400 second-level items reaching one chain 35 ms 11 MB
one list, 10,000 chained second-level items 283 ms 47 MB
200 lists, each its own second-level item, one shared chain 35 ms 11 MB

The tests pin the work, not the time: NodesVisited equals the distinct item count for each shape at two
sizes.

Review findings and what became of them

Early review of the first commit: H1 (test compile break) applied; M1 to M11 applied; the cheap LOWs
applied. For M5, marker substitutions are not mirrored, so a Standard 14 nested bullet does not trip
strict mode.

First review round (c6dd496):

Finding Status
H1 the walk repeated per list (25 s and 10 GB for one list added 1,000 times) Applied first as a per-save memo keyed on the second-level item; replaced in the third round (below)
M1 marker listed through a context the caller built Applied: documented on Document, LayoutDiagnosticCode, ListItem.Children and the CHANGELOG; the rule for UnencodableCharacter is stated once
M2 cancellation under strict Applied: both SaveAsync cancellation tags and the strict ordering list; a test for strict on and off
M3 missing <exception> tags Applied on TextRun (type and Style), ListItem constructor and both AddChild, and TextStyle.FontRef
L1 startItem >= 1 reports nothing Documented on both list codes
L2 read-only view Applied (AsReadOnly); test
L4 strict message counts stored items only Documented

Second review round (tests and prose):

Finding Status
Mutants 1 to 4 survived (marker pre-sync, per-element keying, constant band subject, further-errors count) Applied: four tests; each mutant now fails one (table below)
Default-bytes test hashed stream bodies only Applied: whole file, with the base value shown above
Prose M1 to M5 (TextEncodingWarnings sentence, "further", order, comment, "Standard 14") Applied: one rule for what Diagnostics lists, its order stated, the stale comment fixed
Prose M6 Kernel PdfDocument and Jbig2ImageLoader promises Applied: reworded to current behaviour
Prose M7 private wording in the PR body Applied
Prose M8 font probe claim Applied: the probe was run at base and head (table above)
LOWs: Sign tag, Save tag for dropped errors, "1,000 items" against 1,001, ? wording for a non-BMP character, broken rewraps, over-long comment lines, a test that could not fail, the CHANGELOG bullet Applied

Third review round (961fa3d, the branch after merging main):

Finding Status
H1 the memo still costs one subtree walk per distinct second-level item (22.7 s and 3.8 GB for 400 of them; quadratic for chained ones) Applied: one visited set per save over every item below the first level; the five shapes are pinned by NodesVisited and timed above
M1 the four linear-cost sentences Applied: ListItem.Children, the CHANGELOG Attention, the DocumentRenderer comment and this body state the new rule
M2 TextStyle.FontRef "each such character" Applied: "in your text", pointing to UnencodableCharacter for what it leaves out
M3 every copy of the counting rule Applied: NullGrandchild, NullGrandchildText, the walk's remarks, the ListRenderer comment and the CHANGELOG
LOWs: "drawing order"; the Jbig2 line; gate table; public Timestamp and DocumentId in the pinned-hash test Applied

Fourth review round (65d09f6):

Finding Status
M a list that never reports used up the document-wide set (a list started at a later item, or measured and not drawn, made a later list report nothing, and strict saved) Applied: the walk moved from layout to draw and runs only for a list that reports; two tests (a start-item list before a normal one, with strict on and off, and a list measured through the document's context and not drawn)
L1 "linear in the distinct items" omits child links Applied: "items and child links" in ListItem, ListWalkState, the CHANGELOG and this body
L2 field comment about the walk Applied: the field and its comment are gone with the layout-time walk
L3 the differential note about the baseline Applied
The counting-rule sentences the fix falsified Applied in NullGrandchildText, ListWalkState, the CHANGELOG and this body. ListItem.Children still lacked the "drawn from its first item" condition; it is added in the fifth round (below)

Fifth review round (58e538b), prose only:

Finding Status
M ListItem.Children said a null below the first level is reported and strict refuses, without the "drawn from its first item" condition (a list started at a later item saves with no report) Applied: the condition, and what happens otherwise, are in ListItem.Children; the earlier table row is corrected
L1 "carried to every piece of a split paragraph and list" Applied: narrowed to the paragraph
L2 NullGrandchild remarks named only the start-item case Applied: the list measured and not drawn, and that its items are left for a list that reports
L3 ListWalkState summary Applied: "every list that reports"
L4 the merge commit and the cost-table commit Applied: 39e5fe0 (#637) named, and 65d09f6 named for the timings

Mutation proofs

Each mutant was applied to the committed head, the test project rebuilt, and LayoutDiagnosticsTests
run, then the source restored.

# Mutant Failing tests
1 dedupe off HundredThousandOccurrences_areOneItemWithTheirCount (both cases), TextEncodingWarnings_keepOneEntryPerSubstitutedCharacter
2 strict check removed from LayOut (kept in LayOutThen) Strict_saveAsync_stream_throwsTheExactMessageAndWritesNothing, Strict_saveAsyncPath_leavesAnExistingFileUntouched_andCreatesNothingAtANewPath
3 null-style finding reported from Layout on every call ANullStyleParagraph_withAFooter_isStillCountedOnce and the tests that read the item's location
4 the _startLine == 0 guard removed ANullStyleParagraphThatSplitsOverTwoPages_isCountedOnce
5 cap raised to 1,000,000 ThousandAndOneDistinctSubjects_storeAThousandAndASentinelCountingTheRest, ADroppedSubjectThatRepeats_countsEveryDroppedReport, Strict_whenEveryDroppedReportWasAnError_saysSoWithTheirCount
6 element kind taken from the renderer being laid out HeadingContinuation_isReportedAsAHeading_notAsTheParagraphItOverflowsInto
7 each second-level item walks its own subtree (the per-item memo's behaviour) TheWalk_visitsEachDistinctItemOnce_andCountsTheNullOnce for holders-share-chain, holders-chained and lists-own-holder-share-chain, TwoSecondLevelItemsReachingOneNullTextItem_countItOnceUnderTheFirstList, TheTotalDoesNotDependOnTheOrderOfTheLists (9 in all)
7b a fresh visited set for each list the same theory for every shape, OneListAddedManyTimes_walksItsChainOnce, the two-second-level-items test and the order test (15 in all)
8 the marker pre-sync removed CallerTextInAListItemThatIsNotTheLast_isReported
9 UnencodableCharacter keyed per element TheSameCharacterInTwoElements_isOneItemWithBothOccurrences
10 BandTruncated subject constant ACutHeaderAndACutFooter_areTwoItems
11 the further-errors count includes warnings TheStrictMessage_countsOnlyTheStoredErrorItems, Strict_whenEveryDroppedReportWasAnError_saysSoWithTheirCount
12 the walk taken at layout time, as in 65d09f6 AListStartingAtALaterItem_leavesItsNullsForTheListThatReports (both cases), AListMeasuredAndNeverDrawn_leavesItsNullsForTheListThatIsDrawn

Rows 7 and 7b were re-run on the fixed code and still fail 9 and 15 tests.

Mutant 4 first survived because overflow pieces did not carry the count, which made the guard redundant.
The null-style count is now carried to every piece of a split paragraph (ParagraphRenderer). A list takes no per-piece count: its nulls are found when the first piece is drawn.

Gates

dotnet build VellumPdf.slnx -c Release -m:2: 0 warnings. dotnet format --verify-no-changes, the
clean-room check and generate-roadmap.py --check: clean. Release, REQUIRE_ORACLES=1,
REQUIRE_VERAPDF=1, veraPDF 1.30.4, qpdf 12.4.2, poppler with pdfsig, at the final head. Each count
is net10.0 and net11.0 together, because the runner reports them as one; each TFM runs half.

Project Total Passed Failed Skipped
Layout.Tests 2310 2306 0 4 (Linux-only named-pipe tests)
Kernel.Tests 4742 4742 0 0
Conformance.Tests 2906 2906 0 0
Cli.Tests 1816 1816 0 0

LayoutDiagnosticsTests alone is 65 tests on each TFM. Kernel gained tests from the merge of main.

Differential against 2.3.3

2.3.3 is 2.3.3+1c61fa653ea4bb295140cf682f555c7a8655a440 (printed by the runner for Layout and Kernel).
The runner compared it against the branch point 2027421 and against the head of each commit batch (the 2027421 row is unchanged because that commit predates the merges of main, whose commits the later heads include, at 961fa3d and 0949ccc),
with the default seed and with -Seed 2 -FuzzCount 1500.

Run Rows VIOLATIONS
2027421, seed 1 28,631 0
2027421, seed 2 29,731 0
c6dd496, seed 1 / seed 2 28,631 / 29,731 0 / 0
ea0ce80, seed 1 / seed 2 28,631 / 29,731 0 / 0
8f76228, seed 1 / seed 2 28,631 / 29,731 0 / 0
65d09f6, seed 1 / seed 2 28,631 / 29,731 0 / 0
58e538b (head), seed 1 / seed 2 28,631 / 29,731 1 / 0

At 58e538b the one violation on seed 1 is fuzz.1.269, a document of two headings, the first split over
two pages: the content stream is identical and the file skeleton differs. It comes from main's change
to where a split heading's bookmark is written. The merge at 0949ccc brought in exactly one main
commit, 39e5fe0 (#637): 0949ccc..58e538b changes only
the list walk, the diagnostics sink and documentation, and no earlier head of this branch, run before
that merge, shows it. The runner's table of deliberate output changes does not list #637.

Between the branch point and the heads before that merge no row changes verdict, except r6a-cancel|cancel-scan, a timing scan
that records at which points a cancelled token took effect. The other rows that differ between runs
differ only in the output directory printed in their message.

Not done

  • The AOT smoke script was not re-run after the first commit.
  • No follow-up inventory issue is opened here. Foreign font handle, JBIG2 dropped segment, the
    non-finite class and the "nothing reports" sites keep their "not reported" sentences.
  • A strict test for a signature page past the last page is not added; the Signing and Document
    documentation state the order.
  • DocumentRenderer.Render remarks say that Document.Save builds a renderer and calls Render. That
    was already inaccurate before this PR and is unchanged.
  • No message quotes caller text beyond one code point, so the Reader's excerpt helper is not ported. A
    report that quotes a token will need one.
  • UnencodableCharacter and BandTruncated dedupe document-wide on their subject, and the null-style
    and list codes dedupe per element.

Tim81 added 11 commits November 20, 2026 11:51
A save keeps several inputs while it loses, misplaces or substitutes
content, and the only reports were two unrelated lists. Document.Diagnostics
now lists one item per code and subject with an occurrence count, bounded at
1,000 items with a sentinel counting what was dropped.
Document.StrictDiagnostics, off by default, refuses a save that would report
an error item, after the layout and before anything is written, from every
save overload and from signing. The two older lists keep their content.
…ct docs (#607)

The per-list visited set walked a subtree again for every list that reached
it, which made a chain shared by many lists, or one list added many times,
quadratic. A per-save memo keyed on the second-level item caches its counts.
The strict-mode and marker documentation now says what holds, Diagnostics is
a read-only view, and the members that can now trigger the refusal say so.
Four tests now kill mutants the first suite let survive (the marker pre-sync,
per-element keying, a constant band subject, and the further-errors count).
The default-bytes test hashes the whole file. The documentation states one rule
for which substitutions Diagnostics lists, says what its order is, and no
longer promises reports in the Kernel docs.
# Conflicts:
#	CHANGELOG.md
#	src/VellumPdf.Layout/PublicAPI.Unshipped.txt
…#607)

The per-second-level-item memo still cost one subtree walk per distinct
second-level item, so one list with 400 such items reaching a 100,000-item
chain, or 10,000 chained second-level items, was quadratic. One visited set
per save, carried on the layout context, makes the walk linear in the
distinct items the caller built. A null text or null child is now counted
once in the save, under the first list in drawing order that reaches it.

Tests pin the nodes visited for the five measured shapes, the single count
under the first list, and the order independence of the total. The
documentation states that rule once and the FontRef note says which text is
listed.
# Conflicts:
#	CHANGELOG.md
#	src/VellumPdf.Layout/PublicAPI.Unshipped.txt
…607)

The walk ran when a list was laid out, so a list that starts at a later item,
or that a caller's renderer lays out and never draws, used up the
document-wide visited set and a later list that does report found nothing; strict
mode then saved. The walk now runs when a list is drawn from its first item,
through the document's context. The documentation says that only such a list
takes part, and that the work is linear in the items and child links.
… item (#607)

ListItem.Children, the NullGrandchild remarks and the walk summary now carry
the condition that only a list the document draws from its first item takes
part, and say what happens to a list that starts later or is measured and
never drawn.
@Tim81
Tim81 merged commit 2d4c1df into main Nov 20, 2026
4 checks passed
Tim81 added a commit that referenced this pull request Nov 21, 2026
DocumentRenderer's page-counting pass and drawing pass were two copies
of the same placement branching. One routine now runs both, so the
too-tall refusal, the 50,000-continuation cap and every later placement
rule are written once. Each pass keeps its side effects where it had
them: the drawing pass commits the open page before a too-tall or cap
throw; the counting pass creates no page.

Internal only: no public API change and no output change. A renderer can
report a key and a box for the result the loop accepted, in both passes;
only HeadingRenderer reports, with the y its outline entry uses. Reports
are collected only when something reads them. An internal plan
(target to page and y, page count) feeds plan-dependent renderers through
at most five measuring runs; past that the save throws
InvalidOperationException naming the unstable targets. No public
renderer is a dependent, so no existing document reaches the cap or the
check that the drawing pass matches the last measuring run.

Layout diagnostics (#642) are still reported from the drawing pass only:
a cut footer is reported once whether or not measuring runs repeat.
DocumentRenderer.PendingBookmarks and BookmarkEntry, never read, are
removed. Document.CreateRenderer goes from private to internal for tests.
@Tim81
Tim81 deleted the feat/layout-diagnostics 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: one general diagnostics channel and an opt-in strict mode (the additive half of #496 and the channel of #304)

1 participant