Skip to content

fix(reader): honour object generation numbers on resolve - #192

Merged
Tim81 merged 8 commits into
mainfrom
feat/121-generation-numbers
Aug 18, 2026
Merged

Tim81 merged 8 commits into
mainfrom
feat/121-generation-numbers

Conversation

@Tim81

@Tim81 Tim81 commented Aug 18, 2026 •

Copy link
Copy Markdown
Owner

Closes #121.

PdfIndirectReference carried only an object number and hardcoded " 0 R" on write; the parser dropped
the middle field of a parsed N G R; and the cross-reference table was keyed on object number alone. So
10 2 R resolved to whatever object 10 held at generation 0.

This also unblocks #97: per-object key derivation for security handler revisions R2-R4 is
MD5(fileKey ‖ objNum[0..3] ‖ gen[0..2]), so decrypting V1/V2/V4 files is impossible without the generation.

Scope grew during review. What began as a reader change now also touches the write path and adds four
public Kernel members, because the read fix made a latent write-path defect reachable. Detail below —
worth a look before merge, since public surface on a Stable package is permanent.

Approach

The generation is stored on XrefEntry and validated on resolve, rather than re-keying the dictionary on
(objNum, gen) — a compound key would have broken ObjectNumbers, NextFreeObjectNumber, and
UncompressedObjectOffset(int), all consumed by PreflightContext. Resolve(int) keeps its
generation-agnostic behaviour for callers with no reference in hand; Resolve(PdfIndirectReference) enforces.
The cache stores (Value, Generation) so a generation-bearing lookup cannot be answered from an entry a
generation-agnostic call warmed first.

The cross-reference table is the single authority for a generation it actually records. Where it does not — a
garbled field, or one above the ISO 32000-2 §7.5.4 ceiling of 65535 — the entry is marked unknown and the
object's own header takes over, rather than guessing 0 and making a reachable object silently unresolvable.

Public API

Four additive members, all in PublicAPI.Unshipped.txt; PublicAPI.Shipped.txt is byte-untouched in all
eight packages.

  • PdfIndirectReference.Generation + a two-argument constructor.
  • PdfIndirectObject.Generation + a three-argument constructor.

The second pair is what fixes the write path. An incremental update preserves an object's generation — it
advances only when a freed number is reused for a different object (§7.5.4/§7.5.6) — so re-emitting an object
must write the generation the reference to it carries. The considered alternative, normalising the trailer to
generation 0, was rejected: it is spec-wrong, it fixes only /Root while every other reference in the base
file still names the old generation, and doing it properly would mean rewriting the whole file, invalidating
the very signatures the DSS and archive-timestamp paths exist to preserve.

Four members change behaviour on surfaces Stable since 2.0.0 — WriteTo, Equals (narrowed),
GetHashCode (now deterministic; HashCode.Combine is salted per process), and PdfIndirectObject.Reference.
All four are documented under ### Changed.

What review caught

Four defects, each of which survived a fully green 4,500-test suite:

  1. Hybrid free-entry regression. Free-entry tracking was shared between a revision's classic table and its
    own /XRefStm, but per §7.5.8.4 the classic table marks an object free because the stream defines it.
    The existing hybrid test could not see it — its table omits the object rather than marking it free.
  2. The parser discarded the generation, so enforcement rejected valid documents. An object at generation 1
    became unresolvable; a catalog at nonzero generation made Open throw. The tests hand-constructed
    references instead of parsing them.
  3. AppendRevision emitted files it could not reopen — the PAdES LTV path. WriteTo began emitting the
    real generation while the object header and incremental xref still wrote 0.
  4. int.MaxValue saturation aliased. A /W [1 4 4] field records 0x7FFFFFFF legitimately, so every
    out-of-range reference token collapsed onto it and resolved — the exact risk the neighbouring comment
    claimed to have eliminated.

Each is now pinned by a regression test that fails against the commit before its fix.

Verification

  • 4,539 tests, 0 failed, 0 skipped, with oracles enabled (REQUIRE_VERAPDF=1, qpdf on PATH).
    Conformance runs 1237/1237 in ~4m30s; the same suite finishes in 2s with 277 skipped when the oracles are
    off, which is how we know they ran.
  • veraPDF verdicts are identical to main — 1237/0/0 both sides. No conformance verdict moved.
  • Performance at parity. The checked resolve path is 1.02-1.03× the agnostic one (+0.15 to +0.51 ns/op),
    inside the noise floor — main's own ratio wanders 0.976-1.011 on identical code. End-to-end
    PdfPreflight.Validate is 0.785 ms vs main's 0.787 ms. Zero allocation across 300M ops.
  • No fixture changed. Normalising both revisions of OracleCorpus.cs for the tuple widening makes them
    byte-identical to main, across ~340 migrated call sites.
  • Build 0 warnings, dotnet format --verify-no-changes clean, clean-room passed, no golden snapshot moved.

Known and disclosed

A non-/Root object rewritten at the wrong generation is still silent — the object resolves to nothing,
with no exception. AppendRevision guards /Root specifically because that one fails loudly at reopen. The
API is internal, both in-repo callers now pass real generations, and the XML doc states this explicitly.

9eddcd5 is unrelated to #121: it pins SigningTime in a determinism test that was reading the live clock.
Kept as a separate commit; see #194.

@Tim81

Tim81 commented Aug 18, 2026

Copy link
Copy Markdown
Owner Author

Blocked — adversarial review found a regression that breaks valid documents. Not ready to merge despite green CI.

The parser discards the generation, so the new check rejects conforming files

PdfObjectParser.cs:202 has the generation token in hand and drops it:

var objNum = ParseObjectNumber(firstIntToken.Raw, "indirect reference object number");
return new PdfIndirectReference(objNum);      // peekTok — the generation — thrown away

Every reference parsed from a real document therefore carries Generation == 0, while
Resolve(PdfIndirectReference) now enforces reference.Generation == entry.Generation. The check is
not "does the reference match the cross-reference table" — it is "the table's generation must be 0".
Any object legitimately recorded at a nonzero generation becomes unresolvable.

Reproduced independently, twice:

Input main This branch
Single revision, /Extra 10 1 R + 10 1 obj + xref … 00001 n resolves null
Canonical incremental update: rev 2 frees object 5, rewrites it as 5 1 obj resolves to the new value null
Catalog at generation 1 (1 1 obj, trailer /Root 1 1 R) opens Open throws /Root does not resolve to a dictionary — unopenable

ResolveLength was switched to the enforcing overload in the same commit, so a stream whose /Length
points at a gen≠0 object now silently falls back to the endstream scan for the same reason.

Why the suite is green. Every generation-bearing reference in GenerationNumberTests is
hand-constructed as new PdfIndirectReference(10, 2). Nothing resolves a generation-bearing reference
that came out of the parser. That test — resolving a nonzero generation read from the document — is
the actual acceptance criterion for #121, and it was missing. This is the "test passes while dodging the
feature" pattern CLAUDE.md warns about, and it is the second time on this branch that a fully green
run concealed a defect.

Three more, all confirmed

  1. ResolveStream(PdfIndirectReference) has no callers. Every real stream lookup uses the
    generation-agnostic overload — PreflightContext.cs:420-421 is the entry point for ~40 conformance
    rules — while PreflightContext.Resolve goes through the enforcing path. For a gen≠0 object the same
    reference resolves to null as a dictionary but to a live ParsedStream, so two rules examining one
    object reach opposite conclusions.
  2. A space-padded generation now aborts the document. XrefParser.cs:278-282 parses with
    NumberStyles.None, which rejects leading whitespace, so 0000000123 0 n throws out of
    Open. That file opens on main; the field was simply never read before.
  3. The result depends on call order. A cached object carries no record of the generation it was
    parsed at, so a generation-agnostic Resolve(10) that warms the cache lets a later
    Resolve(10 2 R) return the object it should have rejected. PreflightContext enumerates
    ObjectNumbers and resolves each generation-agnostically, so the cache is routinely warm first.

Verified sound — not re-litigating these

WriteTo is byte-identical for generation 0 (every new PdfIndirectReference( call site in src/ is
single-arg, so the write path can never emit a nonzero generation; signing's fixed-width placeholders are
/ByteRange and /Contents, not references). Object streams genuinely enforce generation 0 rather than
assuming it. /W[2] == 0 correctly defaults to 0. The hybrid free-entry rescoping holds up against
further cases, including a /XRefStm that frees an object its own classic table declares live.

Fixes are in progress. A second review pass is still running.

Tim81 added 3 commits August 18, 2026 09:12
PdfIndirectReference carried only an object number and hardcoded
" 0 R" on write, and the xref table was keyed on object number
alone, so 10 2 R resolved to whatever object 10 held at generation
0. Store the generation on XrefEntry and validate it on resolve; a
mismatch (including one against an object a later revision freed)
now resolves to nothing instead of the wrong object. Classic-table
'f' entries were also silently skipped rather than recorded, which
let an older revision's stale entry resurface through a freed
object number.

Prerequisite for decryption (#97): R2-R4 per-object key derivation
consumes the generation.
freed was shared between a revision's classic table and that same
revision's /XRefStm, but a hybrid-reference file marks an object 'f'
in the classic table precisely because its live definition is in the
accompanying stream (ISO 32000-2 §7.5.8.4) — the object is free only
to a reader that cannot see the stream. The shared set made the
classic 'f' entry block the stream's own live entry for the same
object in the same revision, making it unresolvable.

Scope the free set per revision: classic table and /XRefStm each
record into a local set, suppressing only against frees carried in
from a newer revision, and the local set is folded into the
cross-revision set only after both halves of the revision have had a
chance to add the object back. Classic-wins precedence between the
two halves is unchanged.

Also restores the cache-first fast path in Resolve/ResolveStream for
the generation-agnostic case, so a lookup with no generation to check
still costs one dictionary lookup on a hit.
ParseIntegerOrReference parsed the middle "G" token of "N G R" only to
peek past it and throw it away, so every reference read from a real
document looked like generation 0 no matter what the file said. The
enforcement added in the previous two commits then rejected any object
legitimately at a nonzero generation, including a catalog referenced
as "1 1 R" — PdfReader.Open threw "/Root does not resolve to a
dictionary" outright, and a canonical incremental update that reuses a
freed object number at a higher generation resolved to nothing. Carry
the generation through, validated by the same helper the "N G obj"
header already uses.

Two more gaps surfaced alongside it:

- A cache entry populated by a generation-agnostic Resolve(int) call
  carried no record of what generation it was actually parsed at, so a
  later generation-bearing call for the same object could pass the
  xref check, hit the warm cache, and return a value nothing had ever
  verified against the requested generation. Cache the parsed
  generation alongside the value and re-check it on a hit.
- PreflightContext.ResolveStream unwrapped a reference to its object
  number before calling Reader.ResolveStream, bypassing the new
  generation check entirely — the same reference could resolve to a
  live dictionary through Resolve and to null through ResolveStream.
  Route it through the generation-aware overload instead.

Also: the classic-table and xref-stream generation fields are now
parsed leniently (space-padded, or a value overflowing int in an
8-byte xref-stream row, falls back to generation 0) rather than
aborting a document that used to open fine — this field was never
read before this change. GetHashCode uses a deterministic combination
instead of HashCode.Combine, which salts with a per-process seed;
this type shipped Stable in 2.0.0.

Left two round-trip normalizers (PdfObjectRemapper and
LinearizedCrossReferenceBuilder) hardcoding generation 0, with a
comment at each explaining why that is still safe today — fixing them
is v3.0 read-modify-write territory (#101).
@Tim81
Tim81 force-pushed the feat/121-generation-numbers branch from 446d8ca to 7f517b0 Compare August 18, 2026 07:12
Tim81 added 5 commits August 18, 2026 10:28
The read path was fixed; the write path was not, and it broke the
AppendRevision case DssBuilder and ArchiveTimestampBuilder both use
for LTV and archive-timestamp signing. Given a catalog at generation
1, AppendRevision wrote its re-emitted object header as "N 0 obj" and
its xref entry as "... 00000 n" (both hardcoded), while the trailer's
/Root now carried the real generation 1 from the parsed reference.
Reopening the result threw "/Root does not resolve to a dictionary".
Rewriting any other existing object at the wrong generation failed
the same way but silently — Resolve returned null, no exception, and
a page or font just vanished.

PdfIndirectObject gains a Generation property and a three-argument
constructor; IncrementalCrossReferenceBuilder writes the real
generation into both the object header and the xref entry;
AppendRevision's parameter and IncrementalCrossReferenceBuilder's
writtenObjects both become (ObjectNumber, Generation, Value) triples,
and AppendRevision now checks that a rewritten /Root's generation
agrees with the trailer before writing anything, rather than
producing an inconsistent file. DssBuilder and ArchiveTimestampBuilder
thread the real generation through for every object they rewrite
(catalog in both; first page in ArchiveTimestampBuilder) while new
objects stay at generation 0. The PdfObjectRemapper and
LinearizedCrossReferenceBuilder comments justifying their own
hardcoded generation 0 no longer claim a read-then-rewrite path
doesn't exist — AppendRevision is one and ships today; those two
specifically are just never reached by it.

Also in this pass:

- Nine call sites still unwrapped a reference to its object number
  before calling Resolve/ResolveStream, bypassing the generation
  check the previous commit added elsewhere. SeparationConsistencyRule
  tried the number-only path first and returned on success, so
  enforcement was fully bypassed there rather than merely
  inconsistent. All nine now go through the reference-aware overload.
- An xref generation field that is genuinely unparseable (not merely
  sloppy) is recorded as unknown rather than guessed at 0: with xref
  and header disagreeing, guessing 0 made a legitimately reachable
  object unresolvable at every generation. XrefEntry.UnknownGeneration
  marks it, and the object's own header becomes the sole authority for
  that one entry instead.
- A reference's own generation token that overflows int no longer
  aborts the parse. It saturates to int.MaxValue, which cannot match
  any real xref entry — the same outcome an ordinary mismatch already
  produces, not a document-wide failure.
- Given the above, the xref is now the single authority for an
  object's generation whenever it parses cleanly, instead of also
  requiring the object's own header to agree. Requiring both made a
  disagreement (however it arose) unresolvable at any generation
  rather than resolvable at the one the xref actually recorded.
- PdfIndirectReference's two-argument constructor now rejects a
  negative generation.
- Resolve/ResolveStream fold the entry's authoritative generation into
  the cache tuple, so a warm hit costs one dictionary lookup instead
  of an xref lookup followed by a cache lookup.

CHANGELOG documents the three behaviour changes this leaves on
PdfIndirectReference, a Stable type since 2.0.0: WriteTo emits the
real generation, Equals narrowed, GetHashCode differs.
)

The freed-entry tracking added earlier removes a recovery behaviour
some producers may have relied on: a tool that writes a full "0 N"
subsection on every incremental update, marking every untouched
object 'f' instead of only the ones it actually freed, used to have
those spurious frees silently overridden by xref.TryAdd resurrecting
the older-revision entry. Under the current tracking they are treated
as genuine deletions instead. No real-world fixture exhibiting this
has turned up; note it near the freed set so the interaction with
PR #193's xref-rebuild fallback is visible if one does.
PrepareForSigning_withPins_isByteIdentical pinned Timestamp and
DocumentId but passed a default SignaturePlaceholderOptions with no
SigningTime, so PdfDocument.PrepareForSigning fell back to the live
clock (options.SigningTime ?? DateTimeOffset.UtcNow). The two Build()
calls the test compares straddling a wall-clock second produced one
differing byte inside /M, an intermittent failure unrelated to
whatever the test happened to be exercising. Not caused by #121 or
any change in this branch — reproduces on an unmodified checkout.

A determinism test that reads the clock is not testing determinism.
…121)

ParseGenerationLenient's out-of-range fallback saturated at int.MaxValue on
the theory that no real xref entry could ever hold that value. XrefParser
only routed a field to XrefEntry.UnknownGeneration when it exceeded int
range, so a /W field wide enough to hold int.MaxValue recorded it as an
ordinary generation — and a reference whose own token overflowed int (or
even long) collapsed onto that exact saturated value and resolved. The
object-number half of the same parser is careful to avoid precisely this
shape of aliasing; the generation half reintroduced it.

ISO 32000-2 §7.5.4 bounds a generation number at 65535, not int.MaxValue.
Both XrefParser paths (classic table, xref-stream type-1) now route
anything above 65535 to UnknownGeneration, and ParseGenerationLenient
saturates at the same ceiling instead of only on true overflow — an xref
entry can never legitimately hold more than 65535 either way, so nothing
above it can be a real match, and nothing above it is safe to let a
header-authority fallback pass through uncapped once the xref stops having
an opinion on that entry.

This also closes the write side: DssBuilder and ArchiveTimestampBuilder
only ever thread a PdfIndirectReference.Generation parsed off the source
document into AppendRevision, and that value is now guaranteed to fit the
5-digit xref field IncrementalCrossReferenceBuilder writes — a document
whose /Root named a larger generation fails to open at all, so neither
signing entry point can ever reach the field-width guard with a
document-supplied value. The guard itself is untouched: it still protects
a caller that builds an out-of-range generation by hand.

CHANGELOG: moved the four Stable/Shipped member changes (PdfIndirectReference
.WriteTo/Equals/GetHashCode, PdfIndirectObject.Reference) from Fixed to
Changed — Equals narrowing is a genuine break for anyone keying a
collection on the type, not merely a fix.
The single Fixed bullet ran 34 lines and packed five distinct changes
into one paragraph — nearly four times the longest bullet anywhere else
in the file, where 2.0.0 established a 2-9 line convention with 5 the
norm. Nobody scanning the changelog for what moved would find it.

Split into four bullets, one per change, each with its own bold lead-in:
the core read/write generation fix, the AppendRevision/signing round-trip
fix (its own bullet, since a rewritten non-catalog object silently
resolving to nothing is the failure most likely to bite someone), the
freed-object tracking, and generation-field leniency. Every fact that
was in the original bullet is still here, just distributed. Ran the
avoid-ai-writing skill over the result per CLAUDE.md and tightened one
over-compressed closing sentence that chained a semicolon onto an
em-dash parenthetical.
@Tim81
Tim81 merged commit f379554 into main Aug 18, 2026
3 checks passed
Tim81 pushed a commit that referenced this pull request Aug 18, 2026
Rebasing onto #192 left the reconstruction scanner calling the old
one-argument XrefEntry.Uncompressed. The scanner already parses the
generation out of each "N G obj" header and was discarding it, so the
obvious repair — passing 0 — would have recorded every recovered object
at generation 0 and made a legitimately nonzero-generation object
unresolvable at every generation.

Reconstruction runs precisely when the cross-reference table is unusable,
so the object header is the only authority left for a generation. Carry
it through, and record anything outside the ISO 32000-2 §7.5.4 range of
0-65535 as unknown, matching how the xref-side generation fields already
handle a value they cannot trust.
@Tim81
Tim81 deleted the feat/121-generation-numbers branch August 28, 2026 14:40
Tim81 added a commit that referenced this pull request Sep 6, 2026
The reader dropped PDF object generation numbers: PdfIndirectReference carried
only an object number and hardcoded " 0 R" on write, the parser discarded the
middle field of a parsed N G R, and the cross-reference table was keyed on
object number alone, so 10 2 R resolved to whatever object 10 held at
generation 0.

The generation is now stored on XrefEntry and validated on resolve, with the
cross-reference table as the single authority for a generation it actually
records. Where it has no opinion — a garbled field, or one above the ISO
32000-2 §7.5.4 ceiling of 65535 — the entry is marked unknown and the object's
own header takes over, rather than guessing 0 and making a reachable object
silently unresolvable.

PdfIndirectObject gains a matching Generation, because an incremental update
preserves an object's generation (§7.5.4/§7.5.6). Without it AppendRevision
wrote a trailer whose /Root disagreed with the object header beside it, and
the long-term-validation and archive-timestamp signing paths produced files
that could not be reopened.

Prerequisite for decryption (#97): R2-R4 per-object key derivation consumes
the generation.

Closes #121.
Tim81 added a commit that referenced this pull request Sep 6, 2026
The reader dropped PDF object generation numbers: PdfIndirectReference carried
only an object number and hardcoded " 0 R" on write, the parser discarded the
middle field of a parsed N G R, and the cross-reference table was keyed on
object number alone, so 10 2 R resolved to whatever object 10 held at
generation 0.

The generation is now stored on XrefEntry and validated on resolve, with the
cross-reference table as the single authority for a generation it actually
records. Where it has no opinion — a garbled field, or one above the ISO
32000-2 §7.5.4 ceiling of 65535 — the entry is marked unknown and the object's
own header takes over, rather than guessing 0 and making a reachable object
silently unresolvable.

PdfIndirectObject gains a matching Generation, because an incremental update
preserves an object's generation (§7.5.4/§7.5.6). Without it AppendRevision
wrote a trailer whose /Root disagreed with the object header beside it, and
the long-term-validation and archive-timestamp signing paths produced files
that could not be reopened.

Prerequisite for decryption (#97): R2-R4 per-object key derivation consumes
the generation.

Closes #121.
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.

Reader: object generation number is dropped (xref keyed by object number only)

1 participant