Modern Apps git

← Modern-Apps.git

pdf: harden renderer against malformed input, add test suites (#321)

Commit
cfd09990b90742474e768d747ac8aa11f591cdd2
Author
vayun-mathur <[email protected]>
When
2026-08-31 04:30 UTC (3 months ago)
Parents
318fadf

Diff

pdf/build.gradle.kts
diff --git a/pdf/build.gradle.kts b/pdf/build.gradle.ktsindex 1f68c2b9b2..d51485396b 100644--- a/pdf/build.gradle.kts+++ b/pdf/build.gradle.kts@@ -13,6 +13,14 @@ android {     defaultConfig {         applicationId = "com.vayunmathur.pdf"     }+    // The wire parser logs via android.util.Log on its clamp/desync/non-affine paths, and the+    // structural rasterizer tests drive drawSafePage through a spy android.graphics.Canvas. Both+    // need the stub android.jar to return defaults instead of throwing "not mocked" (same as+    // :cast, :maps). Robolectric-run tests are unaffected: they replace android.jar outright.+    testOptions.unitTests.isReturnDefaultValues = true+    // Robolectric reads the merged manifest and resources through the AGP-generated+    // com/android/tools/test_config.properties, which only exists when this is on.+    testOptions.unitTests.isIncludeAndroidResources = true }  androidComponents {@@ -38,4 +46,10 @@ dependencies {     implementation(libs.androidx.camera.view)     implementation(project(":library:image"))     implementation(project(":library:ocr"))++    // drawSafePage paints straight onto an android.graphics.Canvas via Typeface/Paint/Matrix,+    // none of which the unit-test stub android.jar implements — Typeface.create returns null, so+    // every Text primitive throws before it reaches the render-mode-3 paint guard. Robolectric+    // supplies a real Skia-backed graphics stack so those tests can assert actual pixels.+    testImplementation(libs.robolectric) }
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.ktindex c4b48baca7..7820a7d36b 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -252,6 +252,16 @@ object SafePdfParser {         var outermostSoftMaskStart = -1         for (primIndex in 0 until count) {             if (!buf.hasRemaining()) break+            val primStart = buf.position()+            // The robustness contract above: a primitive cut short must keep the clean prefix,+            // never discard the page, because renderPage can only turn a throw into a null page+            // and the UI shows that as an indefinite spinner. The per-field `throw`s below+            // predate that contract and each one killed a whole page over its last primitive;+            // catching here converts every one of them — plus any unguarded relative get that+            // raises BufferUnderflowException — into the same `break` tag 13 already chose.+            // Deliberately not reindented: this wraps the `when` untouched so the guard is a+            // reviewable seven lines rather than a whole-body reindent.+            try {             when (val tag = buf.get().toInt() and 0xFF) {                 TAG_TEXT -> {                     val x = buf.float@@ -545,6 +555,15 @@ object SafePdfParser {                     break                 }             }+            } catch (e: RuntimeException) {+                android.util.Log.w(+                    TAG,+                    "primitive $primIndex of $count failed to decode at offset $primStart " ++                        "(wire v$wireVersion), keeping the ${primitives.size} that decoded cleanly",+                    e,+                )+                break+            }         }          // A page cut short — by the count clamp, a desync, or a truncated buffer — can end
pdf/src/main/rust/README.md
diff --git a/pdf/src/main/rust/README.md b/pdf/src/main/rust/README.mdindex 37a8bdf251..fa7ec8c59a 100644--- a/pdf/src/main/rust/README.md+++ b/pdf/src/main/rust/README.md@@ -50,11 +50,12 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   owns the whole decompressed embedded font program — used to be rebuilt on every   `interpret_content` call, so a font shared by *N* pages was parsed *N* times to   render and another *N* times to build the search index. The cache is keyed by-  the font dictionary's object id and is scoped to a single top-level operation,-  then dropped: an object id is only a complete key while the document is-  unmutated, so a short-lived cache is correct where a global one would serve-  stale fonts after a `docedit`. Direct (non-indirect) font dictionaries are-  never cached.+  the font dictionary's object id *plus* a hash of that dictionary with every+  indirect reference resolved, so a colliding id from another document cannot be+  served, and is scoped to a single top-level operation, then dropped: even that+  key is complete only while the document is unmutated, so a short-lived cache is+  correct where a global one would serve stale fonts after a `docedit`. Direct+  (non-indirect) font dictionaries have no id and are never cached. - **Embedded glyph outlines**: TrueType/OpenType, bare CFF (`/Type1C`,   `/CIDFontType0C`) and bare Type 1 programs are parsed and their real glyph   contours are emitted as vector fills/strokes (`outlines.rs`), so paint modes@@ -176,8 +177,108 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   Ink, Highlight, Underline and StrikeOut (via `/QuadPoints`, `/C`, `/IC`,   `/BS`). +## Known cross-fix interaction risks (round-3 review)++These came out of a review of the ~90 changes that landed across rounds 1 and 2,+looking specifically for fixes that conflict, cancel or double-apply rather than+for individually-wrong code. All were verified against the working tree. The+first two are open because they live outside the reviewing agent's file set.++- **Optional content does not gate form XObject content.** `oc_stack` is a local+  in `interpret_content_seeded` and is not threaded into nested streams, so+  `/OC1 BDC /Fm0 Do EMC` with `OC1` OFF paints the form's whole contents —+  and, because the `/BBox` clip is suppressed by the same hidden flag, paints+  them *unclipped*. Round 1 fixed the BMC/BDC/EMC balance and round 2 fixed the+  text operators, but the `Do` recursion was never gated. An XObject's own `/OC`+  key (§8.11.3.3) *is* honoured; it is only the BDC-bracket state that is lost.+- **The §11.6.6 group alpha reset is disabled whenever a soft mask is active.**+  Round 2 made the transparency-group push and the soft-mask bracket mutually+  exclusive (`should_emit_group = is_transparency_group && !use_smask`), and the+  reset of `alpha_fill`/`alpha_stroke` to 1.0 is gated on the push having+  happened. A group form drawn with both `/ca < 1` and an `/SMask` therefore+  applies `ca` to every element inside the group instead of once to the+  composited result. Same hole when `MAX_PRIMITIVES` or the group-depth cap+  demotes the push. Identical output for non-overlapping content; over-darkens+  overlapping content.+- **Annotation `/CA` used to be applied twice** — fixed. `render_annotation`+  scaled the alpha of every prim it had just emitted, which hit both a nested+  `GroupPush`'s alpha *and* every prim inside that group (CA² on the contents),+  and also hit the soft-mask group's own prims, which `wrap_with_soft_mask`+  appends after `SoftMaskContent` in the same range — so `/CA` altered the mask+  rather than the content. It now wraps the appearance in one+  `GroupPush{alpha: ca}`/`GroupPop`, which is the §12.5.2 + §11.6.6 model and+  applies the opacity once, at composite time.++Verified clean, with the evidence, so a future change knows what it is allowed to+disturb:++- **Mask polarity is inverted exactly once on every convention.** `/Decode` is+  read in exactly five places in `images.rs`, and `decode_mask_stream_gray`+  deliberately does not read it at all — polarity comes only from its+  `MaskPolarity` argument, and the caller applies `/Decode` once afterwards. The+  CCITT stencil path folds `/Decode` into its `black_bit` and then calls+  `stencilize` with `invert: false` precisely so it is not re-applied. The CCITT+  and JBIG2 stencil paths are now covered by tests as well as by reading —+  including `/BlackIs1`, the second inversion source, and the `/BlackIs1` ++  `/Decode [1 0]` pair that cancel. `stencilize` zeroes alpha and leaves the RGB+  of a transparent pixel as the raster left it, so those tests state polarity in+  terms of alpha; the colour beneath an unpainted pixel is not part of the+  contract. The DCT and JPX mask branches remain untested.+- **Neither round-2 cache leaks.** The font cache is a `thread_local` installed+  by an RAII `FontCacheScope` (one per page render, one per search-index build)+  and keyed by the font's `ObjectId` plus a hash of its dictionary with every+  indirect reference *resolved* — not by resource name, so two+  pages both binding `/F1` to different font objects stay distinct, and not by+  the `Document`'s address, which is not an identity: `Document`s are held by+  value in the registry's `IndexMap`, so one can be replaced at the address+  another just vacated and a scope spanning both would serve the first+  document's fonts for the second. Resolving through the references also catches+  two font dicts that are byte-identical but whose `/Widths 7 0 R` names+  different arrays. It has no+  invalidation hook and needs none: it does not exist between operations, so a+  `docedit` mutation cannot be served a stale entry. Residual fragility: the key+  is complete only while the document is unmutated *within* a scope, which is+  what scoping it to one top-level operation buys. The soft-mask+  coalescing memo is a local in `interpret_content_seeded`, and its key includes+  the group id, mask type, the CTM as exact `f64::to_bits()`, `/BC` and the whole+  256-byte `/TR` LUT, so a mask cannot be reused at a different CTM.+- **Clip and group brackets balance on every path**, including the truncation+  and cap paths: every structural pop is emitted *without* a `MAX_PRIMITIVES`+  guard while every content push has one, so the cap can never suppress a+  closer, and the end-of-stream drain closes whatever is left.++### Deliberate omission: GB18030's four-byte plane++Now implemented. `EncodingCMap::code_len` dispatches on the first byte alone,+which cannot see GB18030's four-byte plane (distinguished from its two-byte plane+only by the second byte being `0x30`-`0x39`). Round 2 left this alone on the+grounds that widening the lookahead for every font to fix a rare case was not+obviously right. `code_len_at` resolves it as a *strict refinement* instead: it+only ever chooses a longer range, and only when that range also matches the+second byte. No other predefined codespace has two ranges of different length+sharing a first byte, so for every font but GB18030 the answer is provably+identical to `code_len` — which removes the tradeoff that made the deferral+reasonable. `gb18030_four_byte_plane_needs_the_second_byte` asserts both halves,+exhaustively over all 256 first bytes for the other families.++ ## Genuinely unsupported (documented, not silently skipped) +Per-feature spec coverage, and the rationale for each deliberately-ignored+feature: [SPEC_COVERAGE.md](SPEC_COVERAGE.md).++### An OCG listed in both `/ON` and `/OFF` renders as OFF++§8.11.4.3 gives `/ON` and `/OFF` as overrides of `/BaseState` and does not spell+out the result when the same group appears in both. `OcConfig::is_ocg_visible`+applies them in the order Table 101 lists them — `/BaseState` (default ON), then+`/ON`, then `/OFF` — so `/OFF` is applied last and wins, which is what mainstream+viewers do and therefore how a file authored against them was meant to look.++`/BlackPoint` on CIE-based spaces (§8.6.5.2, §8.6.5.4) is a genuine deviation of+this kind: the conversion adapts from `/WhitePoint` only, so the effect is a+slight shift in the darkest tones rather than missing content.+ > ### WARNING: Redaction does not remove content — it covers it > > **Do not rely on `/Redact` to scrub sensitive data.** Applying a redaction@@ -190,9 +291,7 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes. > This is a **security** limitation, not a fidelity one — the page looks redacted > while the data is still there. The removal is a heuristic over text-showing > operators, not a content-stream rewrite. There is currently no user-facing-> warning on the apply action. It also compounds with the stale search index below:-> in the same session, search can still surface and highlight the text you just-> redacted.+> warning on the apply action.   - **Public-key / certificate encryption** (`/Filter /Adobe.PubSec`): decryption@@ -358,18 +457,20 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   bracket per painting operator re-expanded the mask for every operator and pushed   pages past the primitive cap, truncating real content — a visibly worse outcome   than a slight blend error.-- **The search index is never invalidated after a document edit**: redacting,-  adding or deleting an annotation, filling a form field, or moving, removing or-  rotating a page does **not** rebuild the text index for the rest of the session.-  Search then returns hits computed from the pre-edit text and highlights-  rectangles that point at content which has moved or no longer exists. The-  privacy-relevant case compounds with the redaction warning above: **search can-  still surface and highlight text that was just redacted.** `invalidate_index`-  exists and is correct, but has no callers — the mutators take the registry lock-  directly rather than through a single accessor, so there is no one place that-  observes "this document changed", and the ~25 handle-taking mutators across-  `docedit.rs`, `annotations.rs` and `forms.rs` would each have to remember to call-  it. Closing an unused document is the only thing that currently evicts an index.+- **The search index is invalidated by an RAII guard, not by the mutators+  themselves**: `ensure_index` is a pure memo keyed by handle and never re-reads+  the document, so the "a search answers from the current document" contract rests+  entirely on every mutating entry point dropping the entry. `invalidate_index`+  used to have no callers at all, which meant redacting, annotating, filling a+  form field or moving a page left search answering from the pre-edit text —+  including, in the privacy-relevant case, surfacing and highlighting text that+  had just been redacted. Each mutating `extern` fn in `jni_bindings.rs` now holds+  an `InvalidateSearchIndex` guard for the whole call, so the eviction happens on+  the unwind path too and a panic that leaves a document half-edited cannot leave+  a matching index behind. The residual fragility is that it is per-entry-point+  rather than structural: a *new* mutating binding that forgets the guard+  reintroduces the staleness, because there is still no single accessor that+  observes "this document changed". - **Form fields with no appearance stream are invisible**: a field that relies on   the viewer to build its own appearance (`/NeedAppearances` set, no `/AP`)   renders as nothing at all rather than as a box showing its value, because
pdf/src/main/rust/SPEC_COVERAGE.md
diff --git a/pdf/src/main/rust/SPEC_COVERAGE.md b/pdf/src/main/rust/SPEC_COVERAGE.mdnew file mode 100644index 0000000000..a13533d2f3--- /dev/null+++ b/pdf/src/main/rust/SPEC_COVERAGE.md@@ -0,0 +1,387 @@+# Spec coverage matrix (ISO 32000-1)++A per-feature inventory of what this renderer implements, what it deliberately ignores,+and — for each gap — how likely it is to appear in a real document and how visible its+absence would be.++The point of this document is that an **unimplemented** feature never shows up in code+review, because there is no code to review. It produces the same user-visible symptom as+a bug ("things that should be there are not rendered") while looking clean from the+inside. So the inventory is exhaustive even where the answer is boring.++## How to read this++| Status | Meaning |+| --- | --- |+| **full** | Implemented to spec, to the fidelity the flat-primitive wire format allows. |+| **partial** | Implemented, with a named limitation. The limitation is always stated. |+| **ignored** | Recognised and deliberately given no effect, with the reason stated. Not an oversight. |+| **missing** | Not implemented. Triaged below. |++"Ignored" is a real answer, not a euphemism. Round 2 removed an overprint approximation+because simulating it was **worse** than ignoring it: `white MULTIPLY dst == dst` turned+white knockout rectangles into no-ops and let content that was meant to be covered+reappear. Where a partial simulation would change the common case in order to improve the+rare one, this renderer ignores the feature and says so.++Triage columns are a judgement about real-world producers (Acrobat/Distiller, Illustrator,+InDesign, Word, LaTeX, Ghostscript, scanner firmware), not about the spec. A feature no+real producer emits is not worth implementing however cleanly it is specified.++---++## 1. Content-stream operators (Annex A, Table A.1)++**All 73 operators in Table A.1 are recognised.** There is no operator that falls through+to the catch-all arm, so there is no case where the interpreter silently skips a construct+it does not know about. The dispatch is the single `match op.operator.as_str()` in+`src/interpret.rs`.++`ID` is not listed separately: `lopdf` delivers an inline image as one `BI` operation whose+operand is the whole stream, so `BI`/`ID`/`EI` are one unit here (`EI` is matched as a+no-op for streams that emit it separately).++### Graphics state++| Op | Status | Note |+| --- | --- | --- |+| `q` `Q` | full | Bounded by `MAX_GRAPHICS_STACK_HARD`; overflow is counted so an unmatched `Q` cannot pop a frame it does not own. |+| `cm` | full | Non-finite results rejected, since a poisoned CTM makes whole regions vanish. |+| `w` `J` `j` `M` `d` | full | |+| `i` | full | Feeds `bezier_steps_for_flatness` (§10.6.2). |+| `gs` | **partial** | Table 58 subset — see §2. |+| `ri` | ignored | §8.6.5.8. See `/RI` in §2. |++### Path construction and painting++| Op | Status | Note |+| --- | --- | --- |+| `m` `l` `c` `v` `y` `h` `re` | full | `l`/`c` with no current point are no-ops per §8.5.2.1 rather than fabricating a subpath. |+| `S` `s` `f` `F` `f*` `B` `B*` `b` `b*` `n` | full | Including pattern fills/strokes and soft-mask bracketing. |+| `W` `W*` | full | One `ClipPush` per operator, carrying the full path (beziers retained) so holes survive. |+| `sh` | full | Shading types 1-7 all real. Every content stream that can host one now seeds its clip extent — see §7 item 1 for why that was load-bearing, and for the single documented remainder (Type 3 CharProcs). |++### Colour++| Op | Status | Note |+| --- | --- | --- |+| `CS` `cs` | full | Selecting a space resets the colour to its initial value (§8.6.8). |+| `SC` `sc` `SCN` `scn` | full | Including `/Pattern` with an underlying base space for uncoloured (`/PaintType 2`) patterns. |+| `G` `g` `RG` `rg` `K` `k` | full | |++### Text++| Op | Status | Note |+| --- | --- | --- |+| `BT` `ET` | full | `ET` commits an accumulated text clip. |+| `Tc` `Tw` `Tz` `TL` `Ts` `Tf` | full | |+| `Tr` | **partial** | Modes 0-3 full. Clip modes 4-7 build the clip from substitute-glyph records, so **Type 3 glyphs and glyphs with no recoverable Unicode contribute nothing to it**. See §7. |+| `Td` `TD` `Tm` `T*` | full | |+| `Tj` `TJ` `'` `"` | full | Vertical writing mode (`/W2`, `/DW2`) honoured on the advance and the position vector. |++### XObjects, images, marked and compatibility++| Op | Status | Note |+| --- | --- | --- |+| `Do` | full | Image and Form subtypes. `/Subtype /PS` is correctly ignored (§8.8.2 says a reader shall ignore PostScript XObjects). Form `/BBox` clip, `/Matrix`, `/Group`, and `/OC` all honoured. Recursion bounded at depth 10. The form recursion is gated on the surrounding BDC bracket's hidden flag (§8.11.2) — see §7 item 0. |+| `BI` … `EI` | full | With a lenient re-tokenizer, because `lopdf` wraps inline-image parsing in a nom `cut(...)` and one unparseable image used to blank the whole stream. |+| `BMC` `BDC` `EMC` | full | Optional content, with inherited hiding (§8.11.4.5) and 1:1 nesting. Every construct that can paint is gated on the hidden flag: paths, images, `sh`, patterns, text (via render mode 3, so hidden text stays searchable), Type 3 CharProcs (same), soft-mask brackets, and the form recursion. |+| `MP` `DP` | ignored | Marked-content *points*: no matching `EMC`, so correctly excluded from the stack. |+| `BX` `EX` | ignored | Correct by construction. §7.8.2 requires unrecognised operators inside a compatibility section to be ignored along with their operands; every unrecognised operator is already ignored everywhere, and `lopdf` groups operands with their operator, so the operands go too. |+| `d0` `d1` | **partial** | Recognised and treated as no-ops, which is right for the width/bbox declaration itself. **Not enforced:** §9.6.5 says a `d1` glyph is a shape only and colour operators inside it *shall be ignored*. Here they take effect. See §7. |++---++## 2. ExtGState parameters (§8.4.5, Table 58)++Implemented in the `"gs"` arm of `src/interpret.rs`. All 26 keys accounted for.++| Key | Status | Spec | Real-world likelihood | Visibility if absent |+| --- | --- | --- | --- | --- |+| `/LW` | full | 8.4.3.2 | common | — |+| `/LC` | full | 8.4.3.3 | common | — |+| `/LJ` | full | 8.4.3.4 | common | — |+| `/ML` | full | 8.4.3.5 | common | — |+| `/D` | full | 8.4.3.6 | common | — |+| `/FL` | **full (added this round)** | 8.4.5 / 10.6.2 | uncommon | low — visibly faceted large curves |+| `/Font` | **full (added this round)** | 8.4.5 / 9.3.1 | rare | high — text at the wrong place, spacing and encoding. Two documented limits: the registration bypasses the font cache, and an *inherited* selection does not resolve inside a nested stream (as is already true of an inherited `Tf` resource name). |+| `/BM` | full | 11.3.5 | very common | — |+| `/SMask` | full | 11.6.5 | very common | — |+| `/CA` | full | 11.6.4.4 | very common | — |+| `/ca` | full | 11.6.4.4 | very common | - |+| `/RI` | ignored | 8.6.5.8 | common (as `/RelativeColorimetric`) | none |+| `/OP` `/op` `/OPM` | ignored | 8.6.7 | common in print PDFs | none on an RGB device; **simulating it is actively harmful** |+| `/TR` `/TR2` | ignored | 10.4 | rare non-identity | see below |+| `/HT` | ignored | 10.5 | uncommon | none |+| `/BG` `/BG2` | ignored | 10.3 | uncommon | none |+| `/UCR` `/UCR2` | ignored | 10.3 | uncommon | none |+| `/SM` | ignored | 10.6.3 | common | none |+| `/SA` | ignored | 10.6 | common | very low |+| `/TK` | ignored | 9.3.8 | rare | very low |+| `/AIS` | ignored | 11.6.4.3 | rare | low |++### Why `/TR` and `/TR2` are ignored++This was the leading suspicion going into this round, so it is worth stating the reasoning+rather than the conclusion.++`/TR` is real and it does apply to **all** painting, not only to soft masks. But it sits in+Clause 10, *Rendering*, alongside halftones, black generation and undercolour removal, and+§10.4 defines it as operating on the **device colour components after conversion into the+device colour space**. It is press calibration: the mechanism by which a document+compensates for a specific output device's tone response. It is not a description of what+the page looks like.++Three things follow.++1. Our device colour space is 8-bit sRGB assembled from whatever space the document used.+   A curve authored to linearise a CMYK press applied to those components is not "more+   correct" — it is a different wrong answer.+2. Honouring it would have to be all-or-nothing, and it cannot be. Fill, stroke and text+   colours are computed in Rust and could be remapped through a LUT. A `DCTDecode` image is+   handed to the renderer as **JPEG bytes** and cannot be. So an inverting `/TR` — the one+   case where `/TR` is dramatic rather than subtle — would invert the vector artwork and+   leave every photograph alone. A uniformly wrong page is better than a half-inverted one.+   This is round 2's overprint lesson applied verbatim.+3. Non-identity `/TR` is rare in the wild. The overwhelmingly common occurrences are+   `/TR /Identity` and `/TR2 /Default`, which are no-ops by definition.++**The half of transfer functions that genuinely matters is implemented.** §11.6.5.2's soft+mask `/TR` is a completely different parameter: it maps the *mask value*, not device+colour, it is device-**in**dependent, and an inverting one (`{ 1 exch sub }`, or Type 2 with+`/C0 [1] /C1 [0]`) is the standard idiom for "mask out where the group is bright" — so+ignoring it hides exactly the wrong half of the content. That one is parsed+(`functions::read_transfer_lut`), sampled to a 256-entry LUT, carried on the wire as+`SoftMaskTransfer` (tag 13) and applied by the renderer. Note the asymmetry: the same key+name in two dictionaries, one ignorable and one not.++### Why `/HT` is ignored++Deliberately, not accidentally. A halftone screen exists to represent continuous tone on a+**bilevel** device by trading spatial resolution for tonal resolution. The output here is+8-bit-per-channel antialiased RGB, which represents the requested tone directly. Applying a+screen could only throw tonal resolution away. Same reasoning covers `/BG`, `/BG2`, `/UCR`+and `/UCR2`, which are defined only for the DeviceGray → DeviceCMYK conversion that never+happens here.++---++## 3. Colour spaces (§8.6, Table 61)++| Space | Status | Note |+| --- | --- | --- |+| DeviceGray, DeviceRGB, DeviceCMYK | full | Plus the `/G` `/RGB` `/CMYK` inline abbreviations. |+| CalGray, CalRGB | full | White point, gamma, matrix. |+| Lab | full | White point and `/Range`. |+| ICCBased | **partial** | Resolved through `/Alternate`, or by `/N` when absent. There is no ICC transform engine; this is what every non-colour-managed viewer does and the deviation is small for the sRGB-like profiles that dominate. |+| Indexed | full | Any base space, `/Hival`, lookup as string or stream. |+| Separation | full | Tint transform through any function type. |+| DeviceN | full | As Separation, n-component. |+| Pattern | full | With and without an underlying base space. |+| `/DefaultRGB` `/DefaultGray` `/DefaultCMYK` | **missing** | §8.6.5.6 resource-level substitution of a CIE-based space for a device space. Likelihood: rare. Visibility: none — ignoring them means using the device space directly, which is what viewers do anyway. Not worth implementing. |++## 4. Shadings (§8.7.4.5)++| Type | Status |+| --- | --- |+| 1 function-based | full |+| 2 axial | full — `/Domain`, both `/Extend` flags, `/Background`, `/BBox` |+| 3 radial | full — including the non-negative-radius constraint and both `/Extend` flags |+| 4 free-form Gouraud triangle mesh | full |+| 5 lattice-form Gouraud mesh | full — `/VerticesPerRow` |+| 6 Coons patch mesh | full |+| 7 tensor-product patch mesh | full — including the 4 interior control points |++`/Function` on types 4-7 (colour as a single parametric value through a function rather+than as direct components, §8.7.4.5.5) is handled. `/AntiAlias` (Table 78) is ignored;+the spec itself calls it a hint that may be disregarded.++## 5. Functions (§7.10)++| Type | Status |+| --- | --- |+| 0 sampled | full — n-D multilinear interpolation, all of Table 39's `/BitsPerSample` values, `/Encode`, `/Decode` |+| 2 exponential | full — with `/Range`-implied output arity when `/C0`/`/C1` are absent |+| 3 stitching | full |+| 4 PostScript calculator | full — the entire operator set of Table 42 |++Array-of-functions is supported everywhere a `/Function` may be an array.++## 6. Filters (§7.4) and fonts (§9.5-9.7)++All ten filters are recognised, with abbreviations: `ASCIIHexDecode`, `ASCII85Decode`,+`LZWDecode`, `FlateDecode` (both with `/Predictor`), `RunLengthDecode`, `CCITTFaxDecode`,+`DCTDecode`, `JPXDecode` (decoded in-process via the `openjp2` port, not passed through),+`JBIG2Decode`, `Crypt`.++Font types: Type1, MMType1, TrueType, Type3, and Type0 over CIDFontType0/CIDFontType2 are+all real. Embedded programs are rendered as true outlines from `/FontFile` (Type 1+eexec), `/FontFile2` (TrueType/OpenType) and `/FontFile3` (bare CFF and OpenType-CFF);+substitute typefaces are the fallback, not the primary path. The standard 14 fall back to+AFM metrics. The documented exception is the compiled code→CID tables of the predefined+CJK CMaps.++---++## 7. Triage: what is actually left++Ordered by (likelihood × visibility), which is the only ordering worth having.++0. **A form XObject inside a disabled optional-content group painted anyway — FIXED.**+   The single highest-impact gap found across all rounds, and the strongest candidate for+   the original "renders things that shouldn't even be there" report. `oc_stack` is a local+   in `interpret_content_seeded` that no nested stream inherits. The `Do` arm gated its+   Image branch, its `/BBox` `ClipPush` and its `GroupPush` on the hidden flag — but not the+   recursive interpret call. So `/OC1 BDC /Fm0 Do EMC` with OC1 switched OFF painted the+   form's ENTIRE contents, and painted them UNCLIPPED, because the clip that would have+   bounded them was suppressed by the very flag the recursion ignored. §8.11.2: content in+   a disabled optional-content group shall not be drawn.++   Round 1 fixed the BMC/BDC/EMC balance and round 2 fixed the text operators; `Do` was+   missed by both, and by two full review passes, because there is no wrong-looking code to+   review — the gate is simply absent. The XObject's own `/OC` key (§8.11.3.3) was always+   handled; only the surrounding bracket state was lost.++   Fixed by gating the recursion rather than threading the flag into it: a hidden form is+   skipped whole, which is both cheaper and impossible to get half-right. `text_only`+   deliberately still descends, because that caller is `search::build_index` and the policy+   set in the `Tj` arm is that a hidden layer is hidden, not absent — its text stays+   searchable. Covered by `a_form_xobject_in_a_disabled_oc_group_paints_nothing`, which+   asserts both directions and pins the fixture with an ON-layer control.++   Every other recursion site was audited for the same omission and all are already gated:+   tiling-pattern cells and pattern strokes (behind the painting arms' hidden check),+   soft-mask groups (same), Type 3 CharProcs (via render mode 3 in `show_string_type3`).+   Annotation appearance streams are not inside page-content brackets at all and carry+   their own `/OC` (§12.5.3), so `oc_stack` does not apply to them.++0b. **Group alpha was silently dropped whenever a soft mask was active — FIXED.**+   §11.6.6 resets the alpha constants to 1.0 on entering a transparency group, because+   `/ca` applies ONCE to the group's composited result. That reset is gated on+   `pushed_group`, and round 2 had made the group push and the soft-mask bracket mutually+   exclusive — so a form carrying both `/ca` < 1 and an `/SMask` applied `ca` to every+   element inside instead, over-darkening wherever that content overlapped itself. Exactly+   the failure the comment two lines above the reset warns about.++   Fixed by making the two non-exclusive. `sm_start` is captured above the push, so+   `wrap_with_soft_mask` inserts `SoftMaskPush` outside the group: the group composites+   (applying `ca` once) inside the masked layer, then the mask applies to that result, which+   is the §11.6.5.1 order. Covered by+   `group_alpha_resets_even_when_a_soft_mask_is_active`, whose fixture uses two OVERLAPPING+   fills because overlap is the only shape that can witness the bug.++   The reset stays gated on `pushed_group`, so when `MAX_PRIMITIVES` or the group-depth cap+   demotes the push, `ca` is still applied per element. That is deliberate, not a residual:+   with no composite to apply it to once, resetting anyway would drop `ca` entirely and+   paint the form fully opaque — wrong for all content, where per-element is wrong only+   where content overlaps itself. Round 2's overprint lesson again.++1. **`sh` in a nested content stream — FIXED in round 3, everywhere including the one+   documented remaining case.** §8.7.4.1 requires `sh` to cover the whole clip region, so `rasterize_shading`+   refuses to invent an extent and paints *nothing* when given neither a shading `/BBox` nor+   a clip extent. That extent is a separate ARGUMENT and is not the `ClipPush` primitive — a+   clip bounds the shading at render time, the extent is what lets it produce a raster at+   all. Only the page-level caller seeded it; every nested stream reached the interpreter+   through `interpret_content`, which passes `None`. A gradient drawn with `sh` inside a form+   XObject was therefore invisible.++   Now seeded from the box each stream is clipped to: form XObjects (§8.10.1), soft-mask+   groups (§11.6.5.2), tiling-pattern cells including both malformed-pattern fallbacks+   (§8.7.3.1), and annotation appearance streams (§12.5.5, fixed by `residuals`).++   One of these was worse than "invisible gradient" and worth calling out, because it shows+   how a missing seed can corrupt a DECISION rather than just an output. The periodic-raster+   path rasterizes a pattern cell once and repeats it as a bitmap, but only if the cell+   consists solely of fills and strokes. Unseeded, a cell whose content was `sh` produced no+   Image primitive at all, so the cell *looked* like pure fills/strokes, the periodic path+   was taken, and the gradient was silently dropped from every tile. Seeded, the Image+   appears, the gate correctly rejects it, and the per-tile path paints it.++   **Remaining, deliberately:** Type 3 glyph CharProcs (`draw.rs`). Unlike every case above+   there is no correct box to seed from — §9.6.4.2 permits an all-zero `/FontBBox`, in which+   case no assumptions may be made about glyph extent, and §9.6.5 does not clip a CharProc to+   it. Inventing one would be the guess `rasterize_shading` exists to refuse. A CharProc+   containing `sh` is also close to unheard of; real Type 3 glyphs are image masks or simple+   fills.++   Worth remembering as a pattern: the comment on that early return in `images.rs` asserts+   the `None` arm "should be unreachable in practice" because the page device box is seeded.+   It was accurate about the caller it considered and silently wrong about five others. A+   claim of unreachability is only as good as its enumeration of callers.+2. **ExtGState `/Font` — FIXED in round 3.** Total-text-degradation failure when present,+   though rarely present.+3. **ExtGState `/FL` — FIXED in round 3.** The one Table 58 key that had full plumbing+   (`bezier_steps_for_flatness`) and no parser.+4. **`/Interpolate` on images — built, never wired.** `images::image_should_interpolate`+   computes the right answer and nothing calls it, so every image is bilinearly smoothed on+   magnification, including bilevel art: a magnified QR code, barcode or scanned fax gets a+   grey ramp and a translucent fringe instead of hard black and white (§8.9.5.1 Table 89).+   Blocked on the wire format — `wire.rs` reserves a v11 `u8 interpolate` in the Image arm+   and the Kotlin parser already has the `isV11` gate, so this needs a `Prim::Image` field,+   a `WIRE_VERSION` bump and a Kotlin constant bump **atomically**. Cross-language; not+   landed here.+5. **Text clip (`Tr` 4-7) from Type 3 glyphs and from glyphs with no recoverable Unicode.**+   The clip is accumulated on the Kotlin side from substitute-glyph text records, and those+   two cases emit none, so the clip ends up under-constrained: content that should show+   through letterforms floods the whole area instead. Note the failure direction — the+   renderer guards with `if (hasTextClip)`, so an empty accumulator is a no-op rather than+   a blackout, which is the safe way round. Fixing it means clipping to `Fill` contours on+   the Kotlin side; cross-language, and niche.+6. **`d1` colour suppression (§9.6.5).** A `d1` Type 3 glyph is a shape only and colour+   operators inside it shall be ignored; here they take effect. Worst case is a glyph whose+   CharProc sets white and paints invisibly where a conforming reader would use the current+   fill colour. Real Type 3 producers (dvips, Metafont, TeX bitmap fonts) emit `d1` followed+   by an image mask and no colour operators, so this is close to unreachable in practice.+   Deliberately not fixed: threading a "colour is locked" flag through `interpret_content`+   changes a signature used by four files this round's ownership splits across, for a case+   no producer generates.+7. **`/DefaultRGB` / `/DefaultGray` / `/DefaultCMYK` (§8.6.5.6).** Not worth implementing;+   see §3.++Everything else in Clause 10 is ignored on purpose, and §2 says why for each key.++## 8. Dead-code verdicts++Three warnings survived earlier rounds. The distinction that matters is *leftover* versus+*built and never wired up* — the second is a real bug. Established by comparing+`cargo check --lib` against `cargo check --profile test --lib`: an item that warns in the+first but not the second is read **only by tests**.++| Item | Verdict |+| --- | --- |+| `images::image_should_interpolate` | **Built and never wired up — a real gap.** Its own doc comment names the handoff and `wire.rs` reserves the field for it. Blocked on wire.rs + Kotlin; see §7 item 4. |+| `images::shading_device_size` | **Superseded leftover — delete.** `rasterize_shading`'s own `auto_size()` closure does the same job from the device-space clip bbox, which is the right quantity; `shading_device_size` uses the unit-square→device matrix, which is not. Every caller passes `size == 0`, so `auto_size()` always wins. Its only reference is its own test. |+| `FontInfo::base_font` | **Diagnostic field, not unfinished work.** Its only reader is a `println!` in `debug_ishi_test`. The parts of the base font name that matter downstream are already distilled into `style.bold`/`style.italic` and `family` at parse time and shipped in the v8 `fontFlags` byte. Using the raw string for exact-family substitution would need a per-primitive wire string that nobody has started. Keep and annotate, or delete. |++Note these three no longer surface under `cargo check --all-targets`, which compiles the+tests and so sees the test-only readers. The verdicts above stand; reproduce them with+`cargo check --lib`. `shading_device_size`'s verdict has since been actioned: it is gone+from the tree, and a grep for it now returns nothing. The other two are unchanged.++## 9. Memory, which is a coverage question too++A feature that aborts the process is not implemented either. `bench` measured peak heap on+a 400_000-rect page at 533 MiB, of which 415 MiB is the `Vec<Operation>` materialised in+full before interpretation starts, against 32 MiB of primitives at the `MAX_PRIMITIVES`+cap. So `MAX_PRIMITIVES` does not bound page memory in any meaningful way.++`MAX_CONTENT_OPS` was lowered 1_000_000 -> 660_000 as a deliberate cap rather than a+streaming refactor: a defensible bound now beats a half-finished refactor, and truncating+the tail of a page beats an uncatchable process abort that loses the whole document. At+`bench`'s 544 B/op that cuts the admitted worst case from ~519 MiB to ~342 MiB while+discarding no primitive the old value could have produced, because every operator above+~660_000 could only be read after `MAX_PRIMITIVES` had already stopped emitting.++Two things learned in the process are worth recording here rather than only in the code.+First, `MAX_CONTENT_OPS >= 2 * MAX_PRIMITIVES` is necessary but not sufficient: it is stated+for the densest shape (`re f`, 2 operators per prim), and a page also spends operators on+colour, `q`/`Q`, `cm` and clip setup, so setting the cap to exactly 2x leaves+`MAX_PRIMITIVES` unreachable and quietly disarms the truncation test. Second, a cap here+cannot bind on the path that matters without help: `content::MAX_OPERATIONS` ties the+lenient recovery tokenizer to it, but the strict `lopdf` parse materialises the vector in+full before `take` is applied, so a well-formed heavy page — the one `bench` measured — is+unaffected until `content.rs` truncates and shrinks after the parse.++The measurement table and the full reasoning live on the `MAX_CONTENT_OPS` and+`MAX_PRIMITIVES` doc comments in `src/graphics_state.rs`, kept next to the numbers so they+cannot drift apart from them.
pdf/src/main/rust/src/annotations.rs
diff --git a/pdf/src/main/rust/src/annotations.rs b/pdf/src/main/rust/src/annotations.rsindex 5e3eaf6ebf..954cc0ce45 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -39,7 +39,19 @@ pub(crate) fn appearance_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> /// position 2 (value 2), NoView is bit position 6 (value 32). Also honors /// optional content (§8.11.2) and skips `/Popup`, whose appearance is shown only /// via its parent's open state (§12.5.6.14).-pub(crate) fn annot_visible_on_screen(doc: &Document, dict: &lopdf::Dictionary) -> bool {+///+/// The `OcConfig` is a PARAMETER, deliberately. There was a `annot_visible_on_screen(doc,+/// dict)` convenience wrapper that called `OcConfig::from_doc` itself, and both callers+/// walk an `/Annots` array — so it rebuilt the catalog's whole membership configuration+/// once per annotation. It is deleted rather than left for the next caller to reach for,+/// because that shape is what silently undid a measured 8.8x win twice: once in the+/// renderer's `Do` arm and once here in `flatten_document`. Resolve the config once, at+/// the outermost point that has the document, and pass it down.+pub(crate) fn annot_visible_on_screen_with(+    oc: &OcConfig,+    doc: &Document,+    dict: &lopdf::Dictionary,+) -> bool {     let flags = dict         .get(b"F")         .ok()@@ -49,7 +61,7 @@ pub(crate) fn annot_visible_on_screen(doc: &Document, dict: &lopdf::Dictionary)     if flags & 0b10 != 0 || flags & 0b10_0000 != 0 {         return false;     }-    if dict.get(b"OC").ok().map(|oc| crate::oc_object_hidden(doc, oc)).unwrap_or(false) {+    if dict.get(b"OC").ok().map(|o| oc.object_hidden(doc, o)).unwrap_or(false) {         return false;     }     dict.get(b"Subtype")@@ -73,16 +85,29 @@ pub(crate) fn render_annotations(doc: &Document, page_id: ObjectId, base: &Mat,         _ => return,     }; -    for a in &annots {+    let oc = OcConfig::from_doc(doc);+    for a in annots.iter().take(MAX_ANNOTATIONS) {         let dict = match deref(doc, a).and_then(|o| o.as_dict().ok()) {             Some(d) => d,             None => continue,         };-        if !annot_visible_on_screen(doc, dict) {+        if !annot_visible_on_screen_with(&oc, doc, dict) {             continue;         }         render_annotation(doc, dict, base, prims);     }+    if annots.len() > MAX_ANNOTATIONS {+        // Each annotation can emit an appearance stream's worth of primitives, so an+        // /Annots array with a hostile number of entries is an unbounded amount of work+        // even though the array itself is bounded by the file size.+        if cfg!(debug_assertions) {+            eprintln!(+                "[pdf_render/annotations] page has {} annotations - only the first {} are rendered",+                annots.len(),+                MAX_ANNOTATIONS+            );+        }+    } }  pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base: &Mat, prims: &mut Vec<Prim>) {@@ -172,19 +197,42 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:     // fit — the latter is too loose and lets a rotated appearance spill. The     // same `ctm` is reused for the clip and the content, so the form's /Matrix     // (already folded into it by appearance_matrix) cannot be applied twice.-    // A degenerate BBox is skipped: a collapsed quad would swallow the whole-    // annotation, turning a spill into a vanish.-    let clip = bbox_raw+    //+    // A degenerate BBox cannot clip — a collapsed quad would swallow the whole+    // annotation, turning a spill into a vanish — but emitting NO clip is not safe+    // either: `sh` fills the whole of the current clip region (§8.7.4.3), so an+    // appearance stream containing one floods the entire page. Fall back to the+    // annotation's own /Rect, which bounds it per §12.5.5 regardless of the /BBox.+    // /Rect is in default user space, so it maps through `base`, not `ctm`.+    let (clip, clip_ctm) = match bbox_raw         .map(normalize_rect)-        .filter(|b| b[2] - b[0] > 0.0 && b[3] - b[1] > 0.0);+        .filter(|b| b[2] - b[0] > 0.0 && b[3] - b[1] > 0.0)+    {+        Some(b) => (Some(b), ctm),+        None => {+            let r = normalize_rect(rect);+            let usable = (r[2] - r[0] > 0.0 && r[3] - r[1] > 0.0).then_some(r);+            (usable, *base)+        }+    };+    let mut clip_bbox_device: Option<[f64; 4]> = None;     if let Some(b) = clip {-        let pts: Vec<(f32, f32)> = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])]+        let dev: Vec<(f64, f64)> = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])]             .iter()-            .map(|&(x, y)| {-                let (dx, dy) = transform(&ctm, x, y);-                (dx as f32, dy as f32)-            })+            .map(|&(x, y)| transform(&clip_ctm, x, y))             .collect();+        let xs = dev.iter().map(|p| p.0);+        let ys = dev.iter().map(|p| p.1);+        let bb = [+            xs.clone().fold(f64::INFINITY, f64::min),+            ys.clone().fold(f64::INFINITY, f64::min),+            xs.fold(f64::NEG_INFINITY, f64::max),+            ys.fold(f64::NEG_INFINITY, f64::max),+        ];+        if bb.iter().all(|v| v.is_finite()) && bb[2] > bb[0] && bb[3] > bb[1] {+            clip_bbox_device = Some(bb);+        }+        let pts: Vec<(f32, f32)> = dev.iter().map(|&(x, y)| (x as f32, y as f32)).collect();         let mut path_ops = vec![PathOp::Move(pts[0].0, pts[0].1)];         path_ops.extend(pts[1..].iter().map(|&(x, y)| PathOp::Line(x, y)));         path_ops.push(PathOp::Close);@@ -196,14 +244,53 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:         ..Default::default()     };     let start = prims.len();-    interpret_content(doc, &ops, res.as_ref(), gs, prims, 1, false);+    // Seed the device clip extent rather than using `interpret_content`, which passes+    // `None`. §8.7.4.1 requires `sh` to cover the entire clipping region, so when a+    // shading has no `/BBox` of its own `rasterize_shading` needs that extent to know+    // what to cover — and with `None` it returns `None` and pushes no prim at all, so a+    // gradient painted with `sh` inside an appearance stream was INVISIBLE. The comment+    // on that early return assumed the page-level caller always seeds it; an annotation+    // appearance is the caller that does not. The extent is the same BBox-or-Rect quad+    // clipped above, which is exactly the region such an `sh` may cover.+    interpret_content_seeded(+        doc,+        &ops,+        res.as_ref(),+        gs,+        prims,+        1,+        false,+        clip_bbox_device,+    ); -    // Honor the annotation's constant opacity (/CA) over its rendered prims.+    // §12.5.2: /CA is the constant opacity the WHOLE annotation is painted with, so+    // §11.6.6 applies it once to the composited appearance — exactly what a+    // GroupPush/GroupPop layer does, and the same mechanism the `Do` arm uses for /ca on+    // a form XObject.+    //+    // This used to walk `prims[start..]` calling `scale_prim_alpha` on each, which+    // conflicts with two other fixes:+    //   * a transparency group inside the appearance already carries its alpha on+    //     `GroupPush`, and the loop scaled BOTH the GroupPush and every prim inside it,+    //     so /CA landed twice (CA² on the group's contents);+    //   * `wrap_with_soft_mask` appends the mask group's own prims after+    //     `SoftMaskContent`, inside this same range, so the loop faded the MASK rather+    //     than the content — for a luminosity mask that changes the mask's shape, not+    //     its opacity.+    // Wrapping instead of scaling cannot reach either: the layer's alpha is applied to+    // the composite, and nothing inside is rewritten.     let ca = dict.get(b"CA").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(num).unwrap_or(1.0);-    if ca < 1.0 {-        for p in prims[start..].iter_mut() {-            scale_prim_alpha(p, ca);-        }+    if ca < 1.0 && prims.len() > start {+        prims.insert(+            start,+            Prim::GroupPush {+                isolated: true,+                knockout: false,+                alpha: ca.clamp(0.0, 1.0) as f32,+                blend: BlendMode::Normal,+            },+        );+        prims.push(Prim::GroupPop);     }     // Unconditional pop (mirrors the `Do` arm): interpret_content always returns     // with a balanced clip depth, so this keeps the canvas clip stack balanced@@ -741,8 +828,15 @@ pub(crate) fn decode_id(v: i64) -> ObjectId {     (((v >> 16) & 0xFFFF_FFFF) as u32, (v & 0xFFFF) as u16) } +/// Object id of the `index`-th page (0-based), or `None` when out of range.+///+/// `index` arrives unvalidated from the JNI boundary as a `jint`, so it may be negative.+/// `(index as u32) + 1` overflowed for `-1`: a debug panic, and in release a silent wrap+/// to 0, which page keys being 1-based made accidentally harmless. Reject negatives up+/// front instead of relying on that. pub(crate) fn nth_page_id(doc: &Document, index: i32) -> Option<ObjectId> {-    doc.get_pages().get(&((index as u32) + 1)).copied()+    let page_number = u32::try_from(index).ok()?.checked_add(1)?;+    doc.get_pages().get(&page_number).copied() }  pub(crate) fn name_obj(s: &str) -> Object {@@ -1843,6 +1937,149 @@ mod synthesis_tests {     use super::stamp_label;     use crate::*; +    // A page index arrives from the JNI boundary as a `jint` and is not validated there,+    // so `nth_page_id` must treat a negative one as out of range. `(index as u32) + 1`+    // panicked in debug for -1 and wrapped to 0 in release, which page keys being 1-based+    // made harmless by luck rather than by design.+    #[test]+    fn a_negative_page_index_is_out_of_range_not_an_overflow() {+        let mut doc = Document::with_version("1.7");+        let pages_id = doc.new_object_id();+        let page = doc.add_object(dictionary! {+            "Type" => name_obj("Page"),+            "Parent" => Object::Reference(pages_id),+            "MediaBox" => rect_obj([0.0, 0.0, 100.0, 100.0]),+        });+        doc.objects.insert(+            pages_id,+            Object::Dictionary(dictionary! {+                "Type" => name_obj("Pages"),+                "Kids" => Object::Array(vec![Object::Reference(page)]),+                "Count" => 1,+            }),+        );+        let catalog_id = doc.add_object(dictionary! {+            "Type" => name_obj("Catalog"),+            "Pages" => Object::Reference(pages_id),+        });+        doc.trailer.set("Root", catalog_id);+        assert_eq!(nth_page_id(&doc, 0), Some(page), "page 0 is the first page");+        for bad in [-1, -2, -1000, i32::MIN, i32::MIN + 1] {+            assert_eq!(nth_page_id(&doc, bad), None, "index {bad} must be out of range");+        }+        assert_eq!(nth_page_id(&doc, i32::MAX), None, "past the end is out of range");+    }++    // §8.7.4.3: `sh` fills the whole of the CURRENT CLIP. An appearance stream is a form+    // XObject (§12.5.5) and is normally clipped to its /BBox, but a missing or degenerate+    // /BBox used to emit no clip at all — so one `sh` inside such an appearance flooded+    // the entire page instead of the annotation. The /Rect bounds the annotation whatever+    // the /BBox says, so it is the fallback.+    #[test]+    fn an_appearance_without_a_usable_bbox_still_clips_shadings_to_the_rect() {+        let rect = [10.0, 20.0, 40.0, 60.0];+        for bbox in [None, Some(vec![0.into(), 0.into(), 0.into(), 0.into()])] {+            let mut doc = Document::with_version("1.7");+            let mut ap_dict = dictionary! {+                "Type" => name_obj("XObject"),+                "Subtype" => name_obj("Form"),+            };+            if let Some(b) = bbox.clone() {+                ap_dict.set("BBox", Object::Array(b));+            }+            let ap = doc.add_object(Stream::new(ap_dict, b"0 0 1 rg 0 0 100 100 re f".to_vec()));+            let annot = dictionary! {+                "Type" => name_obj("Annot"),+                "Subtype" => name_obj("Square"),+                "Rect" => rect_obj(rect),+                "AP" => dictionary! { "N" => ap },+            };+            let mut prims = Vec::new();+            render_annotation(&doc, &annot, &IDENTITY, &mut prims);++            let clips: Vec<&Prim> = prims+                .iter()+                .filter(|p| matches!(p, Prim::ClipPush { .. }))+                .collect();+            assert_eq!(clips.len(), 1, "an unusable /BBox must still emit one clip");+            let Prim::ClipPush { pts, .. } = clips[0] else {+                unreachable!()+            };+            let xs = pts.iter().map(|p| p.0);+            let ys = pts.iter().map(|p| p.1);+            let (x0, x1) = (xs.clone().fold(f32::MAX, f32::min), xs.fold(f32::MIN, f32::max));+            let (y0, y1) = (ys.clone().fold(f32::MAX, f32::min), ys.fold(f32::MIN, f32::max));+            for (got, want) in [(x0, 10.0), (y0, 20.0), (x1, 40.0), (y1, 60.0)] {+                assert!(+                    (got - want).abs() < 0.01,+                    "clip must be the /Rect, got [{x0} {y0} {x1} {y1}]"+                );+            }+            // The clip is still balanced.+            assert_eq!(+                prims.iter().filter(|p| matches!(p, Prim::ClipPop)).count(),+                1,+                "the fallback clip must be popped exactly once"+            );+        }+    }++    // The OPPOSITE failure to the clip test above, and a separate bug: §8.7.4.1 makes `sh`+    // cover the whole clipping region, so a shading with no `/BBox` of its own needs the+    // device clip extent to know what to cover. `render_annotation` used `interpret_content`,+    // which seeds that extent as `None`, and `rasterize_shading` then returns `None` and+    // pushes nothing — so a gradient painted with `sh` inside an appearance stream was+    // INVISIBLE. Too little painted, where the clip bug was too much.+    #[test]+    fn a_shading_with_no_bbox_still_paints_inside_an_appearance_stream() {+        let mut doc = Document::with_version("1.7");+        let func = doc.add_object(dictionary! {+            "FunctionType" => 2,+            "Domain" => Object::Array(vec![0.into(), 1.into()]),+            "C0" => Object::Array(vec![1.into(), 0.into(), 0.into()]),+            "C1" => Object::Array(vec![0.into(), 0.into(), 1.into()]),+            "N" => 1,+        });+        // Deliberately no /BBox on the shading: that is the case that needs the seed.+        let shading = doc.add_object(dictionary! {+            "ShadingType" => 2,+            "ColorSpace" => name_obj("DeviceRGB"),+            "Coords" => Object::Array(vec![0.into(), 0.into(), 40.into(), 0.into()]),+            "Function" => Object::Reference(func),+        });+        let ap = doc.add_object(Stream::new(+            dictionary! {+                "Type" => name_obj("XObject"),+                "Subtype" => name_obj("Form"),+                "BBox" => Object::Array(vec![0.into(), 0.into(), 40.into(), 40.into()]),+                "Resources" => dictionary! { "Shading" => dictionary! { "Sh0" => shading } },+            },+            b"/Sh0 sh".to_vec(),+        ));+        let annot = dictionary! {+            "Type" => name_obj("Annot"),+            "Subtype" => name_obj("Square"),+            "Rect" => rect_obj([0.0, 0.0, 40.0, 40.0]),+            "AP" => dictionary! { "N" => ap },+        };+        let mut prims = Vec::new();+        render_annotation(&doc, &annot, &IDENTITY, &mut prims);+        let images = prims.iter().filter(|p| matches!(p, Prim::Image { .. })).count();+        assert_eq!(+            images, 1,+            "the shading must rasterize: got {:?}",+            prims+                .iter()+                .map(|p| match p {+                    Prim::Image { .. } => "Image",+                    Prim::ClipPush { .. } => "ClipPush",+                    Prim::ClipPop => "ClipPop",+                    _ => "other",+                })+                .collect::<Vec<_>>()+        );+    }+     fn annot(subtype: &str) -> Dictionary {         let mut d = Dictionary::new();         d.set("Type", name_obj("Annot"));@@ -1858,6 +2095,77 @@ mod synthesis_tests {         prims     } +    /// §12.5.2 /CA is the opacity of the WHOLE annotation, and §11.6.6 applies a group's+    /// alpha once, to the composited result. Round 1 put that alpha on `GroupPush`; round 2+    /// added a `/CA` pass that walked the emitted prims and scaled each one — so an+    /// appearance containing a transparency group got `/CA` on the group AND on everything+    /// inside it, i.e. CA² on the contents. This pins one application per layer.+    #[test]+    fn annotation_ca_is_applied_once_over_a_transparency_group() {+        let mut doc = Document::with_version("1.7");+        let form = doc.add_object(Stream::new(+            dictionary! {+                "Type" => name_obj("XObject"),+                "Subtype" => name_obj("Form"),+                "BBox" => Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]),+                "Group" => dictionary! { "S" => name_obj("Transparency") },+            },+            b"0 0 1 rg 0 0 10 10 re f".to_vec(),+        ));+        let gstate = doc.add_object(dictionary! { "Type" => name_obj("ExtGState"), "ca" => 0.5 });+        let ap = doc.add_object(Stream::new(+            dictionary! {+                "Type" => name_obj("XObject"),+                "Subtype" => name_obj("Form"),+                "BBox" => Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]),+                "Resources" => dictionary! {+                    "XObject" => dictionary! { "Fm1" => form },+                    "ExtGState" => dictionary! { "GS1" => gstate },+                },+            },+            b"/GS1 gs /Fm1 Do".to_vec(),+        ));+        let annot = dictionary! {+            "Type" => name_obj("Annot"),+            "Subtype" => name_obj("Square"),+            "Rect" => Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]),+            "AP" => dictionary! { "N" => ap },+            "CA" => 0.5,+        };+        let mut prims = Vec::new();+        render_annotation(&doc, &annot, &IDENTITY, &mut prims);++        let group_alphas: Vec<f32> = prims+            .iter()+            .filter_map(|p| match p {+                Prim::GroupPush { alpha, .. } => Some(*alpha),+                _ => None,+            })+            .collect();+        assert_eq!(group_alphas.len(), 2, "one layer for /CA, one for the form's own group");+        for a in &group_alphas {+            assert!((a - 0.5).abs() < 1e-6, "each layer carries its own alpha once, got {a}");+        }+        let fills: Vec<u32> = prims+            .iter()+            .filter_map(|p| match p {+                Prim::Fill { argb, .. } => Some(*argb),+                _ => None,+            })+            .collect();+        assert_eq!(fills.len(), 1, "expected the form's single fill");+        assert_eq!(+            fills[0] >> 24,+            0xFF,+            "the fill inside the group must stay opaque: both /ca and /CA belong to the \+             composited layers, not to each element inside them"+        );+        // Every push is closed.+        let pushes = prims.iter().filter(|p| matches!(p, Prim::GroupPush { .. })).count();+        let pops = prims.iter().filter(|p| matches!(p, Prim::GroupPop)).count();+        assert_eq!(pushes, pops, "group brackets must balance");+    }+     /// `Prim` has no `Debug`, so failures report the primitive kinds instead.     fn kinds(prims: &[Prim]) -> Vec<&'static str> {         prims
pdf/src/main/rust/src/color.rs
diff --git a/pdf/src/main/rust/src/color.rs b/pdf/src/main/rust/src/color.rsindex a6bfa18abe..5481431c11 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -26,14 +26,18 @@ pub(crate) enum CsKind {     DeviceGray,     DeviceRGB,     DeviceCMYK,-    Lab { white: [f64;3], range: [[f64;2];2], black: Option<[f64;3]> },+    Lab { white: [f64;3], range: [[f64;2];2] },     Separation { name: Vec<u8>, alt: Box<CsKind>, tint_fn: Option<PdfFunction> },     DeviceN { names: Vec<Vec<u8>>, alt: Box<CsKind>, tint_fn: Option<PdfFunction> },     Pattern { base: Option<Box<CsKind>> },     Indexed { base: Box<CsKind>, lookup: Vec<u8>, base_ncomp: u8, hival: u16 },     ICCBased { n: u8, alt: Option<Box<CsKind>> },     CalRGB { white: [f64;3], gamma: [f64;3], matrix: [[f64;3];3] },-    CalGray { white: [f64;3], gamma: f64, black: Option<[f64;3]> },+    /// CIE-based grey (§8.6.5.2). `/BlackPoint` is parsed by nobody and ignored: the+    /// conversion below adapts from `/WhitePoint` only, so a non-default black point+    /// shifts the darkest tones slightly. Recorded here rather than kept as an+    /// always-`None` field that reads as if the support were half-written.+    CalGray { white: [f64;3], gamma: f64 }, }  pub(crate) fn colorspaces_from_resources(doc: &Document, res_dict: &lopdf::Dictionary) -> HashMap<Vec<u8>, ObjectId> {@@ -76,7 +80,22 @@ pub(crate) fn patterns_from_resources(doc: &Document, res_dict: &lopdf::Dictiona }  // Parse a colorspace object (Name or Array) into CsKind, using resources map for named entries+/// Depth ceiling for colour-space nesting. §8.6 nests only a handful of levels deep in+/// practice (Indexed over ICCBased over an /Alternate, say), so this only ever stops a+/// cycle. `[/Indexed 5 0 R 255 <00FF00>]` stored AS object 5 makes the base resolve back+/// to the same array, and the plain per-name self-reference guard cannot see it because+/// the cycle runs through the array element rather than a name. That recursed until the+/// stack overflowed, which unlike a panic cannot be caught and takes the process with it.+const MAX_CS_DEPTH: u32 = 16;+ pub(crate) fn parse_cs_kind(doc: &Document, cs_obj: Option<&Object>, cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<CsKind> {+    parse_cs_kind_at(doc, cs_obj, cs_resources, 0)+}++fn parse_cs_kind_at(doc: &Document, cs_obj: Option<&Object>, cs_resources: &HashMap<Vec<u8>, ObjectId>, depth: u32) -> Option<CsKind> {+    if depth >= MAX_CS_DEPTH {+        return None;+    }     let obj = cs_obj?;     // If Name, check if it's a resource reference     if let Object::Name(name) = obj {@@ -87,10 +106,10 @@ pub(crate) fn parse_cs_kind(doc: &Document, cs_obj: Option<&Object>, cs_resource         if let Some(&id) = cs_resources.get(name) {             if let Ok(resolved) = doc.get_object(id) {                 match resolved {-                    Object::Array(arr) => return parse_cs_array(doc, arr, cs_resources),+                    Object::Array(arr) => return parse_cs_array_at(doc, arr, cs_resources, depth + 1),                     // Guard against a name that resolves to itself.                     Object::Name(n2) if n2 != name => {-                        return parse_cs_kind(doc, Some(resolved), cs_resources);+                        return parse_cs_kind_at(doc, Some(resolved), cs_resources, depth + 1);                     }                     _ => {}                 }@@ -106,11 +125,11 @@ pub(crate) fn parse_cs_kind(doc: &Document, cs_obj: Option<&Object>, cs_resource         }     }     if let Object::Array(arr) = obj {-        return parse_cs_array(doc, arr, cs_resources);+        return parse_cs_array_at(doc, arr, cs_resources, depth + 1);     }     // If Reference, deref     if let Some(deref_obj) = deref(doc, obj) {-        return parse_cs_kind(doc, Some(deref_obj), cs_resources);+        return parse_cs_kind_at(doc, Some(deref_obj), cs_resources, depth + 1);     }     None }@@ -148,7 +167,15 @@ pub(crate) fn parse_named_cs(     parse_cs_kind(doc, Some(cs_obj), cs_resources) } -pub(crate) fn parse_cs_array(doc: &Document, arr: &[Object], cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<CsKind> {+fn parse_cs_array_at(doc: &Document, arr: &[Object], cs_resources: &HashMap<Vec<u8>, ObjectId>, depth: u32) -> Option<CsKind> {+    if depth >= MAX_CS_DEPTH {+        return None;+    }+    // Every nested colour space below goes through `parse_cs_kind_at` so the depth keeps+    // accumulating across the array/kind boundary; a cycle alternates between the two.+    let parse_cs_kind = |doc: &Document, o: Option<&Object>, r: &HashMap<Vec<u8>, ObjectId>| {+        parse_cs_kind_at(doc, o, r, depth + 1)+    };     // arr head is name     let head = arr.first().and_then(|o| o.as_name().ok()).unwrap_or(b"");     match head {@@ -176,7 +203,7 @@ pub(crate) fn parse_cs_array(doc: &Document, arr: &[Object], cs_resources: &Hash             if let Some(d) = dict {                 let white = read_white_point(d).unwrap_or([0.9505,1.0,1.0890]);                 let gamma = d.get(b"Gamma").ok().and_then(num).unwrap_or(1.0);-                Some(CsKind::CalGray { white, gamma, black: None })+                Some(CsKind::CalGray { white, gamma })             } else {                 Some(CsKind::DeviceGray)             }@@ -187,9 +214,9 @@ pub(crate) fn parse_cs_array(doc: &Document, arr: &[Object], cs_resources: &Hash             if let Some(d) = dict {                 let white = read_white_point(d).unwrap_or([0.9505,1.0,1.0890]);                 let range = read_lab_range(d).unwrap_or([[ -100.0, 100.0],[ -100.0, 100.0]]);-                Some(CsKind::Lab { white, range, black: None })+                Some(CsKind::Lab { white, range })             } else {-                Some(CsKind::Lab { white: [0.9505,1.0,1.0890], range: [[ -100.0,100.0],[ -100.0,100.0]], black: None })+                Some(CsKind::Lab { white: [0.9505,1.0,1.0890], range: [[ -100.0,100.0],[ -100.0,100.0]] })             }         }         b"ICCBased" => {@@ -447,11 +474,9 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re                 [ 0.4323053,  0.5183603,  0.0492912],                 [-0.0085287,  0.0400428,  0.9684867],             ];-            // CIE reference white points. The Lab source white is the space's-            // /WhitePoint (`white`) per PDF 8.6.5.4; D65 is the sRGB destination.-            const LMS_D50_X: f64 = 0.96422;-            const LMS_D50_Y: f64 = 1.0;-            const LMS_D50_Z: f64 = 0.82521;+            // CIE reference white point of the DESTINATION. The Lab source white is the+            // space's own /WhitePoint (`white`) per §8.6.5.4, not a fixed D50, which is+            // why only the D65 trio is needed here.             const LMS_D65_X: f64 = 0.95047;             const LMS_D65_Y: f64 = 1.0;             const LMS_D65_Z: f64 = 1.08883;@@ -811,7 +836,7 @@ mod tests {         ));         let arr = vec![Object::Name(b"ICCBased".to_vec()), Object::Reference(icc_id)];         let empty = HashMap::new();-        let kind = parse_cs_array(&doc, &arr, &empty).expect("iccbased");+        let kind = parse_cs_array_at(&doc, &arr, &empty, 0).expect("iccbased");         assert_eq!(cs_kind_ncomp(&kind), 3, "must infer 3 from /Alternate, not default to 1");     } @@ -915,7 +940,7 @@ mod tests {             Object::Name(b"DeviceCMYK".to_vec()),         ];         let empty = HashMap::new();-        let kind = parse_cs_array(&doc, &arr, &empty).expect("pattern cs");+        let kind = parse_cs_array_at(&doc, &arr, &empty, 0).expect("pattern cs");         match kind {             CsKind::Pattern { base: Some(b) } => {                 assert!(matches!(*b, CsKind::DeviceCMYK), "base must be DeviceCMYK");@@ -943,7 +968,7 @@ mod tests {             Object::Reference(lookup),         ];         let empty = HashMap::new();-        let kind = parse_cs_array(&doc, &arr, &empty).expect("indexed cs");+        let kind = parse_cs_array_at(&doc, &arr, &empty, 0).expect("indexed cs");         match kind {             CsKind::Indexed { lookup, base_ncomp, .. } => {                 assert_eq!(base_ncomp, 3);
pdf/src/main/rust/src/content.rs
diff --git a/pdf/src/main/rust/src/content.rs b/pdf/src/main/rust/src/content.rsindex 15a5374993..9a0f2de394 100644--- a/pdf/src/main/rust/src/content.rs+++ b/pdf/src/main/rust/src/content.rs@@ -103,25 +103,117 @@ pub(crate) fn parse_operations_lenient(data: &[u8]) -> Vec<Operation> {     Lexer { d: data, p: 0 }.run() } +/// Whether array/dictionary nesting in `data` ever exceeds [`MAX_DEPTH`].+///+/// `lopdf::content::Content::decode` recurses per nesting level with no bound, so+/// `BT [[[[…(x)…]]]] TJ ET` overflows the stack — measured at N≈360 on an 8 MiB stack and+/// N≈48 on the 1 MiB an Android render thread gets. That is a guard-page fault, not an+/// unwind, so the `catch_unwind` at the JNI boundary cannot catch it and the whole process+/// dies. The lenient tokenizer already bounds itself at [`MAX_DEPTH`] and survives, but it+/// only runs when the strict parser *returns*.+///+/// So this is a pre-check, not a parser: it decides only whether the strict parser is safe+/// to call. It deliberately errs toward "too deep" — a false positive costs one pass of the+/// lenient tokenizer, which handles valid content identically, while a false negative is a+/// process kill. §7.3.4.2 literal strings (balanced unescaped parens, backslash escapes),+/// §7.3.4.3 hex strings and §7.2.4 comments are skipped so a `[` inside them cannot count.+fn nesting_is_too_deep(data: &[u8], max: u32) -> bool {+    let mut depth: u32 = 0;+    let mut i = 0usize;+    while i < data.len() {+        match data[i] {+            b'%' => {+                while i < data.len() && data[i] != b'\n' && data[i] != b'\r' {+                    i += 1;+                }+            }+            b'(' => {+                let mut nest = 1usize;+                i += 1;+                while i < data.len() && nest > 0 {+                    match data[i] {+                        b'\\' => i += 1,+                        b'(' => nest += 1,+                        b')' => nest -= 1,+                        _ => {}+                    }+                    i += 1;+                }+            }+            b'<' if data.get(i + 1) == Some(&b'<') => {+                depth += 1;+                if depth > max {+                    return true;+                }+                i += 2;+            }+            b'<' => {+                i += 1;+                while i < data.len() && data[i] != b'>' {+                    i += 1;+                }+                i += 1;+            }+            b'>' if data.get(i + 1) == Some(&b'>') => {+                depth = depth.saturating_sub(1);+                i += 2;+            }+            b'[' => {+                depth += 1;+                if depth > max {+                    return true;+                }+                i += 1;+            }+            b']' => {+                depth = depth.saturating_sub(1);+                i += 1;+            }+            _ => i += 1,+        }+    }+    false+}++/// Strict parse first, lenient tokenizer only if that fails, yields nothing, or is+/// unsafe to attempt at all.+fn strict_operations(bytes: &[u8]) -> Option<Vec<Operation>> {+    if nesting_is_too_deep(bytes, MAX_DEPTH) {+        return None;+    }+    match Content::decode(bytes) {+        Ok(content) if !content.operations.is_empty() => Some(content.operations),+        _ => None,+    }+}+ /// Operations for a page's content, preferring lopdf's strict parser and falling /// back to [`parse_operations_lenient`] when it fails or recovers nothing. /// /// The `bool` is true when the fallback produced the result (for logging/tests). pub(crate) fn page_operations(doc: &Document, page_id: ObjectId) -> (Vec<Operation>, bool) {-    // Try lopdf first and return its result untouched, so files that render today-    // are completely unaffected.-    if let Ok(content) = doc.get_and_decode_page_content(page_id) {-        if !content.operations.is_empty() {-            return (content.operations, false);-        }-    }-    // Either the parse failed (the inline-image `cut` case) or it recovered nothing.-    // Both render a blank page today, so the lenient path can only improve matters.+    // Decode with OUR filter chain, then parse strictly first so files that render+    // today are unaffected by the parse, falling back to the lenient tokenizer.+    //+    // NOT `get_and_decode_page_content`: that decodes through lopdf, whose ASCII85+    // decoder adds a base-85 5-tuple into a `u32` unchecked (lopdf/src/object.rs:777),+    // so a stream containing `uuuuu` panics with "attempt to add with overflow" in+    // debug and wraps silently in release. A panic here is fatal at the JNI boundary:+    // one malformed content stream kills the whole document. `page_content_bytes` is+    // also the more correct decode — it joins every /Contents stream with intervening+    // white space per §7.8.2, and yields nothing rather than ciphertext when a decoder+    // fails.     let bytes = page_content_bytes(doc, page_id);     if bytes.is_empty() {         return (Vec::new(), false);     }-    (operations_from_bytes(&bytes), true)+    if let Some(ops) = strict_operations(&bytes) {+        return (ops, false);+    }+    // Either the parse failed (the inline-image `cut` case), it recovered nothing, or the+    // nesting was too deep to hand to lopdf at all.+    // All three render a blank page today, so the lenient path can only improve matters.+    (parse_operations_lenient(&bytes), true) }  /// Operations for a NESTED content stream: a form XObject (`Do`), a soft-mask@@ -137,10 +229,8 @@ pub(crate) fn stream_operations(doc: &Document, stream: &Stream) -> Vec<Operatio  /// Strict parse first, lenient tokenizer only if that fails or yields nothing. fn operations_from_bytes(bytes: &[u8]) -> Vec<Operation> {-    if let Ok(content) = Content::decode(bytes) {-        if !content.operations.is_empty() {-            return content.operations;-        }+    if let Some(ops) = strict_operations(bytes) {+        return ops;     }     parse_operations_lenient(bytes) }@@ -1380,6 +1470,43 @@ mod tests {         }     } +    #[test]+    fn the_depth_pre_check_only_counts_real_nesting() {+        // The guard decides whether lopdf's unbounded strict parser is safe to call, so a+        // false negative is a process kill. But a false POSITIVE silently demotes healthy+        // content to the lenient tokenizer, so brackets inside strings and comments must+        // not count.+        assert!(!nesting_is_too_deep(b"BT [(x)] TJ ET", MAX_DEPTH));+        let deep = |n: usize| {+            let mut v = b"BT ".to_vec();+            v.extend(std::iter::repeat_n(b'[', n));+            v.extend_from_slice(b"(x)");+            v.extend(std::iter::repeat_n(b']', n));+            v.extend_from_slice(b" TJ ET");+            v+        };+        assert!(!nesting_is_too_deep(&deep(MAX_DEPTH as usize), MAX_DEPTH));+        assert!(nesting_is_too_deep(&deep(MAX_DEPTH as usize + 1), MAX_DEPTH));+        // §7.3.4.2: a literal string may contain unescaped balanced parens and escaped+        // anything. None of these brackets are nesting.+        let mut s = b"BT (".to_vec();+        s.extend(std::iter::repeat_n(b'[', 200));+        s.extend_from_slice(b"(nested) \\) \\( ");+        s.extend_from_slice(b") Tj ET");+        assert!(!nesting_is_too_deep(&s, MAX_DEPTH));+        // §7.2.4 comment, and a §7.3.4.3 hex string.+        let mut c = b"% ".to_vec();+        c.extend(std::iter::repeat_n(b'[', 200));+        c.extend_from_slice(b"\nBT <");+        c.extend(std::iter::repeat_n(b'A', 40));+        c.extend_from_slice(b"> Tj ET");+        assert!(!nesting_is_too_deep(&c, MAX_DEPTH));+        // Dictionaries count, and an unterminated construct must not run past the end.+        assert!(nesting_is_too_deep(&b"<<".repeat(MAX_DEPTH as usize + 1), MAX_DEPTH));+        assert!(!nesting_is_too_deep(b"BT (unterminated", MAX_DEPTH));+        assert!(!nesting_is_too_deep(b"BT <unterminated", MAX_DEPTH));+    }+     #[test]     fn stream_operations_leaves_a_healthy_nested_stream_to_lopdf() {         let doc = Document::with_version("1.5");
pdf/src/main/rust/src/differential_tests.rs
diff --git a/pdf/src/main/rust/src/differential_tests.rs b/pdf/src/main/rust/src/differential_tests.rsnew file mode 100644index 0000000000..eb432fdded--- /dev/null+++ b/pdf/src/main/rust/src/differential_tests.rs@@ -0,0 +1,1255 @@+//! Differential tests: invariant and metamorphic checks that do not need an+//! oracle.+//!+//! Why this module exists. Rounds 1 and 2 verified ~90 fixes by reading ISO+//! 32000-1 and asserting what we concluded. That process cannot catch a bug+//! where the code is SELF-CONSISTENT but our reading of the spec was WRONG,+//! because the tests assert the same belief the code implements — they agree+//! with us by construction. Two families of check escape that trap without+//! needing a second implementation:+//!+//! * INVARIANTS that must hold whatever the right answer is. Rendering the same+//!   page twice must produce identical primitives; rendering page N must not+//!   depend on whether page M was rendered first. These are true of every+//!   conforming renderer and of every non-conforming one, so they are immune to+//!   a mistaken spec reading. They are exactly the checks that catch leaking+//!   shared state — see the `FontCacheScope` thread-local in `fonts.rs`.+//! * METAMORPHIC relations, where a transformation of the input implies a+//!   predictable transformation of the output. We need not know where a mark+//!   belongs on a `/Rotate 90` page to know that turning the page four times+//!   must put it back where it started, or that prepending a `cm` translation+//!   must move it by exactly that vector.+//!+//! A reference renderer was investigated and none was usable here; see the+//! module-level note in the report. These checks are what remains valuable+//! regardless, and were wanted even if a reference had been found.+//!+//! House style follows `golden_tests.rs`: build with `lopdf`, run the real+//! pipeline. Unlike `golden_tests.rs` this module deliberately compares EXACT+//! fingerprints rather than meaning, because the property under test is+//! bit-level reproducibility — a "close enough" comparison would let precisely+//! the cache-staleness bugs being hunted slip through.++use crate::*;+use lopdf::content::{Content, Operation};+use lopdf::{dictionary, Object, Stream};++// ---------------------------------------------------------------------------+// Exact fingerprinting of a rendered page+//+// `Prim` deliberately derives nothing — not `Debug`, not `PartialEq` — so the+// determinism checks need their own total projection. Every field of every+// variant is matched by name with no `..` rest pattern, which means adding a+// field to `Prim` breaks THIS FILE at compile time. That is intentional: a new+// field silently excluded from the fingerprint would quietly weaken every test+// below into a vacuous pass.++fn fnv1a(bytes: &[u8]) -> u64 {+    let mut h: u64 = 0xcbf2_9ce4_8422_2325;+    for &b in bytes {+        h ^= b as u64;+        h = h.wrapping_mul(0x100_0000_01b3);+    }+    h+}++/// Floats go in as raw bits, never as formatted decimals. Two renders that+/// differ by one ULP are a determinism bug, and `{:?}` would round them into+/// agreement and hide it. Bit equality also distinguishes `0.0` from `-0.0`.+fn f32b(v: f32) -> String {+    format!("{:08x}", v.to_bits())+}++fn f64b(v: f64) -> String {+    format!("{:016x}", v.to_bits())+}++fn fp_mat(m: &Mat) -> String {+    m.iter().map(|v| f64b(*v)).collect::<Vec<_>>().join(",")+}++fn fp_pts(pts: &[(f32, f32)]) -> String {+    let mut s = String::with_capacity(pts.len() * 18);+    for (x, y) in pts {+        s.push_str(&f32b(*x));+        s.push(':');+        s.push_str(&f32b(*y));+        s.push(';');+    }+    s+}++fn fp_path_ops(ops: &Option<Vec<PathOp>>) -> String {+    match ops {+        None => "none".to_string(),+        Some(v) => v+            .iter()+            .map(|o| match o {+                PathOp::Move(a, b) => format!("M{}:{}", f32b(*a), f32b(*b)),+                PathOp::Line(a, b) => format!("L{}:{}", f32b(*a), f32b(*b)),+                PathOp::Cubic(a, b, c, d, e, f) => format!(+                    "C{}:{}:{}:{}:{}:{}",+                    f32b(*a),+                    f32b(*b),+                    f32b(*c),+                    f32b(*d),+                    f32b(*e),+                    f32b(*f)+                ),+                PathOp::Close => "Z".to_string(),+            })+            .collect::<Vec<_>>()+            .join(","),+    }+}++/// A total, exact projection of one primitive to a string.+///+/// Bulk pixel payloads are hashed rather than inlined — a page with a 4 MB+/// image would otherwise produce an 8 MB fingerprint per render — but the hash+/// covers every byte, so a single differing pixel still changes the result.+fn fp_prim(p: &Prim) -> String {+    match p {+        Prim::Text {+            x,+            y,+            size,+            argb,+            text,+            stroke_argb,+            stroke_width,+            advance,+            render_mode,+            blend,+            is_bold,+            is_italic,+            font_family,+            outline,+            h_scale,+        } => format!(+            "Text|{}|{}|{}|{:08x}|{}|{:?}|{:?}|{}|{}|{}|{}|{}|{}|{}|{}",+            f32b(*x),+            f32b(*y),+            f32b(*size),+            argb,+            text.escape_debug(),+            stroke_argb,+            stroke_width.map(f32b),+            f32b(*advance),+            render_mode,+            *blend as u8,+            is_bold,+            is_italic,+            font_family,+            outline,+            f32b(*h_scale)+        ),+        Prim::Fill { argb, even_odd, contours, blend } => format!(+            "Fill|{:08x}|{}|{}|{}",+            argb,+            even_odd,+            contours.iter().map(|c| fp_pts(c)).collect::<Vec<_>>().join("/"),+            *blend as u8+        ),+        Prim::Stroke { argb, width, dash, dash_phase, cap, join, miter, pts, blend } => format!(+            "Stroke|{:08x}|{}|{}|{}|{}|{}|{}|{}|{}",+            argb,+            f32b(*width),+            dash.iter().map(|d| f32b(*d)).collect::<Vec<_>>().join(","),+            f32b(*dash_phase),+            cap,+            join,+            f32b(*miter),+            fp_pts(pts),+            *blend as u8+        ),+        Prim::Image { ctm, w, h, format, data, alpha, blend } => format!(+            "Image|{}|{}|{}|{}|{}|{:016x}|{}|{}",+            fp_mat(ctm),+            w,+            h,+            format,+            data.len(),+            fnv1a(data),+            f32b(*alpha),+            *blend as u8+        ),+        Prim::ImageTiled {+            ctm,+            w,+            h,+            data,+            xstep,+            ystep,+            i0,+            j0,+            nx,+            ny,+            alpha,+            blend,+        } => format!(+            "ImageTiled|{}|{}|{}|{}|{:016x}|{}|{}|{}|{}|{}|{}|{}|{}",+            fp_mat(ctm),+            w,+            h,+            data.len(),+            fnv1a(data),+            f32b(*xstep),+            f32b(*ystep),+            i0,+            j0,+            nx,+            ny,+            f32b(*alpha),+            *blend as u8+        ),+        Prim::ClipPush { even_odd, pts, path_ops } => {+            format!("ClipPush|{}|{}|{}", even_odd, fp_pts(pts), fp_path_ops(path_ops))+        }+        Prim::ClipPop => "ClipPop".to_string(),+        Prim::TextClipApply => "TextClipApply".to_string(),+        Prim::GroupPush { isolated, knockout, alpha, blend } => format!(+            "GroupPush|{}|{}|{}|{}",+            isolated,+            knockout,+            f32b(*alpha),+            *blend as u8+        ),+        Prim::GroupPop => "GroupPop".to_string(),+        Prim::SoftMaskPush { mask_type } => format!("SoftMaskPush|{}", mask_type),+        Prim::SoftMaskTransfer(lut) => format!("SoftMaskTransfer|{:016x}", fnv1a(&lut[..])),+        Prim::SoftMaskContent => "SoftMaskContent".to_string(),+        Prim::SoftMaskPop => "SoftMaskPop".to_string(),+    }+}++/// Order-sensitive fingerprint of a whole rendered page, dimensions included.+/// Order matters because primitive order IS the paint order; a renderer that+/// emitted the same set in a different sequence would draw a different page.+fn fingerprint(page: &PageData) -> String {+    let mut s = format!("{}x{}\n", f32b(page.width), f32b(page.height));+    for (i, p) in page.prims.iter().enumerate() {+        s.push_str(&format!("{i}:{}\n", fp_prim(p)));+    }+    s+}++/// Where the fingerprints first diverge, for a failure message that names the+/// offending primitive instead of dumping two multi-kilobyte blobs.+fn first_difference(a: &str, b: &str) -> String {+    let (mut la, mut lb) = (a.lines(), b.lines());+    let mut n = 0;+    loop {+        match (la.next(), lb.next()) {+            (None, None) => return "identical".to_string(),+            (x, y) if x == y => n += 1,+            (x, y) => return format!("line {n}:\n  first:  {x:?}\n  second: {y:?}"),+        }+    }+}++// ---------------------------------------------------------------------------+// Fixture builders (mirrors of the `golden_tests.rs` helpers, which are private+// to that module)++fn assemble_with_contents(+    doc: &mut Document,+    contents: Object,+    resources: Dictionary,+    page: &mut Dictionary,+    catalog: Dictionary,+) -> ObjectId {+    let pages_id = doc.new_object_id();+    page.set("Type", Object::Name(b"Page".to_vec()));+    page.set("Parent", pages_id);+    page.set("Resources", resources);+    if !matches!(contents, Object::Null) {+        page.set("Contents", contents);+    }+    if page.get(b"MediaBox").is_err() {+        page.set("MediaBox", vec![0.into(), 0.into(), 612.into(), 792.into()]);+    }+    let page_id = doc.add_object(page.clone());+    doc.objects.insert(+        pages_id,+        Object::Dictionary(dictionary! {+            "Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1,+        }),+    );+    let mut cat = catalog;+    cat.set("Type", Object::Name(b"Catalog".to_vec()));+    cat.set("Pages", pages_id);+    let catalog_id = doc.add_object(cat);+    doc.trailer.set("Root", catalog_id);+    page_id+}++fn assemble(+    doc: &mut Document,+    content: Vec<u8>,+    resources: Dictionary,+    mut page: Dictionary,+) -> ObjectId {+    let content_id = doc.add_object(Stream::new(dictionary! {}, content));+    assemble_with_contents(+        doc,+        Object::Reference(content_id),+        resources,+        &mut page,+        dictionary! {},+    )+}++fn page_from_ops(doc: &mut Document, ops: Vec<Operation>, resources: Dictionary) -> ObjectId {+    let bytes = Content { operations: ops }.encode().unwrap();+    assemble(doc, bytes, resources, dictionary! {})+}++/// Build a many-page document. `per_page` supplies the operator list and the+/// resource dictionary for page `i`, so callers can give each page a distinct+/// font object — the arrangement that would expose a font cache keyed on the+/// resource NAME rather than the font object's id.+fn multi_page_doc<F>(n: usize, mut per_page: F) -> (Document, Vec<ObjectId>)+where+    F: FnMut(&mut Document, usize) -> (Vec<Operation>, Dictionary),+{+    let mut doc = Document::with_version("1.5");+    let pages_id = doc.new_object_id();+    let mut page_ids = Vec::new();+    for i in 0..n {+        let (ops, resources) = per_page(&mut doc, i);+        let content_id =+            doc.add_object(Stream::new(dictionary! {}, Content { operations: ops }.encode().unwrap()));+        let page_id = doc.add_object(dictionary! {+            "Type" => "Page",+            "Parent" => pages_id,+            "MediaBox" => vec![0.into(), 0.into(), 300.into(), 200.into()],+            "Contents" => content_id,+            "Resources" => resources,+        });+        page_ids.push(page_id);+    }+    doc.objects.insert(+        pages_id,+        Object::Dictionary(dictionary! {+            "Type" => "Pages",+            "Kids" => page_ids.iter().map(|id| Object::Reference(*id)).collect::<Vec<_>>(),+            "Count" => n as i64,+        }),+    );+    let catalog_id = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });+    doc.trailer.set("Root", catalog_id);+    (doc, page_ids)+}++/// A page touching as many subsystems as one fixture reasonably can: a filled+/// path, a dashed stroke, text through a simple font, a Form XObject, an image+/// XObject, an axial shading, and an ExtGState luminosity soft mask.+///+/// Breadth is the point. A determinism check over a single filled rectangle+/// would pass even if the font cache were badly broken, so the fixture has to+/// reach the caches, the shading sampler and the mask bracketing code.+fn rich_page(doc: &mut Document) -> ObjectId {+    let font_id = doc.add_object(dictionary! {+        "Type" => "Font", "Subtype" => "Type1",+        "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding",+    });++    let form_ops = Content {+        operations: vec![+            Operation::new("0 1 0 rg", vec![]),+            Operation::new("re", vec![0.into(), 0.into(), 20.into(), 20.into()]),+            Operation::new("f", vec![]),+        ],+    }+    .encode()+    .unwrap();+    let form_id = doc.add_object(Stream::new(+        dictionary! {+            "Type" => "XObject", "Subtype" => "Form",+            "BBox" => vec![0.into(), 0.into(), 20.into(), 20.into()],+        },+        form_ops,+    ));++    // 2x2 DeviceRGB image.+    let img_id = doc.add_object(Stream::new(+        dictionary! {+            "Type" => "XObject", "Subtype" => "Image",+            "Width" => 2, "Height" => 2,+            "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8,+        },+        vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0],+    ));++    // Luminosity soft-mask group.+    let mask_ops = Content {+        operations: vec![+            Operation::new("0.5 g", vec![]),+            Operation::new("re", vec![0.into(), 0.into(), 100.into(), 100.into()]),+            Operation::new("f", vec![]),+        ],+    }+    .encode()+    .unwrap();+    let mask_group_id = doc.add_object(Stream::new(+        dictionary! {+            "Type" => "XObject", "Subtype" => "Form",+            "BBox" => vec![0.into(), 0.into(), 100.into(), 100.into()],+            "Group" => dictionary! {+                "S" => "Transparency", "CS" => "DeviceGray", "I" => true,+            },+        },+        mask_ops,+    ));+    let gs_id = doc.add_object(dictionary! {+        "Type" => "ExtGState",+        "SMask" => dictionary! { "S" => "Luminosity", "G" => mask_group_id },+    });++    let shading = dictionary! {+        "ShadingType" => 2,+        "ColorSpace" => "DeviceRGB",+        "Coords" => vec![0.into(), 0.into(), 120.into(), 0.into()],+        "Function" => dictionary! {+            "FunctionType" => 2,+            "Domain" => vec![0.into(), 1.into()],+            "C0" => vec![1.into(), 0.into(), 0.into()],+            "C1" => vec![0.into(), 0.into(), 1.into()],+            "N" => 1,+        },+    };++    let resources = dictionary! {+        "Font" => dictionary! { "F1" => font_id },+        "XObject" => dictionary! { "Fm0" => form_id, "Im0" => img_id },+        "ExtGState" => dictionary! { "GS0" => gs_id },+        "Shading" => dictionary! { "Sh0" => shading },+    };++    let ops = vec![+        // Filled path.+        Operation::new("rg", vec![0.9.into(), 0.1.into(), 0.2.into()]),+        Operation::new("re", vec![10.into(), 10.into(), 60.into(), 40.into()]),+        Operation::new("f", vec![]),+        // Dashed stroke with a bezier.+        Operation::new("RG", vec![0.into(), 0.into(), 1.into()]),+        Operation::new("w", vec![3.into()]),+        Operation::new("d", vec![vec![4.into(), 2.into()].into(), 1.into()]),+        Operation::new("m", vec![10.into(), 120.into()]),+        Operation::new("c", vec![40.into(), 160.into(), 80.into(), 80.into(), 120.into(), 120.into()]),+        Operation::new("S", vec![]),+        // Text.+        Operation::new("BT", vec![]),+        Operation::new("Tf", vec![Object::Name(b"F1".to_vec()), 14.into()]),+        Operation::new("Td", vec![20.into(), 70.into()]),+        Operation::new("Tj", vec![Object::string_literal("Diff Wg")]),+        Operation::new("ET", vec![]),+        // Form XObject under a translation.+        Operation::new("q", vec![]),+        Operation::new("cm", vec![1.into(), 0.into(), 0.into(), 1.into(), 200.into(), 20.into()]),+        Operation::new("Do", vec![Object::Name(b"Fm0".to_vec())]),+        Operation::new("Q", vec![]),+        // Image XObject.+        Operation::new("q", vec![]),+        Operation::new("cm", vec![40.into(), 0.into(), 0.into(), 40.into(), 220.into(), 90.into()]),+        Operation::new("Do", vec![Object::Name(b"Im0".to_vec())]),+        Operation::new("Q", vec![]),+        // Soft-masked shading inside a clip.+        Operation::new("q", vec![]),+        Operation::new("gs", vec![Object::Name(b"GS0".to_vec())]),+        Operation::new("re", vec![100.into(), 150.into(), 120.into(), 40.into()]),+        Operation::new("W", vec![]),+        Operation::new("n", vec![]),+        Operation::new("sh", vec![Object::Name(b"Sh0".to_vec())]),+        Operation::new("Q", vec![]),+    ];++    let bytes = Content { operations: ops }.encode().unwrap();+    assemble(+        doc,+        bytes,+        resources,+        dictionary! { "MediaBox" => vec![0.into(), 0.into(), 300.into(), 200.into()] },+    )+}++// ---------------------------------------------------------------------------+// Invariant: rendering is a pure function of (document, page)++/// Rendering the same page repeatedly must produce byte-identical primitives.+///+/// This is the primary guard on the `FontCacheScope` thread-local in+/// `fonts.rs`: the cache is installed and torn down inside `interpret_page`, so+/// the second render must repopulate it from scratch and reach exactly the same+/// answer. A cache that returned a partly-initialised or mutated `FontInfo` on+/// a hit, or a sampler that accumulated state in a static, shows up here as a+/// divergence. Ten repeats rather than two so an alternating (even/odd) fault+/// cannot hide.+#[test]+fn same_page_rendered_repeatedly_is_identical() {+    let mut doc = Document::with_version("1.5");+    let page_id = rich_page(&mut doc);++    let baseline = fingerprint(&interpret_page(&doc, page_id).expect("render"));+    assert!(+        baseline.lines().count() > 8,+        "fixture must emit a substantial number of primitives, else this test is vacuous; got:\n{baseline}"+    );++    for i in 1..10 {+        let again = fingerprint(&interpret_page(&doc, page_id).expect("render"));+        assert_eq!(+            baseline,+            again,+            "render {i} diverged from render 0: {}",+            first_difference(&baseline, &again)+        );+    }+}++/// The same invariant one level up, through the handle API and the wire+/// serializer, so a non-determinism introduced by `wire::serialize` (map+/// iteration order, uninitialised padding) is caught too.+#[test]+fn wire_bytes_are_identical_across_renders() {+    let mut doc = Document::with_version("1.5");+    rich_page(&mut doc);+    let mut bytes = Vec::new();+    doc.save_to(&mut bytes).unwrap();++    let handle = open_document(&bytes);+    assert_ne!(handle, 0, "fixture must open");+    let first = render_page(handle, 0).expect("render 0");+    assert!(first.len() > 64, "wire buffer suspiciously small: {}", first.len());+    for i in 1..5 {+        let again = render_page(handle, 0).expect("render again");+        assert_eq!(first.len(), again.len(), "wire length changed on render {i}");+        assert!(first == again, "wire bytes changed on render {i}");+    }+    close_document(handle);+}++/// Two independent `Document`s parsed from the same bytes must render+/// identically. Distinguishes a genuinely pure pipeline from one that happens+/// to be stable only because it keeps hitting the same warm cache: here the+/// second document has different object addresses and a cold cache, so any+/// dependence on either would surface.+#[test]+fn two_documents_from_the_same_bytes_agree() {+    let mut doc = Document::with_version("1.5");+    rich_page(&mut doc);+    let mut bytes = Vec::new();+    doc.save_to(&mut bytes).unwrap();++    let a = load_document_lenient(&bytes).expect("load a");+    let b = load_document_lenient(&bytes).expect("load b");+    let pa = nth_page_id(&a, 0).expect("page a");+    let pb = nth_page_id(&b, 0).expect("page b");++    let fa = fingerprint(&interpret_page(&a, pa).expect("render a"));+    let fb = fingerprint(&interpret_page(&b, pb).expect("render b"));+    assert_eq!(fa, fb, "reparsed document differs: {}", first_difference(&fa, &fb));+}++// ---------------------------------------------------------------------------+// Invariant: page independence++/// A four-page document where every page has its OWN font object bound to the+/// SAME resource name `/F1`, and draws different text.+///+/// This is the adversarial shape for a font cache: if the cache key were the+/// resource name, or the page's resource dictionary, page 1 would be served+/// page 0's font. It is keyed on `(document address, font ObjectId)`+/// (`fonts.rs:220`), which should be immune — this fixture is what proves it+/// rather than assuming it.+fn distinct_font_per_page_doc() -> (Document, Vec<ObjectId>) {+    const FACES: [&str; 4] = ["Helvetica", "Courier", "Times-Roman", "Helvetica-Bold"];+    multi_page_doc(4, |doc, i| {+        let font_id = doc.add_object(dictionary! {+            "Type" => "Font", "Subtype" => "Type1",+            "BaseFont" => FACES[i], "Encoding" => "WinAnsiEncoding",+        });+        let ops = vec![+            Operation::new("BT", vec![]),+            Operation::new("Tf", vec![Object::Name(b"F1".to_vec()), (12 + i as i64).into()]),+            Operation::new("Td", vec![20.into(), (30 + 25 * i as i64).into()]),+            Operation::new("Tj", vec![Object::string_literal(format!("page{i} WAV"))]),+            Operation::new("ET", vec![]),+            Operation::new("rg", vec![(0.2 * i as f64).into(), 0.4.into(), 0.6.into()]),+            Operation::new("re", vec![(10 * i as i64).into(), 5.into(), 30.into(), 12.into()]),+            Operation::new("f", vec![]),+        ];+        (ops, dictionary! { "Font" => dictionary! { "F1" => font_id } })+    })+}++/// Rendering page N must not depend on which pages were rendered before it.+///+/// Checked against three orders: forward, reverse, and each page rendered in+/// isolation by a freshly reparsed document. The isolated pass is the real+/// control — it is the only one where no other page has ever been touched, so+/// agreement with it means "no page leaked into any other".+#[test]+fn page_rendering_is_independent_of_order() {+    let (mut doc, page_ids) = distinct_font_per_page_doc();+    let n = page_ids.len();++    let forward: Vec<String> = (0..n)+        .map(|i| fingerprint(&interpret_page(&doc, page_ids[i]).expect("fwd")))+        .collect();++    let mut reverse = vec![String::new(); n];+    for i in (0..n).rev() {+        reverse[i] = fingerprint(&interpret_page(&doc, page_ids[i]).expect("rev"));+    }++    // Isolated: a brand-new Document per page, so nothing else has been rendered.+    let mut bytes = Vec::new();+    doc.save_to(&mut bytes).unwrap();+    let isolated: Vec<String> = (0..n)+        .map(|i| {+            let fresh = load_document_lenient(&bytes).expect("reload");+            let pid = nth_page_id(&fresh, i as i32).expect("page");+            fingerprint(&interpret_page(&fresh, pid).expect("iso"))+        })+        .collect();++    for i in 0..n {+        assert_eq!(+            forward[i], reverse[i],+            "page {i} depends on render order: {}",+            first_difference(&forward[i], &reverse[i])+        );+        assert_eq!(+            forward[i], isolated[i],+            "page {i} differs when rendered alone, i.e. another page leaked into it: {}",+            first_difference(&forward[i], &isolated[i])+        );+    }++    // Guard against a vacuous pass: the pages must actually differ from each+    // other, or "order does not matter" would be trivially true.+    for i in 1..n {+        assert_ne!(forward[0], forward[i], "fixture pages 0 and {i} are indistinguishable");+    }+}++/// The narrow form of the same property, stated the way a bug report would be:+/// render page 3 first, then render it again after rendering pages 0..3.+#[test]+fn rendering_a_page_first_or_last_agrees() {+    let (doc, page_ids) = distinct_font_per_page_doc();+    let last = *page_ids.last().unwrap();++    let alone = fingerprint(&interpret_page(&doc, last).expect("alone"));+    for pid in &page_ids[..page_ids.len() - 1] {+        let _ = interpret_page(&doc, *pid).expect("warm the caches");+    }+    let after = fingerprint(&interpret_page(&doc, last).expect("after"));+    assert_eq!(+        alone, after,+        "rendering earlier pages changed this page: {}",+        first_difference(&alone, &after)+    );+}++/// The text index is built for every page under ONE `FontCacheScope`+/// (`search.rs:49`), unlike rendering which scopes per page. Building it twice+/// must agree, and it must agree with a build from a reparsed document.+#[test]+fn text_index_is_reproducible() {+    let (mut doc, _) = distinct_font_per_page_doc();+    let first: Vec<String> = crate::search::build_index(&doc).iter().map(|p| p.text.clone()).collect();+    let second: Vec<String> = crate::search::build_index(&doc).iter().map(|p| p.text.clone()).collect();+    assert_eq!(first, second, "build_index is not deterministic");++    let mut bytes = Vec::new();+    doc.save_to(&mut bytes).unwrap();+    let fresh = load_document_lenient(&bytes).expect("reload");+    let third: Vec<String> = crate::search::build_index(&fresh).iter().map(|p| p.text.clone()).collect();+    assert_eq!(first, third, "build_index differs on a reparsed document");++    assert!(+        first.iter().any(|t| !t.trim().is_empty()),+        "fixture produced no indexed text, so this test would be vacuous: {first:?}"+    );+}++/// Directly probes the documented weak point of the font cache key.+///+/// The key is `(doc as *const Document as usize, font ObjectId)`+/// (`fonts.rs:220`), and `fonts.rs:169` argues that is safe because a+/// `FontCacheScope` is short-lived and never spans two documents. Address+/// reuse is normally hard to force, so this test removes the chance element:+/// it renders document A through a boxed pointer, then overwrites THAT SAME+/// BOX in place with document B. B is therefore guaranteed to live at the exact+/// address A did, with colliding object ids, while an outer scope is still+/// open.+///+/// If the cache leaks, B's `/F1` resolves to A's cached font and B renders with+/// the wrong face.+///+/// HISTORY. This test originally FAILED and was `#[ignore]`d as a documented+/// tripwire: the key was `(doc as *const Document as usize, font ObjectId)`, and+/// document B (Courier, monospaced) rendered with document A's Helvetica metrics+/// — advances 19.99/6.67/5.33 for `M`/space/`i`, which are 833/278/222 per mille+/// at 24pt, instead of Courier's uniform 14.4 — with `font_family` flipping from+/// 2 (mono) to 0 (sans). `residuals` then removed the raw pointer from the key+/// entirely: it is now the `ObjectId` alone, and a hit additionally requires the+/// stored font dictionary to still equal the one that id resolves to. The test+/// passes and is enabled.+///+/// It is kept because the reproduction is the cheap part and the guarantee is+/// worth pinning: an address is not a stable document identity, and nothing else+/// in the suite enforces that.+#[test]+fn font_cache_does_not_leak_between_documents_at_one_address() {+    // Two documents, same object numbering, deliberately different faces.+    let build = |face: &str, label: &str| {+        let mut doc = Document::with_version("1.5");+        let font_id = doc.add_object(dictionary! {+            "Type" => "Font", "Subtype" => "Type1",+            "BaseFont" => face, "Encoding" => "WinAnsiEncoding",+        });+        let ops = vec![+            Operation::new("BT", vec![]),+            Operation::new("Tf", vec![Object::Name(b"F1".to_vec()), 24.into()]),+            Operation::new("Td", vec![10.into(), 40.into()]),+            Operation::new("Tj", vec![Object::string_literal(label)]),+            Operation::new("ET", vec![]),+        ];+        let page_id = page_from_ops(&mut doc, ops, dictionary! {+            "Font" => dictionary! { "F1" => font_id }+        });+        (doc, page_id)+    };++    // Control renders, each with its own scope, no sharing possible.+    let (doc_a, pa) = build("Helvetica", "MMM iii");+    let (doc_b, pb) = build("Courier", "MMM iii");+    let want_a = fingerprint(&interpret_page(&doc_a, pa).expect("a"));+    let want_b = fingerprint(&interpret_page(&doc_b, pb).expect("b"));+    // Courier is monospaced and Helvetica is not, so "MMM iii" must advance+    // differently. Without this the test could pass by both being wrong.+    assert_ne!(+        want_a, want_b,+        "fixture fonts are indistinguishable; pick faces with different metrics"+    );+    drop(doc_a);+    drop(doc_b);++    // Now the adversarial arrangement: one outer scope spanning both documents,+    // with B forced to occupy A's address.+    let (got_a, got_b) = {+        let _outer = crate::FontCacheScope::new();++        let (doc_a2, pa2) = build("Helvetica", "MMM iii");+        let mut slot = Box::new(doc_a2);+        let addr_a = &*slot as *const Document as usize;+        let got_a = fingerprint(&interpret_page(&slot, pa2).expect("a2"));++        let (doc_b2, pb2) = build("Courier", "MMM iii");+        *slot = doc_b2; // same heap address, different document+        let addr_b = &*slot as *const Document as usize;+        assert_eq!(+            addr_a, addr_b,+            "in-place overwrite failed to reuse the address; test cannot conclude"+        );+        let got_b = fingerprint(&interpret_page(&slot, pb2).expect("b2"));+        (got_a, got_b)+    };++    assert_eq!(got_a, want_a, "document A rendered differently under an outer cache scope");+    assert_eq!(+        got_b, want_b,+        "STALE FONT CACHE: document B at document A's address was served A's cached font. {}",+        first_difference(&want_b, &got_b)+    );+}++// ---------------------------------------------------------------------------+// Metamorphic: page rotation++/// The font cache key requires the STORED font dictionary to still equal the one+/// the object id resolves to now (`fonts.rs`, `cached_font`). That kills the+/// address-reuse collision above, but `Dictionary` equality is SHALLOW: a font+/// dictionary carries indirect references (`/Widths`, `/FontDescriptor`,+/// `/ToUnicode`, `/DescendantFonts`), and comparing them compares object+/// NUMBERS, not the objects they resolve to.+///+/// So two documents can hold a byte-identical font dictionary at the same object+/// id whose referenced metrics differ completely. This fixture is that case,+/// reduced to its simplest form: both documents allocate objects in the same+/// order, so both have the font at the same id with a dictionary naming+/// `/Widths 1 0 R`; only the CONTENTS of object 1 differ (every glyph 500/1000+/// vs 900/1000). Nothing about the dictionaries distinguishes them.+///+/// Same precondition as the address-reuse case — it needs one scope spanning two+/// documents, which no current caller does — so this is latent too. It is here+/// because "a colliding object id from another document cannot be served" is+/// slightly stronger than what shallow dictionary equality actually buys, and+/// that gap should be written down rather than rediscovered.+///+/// IGNORED, and it FAILS when run, exactly as its predecessor did before the fix.+/// Verified 2026-08-29 against the `ObjectId` + stored-dictionary key: the+/// 900/1000 document was served the 500/1000 document's metrics, giving an+/// advance of 10.0 (= 500/1000 x 20pt) where 18.0 (= 900/1000 x 20pt) is correct,+/// and glyph origins at 10/20/30 instead of 10/28/46. Ignored because no caller+/// can reach it, NOT because the finding is doubtful. Routed to `residuals`.+///+/// A deep fix does not need a deep dictionary compare: including the resolved+/// generation of each indirect target would cost as much as the parse being+/// cached. Cheaper is to scope the cache to a document identity that cannot be+/// recycled — a monotonic id minted per `Document` load — which closes the class+/// rather than another instance of it.+#[ignore = "latent, not live: stale hit through shallow /Widths dictionary equality, unreachable \+            by any current caller; see the doc comment and the note routed to residuals"]+#[test]+fn font_cache_distinguishes_documents_whose_font_dicts_are_equal_but_indirect_targets_differ() {+    let build = |width: i64| {+        let mut doc = Document::with_version("1.5");+        // Object 1: the widths array. Same id in both documents, different values.+        let widths: Vec<Object> = (32..=122).map(|_| width.into()).collect();+        let widths_id = doc.add_object(Object::Array(widths));+        // Object 2: the font dictionary. Byte-identical in both documents.+        let font_id = doc.add_object(dictionary! {+            "Type" => "Font", "Subtype" => "Type1",+            "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding",+            "FirstChar" => 32, "LastChar" => 122,+            "Widths" => widths_id,+        });+        let ops = vec![+            Operation::new("BT", vec![]),+            Operation::new("Tf", vec![Object::Name(b"F1".to_vec()), 20.into()]),+            Operation::new("Td", vec![10.into(), 40.into()]),+            Operation::new("Tj", vec![Object::string_literal("iii")]),+            Operation::new("ET", vec![]),+        ];+        let page_id = page_from_ops(&mut doc, ops, dictionary! {+            "Font" => dictionary! { "F1" => font_id }+        });+        (doc, page_id, font_id)+    };++    let (narrow, np, nf) = build(500);+    let (wide, wp, wf) = build(900);+    assert_eq!(nf, wf, "fixture must place the font at the same object id in both documents");+    assert_eq!(+        narrow.get_object(nf).unwrap().as_dict().unwrap(),+        wide.get_object(wf).unwrap().as_dict().unwrap(),+        "fixture must give both documents an EQUAL font dictionary, else it proves nothing"+    );++    let want_narrow = fingerprint(&interpret_page(&narrow, np).expect("narrow"));+    let want_wide = fingerprint(&interpret_page(&wide, wp).expect("wide"));+    assert_ne!(+        want_narrow, want_wide,+        "/Widths is not reaching the advances, so this test cannot detect a stale hit"+    );++    // One scope spanning both documents: the arrangement a cache hit needs.+    let (got_narrow, got_wide) = {+        let _outer = crate::FontCacheScope::new();+        let a = fingerprint(&interpret_page(&narrow, np).expect("narrow scoped"));+        let b = fingerprint(&interpret_page(&wide, wp).expect("wide scoped"));+        (a, b)+    };++    assert_eq!(got_narrow, want_narrow, "first document changed under a shared cache scope");+    assert_eq!(+        got_wide, want_wide,+        "STALE FONT CACHE via shallow dictionary equality: the second document's font \+         resolves to different /Widths through an identical dictionary, but was served \+         the first document's parsed metrics. {}",+        first_difference(&want_wide, &got_wide)+    );+}++/// The live counterpart of the ignored test above: the SAME address-reuse+/// arrangement, but without an outer `FontCacheScope` — which is exactly how+/// production calls in. `interpret_page` opens and drops its own scope per call+/// (`interpret.rs:113`), so the cache must be empty on entry and document B must+/// render with its own font despite sitting at document A's address.+///+/// This is the property that currently protects us, and it was previously+/// implicit. Pinning it means the protection cannot be removed silently: if+/// someone hoists the scope out of `interpret_page` for a performance win, this+/// test goes red rather than the bug shipping.+#[test]+fn font_cache_is_scoped_per_render_so_address_reuse_is_safe() {+    let build = |face: &str| {+        let mut doc = Document::with_version("1.5");+        let font_id = doc.add_object(dictionary! {+            "Type" => "Font", "Subtype" => "Type1",+            "BaseFont" => face, "Encoding" => "WinAnsiEncoding",+        });+        let ops = vec![+            Operation::new("BT", vec![]),+            Operation::new("Tf", vec![Object::Name(b"F1".to_vec()), 24.into()]),+            Operation::new("Td", vec![10.into(), 40.into()]),+            Operation::new("Tj", vec![Object::string_literal("MMM iii")]),+            Operation::new("ET", vec![]),+        ];+        let page_id = page_from_ops(&mut doc, ops, dictionary! {+            "Font" => dictionary! { "F1" => font_id }+        });+        (doc, page_id)+    };++    let (ctl_a, ca) = build("Helvetica");+    let (ctl_b, cb) = build("Courier");+    let want_a = fingerprint(&interpret_page(&ctl_a, ca).expect("ctl a"));+    let want_b = fingerprint(&interpret_page(&ctl_b, cb).expect("ctl b"));+    assert_ne!(want_a, want_b, "fixture fonts must be distinguishable");+    drop(ctl_a);+    drop(ctl_b);++    // No outer scope here: this is the production arrangement.+    let (doc_a, pa) = build("Helvetica");+    let mut slot = Box::new(doc_a);+    let addr_a = &*slot as *const Document as usize;+    let got_a = fingerprint(&interpret_page(&slot, pa).expect("a"));++    let (doc_b, pb) = build("Courier");+    *slot = doc_b;+    assert_eq!(+        addr_a,+        &*slot as *const Document as usize,+        "in-place overwrite failed to reuse the address; test cannot conclude"+    );+    let got_b = fingerprint(&interpret_page(&slot, pb).expect("b"));++    assert_eq!(got_a, want_a, "document A rendered differently after boxing");+    assert_eq!(+        got_b, want_b,+        "per-render font cache scoping is broken: document B at A's address was \+         served A's font even with no outer scope. {}",+        first_difference(&want_b, &got_b)+    );+}++/// One quarter turn, as documented at `geometry.rs:144`: `(x,y) -> (y, w-x)`,+/// and the page's width/height swap. Returns the mapped point and the new+/// dimensions so the map can be composed.+fn quarter_turn(p: (f64, f64), w: f64, h: f64) -> ((f64, f64), (f64, f64)) {+    ((p.1, w - p.0), (h, w))+}++/// Four quarter turns are the identity on both the point and the dimensions.+///+/// Pure algebra on the documented map, kept as a test because it is the+/// premise every rotation assertion below rests on: if the composition were+/// not the identity, the documented maps could not all describe the same+/// rotation and one of the arms in `page_base_matrix` would have to be wrong.+#[test]+fn four_quarter_turns_compose_to_the_identity() {+    let (w0, h0) = (300.0_f64, 200.0_f64);+    let p0 = (37.0_f64, 91.0_f64);++    let (mut p, mut d) = (p0, (w0, h0));+    let mut seen = Vec::new();+    for _ in 0..4 {+        let (np, nd) = quarter_turn(p, d.0, d.1);+        p = np;+        d = nd;+        seen.push((p, d));+    }++    // Intermediate turns must match the other two documented maps.+    assert_eq!(seen[1].0, (w0 - p0.0, h0 - p0.1), "two turns must equal the 180 map");+    assert_eq!(seen[2].0, (h0 - p0.1, p0.0), "three turns must equal the 270 map");+    assert_eq!(seen[3].0, p0, "four turns must restore the point");+    assert_eq!(seen[3].1, (w0, h0), "four turns must restore the dimensions");+}++/// Marker rectangle and page used by the rotation tests. Asymmetric in both the+/// page (300x200) and the mark's placement, so a swapped 90/270 arm — the+/// regression behind issue #321 — cannot coincidentally still line up.+fn rotated_marker_doc(rotate: Option<i64>) -> (Document, ObjectId) {+    let mut doc = Document::with_version("1.5");+    let mut page = dictionary! { "MediaBox" => vec![0.into(), 0.into(), 300.into(), 200.into()] };+    if let Some(r) = rotate {+        page.set("Rotate", r);+    }+    let bytes = Content {+        operations: vec![+            Operation::new("rg", vec![1.into(), 0.into(), 0.into()]),+            Operation::new("re", vec![20.into(), 30.into(), 40.into(), 25.into()]),+            Operation::new("f", vec![]),+        ],+    }+    .encode()+    .unwrap();+    let page_id = assemble(&mut doc, bytes, dictionary! {}, page);+    (doc, page_id)+}++/// The bounding box of the single filled marker.+fn marker_box(page: &PageData) -> [f64; 4] {+    let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];+    let mut found = false;+    for p in &page.prims {+        if let Prim::Fill { contours, .. } = p {+            for pt in contours.iter().flatten() {+                b[0] = b[0].min(pt.0 as f64);+                b[1] = b[1].min(pt.1 as f64);+                b[2] = b[2].max(pt.0 as f64);+                b[3] = b[3].max(pt.1 as f64);+                found = true;+            }+        }+    }+    assert!(found, "fixture emitted no Fill primitive to measure");+    b+}++fn boxes_close(a: [f64; 4], b: [f64; 4]) -> bool {+    // Generous relative to page size but far tighter than any real rotation+    // error, which displaces the mark by tens of points.+    a.iter().zip(b.iter()).all(|(x, y)| (x - y).abs() < 0.01)+}++/// Rotating the page through the four quarter turns moves the mark exactly as+/// the documented maps predict, and the fourth turn brings it home.+///+/// This is the check that would have caught issue #321 without knowing which+/// way round PDF rotation goes: it never asserts where the mark "should" be,+/// only that each successive turn is one application of the same map as the+/// previous, and that four of them are the identity.+#[test]+fn rotating_a_page_four_quarter_turns_returns_to_the_original() {+    let (d0, p0) = rotated_marker_doc(None);+    let base = interpret_page(&d0, p0).expect("rotate 0");+    let (w0, h0) = (base.width as f64, base.height as f64);+    let mut expect_box = marker_box(&base);+    let mut dims = (w0, h0);++    for (turns, rotate) in [(1, 90_i64), (2, 180), (3, 270), (4, 360)] {+        // Advance the prediction by one quarter turn.+        let corners = [+            (expect_box[0], expect_box[1]),+            (expect_box[2], expect_box[1]),+            (expect_box[2], expect_box[3]),+            (expect_box[0], expect_box[3]),+        ];+        let mut next = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];+        let mut nd = dims;+        for c in corners {+            let (m, d) = quarter_turn(c, dims.0, dims.1);+            nd = d;+            next[0] = next[0].min(m.0);+            next[1] = next[1].min(m.1);+            next[2] = next[2].max(m.0);+            next[3] = next[3].max(m.1);+        }+        expect_box = next;+        dims = nd;++        let (doc, pid) = rotated_marker_doc(Some(rotate));+        let got = interpret_page(&doc, pid).expect("rotated render");+        assert_eq!(+            (got.width as f64, got.height as f64),+            dims,+            "/Rotate {rotate} ({turns} quarter turns) gave the wrong display size"+        );+        let got_box = marker_box(&got);+        assert!(+            boxes_close(got_box, expect_box),+            "/Rotate {rotate} ({turns} quarter turns) put the mark at {got_box:?}, \+             but composing the documented quarter-turn map {turns} times predicts {expect_box:?}"+        );+    }++    // The fourth turn is /Rotate 360, which must be indistinguishable from 0 —+    // not merely close, but the same primitives.+    let (d360, p360) = rotated_marker_doc(Some(360));+    let f0 = fingerprint(&base);+    let f360 = fingerprint(&interpret_page(&d360, p360).expect("rotate 360"));+    assert_eq!(+        f0, f360,+        "/Rotate 360 must render exactly as /Rotate 0: {}",+        first_difference(&f0, &f360)+    );+}++/// `/Rotate` is reduced modulo 360 (§7.7.3.3 requires a multiple of 90; the+/// implementation normalises rather than rejecting). Every value congruent to+/// the same quarter turn must render identically — including negatives, which+/// are the common real-world spelling of a counter-clockwise turn.+#[test]+fn congruent_rotations_render_identically() {+    let canonical: Vec<String> = [0_i64, 90, 180, 270]+        .iter()+        .map(|r| {+            let (d, p) = rotated_marker_doc(Some(*r));+            fingerprint(&interpret_page(&d, p).expect("canonical"))+        })+        .collect();++    for (value, quarter) in [+        (360_i64, 0_usize),+        (720, 0),+        (-360, 0),+        (450, 1),+        (-270, 1),+        (-180, 2),+        (540, 2),+        (-90, 3),+        (630, 3),+    ] {+        let (d, p) = rotated_marker_doc(Some(value));+        let got = fingerprint(&interpret_page(&d, p).expect("congruent"));+        assert_eq!(+            got,+            canonical[quarter],+            "/Rotate {value} must match /Rotate {}: {}",+            quarter * 90,+            first_difference(&canonical[quarter], &got)+        );+    }+}++// ---------------------------------------------------------------------------+// Metamorphic: translation and Form XObject equivalence++/// Prepending a `cm` translation must translate every emitted coordinate by+/// exactly that vector and change nothing else — same primitive kinds, same+/// order, same colours.+#[test]+fn translating_content_translates_the_primitives() {+    const DX: f64 = 37.0;+    const DY: f64 = -21.0;++    let draw = vec![+        Operation::new("rg", vec![0.2.into(), 0.7.into(), 0.3.into()]),+        Operation::new("re", vec![20.into(), 60.into(), 40.into(), 25.into()]),+        Operation::new("f", vec![]),+        Operation::new("w", vec![2.into()]),+        Operation::new("m", vec![15.into(), 100.into()]),+        Operation::new("l", vec![90.into(), 130.into()]),+        Operation::new("S", vec![]),+    ];++    let mut d0 = Document::with_version("1.5");+    let p0 = page_from_ops(&mut d0, draw.clone(), dictionary! {});+    let plain = interpret_page(&d0, p0).expect("plain");++    let mut shifted_ops = vec![Operation::new(+        "cm",+        vec![1.into(), 0.into(), 0.into(), 1.into(), DX.into(), DY.into()],+    )];+    shifted_ops.extend(draw);+    let mut d1 = Document::with_version("1.5");+    let p1 = page_from_ops(&mut d1, shifted_ops, dictionary! {});+    let shifted = interpret_page(&d1, p1).expect("shifted");++    assert_eq!(+        plain.prims.len(),+        shifted.prims.len(),+        "translation changed the primitive count"+    );+    assert!(!plain.prims.is_empty(), "fixture emitted nothing");++    for (i, (a, b)) in plain.prims.iter().zip(shifted.prims.iter()).enumerate() {+        match (a, b) {+            (+                Prim::Fill { argb: c0, contours: k0, .. },+                Prim::Fill { argb: c1, contours: k1, .. },+            ) => {+                assert_eq!(c0, c1, "prim {i}: translation changed the fill colour");+                assert_eq!(k0.len(), k1.len(), "prim {i}: contour count changed");+                for (ca, cb) in k0.iter().zip(k1.iter()) {+                    assert_eq!(ca.len(), cb.len(), "prim {i}: vertex count changed");+                    for (pa, pb) in ca.iter().zip(cb.iter()) {+                        assert!(+                            ((pb.0 - pa.0) as f64 - DX).abs() < 1e-3+                                && ((pb.1 - pa.1) as f64 - DY).abs() < 1e-3,+                            "prim {i}: vertex moved by ({}, {}), expected ({DX}, {DY})",+                            pb.0 - pa.0,+                            pb.1 - pa.1+                        );+                    }+                }+            }+            (Prim::Stroke { pts: s0, width: w0, .. }, Prim::Stroke { pts: s1, width: w1, .. }) => {+                assert_eq!(w0, w1, "prim {i}: a pure translation must not change stroke width");+                assert_eq!(s0.len(), s1.len(), "prim {i}: point count changed");+                for (pa, pb) in s0.iter().zip(s1.iter()) {+                    assert!(+                        ((pb.0 - pa.0) as f64 - DX).abs() < 1e-3+                            && ((pb.1 - pa.1) as f64 - DY).abs() < 1e-3,+                        "prim {i}: point moved by ({}, {}), expected ({DX}, {DY})",+                        pb.0 - pa.0,+                        pb.1 - pa.1+                    );+                }+            }+            _ => panic!("prim {i}: translation changed the primitive kind"),+        }+    }+}++/// Content invoked through a Form XObject with an identity `/Matrix` and a+/// `/BBox` large enough not to clip must paint the same ink as the same content+/// written inline (§8.10.2). The form path runs a different code route —+/// resource inheritance, `q`/`Q` bracketing, bbox clipping — so agreement here+/// is a real check on that route rather than a tautology.+#[test]+fn form_xobject_paints_the_same_ink_as_inline_content() {+    let draw = vec![+        Operation::new("rg", vec![0.1.into(), 0.4.into(), 0.9.into()]),+        Operation::new("re", vec![25.into(), 35.into(), 50.into(), 30.into()]),+        Operation::new("f", vec![]),+        Operation::new("RG", vec![0.into(), 0.5.into(), 0.into()]),+        Operation::new("w", vec![4.into()]),+        Operation::new("m", vec![30.into(), 120.into()]),+        Operation::new("l", vec![140.into(), 150.into()]),+        Operation::new("S", vec![]),+    ];++    let mut inline_doc = Document::with_version("1.5");+    let inline_page = page_from_ops(&mut inline_doc, draw.clone(), dictionary! {});+    let inline = interpret_page(&inline_doc, inline_page).expect("inline");++    let mut form_doc = Document::with_version("1.5");+    let form_bytes = Content { operations: draw }.encode().unwrap();+    let form_id = form_doc.add_object(Stream::new(+        dictionary! {+            "Type" => "XObject", "Subtype" => "Form",+            // Covers the whole page, so /BBox clipping cannot be what differs.+            "BBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],+            "Matrix" => vec![1.into(), 0.into(), 0.into(), 1.into(), 0.into(), 0.into()],+        },+        form_bytes,+    ));+    let form_page = page_from_ops(+        &mut form_doc,+        vec![Operation::new("Do", vec![Object::Name(b"Fm0".to_vec())])],+        dictionary! { "XObject" => dictionary! { "Fm0" => form_id } },+    );+    let via_form = interpret_page(&form_doc, form_page).expect("form");++    assert_eq!(+        inline.width, via_form.width,+        "form and inline disagree on page width"+    );++    // Compare the ink only: the form route legitimately adds clip bracketing+    // primitives for /BBox, which are not ink and must not count as a+    // difference.+    let ink = |page: &PageData| -> Vec<String> {+        page.prims+            .iter()+            .filter(|p| matches!(p, Prim::Fill { .. } | Prim::Stroke { .. } | Prim::Text { .. }))+            .map(fp_prim)+            .collect()+    };+    let a = ink(&inline);+    let b = ink(&via_form);+    assert!(!a.is_empty(), "inline fixture emitted no ink");+    assert_eq!(+        a, b,+        "Form XObject ink differs from the same content inline:\n  inline: {a:#?}\n  form:   {b:#?}"+    );+}
pdf/src/main/rust/src/docedit.rs
diff --git a/pdf/src/main/rust/src/docedit.rs b/pdf/src/main/rust/src/docedit.rsindex fb25a5159b..b781a5f470 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -316,6 +316,18 @@ pub(crate) fn extract_page(handle: i64, index: i32) -> Option<Vec<u8>> {     Some(buf) } +/// Stack for the page-interpretation worker (see [`render_page`]).+///+/// Smaller than `registry::OP

Diff truncated.