Repository navigation
perf: keep the whole main header across header() calls and check PPM without copying - #791
Open
D0ubleD0uble wants to merge 1 commit into
Open
D0ubleD0uble wants to merge 1 commit into
D0ubleD0uble wants to merge 1 commit into
Conversation
Codecov Report❌ Patch coverage is
📢 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
force-pushed
the
perf/main-header-cache
branch
from
November 30, 2026 10:07
7d1b980 to
fd12e26
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #788
Once the codestream main header is whole,
IncrementalDecoder::headernow keeps its parse and shares it on later calls. No header read copies thePPMdata any more.What changed
PPMis checked in place (src/codestream/mod.rs).check_ppmreplacesdecode_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::ppmis now aPpm: where each segment'sIppmis, inZppmorder (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 oneVecper record.src/pipeline/header.rs).KeptMainis a newHeaderCachepart. It holdsArc<ParsedHeader>, theMainKeyhashed once, the codestream start and length, and a sample hash of the main header's bytes. It is lent toKeptCut::parse_mainfor each read, the same wayKeptCutis 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 forMainKeyeither (that hash alone was 3 ms a call on 16.8 MB).Jp2Prefix::parsedis anArc. The one-shot decode unwraps it withArc::unwrap_or_clone, which never clones there because the count is 1.KeptMainrow and a Memory entry. TheMainKeydoc now says the key is hashed once.Key decision: a sample check in release builds too
what_is_kept_is_for_one_inputreads a second input with another main header on the same cache. It expects whatread_headergives. On main, the fullMainKeyhash gave that defense. The memo would lose it, soKeptMain::holds_forcheckssample_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_hashandSAMPLEare no longer debug-only. TheKeptCutdebug tripwire is unchanged.Before / after (release,
PeakAllocshim, the review's probe)Second
header()call with nothing new fed:.j2k, 16.8 MBPPM, 4.19M empty recordsPPMas one recordCOC+QCC+RGN(541 KB)TLMread_headeron the 16.8 MBPPMfile: 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
PPMfile with a 1 MiB tile-part, fed 64 KiB at a time. The 16 calls after the one that finds the main header whole: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:
PPMfile;COCof 33 precinct sizes, a 97-stepQCCand anRGN. 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
PPMfile allocates a small constant (25 bytes):tests/main_header_alloc.rsasserts < 1 KiB.read_headerpeak before → after: 167.8 MB → 31 KB, above. Asserted < 64 KiB intests/main_header_alloc.rs.New guard cases fail on ad5db35 and pass here:
tests/main_header_alloc.rscovers many records, one record, 16384 components and streaming. Run against ad5db35'ssrc, it measures:read_headerpeaks: 167791056 and 33581520;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 undertests/fixtures(.j2k,.j2c,.jp2,.jph,.seed,.raw,.cut) in 3 modes: default,Srgband strict off. Per file and mode I hashed:decode_withandread_header_with;IncrementalDecoderheadertwice, thenfinish;headerafter each piece and thenfinish.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
PPMcheck are caught: see the table below.Docs match the measured figures:
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);HeaderCachedocs.tests/incremental_header_cache_alloc.rsnow expects the kept parse (4528 B on itsPPMfile, 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:Arc::ptr_eq) and the kept key is the one used;QCDbyte 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.holds_forsample check droppeda_whole_main_header_is_kept_for_one_codestream,what_is_kept_is_for_one_inputa_whole_main_header_is_kept_for_one_codestreama_whole_main_header_is_kept_for_one_codestreama_whole_main_header_is_kept_for_one_codestream,a_whole_main_header_is_shared_and_its_ppm_data_read_in_placea_whole_main_header_is_kept_for_one_codestreamNppmcheck droppedppm_chunks_reject_malformed_framing,an_nppm_split_across_ppm_segments_is_refused_on_every_prefixppm_chunks_split_by_nppm_across_markers,the_fault_walk_gives_the_tile_parts_parse_error_on_rare_shapes, HT corpus pass counts, and moreppm_chunks_split_by_nppm_across_markers,packed_headers_with_sop_markers_refine_to_the_one_shot_decode, HT corpus, and morea_ppm_chunk_past_the_ppm_payload_is_codestream,ppm_chunks_reject_malformed_framingppm_chunks_split_by_nppm_across_markers,grades_the_conformance_corpus_by_compliance_class, HT corpusLppm3) check droppeda_ppm_of_lppm_3_is_markerAll 11 were killed; none survived.
Gate
Run on rustc 1.100.1, the latest stable after
rustup update stable. Allnice,-j 4.cargo fmt --all -- --check: okcargo clippy --all-targets -- -D warnings: okcargo clippy --lib -- -D warnings: okcargo test: 2095 passed, 0 failed, 20 ignored, over 117 binariescargo deny check: advisories, bans, licenses and sources ok--lib math_tests,--test jp2_icc,--lib,--test sample_limit,--test limit_32bit): all passRUSTDOCFLAGS=-D warnings cargo doc --no-deps --document-private-items: cleanjp2_boxes571k runs,header_split125k,incremental_decode1.02M.fuzz/is unchanged, so no fuzz build step is needed.Look at hardest
KeptMain::holds_forkeys on start==, length<=and the sample. The parse reads nothing past the firstSOT, 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_intoreturnsError::Inconsistentif 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.Not done (outside #788)
Incompleteerror is not kept, so each call parses it again to give the same error. That is an error path only.read_headeron 65000 one-byteCOMs still allocates 4.2 MB. That is the located-segment list, one-shot and notPPM.refinestill parses the main header for each refine (documented indocs/incremental-decoding.md).Review fixes (rebased on #790, 20642cd)
Stoppednow carries the firstSOToffset when the walk reached it.KeptCut::parse_mainkeeps a non-Incompleteerror of such a header inKeptMain, 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 ofPPMwhose lastNppmruns 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 intests/main_header_alloc.rsasserts < 1 KiB, both whole and streamed; on 7d1b980 it measured 63719 B.ppm_chunks_reject_malformed_framingnow checks that[(0,[0;6]),(1,[0;2])]gives theMarkererror "Zppm0 ends 2 byte(s) into anNppmfield". The>= 4to> 4mutant now fails it.bytesdoc insrc/incremental.rsnow says thatKeptMain::holds_forchecks the sample in every build. Adebug_assertalso compares the fullMainKey.Incompletekept too): killed by four incremental tests.SOT): survived. It looks equivalent, since a non-Incompletemain-header error is prefix-stable. Requiring the walk to reachSOTis the conservative choice.header_boxes_allocmany-boxes: 648 → 56 B;bpccis still 2.48 MB.src/jp2. perf is unavailable here, so it is reported in the docs rather than explained.cargo test(2101 passed),cargo doc -D warnings(public and private) and deny: all pass;header_split110k runs andincremental_decode992k, no crashes.🤖 Generated with Claude Code
https://claude.ai/code/session_01EhjiZ6QTR3gTC3QaD9m2QV