Skip to content

fix(kernel): save a deep structure tree without recursing - #645

Merged
Tim81 merged 4 commits into
mainfrom
fix/deep-structure-tree
Nov 20, 2026
Merged

Tim81 merged 4 commits into
mainfrom
fix/deep-structure-tree

Conversation

@Tim81

@Tim81 Tim81 commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Closes #638

What changed

A tagged document whose structure tree is deeper than the calling thread's stack allows overflowed the stack inside Save, and .NET cannot catch that. The six walks in PdfStructureTree recursed once per level. #571's cycle guard added a HashSet parameter to three of them, which lowered the depth they survive on the default stack.

  • All six walks (CollectPages, CollectElems, CollectElemsOnPage, BuildParentMap, CollectStructTypes and the first-leaf search) are now iterative. Five share one explicit-stack pre-order walk that calls its visitor on entry in the order the recursive code entered nodes. The cycle path set is added to on entry and removed when the node is popped, so a cycle still raises the same InvalidOperationException. The null check in CollectPages runs before anything reads the node.
  • The page of a grouping element used to be found by walking its whole subtree, once per element, so a chain cost the square of its depth. FirstLeafPages computes it for every element in one post-order pass, local to one Build call (nothing survives the call). It is internal static and returns a step count, so a test pins the linear cost without a clock.
  • No depth bound. A bound would refuse something 2.3.3 saved on a large stack, and the limit of the old code grew with the caller's stack. ISO 32000-2 Annex C, Table C.1 ("Nested objects") warns that readers may recurse and fail on deep nesting, so AddChild documents "Do not build a tree deeper than a reader can walk" and that Save does not limit depth.
  • No public API change; no PublicAPI file edit.

2.3.3 against this build

Input (tagged, Save) 2.3.3 This PR Why this is allowed
Acyclic tree up to the depth 2.3.3 saved (all test shapes, a 6,500 chain) saves saves, same normalised bytes a file that saved still saves, unchanged
Acyclic chain past 2.3.3's limit for the stack (100,000 on a default stack) process killed, stack overflow saves; qpdf --check clean 2.3.3 crashed on valid input; it now saves
Self-cycle, deep cycle, cycle then null stack overflow InvalidOperationException, same message refused as #521 refuses it, instead of crashing
Null child, null then cycle NullReferenceException ArgumentNullException, ParamName child still refused; a runtime fault became a named argument error
Shared element without an MCID InvalidOperationException "Object 8 was reserved but never assigned a value." same still refused, same exception
Shared leaf, duplicate MCID, MCID over the cap, non-standard type InvalidOperationException same type and message still refused, same exception

The base commit (23d50e2) already crashed on a 6,500 chain that 2.3.3 saved. That regression came from #571 and never shipped, so the CHANGELOG describes only the 2.3.3 behaviour.

Tests

StructureTreeDepthTests (Kernel), DeepStructureTreeOracleTests (Conformance). Expected hashes and messages were recorded by running the same tests on a detached checkout of the base commit before the change.

  • Byte identity: six shapes (chain 50, chain 3,000, wide, two pages, group without a page, first-leaf order) pinned by the SHA-256 of the normalised file; one value serves both TFMs.
  • 100,000-element chain saved on a thread with a 256 KB stack: the file holds 100,002 /Type /StructElem objects and the leaf's /P links reach /StructTreeRoot in 100,002 hops. The same chain through UseObjectStreams, Linearize, Encrypt, PrepareForSigning and SaveAsync, each checked with qpdf --check (linearized file: "File is linearized").
  • Step count: FirstLeafPages on a 10,000 chain takes at most twice the number of elements in steps and names the leaf's page for every group. A second test pins first-leaf order, a shared element and leaves nested below a group.
  • Refusals: exact exception type and exact message for 13 inputs, ParamName child for the null rows, a cycle of 100,000 elements on the small stack.
  • Second save of the same elements in another document: /Pg count changes from 1 to 3.
  • veraPDF 1.30.4, --flavour ua1, 1,000 nested Div ending in P: jobEndStatus="normal", no failed rule in clause 7.1 or 7.2.

On the base commit the 100,000-chain test ends the process with a stack overflow.

Run in Release with REQUIRE_ORACLES=1, REQUIRE_VERAPDF=1, qpdf 12.4.2, veraPDF 1.30.4, poppler:

Project net10.0 net11.0
Kernel 2,401 passed 2,401 passed
Layout 1,074 (2 skipped) 1,074 (2 skipped)
Conformance 1,454 passed 1,454 passed
Reader 2,023 (12 skipped) 2,023 (12 skipped)

Release build 0 warnings, dotnet format --verify-no-changes, clean-room check and generate-roadmap.py --check pass.

Mutations

Each mutant was applied to the committed change, rebuilt, and run on net10.0 against the named test filter, then restored.

Mutant Result
M1a-M1f: one walk back to recursion (CollectElems, CollectPages, CollectElemsOnPage, BuildParentMap, first-leaf search, CollectStructTypes), one at a time the 100,000-chain test aborts the process with "Stack overflow." in each case (a crash, not an assertion; run alone with -method so it is attributable)
M3: first-leaf answer computed per element by walking its subtree FirstLeafPages_ofAChainOf10000Elements_takesLinearSteps_... fails
M4: children visited in reverse order byte-identity fails for wide, twopages, groupnopage and firstleaf
M5: node read before the null check the null-then-cycle, null-child and null-deep refusal rows fail, and so does CycleGuardTests.StructElem_AddChild_nullChild_isStored_andRefusedWhereTheTreeIsBuilt: NullReferenceException instead of ArgumentNullException
M6: first-leaf map kept in a static field across Build Save_readsTheTreeAfresh_... fails (/Pg count 2, expected 3)

Differential run (2.3.3 against this build, net10.0)

The runner got two rows, K15.tree.deep6500 and K15.tree.deep100000 (child process, since 2.3.3 dies), and a category for "2.3.3 crashed on valid input, this build saves", scoped to the second row.

  • At the base commit: deep6500 is a violation (2.3.3 saved a file qpdf --check accepts, base crashes). That is the regression above, and it is the only violation in the run. deep100000 crashes on both sides.
  • At this branch: deep6500 is identical to 2.3.3; deep100000 is 2.3.3 "stack overflow" against this build "saved", in that category. The run has no violations, and the only two rows whose verdict differs from the base-commit run are these two (28,633 rows compared).

Not done

  • veraPDF cannot read a 10,000-deep tree: it ends with a Java StackOverflowError in its own recursive structure-tree walk, and the depth it reads depends on the JVM. On the development machine it read 5,000 levels and overflowed at 5,500; the CI runner's JVM overflowed at 4,000 (a first version of the test used 4,000 and failed there). CI's limit below 4,000 was not measured, so the oracle test uses 1,000, well under the lowest overflow seen anywhere, which is below the depth 2.3.3 saved. It checks ordinary-depth output, not the 100,000-level row. The 100,000-level coverage is qpdf --check and the save-path tests.
  • A diamond DAG (each level holds the next element twice, no cycle) is still walked once per path, as before. The docs say so: where each element has one parent the walks are linear in the number of elements, and an element under two parents costs time exponential in depth before the save refuses it. Measured on ee30ec7 at depth 18, net10.0: InvalidOperationException "Object 8 was reserved but never assigned a value." after 629 ms with no leaf, and the duplicate-MCID InvalidOperationException after 321 ms with a leaf. Changing it changes where its refusal is raised.
  • Direct nesting of PdfArray in PdfArray (a stream dictionary) and CountVisibleDescendants recurse too; neither is reached by a structure tree.

The six walks over the structure tree recursed once per level, so a tagged
document whose tree was deeper than the thread's stack allowed ended the
process in Save, and #571's cycle guard lowered that limit. Each walk is now
an explicit-stack pre-order walk that visits nodes in the order the recursive
code did, with the same cycle and null-child refusals.

The first-leaf page of a grouping element was found by walking its whole
subtree, once per element, so a chain cost the square of its depth. One
post-order pass local to Build now computes it for every element.
@Tim81 Tim81 changed the title fix(kernel): walk the structure tree without recursion fix(kernel): save a deep structure tree without recursing Nov 20, 2026
Corrects the previous commit in this branch and its message. That message
said each walk became an explicit-stack pre-order walk; five did, and the
first-leaf pass is a post-order pass.

CHANGELOG: a negative MCID is not refused (CollectElemsOnPage collects only
MCIDs of 0 or more, so that check cannot run); "as before" now names what
2.3.3 already refused with the same message, and says the cycle and
null-child refusals are the ones #521 added. Time and memory are stated per
walk, with the Linearize planner called out as slower on a very large tree.
Comments no longer claim a cycle walk "never finishes" and "runs out of
memory" in the same breath.

The veraPDF oracle test used 4,000 levels, which the CI runner's JVM could
not read (StackOverflowError); it now uses 1,000 and says why.
…638)

An element added under two parents is walked once per path, so the time can
grow exponentially with the depth before Save refuses the tree. Probed on
the previous head at depth 18 with each level's element added twice: an
InvalidOperationException after 629 ms with no leaf and after 321 ms with a
leaf. The CHANGELOG entry, the AddChild remarks and the helper comment now
say the linear cost holds where each element has one parent.
@Tim81
Tim81 merged commit 1bbdee2 into main Nov 20, 2026
4 checks passed
@Tim81
Tim81 deleted the fix/deep-structure-tree 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.

Kernel: A deep, acyclic structure tree overflows the stack in Save

1 participant