Skip to content

measured · · 10 min

Halving the heap of a 119-page invoice: four commits and a counting allocator

The first thing I did after forking a Rust PDF engine was measure where a 2,000-row invoice kept its memory. A guard test with a counting global allocator, a peak broken down by allocation site, DOM nodes from 152 to 72 bytes, shared styles, a font held once, and 668 test PDFs that stayed byte for byte the same.

This is part 3 of the pdfblaze series. The reason for leaving headless Chrome was memory, so the first thing I measured in the fork was memory too. A 2,000-row invoice, 119 pages, peaked at 63.5 MiB of heap inside the engine. Four commits later, the same invoice peaked at 33.1 MiB, and peak resident memory for the whole process went from 114 to 86 MiB. Every one of the 668 PDFs in the determinism corpus came out byte for byte the same as before.

This post is how: the guard test, the profile that said where to look, the four changes, and the two numbers that still do not agree with each other.

Why memory, and why a long invoice

The engine I forked was already small on a one-page quote: 24–26 MiB for the whole process. That is not where a server dies. It dies when a customer prints a quote with a thousand lines while other documents print, on a small 2 GB cloud instance that also runs the app. Short documents are cheap; the shape of the curve on long ones decides how many you can print at once.

So the test document was the longest realistic one: an invoice with 2,000 rows, which lays out to 119 pages.

First, a test that fails when memory grows

A profile tells you where memory goes once. A test tells you when it comes back. The first memory commit brought its test with it: a global allocator that counts bytes held and keeps the maximum, around one render of a 600-row table.

terminal
unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let held = HELD.fetch_add(layout.size(), Ordering::Relaxed) + layout.size();
        PEAK.fetch_max(held, Ordering::Relaxed);
        unsafe { System.alloc(layout) }
    }
    // dealloc subtracts; realloc adds or subtracts the difference
}

#[global_allocator]
static ALLOCATOR: Counting = Counting;

The test resets the peak to what is held before the render, renders, and asserts the difference stays under 27/2 MiB, which is 13.5:

terminal
let before = HELD.load(Ordering::Relaxed);
PEAK.store(before, Ordering::Relaxed);
let output = engine.render(&document).unwrap();
let peak = PEAK.load(Ordering::Relaxed) - before;
assert!(peak < 27 * MIB / 2, "heap peak {:.1} MiB", peak as f64 / MIB as f64);

Three choices in that test are deliberate.

  • A counting allocator, not a profiler. dhat gives a richer picture, and I used it for the profile below. But a profiler in the workspace is a dependency every build pays for, and the test only needs one number. The allocator is the one place that needs unsafe in a test, which the workspace allows only in a few named places; it only adds and subtracts.
  • 600 rows, not 2,000. The test runs on every cargo test. 600 rows is enough to make layout's per-row costs dominate and fast enough not to be skipped.
  • A bound, not an exact value. The peak after the first fix was 12.7 MiB. The bound sits a little above it, so ordinary changes pass and a regression of the kind this work removed fails.

The test's own header records what it catches. With the first fix reverted in parts, the peak was 14.3 MiB without the clear, 17.1 without the shrink, and 18.8 with neither. All three fail the bound. That is the check that the test is a test: take the fix out, watch it go red.

Where the heap was

The profile was a dhat run of the 2,000-row invoice. Its maximum heap was 66,549,034 bytes, 63.5 MiB. At that moment, the largest allocation sites were:

SiteMiB
node array9.50
fragment iter_mut7.24
style.rs:705.52
inline emit5.24
block5.14
inline clone3.82
table place_cells3.23
figure 1 · the peak, by allocation site

top sites at a 63.5 MiB peak

  • node array9.50 MiB
  • fragment iter_mut7.24 MiB
  • style.rs:705.52 MiB
  • inline emit5.24 MiB
  • block5.14 MiB
  • inline clone3.82 MiB
  • table place_cells3.23 MiB
The largest allocation sites at the heap peak of the 2,000-row invoice, from dhat. Before: the node array and copied fragments lead. After: no single site holds more than a few MiB.

Two things in that list are not layout doing its job. The node array is the parsed HTML, which should be small next to the layout of 119 pages. And "fragment iter_mut" is fragments being copied after the page loop, which is work done twice.

Four commits

Each commit message records the heap peak of the 2,000-row invoice in layout before and after it, in MB. Those are the steps in the figure; I come back to the units at the end.

figure 2 · the heap, commit by commit
0204060heap MB65.0d1fff6247.586444c642.25921f8a36.8be207de34.5864ce20

864ce20 · 36.8 → 34.5 MB

A font file once

An @font-face file was copied into its face while the resources kept the original. A TrueType or OpenType file is now used as it is.

guard: holds_a_web_font_file_once, which fails with the copy back

Heap peak of the 2,000-row invoice in layout, as each commit message reports it, in MB. The CHANGELOG's dhat measurement of the same work reads 63.5 → 33.1 MiB. Step through to see each change and the test that holds it.

1. Clear and shrink: 65.0 → 47.5

Commit 86444c6. The engine cached laid-out tables, and the cache shared its fragments with the pages. So the passes after the page loop, which place positioned boxes and margin boxes and change the pages in place, found every fragment shared and copied it. On a 119-page table that is most of the document, twice.

The fix is to drop the table cache once the page loop is done, so the later passes own their fragments and change them in place. The second half was smaller and everywhere: lists of fragments built by push kept the spare capacity that growth leaves behind. They are now shrunk to fit as they are made.

This is the commit the guard test arrived with, and the one its three reverted numbers describe.

2. Compact nodes: 47.5 → 42.2

Commit 5921f8a. Every DOM node, text or element, was 152 bytes, because the node type carried an element's data inline. Moving the element data into a box makes a node 72 bytes: a node that is not an element no longer carries room for one.

The node array also kept up to as many empty slots again as it had nodes, the way a growing Vec does. It is now shrunk to fit once parsing is done. The engine's memory budget charges the boxed element data as well, so the budget still sees what the change moved off the array.

The guard is holds_the_nodes_compactly, which fails with either change reverted.

3. Shared anonymous styles: 42.2 → 36.8

Commit be207de. A table cell with text in it gets an anonymous block box around that text, and the box needs computed style values. Each one got its own: 2,000 copies of 2.7 KB in a 2,000-row table, all alike.

The box tree now keeps one set of values per set of parent values and hands it to every anonymous block with alike parents. Each box still has its own style handle, because layout compares styles by address in places, and a box only gets a private copy where something writes to it (-webkit-box and text-indent do).

The guard is shares_the_values_of_anonymous_blocks_in_cells_alike.

4. A font file once: 36.8 → 34.5

Commit 864ce20. The face of an @font-face rule was built from a copy of the font file, while the resources kept the original. For TrueType and OpenType, the face now uses the file's bytes as they are. Only WOFF and WOFF2 are unpacked into data of their own, because they have to be.

The guard is holds_a_web_font_file_once, which fails with the copy back.

The safety net: 668 PDFs, byte for byte

Memory work in a layout engine has one failure mode that no memory test catches: the output changes. A shared style that should not have been shared, a cleared cache that a later pass still needed, and a row of a table moves.

The engine already had a determinism script that renders a corpus with a fixed creation date. I ran it at the fork commit and after the last change and compared the files. 668 PDFs were identical, 190 were refused as not conforming, and 0 differed. Commit 4b8c5dd records it.

Byte-identical is a strong claim, and it is the right bar here. None of the four changes was meant to move a single glyph, so any difference at all would have been a bug.

What the process saw

The heap is the engine's own memory. A server sees the process. Peak resident memory on Apple silicon, a new process per document, after the four commits:

DocumentPeak RSS
One-page quote26–27 MiB
500 rows42 MiB
2,000 rows86 MiB (114 before)

The heap fell by about half; the process, which also holds the binary and everything outside layout, fell from 114 to 86 MiB on the long invoice.

Did it cost speed?

Copying less is usually faster, and the bench smoke agreed. Medians before and after the fork's changes, in milliseconds, with the budgets the CI job checks against three times over:

CaseBeforeAfterBudget
Invoice without lines4.743.512.5
1 page4.154.065
10 pages30.4926.5635
100 pages282.75273.29300
New process17.2513.6910

Two cases are over their own budget before and after, and inside the ×3 that CI allows. These are medians from a smoke test on a laptop, so read the direction, not the decimals.

Separately, I switched the release build from thin to fat LTO in commit d095c5b. That made a one-page quote, 500 rows and 2,000 rows 4–5% faster (19.0 vs 19.9 ms, 100.7 vs 104.7 ms, 331.9 vs 348.5 ms) and the binary 8% smaller. Part 8 has the binary sizes.

Two series that do not agree

There are two sets of numbers for the same work, and I am showing both.

  • The commit messages: 65.0 → 47.5 → 42.2 → 36.8 → 34.5 MB.
  • The CHANGELOG for 1.4.0: 63.5 → 33.1 MiB, from the dhat run.

The starts are most likely one peak in two units: dhat's 66,549,034 bytes is 63.5 MiB, and the commit messages say MB. The ends, 34.5 and 33.1, I cannot reconcile from the files I kept. The likeliest reading is that the commit messages came from one measurement path and the CHANGELOG from another, run at a different moment. The direction and the size of the drop agree: about half.

One more number worth owning: my plan predicted 42.4 after the first round of changes. The measured end was 33.1. The plan was too cautious, which is the better way to be wrong.

What it means for a real document

In the CRM's own benchmark on 1.4.3, a 1,000-line invoice peaked at 58.5 MB and a 1,000-message chat transcript at 74.6 MB, where the old engine grew the app process by 52.4 MB and 389.1 MB for the same documents. Part 7 has the full table.

What I'd do differently, and what's still open

  • Settle the two series. Re-run dhat and the counting test on 1.4.3 and publish one number with its unit. Until then the honest headline is "about half".
  • The memory budget is still an estimate. The engine's --memory-budget stops a document when its own estimate passes the budget. It is not a cap on the process: in the CRM's benchmark, the largest documents that passed under a 256 MiB budget peaked at 415–583 MB of real memory. This work made documents smaller; it did not make the estimate more accurate. On Linux, a hard --memory-limit is the cap.
  • The guard counts requested bytes, not pages. A counting allocator sees what Rust asks for, not what the system allocator holds for it. A change that fragments the heap could raise resident memory and still pass. The peak RSS numbers above are the check for that, and they are not in CI yet.
  • The test is 600 rows. It catches regressions in per-row costs. A regression that only bites past a few hundred pages would get through.
  • Nothing here touched the worker. A long-running worker's memory between documents depends on how freed memory goes back to the system, which the engine already handled before the fork. I did not measure whether these changes moved it.

Part 4 is the next day: a security audit of the released engine, and the two releases that came out of it.

Working through something like this? I help teams ship AI and cloud systems that hold up, and cost what they should.