Skip to content

perf: record the header boxes before the codestream once (#789) - #790

Open
D0ubleD0uble wants to merge 9 commits into
mainfrom
perf/jp2h-records-once
Open

D0ubleD0uble wants to merge 9 commits into
mainfrom
perf/jp2h-records-once

Conversation

@D0ubleD0uble

@D0ubleD0uble D0ubleD0uble commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

Closes #789

What changed

An IncrementalDecoder now records the header boxes before the codestream once (every jp2h child, a repeated jp2h, and misplaced top-level colr/bpcc/pclr/cmap/cdef after jp2h) and shares them with every later header() call. Before, each call rebuilt the whole list.

Decision: keep, don't document. The records can be kept without borrowing the input. A record is now an owned Child { kind, start, end }, a range of the input (24 B, 12 B on 32-bit). The records sit in jp2::Walks::header as a MetadataList<Child> (the 64-record blocks the metadata lists use), under the same key as the other kept walks (the jp2c start, with input that only grows). A later walk still walks and checks every header box, then adopts the kept records instead of pushing new ones. adopt refuses records that end past the input with Error::Inconsistent. One-shot parse_boxes keeps none, so read_header/decode gain no extra allocation. The records are built in blocks of 64 (list::Extender): a full block never moves or grows, so no record is held twice and nothing is shrunk. The decoder holds 24 bytes a record, at most 64 more for each block of 64 (its 16-byte header and up to two 24-byte table slots), and 128 bytes more: at most 3.2 bytes for each byte of those boxes, plus 128 bytes.

Also in this PR:

  • The colr()/pclr()/cmap()/cdef()/res() accessors return iterators, so a call collects no Vec.
  • IccMemo::fit takes a ptr::eq fast path, so a shared profile is not compared byte by byte.
  • Jp2Header has a manual Debug (it prints the same in both modes and does not print the input).
  • size_of::<jp2::Walks>() goes from 2448 to 2504.
  • MetadataList gains a crate-internal blocks() (the items as their slices), and Extender gains len(), blocks() and Clone.
  • The five long lines from feat!: read every header box once and share it: ftyp, cdef, pclr and an all-boxes allocation guard #787 are re-wrapped (SECURITY.md:50/72/78, docs/incremental-decoding.md:420/474).

No public API change. No error or refusal changes.

Acceptance → test

Item Demonstrated by
Later header() allocates nothing per header box (misplaced colr, repeated jp2h, many jp2h children) tests/header_boxes_alloc.rs every_header_box_is_read_once_and_shared: n=10000 per shape, later call < 1 KiB and equal to the first. On main these shapes allocate 787,048 / 1,311,208 / 1,311,208 B
Records kept once and shared jp2::tests::the_walks_keep_the_header_box_records_once (5 records, Arc shared across later parses, ihdr position, Debug equal, the one-shot path keeps none)
Records kept for another jp2c start are made again, even with no kept box lists jp2::tests::header_box_records_kept_for_another_codestream_start_are_made_again (kills if kept.count_only at the re-walk guard)
Records across block boundaries are read back in order jp2::tests::header_box_records_past_a_block_are_read_back_in_order (130 records: two full blocks and a partial one, on the first walk and on the adopting walk)
Records past the input refused jp2::tests::header_box_records_past_the_input_are_refused
One-shot read_header not made worse same alloc test: 10k-bpcc one-shot < 480000 + 24 KiB (measured 498,593; main 789,401)
ICC memo does not re-compare a shared profile jp2::srgb::memo_tests::the_memo_compares_no_bytes_of_the_profile_it_shares
Output unchanged hashed comparison below
Docs state the cost header() rustdoc, docs/resource-bounds.md (new #789 table), docs/incremental-decoding.md, SECURITY.md, HeaderCache notes, CHANGELOG

Before / after (later header() call)

Case main this PR
100k misplaced colr 10,486,248 B, 6.29 MB peak, 1.54 ms 892 B, 1.26 ms
100k jp2h boxes 10,486,248 B, 6.29 MB peak, 3.95 ms 892 B, 3.49 ms
jp2h with 100k bpcc 6,292,072 B, 4.72 MB peak, 1.10 ms 892 B, 1.07 ms
jp2h with 50k colr 5.24 MB, 0.63 ms 892 B, 0.55 ms
jp2h with 100k free 1,052 B, 0.69 ms 892 B, 0.68 ms
fixture base 1,052 B, 1.5 µs 892 B, 1.46 µs

(Release build, median of 21 runs.)

First header() call, and what the decoder holds

Release build, one decoder per row. Time is the median of 7 first calls.

Case main shrink_to_fit version blocks (this PR)
jp2h with 100k bpcc: allocated / peak 6,297,152 / 4,721,040 B 8,696,920 / 5,548,264 B 4,929,696 / 2,478,908 B
held after the call 2,520 B 2,402,608 B 2,476,776 B
first call / later call time 1.6 / 1.15 ms 2.8 / 1.1 ms 2.2 / 0.94 ms
100k misplaced colr: allocated / peak 33,790,368 / 8,520,620 B 15,219,256 / 5,678,900 B 11,452,032 / 5,753,068 B
held after the call 3,276,680 B 5,676,768 B 5,750,936 B
100k jp2h: allocated / peak 33,790,336 / 8,520,620 B 15,219,200 / 5,678,844 B 11,451,976 / 5,753,012 B
later call, every shape 6.3 to 10.5 MB 648 B, 592 peak 648 B, 592 peak

For the bpcc row, the held records come to 24.74 bytes each, 2.75 bytes for each byte of the 9-byte boxes. Main holds nothing for the records, because it builds them again on every call. In the colr rows the held figure also includes the metadata's colr list, which main holds too.

Verification

  • Gate on rustc 1.100.1, all green: cargo fmt --check, both clippy -D warnings runs, cargo test (116 suites, 2098 passed), cargo deny check, RUSTDOCFLAGS=-D warnings cargo doc --no-deps.
  • wasm32-wasip1 (wasmtime): --lib 862 passed, jp2_icc 30, sample_limit 18, limit_32bit 2.
  • Fuzz, 60 s each, no findings: jp2_boxes (798k runs on the block version), header_split (142k), incremental_decode (983k on the block version, -max_len=4096).
  • Hashed output comparison against main: 391 fixtures (89 .jp2/.jph) × default, Srgb and strict-off. Covers decode_with, read_header_with, incremental header() twice and finish(). FNV-128 over {:#?}, 5,865 hashes, identical. The first and second header() hashes match in every case.
  • Mutations, all killed:
    • block boundary at 63 instead of 64
    • Extender::finish drops the partial tail
    • Extender::blocks drops the pending tail
    • MetadataList::blocks drops the tail, or the last full block
    • Extender::len leaves out the tail
    • re-walk guard reduced to if kept.count_only
    • records never kept
    • adopt skipped
    • one-shot path keeps records
    • end check removed
    • ICC ptr::eq removed
    • children counted only when recording
    • misplaced boxes not recorded
    • wrong child offset

What to look at hardest

  • parse_boxes_in in src/jp2/mod.rs. When records are kept, the early walk checks without pushing. If keeps_for fails, it starts the walk again from scratch. Records are saved only once the jp2c start is kept.
  • Jp2Header::read in src/jp2/header.rs. ihdr_at and the child count are taken from the walk whether or not the walk records. That is why Records no longer carries ihdr_at.
  • adopt trusts that the walk under the same key saw the same boxes. The end check is a backstop against reading past the input, not a full equality check.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV

D0ubleD0uble and others added 7 commits November 30, 2026 01:20
An IncrementalDecoder walked the boxes before the codestream on every
header() call and made a 24-byte record of each header box: the children
of each jp2h, and the bpcc, colr, pclr, cmap and cdef boxes misplaced at
the top level after it. The per-type accessors then collected payload
Vecs. 100,000 misplaced colr boxes cost 10.5 MB allocated a call.

The records now hold the box type and a range of the input, so they
borrow nothing and the walks keep them (Walks::header) for one jp2c
start, as they keep the lists. A later walk still checks the boxes but
takes the kept records in place of new ones. The accessors return
iterators, so no call collects a Vec. IccMemo::fit checks whether the
profile is the one it holds, shared, before comparing the bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Keep the records only where the walks outlive the parse, shrunk to fit,
and pin it: a unit test that the walks keep them once and later parses
share them, and three shapes in the allocation guard (a jp2h of bpcc
children, repeated jp2h boxes, misplaced top-level colr boxes) that a
later call allocates under 1 KiB for, 787 KB to 1.3 MB on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
…g lines

The IncrementalDecoder::header rustdoc, docs/resource-bounds.md,
docs/incremental-decoding.md, SECURITY.md and the HeaderCache docs now
say that the first call keeps a 24-byte record for each header box in or
after jp2h and later calls share it, with measured figures, and that the
walks are 2480 bytes. Five prose lines over 80 columns are re-wrapped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
The walk places ihdr among the header boxes whether it records them or
not, so the kept records need not carry it. A record past the input a
header reads is refused as Error::Inconsistent, now pinned by a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Shrinking the list to fit held both lists at once: with 100000 bpcc
children the first incremental call peaked at 5.55 MB against 4.72 MB on
main. The list is now kept as it grew, with room for at most twice as
many records, and the first call's peak is main's.

Also test that records kept for another jp2c start are made again where
the walks hold no lists of the boxes before the codestream: the guard
in parse_boxes_in was reached by no test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.05213% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/jp2/header.rs 99.1% 1 Missing ⚠️
src/jp2/mod.rs 98.3% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

D0ubleD0uble and others added 2 commits November 30, 2026 03:03
A list that grows by doubling either keeps up to twice the room it uses
or, shrunk to fit, holds both copies at once on the first call. The
records now go in the blocks MetadataList uses: a full block never moves
or grows, so the first call peaks at the records (2.48 MB for 100000
bpcc children, 4.72 MB on main) and the decoder holds at most 3.2 bytes
for each byte of the boxes, plus 128 bytes. The walks grow to 2504 bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV

This branch has not been deployed

No deployments
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.

perf: header boxes after jp2h and repeated jp2h are recorded on every header() call

2 participants