Skip to content

feat!: read every header box once and share it: ftyp, cdef, pclr and an all-boxes allocation guard - #787

Merged
D0ubleD0uble merged 10 commits into
mainfrom
feat/share-header-boxes
Nov 30, 2026
Merged

D0ubleD0uble merged 10 commits into
mainfrom
feat/share-header-boxes

Conversation

@D0ubleD0uble

@D0ubleD0uble D0ubleD0uble commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

Closes #786

Every header box is now read once and shared, following the design of #781 and #784 (jp2::Lists/kept, read once per walk, cloned in O(1)). Before this change:

  • the ftyp, pclr, cmap and cdef boxes were read twice by each read of the file, once for the checks and once for the plans and metadata;
  • IncrementalDecoder::header copied them on every call.

The checks now build nothing. jp2::box_layout reads the palette, cmap and cdef once into a BoxLayout, which the plans and the metadata share. The ftyp is checked in place and builds its FileType once. An IncrementalDecoder keeps both in jp2::Lists from the first call that finds the jp2c box. The boxes before the jp2c are fixed from then on, and the lists are reset as before when the jp2c start changes or the input shrinks.

Review round 1: what changed

1. Shares are kept while the codestream arrives (blocking)

AfterWalk resets its Lists when its from moves, which it does on each call while the codestream's end is not yet fed. So every call rebuilt the lists of the boxes before the codestream.

  • jp2::Walks::before now keeps the lists as the boxes before the codestream left them, with file_type, layout and colr. It is keyed on the jp2c start: Walks::fit drops it with the rest.
  • Walks::reported seeds a fresh AfterWalk's lists with an O(1) clone of before, so the walk reads only the boxes after the codestream.
  • Decision on the walk after the codestream: it cannot extend from the old position. While the codestream's end is unknown, the bytes between the old and the new from are codestream, not boxes. So that walk still starts again, but from the shared lists.
  • Decision on the walk before the codestream: it still runs on each call, to check the boxes. It no longer keeps a record of each box the metadata reports while before is held, only a count (Kept::count_only), and a walk that finds the jp2c at another start reads them again. Boxes::read no longer builds a String name for each box; it is formatted only into an error. The records of the jp2h children (24 bytes each, for the length of the call) remain; caching them means holding borrowed records apart from the input, so it is documented instead.
  • Streaming guard in tests/header_boxes_alloc.rs: the 1 MiB tile-part is fed 4 KiB at a time, each call must allocate under the per-call bound, and each header must share its compatibility, palette column, cdef, colr payload, xml payload, uinf ids and rreq features with the first header (pointer equality). It fails on 2beaa70 (the PR head reviewed).

2. The sRGB plan is kept across calls

jp2::IccMemo (crate-internal, in Walks) keeps what the plan read of an ICC profile for each form (gray or RGB, a refusal included), the transform built for each format (at most three), and the gray table. It is keyed on the profile's bytes, and a plan of another profile drops it. The checks that depend on the options still run on each plan. No public API changed.

tests/srgb_header_alloc.rs (new) runs every profile in icc/profiles.json that OpenJPEG converts: 179 converted, and a later call allocates at most 4252 bytes (under the 8 KiB bound; one transform built is 50 to 400 KB).

Conformance file, later Srgb call Before Now
file5 6.8 ms, 187 KB 2.1 µs, 1848 bytes
file7 11.1 ms, 281 KB 2.5 µs, 1848 bytes
file8 0.8 ms, 52 KB 1.9 µs, 1968 bytes

3. The docs give the exact costs

The IncrementalDecoder::header rustdoc, docs/resource-bounds.md, docs/incremental-decoding.md, SECURITY.md, the CHANGELOG and the HeaderCache docs no longer say a call "builds nothing of them again" or "8 to 12 bytes per output channel". They now say:

  • the walk before the codestream costs about 9 ns and nothing allocated for each top-level box, plus the contents it checks (0.5 ms for a 4 MiB ftyp or a 65535-entry cdef);
  • each jp2h child costs a 24-byte record for the length of the call, so 50000 unusable colr children (550 KB) cost 0.64 ms and 5.2 MB allocated (3.1 MB peak) a call;
  • output channels cost 20 to 26 bytes each in a header, with at most 16384 of them without a palette: such a header holds 320 KiB, and a call allocates 2.0 MB with its main header parse;
  • the ICC memo holds at most three transforms of 50 to 400 KB.

size_of::<jp2::Walks>() is now 2448 bytes (was 1824), and the docs and the pin test say so. The incremental.rs line of 102 columns is re-wrapped.

The catch-all now also has the many-small-boxes shape: 200 small uuid and 200 small uinf boxes, a res , and an rreq with ML 255 masks. A later call allocates 1304 bytes with 3 columns and 30536 with 255 (the review measured 58,336 at 255 columns); a header holds 98 and 6650.

4. Smaller fixes

  • The HeaderCache Key rules table has rows for jp2::Walks::before (with file_type, colr and layout) and jp2::IccMemo, and its Memory list covers both.
  • M6 is killed by a_uinf_only_checked_builds_no_uuid (src/jp2/tests/uuid_info.rs).
  • docs/stability.md needs nothing: no public type or signature changed in this round, and IccMemo and Walks::before are crate-internal.

Breaking changes (approved for 0.6.0)

  • FileType::compatibility is a MetadataList<[u8; 4]>.
  • UuidInfo::ids is a MetadataList<[u8; 16]>.
  • Jp2Metadata::channel_definitions is an Option<MetadataList<ChannelDefinitionEntry>>.
  • Palette keeps its public API. Its tables are behind Arc, so a clone shares them.

The CHANGELOG "Migrating from 0.5" entry lists these.

Audit: everything metadata() and header build or clone

Value Status
FileType (compatibility) shared: Lists::file_type, MetadataList
channel_definitions (cdef) shared: BoxLayout::cdef, one MetadataList for the plans and the metadata
Palette (columns, values) shared: Arc in BoxLayout
cmap entries shared: Arc<[_]> in BoxLayout
UuidInfo::ids shared: MetadataList, built only in the pass that keeps it
xml , uuid, ipr, uuid_info (location), rreq, colr list, ICC profile already shared (#769, #780, #781, #783, #784)
ImageHeader, Resolution, color (enum) Copy or fixed size
Jp2Metadata::channels (Vec<ChannelDefinition>, 8 B each) bounded by the output channels (at most 16384 components, or 255 palette columns); rebuilt because it depends on the options (raw_channels, component subset, Srgb)
channel_mapping (6 B each) at most 255 entries; rebuilt because it depends on the options
Header::components (12 B each) one per output channel; rebuilt because it depends on reduction, window and subset
plan internals (PalettePlan channels, ChannelPlan order/definitions) one per channel, transient per call; rebuilt for the options
Jp2File::other no longer built while Walks::before is held: only counted
Jp2Header children, colr()/pclr() payload Vecs a 24-byte record per jp2h child, for the length of a call; documented with exact figures
sRGB plan (ICC input profile, transform, gray table) kept: jp2::IccMemo, keyed on the profile bytes
codestream Header pieces in IncrementalDecoder::header the main header is parsed again each call (already documented); not JP2 boxes

Measured (docs/resource-bounds.md method)

The base file is tests/fixtures/jp2_sycc_422_even.jp2 with each box added. Each figure comes from a release program with a counting allocator, with resident memory from /usr/bin/time -v less the base file's 2.9 MiB. Heap figures are bytes per byte the boxes add; resident is in MiB. The 1-minute load was about 13.

Box (bytes added) Heap peak, main → now Heap held, main → now Resident peak, main → now Later header call (nothing new), main → now
4 MiB ftyp (4.19 MB) 2.00 → 1.16 1.00 → 1.16 11.8 → 8.7 4.9 ms, 8.4 MB alloc → 0.48 ms, 1092 B
65535-entry cdef (393 KB) 3.36 → 1.80 1.67 → 1.77 2.1 → 0.9 0.95 ms, 2.4 MB → 0.50 ms, 1247 B
1024 x 255 pclr + cmap (262 KB) 8.24 → 4.26 4.25 → 4.25 2.2 → 1.2 1.6 ms, 3.2 MB → 24 µs, 16 KB

The first-call incremental peak follows the one-shot peak: ftyp 2.00 → 1.16, cdef 3.34 → 1.78, pclr 8.00 → 4.03 B/B. A header held after a later call holds 4.2 MB → 68 B (ftyp), 655 KB → 80 B (cdef), and 1.05 MB → 6.6 KB (pclr, the 255 output channels' entries).

Bound correction: a palette holds an i32 per entry, which is 4 bytes for each byte of an 8-bit column. That is over the 3.2 B/B the docs gave for metadata boxes, and it was true on main as well (held 4.25 there). The palette is capped at 1024 x 255 entries, about 1 MiB. Every citation of the bound now adds "and about 1 MiB more for a palette", the same way the rreq 4.6 MiB clause is written. These docs were updated: README, SECURITY (×5), docs/resource-bounds.md (×4 plus a new table), docs/incremental-decoding.md, the src/lib.rs rustdoc (×2), the IncrementalDecoder::header rustdoc and the HeaderCache docs.

size_of::<jp2::Walks>() went from 1424 to 2448 bytes: Lists gained file_type and layout, and Walks gained before and icc. The docs now say 2448, and a test pins it on 64-bit targets. A call with nothing new on incremental_header_list_alloc now allocates 688 B (692 before), and its header holds 44 B (48 before). The docs are updated to match.

Output identical to main

A release program hashed (128-bit FNV over the {:#?} text, written as it is formatted, so no dump is kept) each output on main (e8b5b49) and on c57ec70, for all 89 .jp2/.jph fixtures under tests/fixtures, in default, Srgb and strict-off modes: decode_with, read_header_with, and IncrementalDecoder header twice and finish. That is 1335 hashes, and the two files are identical by cmp. On this branch the two header calls hash the same for every file and mode. No oracle snapshot or fixture changed.

Acceptance → tests

  • Catch-all guard: tests/header_boxes_alloc.rs (new). One file holds a large box of every type the metadata reports or reads, before and after the codestream. With 3 and with 255 palette columns:

    • a later call allocates < 4 KiB and < 40 KiB (1304 and 30536 B measured);
    • a held header has < 1 KiB and < 8 KiB of its own (98 and 6650 B);
    • 10 headers stay under 10 × that;
    • while the tile-part is fed 4 KiB at a time, each call stays under the same bound (at most 1752 and 30984 B) and each header shares the first one's lists (pointer equality);
    • one-shot peak and held < 1.4 B/B (0.96 and 1.12 measured), and peak minus held < 48 KiB (35 KB).

    It fails on main (4,495,078 B per call with 3 columns).

  • Shared across calls (pointer equality): tests/incremental_header_payloads.rs::header_shares_the_header_boxes_across_calls checks palette columns and entries, compatibility, cdef and uinf ids across first, again and longer, for raw on and off. It fails on main.

  • rreq_seen: tests/rreq_alloc.rs feeds a second whole rreq after the codestream. The call allocates < 4 KiB (1048 B) and shares the entries.

  • Sizes the docs give: a_channel_entry_is_the_size_the_docs_give and the_kept_walks_are_the_size_the_docs_give (in src/jp2/tests/channels.rs).

  • Auto traits: tests/auto_traits.rs covers MetadataList<ChannelDefinitionEntry>, <[u8; 4]> and <[u8; 16]>.

Mutation checks

Each file was backed up and restored after its mutation, each mutation was asserted to apply, and the work was committed first. The suites run were --lib, header_boxes_alloc, srgb_header_alloc, incremental_header_payloads, rreq_alloc, jp2_palette_metadata, read_header_alloc, incremental_header_list_alloc, incremental and incremental_header. All 13 were killed.

Mutant Killed by
M1 rreq_seen: false rreq unit test, header_boxes_alloc
M2 layout read again on each call header_boxes_alloc, incremental_header_payloads
M3 ftyp built on each call same
M4 palette deep clone in palette::plan same
M5 cdef deep copy into the plans same
M6 uinf ids also built in the measure pass a_uinf_only_checked_builds_no_uuid (new)
M7 lists not seeded from before header_boxes_alloc, and two incremental unit tests via the new inconsistency guard
M8 before never kept header_boxes_alloc (streaming)
M9 ICC memo dropped on each plan srgb_header_alloc
M10 ICC input profile not memoized srgb_header_alloc
M11 ICC transform not memoized srgb_header_alloc
M12 boxes before the codestream always recorded header_boxes_alloc
M13 counted boxes not read again when the jp2c moved the_walks_kept_past_the_boxes_start_again_for_another_codestream (extended)

Gate (stable 1.100.1 after rustup update stable, nice -n 19 -j 4)

  • cargo fmt --all -- --check: ok
  • cargo clippy --all-targets -- -D warnings: ok
  • cargo clippy --lib -- -D warnings: ok
  • cargo test: 116 suites, 2092 passed, 0 failed
  • cargo deny check: advisories ok, bans ok, licenses ok, sources ok
  • RUSTDOCFLAGS=-D warnings cargo doc --no-deps: ok
  • wasm32-wasip1 (wasmtime run --dir=$PWD::$PWD, as CI sets it): --lib 856 passed, 6 ignored; jp2_icc 30, sample_limit 2, limit_32bit 18 passed
  • fuzz, 60 s each, one at a time: jp2_boxes 633,213 runs, header_split 117,020, incremental_decode 1,044,958 (-max_len=4096); no crash

What to look at hardest

  • jp2::box_layout and Lists::layout/file_type rest on one premise: once a jp2c is found, the boxes before it are fixed. Walks::fit already resets Lists when the jp2c start moves or the input shrinks, and nothing new depends on the options (layout::read takes only the header and jph).
  • color_channels(plans.palette.output_count(siz), …) replaces plans.outputs(siz, 0)?.len(). They are equal: ChannelPlan::apply keeps the length or returns an Inconsistent error that can't occur here, since the plan is built from that count.
  • The pclr bound clause above is a correction to a bound that was already exceeded on main.
  • Kept::count_only in parse_boxes_kept: the walk before the codestream counts the reported boxes only while Walks::before is held, and walks again keeping them if the jp2c start is not the one the walks were kept for. read_before refuses (Inconsistent) a file whose boxes were only counted.
  • IccMemo is keyed on the profile bytes only. The options reach the plan through the format and the checks, which run on each call.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV

D0ubleD0uble and others added 3 commits November 29, 2026 22:06
FileType::compatibility, Jp2Metadata::channel_definitions and
UuidInfo::ids become MetadataLists, and Palette shares its table. The
ftyp is checked without allocating and built once into the kept lists;
the pclr, cmap and cdef are read once into a BoxLayout kept there too,
which the plans and the metadata share. The checks after the codestream
read no palette table. A new allocation test holds a large box of every
type the metadata reports or reads and guards the whole class.

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

The palette holds 4 bytes for each byte of an 8-bit column, past the 3.2
bound the docs gave for metadata boxes, but at most about 1 MiB, so each
citation of the bound names it as the rreq is named. Adds the measured
before and after table, pins the entry sizes and the kept walks' size, and
lists the new MetadataList types in the auto-trait check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Clippy's wrong_self_convention on the current stable toolchain.

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

codecov-commenter commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.21429% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/jp2/mod.rs 95.6% 4 Missing ⚠️
src/jp2/srgb.rs 97.5% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

D0ubleD0uble and others added 7 commits November 29, 2026 23:10
…at starts again

While the codestream's end is not found, the walk after it starts again
on each feed, which dropped its lists with it: the ftyp, the box layout,
the colr list and the lists of the boxes before the codestream were built
again on each call. The walks now keep those apart, for the jp2c start,
and a walk that starts again starts from a clone of them.

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

An IncrementalDecoder now keeps what an sRGB plan read of an ICC profile
and the transforms it built, so a later header call builds none again.
While the walks hold the lists of the boxes before the codestream, the
walk there counts the boxes the metadata reports instead of keeping a
record of each, and a box is named only for an error.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
@D0ubleD0uble
D0ubleD0uble merged commit ad5db35 into main Nov 30, 2026
15 checks passed
@D0ubleD0uble
D0ubleD0uble deleted the feat/share-header-boxes branch November 30, 2026 06:44
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.

feat!: read every header box once and share it: ftyp, cdef, pclr and an all-boxes allocation guard

2 participants