Skip to content

fix(layout): resolve table columns against every row and the available width - #485

Merged
Tim81 merged 12 commits into
mainfrom
fix/table-column-axis
Sep 11, 2026
Merged

Tim81 merged 12 commits into
mainfrom
fix/table-column-axis

Conversation

@Tim81

@Tim81 Tim81 commented Sep 10, 2026 •

Copy link
Copy Markdown
Owner

Four issues that meet in TableGridResolver.Resolve, TableGridResolver.AutoWidth and the cell
text path. They are together because fixing any one alone reintroduces another: a short widths array
fixed on its own pads with zero, and zero is the pathological value of the second defect.

Issue Defect
#480 section 1 the column count came from the first row, so a wider later row lost its extra cells
#477 an explicit widths array was applied literally: zero overlapped, negative advanced backwards, a short array discarded cells
#468 auto widths were floored at min-content and the sum was never capped
#473 a cell wider than its column was never hard-broken and its offset never floored, so it drew off the page

The row axis, the spans and the doubly-applied table margins are the next pull request. Three corpus
rows exist to hold that line and are byte-identical here.

What the fixes do

The column count is the widest row. Nothing stops a caller giving one row more cells than
another: Row.AddCell checks no other row's arity and TableElement exposes no column count to
check against.

Two shapes reach that, and only one of them was losing content. A later row with an extra cell
lost it outright: measured, a first row of two cells and a second of three drew four literals rather
than five. A later row whose excess comes from a ColSpan lost nothing, and its bytes still
move, because the span was silently truncated instead. Measured on a 400x300pt page at 10pt margins:

Columns Span cell width
Before 190, 190 190, one column's worth
After 152, 152, 76 228, exactly 152 + 76

Both drew four literals inside the content box, so the justification there is not content loss: it is
that the renderer discarded a span the caller set, which is the same class as a margin it ignores.

An explicit widths array is reconciled against that count rather than copied. Four inputs mean
auto: a missing entry, an explicit zero, a negative width and a non-finite one. The first two are
what TableElement.ColWidths and SetColumnWidths already document in two places and neither
implemented.

An explicit entry is honoured verbatim only when the array covers every resolved column. When it is
shorter, the column the resolver has to invent competes for the width, so two fitting 190pt entries
come out at 178.72 each. The alternative is a zero-width column the caller never asked for.

A negative width is clamped rather than refused, and that is a maintainer decision recorded here:
refusing it would turn a document that renders today into an exception, which a patch must not do.

A non-finite width was the worst of the four, and it was found by measuring rather than by reading
the brief, which never covered it. On the base, NaN put the token NaN where a PDF number belongs,
positive infinity Infinity, negative infinity -Infinity, and each also left the x operand of
every following column non-numeric. A content stream carrying those is not a conforming content
stream, so replacing them changes only output no consumer could have drawn.

When both the explicit widths and the auto columns' content floors cannot be satisfied, both
scale.
The first version of this scaled only the explicit set, which drove it to zero: a 200pt
column became zero wide and its text was shredded to one rune per line, reintroducing on one column
the defect the pull request removes on another. Measured after the change, that fixture resolves to
65.74 and 314.26, and neither set reaches zero.

The auto-width sum is capped. Re-measured at the generator's own worst corner, a 400x400pt page
with 60pt margins and three auto columns at 24pt, so a content box ending at 340: the rightmost
cell's right edge is 340 through five characters, 364.128 at six, 404.16 at seven and 444.192 at
eight.

Cell text wider than its column is hard-broken, and its offset floored. Measured before the fix
at x -83.2 centred and -222.4 right-aligned on a 400x900pt page at 50pt margins with a 300pt column.

The floor's precondition is not only an unbreakable rune, and the comment says so now. The cell wrap
measures against max(1pt, inner width) while the offset uses the inner width itself, so any line
in a cell narrower than its own padding exceeds it, an empty line included: an empty cell in a 1pt
column moved from x 50.5 centred and 45 right-aligned to 56, the cell's own inner edge.

Two behaviour changes this pull request owes you, neither of them free

Hard-breaking a cell can make its row taller than the page, so a document that rendered now
throws.
Measured against the base's own sources: a 100pt column with zero padding on a 400x200pt
page holding 300 W at 10pt. The base drew one line past the page edge. This branch breaks it into
enough lines that the row no longer fits, and save raises the too-tall exception.

This is the one place the pull request contradicts the release decision that the patch renders
correctly and raises nothing new. It is not a new exception type and not new validation, since that
exception already fires for any oversized element, and the alternatives were drawing off the page as
the base did or discarding the overflow. A document that relied on the base's off-page overrun to
avoid it will now raise it. Pinned by
CellText_hardBrokenRowTallerThanThePage_throwsElementTooTall.

The row-height measurement and the row drawing used to disagree, and now do not. The commit that
delegated the counting walk to the wrapper carried a comment saying the two "happened to agree".
They did not. The direction is one-sided: every case either of two random sweeps found had the walk
counting a taller row than the lines drawn, and none a shorter one. The count itself belongs to the
sample rather than to the defect, and the two sweeps gave 152 and 744 in 4,000, so neither is quoted
as a constant. The known-answer case does not move: the cell "AAAAii " in a 40pt column at
Helvetica 12 drew one line in a row sized for two, 28.8pt, and now resolves to the 14.4pt the single
line needs. So a document whose cell text ends in a space that does not fit gets a shorter row.

Evidence

  • Byte identity. 226 documents rendered before and after and hashed over their decompressed
    content streams, each row carrying a text-run count so a difference says whether text moved or was
    lost. Six rows differ and every count moves as the acceptance criterion required: the column count
    from four literals to five, four explicit-widths rows from two to three, and the over-wide cell
    from one to two. No seventh row moved across the fix round.

    Zero, negative and a short array hash identically on this fixture, and the reason is narrower
    than it looks: its content box is 300pt, three auto columns are 100pt each, and the short array's
    two explicit entries are also 100. On a 380pt box the same three give 126.67 three times, 126.67
    three times, and 100, 100, 180.

  • Gates. 6929 tests, 0 failures, in Debug and Release. Release matters here, since a duplicated
    or short grid is the shape a conformance rule inspects. Build with no warnings, format and
    clean-room clean, no public API entries.

  • Discrimination. Every behaviour was reverted in isolation and the test naming it confirmed to
    fail with the pre-fix number its comment claims. That pass is what found three behaviours no test
    covered, the most serious being that removing the guard which stops the scale-down firing on an
    array that already fits scaled every fitting array up, with nothing failing.

What the reviews found in this work

Two code defects, both in code written for this pull request: the explicit-only scale-down driving a
column to zero, and the span sum losing its overflow check when a checked Sum became a bare
accumulation, so a ColSpan of int.MaxValue stopped throwing and quietly dropped a cell.

One test that did not pin what it claimed: its three widths were identical, so a mutation folding the
surplus entry into the sum scaled both sides equally and it passed. One character of fixture data
fixes it.

And a count of prose corrections. The largest were the hash-equality reason above, a comment claiming
list items would hard-break when measurement shows they do not break at all at that corner, and the
inherited "only way" claim about the alignment floor.

Refs #365, #468, #473, #477, #480

…#480, #477)

TableGridResolver.Resolve took ColCount from table.Rows.FirstOrDefault()
alone, so a later row with more cells than the first lost every cell
past the first row's own count -- DrawRow's while (col <
_colWidths.Length) loop had no column for them. ColCount is now the
widest row.

An explicit SetColumnWidths array was also copied verbatim: an array
shorter than the resolved column count silently dropped the trailing
columns at the array boundary, and a zero entry rendered at zero width
even though TableElement.ColWidths and SetColumnWidths both document
zero as meaning auto. Reconciling the array against the column count
fixes both, because they are the same defect at two different
boundaries -- padding a short array with zero would just trade one for
the other.

A negative entry advanced x backwards for every following column. The
plan left the response to a negative width to the maintainer; refusing
it would turn a document that renders today into a thrown exception,
which a patch release should not do, so it is clamped to the same auto
meaning as zero instead.

Auto columns now take their share from the width left over after the
explicit ones, floored at their own minimum content width, and the
whole row is scaled down to the available width when the explicit
entries, the floors, or both leave it over budget -- an explicit array
whose entries alone exceed the available width reaches the same cap.
TableGridResolver.AutoWidth floored each column at its minimum content
(longest word) width and distributed the rest proportionally, but
never capped the total: when every column's floor alone was wider than
its proportional share, the sum exceeded the available width with
nothing pulling it back, and the table drew past the content box and,
far enough, past the page.

Measured on a 400pt page, 60pt margins, three auto-width columns at
Helvetica 24pt -- a content box ending at x 340 -- on the word family
"W" followed by g's: the rightmost cell's right edge sat at 340
through five characters, 364.128 at six (past the content box) and
404.16 at seven (past the page). Scaling every column down
proportionally when the sum overruns keeps their relative sizes rather
than truncating the rightmost one; the same seven-character word now
measures 340 regardless.

LayoutGen.CellWord carried this defect as a documented constant rather
than a generated one, so #468 could not surface as a failing property.
Widened from "Wg" to "Wgggggg" now that the cap holds for every table
the property suite generates.
The previous commit widened LayoutGen.CellWord to six characters,
verified against #468's own overflow boundary, but that field also
fills DocSpec.Word, which ParagraphText and every generated list item
share with the table cells. At this generator's own worst corner (a
400pt page, 60pt margins, 24pt font), a single-word cell's
content-floor width and its post-cap width coincide once the word
alone passes 81.33pt: the default padding subtracted from an equal
three-way share of the 280pt content box. A word past that line trips
#468's old overflow and #473's new hard-break at the same time, and
the paragraph and list items hit the same line on the same corner, so
widening this far turned an intermittent CsCheck failure -- caught on
one seed, not reproduced on the next several -- into a real gap: the
paragraph no longer drew as the single literal
PropertyTests.ValidDocument_placesNothingOutsideThePage assumes for
every element built from this word.

Five characters measures 76.032pt per word at that same corner, 5.3pt
under the line, so it widens the constant without reaching either
defect. #468 itself still gets a property that fails before the fix
and passes after -- TableColumnAxisTests now carries one, built for
this exact corner rather than shared with the paragraph and list
generators.
TableRenderer.WordWrapLines emitted a word wider than the column
whole -- its lineW == 0 arms, reached both for a cell's first word and
for the word starting a fresh line after a wrap. Measured on a 400x900
page, margin 50, one 300pt column (288pt inner width), a cell holding
60 "W"s at 10pt: before the fix that drew as one 60-character literal
at Tm x -83.2 under Centre and -222.4 under Right, both off the page.

HardBreakWord now splits an over-wide word at character granularity,
the same behaviour ParagraphRenderer.HardBreakWord already has for a
paragraph line (#472) -- kept as its own copy rather than shared,
since the two callers differ in what they know about their own box.
The same fixture now hard-breaks into 30 + 30 characters, both under
the inner width, at x 58.4 and 60.8.

The centre and right offsets are also floored at the cell's own left
edge, the same clamp #472 made for a paragraph and for the same
reason: hard-breaking keeps every line within the column except the
one line consisting of a single over-wide rune that cannot be broken
any further, and that is the only way the offset can go negative.
Measured on a 20pt column with zero padding, one "W" at 106pt (~100pt
wide): before the fix, Tm x -30.064 under Right and 9.968 under
Centre; floored, both now land on the column's own left edge.

WordWrapCount now delegates to WordWrapLines instead of carrying a
separate line-counting walk, so Layout's row height and Draw's actual
line count cannot drift apart -- which is also what lets the
hard-break reach both call sites from one change.
…-explicit scale-down

ReconcileExplicitWidths scaled every column, auto included, by one
factor whenever the row overran the available width. That is right
when nothing pushed a column below its own content floor, but a
floor's whole point is that a column should not go under it: when the
explicit entries alone already exceed the available width, the auto
column's residual is already zero, so its target is exactly its own
floor -- and the joint scale then shrank that floor too, reaching
TableRenderer's hard-break path (#473) for a cell that was never the
reason the row was too wide.

Measured on the corpus harness's own "table explicit oversized" row --
a two-entry 500+500 array against a three-cell row, so short as well
as oversized -- the joint scale gave four content operators (the third
cell hard-broken into two fragments) where the acceptance table for
this pull request calls for three, one literal per cell.

The explicit columns now absorb the correction on their own, scaled to
whatever the auto columns' floors leave available; the auto columns
keep their floor unless even scaling the explicit ones to zero still
is not enough, the one case the previous joint scale is kept for, as a
last resort.
Covers #480 section 1, #477, #468 and #473 as one entry, since the
plan treats them as one interacting defect rather than four
independent ones.
A non-finite explicit width was the fourth input the resolver could not
honour, and the only one whose output was not a PDF. Measured on eedaa3c,
a 400x300pt page at 10pt margins with widths of NaN, 100 and 100: the
first cell emitted w=NaN, positive infinity emitted w=Infinity and
negative infinity -Infinity, and each also left the x operand of every
following column non-numeric.

This branch had already fixed negative infinity as a side effect of
clamping negative widths, and left NaN and positive infinity emitting a
token where a PDF number belongs. All three now classify as auto,
alongside a missing entry, an explicit zero and a negative width. A stream
carrying those tokens is not a PDF, so this changes only output that was
already invalid.

The test asserts the token is absent from the whole stream rather than
only checking the resolved widths, because a width assertion alone passes
on a stream that still carries NaN somewhere else in it.

Also drops a claim about ISO 32000-2 that the comment could not support.
The column count needed no appeal to the specification: Row.AddCell checks
no other row's arity and TableElement exposes no column count to check
against, which is the whole reason a wider later row lost its extra cell.

Refs #477, #480
Three defects an adversarial review round found in the table column
axis fix:

TableGridResolver.ReconcileExplicitWidths zeroed every explicit
column when the auto columns' own content floors alone already
exceeded the available width, because the leftover budget for the
explicit set floored at zero and scaled straight to it. That crushed
the explicit side to nothing while the auto side kept its full,
unreduced floor -- the same one-sided collapse the auto-width cap
exists to prevent, just moved to the other set. The explicit columns
are no longer scaled down when their own budget is non-positive;
instead they are left at their raw sum and folded into the final
ScaleToFit call alongside the auto floors, so both sets shrink by the
same ratio and neither reaches zero while the other keeps its floor.

The column-count loop's ColSpan accumulation used unchecked `+=`
where the LINQ Sum it replaced threw OverflowException on a per-row
total past int.MaxValue. A caller passing pathological ColSpan values
now gets the same loud failure back, inside a `checked` block, rather
than a silently wrapped count and a quietly wrong document.

TableRenderer.WordWrapLines decided whether a word started a fresh
line by testing `lineW == 0`, a measured advance rather than an
emptiness flag. A word whose advance is genuinely zero -- Helvetica's
DEL among them -- left the line buffer holding a pending, un-flushed
line while lineW still read 0, so the next over-wide word believed it
was starting fresh too and pushed its hard-break fragments ahead of
the pending one, which was flushed only at the very end, after
content that followed it in the source. Guarding on
`lineBuilder.Length == 0` instead, the same test ParagraphRenderer
already uses, restores source order.
Several existing tests compared two renders against each other rather
than pinning an absolute value, which lets a mutation that scales
both sides equally slip through: ExplicitWidths_surplusArray now uses
a genuinely surplus 500 instead of a third 100, so folding it into
the sum discriminates (54.28571 against the expected 100 per column).
A new ExplicitWidths_arrayThatFits_resolvesToExactWidths pins absolute
widths for a fitting array, catching a ScaleToFit guard removed.

ExplicitWidths_bothSetsCannotBeSatisfied_neitherReachesZero pins the
fix in the paired commit: neither the explicit nor the auto column
collapses to zero when both would otherwise overrun the row, and it
also catches ScaleToFit being dropped from ReconcileExplicitWidths.
ExplicitWidths_noAutoContentWithNegativeResidual_clampedNotNegative
covers the one branch with no floor of its own -- an auto column
whose own content contributes nothing to autoMaxTotal -- where a
missing residual clamp would resolve a negative column width.

ColumnCount_columnSpanOnALaterRow_resolvesTheSpanWidth pins that the
widest-row rule also widens for a ColSpan the caller set, not only
for an ordinary extra cell, since the old count silently discarded
a span width the same way it dropped an extra cell.

CellText_oneRuneWiderThanTheColumn_glyphStillLeavesANarrowPage adds a
page narrow enough that a single over-wide rune's glyph, not just its
origin, leaves the page -- the existing test's 200pt page cannot see
this, and the origin floor is documented as a limit rather than a fix
for it. CellText_emptyCellNarrowerThanItsPadding pins that an empty
cell reaches the same offset floor with no over-wide rune involved,
which the comment ahead of it used to say could not happen.
CellText_zeroAdvanceCharacterBeforeAHardBreak_keepsSourceOrder pins
the draw-order fix in the paired commit.

CellText_hardBrokenRowTallerThanThePage_throwsElementTooTall pins a
disclosed behaviour change: hard-breaking a cell can now raise the
same too-tall exception any other element does, where the base drew
the overrun off the page instead. See the CHANGELOG entry this pins.

ColumnCount_unevenRowsIncludingAHeader_resolvesWithoutLoss's own
docstring miscounted its fixture as three rows; it is two.
The entry was written before the non-finite-width fix landed and
still enumerated three auto inputs (missing, zero, negative) instead
of four; it now names the non-finite one and its own measurement.
The hard-break coordinates gave a column width but not the page size
or margin they also depend on, so the fixture could not be
reproduced from the sentence alone. The entry now also discloses the
column-span widening, the scale-both-sides fix, the draw-order fix
for a zero-advance character, the WordWrapCount-to-WordWrapLines
delegation (which corrects row heights, not merely refactors their
computation), and the one place this pull request now throws where
the base drew off the page instead.

LayoutGen.CellWord's own doc comment overstated the coupling between
the shared word, the paragraph and the list items as three-way and
geometry-identical. A list item never wraps or hard-breaks the word
regardless of length, so only the cell and the paragraph are coupled
to it, and they diverge at different thresholds (81.33pt for the
cell, 88.89pt for the paragraph) that only happen to cross in the
same character step for this particular word family. It also had the
paragraph hard-breaking at the same point the cell does; a single
word first exceeds the paragraph's own content box, its hard-break
trigger, only at twenty-one characters. A cross-reference pointed
"below" at a property that is declared above it.
Two places gave the row-height disagreement as 744 of 4,000 random cell
strings. That number is a property of the sample's alphabet and seed, not
of the defect: a reviewer's own sweep over a different alphabet found 152
in 4,000, and neither figure is wrong. Quoting one as though it were a
constant invites the next reader to reproduce a third and conclude
someone miscounted.

What does not move is the direction and the known-answer case. Every case
either sweep found had the old walk counting a taller row than the lines
actually drawn and none a shorter one, and the cell "AAAAii " in a 40pt
column at Helvetica 12 counted two lines for one drawn line either way.
Both places now say that, and name both sweeps so the spread is visible
rather than hidden behind whichever number was written last.

Refs #480
Five sentences claimed more than the code does, and a sixth test asserted
less than it read.

"Neither set can reach zero" is true of the non-positive-budget regime,
not of the method. The two regimes meet at a cliff: measured on a 200pt
explicit entry against a 956pt auto floor, an available width of 956
gives 165.22 and 789.78 while 956.000000000001 gives 0 and 956. That is
the stated preference working as designed, since overflow comes out of
the explicit columns first, but the sentence had promised otherwise. The
continuous alternative was tried on paper and rejected: never scaling an
explicit column below its proportional share crushes the auto floor in
the oversized-and-short case the preference exists for.

The proportional regime has a cost the changelog did not carry. An
explicit entry far larger than the table takes proportionally more of it:
measured on a 380pt width against that same floor, 5,000 resolves to
319.01 and 60.99 and renders, and 10,000 to 346.84 and 33.16, where the
auto column's hard-broken content makes the row taller than the page and
the render refuses. That refusal class is now named alongside the one the
hard-break itself introduces.

"If available is zero or negative, ScaleToFit leaves the array unscaled"
is false; it scales to a non-positive ratio, measured as every column 0
at an available width of 0 and negative widths at -50. No document
reaches it, and the comment now says which caller guarantees that rather
than claiming the method is safe on its own.

"Nothing visible moves" for the guard change was wrong in two directions.
The space after a zero-advance character came back, so following glyphs
shift, and the line count goes up rather than down: one line in a 24pt
row becomes two in a 48pt row on a measured fixture. Across 9,607 cell
strings 479 gained a line, none lost one, and the drawn glyph sequence
disagreed with the source in 399 cases before and none after.

"38 code points in every Standard-14 face" is 38 in Helvetica and Times,
32 in Courier, and all 256 in Symbol and ZapfDingbats.

"A list item never wraps or hard-breaks it, regardless of length" was
measured only near the binding constraint. All three elements are coupled
to the constant, at six characters for a cell, nineteen for a list item
and twenty-one for the paragraph.

The span test's containment assertion summed two of three columns and
could not fail while the widths above it held; it now asserts the span
cell's own right edge. And the checked accumulation had no test at all.

Refs #477, #480
@Tim81
Tim81 merged commit adf6acf into main Sep 11, 2026
4 checks passed
Tim81 added a commit that referenced this pull request Sep 11, 2026
Two entries. A new one for the header window and the doubly applied
table margin, and a correction to the merged column-axis entry, which
called the too-tall fixture's explicit 10pt "the default"; TextStyle
FontSize defaults to 12, and at 12 that row is 22.4pt rather than 20pt,
so the arithmetic the sentence invites does not work out.

The new entry states what a currently-correct document loses, which the
release rule for this patch requires: a non-zero left or top table
margin shifts the table by exactly that margin, a right or bottom one
moves nothing, and a caller who halved their margin to compensate for
the doubling will see their table move.

Three figures in it are measured rather than inherited. The loss
threshold is the emitted row height exactly, 20, 32 and 44 at font
sizes 10, 20 and 30, from a 0..60 integer sweep that draws the row at
every margin after the fix. The x origin is 36 rather than 26 at a 10pt
table margin, which is the document margin plus the table margin twice
plus the cell's own 6pt left padding, a term the first draft omitted.
And the geometric stop test drops no row: 108,880 documents over page
heights 60..400 and table margins 0..19.75 in quarter-point steps,
107,320 rendered drawing all twelve rows, 1,560 raising the too-tall
exception, none with a wrong row count.

Also corrects the comments and public documentation the two fixes made
stale. Two comments in TableRenderer still described the pre-fix
behaviour. FindHeaderRowIndices claimed the leading contiguous run was
"the only reading" under which the two loops partition the rows, which
a prefix of any length equally satisfies. AddRow and AddHeaderRow still
documented every header row as repeating. And the row-axis test class
doc called the margin defect content loss, when it is an offset below
the row height and loss only at or above it.
@Tim81
Tim81 deleted the fix/table-column-axis 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.

1 participant