Skip to content

FT-070 memory: pages reference the assembled items instead of cloning them (-244 MiB at 2 MB) - #283

Closed
GoKubar wants to merge 8 commits into
mainfrom
agent/linux-primary/ft070-share-items
Closed

GoKubar wants to merge 8 commits into
mainfrom
agent/linux-primary/ft070-share-items

Conversation

@GoKubar

@GoKubar GoKubar commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

FT-070 follow-up 1 of the three #232 ranked. Pages stop cloning the assembled
items and reference them instead.

Based on #232's branch (41fee414) with current main merged in — #232 is
not on main yet, and neither is #206's harness, which #232's branch carries. The
merge is clean and brings the current vendor pin, so every number here is against
a control at that same base, not against the committed perf baseline (which
predates main and differs on 50/90 digests independently of any change).

What it does

A block's lines are assembled once, in line-local coordinates, and cached.
Placing a line then cloned every item into the page — baseline added to each y,
column offset to each x, the block's byte delta to each source range. Every
glyph, cluster, hit rect and source range existed twice: once in the assembled
block the cache owns, once in the page.

A page now stores what the clone was made from:

PageItem::Placed { block: Rc<LineItems>, line, index, dy, dx, delta }

48 bytes per slot against 200 for an inline Item plus the vectors it owned.
Page::items applies the same place_item/shift_x on read, so the bytes
every consumer gets are unchanged. Items a page builds for itself — images, the
\pagecolor rule — stay owned in a boxed Owned variant, which is what keeps
the enum at 48 bytes rather than 208.

The document default colour moves onto the page as a field. It used to be
written into every item after placement; it is uniform over the document, applies
only to a glyph run's or rule's paint, and only where that paint carries none, so
applying it on read is the same rule in one place instead of once per item.

The clone was not load-bearing for invalidation

That was the thing to establish before removing it, and it holds for four
separate reasons:

  • Nothing mutates an assembled block. RenderCache.assembled only inserts,
    reads (cloning the Rc) and clears the whole map. No Rc::get_mut, no
    make_mut, no interior mutability inside AssembledBlock or LineItems. A
    page referencing one cannot observe a change to it.
  • Invalidation is by key, not by ownership. A block whose content changed
    hashes to a different cache_key and gets a different AssembledBlock; the
    old entry stays correct for the display list still referencing it.
  • relocate_block rewrites a CachedBlock, never an AssembledBlock. A
    pure source relocation reaches the page through the placement's delta, which
    is why that field exists.
  • Nothing mutated a page's items either — every change to a page went through
    constructing a new one. That was true across the repo before the change, and
    the representation now enforces it.

Clearing the cache past MAX_BLOCKS no longer frees blocks a live display list
references. That is correct — the page needs them — and costs nothing, because
the page owned that data outright before.

Memory, measured

memprofile from #232, against a control at the same base:

case live before live after VmRSS before VmRSS after
synthetic-500kb, 385 pages 367.8 MiB 306.9 651.2 MiB 590.3
synthetic-2mb, 1507 pages 1458.4 MiB 1214.2 2569.5 MiB 2326.2

At 2 MB: −244.2 MiB live (−16.7%), −243.3 MiB resident (−9.5%). The walked
display-list-plus-cache total falls 963.5 → 711.7 MiB, all of it the removed
second copy. Allocator retention is unmoved (1111.2 → 1112.0 MiB), so this is
data that stopped existing, not data that moved into the arena.

Cluster (88 B), Item (200 B) and GlyphRun (184 B) are unchanged — this
removes a copy, not a field.

On the ~386 MiB this was ranked at. That estimate came from #232's table
taken before its own caret change, which then removed 101.6 MiB from the
display-list side of the same total. Measured after that change landed, the copy
left to remove is smaller, and 244 MiB is what it is actually worth. Worth
correcting in the ranking rather than leaving the larger number standing.

Gates

All against a control run at the same base, this machine (NixOS, loaded — memory
and digests are load-independent, so no timing claims here):

gate control this branch
perf-bench digests, 14 fixtures 106 106 identical, 0 differing
harness diagnostic notes — identical set, both runs
amsmath oracle 59/59 within 0.5 bp 59/59
HW1 / HW2 3 pages, 0 errors, 0 overfull 3 pages, 0 errors, 0 overfull
font diagnostics 0 0
render-pipeline suite 202 passed / 0 failed / 1 ignored 202 / 0 / 1
the ignored slow one: 30 edits of a 107-page document, byte-identical — passes

That last one is the direct test of this change: it drives the incremental cache
through 30 edits and asserts the output is byte-identical each time, which is
exactly the reuse-and-relocate path the sharing now goes through.

What this does not do

It does not move the 100 MB target. #232's arithmetic still holds — 100 MB over
1507 pages is ~68 KB/page, below one page of glyph data at any representation
that keeps per-glyph source ranges — and that needs a page window rather than the
whole document resident.

Follow-up 2 of the three (SourceRange.path → a document index, Cluster
88 → 64) is independent of this and lands separately. The third
(render-cache eviction) is untouched.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

claude and others added 8 commits September 13, 2026 16:10
There was no way to tell whether an engine change made the compiler faster.
The numbers that existed came from `examples/stages.rs` and `perf_bench.rs`:
macOS-only metadata, one sample per cell, no memory figure, no machine-readable
output, and no way to fail a build on a regression. This adds a harness whose
output can be argued with.

`crates/perf-bench` measures the product path -- the same
`protocol::handle_line` the `flashtex-render` worker serves -- over the ten
committed real-world fixtures and four generated documents (500 KB, 2 MB,
math-heavy, TikZ-heavy; generators committed, not blobs). Per case it reports
cold timings with a per-phase split, warm single-keystroke timings, PDF export,
peak and steady RSS, and an output digest. `--baseline ... --check` turns the
same run into a CI gate.

Three rules the harness enforces on itself, because breaking any of them
produces numbers that look fine and mean nothing:

* No measurement without fonts. Latin Modern and the pinned 12 pt TFM set must
  load and no render may substitute a face or a metric, or the case produces no
  timing at all -- a substituted metric is a different workload, not a slower
  one. The font set is built with `FontSet::with_dirs`, which probes nothing,
  so this box's TeX Live cannot supply the metrics by accident. The line is
  drawn at the configuration, not the document: a character with no glyph, or a
  class command the compiler does not model, is deterministic and identical
  every run, so the case is measured and the degradation is recorded next to
  the number.
* Cold means cold. Every repetition runs in a child process of its own, so the
  expander's thread-local cache, the font set's memoised faces and the
  allocator all start empty, and peak RSS belongs to one document.
* Medians, with the spread shown. Nothing comes from one sample; every metric
  carries n, p25/p75, p95 and MAD, and the table prints the run's own noise
  estimate per case.

The gate is built to survive a shared machine. A metric counts as regressed
only when it exceeds both the tolerance and that metric's own measured spread
in the baseline, and the comparison warns and stops enforcing timings when the
host, build profile, font configuration or peak load differ. Output identity
does not depend on the machine -- the fonts come from the repository -- so a
changed digest fails everywhere and unconditionally.

Baseline, at main 8465bbd on a Ryzen 7 7800X3D: cold HW1 meets its 10 ms
target; warm keystroke is 153x over budget at 500 KB and 132x at 2 MB, HW1 PDF
export is 5.6x over, and steady memory at 2 MB is 49x over. Full numbers,
method and three findings are in docs/evidence/perf-ft070-2026-09-13.

The clearest of those findings: typesetting a 2 MB document costs 42.7 s with
the document sources attached and 1.04 s without. Two per-formula code paths in
render-pipeline's typeset ask a question about the preamble and answer it by
searching the entire document, so a document that does not contain the searched
string pays a full scan per formula. That crate is another lane's, so this lane
has measured and reported it rather than touching it.

Gates unchanged (this adds a crate and edits no existing crate's source):
amsmath 59/59, HW1/HW2 3 pages with 0 errors and 0 overfull, render-pipeline
170 passed / 0 failed, compiler 395 passed / 0 failed, perf-bench 13 passed.

Implementation-Agent: Claude Opus 5 (FT-070 perf lane, linux-primary)
Commit-Executor: Claude Opus 5 (direct agent Git execution, per the AGENTS.md
  Cursor-limit fallback in force on this machine)
Co-authored-by: GoKubar <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
The memory work measures with this harness, so the lane branches from main
with the harness merged in rather than duplicating the crate.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…ilities fields)

`typeset::assemble` grew `page_color`/`default_color` and `v1::Capabilities`
grew `device_color`/`delta`/`v2_only` after the harness was written. Pass
`None`/`None` and spread the default so the measured path is still the one the
committed baselines were recorded against.

Reported on PR #206.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…lyph

`Cluster` carried a `Carets { first: Caret, last: Option<Caret> }` — 72 of
its 160 bytes — and a text run emits one cluster per glyph, so a 1507-page
document held 1.48 million caret pairs. They were never independent data:

  carets.first == Caret { text_byte: text_start_byte,
                          x:  hit_rect.x,
                          top: hit_rect.top,
                          height: hit_rect.height }

at all three construction sites (text runs, math, TikZ node text), and
`place_item`/`shift_x` moved the rect and both carets by the same offset,
so placement preserved it too. Audited over the twelve corpus cases —
1 991 552 clusters — the start caret was byte-identical to the derived one
in every single one, the end caret never sat on a cluster other than its
run's last, and its top/height always equalled that cluster's hit rect.

So `Cluster` keeps the rect and derives both carets, and the one thing that
is genuinely not derivable — the end caret's `x` (the TikZ path clamps the
hit rect's width to one tick but not the caret) and its text byte — moves to
the run as `GlyphRun::end_caret`, one per run instead of 40 bytes per glyph.
`Cluster`: 160 -> 88 bytes.

This also makes an invariant structural that `join_runs` used to maintain by
hand: it cleared the joined-over cluster's trailing caret so that only a
run's last cluster carried one. With the caret on the run there is nowhere
for a mid-run one to live.

Output is unchanged and that is the point of the change: both JSON emitters
and the delta digest now call `GlyphRun::carets_of`, which reconstructs the
same `Carets` value. `delta::changed_items` compares `end_caret` once per run
in place of `carets` per cluster — the same comparison, since the rest of the
caret is the cluster bytes and hit rect it already compares.

Measured on synthetic-2mb (1507 pages, 1.48M clusters), the perf harness
reports identical digests for all three scenarios (cold.reply
b0d5e89b71ab0200, warm.type-display-eq 4ec7e38a83002099,
warm.type-paragraph 484f07ea71d1b181) and steady RSS 5107 -> 4897 MiB.

FT-070. Reported on PR #206.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
FT-070's memory gap was a single number with no attribution. This adds the
instrument, so the breakdown is measured rather than argued about.

`render_pipeline::memsize` walks an already-built display list and render
cache and charges allocated bytes (capacity, not length — that is what the
allocator holds) to named lines, counting each shared `Rc` once so the two
totals can be added. It is read-only and touches no render path.

`memprofile <case>` renders a corpus case through the product path, runs the
warm keystrokes the harness runs, and reports VmRSS, live bytes from a
counting global allocator, and the walked breakdown, so the three gaps are
separated: live-minus-walked is what the walk cannot reach (font, expander
and compiler caches), RSS-minus-live is allocator retention, and a
`malloc_trim(0)` probe splits that last one into trimmable and fragmented.

It is a second binary because the counting allocator must not be linked into
the timing binary, and `main.rs` keeps its own module declarations: every
committed baseline was recorded by it exactly as it stands.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
Two tests constructed or read `Cluster.carets` directly. The JSON
round-trip test now sets the run's `end_caret` — which also makes it check
that both writers agree about *which* cluster shows the end caret, not just
about its value — and the joined-fragment test reads `GlyphRun::carets_of`,
so it still asserts the property it was written for: a caret never falls
outside its own cluster's byte range.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
…them

A block's lines are assembled once, in line-local coordinates, and cached.
Placing a line then *cloned* every item into the page with the baseline
added to each y, the column offset to each x and the block's byte delta to
each source range. So every glyph, cluster, hit rect and source range
existed twice: once in the assembled block the cache owns, once in the page.

A page now stores what the clone was made from instead of the clone:

    PageItem::Placed { block: Rc<LineItems>, line, index, dy, dx, delta }

48 bytes per slot, against 200 for an inline `Item` plus the vectors it
owned. `Page::items` applies the same `place_item`/`shift_x` on read, so
the bytes handed to every consumer are unchanged. Items a page builds for
itself -- images, the `\pagecolor` rule -- stay owned in a boxed `Owned`
variant, which is what keeps the enum at 48 bytes.

The document default colour moves onto the page as a field. It used to be
written into every item after placement; it is uniform over the document,
applies only to a glyph run's or rule's paint, and only when that paint
carries none, so applying it on read is the same rule at one place instead
of once per item.

The clone was not load-bearing for invalidation, which was the thing to
check before removing it:

* nothing mutates an assembled block. `RenderCache.assembled` only inserts,
  reads (cloning the `Rc`) and clears the whole map; there is no
  `Rc::get_mut`, no `make_mut` and no interior mutability inside
  `AssembledBlock` or `LineItems`. A page referencing one can never observe
  a change to it.
* invalidation is by key, not by ownership. A block whose content changed
  hashes to a different `cache_key` and gets a different `AssembledBlock`;
  the old entry stays correct for the display list that still references it.
* `relocate_block` rewrites source offsets in a `CachedBlock`, never in an
  `AssembledBlock`. A pure source relocation reaches the page through the
  placement's `delta`, which is why that field exists.
* nothing mutated a page's items either: every change to a page went
  through constructing a new one. Confirmed across the repo before the
  change, and now enforced by the representation.
* clearing the cache past `MAX_BLOCKS` no longer frees blocks a live
  display list still references. That is correct -- the page needs them --
  and costs nothing, because the page owned that data outright before.

Measured with `memprofile` (#232) against a control at this same base,
which is main + #232 with the current vendor pin:

    synthetic-500kb   live  367.8 ->  306.9 MiB   VmRSS  651.2 ->  590.3 MiB
    synthetic-2mb     live 1458.4 -> 1214.2 MiB   VmRSS 2569.5 -> 2326.2 MiB

At 2 MB that is -244.2 MiB live (-16.7%) and -243.3 MiB resident (-9.5%);
the walked display-list-plus-cache total falls 963.5 -> 711.7 MiB, the
whole of it the removed second copy. Allocator retention is unmoved
(1111.2 -> 1112.0 MiB), so this is data that stopped existing, not data
that moved into the arena.

`Cluster`, `Item` and `GlyphRun` are unchanged; this removes a copy, not a
field.

The ~386 MiB this was ranked at on #232 was estimated from the table taken
*before* #232's own caret change, which then removed 101.6 MiB of it from
the display-list side. Measured after that change landed, the copy left to
remove is smaller, and the numbers above are what it is worth.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
@GoKubar

GoKubar commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Backlog triage: the dependency this was waiting on has landed. #232 is now on main (2d1b517, "FT-070 memory: measure the breakdown, derive the per-glyph carets (Cluster 160 -> 88 B)"), and #206's harness with it (fe9bc43). This PR's own change is not on main — checked by content, not ancestry (main has no pub items: Rc<crate::display::LineItems> / pub block: std::rc::Rc<LineItems>) — so the work is still wanted.

Not closing: rebase onto current main and the numbers can be re-measured against the committed baseline instead of against a branch control. One caveat for whoever picks it up: the perf gate's output-identity check is a hard fail, so re-record crates/perf-bench/baselines/linux-x86_64-ryzen7-7800x3d.json on the reference host if the change moves any digest.

@GoKubar

GoKubar commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Closed under the old-engine freeze (DESIGN.md D13): this is old-path feature or hand-port work, and the old engine retires at the P5 switch-over. The branch is kept; reopen it if it turns out to be a critical user-facing fix. — kabir-claude (Commander), nightly review 2026-09-30

@GoKubar GoKubar closed this Sep 30, 2026
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.

2 participants