Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
name: CI

# `release/**` is here so a patch cut from a tag can be verified before it ships. Every patch tag
# so far (v1.5.1 through v1.8.2) was an ancestor of `main` and got its CI as an ordinary push, but
# a release branch built on an older tag never touches `main` and would otherwise be tagged and
# published having run nothing at all. `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 this file: 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
# (#462).
on:
push:
branches: [ main, v1.7-conformance ]
branches: [ main, v1.7-conformance, 'release/**' ]
pull_request:
branches: [ main, v1.7-conformance ]
branches: [ main, v1.7-conformance, 'release/**' ]

jobs:
build:
Expand Down
52 changes: 52 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

### Changed

- **CI now runs on release branches too.** It 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 so 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. Because GitHub reads the workflow from the branch being pushed,
the trigger has to be cherry-picked onto any release branch cut from an earlier tag. (#462)

- **Three rule justifications now derive from the clause rather than from veraPDF, and one of them
reached the caller.** `ActionRule` claimed §6.5.1 "is an allow-list", and separately claimed
derivation from the specification text while a comment a hundred lines below justified its
Expand Down Expand Up @@ -227,6 +236,49 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

### Fixed

- **A document deep enough to need more than about 4,250 page continuations killed the process
(#459).** `DocumentRenderer` recursed once per continuation, so stack depth grew with the
number of pages a single element spanned. Past the limit the runtime raised a stack overflow,
which .NET makes unrecoverable: no `try`/`catch` in calling code could turn it into a message,
unlike every other malformed-input failure in this library. A list item, a table row and a
block element each occupy at least one line however few characters they carry, which is why
4,950 characters arranged as list items overflow a 200pt-tall page while the same count of
characters wrapped into one paragraph on a page with room for more lines does not. Both
pagination passes recursed, not just the one that draws: measured on the same list document,
the render pass died at about 4,356 `PlaceRenderer` frames, and adding a footer moved the
crash to about 4,181 `CountPlaceRenderer` frames in the page-counting pass that runs first.
Stack layout jitters a few frames between runs, and both figures come from a Release build: a
Debug one fails sooner, at roughly 2,456 and 2,825 frames, with the counting pass surviving
longer than the drawing pass rather than the reverse. Both are now loops. The conversion
changes nothing else: every call sat in tail position, so no local outlived it and all the
state that crosses a continuation already lived in fields.

Alongside it, an element may now produce at most 50,000 continuations before
`InvalidOperationException` is thrown naming that limit. The count resets per top-level element,
so a document built from many separate elements is not bounded by it. It guards a case the
recursion used to stop by accident: `Document.Add(IRenderer)` takes any implementation, and one
whose `Partial` result never advances would now loop forever, allocating pages until memory ran
out. It is also a ceiling on how many pages a single element may span, and the library's own
renderers can reach it: on a 420x400pt page laid out one table row to a page, 50,001 rows render
and 50,002 throw, having made progress on every page, so the message names both causes. For some
callers it is a new limit, and 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. 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, where the recursion
tail-calls. Anyone who had already worked around the crash either way meets the cap instead.

- **The two pagination passes disagreed about an element too tall to fit (#460).** With a header or
footer set, `DocumentRenderer` counts pages before it draws them. Given an element that fits on no
page, the counting pass skipped it and carried on, while the drawing pass threw. The wrong count
never surfaced, because the second pass's exception ended the render before anyone could read it,
but the disagreement is load-bearing the moment anything reads the first pass's output, which is
what #288 sets out to do. The counting pass now throws the same exception, and both sites read one
shared message so they cannot drift apart. One visible consequence: with a running band, the
exception now comes from 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. Split out of #312, which keeps the image fit modes it also asked for.

- **Sixteen PDF/A clause citations named clauses that say something else, and several reached the
emitted output.** `FontEmbeddingRule` cited ISO 19005-2 §6.3.4–§6.3.5 for font embedding, in its
summary, its remarks, its `RuleId` and its `Clause` property. Clause 6.3 of ISO 19005-2 is
Expand Down
6 changes: 5 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,11 @@ release time.
## Branch and PR etiquette

- **Target `main`.** All pull requests should be opened against the `main`
branch.
branch. The one exception is a patch release cut from an older tag, which
lives on a `release/x.y.z` branch because `main` carries work the patch must
not ship. CI runs on `release/**`, but GitHub reads the workflow from the
branch being pushed, so a branch cut from a tag older than that trigger gets
no CI until the workflow change is cherry-picked onto it as well (#462).
- **One logical change per PR.** Keep pull requests focused. Split unrelated
fixes into separate PRs.
- **Link issues.** Reference the relevant GitHub issue in the PR description
Expand Down
175 changes: 123 additions & 52 deletions src/VellumPdf.Layout/Rendering/DocumentRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,44 @@ namespace VellumPdf.Layout.Rendering;
/// </summary>
public sealed class DocumentRenderer
{
// Bounds the per-element continuation loop in both pagination passes (#459). It exists because
// Document.Add(IRenderer) takes any implementation and LayoutResult.Partial accepts any overflow
// renderer: one whose overflow never advances used to be stopped by the CLR stack overflowing,
// which is a crash rather than something a caller can catch, and now that both passes loop it
// would page forever instead.
//
// It is therefore also a hard ceiling on how many pages one top-level element may span, and the
// library's own renderers can reach it: measured on a 420x400pt page laid out one table row to
// a page, 50,001 rows render and 50,002 throw here, having made progress on every page. That is
// deliberate rather than ideal, and for some callers it 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 the 50,000 was pitched. 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, where the recursion
// tail-calls. A caller who had already worked around the crash either way meets the cap
// instead. The message names the causes it can, because only one of them is the caller's own.
private const int MaxContinuationsPerElement = 50_000;

// Shared by PlaceRenderer and CountPlaceRenderer so the two passes cannot drift to different
// wording, or different verdicts, on an element neither can place (#460). It does not make the
// passes agree in general: with a running band and no content at all, pass 1 still counts one
// page where pass 2 creates none, which predates this change. Making pass 1 throw also moves
// the throw earlier when a band is set, so a caller that catches it is left holding an empty
// PdfDocument rather than the pages pass 2 had already committed; PdfDocument.Save then reports
// that the document has no pages.
private const string ElementTooTallMessage =
"An element is too tall to fit on a single page and cannot be rendered. " +
"Reduce the element's content or increase the page size.";

private static InvalidOperationException TooManyContinuations() =>
new($"A single element needed more than {MaxContinuationsPerElement} page continuations, so " +
"its layout is not converging. Either an overflow renderer never advances, or the " +
"element genuinely spans more pages than one element may and should be split into " +
"several, or its height sits within a rounding error of the content area, so " +
"pagination refuses and accepts it by turns.");

private readonly PdfDocument _pdf;
private readonly PdfRectangle _pageSize;
private readonly EdgeInsets _margins;
Expand Down Expand Up @@ -142,40 +180,58 @@ private void FinishCurrentPage(int totalPages)

private void PlaceRenderer(IRenderer renderer, int totalPages)
{
EnsurePage();
var continuations = 0;
while (true)
{
EnsurePage();

var availableArea = new LayoutBox(
ContentArea.X, _currentY,
ContentArea.Width, ContentArea.Bottom - _currentY);
var availableArea = new LayoutBox(
ContentArea.X, _currentY,
ContentArea.Width, ContentArea.Bottom - _currentY);

var result = renderer.Layout(new LayoutContext(availableArea));
var result = renderer.Layout(new LayoutContext(availableArea));

switch (result.Status)
{
case LayoutResult.Outcome.Full:
DrawRenderer(renderer);
_currentY = result.OccupiedArea!.Value.Bottom;
break;
switch (result.Status)
{
case LayoutResult.Outcome.Full:
DrawRenderer(renderer);
_currentY = result.OccupiedArea!.Value.Bottom;
return;

case LayoutResult.Outcome.Partial:
DrawRenderer(result.SplitRenderer!);
FinishCurrentPage(totalPages);
PlaceRenderer(result.OverflowRenderer!, totalPages);
break;
case LayoutResult.Outcome.Partial:
DrawRenderer(result.SplitRenderer!);
FinishCurrentPage(totalPages);
renderer = result.OverflowRenderer!;
break;

case LayoutResult.Outcome.Nothing:
FinishCurrentPage(totalPages);
EnsurePage();
var retry = renderer.Layout(new LayoutContext(ContentArea));
if (retry.Status == LayoutResult.Outcome.Nothing)
{
case LayoutResult.Outcome.Nothing:
FinishCurrentPage(totalPages);
throw new InvalidOperationException(
"An element is too tall to fit on a single page and cannot be rendered. " +
"Reduce the element's content or increase the page size.");
}
PlaceRenderer(renderer, totalPages);
break;
EnsurePage();
var retry = renderer.Layout(new LayoutContext(ContentArea));
if (retry.Status == LayoutResult.Outcome.Nothing)
{
FinishCurrentPage(totalPages);
throw new InvalidOperationException(ElementTooTallMessage);
}
break;

default:
// Unreachable: LayoutResult's constructor is private and its three factories
// pass only these three members. Kept because a fourth Outcome used to make
// this method return and skip the element; under the loop it would instead
// spin to the cap and blame the renderer (#459).
throw new InvalidOperationException($"Unknown layout outcome {result.Status}.");
}

if (++continuations > MaxContinuationsPerElement)
{
// Symmetry with the too-tall throw above: commit the open page rather than leave
// its canvas unflushed. The page still stays in the document. Both
// branches reach this throw, but only the Nothing branch can arrive with a page
// still open, because the Partial branch has already finished one.
FinishCurrentPage(totalPages);
throw TooManyContinuations();
}
}
}

Expand Down Expand Up @@ -284,32 +340,47 @@ private int CountPages()

private void CountPlaceRenderer(IRenderer renderer, ref double currentY, ref int pages, LayoutBox contentArea)
{
var availableArea = new LayoutBox(
contentArea.X, currentY,
contentArea.Width, contentArea.Bottom - currentY);
var continuations = 0;
while (true)
{
var availableArea = new LayoutBox(
contentArea.X, currentY,
contentArea.Width, contentArea.Bottom - currentY);

var result = renderer.Layout(new LayoutContext(availableArea));
var result = renderer.Layout(new LayoutContext(availableArea));

switch (result.Status)
{
case LayoutResult.Outcome.Full:
currentY = result.OccupiedArea!.Value.Bottom;
break;

case LayoutResult.Outcome.Partial:
pages++;
currentY = contentArea.Y;
CountPlaceRenderer(result.OverflowRenderer!, ref currentY, ref pages, contentArea);
break;

case LayoutResult.Outcome.Nothing:
pages++;
currentY = contentArea.Y;
var retry = renderer.Layout(new LayoutContext(contentArea));
if (retry.Status == LayoutResult.Outcome.Nothing)
break; // element too tall — skip (real render will throw)
CountPlaceRenderer(renderer, ref currentY, ref pages, contentArea);
break;
switch (result.Status)
{
case LayoutResult.Outcome.Full:
currentY = result.OccupiedArea!.Value.Bottom;
return;

case LayoutResult.Outcome.Partial:
pages++;
currentY = contentArea.Y;
renderer = result.OverflowRenderer!;
break;

case LayoutResult.Outcome.Nothing:
pages++;
currentY = contentArea.Y;
var retry = renderer.Layout(new LayoutContext(contentArea));
if (retry.Status == LayoutResult.Outcome.Nothing)
{
// This pass used to skip the element and undercount here while
// PlaceRenderer threw on it; the two passes must agree (#460).
throw new InvalidOperationException(ElementTooTallMessage);
}
break;

default:
// Unreachable for the same reason as PlaceRenderer's arm above, and kept for
// the same reason (#459).
throw new InvalidOperationException($"Unknown layout outcome {result.Status}.");
}

if (++continuations > MaxContinuationsPerElement)
throw TooManyContinuations();
}
}

Expand Down
22 changes: 0 additions & 22 deletions tests/VellumPdf.Layout.Tests/LayoutFixTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,28 +75,6 @@ public void Paragraph_veryLongWord_doesNotOverflow()
Assert.True(ms.Length > 0);
}

// ── Group D4: Too-tall element throws ────────────────────────────────────

[Fact]
public void DocumentRenderer_tooTallElement_throwsInvalidOperation()
{
using var doc = new Document();
doc.PageSize = new PdfRectangle(0, 0, 200, 100); // Very short page
doc.Margins = new EdgeInsets(5);

// Add 20 lines of text — each line is ~12pt, so 20*12=240pt > 90pt content height
// This creates a paragraph that is taller than a single page
var style = new TextStyle { FontSize = 12 };
var text = string.Join(" ", Enumerable.Repeat("Word", 150)); // very long paragraph
doc.Add(new Paragraph(text, style));

var ms = new MemoryStream();
// The very long single paragraph should either paginate or, if too tall, throw.
// In practice pagination handles this; the test just verifies no infinite loop.
doc.Save(ms);
Assert.True(ms.Length > 0);
}

// ── Group E: RowSpan ─────────────────────────────────────────────────────

[Fact]
Expand Down
Loading