Repository navigation
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
Closed
render-pipeline: layout cache keys tag each kind by its own discriminant (3 colliding tags, latent)#182GoKubar wants to merge 1 commit into
GoKubar wants to merge 1 commit into
Conversation
`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
This was referenced Sep 15, 2026
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)
Contributor
Author
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The bug
incremental::hash_itemsandhash_mathopened every item and every math nucleus with a hand-written number, and three pairs had drifted onto the same one. Onorigin/main@89e49fed:crates/render-pipeline/src/incremental.rs:249Item::LogoItem::Tableat:268crates/render-pipeline/src/incremental.rs:256Item::RuleItem::Footnoteat:272crates/render-pipeline/src/incremental.rs:296Nucleus::RuleNucleus::SubArrayat:401The third one was not in the report — the audit turned it up. It is live under the default
amsmath-inlinefeature.The numbering scheme was: one
u8literal per match arm,0..=11forItem(hand-assigned,TableandFootnoteappended last and reusing 9/10),0..=16forNucleus(withRulesitting on 15 out of order andSubArraylater 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
Rulelist and aFootnotelist padded with 106 segment-lessWords absorb exactly the same bytes and both hash to0xcf4bedf5dbfa4a3b. 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:But those values are synthetic. To decide reachability I instrumented
hash_items/hash_mathwith an env-gated counter and drove the real cached pipeline (render_cachedwith a liveRenderCache) over documents holding each construct at top level and inside\intertext, plus the crate's own suite. Results:Item::Tablereachedhash_items0 times.block_origin(incremental.rs:180) returnsNonefor any list holding a table, sokey_fornever produces a key for such a block. Tag 9 is dead on the cache path.Item::Footnotereachedhash_items0 times.key_for(typeset.rs:4843) bails out when any item is a footnote. Tag 10 is dead on the cache path. (hash_itemsrecurses into a footnote's own text, but only under a top-level footnote, which is already excluded.)Nucleus::RuleandNucleus::SubArrayboth 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::RulewritesTextRule.raise.negative, abool(0x00/0x01), whileNucleus::SubArraywritesalign as u32, whose low byte is0x63— the compiler's only construction site (vendor/compiler/src/math.rs:901) hardcodesalign: 'c', andMathAtom::class_overrideispub(crate)so no math list reachinghash_mathcan 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 nextItemorNucleusvariant from landing on a tag whose partner is not excluded.The fix
The tag is now
std::mem::discriminantof the value (incremental::tag/ the publickind_tag). Distinct variants have distinct discriminants by construction, so: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
HashMapkeys (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, tags0..=14. No collision — all fifteen are distinct. Converted to the same scheme anyway so the class of bug cannot come back there.adapter.rs:4335fn shapemaps items to letters, but it is a test helper with a_ => '?'catch-all, not a cache key. Left alone.incremental::style_fingerprinthashesformat!("{style:?}")— a Debug string, self-delimiting, no per-kind tags.Optionmarkers (0/1) insidehash_mathfor superscript/subscript andStacked's over/under are two-valued and distinct; left as they are.Tests added —
crates/render-pipeline/tests/layout_cache_keys.rsno_two_item_kinds_share_a_tag— one sample of every one of the 14Itemvariants, 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 theblock_originguard 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/Fontstree (FLASHTEX_TFM_DIRS= lm + jknappen/ec + amsfonts/symbols). MacTeX is oracle-only; no committed expected data was regenerated.cargo testrender-pipeline, noFLASHTEX_*exportscargo testunder CI's font triple--ignored)eaa6f588…/86c7d740…--no-oracle --no-pixels, 10 fixtures)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 preamblecompiler 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