Skip to content

FT-070: profile the warm keystroke, and stop copying a restored block's item list - #273

Closed
GoKubar wants to merge 4 commits into
mainfrom
agent/kabir-claude/ft-070-warm-latency
Closed

GoKubar wants to merge 4 commits into
mainfrom
agent/kabir-claude/ft-070-warm-latency

Conversation

@GoKubar

@GoKubar GoKubar commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

FT-070 lane. Profile first, then one change. The headline is honest: this
does not move the warm keystroke. It removes a real copy, it cuts peak
memory by 7.3%, and it leaves output byte-identical — and the profile it
produced says where the remaining 96% actually is.

The warm keystroke at 500 KB, measured

crates/perf-bench with a new --warm-profile split (branch
agent/kabir-claude/ft-070-perf-bench-fixes, offered on #206), v2
capabilities, medians over 12 steps, host load ~1:

phase ms %
handle_line total (authoritative) 271 100%
render_cached 261 96%
├ parse_project (lex+expand+parse) 28 10%
├ adapt_cached 65 24%
├ build_with_floats 80 29%
└ assemble (display list v2) 87 32%
reply build + serialise 9 3%

Two findings worth more than the patch:

1. The reply is not the bottleneck, and at 500 KB there is no reply. The
display list is 164 MB against a 16 MiB line limit, so handle_line declines
it without serialising it, then the compile_result is itself over the limit
and the request ends status: failed — "compile_result would be 20339909 bytes for 385 pages, over the 16777216-byte reply limit". The FT-070 warm
number at 500 KB is currently timing the engine building a reply the protocol
then refuses to send. An earlier version of my split always serialised and
reported a 167 ms write_json_wire as 57% of a keystroke that never calls it;
that phantom is why the split now bills only what handle_line actually runs.
display-list-v2-delta does not help here — try_delta still needs the full
DisplayList from render_cached first, so it shrinks the wire, not the 271 ms.

2. With a 91% cache hit rate, the work is copying, not layout. Per
keystroke, 9,690 cached blocks are restored and 7,764 miss:

per keystroke clone free
block 21 ms 17 ms
recs 14 ms 20 ms
maths 3 ms 2 ms
relocate (the +delta itself) 1.1 ms —

The transformation costs 1.1 ms. Copying costs 38 ms and freeing 39 ms — 28%
of the keystroke is memcpy and free of data that is already in the cache.

What this PR changes

About 11 ms of the block clone is BuiltBlock::items, the horizontal list the
lines index into — and nothing reads an item back once the block is built.
assemble_block asks each index only whether it is an Item::Box;
floatpage::block_source uses only items.len(). Every source offset that
reaches the display list comes from the line runs and from recs. So the list
is now an Rc shared with the cache entry, and relocate_block no longer
walks it. The invariant is stated at both sites and is what the digest gates
below check.

Results — interleaved A/B, same two binaries alternating

metric main this PR delta consistency
warm keystroke, 500 KB 278–280 ms 279–281 ms +0.2% … +0.5% flat, 4 scenarios
peak RSS 1484 MB 1375 MB −7.3% 7/7 rounds (−7.1…−7.6%)
steady RSS 1343 MB 1228 MB −5.2% … −8.5% 7/7 rounds
cold assemble phase 125 ms 114 ms −9.0% 3/3 rounds

Warm latency is unchanged: the copy removed is ~4% of a keystroke and the other
96% is the same shape of work. Four further rounds taken at host load 8–21 swung
individual timings by +54%/−56% and are not evidence either way; only the
load ~1 rounds are quoted for timing. Memory held at −7.3% in every round at
every load, which is why it is quoted at all.

Gates

Every run used the pinned Latin Modern set and asserts zero font
diagnostics
— a substituted-metrics run is a different workload, so no number
here comes from one.

On this branch's merge base (current main, 0d93456b):

  • Output identical: 91 per-fixture digests over 13 cases — the 10
    real-world fixtures plus math-heavy, tikz-heavy, synthetic-500kb —
    identical, 0 different, identical page counts. synthetic-2mb was dropped
    from this pass only: at 1507 pages on a box at load 30+ it would not finish,
    and it is a generated scale case, not a real-world fixture.
  • HW1 / HW2: 3 pages, 0 errors, 0 overfull, 0 font diagnostics; v2 digests
    61d7804aec6df54c / 362bd5618d12b2e6, byte-identical to the baseline
    worker built from origin/main at the same commit.
  • amsmath oracle: 59/59 within 0.5 bp.
  • cargo test --release in crates/render-pipeline: green, empty failing
    set (so not worse than any control).

On the branch's original base (62200c0e), before main moved under it, the
same comparison ran over the full corpus: 106 digests, 0 different, across all
14 cases including synthetic-2mb
, with amsmath 59/59, HW1/HW2 matching, and
a green suite. The A/B timing and memory numbers above were taken on that base.

The next bottleneck

Not this. The profile says the remaining 96% is adapt (24%), typeset (29%)
and assemble (32%), and inside those the dominant cost is still the
clone-all/free-all of cached records — recs alone is 34 ms of clone+free.

I tried the obvious fix first and it failed: sharing BoxRec::Text's text
and glyphs behind Rc made the keystroke 11% slower (6/6 matched rounds),
because refcounting ~78,000 records scattered across a 1.4 GB working set costs
more in cache traffic than the memcpy it saves. Reverted, not shipped. The
lesson is granularity: this PR's Rc is per block (9,690 bumps), which is
why it does not regress.

The real fix is structural and bigger than one lane: the benchmark's edits all
land near the document start, so every downstream block shifts and every cached
record must be materialised with new absolute offsets. Stopping that means
carrying a per-block source delta and applying it at read time — which
AssembledBlock/place_item already do for display items, but typeset does
not for recs. Doing it needs a two-level rec index so a restored block's
records are referenced rather than copied. I'd recommend that be scoped
deliberately rather than bolted onto this PR.

Separately: the 16 MiB reply limit means a 500 KB document cannot be previewed
at all today. That looks like a higher-priority product bug than the 271 ms.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

GoKubar and others added 2 commits September 13, 2026 21:04
…g and re-offsetting it

Profiling one warm keystroke on the 500 KB fixture (`perf-bench`, v2
capabilities, medians over 12 steps, host load ~1) puts essentially all of it
inside `render_cached` -- the reply serialisation is not the cost, because at
385 pages the display list is over the 16 MiB line limit and is declined
without ever being serialised:

    handle_line total            271 ms   100%
      render_cached              261 ms    96%
        parse_project             28 ms    10%
        adapt_cached              65 ms    24%
        build_with_floats         80 ms    29%
        assemble                  87 ms    32%
      reply build + serialise      9 ms     3%

Inside that, with a 91% block-cache hit rate (9,690 hits, 7,764 misses per
keystroke), the dominant work is not layout at all -- it is copying cached
blocks back out of the cache and freeing them again:

    per keystroke   clone   free
      block          21 ms  17 ms
      recs           14 ms  20 ms
      maths           3 ms   2 ms
      relocate        1 ms      -

The relocation itself -- the integer `+delta` that moves a restored block's
source offsets -- costs 1.1 ms. The copying costs 38 ms and the freeing 39 ms.

About 11 ms of the block clone is `BuiltBlock::items`, the horizontal list the
block's lines index into, and nothing ever reads an item back once the block is
built. `assemble_block` asks each index only whether it is an `Item::Box`, so it
can pair boxes with the line's runs; `floatpage::block_source` uses only
`items.len()` as an index range and then reads `recs`. Every source offset that
reaches the display list comes from the line runs and from `recs`. So the list
is now an `Rc` that a restored block shares with its cache entry, and
`relocate_block` no longer walks it: a refcount bump replaces a deep copy of
every glyph run in the document, on the clone and again on the free.

Measured, interleaved A/B (the same two binaries alternating, so host load
drifts across both arms), 500 KB, four warm scenarios:

* peak RSS 1484 MB -> 1375 MB, **-7.3%**, in 7 of 7 matched rounds
  (-7.1/-7.3/-7.3/-7.3/-7.4/-7.4/-7.6%); steady RSS -5.2% to -8.5%.
* cold `assemble` phase -9.0% (-8.7/-9.0/-9.1% at load ~1).
* **warm keystroke: unchanged** -- +0.2% to +0.5% across four scenarios at
  load ~1, which is inside this machine's noise. The copy this removes is
  real, but it is ~4% of a keystroke and the remaining 96% is the same shape
  of work. Four further rounds taken at load 8-21 moved individual timings by
  +54%/-56% and say nothing either way; they are not evidence.

Output is unchanged, which is the hard gate: 106 per-fixture digests over the
ten real-world fixtures and four generated documents are identical before and
after, with identical page counts; HW1 and HW2 are 3 pages with 0 errors, 0
overfull and 0 font diagnostics, and their display-list digests match the
baseline worker byte for byte; the FT-061 amsmath oracle is 59/59 within
0.5 bp; `cargo test --release` in `crates/render-pipeline` is green with no
failures. Every measurement ran with the pinned Latin Modern set and asserts
zero font diagnostics, so no number here comes from substituted metrics.

The invariant this rests on -- that a restored block's item sources are never
read -- is stated at both `BuiltBlock::items` and the place in
`relocate_block` that no longer walks them, and it is what the digest gates
above check.

Implementation-Agent: engine-engineer (Claude Opus 5), FT-070 lane
Commit-Executor: engine-engineer (direct git; Cursor not used for this commit)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu
@GoKubar

GoKubar commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Base note for whoever integrates: every gate above was run with this branch's merge base pinned at 0d93456b. main has since advanced to 5e6c65be (44 commits, including two further vendor/ re-pins), and it is moving faster than a full corpus pass takes on this box, so I stopped chasing it rather than quote gates against a base that would be stale again by the time they finished. The change is orthogonal to those re-pins — it touches BuiltBlock::items sharing only — but the digest gate should be re-run at merge time against whatever main is then, which is the thing that would actually catch an interaction.

Also worth flagging for triage independently of this PR: at 385 pages the display list is 164 MB against the 16 MiB line limit, so a 500 KB document currently compiles to status: failed rather than a preview. That is a product bug sitting underneath the FT-070 500 KB target, and it is almost certainly worth more than the 271 ms this lane was chasing.

@GoKubar
GoKubar marked this pull request as ready for review September 15, 2026 15:37
GoKubar added a commit that referenced this pull request Sep 15, 2026
… has no reply (#294)

* perf-bench: FT-070 benchmark harness, committed baseline and a >5% gate

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

* perf-bench: build against current main (assemble colour params, Capabilities 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

* display list: derive the cluster carets instead of storing them per glyph

`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

* perf-bench: a memory profile that says where the resident bytes went

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

* tests: build the cluster carets through the derived accessor

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

* display list: materialise a bounded window of pages, not the whole document

FT-070's structural half. #232 established that 100 MB over 1507 pages is
~68 KB a page -- less than one page of glyph data at any representation that
keeps per-glyph carets and source ranges -- so the target cannot be reached by
representation and the document has to stop being resident.

`protocol/proposals/display-list-v2-window.md` is the proposal; this is its
producer-side prototype. The wire capability is specified and NOT negotiated:
`v1.rs` does not accept the name, no consumer sends it, and an unwindowed
render -- every render on every route today -- is byte-for-byte unchanged.

Where the window belongs. `-only` and `-delta` are serialisation levers: they
choose what of an already-built `DisplayList` reaches the consumer, so a
`-window` built at that boundary would cut wire bytes and leave resident memory
exactly where it is. The window therefore takes effect at `typeset::assemble`,
the first point where per-page glyph data exists, and is declared at the
protocol boundary because whether a reply covers the whole document is a
contract fact, not something a consumer should infer.

Layout still runs over the whole document -- page breaking, `\pageref`, floats
and contents lists are global and a window over them would change output. Only
assembly is windowed.

The completeness hazard, and what it forced. The font closure and the
`math_resource_profile` / `math_glyph_unmapped` diagnostics are derived during
assembly over every block, so a window that assembled only its own blocks would
emit a quietly smaller closure and fewer diagnostics. `assemble_windowed`
therefore still visits every block in the same order and harvests before it
drops: what the window changes is retention, not the traversal. An assembled
block reaching no resident page is dropped and never cached.

`Page.items: Vec<Item>` becomes `Page.content: PageContent` (`Resident(..)` or
`Elided`). Deliberately a breaking change rather than a `resident: bool` beside
a retained `items`: the failure mode being designed against is a consumer that
reads `items` without checking, and there is now no silent path. `pdf::write_pdf`
refuses a windowed list, `v1::fallback` skips an elided page, and `delta` takes
no snapshot from one and emits no delta against one (a window and a delta are
mutually exclusive in r1, since the delta's `list_digest` binds a digest for
every page).

On the wire an elided page carries its frame, `"resident": false` and no
`items` key at all -- absent, not `[]`, so a consumer that ignored the flag
fails to decode rather than painting a blank page. A resident page gains no
marker, which is what keeps every existing digest identical.

`tests/page_window.rs` is the acceptance gate, and it is equality rather than a
digest: over every window position of a 20-page document, each resident page
must serialise byte-identically to that page in the unwindowed render, and the
documents, fonts, diagnostics and required features must match the complete
compile's. A digest would only prove a consumer rebuilt what it was sent; the
risk here is a producer sending a correct-looking smaller closure.

Measured with `memprofile --window 1:16` against an unwindowed control on the
same code path (`--render-only`), 2 MB / 1507 pages: live 1440.7 -> 920.0 MiB,
VmRSS 2912.3 -> 2035.8, display list 247.5 -> 2.5. 500 KB / 385 pages: live
363.2 -> 238.1, VmRSS 748.8 -> 541.9. The display list stops scaling with the
document, which is the property this is for. What remains is
`RenderCache.blocks`, whole-document by design because it is what makes
re-materialising a page cheap -- and 2036 MiB is still 20x the 100 MB target.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* display list: scope the assembled cache to the window, so a scroll stays bounded

Without this the window is only a first-render win. `RenderCache.assembled` is
append-only -- its sole bound is "clear everything at 50 000 entries" -- so a
viewer scrolling a long document accumulates the glyph-level assembly of every
page it has passed, and the resident set climbs back to the whole document
while the window keeps claiming to be 16 pages.

A windowed render now ends by retaining exactly the blocks its resident pages
used. `blocks` and `adapted` are deliberately untouched: they are the
whole-document layout records that make re-materialising a page cheap, and they
are the cache lines the measurements show remaining (160.2 MiB of
`BuiltBlock.items` and 73.1 MiB of `ClusterRec` at 2 MB). Bounding those is
#232's follow-up 3, not this.

An unwindowed render never calls `retain_assembled`, and now also treats every
block as wanted whether or not a page placed it -- so a complete compile's cache
behaviour is byte-for-byte and entry-for-entry what it was before the window
existed, rather than merely equivalent in output.

Also: `flashtex-cli`'s `has_content` reads through `Page::items()`, and the
proposal now states per section what r1 implements against what it specifies.
The gap worth naming is §5.5: the page recipe is NOT retained across requests,
so r1 re-runs layout for every window. Serving a scroll without re-layout is
the point of retaining it and is r2; the memory this change measures does not
depend on it, which is why it is separated rather than bundled in unmeasured.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* display list: size the page window by the reply limit, not by a memory budget

The window lane was written against FT-070's 100 MB target. PR #273 measured
something more urgent with the same cause: a 500 KB document has **no reply at
all** today. Its `display_list` sibling would be 164 MB against a 16 MiB line
limit, so `handle_line` declines it without serialising; the v1 `compile_result`
that would carry the pages instead is 20 339 909 bytes for those 385 pages, also
over; the request ends `status: failed`.

Neither existing sibling capability fixes that, and the reasons are structural.
`-delta` needs the full `DisplayList` from `render_cached` before it can diff
anything, so it shrinks the wire after the producer has already built and failed
to fit the whole document. `-only` empties the v1 `pages` only when a sibling is
present, and here the sibling is the 164 MB line that was declined. The window is
the only one of the three that makes the producer build less, which is what a
size limit actually requires.

So `MAX_WINDOW_PAGES` was 512, which is indefensible: at the measured ~426 KB a
page that is 218 MB. It is now 64, derived from the arithmetic -- a 16 MiB line
carries ~39 pages of that document and the runtime's 8 MiB framed default ~19,
both more than a viewer shows and both finite where 1507 pages is not.

`PageWindow::fitting(centre, pages, bytes_per_page, limit)` is the widest window
a given limit can carry. It takes a measured `bytes_per_page` rather than a
constant, because page size varies by an order of magnitude between a title page
and a dense one and a constant here would be a guess presented as a bound; the
caller supplies the previous reply's `page_bytes` or its own estimate. A page too
large for even one to fit still yields a one-page window -- refusing is the
protocol's job, not the window's. Nothing calls it until the capability is
negotiated.

The consequence worth recording is a composition result: `-window` and `-only`
are each useless alone at this scale and sufficient together. The v1 payload
fails on its own at 385 pages (20.3 MB) and the v2 sibling fails on its own
(164 MB), so a consumer that wants large documents to work sends
`display-list-v2`, `-only` and `-window` together. That is the first hard reason
in this protocol to require two capabilities rather than choose between them.

Proposal gains §1.0 for the failure, §1.1 for the memory argument it started
from, and the §7 composition rule. `tests/page_window.rs` gains
`a_window_is_sized_by_the_reply_limit`, which pins the arithmetic against #273's
measured page size rather than against a number invented here.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* merge main: the new extensible delimiters build on the derived carets and the page's items accessor

Three semantic conflicts between this lane and main's `\lVert`/`\rVert` and
extensible-delimiter work. The textual merge was clean; none of them is.

`typeset.rs`'s stacked-assembly cluster (main's extensible delimiter, one
cluster holding the whole Latin Modern Math assembly) set `Cluster.carets`
explicitly. #232 removed that field: the carets are derived from
`text_start_byte` and `hit_rect` (`Cluster::first_caret`), and the run-level
`end_caret` supplies `last` for the final cluster only. The literal it wrote --
`first { text_byte: start, x: g.x, top, height: hh }`, `last: None` -- is
exactly what the accessor derives from the `hit_rect { x: g.x, top, width,
height: hh }` it sits beside, and the run is built with `end_caret: None`, so
dropping the field is value-preserving rather than a behaviour change.

`tests/big_delimiter_packages.rs` and `tests/extensible_delimiters.rs` are new
on main and read `&page.items`, which this lane made a method returning
`Option<&Vec<Item>>`. Both are unwindowed renders, so they take
`resident_items()` -- the accessor that panics on an elided page rather than
reading it as empty -- like the other 20 tests this lane converted.

Builds: `cargo build --tests` clean in render-pipeline, flashtex-cli and
perf-bench.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* display list: negotiate the page window, so the 500 KB document has a reply

r1 specified the wire capability and deliberately did not negotiate it, because
one of the closures §3 requires whole was not yet whole. This closes that gap
and turns the name on, which is what makes the lane's product claim testable
rather than argued: the document that returns `status: failed` today now
returns a painted window.

The gap. `required_features` is derived by classifying items, and it was
derived from `resident_page_items()` -- the window's items, not the document's.
A document whose only rule sits on page 300 would have announced no `rule` to a
consumer windowed on page 1, which is the same failure as a smaller font
closure: a consumer negotiating a feature set it cannot paint the rest of the
document with. §5.6 already named the rule ("computed during the streaming
pass, over every block, not over `pages`"); r1 had not implemented it, and
`display.rs` said so in a comment. `assemble_windowed` now harvests
`DocumentFeatures` in the same pass that harvests the faces and the
diagnostics, from every block including the ones whose only pages are elided,
plus the page-level items the block loop cannot see (float images, the
`\pagecolor` rule, the document default colour). An unwindowed list still
*scans* its own items, so every line on the wire today is byte-for-byte what it
was; only a windowed list reads the harvest.

`status` too. `v1::fallback` derived `has_content` from the pages it built, and
a windowed payload holds only the resident ones, so a window over blank pages
of a document carrying an error could have reported `failed` where the
unwindowed reply says `recovered`. §4.1 says the window does not change
`status`, so the question is now asked of the same whole-document harvest.

Negotiation follows `-only`'s pattern exactly. `CAP_WINDOW` is accepted only
next to `display-list-v2`, `payload.display_list_window` says where the viewer
is, and the name is echoed only on a reply that actually carries a window --
the way `-only` is echoed only when the pages were really elided. Per §7 the
window declines `-delta`: a delta binds a digest for every page and a windowed
producer has none for a page it never materialised. Per §8 a degenerate window
is not an error; the reply is unwindowed and the echo omits the name.

One behaviour beyond r1, and it is the one that makes the capability worth
having: a window the reply limit still cannot carry is narrowed and served
rather than declined. `MAX_WINDOW_PAGES` bounds what a viewer shows, not bytes,
so a consumer can legitimately ask for 64 pages of a document whose pages are
426 KB each. Declining that is the `status: failed` this exists to fix, so the
producer measures the pages it just built, re-derives the window through the
already-present `PageWindow::fitting`, and serves that; the echoed `window` is
the authority on what was served, so the narrowing needs no diagnostic (§8).

Measured, against the real `synthetic-500kb` corpus case, 385 pages, through
the actual `flashtex-render` worker over JSON Lines:

  today's consumer   status failed -- "compile_result would be 20 339 674 bytes
                     for 385 pages, over the 16 777 216-byte reply limit"
  window 1:16        status recovered, 2 lines, sibling 5 937 794 B,
                     385 pages / 16 resident / 369 elided
  window 300:16      status recovered, sibling 6 369 270 B
  window 1:64        narrowed to 13:40 and served, 15 211 146 B

and the §9 equality gate applied to that document rather than to a 20-page
stand-in: for windows at 1, 185, 300 and 378, every resident page object is
byte-identical to that page in the unwindowed 152 MB render, all 385 page
frames match, and `documents`, `fonts`, `diagnostics` and `required_features`
are byte-identical. Zero font-failure diagnostics in every run.

Tests. `cli_e2e` gains the product bug itself as a regression test: the same
three refusals reproduced through `FLASHTEX_MAX_REPLY_BYTES` (the failure is a
ratio, not an absolute size), with the limit derived from a measured window and
the whole-document size read back out of the producer's own refusal, so nothing
is hard-coded to a page size. `page_window` gains the closure test: a document
whose only rule is on a late page, windowed on page 1, must still announce
`rule` -- and it asserts the resident page carries no rule, so the feature can
only have come from the harvest. Reverting the harvest turns that test red with
`["glyph_run", "rgba-srgb", "cluster-actualtext"]` against
`["glyph_run", "rule", "rgba-srgb", "cluster-actualtext"]`, which is the point.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* memprofile: build a request the worker accepts, and measure the window on the protocol path

`memprofile`'s `request()` built a JSON-RPC 2.0 envelope -- `jsonrpc`, `method`,
`params` -- and `protocol::handle_line` requires runtime-v1's
`protocol_version` / `type` / `payload`. Every warm keystroke on the default
(protocol) path was therefore answered `missing_protocol_version` and rendered
nothing, so a default run's warm phase was measuring an empty cache rather than
a populated one.

The window's published numbers are unaffected: they were measured
`--render-only` on both sides, which never builds a request. `crates/perf-bench`
proper builds a correct request (`measure.rs:204`), so the digests and the
timing gates are unaffected too. What was wrong was memprofile's own default
mode, and only its warm phase.

With that fixed, `--window` no longer has to imply `--render-only`: the
capability is negotiated, so a windowed run can drive the same protocol path
the product does, `display_list_window` and all. The comparison rule is
unchanged and now stated as "compare like with like" rather than "windowed
means render-only".

Measured at this commit, release, this machine, zero font diagnostics:

  synthetic-2mb, --render-only    VmRSS 2912.6 -> 2035.9   live 1440.8 -> 920.1
  synthetic-2mb, protocol         VmRSS 2889.0 -> 2048.5   live 1440.8 -> 920.1
  synthetic-500kb, protocol       VmRSS  751.3 ->  540.3   live  363.3 -> 238.2

The `--render-only` pair reproduces the r1 table (2912.3 -> 2035.8, 1440.7 ->
920.0) to within 0.1 MiB after the rebase onto current main and the
negotiation, which is the point of re-running it. The display list is 2.5 MiB
at 385 pages and at 1507, unchanged.

The proposal goes to r2: the capability is negotiated, `required_features` is
whole-document, `status` is window-independent, and an over-limit window is
narrowed and served rather than declined.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* proposal: r2 records what the producer now does, and what a consumer still has to sign

The §9 gate list gains the two tests r2 adds and the equality run against the
real 500 KB case rather than a 20-page stand-in. §1.0 gains the measured
replies -- the failure and the four windows -- so the section that argues the
bug also shows the fix. The measured table notes that the r1 numbers reproduce
after the rebase, adds the protocol-path pair the harness fix made measurable,
and records the harness fix itself rather than quietly benefiting from it.

The co-signer table gains a column. The producer row is signed; the three
consumer rows and the Commander row are unchanged in substance but are now
explicitly gating the *consumer*, because that is what negotiation changes:
no reply on any route is windowed today, and `apps/mac` must not add the name
to its capability list until the pane paints an elided page as a placeholder
rather than as nothing.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* protocol: a failed reply echoes no sibling capability

`-only` and `-window` are echoed only on a reply that actually carries a
sibling line. The over-limit `compile_result` path filtered `display-list-v2`
out of the echo but left those two in, so a reply that sent nothing could still
have claimed the pages were elided for a sibling, or that a window was served.
Reachable only when a windowed or `-only` v1 payload is itself over the limit,
which is why it went unnoticed; wrong either way.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* display list: the comments that said required_features was still the window's

Two stale notes left over from r1. `resident_page_items` said deriving a
document-wide feature set from it was unreconciled r2 work and the reason the
capability was producer-internal; the harvest reconciled it, and the doc now
says what the accessor is for instead -- what a list carries, never what the
document needs. `negotiate`'s note said "in r1" about the -window/-delta
exclusion, which outlived r1.

Comments only. The binaries used for the digest and memory runs at this SHA
predate these two edits and are unaffected by them.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* typeset: say which direction the feature harvest can err in

The harvest visits every block, including one placed on no page, so it can
announce a feature nothing paints. That is the safe direction -- a consumer
told to support `rule` when no rule is drawn loses nothing, while a consumer
not told is the failure the harvest exists to prevent -- and the §9 equality
gate pins the harvest against the unwindowed scan for every document it
covers, so an over-announcement surfaces as a windowed reply differing from
the unwindowed one rather than passing quietly. Worth saying where the next
reader will be standing when a gate fails.

Comment only.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* merge main: the new footnote and float-note oracles read the page through the accessor

`tests/footnotes_oracle.rs` and `tests/float_notes_oracle.rs` arrived on main
with the single page builder (#343) and read `&page.items`, which this lane
made a method returning `Option<&Vec<Item>>`. Both are unwindowed renders, so
they take `resident_items()` -- the accessor that panics on an elided page
rather than reading it as empty -- like the other 23 tests this lane converted.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* proposal: the r2 numbers, measured rather than described

The memory table stays r1's and now says so, with the r2 re-run of the 2 MB
pair beside it: 2919.5 -> 2037.0 MiB VmRSS and 1442.9 -> 922.2 live against
r1's 2912.3 -> 2035.8 and 1440.7 -> 920.0, with the display-list and
render-cache rows identical to the digit. Reproducing the control after two
merges of main is the point of re-running it.

The digest gate gets its result: 190 digests over 26 cases, 0 differing,
against a control built and run in the same directory from the same merge of
main with this lane's changes reverted.

Implementation-Agent: claude-opus-5 (engine lane, linux-primary NixOS)
Commit-Executor: claude-opus-5 (direct git; Cursor usage limit in effect)
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Xd5Hmwh5GHNTiAmHUJ1MZu

* perf-bench: the negotiated window capability stays off in the harness

Capabilities gained `window` on this branch; the harness's fixed set
keeps it off — the timing and digest gates measure the unwindowed
product path, which this branch keeps byte-identical.

Implementation-Agent: fable-ft070
Commit-Executor: fable-ft070 (direct; Cursor usage limit)

---------

Co-authored-by: Claude Opus 5 <[email protected]>
@d-q222

d-q222 commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

opus-reviewer-A review — 72936d2 (independent, Claude Opus; did not see the author's reasoning)
Verdict: NEEDS-FIX (stale: it merges cleanly as text but does not compile on main)
Tests: not run, because the merge result does not build. I merged locally onto main 027e2bd (git merge auto-resolves) and cargo build --tests in crates/render-pipeline fails with 12 E0308 errors (expected Rc<Vec<Item>>, found Vec<Item>). Oracle: n/a (claimed byte-identical perf change; I could not re-measure).
Findings:

  1. The PR is 1261 commits behind, and main has added BuiltBlock { .. items: Vec } constructors that this PR never saw. Examples: src/typeset/beamer.rs:480, src/typeset/marginpar.rs:76, src/typeset.rs:4427, :6763, :6948, plus 7 more. Every one needs Rc::new(..).
  2. The PR's safety argument (incremental.rs comment: "nothing reads an item back ... only assemble_block and floatpage::block_source") no longer describes main. Main now also reads block.items in post_break_rec (typeset.rs:13453), append_leaders (:13471-13479, line_stretch_order) and a filter at :13060. I checked these: they read item kind, glue and kern widths, not source/cluster, so the invariant still appears to hold. The comment's list of consumers is stale, though, and the rebase has to re-audit it. The riskiest spot is typeset.rs ~8166 (items.extend(Rc::try_unwrap(b.items).unwrap_or_else(clone))), because a cache-restored block's unrelocated items get merged into a freshly built list there.
  3. memsize.rs:277 (vec_cap_bytes(&rc.block.items)) will need &* after the type change. It also now counts shared Rc storage once per block, which overstates the "peak memory -7.3%" accounting.
  4. The perf and memory numbers in the body were measured at base 0d93456 and need to be re-measured after the rebase.
    Recommendation: rebase, fix the constructors, refresh the invariant comment to list every current reader, and re-run the byte-identical corpus gate.
    Conflicts: none of the queue PRs touch incremental.rs. render-pipeline: adapt \newblock as a line break under the openbib class option #962 and render-pipeline: set sectioning commands in \twocolumn[material] box #978 touch render-pipeline/src/adapter.rs/typeset.rs regions.

Plain merge of the reviewer's main tip (027e2bd; no origin remote in
this clone, merged by SHA -- rev-list confirms HEAD was 1261 commits
behind it). Auto-resolved with no conflicts.

Implementation-Agent: muse-spark-1.3-contributor
Commit-Executor: muse-spark-1.3-contributor
Merges main 027e2bd (the exact SHA an independent Opus review used) and
repairs the resulting drift:

- Wrapped the 5 BuiltBlock constructors main added since this PR in
  Rc::new(...) (beamer, marginpar, longtable caption, two single-line
  blocks) so items: Rc<Vec<pl::Item>> typechecks. Only 5 sites exist on
  this main, not the 12 the review saw further back — main moved on.
- Re-audited and rewrote the items-sharing invariant comment on
  BuiltBlock::items and in relocate_block to list every current reader
  (assemble_block/post_break_rec: discriminant + post_break presence
  only; append_leaders/line_stretch_order: Glue/Kern widths only;
  floatpage::block_source: items.len() as an index bound only, never an
  item; the intertext Rc::try_unwrap merge: values identical whether
  moved or cloned, allocation never mutated; memsize: capacity
  accounting only). No make_mut/get_mut/into_inner on this field
  anywhere in the crate.
- memsize.rs: made the vec_cap_bytes deref explicit (&*rc.block.items),
  noted the per-block over-count of shared allocations (documented,
  left for a later slice — the PR's "-7.3% peak memory" claim is
  measured with this over-counting ruler post-rebase).
- The flagged risky spot (typeset.rs, intertext Rc::try_unwrap merge) is
  deliberately untouched.

Tests: cargo build --tests now reports zero errors (was 5 lib + 5
lib-test duplicate reports). Full crate suite, debug and release: 194
targets each, 947 passed, 0 failed in each; no test that passed before
the merge fails now.

Implementation-Agent: muse-spark-1.3-contributor
Commit-Executor: daniel-muse-lead
Reviewed-by: daniel-muse-lead
Muse-Lane-Head: 6c412e15684e93aee7d7b31f405e5b896cde130d
Co-authored-by: d-q222 <[email protected]>
@d-q222

d-q222 commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

daniel-muse-lead: merged main (027e2bd, the exact SHA the independent Opus review used — 1261 commits behind, could not use `git merge origin/main` literally since this lane clone has no origin remote) and repaired the drift on top: 5 `Rc::new(...)` wraps (main only added 5 new BuiltBlock constructors since this PR, not the 12 the review saw further back), re-audited and rewrote the items-sharing invariant comment to enumerate every current reader (verified myself against the actual code, not just the check-in's claim), and made the memsize accounting deref explicit with its over-count documented.

Deliberately left the flagged risky spot (the intertext Rc::try_unwrap merge) untouched per the review's own caution — traced it myself too: values are identical whether the vec moves out or gets cloned, and the shared allocation is never mutated.

Independently re-verified: cargo build --tests 0 errors, full crate suite 194 targets/947 passed/0 failed both profiles (spot-checked lib 233/233 + display_list_delta 3/3 myself rather than trusting the full report, given the size of this suite).

@kabir-claude — pushed directly to your branch (fast-forward, nothing rewritten) since it was flagged in a wave-4a assignment; flag if you want changes.

@d-q222

d-q222 commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

flashtex-2a/opus-review-C verdict @00b117429: MERGE-READY (land after an update from main, so CI runs on the merge)

I reviewed this independently from the diff and the merge result only.

Merge

  • 00b117429 merges cleanly onto current main 70ca914bd, which is 393 commits ahead. There are no conflicts.
  • Every BuiltBlock constructor on main compiles with Rc::new(..). cargo test --no-run is clean.

Tests on the merged tree

  • crates/render-pipeline debug: 1047 passed, 0 failed, 20 ignored across 219 targets.
  • --release --test incremental --test display_list_delta --test cache_counters -- --include-ignored: all pass. That includes the slow incremental_output_is_byte_identical_over_30_edits_of_a_107_page_document, which took 397 s.
  • This is the check that matters for this change. It shows that dropping the item relocation leaves incremental output byte-identical to a full render across edits that shift source offsets.

Invariant audit on the merged main

  • I grepped every .items reader of BuiltBlock. The complete list is:
    • assemble_block, which only tests for Item::Box;
    • post_break_rec, which only tests Penalty::post_break.is_some();
    • append_leaders / line_stretch_order, which read glue and kern widths only;
    • floatpage::block_source, which uses len() only;
    • memsize.
  • None of these reads GlyphRun::source or cluster, so the doc comment on BuiltBlock::items still matches main.
  • The \intertext merge (typeset.rs ~8580) always gets a freshly built paragraph_block result, never one from cached(). So Rc::try_unwrap always moves, and unrelocated cached items cannot leak into it.
  • There is no make_mut or get_mut on the field.

pdflatex check

  • None applies. This is a perf-only change with no layout effect, and the byte-identity tests above are the oracle for it.

Notes

  • The perf and memory figures in the body were measured at base 0d93456b and are stale.
  • memsize now over-counts shared Rc storage. That is documented in the code.
  • Per Commander rule 2, perf-bench digests should be unchanged, because the output is byte-identical.

(flashtex-2a/opus-review-C, mac-m5pro-dq222, independent review for d-q222)

@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
d-q222 added a commit that referenced this pull request 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