Skip to content

perf: keep the whole main header across header() calls and check PPM without copying - #791

Open
D0ubleD0uble wants to merge 1 commit into
mainfrom
perf/main-header-cache
Open

D0ubleD0uble wants to merge 1 commit into
mainfrom
perf/main-header-cache

Conversation

@D0ubleD0uble

@D0ubleD0uble D0ubleD0uble commented Nov 30, 2026 •

Copy link
Copy Markdown
Owner

Closes #788

Once the codestream main header is whole, IncrementalDecoder::header now keeps its parse and shares it on later calls. No header read copies the PPM data any more.

What changed

  • PPM is checked in place (src/codestream/mod.rs). check_ppm replaces decode_ppm_chunks. It reads the (Nppm, Ippm) records across the segments where they are in the input, with the same checks in the same order and the same errors. ParsedHeader::ppm is now a Ppm: where each segment's Ippm is, in Zppm order (16 bytes a segment, at most 256), and the chunk count. The fault walk only ever used the count. The tile walk (walk_tiles, decode only) appends each chunk from the input into its tile's packet headers as it walks (PpmChunks::next_into). Before, the parse copied each segment, then joined the copies, then built one Vec per record.
  • The whole main header is kept (src/pipeline/header.rs). KeptMain is a new HeaderCache part. It holds Arc<ParsedHeader>, the MainKey hashed once, the codestream start and length, and a sample hash of the main header's bytes. It is lent to KeptCut::parse_main for each read, the same way KeptCut is lent, and handed back whatever the read gives. A later call on a codestream at the same start, no shorter and with the same sample, shares it. It does not parse the header again, and it does not hash the whole header for MainKey either (that hash alone was 3 ms a call on 16.8 MB). Jp2Prefix::parsed is an Arc. The one-shot decode unwraps it with Arc::unwrap_or_clone, which never clones there because the count is 1.
  • Key rules table: a new KeptMain row and a Memory entry. The MainKey doc now says the key is hashed once.
  • Public API, errors and refusals: unchanged.

Key decision: a sample check in release builds too

what_is_kept_is_for_one_input reads a second input with another main header on the same cache. It expects what read_header gives. On main, the full MainKey hash gave that defense. The memo would lose it, so KeptMain::holds_for checks sample_hash (length plus the first and last 4 KiB) of the main header's bytes. On a mismatch it parses again; it does not panic. That costs the same for any header. sample_hash and SAMPLE are no longer debug-only. The KeptCut debug tripwire is unchanged.

Before / after (release, PeakAlloc shim, the review's probe)

Second header() call with nothing new fed:

Case main (ad5db35) this branch
.j2k, 16.8 MB PPM, 4.19M empty records 251.7 MB allocated, 167.8 MB peak, 109 ms 25 bytes, 24 B peak, 2 µs
PPM as one record 67.1 MB, 33.6 MB peak, 30 ms 25 bytes, 2 µs
16384 components, each COC+QCC+RGN (541 KB) 11.7 MB, 6.4 MB peak, 8.5 ms 393 KB (the header's component entries), 0.43 ms
16.7 MB TLM 33 KB, 27 ms 25 bytes, 2 µs
JP2, 16384 components 1x1 (the resource-bounds table row) 1.7 ms, 2.0 MB 0.50 ms, 655 KB

read_header on the 16.8 MB PPM file: peak 167.8 MB → 31 KB (allocated 251.7 MB → 64 KB), 105 → 63 ms. The time left is the record walk over 4.19M records. On one record: 33.6 MB → 31 KB, 27 ms → 29 µs.

Streaming the 16.8 MB PPM file with a 1 MiB tile-part, fed 64 KiB at a time. The 16 calls after the one that finds the main header whole:

  • main: 4.03 GB allocated, 1.76 s;
  • branch: 400 bytes and 34 µs in all.

The finding call itself drops from 251.6 MB to 19 KB.

Held by the decoder now, which is the cost of keeping the parse:

  • 4528 B for the 256-segment PPM file;
  • about 80 B a component, plus the overrides' steps and precincts. That is 1.3 MB for 16384 plain overrides, and 8.7 MB for 16384 components each with a COC of 33 precinct sizes, a 97-step QCC and an RGN. That is under the 13 MB already documented for a main header kept while cut short.

The docs state all of this.

Acceptance → tests

  • Second call on the 16.8 MB PPM file allocates a small constant (25 bytes): tests/main_header_alloc.rs asserts < 1 KiB.

  • read_header peak before → after: 167.8 MB → 31 KB, above. Asserted < 64 KiB in tests/main_header_alloc.rs.

  • New guard cases fail on ad5db35 and pass here: tests/main_header_alloc.rs covers many records, one record, 16384 components and streaming. Run against ad5db35's src, it measures:

    • later calls: 251656305, 67109161 and 11665644 bytes;
    • read_header peaks: 167791056 and 33581520;
    • streaming: up to 251656305 a call.

    Every bound fails there (< 1 KiB, < 1 KiB, < 512 KiB, < 64 KiB, < 1 KiB). On the branch it measures 25, 25 and 393408; peaks of 31184; and 25 a streamed call.

  • Output identical to main: I hashed (128-bit FNV over {:#?}, no dumps kept) 470 fixtures under tests/fixtures (.j2k, .j2c, .jp2, .jph, .seed, .raw, .cut) in 3 modes: default, Srgb and strict off. Per file and mode I hashed:

    • decode_with and read_header_with;
    • IncrementalDecoder header twice, then finish;
    • a streamed decoder fed in 8 pieces, with header after each piece and then finish.

    That is 19629 hashes. The files for ad5db35 and this branch are identical by cmp.

  • Mutations of the new cache key and of the in-place PPM check are caught: see the table below.

  • Docs match the measured figures:

    • the header() rustdoc;
    • docs/resource-bounds.md (a new table, the read_header peak, the 16384-component row);
    • docs/incremental-decoding.md;
    • SECURITY.md (a new held-memory bullet);
    • the CHANGELOG Unreleased entry;
    • the HeaderCache docs.

    tests/incremental_header_cache_alloc.rs now expects the kept parse (4528 B on its PPM file, bound ≤ 16 B a segment + 1 KiB), where it expected nothing.

New unit test: pipeline::header::tests::a_whole_main_header_is_kept_for_one_codestream. It checks:

  • the parse is shared on a longer codestream (Arc::ptr_eq) and the kept key is the one used;
  • it is parsed again at another start, on a shorter codestream, and when one QCD byte of the main header changes.

Mutation checks

The work was committed first. Each file was backed up to scratch and restored from the backup, and each mutation was asserted to apply. Suites run: --lib, main_header_alloc, ppm_nppm, packed_overrun, conformance_part4, incremental_header, incremental_header_cache_alloc, read_header, incremental.

Mutation Caught by
K1 holds_for sample check dropped a_whole_main_header_is_kept_for_one_codestream, what_is_kept_is_for_one_input
K2 start check dropped a_whole_main_header_is_kept_for_one_codestream
K3 length check dropped a_whole_main_header_is_kept_for_one_codestream
K4 never shared (memo off) a_whole_main_header_is_kept_for_one_codestream, a_whole_main_header_is_shared_and_its_ppm_data_read_in_place
K5 kept key not used (rehash) a_whole_main_header_is_kept_for_one_codestream
P1 split-Nppm check dropped ppm_chunks_reject_malformed_framing, an_nppm_split_across_ppm_segments_is_refused_on_every_prefix
P2 chunk count doubled ppm_chunks_split_by_nppm_across_markers, the_fault_walk_gives_the_tile_parts_parse_error_on_rare_shapes, HT corpus pass counts, and more
P3 record not stepped over ppm_chunks_split_by_nppm_across_markers, packed_headers_with_sop_markers_refine_to_the_one_shot_decode, HT corpus, and more
P4 overrun check dropped a_ppm_chunk_past_the_ppm_payload_is_codestream, ppm_chunks_reject_malformed_framing
P5 chunk bytes not copied in the walk ppm_chunks_split_by_nppm_across_markers, grades_the_conformance_corpus_by_compliance_class, HT corpus
P6 short-segment (Lppm 3) check dropped a_ppm_of_lppm_3_is_marker

All 11 were killed; none survived.

Gate

Run on rustc 1.100.1, the latest stable after rustup update stable. All nice, -j 4.

  • cargo fmt --all -- --check: ok
  • cargo clippy --all-targets -- -D warnings: ok
  • cargo clippy --lib -- -D warnings: ok
  • cargo test: 2095 passed, 0 failed, 20 ignored, over 117 binaries
  • cargo deny check: advisories, bans, licenses and sources ok
  • wasm32-wasip1 under wasmtime, as in CI (--lib math_tests, --test jp2_icc, --lib, --test sample_limit, --test limit_32bit): all pass
  • RUSTDOCFLAGS=-D warnings cargo doc --no-deps --document-private-items: clean
  • Fuzz, 60 s each, one at a time, no crashes: jp2_boxes 571k runs, header_split 125k, incremental_decode 1.02M. fuzz/ is unchanged, so no fuzz build step is needed.

Look at hardest

  • KeptMain::holds_for keys on start ==, length <= and the sample. The parse reads nothing past the first SOT, so a codestream at the same start that extends the parsed one gives the same parse. A JP2 codestream that later becomes shorter, fixed to the box payload, is parsed again by the length check.
  • PpmChunks::next_into returns Error::Inconsistent if a codestream other than the parsed one is walked. Every caller passes the same slice: decode, jp2::probe_packets, the fuzz hooks and the tests.
  • The decoder now holds the parse for its whole life. Before, it held only a key (two integers) once the header was whole. That costs up to 8.7 MB for the worst 16384-component header, and it is documented.

Not done (outside #788)

  • A whole main header whose parse fails with a non-Incomplete error is not kept, so each call parses it again to give the same error. That is an error path only.
  • read_header on 65000 one-byte COMs still allocates 4.2 MB. That is the located-segment list, one-shot and not PPM.
  • refine still parses the main header for each refine (documented in docs/incremental-decoding.md).

Review fixes (rebased on #790, 20642cd)

  • F1, a refused whole header is kept. Stopped now carries the first SOT offset when the walk reached it. KeptCut::parse_main keeps a non-Incomplete error of such a header in KeptMain, keyed the same way, and gives it again. The replay goes through the same downstream code, so JP2 hold and strict-off behavior are unchanged. For 16.8 MB of PPM whose last Nppm runs one byte past, a later call went from 62.6 ms and 63.7 KB to 2.5 µs and 55 B. Over 16 streamed calls it went from 1.01 s and 1.02 MB to 26 µs and 880 B. The new guard case in tests/main_header_alloc.rs asserts < 1 KiB, both whole and streamed; on 7d1b980 it measured 63719 B.
  • F3: ppm_chunks_reject_malformed_framing now checks that [(0,[0;6]),(1,[0;2])] gives the Marker error "Zppm 0 ends 2 byte(s) into an Nppm field". The >= 4 to > 4 mutant now fails it.
  • F4: the bytes doc in src/incremental.rs now says that KeptMain::holds_for checks the sample in every build. A debug_assert also compares the full MainKey.
  • F5: the ragged lines are rewrapped.
  • New mutations:
    • E1 (refusal not kept): killed by the guard.
    • E3 (Incomplete kept too): killed by four incremental tests.
    • F3: killed.
    • E2 (a refusal kept even when the walk stopped before SOT): survived. It looks equivalent, since a non-Incomplete main-header error is prefix-stable. Requiring the walk to reach SOT is the conservative choice.
  • Combined figures (release, load about 0.5), main 20642cd → this branch:
    • later JP2 call: 892 → 104 B on the base file and every box shape;
    • header boxes: 888 → 296 B with 3 columns, 30120 → 29528 B with 255;
    • streaming: at most 296 / 29528 B a call;
    • header_boxes_alloc many-boxes: 648 → 56 B;
    • list peak: 592 → 56 B;
    • 16384 components: 1.71 ms and 1.97 MB → 0.41 ms and 655 KB;
    • the first-call peak of 100000 bpcc is still 2.48 MB.
  • Docs: the feat!: read every header box once and share it: ftyp, cdef, pclr and an all-boxes allocation guard #786 table column is restored as history. The perf: header boxes after jp2h and repeated jp2h are recorded on every header() call #789 table gains an "after perf: header boxes after jp2h and repeated jp2h are recorded on every header() call #789" column, a "now" column and a 16384-components row.
  • Box-walk timing: the box walk times read 0.1 to 0.16 ms higher on this branch, about 1.5 ns a box. This reproduced across repeated runs, though perf: keep the whole main header across header() calls and check PPM without copying #788 does not touch src/jp2. perf is unavailable here, so it is reported in the docs rather than explained.
  • Gate:
    • fmt, both clippy runs, cargo test (2101 passed), cargo doc -D warnings (public and private) and deny: all pass;
    • wasm32-wasip1, five steps: all pass;
    • fuzz, 60 s each: header_split 110k runs and incremental_decode 992k, no crashes.
  • Hashed comparison: 32,208 hashes over 470 fixtures in 3 modes are identical to 20642cd. The run calls header three times, plus two calls per streamed piece.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.04878% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/codestream/mod.rs 96.1% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

…without copying

Once the main header was whole, each IncrementalDecoder::header call
parsed it again and hashed it for its key, and every parse copied the
PPM data twice (once per segment, then one Vec per Nppm record). On a
16.8 MB PPM main header that was 252 MB allocated and 104 ms a call.

- codestream: check_ppm reads the PPM records in place across the
  segments, with the same checks and errors; ParsedHeader holds where
  each segment's Ippm is and the chunk count (Ppm). The tile walk
  appends each chunk from the input as it walks. A failed parse says
  where the first SOT is when the walk reached it.
- pipeline::header: KeptMain keeps the parsed main header (Arc), or the
  error of one refused once whole, with its MainKey hashed once, keyed
  on the codestream start ==, length <= and a sample hash of the main
  header's bytes, lent to KeptCut::parse_main.
- Guard tests/main_header_alloc.rs: PPM many records, one record, 16384
  components, streaming, and a refused PPM header; it fails on ad5db35.
- Docs: header() rustdoc, resource-bounds, incremental-decoding,
  SECURITY, CHANGELOG, the HeaderCache key rules and the
  header_boxes_alloc figures give the new costs.

Closes #788

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV
@D0ubleD0uble
D0ubleD0uble force-pushed the perf/main-header-cache branch from 7d1b980 to fd12e26 Compare November 30, 2026 10:07

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: keep the whole main header across header() calls and check PPM without copying

2 participants