Research notes / Compression and recovery
LZ4 frame checks: block order, dictionaries and completion
/ Updated / Controlled API experiment and source review
Both block checksums can pass while the decoded data has the wrong order. In our LZ4 test, swapping two independent blocks preserves their checksums and length. Only the content-checksum policy rejects that rearrangement. A separate truncated-frame case returns every expected payload byte without completing the frame.
On this page9 sections
What should a restore accept?
For these experiments, accepting an object means meeting separate requirements. The decoder cannot supply the application's trusted expectations.
- Frame and stream completion: finish every required data frame, advance by consumed input and enforce the intended frame inventory.
- Dependency identity: select the intended dictionary by verified bytes, then keep its storage stable throughout frame decoding.
- Validation coverage: confirm which checks actually ran. A correct prefix or bytes returned before a footer check are provisional.
- Object identity: compare recovered content and required metadata with trusted expectations. Noncryptographic checksums do not authenticate the source.
Stage provisional output separately; publish it as accepted only after the required checks finish. This is a caller design rule derived from the controls below, not an additional LZ4 guarantee.
Move the block and its checksum together
Our input is 65,536 ASCII A bytes followed by 65,536 ASCII B bytes. The compressor creates two independent blocks, each with a block checksum. We move or remove a whole block record, including its original checksum. No checksum is recalculated. The expected restored object always remains A followed by B, exactly 131,072 bytes.
Three independently generated frames isolate the controls: block checksums alone, block plus content checksums, and block checksums plus a declared uncompressed size. All three unchanged controls restore the intended object.
| Policy | Input change | Decoder result | Object accepted |
|---|---|---|---|
| Block checksum | Unchanged A then B | Complete | Yes |
| Block checksum | B then A | Complete | No |
| Block checksum | B removed | Complete | No |
| Block checksum | One payload bit flipped | Block checksum error | No |
| Block checksum | Last EndMark byte missing | Needs more input | No |
| Block checksum | Second complete frame appended | Frame done; input remains | No |
| Block + content checksums | Unchanged A then B | Complete | Yes |
| Block + content checksums | B then A | Content checksum error | No |
| Block + content checksums | B removed | Content checksum error | No |
| Block checksum + declared size | Unchanged A then B | Complete | Yes |
| Block checksum + declared size | B then A | Complete | No |
| Block checksum + declared size | B removed | Size error | No |
Order and inventory are separate checks. Block-only decoding accepts both B+A and A alone as complete frames. Declaring the original size rejects removal, but not same-length reordering. The content checksum rejects both changes in this fixture. Flipping one bit inside the first compressed payload triggers a block-checksum error, providing a corruption-detection control.
The format explains the difference: a block checksum covers that block's stored data; the optional content checksum covers the decoded sequence. Neither is a cryptographic authenticator. The independence flag does not authorize a caller to rearrange an object's contents. [1]
Returned bytes are not a completion signal
Removing only the last byte of the four-byte EndMark produces the entire expected A+B payload, yet the decoder still requests input. A consumer that checks only output length or equality and then silently accepts EOF misses this unfinished frame. Our acceptance rule rejects it.
The public API returns zero when a frame finishes; a non-error, positive return is a next-input hint. It also reports how many input bytes it consumed. Those are distinct signals. Appending another complete frame makes the first call sequence finish with input remaining. Our deliberately single-frame consumer rejects that extra input. A multi-frame application must instead continue according to its explicit framing and inventory policy. [2, LZ4F_decompress]
A reported zero does not mean an empty object
A separate 24-case experiment compares an absent field with zero, 1, 8,191, 8,192 or 8,193-byte size declarations in checksum-enabled frames carrying 8,192 bytes. Only the descriptor and its checksum change; blocks and footer stay byte-identical. Both stored and compressed controls use 1,024- and 16,384-byte output buffers.
On liblz4 1.9.4, both absent and explicitly zero fields report contentSize = 0, complete and return the exact nonempty payload. The three incorrect nonzero sizes fail with ERROR_frameSize_wrong; the exact-size controls pass. The API defines zero as unknown. The format makes this field informational and permits a decoder to skip its validation, so this is not evidence of a format violation. [2, LZ4F_frameInfo_t][1, Content Size]
Our stricter caller rule also compares any advertised size with trusted expected length; it rejects the zero-declared controls. A length in an untrusted header is not an allocation budget or proof of object identity. These are bounded tests, not a resource-exhaustion or security finding. Replay the CC0 size harness against its 24-case receipt, with the original frame and checksum-policy harnesses plus libxxhash installed.
Sizing a header does not validate it
Across seven header probes on liblz4 1.9.4, the ordinary header, its five-byte prefix and headers with a damaged checksum, reserved flag or wrong version all report a size of seven bytes. Yet LZ4F_getFrameInfo rejects those four invalid or incomplete inputs. A header accepted by that function can still precede a damaged content checksum, rejected only during decompression.
Five cursor controls separate the size from consumed input. For our skippable frame, LZ4F_headerSize returns eight, but LZ4F_getFrameInfo consumes four: the length remains unread. Resuming at eight consumes all remaining bytes without completing the frame; resuming at the reported four completes it. Replaying the ordinary header instead fails. Advance by the returned consumed-byte count, not a size estimate or next-input hint. These are caller-policy controls, not a codec defect or a test of every possible header. [2][5]
The CC0 header harness and seven-probe, five-control receipt retain exact input hashes, parser results and completion decisions.
A completed frame need not carry the required data
Our ten multi-frame controls reuse one native context per case. A skippable frame finishes with zero output; its completion is not a recovered data frame. An ordinary empty frame also produces zero bytes, so classify by frameType, not output length. Removing a whole second data frame leaves a valid, fully consumed stream but fails our expected payload and data-frame count. A truncated final skippable frame instead returns all expected data and consumes all available input while still needing more. [2][5]
Completion resets the dictionary binding in liblz4 1.9.4. Reusing the context is supported, but supply the selected dictionary again for each dictionary-dependent frame. Our two-data-frame control fails on the second frame when the dictionary is supplied only for the first; resupplying it succeeds, including with intervening skippable metadata. [5, context reset]
Changing only the skippable generation label leaves our payload-only acceptance unchanged. Decoded-byte verification does not bind that metadata: protect any recovery-critical metadata separately against trusted expectations. These controls use the same dictionary for both data frames, not a different-dictionary selection test. The CC0 harness and ten-case JSON receipt keep frame types, completion and inventory decisions separate.
Do not publish partial output as a verified restore before the required checks finish. Our JSON counts output from successful calls only; bytes and sizes from an error-returning call are not treated as usable output. The chosen 8,192-byte output buffer affects when an error is encountered, not the expected object's identity.
A checksum flag does not prove that it was checked
Our separate option-policy controls change only checksum fields, leaving payload bytes intact. On liblz4 1.9.4, skipChecksums suppresses content-checksum errors and stored (uncompressed) block-checksum errors. It does not suppress the compressed-block checksum error in these fixtures. Header-checksum errors also remain. The compressed-block path computes and compares its checksum without testing the skip state; the pinned v1.10.0 source retains that path, but was not executed here. [5][6]
Setting the option only on the header call, then clearing it before any data, still skips the applicable checks for that frame. Completion resets the option: reusing the context with verification enabled rejects the next frame's damaged content checksum. Choose verification policy before decoding; clearing a later argument cannot restore checks already skipped. [2]
The CC0 harness and 24-case receipt with two reset controls record this version-specific behavior. Earlier experiments keep checksum verification enabled. These mutations do not measure undetected payload corruption, authentication or performance.
A successful call can return an unverified block
Checksum verification is enabled in a separate 32-case streaming experiment. For an 8,192-byte stored block with one altered payload bit, withholding the following block-checksum bytes lets successful calls return all 8,192 changed bytes. Supplying the checksum then reports a block-checksum error. The corresponding compressed-block control returns no output before rejecting the damaged block.
Input partitioning matters: offering the whole stored frame with a 65,536-byte output buffer yields zero bytes from earlier successful calls; a 1,024-byte buffer yields 7,168. Zero does not mean that the failing call left destination memory untouched. Its buffers and counts are excluded. All altered cases fail final acceptance.
The v1.9.4 implementation copies stored bytes before checking their block checksum; it checks compressed block input before decoding. Even that compressed path can return output before a later content-checksum failure. Stage recovered data until the required frame and object checks finish, or give incremental consumers an explicit rollback/discard contract. [5, stored-copy and compressed-block paths]
The CC0 streaming harness and 32-case per-call receipt record both input partitions and output capacities. Keep the original frame and checksum-policy harnesses beside it. This is a one-build validation experiment, not a timing benchmark or an undetected-corruption claim.
Independence removes history, not every dependency
LZ4 independent blocks do not require preceding blocks' decoded history. They may still need an external dictionary: the frame specification initializes each independent block with the same dictionary when one is used. Its identifier is not the dictionary bytes. The original twelve cases above use no dictionary; the supplement below tests that dependency. [1, Dictionary ID]
A raw LZ4 block is a different interface from a frame. Its decoder needs bounds such as compressed size and a maximum decoded size supplied by the surrounding application. An arbitrary byte offset is not a block boundary. [3, Metadata]
A prefix read is not whole-block validation
Our raw-block supplement uses a 71-byte block encoding 96 bytes, then tests truncation, an appended byte, a changed final literal and an invalid history offset. Five full-decoder calls accompany twenty partial calls with targets of 0, 16, 64 and 96 bytes on liblz4 1.9.4.
The partial API returns the correct first 16 bytes in every variant, including the invalid-offset case. With the appended byte, it even returns the exact 96-byte object while the full decoder rejects the supplied input. With the last literal removed, a request for 96 returns a non-error 95; the full decoder rejects that input too. Zero-target calls return zero in all five cases, without establishing any object's validity.
LZ4_decompress_safe_partial stops at a requested output bound. Its return value is not a consumed-input cursor or a whole-block completion signal. Here every target is at most 96, including the oversized-input control, respecting the documented bound for that case. This is expected API scope, not a codec vulnerability. [7]
Full decoding is not identity verification either: the changed literal remains structurally decodable but restores the wrong object. The standalone CC0 harness and native receipt preserve fixture bytes, hashes, signed return codes and separate prefix, length and object checks. No frame checksum or timing is measured.
Hesela's engineering conclusion: random access also needs an offset map, the correct decoder context and a verification policy for the requested data. A frame-wide content checksum cannot be fully checked by decoding only one selected block. Index design and per-object identity belong in the storage system around the codec; independent blocks alone do not supply them.
A dictionary ID selects; it does not identify the bytes
Our separate dictionary experiment adds 18 native cases on liblz41.9.4. The 8,192-byte payload is a slice of a deterministic 32,768-byte dictionary and fits in one block. We supply the correct dictionary, a same-length bytewise-XOR variant, or no dictionary, under two checksum policies and three header IDs: expected, different and omitted.
Each header is generated by the native compressor, including its checksum. Within a checksum policy, every ID variant has identical compressed block records and footer. These are not invalid-header tests. The missing-dictionary controls fail, confirming that this payload actually depends on the dictionary.
| Checks | Dictionary supplied | Codec result | Exact output | ID-only caller accepts |
|---|---|---|---|---|
| Block checksum | correct | Complete | Yes | Yes |
| Block checksum | wrong | Complete | No | Yes |
| Block checksum | missing | Decompression error | No | No |
| Block + content checksums | correct | Complete | Yes | Yes |
| Block + content checksums | wrong | Content checksum error | No | No |
| Block + content checksums | missing | Decompression error | No | No |
A matching ID still permits wrong bytes in this fixture.With block checks alone, the wrong dictionary produces a complete but incorrect output even when the header ID matches the caller's expectation. The content checksum rejects that specific change. Correct dictionary bytes decode under all three IDs, including an omitted ID; the library does not automatically enforce our numeric-ID selection policy.
This follows the version-pinned API and implementation. LZ4F_getFrameInfo exposes Dict-ID; LZ4F_decompress_usingDict takes dictionary bytes and length, not an independently supplied ID to compare. Dictionary lookup and the choice to reject unknown IDs belong to the application. The decoder uses dictionary memory in place, so it must stay accessible throughout frame decoding. Compression-side CDict creation copies it instead. [2, dictionary API] [5, Dict-ID parsing and dictionary decompression]
Hesela's recovery rule is to retain the dictionary bytes and verify their identity against trusted metadata, then require frame completion, intended input consumption and object identity. An out-of-band contract can legitimately select a dictionary without a header ID. Our receipt reports that policy separately from the verified named-ID policy, which adds the expected-ID requirement to the same dictionary and output identity checks. A digest needs a trusted reference, and these noncryptographic frame checks do not authenticate an object.
These designed mutations are neither natural collision measurements nor a claim that every wrong dictionary decodes successfully. The following supplement tests two-block decoding; early buffer release, concurrent decoding and other wrappers remain outside its scope. In particular, do not transfer Zstandard's formatted-dictionary ID behavior to liblz4.
A later argument does not rebind the dictionary
A second supplement follows two 65,536-byte blocks on liblz41.9.4. After consuming the first block and returning all its bytes, we retain the original dictionary, pass a different allocation, or overwrite the original allocation with the XOR variant. A wrong-from-start control checks that dictionary contents matter.
| Blocks | Dictionary action | First block exact | Frame completes | Whole object exact |
|---|---|---|---|---|
| Independent | Retain original | Yes | Yes | Yes |
| Independent | Pass different pointer | Yes | Yes | Yes |
| Independent | Overwrite retained bytes | Yes | Yes | No |
| Independent | Wrong from start | No | Yes | No |
| Linked | Retain original | Yes | Yes | Yes |
| Linked | Pass different pointer | Yes | Yes | Yes |
| Linked | Overwrite retained bytes | Yes | Yes | Yes |
| Linked | Wrong from start | No | Yes | No |
Passing a different pointer leaves the result unchanged in both modes. Overwriting the retained bytes changes later independent-block output; the linked control remains exact after its first full history window. Adding content verification rejects the changed-output cases at the footer.
The implementation installs the external dictionary only during frame initialization. Linked decoding then maintains decoded history. This explains the contrast; it does not authorize releasing or changing dictionary storage early. Keep the selected bytes stable for the whole frame. No freed memory or concurrent mutation is used in this test. [5, LZ4F_decompress_usingDict and LZ4F_updateDict]
Replay the CC0 lifecycle harness against its 16-case JSON receipt, keeping both earlier harnesses beside it:
python3 -B lz4-dictionary-lifecycle.py --verify lz4-dictionary-lifecycle.jsonCompression ratio does not predict read cost
Ji and colleagues' FAST 2021 FPC study is useful context, not an LZ4 benchmark. Their prototype used LZO on F2FS, Android 9.0 and Linux 4.9, on a HiKey 960 with 4 GB RAM and 32 GB UFS. It reorganized read-critical blocks before compression. F2FS was forced into lfs mode, disabling its in-place update fallback. Foreground evaluation replayed captured writes; background evaluation profiled five cold launches per application before compression, clearing the page cache for those profiling launches. Launch times were Android activity-manager measurements, not raw decompressor timings. [4, sections 2.2, 3.3 and 5.1]
The reported launch-time reduction averaged 5.2%, with two of ten applications slightly slower. The best case, 14.8%, was not the average. Its decompression amplification ratio counts compressed logical blocks co-located in physical blocks read, divided by logical blocks actually needed. It is not automatically the ratio of compressed bytes fetched to requested bytes. [4, section 5.2 and figure 13]
FPC's sub-block mapping combines an inode-side index with offsets in the packed physical block's header. That is location metadata around the codec, not a property supplied by block independence. [4, section 4.2 and figure 8]
The paper's Comp baseline reimplemented sequential compression inside F2FS; it was not a head-to-head execution of Btrfs or JFFS2. Thus the reported improvement over Comp should not be relabeled as a speedup over those filesystems. The comparison changes packing and mapping, not only the codec. [4, section 5.1]
FPC also protects mixed compressed data-and-node blocks with a checksum: recovery discards the compressed node when that check fails. This filesystem-level recovery decision is distinct from an LZ4 frame's optional content length or checksum. The paper does not validate the LZ4 zero-size behavior tested here. [4, section 3.2.3]
For a new design, measure useful bytes, bytes fetched, bytes decoded, cache state, CPU time and request latency separately. The checks above establish validation behavior, not a faster block size or a recommended codec.
Reproduce the experiments
Run the CC0 Python harness with Python 3 and an installed liblz4 shared library:
python3 lz4-frame-contract.pyThe recorded JSON includes runtime versions, input and frame hashes, harness hash, exact-output comparisons, errors and generation time. The harness asserts its controls. There is no random seed because the payload and transformations are fixed. This is a bounded fixture parser, not a production decoder or a hostile-input test.
The dictionary supplement has its own CC0 harness and 18-case JSON receipt. Keep the original harness beside it, then run:
python3 -B lz4-dictionary-contract.py --verify lz4-dictionary-contract.jsonThe receipt binds both harness hashes, payload and dictionary recipes, library version, frame and body hashes, and each separate acceptance rule. Consumption and output counts include successful API calls only; they do not report bytes potentially touched by a failing call. The supplement uses exported dictionary functions from the API's static-linking-only section, whose ABI is not guaranteed across versions. A build without those symbols cannot run this harness unchanged. [2]
No checksum-collision probability, performance gain or fleet failure rate is inferred. The mutations demonstrate specified validation boundaries on one library build; they are not a newly discovered LZ4 vulnerability.
Continue with compressed-archive restore checks, LZ4 frames and block-independent compression.
Primary sources
- LZ4 Frame Format 1.6.4, pinned to v1.10.0: block independence, checksums and dictionaries
- LZ4 v1.9.4 public frame API: preferences and LZ4F_decompress completion contract
- LZ4 v1.9.4 block format: out-of-band metadata and decoding bounds
- Ji et al. Pattern-Guided File Compression with User-Experience Enhancement for Log-Structured File System on Mobile Devices. FAST 2021, pp. 127-140
- LZ4 v1.9.4 implementation: frame Dict-ID parsing and LZ4F_decompress_usingDict
- LZ4 v1.10.0 implementation: compressed-block checksum path (source-only comparison)
- LZ4 v1.9.4 raw-block API: LZ4_decompress_safe_partial bounds and return contract