Skip to content

render-pipeline: layout cache keys tag each kind by its own discriminant (3 colliding tags, latent) - #182

Closed
GoKubar wants to merge 1 commit into
mainfrom
agent/linux-engine/layout-cache-discriminants
Closed

GoKubar wants to merge 1 commit into
mainfrom
agent/linux-engine/layout-cache-discriminants

Conversation

@GoKubar

@GoKubar GoKubar commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

The bug

incremental::hash_items and hash_math opened every item and every math nucleus with a hand-written number, and three pairs had drifted onto the same one. On origin/main @ 89e49fed:

file:line variant tag collides with
crates/render-pipeline/src/incremental.rs:249 Item::Logo 9 Item::Table at :268
crates/render-pipeline/src/incremental.rs:256 Item::Rule 10 Item::Footnote at :272
crates/render-pipeline/src/incremental.rs:296 Nucleus::Rule 15 Nucleus::SubArray at :401

The third one was not in the report — the audit turned it up. It is live under the default amsmath-inline feature.

The numbering scheme was: one u8 literal per match arm, 0..=11 for Item (hand-assigned, Table and Footnote appended last and reusing 9/10), 0..=16 for Nucleus (with Rule sitting on 15 out of order and SubArray later taking 15 again). Nothing in the stream was length-prefixed, so the tag was the only thing separating one kind from another.

Reachability: latent, not reachable from any document — measured, not argued

The collision itself is real. Measured constructively: on the parent commit a one-item Rule list and a Footnote list padded with 106 segment-less Words absorb exactly the same bytes and both hash to 0xcf4bedf5dbfa4a3b. That pair is now a test (a_rule_list_and_a_footnote_list_no_longer_share_a_key), and it fails on the parent commit:

thread 'a_rule_list_and_a_footnote_list_no_longer_share_a_key' panicked:
assertion `left != right` failed: collision again at 106 padding words
  left: 14937294229317765691
 right: 14937294229317765691

But those values are synthetic. To decide reachability I instrumented hash_items/hash_math with an env-gated counter and drove the real cached pipeline (render_cached with a live RenderCache) over documents holding each construct at top level and inside \intertext, plus the crate's own suite. Results:

  • Item::Table reached hash_items 0 times. block_origin (incremental.rs:180) returns None for any list holding a table, so key_for never produces a key for such a block. Tag 9 is dead on the cache path.
  • Item::Footnote reached hash_items 0 times. key_for (typeset.rs:4843) bails out when any item is a footnote. Tag 10 is dead on the cache path. (hash_items recurses into a footnote's own text, but only under a top-level footnote, which is already excluded.)
  • Nucleus::Rule and Nucleus::SubArray both reach live cache keys — 4 times each in the probe. Nothing excludes them, so tag 15 was the closest to reachable of the three. A collision is still impossible byte-wise: after the shared tag, Nucleus::Rule writes TextRule.raise.negative, a bool (0x00/0x01), while Nucleus::SubArray writes align as u32, whose low byte is 0x63 — the compiler's only construction site (vendor/compiler/src/math.rs:901) hardcodes align: 'c', and MathAtom::class_override is pub(crate) so no math list reaching hash_math can be built outside the compiler crate. The streams diverge at the first payload byte, always.

So: no wrong-content cache hit is reachable on main. What was reachable was the scheme — nothing stopped the next Item or Nucleus variant from landing on a tag whose partner is not excluded.

The fix

The tag is now std::mem::discriminant of the value (incremental::tag / the public kind_tag). Distinct variants have distinct discriminants by construction, so:

  • adding a variant gets it a fresh tag with no edit anywhere, and
  • no hand-written number exists to be reused.

The item and inline sequences are length-prefixed as well (items.len(), w.segments.len(), inlines.len()), so the stream is self-delimiting and the constructed 107-item collision above is gone too, not just the tag overlap.

Keys are per-process, in-memory HashMap keys (RenderCache); nothing persists them, so a discriminant-derived tag is safe here.

Audit of the same pattern elsewhere in the crate

  • adapter::items_cached (adapter.rs:3596+), the key for the adapted-items cache: same hand-numbered style, tags 0..=14. No collision — all fifteen are distinct. Converted to the same scheme anyway so the class of bug cannot come back there.
  • adapter.rs:4335 fn shape maps items to letters, but it is a test helper with a _ => '?' catch-all, not a cache key. Left alone.
  • incremental::style_fingerprint hashes format!("{style:?}") — a Debug string, self-delimiting, no per-kind tags.
  • The Option markers (0/1) inside hash_math for superscript/subscript and Stacked's over/under are two-valued and distinct; left as they are.

Tests added — crates/render-pipeline/tests/layout_cache_keys.rs

  • no_two_item_kinds_share_a_tag — one sample of every one of the 14 Item variants, asserts all tags distinct, and asserts the sample count so a new variant is noticed. This is the "fails if two variants ever map to the same value" test; it checks the tag, because checking whole keys would not have caught the original bug (the colliding variants' payloads differ in length).
  • no_two_math_nucleus_kinds_share_a_tag — the same for 14 nuclei, sampled by parsing real TeX (math atoms cannot be constructed outside the compiler crate).
  • a_rule_list_and_a_footnote_list_no_longer_share_a_key — the measured reproduction above; fails on the parent commit.
  • a_block_holding_a_table_is_never_keyed — pins the block_origin guard that made tag 9 unreachable, so a later change that starts caching table blocks has to face this test.
  • a_math_rule_and_a_substack_do_not_share_a_key — the pair that does reach live keys.

Gates

NixOS, TeX Live 2025, bundled symlink-free apps/mac/Fonts tree (FLASHTEX_TFM_DIRS = lm + jknappen/ec + amsfonts/symbols). MacTeX is oracle-only; no committed expected data was regenerated.

gate main this branch
cargo test render-pipeline, no FLASHTEX_* exports 170 passed, 0 failed 175 passed, 0 failed (+5 new)
cargo test under CI's font triple 153 passed, 17 failed 158 passed, 17 failed — byte-identical failure set (pre-existing without-NewCM controls)
incremental byte-identical, 27 pages x 200 edits (fonts on) pass, hits 111325 / misses 597, 116.7s pass, hits 111325 / misses 597, 116.3s
incremental byte-identical, 107 pages x 30 edits (--ignored) — pass, hits 65711 / misses 1479
amsmath corpus 59/59 59/59 within 0.5 bp
HW1 / HW2 v2 display list md5 eaa6f588… / 86c7d740… byte-identical, 0 overfull, 0 errors
real-world corpus (--no-oracle --no-pixels, 10 fixtures) report.json identical except the render binary's own sha256

Font-diagnostic guard: the HW harness fails on any diagnostic matching metrics_unavailable / font_missing / fallback — none appeared, and the only amsmath-corpus diagnostic is the pre-existing \pagestyle is not supported in the document preamble compiler warning. The 59/59 within 0.5 bp against pdflatex-generated oracle geometry is itself proof the bundled TFM tree resolved: an OpenType-advance fallback would blow that tolerance everywhere.

Cache hit/miss counts and wall time are unchanged, so the 8-byte tag and the length prefixes cost nothing measurable.

No changes under crates/render-pipeline/vendor/*.


Fixes the colliding-layout-cache-keys item from integration review (#2).

🤖 Generated with Claude Code

https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

`incremental::hash_items` and `hash_math` opened every item and every math
nucleus with a hand-written number, and three pairs had drifted onto the
same one:

  incremental.rs:249 Item::Logo     => 9   vs :268 Item::Table    => 9
  incremental.rs:256 Item::Rule     => 10  vs :272 Item::Footnote => 10
  incremental.rs:296 Nucleus::Rule  => 15  vs :401 Nucleus::SubArray => 15
                                            (default feature amsmath-inline)

Sharing an opening tag is what lets two different item lists absorb the same
bytes, because nothing in the stream was length-prefixed. Measured, not
argued: on the parent commit a one-item `Rule` list and a `Footnote` list
padded with 106 segment-less `Word`s both hash to 0xcf4bedf5dbfa4a3b.

The collision is latent, not reachable from any document. Measured with
temporary instrumentation in `hash_items`/`hash_math` over documents holding
each construct at top level and inside `\intertext`, and over the crate's
test suite:

  - `Item::Table` reached `hash_items` 0 times: `block_origin`
    (incremental.rs:180) returns `None` for any list holding one, so a table
    block never gets a key.
  - `Item::Footnote` reached `hash_items` 0 times: `key_for`
    (typeset.rs:4843) bails out when any item is a footnote.
  - `Nucleus::Rule` and `Nucleus::SubArray` both do reach live keys (4 times
    each), so tag 15 was the closest to reachable -- but a collision is
    impossible byte-wise: after the shared tag, `Rule` writes
    `TextRule.raise.negative` (a bool, 0x00/0x01) and `SubArray` writes
    `align as u32` whose low byte is 0x63, the compiler's only construction
    site (vendor/compiler math.rs:901) hardcoding `align: 'c'`. Math atoms
    cannot be built outside the compiler crate (`MathAtom::class_override`
    is `pub(crate)`), so no other `align` can occur.

The tag is now `std::mem::discriminant` of the value. Distinct variants have
distinct discriminants by construction, so a variant added later gets its own
tag with no edit and cannot silently reuse another's. The item and inline
sequences are length-prefixed as well, so the stream is self-delimiting and
the constructed collision above is gone too.

The same hand-numbered style in `adapter::items_cached` (the adapted-items
cache, tags 0-14) had no collision; converted to the same scheme so the class
of bug cannot come back there either.

Gates (NixOS, TeX Live 2025, bundled symlink-free apps/mac/Fonts tree; the
oracle is read-only, no committed expected data regenerated):

  - cargo test -p render-pipeline, no FLASHTEX_* exports: 170 -> 175 passed,
    0 failed (the 5 new tests). Under CI's font triple both main and this
    branch show the same 17 pre-existing failures.
  - incremental byte-identical gate with the bundled fonts: 27 pages x 200
    edits pass, cache hits 111325 / misses 597 -- identical to main, 116.3s
    vs 116.7s. The ignored 107-page x 30-edit gate passes too (65711/1479).
  - amsmath corpus 59/59 within 0.5 bp; the only diagnostics are the
    pre-existing `\pagestyle` compiler warning, none about fonts or metrics.
  - HW1/HW2 v2 display lists byte-identical to main (md5
    eaa6f588... / 86c7d740...), 0 overfull, 0 errors, no font diagnostic.
  - real-world corpus: report.json identical to main's except the render
    binary's own sha256.

Implementation-Agent: claude-opus-5 engine engineer (linux-primary worktree
  agent-af8b865ba048b0254)
Commit-Executor: claude-opus-5 engine engineer (direct Git, Cursor-limit
  fallback per AGENTS.md)
Co-authored-by: GoKubar <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
GoKubar added a commit that referenced this pull request Sep 13, 2026
16 conflicts (adapter.rs 10, typeset.rs 5, incremental.rs 1). All but one were
misalignments: git shared common tails between this branch's additions and
#156's, so each side ended mid-construct and a plain "keep both" would not
compile. Rebuilt as complete separate pieces, as the merge log records for
#154 and #170.

- `Item` / `BoxRec` / `AItem` / `Paragraph`: both sides add variants and
  fields (#156's Glue, Rigid, Penalty, EmptyBox, Qed, Rules, LocalRule,
  `theorem_head`). Kept from both, with the enclosing enum, struct and match
  arms closed explicitly where git had shared a brace.

- **Incremental cache tags renumbered.** #156 numbered its five new
  `hash_items` arms 10-14, which this branch already uses for
  Footnote/TextBox/SetLength/LengthGlue/HSs. These tags key the incremental
  layout cache, so a collision serves one item's cached layout for another --
  the same hazard #170 hit, fixed the same way. #156's are now 19-23, the
  first free run. The two pre-existing collisions (Logo/Table at 9,
  Footnote/Rule at 10) are left for #182, which replaces the hand-numbering
  with `mem::discriminant`.

- `\qedhere` in a display: #156's block computes e/q before the display is
  placed, so it goes ahead of #157's fleqn/§1201 squeeze rather than the
  plain §1199 centring #156 carried with it. The symbol is built into a
  `NumberBox` (this branch's representation, which is where display_block
  reads the height and depth from) instead of #156's bare `(run, rec)` pair.

- `\addvspace`: kept main's `\@xaddvskip` rule (a negative amount after a
  non-negative `\lastskip` is added to it) together with #156's flex, so the
  surviving skip keeps its own stretch and shrink.

- `gap_has_list_end` came back. The origin/main merge had dropped it as
  having no caller; #156's theorem-skip code needs it. It is now written in
  terms of `LIST_ENVS` so it cannot drift from the other list predicates.

The one real disagreement, found by measurement, not by reading

#156 guards display continuation with `*prev_style == ParaStyle::Plain &&
prev_list.is_none()`. Merged as written, display-placement fell from 33/36 to
31/36: every new failure was a display inside a list or a quote, shifted 12
to 20 pt vertically (`20-enumerate-nested-display`, `29-quote-display`, and
`19-itemize-display` got worse).

Those two conjuncts are #156's older, coarser form of two conditions this
branch already states more precisely two lines above -- `same_list` (which
compares level and margins, not merely "no list") and `styled.unwrap_or_
default() == *prev_style`. Keeping them disabled display continuation inside
every list. Only `&& !theorem_head`, the genuinely new theorem condition, is
kept; display-placement is back to 33/36.

Gates (NixOS PC, TeX Live 2025, bundled tree plus nix-store `ec`; no
committed oracle data regenerated; zero font diagnostics on every run):

- amsmath 59/59, tabular 59/59, display-placement 33/36 -- all unchanged.
- theorem_oracle passes (#156's own corpus, MacTeX references).
- real-world 10/10 recovered, every page count still equal to its committed
  reference. lecture-notes drops from 7 diagnostics to 6: a theorem construct
  that was recovered is now supported.
- `cargo test --release` in render-pipeline: the same 11 known failures as
  before this merge, no more. Eight of them also fail on unmerged
  origin/main on this machine (the four NewCM controls, metrics_provenance,
  font_families_oracle, footnotes_oracle, page_frame); the other three
  (float_bodies, headings, list) have no baseline on a non-MacTeX host.

Implementation-Agent: Claude Opus 5 (subagent kabir-claude integration, nixos-pc-kabir)
Commit-Executor: Claude Code direct Git
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
GoKubar added a commit that referenced this pull request Sep 15, 2026
…ant (#639)

`incremental::hash_items` and `hash_math` opened every item and math
nucleus with a hand-written u8 tag, and four pairs had drifted onto the
same number on main:

  Item::Logo     9   Item::Table     9
  Item::Rule     10  Item::Footnote  10
  Item::Kern     11  Item::ColorBox  11   (new since the original report)
  Nucleus::Rule  15  Nucleus::SubArray 15 (default amsmath-inline)

Nothing in the stream was length-prefixed, so the tag was the only thing
separating one kind from another. Measured constructively on main
@ 386850d: a one-item Rule list and a Footnote list padded with 115
segment-less Words absorb exactly the same bytes and both hash to
0x6c59b42dfda78afd - two different item lists, one cache key. The
Kern/ColorBox pair appearing after the original three-pair report is the
scheme failing exactly as predicted: a new variant landed on an old tag.

The tag is now std::mem::discriminant of the value (incremental::tag /
pub kind_tag): distinct variants get distinct tags by construction, and
a variant added later needs no edit anywhere. The item and inline
sequences are length-prefixed as well (items.len(), w.segments.len(),
inlines.len()), so the stream is self-delimiting and the padded
construction above is impossible, not just the tag overlap. Keys are
per-process HashMap keys (RenderCache); nothing persists them.

adapter::items_cached (the adapted-items cache, tags 0..=19, no
collision yet) is converted to the same scheme so the class of bug
cannot come back there.

Tests (tests/layout_cache_keys.rs): no_two_item_kinds_share_a_tag and
no_two_math_nucleus_kinds_share_a_tag fail if two variants ever share a
tag; a_rule_list_and_a_footnote_list_no_longer_share_a_key is the
measured reproduction (fails on main at pad 115);
a_block_holding_a_table_is_never_keyed pins why tag 9 was unreachable;
a_math_rule_and_a_substack_do_not_share_a_key covers the pair that does
reach live keys.

What was run (FLASHTEX_FONT_DIRS=apps/mac/Fonts, TFMs lm+ec+amsfonts):
cargo test --release --no-run: clean (all render-pipeline test targets)
cargo test --release --test layout_cache_keys: 6 passed, 0 failed
cargo test --release --test cache_counters --test incremental:
  2 passed (incl. incremental_output_is_byte_identical_over_200_edits
  _of_a_27_page_document), 1 ignored, 0 failed
collision probe on unmodified main: FAILED as expected
  (COLLISION at 115 padding words: both hash 0x6c59b42dfda78afd)

Salvaged from PR #182 (agent/linux-engine/layout-cache-discriminants),
rebuilt against current main.

Implementation-Agent: fable-salvage
Commit-Executor: fable-salvage (direct; Cursor usage limit)
@GoKubar

GoKubar commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Closing: this fix landed on main as PR #639 (commit 6bba7ac, "render-pipeline: layout cache keys tag each kind by its own discriminant"), the salvage/re-land of this draft. The discriminant-tagged cache keys this branch introduced are on main.

@GoKubar GoKubar closed this Sep 15, 2026
@GoKubar
GoKubar deleted the agent/linux-engine/layout-cache-discriminants branch September 16, 2026 04:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant