Qué hace
- CRC32 (IEEE), CRC32C con la instrucción de la CPU, Adler-32, XXH32 y XXH64
- RLE, LZ4 block y frame
- Deflate completo, con envoltorios zlib y gzip
- Niveles Fast, Default, Better y Best
- Diccionario predefinido y diccionario preparado persistible
- Streaming en ambos sentidos para deflate, zlib, gzip, LZ4 frame y RLE
- Escudo contra bombas de descompresión, activado por defecto
- No asigna memoria (demostrado por test)
Medido
- Release, bloque de 256 KiB, Windows x64 / Linux x64. CRC32C: 24.26 GB/s y 23.0 GB/s (objetivo de 20 GB/s cumplido)
- Bloque LZ4, texto: comprime a 365 y 380 MB/s, frente a 391.2 MB/s de la referencia <code>LZ4_compress_default</code> en la misma máquina. Objetivo de 600 MB/s no cumplido. Descomprime a 3.24 GB/s en Windows y 2.48 GB/s en Linux (el objetivo de 3 GB/s solo se cumple en Windows)
- Ratio del nivel Best vs. zlib -6, 7 corpus de 200 KiB: entre el 98% y el 100% de zlib, por delante en dos
- Fuzzing por mutación (no guiado por cobertura): 100 millones de entradas con ASan y UBSan, sin caídas. 79,864 verificaciones cruzadas en Linux sin ninguna divergencia frente a liblz4, zlib y libxxhash
- CRC32 (polinomio IEEE), tabla slice-by-8: 1.57 GB/s en Windows y 2.38 GB/s en Linux. Objetivo de 20 GB/s no cumplido: la instrucción x86 <code>CRC32</code> solo calcula CRC32C, que sí lo alcanza
Límites conocidos
- Zstd queda fuera por diseño (<code>eUnsupportedAlgorithm</code>)
- Las pruebas contra las referencias solo se ejecutan en Linux, y el fuzzing no está guiado por cobertura. El LZ4 frame en streaming rechaza bloques de más de 64 KiB
Compression, decompression and the checksums that the envelopes use.
Status: ready, except for Zstd. The checksums, RLE, LZ4 in block and frame format and complete Deflate with the zlib and gzip envelopes are ready and verified against the system reference libraries, with a preset dictionary and an entry point that treats the format as a value. The streaming interface in both directions and the C ABI layer are also ready. "What is missing" says what stays out (Zstd) and what stays open (
DataChunk).
#include <ethereal/cpp/compression/compression_inc.hpp>
using namespace Ethereal::Compression;
// The format is a value: it comes from configuration, from a network header, from anywhere.
const EAlgorithm eAlgo = EAlgorithm::Gzip;
std::vector< std::uint8_t > Comp( CompressBound( eAlgo, Data.size() ) );
std::size_t uComp = 0;
Compress( eAlgo, Data, Comp, uComp );
std::size_t uOut = 0;
Decompress( eAlgo, std::span( Comp.data(), uComp ), Out, uOut ); // shield on
// And when the format did not come along with the data:
EAlgorithm eFound;
if( DetectAlgorithm( Received, eFound ) )
Decompress( eFound, Received, Out, uOut );---
An important correction: the module that already existed compresses nothing
The cpp/compression directory already existed in the tree, and what it holds is DataChunk: a memory buffer with file read and write. No compression. The name is misleading, and this is stated here so that nobody wastes time looking for what is not there.
---
What already exists
| Piece | Status |
|---|---|
ECompressionError, EAlgorithm, ELevel | ready |
SDecompressLimits (shield against bombs) | ready, on by default |
Crc32 / Crc32Update (IEEE 802.3) | ready, slicing-by-8 table |
Crc32c / Crc32cUpdate (Castagnoli) | ready, processor instruction plus table |
Crc32cUsesHardware | ready |
Adler32 / Adler32Update | ready |
XxHash64 | ready |
XxHash32 | ready. It is not a truncated XXH64, it is a different function |
RleCompress / RleDecompress / RleCompressBound | ready |
Lz4Compress / Lz4Decompress / Lz4CompressBound | ready, block format |
Detail::WriteExtendedLength / ReadExtendedLength | ready, exposed on purpose (see below) |
Inflate (RFC 1951) | ready: stored, fixed Huffman and dynamic Huffman |
Deflate / DeflateBound | ready: chooses among stored, fixed Huffman and dynamic Huffman, by measuring all three |
ZlibDecompress / ZlibCompress (RFC 1950) | ready, with Adler-32 verified |
GzipDecompress / GzipCompress (RFC 1952) | ready, with CRC32 and size verified |
Detail::FixedShortcutFilled | ready, exposed on purpose (see below) |
Lz4FrameCompress / Lz4FrameDecompress / Lz4FrameCompressBound | ready, frame format |
Lz4DecompressWithPrefix | ready. It is what makes the frame with linked blocks work |
DeflateWithDictionary / InflateWithDictionary | ready |
ZlibCompressWithDictionary / ZlibDecompressWithDictionary | ready, with DICTID verified |
Lz4CompressWithDictionary | ready |
Compress / Decompress / CompressBound | ready, the format as a value |
DetectAlgorithm | ready, and says clearly when it does not know |
What is missing
Inside the module, nothing. The streaming interface in both directions, the memory report, the C ABI layer, the concatenation of multiple members (gzip and LZ4 frames) and the eight items of section 8 are done and measured.
What stays out by decision is Zstd. What stays open is DataChunk, which lives in this module without compressing anything and accounts for 293 of the 391 KiB that the module costs at link time (see Item 8 further below).
In the compressor, what was missing to reach zlib was no longer Huffman. It was the match finder, which had one entry per slot and no chain. That is closed: Better and Best walk a chain of candidates, and with Best the ratio is between 98% and 100% of zlib on all seven corpora, ahead of it on two. The cost in time and in stack is measured below.
Zstd is out by decision, and the spec itself allows it: "if schedule pressure appears, ship Deflate and LZ4 complete and correct, and stage Zstd behind a compile flag rather than shipping a partial implementation." Requesting EAlgorithm::Zstd returns eUnsupportedAlgorithm.
---
Where the spec is wrong, and what was done
1. The CRC32 instruction does not compute the IEEE CRC
The spec says: *"CRC32 (IEEE) using CRC32 instruction on x64 SSE4.2"*.
That does not work. The x86 CRC32 instruction computes the Castagnoli polynomial, not the IEEE one. They are different polynomials, and no arrangement of registers converts one into the other. The fast path for IEEE exists, but it goes through carry-less multiplication (PCLMULQDQ), which is a different instruction and a different set of constants.
What was done: Castagnoli uses the instruction. IEEE uses a slicing-by-8 table, which is the fastest option without resorting to PCLMULQDQ.
There is a second correction, smaller and more dangerous: capability detection gained its own SSE4.2 level. Before, it only went up to SSE4.1, and using 4.1 as an approximation for the CRC32 instruction would produce an illegal instruction on processors that have 4.1 but not 4.2 (the Penryn family).
2. The expansion ratio does not protect LZ4
SDecompressLimits has two shields: an absolute byte ceiling and a maximum ratio between output and input. The default ratio is 1,024.
It is unreachable in LZ4. The block format limits expansion to about 255 times by construction: each extended length byte adds 255 to the output and costs one byte of input. No valid LZ4 stream reaches 1,024, so there the absolute ceiling is what protects, and it is on by default.
This was discovered through a failing test: its first version required the default to stop a bomb with a ratio of 235, and there was no way to do it. Lowering the ratio to near 255 would reject legitimate data: five thousand zeros compress to twenty bytes, which is already a ratio of 250. The value of 1,024 remains useful for formats that expand more: deflate reaches 1,032.
---
Measured performance
Release, 256 KiB block. The checksums: 400 rounds. The algorithms: 200 rounds.
Checksums
| Measurement | Windows x64 | Linux x64 (WSL) | Spec target |
|---|---|---|---|
| CRC32 (IEEE), slicing | 1.57 GB/s | 2.38 GB/s | 20 GB/s (see above) |
| CRC32C, table | 1.72 GB/s | 2.22 GB/s | n/a |
| CRC32C, instruction | 24.26 GB/s | 23.0 GB/s | 20 GB/s, met |
| Adler-32 | 3.15 GB/s | 2.00 GB/s | n/a |
| XXH64 | 14.66 GB/s | 10.87 GB/s | n/a |
The 20 GB/s target was met, and the path to it is worth telling.
Before, it was 8.9 GB/s, and the cause had been diagnosed: the CRC32 instruction has a latency of three cycles and accepts one per cycle. A loop with one dependency chain waits for the previous iteration and uses a third of the capacity. The known fix is to split the buffer into three independent chains. What was missing was joining them at the end.
No pclmulqdq, by choice
The usual recipe joins the chains with carry-less multiplication. That requires another processor extension and another runtime detection. It would be one more branch that only one of the machines on this bench would exercise, and a platform branch that is never compiled is a draft.
The CRC is linear over GF(2), and that gives another path: advancing a CRC by N zero bytes is a 32x32 matrix over GF(2), and the matrix for N bytes is the one-byte matrix raised to the power N. Since the block sizes are fixed (8,192 and 256), the matrices are produced at compile time: no table at initialization, no allocation, no new extension.
What each static_assert really pins down
I first wrote that the composition assertion (advancing 256 bytes versus advancing 128 twice) pinned down "the polynomial, the bit order and the exponent". A sweep showed that it does not.
| planted defect | what killed it |
|---|---|
| the exponent walk | the build |
| the polynomial swapped for the IEEE one | the test suite, through the differential against the table |
| eight bits per byte turning into seven | the test suite, same as above |
The reason is simple in hindsight: **the same P appears on both sides of the equality and cancels out**. The composition proves that the exponentiation is consistent with itself. A check that compares the construction with itself proves consistency, not correctness.
What pins down the parameters is a constant from outside: 0xF26B8303, entry 1 of the Castagnoli table, which is a published number and is not derived from anything in here. With it in place, swapping the polynomial stops the build. This was verified by planting the defect.
And the test suite passed 42/42 on code that nobody exercised
This is the most valuable finding. Once the new core was written, the whole test suite passed, including the differential against the table, which is precisely the test that should have caught it.
It measured lengths up to 300 bytes. The new path cuts into blocks of 8,192 and of 256, in three chains: below 768 bytes neither of the two runs, and below 24,576 the long chain does not run. The corpus had been sized for the old code.
The lengths now walk across the boundaries (just below, at, and just above each block multiple), and the test was confirmed by planting a defect in the joining of the chains: it fails at two points.
LZ4 block
| Corpus | Ratio | Compress (Win / Linux) | Decompress (Win / Linux) |
|---|---|---|---|
| text | 1.73x | 365 / 380 MB/s | 3.24 / 2.48 GB/s |
| sparse | 252x | 14,305 / 14,096 MB/s | 40.3 / 43.4 GB/s |
| incompressible | 1.00x | 603 / 700 MB/s | 33.0 / 30.2 GB/s |
Spec targets: decompression 3 GB/s, fast compression 600 MB/s.
- Decompression: met on Windows on all corpora. On Linux, text stays at 2.48 GB/s, 17% below the target, with the same code. The difference comes from the compiler, not from the algorithm.
- Compression: not met on text (365 to 380 MB/s against 600, and 297 before the loop described below). See below: the target is not reachable on this corpus by any implementation, and this was measured.
The 600 MB/s target is not reachable on this corpus, and the reference is what shows it
Before optimizing, there was a question to answer by measurement: **how fast is liblz4 here?** The probe now measures both, on the same corpus and on the same machine, in the same loop:
| compress | ratio | |
|---|---|---|
reference (LZ4_compress_default) | 391.2 MB/s | 1.71x |
| ours, before | 296.5 MB/s | 1.73x |
| spec target | 600 MB/s | n/a |
The reference does not reach 600 either. Chasing that number on this text would be chasing something that liblz4 itself does not do. The target, if it is realistic, refers to another corpus (sparse already gives 13 GB/s) or to another machine.
And our ratio was already better: 1.73x against 1.71x. That refuted the diagnosis that was written here, that "the table without a chain loses matches". The finder finds as much as the reference one. It spent more time per position.
The 32% gap was a single loop, and it closed
In text the average match is short, so the eight-byte comparison almost always fails on the first iteration. The byte-by-byte loop that came after it ran up to seven times per match.
The exclusive or of two words tells where they diverge: the first differing byte is at the first differing bit, and counting zeros gives the index in one operation. The endianness choice is made at compile time (std::endian::native), not at run time, so it costs no branch at all.
| before | after | |
|---|---|---|
| ours, Linux | 296.5 MB/s | 370 to 409 MB/s |
| ours, Windows | 296 MB/s | 356 to 373 MB/s |
| reference, same machine | 391 MB/s | 327 to 406 MB/s |
In three side-by-side rounds we won two. The gap closed, and what remains is measurement noise. The variation between rounds of the reference itself is larger than any effect an additional optimization would have. In other words, this instrument cannot measure the next step. Stopping here is what the measurement supports.
The ratio stayed at 1.73x: the gain is purely cost per position, without losing a single match.
The big-endian branch is not exercised. Both machines on this bench are little-endian. It stays written because the alternative was to assume the byte order silently.
Why decompression speed depends on the corpus
The benchmark prints, for each corpus, how many bytes each sequence produces, and that line is what explains the number.
LZ4 decompression costs per sequence, not per byte: one token, one offset and two copies, whether the match is five bytes or five hundred. A corpus that produces a match every six bytes pays all of that every six bytes of output, and no LZ4 decompressor reaches 3 GB/s under those conditions. The arithmetic does not work out for anyone.
This was measured, and it cost an entire corpus: the first version of the "text" corpus had thirty-four words. With such a short vocabulary, every four-byte group had already appeared before, the compressor found a match at every position, and the stream came out with an average literal of zero and 5.7 bytes of output per sequence. The number that came out of it (1.3 GB/s) measured the corpus, not the code. The current corpus has two thousand words and produces 11.7 bytes per sequence.
There was also a corpus labeled "random" that compressed 202 times: it was i * 41 + 17 truncated to eight bits, with a period of 256 bytes. The label lied, and the number with it.
Deflate
Five consecutive rounds, observed range:
| Corpus | Ratio | Compress (Linux) | Decompress (Linux) |
|---|---|---|---|
| text | 2.26x | 33 to 36 MB/s | 0.20 to 0.22 GB/s |
| sparse | 971x | 282 to 304 MB/s | 5.0 to 5.8 GB/s |
| incompressible | 1.00x | 134 to 152 MB/s | 28 to 31 GB/s |
The spec sets no numeric target for deflate: it is the algorithm used when size matters more than time.
Dynamic Huffman cost almost half of the compression speed and gave back much more ratio. On text: 1.77x at 58 MB/s became 2.26x at ~35 MB/s. On sparse data: 158x became 971x. zlib at the default level does 30 to 70 MB/s. We are in the same range.
On incompressible data, compression became faster (43 -> ~145 MB/s), and the reason is the same one that brought the ratio: the choice of block type is now made by measuring the cost of all three before writing. Before, the compressor wrote fixed Huffman and, if it had come out larger than stored, redid everything.
The first round after a build does not count. It comes out 25 to 30% below the following ones. This was measured while investigating a drop that seemed to have a cause and did not. Taking that number as true would have attributed to a code change what was a cold cache. Any regression gate on these numbers must discard the first round.
Incompressible data decompresses at 30 GB/s because it becomes a stored block, and a stored block is a block copy. Getting there cost a measurement: the first version passed those bytes one by one through the bit reader, and did 0.63 GB/s. It was the only corpus that the lookup table did not help, because there is no Huffman there at all.
The ratio against zlib, corpus by corpus
With 200 KiB of each kind, measured by the compression_ratio bench, and the zlib column measured on exactly the same bytes that this bench writes to disk:
| Corpus (200 KiB) | Fast | Default | Better | Best | zlib -6 | zlib -9 |
|---|---|---|---|---|---|---|
| repeated | 103x | 948x | 948x | 948x | 943x | 943x |
| incompressible | 1.00x | 1.00x | 1.00x | 1.00x | 1.00x | 1.00x |
| 4-letter alphabet | 1.53x | 3.02x | 3.32x | 3.40x | 3.40x | 3.43x |
| period 3 | 103x | 939x | 939x | 939x | 939x | 939x |
| mixed with noise | 5.70x | 8.19x | 10.42x | 10.50x | 10.58x | 10.69x |
| 64 KiB window | 102x | 858x | 858x | 862x | 862x | 862x |
| half zeros | 72.0x | 163x | 167x | 167x | 164x | 164x |
**With Best, we are between 98% and 100% of zlib on all seven, and ahead of it on two.** On two others (period 3 and the 64 KiB window) the ratio is identical down to the last byte.
Two labels were swapped, and the right number was on the wrong row
The previous table in this README said "64 KiB window: 8.28x" and "mixed with noise: 858x". Both numbers were right. The labels were what was swapped, because the name array of the reference probe has seven slots and the corpus generator skips kind 4: case 5 is the window, and 4 falls into default, which is the mixed one.
Nothing measured wrong, and nothing could fail: a name array has no way to give itself away. What gave it away was 858x attributed to noisy data, which is impossible, and is exactly what a sea of zeros gives. It is fixed in the probe and here.
The candidate chain, and the defect it had
Until this point the finder kept one entry per table slot and no chain. That finds the most recent candidate, not the longest one. It was the missing difference against zlib, on the two corpora where several candidates compete for the same slot:
| before | after (Best) | zlib -6 | |
|---|---|---|---|
| 4-letter alphabet | 3.02x (89% of zlib) | 3.40x (100%) | 3.40x |
| mixed with noise | 8.19x (77%) | 10.50x (99%) | 10.58x |
The chain is an array of 32,768 16-bit entries: for each position in the window, the distance back to the previous position with the same hash. It is the zlib design, with the same size.
The distance is stored, not the position, and that solves two things at once. Sixteen bits are enough, because the distance never exceeds 32,768. And zero is free to mean "there is no previous one", without needing another sentinel.
The defect broke nothing, and that is why it almost got through
The first version stored the distance and read a position: Insert wrote the backward distance, and the walk reconstructed the candidate with ( uCandidate - uGuardado ) & 0xFFFF, as if the slot held a truncated position. The two halves of the chain disagreed.
And the whole test suite passed green: all 74, in Debug and in Release. It had to pass. The finder checks the bytes before accepting any candidate, so an absurd candidate simply does not match. What is lost in a defective match finder is ratio, not correctness.
What gave it away was the table above. Better and Best came out identical to each other (32 and 128 attempts giving the same number means the walk dies on the first iteration) and **a little worse than Default**, which is what happens when the chain only spends time. No test could catch this. Only the measurement.
The 64 KiB of stack, and who pays for it
The chain is 64 KiB on the stack, in addition to the 32 KiB of the hash table. zlib reserves the same array on the heap. Here it stays on the stack because the module does not allocate, and the allocation guard keeps enforcing that.
Only the levels that ask for it pay for it, and that forced the function to be split in two: DeflateBlock is a thin entry point that declares the array and calls DeflateBlockWith. Declaring the array inside the large function would cost the 64 KiB to everyone, because the frame is reserved on entry to the function and not in the branch where the array is used. An if around the declaration does not change that, and C++ has no variable-length arrays (the first attempt).
Declared: with Better and Best, compressing a block needs ~96 KiB of stack. On a thread with a small stack, use Default or below, which is where the frame remains what it always was.
What the chain costs in time, and it is the knob the spec asks for
| Corpus | Default | Better | Best |
|---|---|---|---|
| 4-letter alphabet | 7.0 ms | 18.4 ms | 48.3 ms |
| mixed with noise | 2.7 ms | 4.2 ms | 7.6 ms |
| incompressible | 1.9 ms | 6.7 ms | 6.8 ms |
| repeated | 0.8 ms | 1.2 ms | 1.2 ms |
**Best costs 7x Default on the small alphabet to gain 13% in ratio**, and that is why it is not the default. The number of attempts (32 with Better, 128 with Best) is the same knob that zlib has, and serves the same purpose: walking the whole chain on a very repetitive input costs endless time to gain fractions of a percent.
Incompressible data is where the chain only costs: 1.9 ms to 6.7 ms, and the ratio stays at 1.00x in both. There is no match to find there, and each position pays 128 comparisons to find that out. It is recorded here: Default is the right level for data that is already compressed.
How the dynamic code is built
Dynamic Huffman needs the frequencies before writing the first bit, and they only exist after walking the entire input. Common implementations keep the symbols in a buffer between the two phases.
Here there is no buffer: the same loop runs twice, counting on the first pass and writing on the second. It costs twice the search time and keeps the promise that the module does not allocate. The only working memory is still the hash table on the stack. The two passes produce the same symbols because they start from the same state. If they ever stop doing so, the stream comes out inconsistent with its own header, and the comparison against zlib catches it on the first round.
The 15-bit limit is mandatory, because the RFC only represents codes up to that length. An unlimited Huffman code goes past it when the frequencies are very uneven, which happens on real data. The approach used here is the simplest one that works: build the tree and, if it went past the limit, divide all frequencies by two (never reaching zero) and rebuild. It is not the optimal code in these rare cases (the optimal length-limited code is package-merge, much more complicated), and the difference is a fraction of a percent. It is recorded here.
The inflate lookup table
Huffman decoding started bit by bit (the form of the reference puff), and that order was deliberate: the comparison against zlib first, the measurement after. The measurement came, and with it the 512-entry shortcut table: nine bits, one kilobyte, on the stack.
Measured gain: text 0.11 -> 0.17 GB/s, sparse 3.80 -> 5.02 GB/s. The bit-by-bit loop is still there and is still the definition: the table is a shortcut for the common case, and long codes, end of input and invalid codes go through the loop.
The hash table: a measured trade-off
The compressor uses 4,096 entries (16 KiB on the stack), which is the same choice as the reference LZ4. Increasing it improves the ratio and worsens the speed, and the reason is the cache:
| Entries | Size | Ratio on text | Compress incompressible |
|---|---|---|---|
| 4,096 (current) | 16 KiB | 1.73x | 700 MB/s |
| 8,192 | 32 KiB | 2.14x | 549 MB/s |
| 16,384 | 64 KiB | 2.28x | 438 MB/s |
| 32,768 | 128 KiB | 2.34x | 283 MB/s |
At 16 KiB the table fits in L1 and each lookup costs four cycles. At 128 KiB it does not fit, and on incompressible data (where every position looks up and none hits) each lookup becomes a trip to L2. It is not the table clearing: that costs 1% of the time, and this was also measured before accusing the wrong suspect.
cmake -S . -B build/bench -G Ninja -DCMAKE_BUILD_TYPE=Release -DETHEREAL_BUILD_BENCH=ON
cmake --build build/bench --target ethereal_bench_compression
./build/bench/bin/ethereal_bench_compression---
The preset dictionary
A small message does not compress: the first bytes have no past to point to, and the format's own header already costs more than what is gained. A dictionary is a borrowed past: bytes that both sides already have, and that a match reaches as if they had come before.
How much it delivers, measured
Messages in the format of an event record, with a dictionary of their vocabulary:
| Message | without dictionary | with dictionary | gain |
|---|---|---|---|
| 64 bytes | 71 | 39 | 1.82x |
| 128 bytes | 103 | 60 | 1.72x |
| 256 bytes | 155 | 87 | 1.78x |
| 1,024 bytes | 410 | 293 | 1.40x |
Where the dictionary lives, and why
The window of this module was never a circular buffer: it was always the caller's own buffer. That is what keeps the promise of not allocating, and that is what decides the shape of the interface:
| Where the dictionary goes | |
|---|---|
| when compressing | immediately before the data, in the same input buffer |
| when decompressing | at the start of the output buffer |
Code that has a fixed dictionary and a stream of messages keeps one buffer with the dictionary at the start and copies each message right after it. The copy is the caller's, not ours, and nobody allocates behind the scenes.
Only the last 32 KiB of the dictionary are reachable (64 KiB in LZ4), because that is the format's window. A larger dictionary is not an error: the excess is simply not used, and the hash table never even receives it.
The prepared dictionary, and the instrument that almost said it was useless
The spec is explicit: "persist and reload a prepared dictionary state so the priming cost is paid once across many small payloads. This is the whole point for TorreSync chunking, do not skip it."
Compressing with a dictionary costs one hash per byte of the dictionary, on every call. PrepareDictionary pays that once and keeps the table in a 32 KiB POD that can be written to disk and reloaded. DeflateWithPreparedDictionary replaces the whole pass with a copy.
Measured, 32 KiB dictionary and 64-byte message:
| per message | |
|---|---|
| building the table every time | 300.29 us |
| reusing the prepared table | 35.98 us, 8.3x |
The first measurement gave 1.0x, and the lazy conclusion would have been "it is useless". The corpus I used had a 216-byte dictionary: both paths pay the same 32 KiB clearing of the table, and preparing 216 positions costs nothing next to that. The gain only appears when insertion dominates, which is exactly the case the spec describes and that corpus did not reach. Again an instrument that did not reach the path.
Using it with the wrong dictionary corrupts nothing, and that is a property, not luck
The finder compares the bytes before accepting any match, and checks the offset against the window before any read. A table entry that points to bytes that changed simply does not match.
So the price of reusing it wrongly is ratio, not correctness. It is the exact opposite of the DICTID, where the wrong dictionary produces plausible and different output. That is why the dictionary content is not checked on every call: checking it would cost the pass that the function exists to avoid. The size, which is cheap to check and is the common mistake, is checked.
And the shortcut declares that it was taken
The two entry points produce a byte-for-byte identical stream. That equality is the entire contract of the shortcut, because a shortcut that gave different output would be another compressor. But comparing identical outputs does not say which path ran: an implementation that ignored the prepared state and built the table from scratch would pass everything.
It is the same pattern as the inflate shortcut, and the same answer: CompressedWithPreparedTable() counts the passes, and the test suite requires two per compression (the compressor counts on one pass and emits on the other).
Mutation on the prepared dictionary: the survivor that required three diagnoses
Eleven planted defects, nine killed. One of the two survivors is equivalent (see below). The other, deleting the table clearing in PrepareDictionary, made me get the diagnosis wrong twice before the measurement pointed to the right property.
First mistake: the corpus was blind. The test message was Dic[(i*7 + 11000) % N], a sampling with stride 7. The finder looks for three-byte sequences, and a strided sampling has no sequences. Zero matches, and with zero matches the table can be in any state and the output is the same. Three mutants survived for this reason at the same time, which was already the signal.
It is the same defect this module had already had with the preset dictionary (111,245 comparisons against zlib with zero matches), repeated in the prepared dictionary test, after I had written the rule in the README. The fix was not only the corpus. The rule became an assertion, requiring the dictionary to cut the message to less than half. Measured: 301 bytes without a dictionary, 47 with it.
Second mistake: "the reuse case is missing". With the corpus fixed, two of the three died and this one survived. I diagnosed that preparing twice on the same object was missing: aOpaque has a member initializer, so a new object already comes zeroed and the clearing would only matter on the second preparation. I wrote the case. It survived all the same.
What the measurement showed. A stale entry behaves like an empty slot: the finder compares the bytes before accepting, and bytes from another dictionary do not match. For the produced stream, the clearing really is redundant. The mutant was right and I was wrong.
Where it is not redundant is in what the spec asks for: "persist and reload a prepared dictionary state". Without clearing, the same dictionary prepared in two objects gives different bytes on disk, and that breaks any cache by hash, version comparison or reproducible write.
The right assertion was not about the output. It was a memcmp between the two objects. With it, the mutant dies.
And the other survivor: the window guard saves time and does not change the output
Deleting the trimming to the last 32 KiB survives any output test, and the note that was in the code explained badly why: it said that entries from outside the window "would only serve to evict the useful ones".
Measured, that is false. The table has one entry per slot and insertion walks in increasing order, so later positions overwrite earlier ones. With 8,192 slots and tens of thousands of insertions afterwards, almost nothing of the excess survives. And an entry that happens to survive is rejected by the distance check before any read.
The real cost is time: one hash per byte that cannot yield any match. The guard stays. The justification was corrected.
The DICTID, and why it matters more than the average
Decompressing with the wrong dictionary does not give an error: it gives plausible and different output. A mismatch here would not show up as a failure. It would show up as silently swapped data.
That is why the zlib envelope carries the DICTID, which is the Adler32 of the dictionary, and that is why it is checked: a stream that asks for a different dictionary returns eInvalidArgument. Raw deflate has no such field. There, the responsibility lies with whoever chose the raw format.
---
The entry point, and an enum correction
The EAlgorithm enum existed from the start and led nowhere: using the module required knowing the function name for each format. Someone who stores "compress with gzip" in a configuration does not want to write a switch over seven functions, and each such switch is a place where the eighth format will be forgotten.
Compress, Decompress and CompressBound take the format as a value. Nothing there is faster or slower than calling the function directly: it is dispatch, not a second implementation.
A correction in the enum itself: EAlgorithm::Store said "copies the bytes with a minimal header". There is no header. Whoever stores without compressing already knows the size, and inventing two decorative bytes would only make the format stop being a copy. The minimal header is none, and the enum was corrected.
What declares itself, and what does not
DetectAlgorithm guesses the format from the start of the stream. Only three declare themselves, and that comes from their design:
| Format | How it declares itself |
|---|---|
| gzip | 1F 8B plus method eight |
| zlib | method eight, window up to 32 KiB, and the check that closes on 31 |
| LZ4 frame | the magic number 04 22 4D 18 |
Raw deflate, the LZ4 block and RLE start with data, and any data is a valid start. For them the answer is false, not a guess.
A raw stream can look like zlib by chance: the header is two bytes with five check bits, so an arbitrary sequence passes it once in a thousand. That is not a defect of the function, it is what the format allows. That is why it guesses, and the name says so.
---
The LZ4 frame
The block format carries nothing besides the data: whoever reads it needs to know, from outside, the original size and whether the content arrived whole. The frame is the file format (magic number, descriptor, bounded blocks, end mark and checksums), and it is what the lz4 program writes.
Linked blocks are the reference default, not a rare case
With linked blocks, a match can point into the previous block. LZ4F_compressFrame produces exactly that when nobody says otherwise. So a reader that only understands independent blocks fails on the most common case there is.
Here both modes work, at no cost: the window was never a circular buffer, it was always the caller's own buffer. It was enough to say how much of it is already written, and the block decompressor gained Lz4DecompressWithPrefix, of which the old one became a special case. The offset check stays the same and still applies.
XXH32, which is not a truncated XXH64
The frame uses XXH32 in the header, in each block and over the entire content. They are different functions, with different constants, a different threshold (sixteen bytes, not thirty-two) and a different final mix. Confusing the two produces a number that looks plausible and matches nobody's.
It was verified from birth: **8,804 comparisons against the system libxxhash**, at every size up to 2,200 bytes and four seeds, zero divergence on the first run.
What the frame checks
Magic number, version, reserved bits of FLG and BD, the block size identifier against the format's table, the header checksum, the size of each block against what remains of the input and against the declared maximum, how much each block produces against that same maximum, the per-block checksum when present, the end mark, the announced content size and the content checksum.
A block that does not compress goes raw. The format has a bit for this, and using it is what keeps the frame from growing with incompressible content. Without it, each block would pay the LZ4 overhead and the file would end up larger than the original.
---
Streaming
The one-shot entry points require the entire input in memory and output space for the entire result. That is enough for a configuration file and not enough for anything that comes from the network or from a large disk. CInflateStream consumes chunks and returns chunks, and the state survives between calls.
The acceptance criterion comes from the spec itself, and is written there like this: "chunked at sizes 1, 3, 17, 4096 produces byte-identical output to one-shot". That is not a round trip. It is the comparison of two of our own paths, which is precisely the kind of divergence that the comparison against zlib does not catch, because both divergent sides would be legitimate in its eyes.
And nothing allocates, not even in Init
The spec allows allocating once in Init. It was not needed: the 32 KiB window, the input staging area and the two Huffman tables are members, and whoever creates the object decides where it lives. The object is about 40 KiB and fits on the stack, in a static, or in a vector. The test suite requires less than 48 KiB, so that this budget does not grow without someone noticing.
The step is atomic, and that is what makes chunking work
The bit reader goes onto the stack at the start of each step and only goes back into the object if the whole step succeeds. A step that stopped for lack of input leaves no trace: the next call redoes the step from scratch. Without this, a cut in the middle of a Huffman symbol would consume bits that nobody would read again.
That is why reading a header in chunks costs nothing. It was necessary: the reader's accumulator has 64 bits, and refilling stops after passing 56. So Has(80) returns false forever, and a loop that answers that false with "I need more input" never exits. The gzip header asked for its ten bytes at once and the test hung. The limit was written in the core as MAX_REQUEST = 56, and the header now goes in byte by byte.
The window is now a ring, and the offset is checked against something else
In the one-shot entry point the window is the caller's own buffer: the entire past is there, and the offset is checked against what has already been written. In streaming the window is a 32 KiB ring buffer, and the check is now against what the window still holds: the smaller of the total produced and the 32 KiB. A stream that points to before that asks for a byte that the format no longer guarantees to exist.
This guard has an aggravating factor that the sanitizer does not see: the window is a member and is fully allocated, so obeying an offset that is too large at the start of the stream is not an out-of-bounds read. It is a read of memory that nobody filled. ASan stays quiet. Only a forged case sees it, and that case exists because of this.
A step always starts with the window empty
Update drains before each step, and when the output fills up it breaks the loop instead of taking the step. So m_uPending is zero at the start of any step, and the whole window is free: a 258-byte match fits by construction.
There were three scattered guards that said this in three ways ("does one byte fit?", "do 258 fit?", "has everything gone out?"). The mutation sweep killed none of the three, and reading the code showed why: none of them is reachable. The three unreachable copies of the same fact became one statement of it, at the top of Step.
And the fact is measured, not argued. PeakPendingAtStep() keeps the largest value that line has ever seen, and the test suite requires zero. If someone changes the Update loop, the number stops being zero and the test says that those guards have stopped being just a backstop.
A measurement that must give zero cannot be told apart from a broken measurement that always gives zero. That is why there is a second reading, PeakPending(), taken by the same function at another point, where the pending amounts are large. The test suite requires it to exceed 258. Breaking the mechanism brings down both, and the second one reports it.
The compressing side of streaming
CDeflateStream accumulates input in a 32 KiB block and, when it fills up, calls **the same DeflateBlock that the one-shot entry point calls**. There is no separate emitter here. The core moved to deflate_core.hpp and became shared, as had already happened with inflate.
The output is a single stream, not several glued together
Two things prevent emitting independent blocks and gluing the result together.
A deflate stream has one end bit, on the last block. Gluing two complete streams does not give a valid stream: the reader stops at the first end bit and the rest becomes garbage. So DeflateBlock now takes bLast, and WriteStored had to distinguish two different "lasts": the last 65,535-byte piece inside a stored block is not necessarily the last block of the stream.
And the blocks are not byte-aligned. A new bit writer for each block would fill the rest of the current byte with zeros, and the decompressor would read those zeros as the start of the next block. That is why the writer belongs to the object and not to the block: uAcc and iN cross the boundary. It costs two fields and not a single byte. That is why the empty stored block trick (five bytes per block) that compressors usually use on flush was not used.
What it costs
History and new data live side by side in a single region, with an index saying where the history ends. It is the same shape that the preset dictionary already used. After each block, the new data becomes history.
The hash table is not kept between blocks: WalkLz77 reinserts the last 32 KiB of history at the start of each block. With 32 KiB blocks this doubles the hashing work. It is the price of not carrying the table in the object, and the block size is where that trade-off is tuned.
The object takes about 100 KiB: twice the block, plus the output stage. It is too large for the stack of a small thread, and the header says so: whoever creates it decides where it lives. The test suite requires less than 128 KiB so that the number does not grow without someone noticing.
The acceptance criterion is different, and confusing them would mean measuring the wrong thing
In the decompressor the criterion is output identical to that of the one-shot entry point. Here it cannot be: cutting the input into chunks changes the division into blocks, and different blocks give different bytes, all legitimate.
What is required is that the produced stream turns back into the original. And the round trip that matters is not through our decompressor, because two of our own paths can be wrong together and agree. It is through the system zlib, in the reference probe, which has never seen this code.
And the oracle declares its own reach. The probe prints how many chained blocks zlib actually read in a single stream. Today, three. Without that number, a corpus that fit in one block would make everything pass without the "not the last" bit being written as zero even once, and the streaming path would be measured as the one-shot entry point with extra steps. An oracle passing without reaching the path has already happened three times in this module.
Gzip with multiple members, on both paths
cat a.gz b.gz > c.gz produces a legitimate gzip file, and pigz produces that naturally. Reading only the first member and stopping loses data silently, with no error for the caller to see, which is the worst way to fail. Both entry points read all members.
In streaming this cost an entire phase, for a reason the one-shot entry point does not have: when closing a member, the object does not know whether another one is coming. The two bytes of the mark may not have arrived yet, and "has not arrived yet" and "is not coming" are indistinguishable from inside. What settles that doubt is Finish: it is the statement that the input has ended.
And the offset reach is now per member, not per stream. The ring window still holds the bytes of the previous member, but the deflate of a new member starts with no past. Checking against the stream total would let a member point into the previous one, which the format does not allow and which no other decompressor would accept. It is a security detail, not a tidiness one.
The output ceiling applies to the total. Otherwise, a thousand one-megabyte members would pass through a one-megabyte ceiling, which is exactly the bomb the ceiling exists to stop.
The comparison that counts uses zlib members, not a concatenation of ours. Reading what we wrote ourselves proves no interoperability at all. The probe glues together three members produced by zlib at different levels and requires all three back.
The LZ4 frame in streaming
CLz4FrameStream reads an LZ4 frame in chunks. It is harder than deflate for a format reason: deflate is decoded bit by bit and an LZ4 block is not. It is read in one go, from the first literal to the last match. The compressed block has to be entirely in hand before starting.
The 64 KiB per block limit is declared, and the number for each side is here
The format lets the frame choose between 64 KiB, 256 KiB, 1 MiB and 4 MiB blocks. A streaming reader would have to carry the largest of them: four megabytes in every object, even to read a 64 KiB frame.
The opposite was preferred: the object fits in a little over 190 KiB and rejects a frame that declares a larger block, with eOutOfMemory. That error is the truth of the case (the format is known, it is the memory that is not there), and saying eUnsupportedAlgorithm would send the integrator looking for the problem in the wrong place.
| who writes | block size | goes through streaming? |
|---|---|---|
our Lz4FrameCompress | 64 KiB | yes |
the reference LZ4F_compressFrame | 64 KiB | yes |
the lz4 command-line utility | 4 MiB | no, only through the one-shot entry point |
The one-shot entry point reads all four sizes, because there the space belongs to the caller. **A file coming from the lz4 utility does not go through streaming**, and that is stated in the header, here, and in the error itself.
The prefix is what makes the linked block work
Linked blocks are the reference default, and in one of them the match points into the previous block. In the one-shot entry point that comes for free: the caller's buffer has everything that has already gone out. Here the output goes out and disappears, so the last 64 KiB decoded stay side by side with the current block, contiguous, which is the shape that Lz4DecompressWithPrefix wants.
And the pair of prefix readings (the smallest must be zero, the largest must exceed zero) comes from the same annotation, following the lesson the deflate compressor taught: a single-reading instrument accepts being replaced by the constant it expects.
The content checksum forced a chunked XXH32
The frame stores the XXH32 of the entire content at the end, and a streaming reader never has the entire content. Without a chunked form, the only way out would be to not check the checksum, throwing away a defense for convenience.
XxHash32Begin/Update/End exists for this reason. The state is POD, becomes a member and does not allocate. The subtlety is at the end: below sixteen bytes XXH32 uses no accumulator at all and starts from a different mix. A chunked state that gets this choice wrong gives a plausible and wrong number. That is why the test suite checks sizes of 0, 1, 15, 16, 17, 31, 32, 33 and 5,000, each with five cuts.
The oracle is reference frames
The test suite reads frames that we wrote, and our compressor always writes in the same way. The probe covers what is missing: every frame that liblz4 builds (linked or independent blocks, with or without per-block checksum, with or without declared size) also goes through the streaming reader, in three-byte chunks, so the block boundary falls in the middle of each call.
A real defect, and the path that led to it
The frame reader had a buffer overflow. A raw block is exactly 64 KiB (incompressible content goes whole), and with a per-block checksum four more bytes come after it. The input buffer was sized only by the block.
The path to the finding is worth more than the fix:
- A mutant survived: deleting the block size guard.
- I diagnosed "a hostile case is missing" and wrote one.
- I also wrote that ASan would catch this kind of defect, and that having removed it from the chain of oracles of that sweep had been a mistake.
- When I gave the probe a configuration that reached the path (per-block checksum with a 64 KiB block), 42 real failures appeared.
- I planted the defect again and ran under ASan to confirm what I had claimed. It said nothing.
Two things remain, and both contradict what I had written:
The probe configurations that had a per-block checksum used 256 KiB and 4 MiB blocks, the sizes this reader rejects for memory reasons. The field existed in the table and the path was never reached. A hostile case was not missing. What was missing was a frame that the reader could read and that had the field.
ASan does not put a fence between members. The extra bytes fall into the next member of the same object, legitimate memory of the same allocation, and there is nothing it can see. It is the same family as the survivor already recorded here: a read one slot past a constant table falls into the neighboring table, in the same read-only block. Against overflow between fields of an object, what works is the external oracle.
ASan went back into the chain, now for the right reason: it catches what leaves the whole allocation, and a shorter chain is not worth the minutes it saves.
The LZ4 frame compressor in streaming
CLz4FrameCompressor writes a frame in chunks. This side is simpler than the other one, for a format reason. The reader needs a window because a linked block points into the previous one, and it does not choose what it reads. This one writes independent blocks (the same choice that the one-shot entry point already made), and an independent block has no past at all. There is no prefix to slide.
The trade-off is ratio for simplicity, and it closes no door: our reader understands both modes, and the one that writes linked blocks is the reference.
No declared size in the header, unlike the one-shot entry point. In streaming the size is not known before the end, and lying about it would be worse than not having it.
The raw block is not an edge case, and it cannot be seen in the output
Incompressible content grows in LZ4. Without the raw block bit, each block would pay that overhead and the frame would end up larger than the original. The branch is common, not rare.
And it cannot be told apart by the output: a frame with a raw block and one without are both valid and both turn back into the original. Only the size changes, and size does not fail a test. That is why the object counts how many blocks went out raw and the test suite requires that number to exceed zero. It is the same pattern as the inflate shortcut and the prepared dictionary.
A defect the test found on the first round
The first version had Finish call Update to write the header, passing nullptr for the output counter. The bytes that Update put into Out vanished (Finish did not count them), and the Drain of the next iteration wrote over them.
The fix was to extract the header into a method that both functions call. A single function has no way to have this problem. Two chained calls, with an optional counter in between, do.
And the oracle is liblz4 reading what we write
The test suite checks the round trip through our reader, and two of our own paths can be wrong together and agree. The probe closes that gap: the frame comes out of our compressor in three-byte chunks and goes into liblz4, which has never seen this code.
RLE in streaming
CRleCompressor and CRleStream. It is the simplest piece of the module (RLE is byte-oriented, with no window, no table, no bit crossing a boundary), and even so it yielded three findings, of which two were not about RLE.
The rule that makes the output identical, and that is deduction, not hope
RLE compression requires looking ahead: the length of a run (up to 128) and the three-byte peek that ends a group of literals. Deciding near the end of what has been gathered means deciding with incomplete information, and it comes out different from what the one-shot entry point would decide there.
The first version patched case by case, and diverged: it closed shorter literal groups next to the boundary of what had been gathered. The round trip did not see it (both outputs turn back into the original), but the test suite requires byte-for-byte equality, and it saw it.
The fix was not to patch. It was to decide only when there is information to decide: **while input can still come, process only until MAX_RUN + MIN_RUN bytes remain.** With that margin every decision fits in what is already in hand: a run stops at 128, and the peek asks for three beyond a group that also stops at 128. The output is identical by deduction, not by trial.
RLE has bombs, real ones
Two bytes of input become one hundred and twenty-eight of output. The expansion ratio matters here more than in any other format in this module, and the test suite requires the ceiling to stop it.
The two findings that were not about RLE
Segfault on Windows, test suite green on Linux, even under ASan. The test function created half a megabyte of stream objects as locals, and the default stack of a thread is 1 MB on Windows against 8 MB on Linux. No sanitizer saw it. The process died.
And the defect indicted the test itself: the header says, written by me, that these objects are too large for a small stack and that whoever creates them decides where they live. And I put them on the stack.
**Implicit padding in SPreparedDictionary.** The assertion that two dictionaries prepared from the same dictionary are byte-for-byte identical (the property the spec asks for when it says "persist and reload") passed by accident: the garbage between the fields only matched as long as the two objects were born next to each other on the stack. Moving something else revealed it.
The defect was in the promise, not in the test: whoever writes to disk writes sizeof bytes, and the padding goes along. The type gained explicit padding (which the conventions already required), plus a static_assert on the total size, which breaks the build if someone reopens a gap.
What it does not do yet
Nothing, in streaming: the five formats that this module compresses have both directions in chunks. What stays declared is the 64 KiB per block limit of the LZ4 frame, above.
---
The C layer
include/ethereal/c/compression/compression.h plus src/c/compression/compression.cpp. Every export returns int (zero is success, negative is an error), and no C++ type crosses over.
The handle is opaque and the memory belongs to the caller
The conventions ask for an opaque handle, and this module promises not to allocate. The two seem to conflict and do not: the handle is a pointer into memory that the caller provided.
size_t uBytes; ETLC_CompressorStorageBytes( algo, level, &uBytes );
void * p = your_memory( uBytes );
ETLC_Compressor h; ETLC_CompressorCreate( p, uBytes, &Params, &h );A library that allocates internally takes away from the integrator the choice of where the object lives. This one does not, and the byte count already existed, because the spec asked for the memory report.
Zero in a ceiling means default, not "no ceiling"
It is the opposite of the usual convention, and it is deliberate. An ETLC_DecompressParams zeroed by memset (which is how every C struct starts) would have both ceilings at zero. If zero meant "off", the caller would have turned off the bomb defense without ever having written anything.
Turning it off requires saying ETLC_COMPRESS_NO_LIMIT. The silent mistake has to be the safe one.
For the same reason, iStructSize == 0 is rejected: a struct that nobody filled in arrives zeroed, and accepting it would be accepting parameters the caller never wrote.
The test is a .c file, and that is the reason it exists
A C header included only from C++ is not proven as C. A stray bool, a missing extern "C", a comment that C89 does not accept: none of that shows up while the includer is a C++ compiler. It is the same pattern as "a build switch that was never turned on".
The compression.cabi target compiles with C_STANDARD 11 and C_EXTENSIONS OFF, and the gate is the build itself.
And it found something on the first round. The first version used aligned_alloc, which is C11, and the target asks for C11. GCC linked it without complaint. The MSVC linker refused, because the Microsoft CRT does not have it (it has _aligned_malloc, which also requires _aligned_free instead of free).
The defect was not only in the test: the API required 16-byte alignment, and the standard way to obtain it does not exist on half of the platforms where this library runs. The header now documents the portable recipe.
---
Design notes
The match copy: where an LZ decompressor wins or loses
An offset of one with a length of one hundred means "repeat the last byte one hundred times". A raw memcpy there gives a wrong result, because it does not promise to read what it has just written. It is the most common mistake of anyone writing an LZ decompressor, and it does not show up with ordinary content: only with short repetition.
But copying byte by byte is always expensive (measured: 0.36 GB/s on text, against a target of 3). So there are three paths, and all of them write exactly the same bytes:
- Distance >= 16 and slack checked: constant-size 16-byte blocks, which the compiler resolves with no call at all.
- Distance >= 8: exact 8-byte blocks, without going past the end of the match.
- Distance < 8: growth by doubling. One period is written byte by byte, and from then on the stretch already written is itself the source and doubles on each iteration. Since the amount already done is always a multiple of the offset, the phase of the pattern is preserved. Since the step never exceeds what already exists, the regions do not overlap. A thousand-byte match with an offset of one comes out in ten copies, not a thousand.
Two loops, and the reason is measured
The safe loop checks ten things to produce twelve bytes. Each one is necessary, because this is where network data comes in, but together they cost more than the copy.
As long as there is ample margin on both sides, none of them can fail. So the fast loop checks the margin once per sequence and the others disappear by construction. As soon as the margin runs out, or a sequence with an extended length appears, the safe loop takes over, handles one sequence checking everything, and hands back control.
The end of the stream, which is where hostile input lives, always goes through the safe loop. The offset check (zero or greater than what has been written) is not removed even from the fast loop: it does not depend on any margin, and it is what prevents reading someone else's memory.
The space after the end of the output may be touched
The constant-size copies only happen after checking that the slack exists inside the caller's buffer. What goes past the logical end becomes scribble. Nothing is written outside, not even with a hostile stream. A caller who provides space of the exact size sees no scribble at all, because then there is no slack and the narrow path takes over. The reference library requires more than this: it asks the caller to size with extra room and writes into that extra room without checking.
The length codec lives in a header, and this is deliberate
Detail::WriteExtendedLength and Detail::ReadExtendedLength are public templates. The reason is that two of their guards are not reachable on a 64-bit machine: making the accumulator overflow would take seventy thousand trillion bytes of 0xFF. On a 32-bit machine seventeen megabytes are enough, which an attacker sends without effort.
This was not deduced: the defect was planted, and it survived the entire test suite. A guard that no test can exercise is unmeasured code. With the accumulator turned into a template, the test instantiates it with sixteen bits and the overflow fits in three hundred bytes, and the measured line is the same one the decompressor executes, without a copy.
About the checksums
There are two IEEE CRC32 implementations in this tree, and that is on purpose. Section 10 of the conventions says to reuse what exists, and section 2 forbids a module from including another module's header to obtain functionality. This module's spec breaks the tie: it lists the checksums as part of Compression. The side effect is good: the one in cryptography/crc.hpp is byte by byte with a 256-entry table, the one here is slicing-by-8, and the test suite uses each one as the oracle of the other.
The CRC inversion stays inside the function. Leaving it to the caller is the classic source of wrong CRCs. Adler-32 starts at 1, as RFC 1950 requires. The tables are created at compile time, because section 6 forbids statics with lazy initialization.
---
How this was verified
In the build matrix round (see Item 6): Windows 41/41, Linux 44/44 in Debug and 45/45 in Release, and 44/44 under ASan and UBSan. Linux registers more tests (the reference probe, for example, only runs on POSIX). The checksum section has 20 checks, compress has 103, inflate has 51, the compression.reference probe has 114,459 comparisons, and the fuzz target, 100 million inputs in the long run.
The ratio bench exists because the probe does not run where the module is written
tests/compression_ratio.cpp, test compression.ratio. It fails nothing and always exits with zero: there is no ratio target to enforce, and a gate on compression ratio would fail because of an improvement on another corpus.
The compression.reference probe is the good one: the judge there is a library that nobody here wrote. It just starts with #error on Windows, because it comes in through dlopen and there is no system library to open. The result was that the ratio table in this README could not be checked on the machine where the module is developed, which is exactly where it matters, because that is where the match finder is changed.
The bench measures our side, level by level, and writes the corpora to disk so that an external reader can measure the other column on the same bytes. The generators are copied from the probe and not reinvented: two generators that diverge give a comparison that looks valid.
And the first generator I wrote diverged. It used a linear congruential generator, and the four-letter alphabet corpus came out at 930x instead of 3x. Next() % 4 takes the two low bits, and in a congruential generator modulo 2^64 those bits have period four. What should have been noise was abcd repeated two hundred thousand times. The number did not look wrong by itself. It only looked wrong next to what the probe had already measured for the same name.
Mutation on the dictionary: 7 planted, 7 killed, and a finding that almost got through
Six died on the first round, all by zlib rejecting the stream: the dictionary bit that does not come out in the header, the DICTID computed over the wrong content, the trailer Adler32 including the dictionary.
The seventh (the stored block that stores the dictionary along with the data) survived, and the reason is the usual one by a new path: the stored path is only chosen when nothing compresses, and a useful dictionary prevents exactly that. It took a case opposite to all the others: incompressible data with a dictionary that does not help.
The finding that only the report caught
The first version of the report said that the dictionary worsened compression by 5%, and the difference was exactly four bytes, the size of the DICTID. That is: zero matches inside the dictionary.
The cause was the corpus generator: it uses a global PRNG, so two calls produce data that have nothing to do with each other. The "dictionary" was noise.
And the 111,245 comparisons against zlib passed like that. Both sides agreed on finding no match at all. An independent oracle is only worth as much as the corpora reach, and this one did not reach the path it should have measured. Without the number on the screen, the dictionary would have gone into the product without ever having been exercised.
The lesson was already written in this README, about the 64 KiB window of LZ4. It showed up again, in another place, and this time what caught it was distrusting a number that did not make sense, not mutation.
Mutation on the entry point: 17 planted, 17 killed
A dispatch switch looks too small to get wrong, and thirteen of the seventeen defects died immediately: swapping gzip for zlib, decompressing the frame as a block, the Store that does not copy, the Zstd that pretends to exist.
The four survivors were all of the same kind: my test cases did not isolate the check that the defect deleted.
| What survived | Why the test did not reach it |
|---|---|
| The zlib bound forgets the six bytes of the envelope | The deflate bound has plenty of slack, and the round trip never comes close to it. Plenty of slack today is not slack tomorrow: the relation between the two bounds became an arithmetic assertion. |
| The frame detection looks at only two of the four magic bytes | No stream in the test started with 04 22 without being a frame. |
| The gzip detection does not look at the method | Same as above: a 1F 8B with a method other than eight was missing. |
| The zlib detection does not look at the method | The case I had already failed the check modulo 31, so deleting the method test did not change the result. It took choosing a pair with a valid window, a check that closes, and method seven: 77 09. |
The pattern is always the same, and it has already shown up in every module of this work: a test case that fails for several reasons at the same time measures none of them.
Mutation on the LZ4 frame: 22 planted, 21 killed, 1 that does not compile
Sixteen died on the first round. Five survived, all for the same reason: no frame the test suite had went through those guards.
Our compressor writes independent 64 KiB blocks, without a per-block checksum and always smaller than the maximum. The reference writes valid frames. Neither of the two produces a block that lies about its own size, so deleting the check for the lie changed nothing anywhere.
The way out was five frames built byte by byte, each designed to reach a guard: one with the wrong per-block checksum, one that announces more than what remains of the input, one larger than the maximum it declared itself, one that produces more than that maximum, and two raw blocks that together exceed the space.
And two of them still survived, because of traps in the instrument
**The first: std::vector allocates more than the size.** The frames were built with push_back, and the vector grows by doubling. A read ten bytes past the declared end fell inside the capacity (legitimate memory), and the sanitizer saw nothing. It is the same trap as the slack buffers, by a path I had not foreseen: this time the slack was not my choice, it was the vector's growth policy. The frames are now copied into an allocation of exact size.
The second was in my harness. The sanitizer step ran the inflate section, and the frame tests are in compress: ASan was measuring something else. With the harness fixed, all five died, and the report shows the heap-buffer-overflow pointing at the line.
Mutation on dynamic Huffman: 18 planted, 17 killed, 1 recorded
Building the dynamic code took 18 planted defects. Eleven died on the first round, all by the same judge: zlib rejected our stream. Inverted bit order, wrong range in the fixed code, HLIT without subtracting 257, the lengths out of the shuffled order, symbol 18 without taking 11 off the count. None of these gets past a real library, and our own round trip would catch none of them.
The survivors gave the usual result. They did not indict the code:
| What survived | What it revealed |
|---|---|
| "never use dynamic" | Only the ratio changes. Fixed Huffman produces legitimate deflate, zlib reads it without complaint, the round trip closes. It called for a test that enforces the ratio: a corpus where fixed comes close to 100x and dynamic goes past 900x, with the limit at 300x between the two. |
| "the two passes start from different states" | The promise that the two passes produce the same symbols was a comment. It became a check (see below). |
| "do not avoid the empty distance alphabet" | Recorded. See below. |
The promise of the two passes became a check
The written header describes what the first pass counted. If the second one produces something else, the stream comes out describing one thing and carrying another, and the worst place for this to show up is in someone else's decompressor, months later.
The first version of the check counted symbols, and that was not enough: planting "the second pass walks differently from the first", the defect survived, because on uniform data the two paths produce the same number of symbols with different lengths and distances.
Now the two passes sign the sequence (one multiplication per symbol), and a divergence returns eInvalidState instead of a corrupted stream. With the defect planted back, that is exactly what comes out.
The coupling that mutation revealed out of the corner of its eye
A mutant forced the dynamic branch at a level that does not compute the header, and the result was uHlit - 257 with uHlit at zero: in an unsigned integer, 31. A header that no decompressor reads.
The branch was never taken there (the dynamic cost stayed at a maximum sentinel), but that was true by accident, and was not written anywhere. The condition now says explicitly that dynamic is only used when it was computed.
The second survivor that stays
When the content has no match at all, the distance alphabet comes out empty. The compressor forces two one-bit codes, which nobody uses, so that it does not come out empty.
Deleting that forcing survived: zlib accepts the empty alphabet, and that is how it was discovered that it does. The forcing stays because the RFC does not clearly bless the empty alphabet and not every decompressor is as permissive as zlib. It costs two bits in the header.
The case is only reachable with short input and no three-byte repetition at all, and that is why the probe gained a corpus designed to produce it: half zeros, half a cycle of two hundred values, whose trigrams do not repeat as long as the corpus is short.
Mutation on Deflate: 40 planted, 38 killed, 1 killed by simplification, 1 recorded
Inflate, deflate and the shared tables took 40 planted defects. Thirty survived the first sweep or died in it. What matters is what the five survivors revealed, because none of them indicted the code:
| What survived | What it revealed |
|---|---|
| Distance larger than the 32 KiB window | Dead code. The largest distance the format represents is symbol 29 with all thirteen extra bits: 24,577 + 8,191 = 32,768, the exact window. The if was superfluous. It became a static_assert on the tables, which breaks the build if someone changes them. |
| Incomplete Huffman code accepted | The test measured nothing. It built an incomplete code and immediately asked for a symbol outside it: with or without the guard, it gave the same eCorruptStream. Only a test that makes the rest of the block perfectly valid measures it. Then the version that checks rejects and the one that does not check returns content. |
| Block without an end symbol | Without the guard, the decoder emits literals until the input runs out: it is amplification, a few bytes turning into a lot of output. The test now looks at which error comes out, not just that there is an error. |
| "Repeat the previous" with no previous | Reads one slot before the start of the array. It called for a dynamic block that starts with symbol 16. |
| Length symbol 286/287 accepted | Indistinguishable on this bench (see below). |
Later, the inflate lookup table took 6 more, and the two that survived were of the kind that no output comparison catches: they only fill the table halfway, the shortcut misses, and the bit-by-bit loop (which is still the definition) returns the right result. Nothing that is compared changed. Only the speed.
Saying "the benchmark catches it" does not solve it, because a benchmark does not fail. So the code now declares the property: Detail::FixedShortcutFilled() says how many of the 512 entries the fixed code fills, and the answer has to be all of them. In the RFC fixed code no code exceeds nine bits, which is the table index. With that, both died.
The survivor that stays, and why
The guard against length symbols 286 and 287 survived everything: the test suite, the comparison against zlib, and the sanitizer. Deleted, what happens is a read one slot past the end of a constant table, which falls inside the neighboring table, in the same read-only block. ASan does not put a fence between constants like that, and the value read leads the stream to be rejected one step later, with the same error code.
No instrument on this bench tells the two apart. The guard stays, because what it prevents (an out-of-table read driven by hostile input) does not stop being real just because it is indistinguishable here: with another memory layout, or another compiler, the read lands somewhere else. Its limit now comes from the size of the table itself, so that it cannot go out of sync. This is written in the code, next to the guard.
Mutation on streaming: 12 planted and killed, 1 equivalent, and the first round was 8 survivors out of 12
This is the sweep that yielded the most, and it did because the first round went badly. The inflate section passed with 60 checks and zero failures. Of the twelve planted defects, eight survived. A test suite that passes and a test suite that measures are different things, and here the distance between them was two thirds.
The survivors split into two families, and each one called for something different.
Five were test gaps. All for the same underlying reason: the existing cases compared our output with our input, so everything that went through them was a legitimate stream, and no guard ever fired.
| planted | why it survived | the case that killed it |
|---|---|---|
| the reach ignores how much has already been produced | no case pointed to before the start | a stream forged bit by bit: literal A, then a match with distance 4 |
| the trailer Adler-32 is not checked | no case corrupted the trailer | flip the last byte of the zlib stream |
| the gzip CRC-32 is not checked | same as above | flip the third-to-last group of four |
| the gzip size is not checked | same as above | flip the last byte, a case separate from the CRC, because they are two promises |
| the output ceiling does not stop the match | all tests ran with the shield off | a tight ceiling, plus a control with the exact ceiling |
The forged case deserves a note. Obeying a distance that is too large at the start of the stream is not an out-of-bounds read: the window is a member and is fully allocated, so what is read is memory that nobody filled. ASan stays quiet. No instrument on this bench sees this defect. Only a hand-built case sees it. And the one-shot entry point rejects the same stream, which proves that it can be forged and is not an artifact of the test.
Three were unreachable guards, and reading the code showed why: Update drains before each step and breaks the loop when the output fills up, so m_uPending is always zero at the start of a step. The three copies of the same fact became one statement of it, and uLivre ceased to exist.
And the instrument had to prove itself. The measurement "the peak of pending bytes when stepping must be zero" cannot be told apart from a broken counter that always returns zero: the instrument would pass its own test without ever having measured anything. That is why there are two readings by the same function: one that must give zero and another, at another point, that must exceed 258. The "blind instrument" mutant dies by the second.
In the second round, twelve of the thirteen died. The only survivor is the top invariant itself: deleted, nothing changes, because it never fires. Equivalent, and recorded here and in the code.
Mutation on the streaming compressor: 14 planted, 12 killed, 2 survivors for different reasons
The twelve killed cover what this compressor has and the one-shot entry point does not: the end bit on the right block (on both paths, Huffman and stored block), the bit accumulator crossing the boundary between blocks in both directions, the history sliding to the right place, the envelope checksum, the gzip size, the final block of an empty stream, the header and the trailer.
Two things are worth saying about how they died.
All of them died in the round trip, and none in zlib. The round trip is strong here (a malformed stream does not turn back into the original), but it is our decompressor judging our compressor. That the probe killed nothing does not mean it is useless. It means that the defect only it would catch has not been planted yet. See the note about the empty distance alphabet, below.
One died by the hang guard, not by a content assertion. Deleting "an empty stage goes back to the start" makes the loop stop making progress. Without the iteration ceiling the test carries, it would have hung, and a test that hangs does not fail, it just stops responding. The ceiling exists because this part of the module has already hung twice.
The two survivors are from different families, and each one called for something different:
| survivor | what it is | the answer |
|---|---|---|
| the history does not cross the block | a real ratio defect: the output remains valid, only larger | the code now declares how much history it used |
| emits with the stage occupied | an unreachable guard: Update drains before each iteration | one statement of the invariant in place of three copies of it |
The second is the same finding as in the decompressor, in the same form: the scattered "out of space" guards were three ways of saying a fact that the loop already guarantees.
And the first one showed the limit of the obvious instrument
The obvious answer to a ratio defect is to check the ratio. Measured with a corpus that repeats with a period of 20,000: inside the window, so the match is representable, and larger than half a block, so part of it falls on the other side of the boundary.
| bytes | against the one-shot entry point | |
|---|---|---|
| one-shot entry point | 4,258 | n/a |
| streaming, as it is | 4,305 | 1.011x |
| streaming, history that does not cross | 5,272 | 1.238x |
| streaming, history present and ignored | 9,161 | 2.152x |
The defect that survived costs 24%. No ratio threshold separates 1.238 from 1.011 without being fragile to level, corpus and compiler, and a fragile threshold fails correct code, which is worse than failing nothing.
So what kills it is MaxHistory(), which looks at the mechanism (did the block get to see the entire window of the previous block?) instead of the effect. The ratio check stayed, in the role it has: a wide ceiling against gross loss, with the one-shot entry point as the reference instead of a number chosen by eye. It accompanies the instrument and does not replace it.
The third row of the table does not even get that far: ignoring the history emits distances that point to before the start of the stream, and the round trip already fails it.
And the instrument was blinded, which refuted a sentence I had written
When creating MaxHistory() I wrote in the header that it could not be blinded ("a dead instrument returns zero, and zero is what fails"). A sweep over the instrument itself showed that the sentence was wrong: the mutant does not return zero, it returns the constant the test suite expects.
if( uAmount > m_uMaxHistory )
m_uMaxHistory = 32768u; /// instead of 'uAmount'The assertion MaxHistory() == 32768 accepts this without blinking. The same pair of readings that had worked for the stage (one that gives zero, another that gives more than zero) did not work here, because there is only one expected value.
The fix was to take two readings of the same argument: the largest history seen, which must reach 32,768, and the smallest, which must be zero, because the first block of a stream has no past. Blinding the argument with a constant breaks one of the two.
And the limit is still written where it is true: mutating both lines inside the function at the same time would still pass. The pair makes the fraud more expensive, but does not make it impossible.
Mutation on LZ4 and RLE: 28 planted defects, 28 killed
Each defect was planted by script, with a backup copy before any write and a baseline check afterwards, and the tree goes back to its original state even if the script dies midway.
On the first sweep, ten of the twenty-four survived, and the survivors were precisely the defenses, which indicts the tests, not the code. Each one was investigated:
| What survived | What it revealed |
|---|---|
| Literals checked against the whole input | The hostile stream in the test asked for 5 literals in 3 bytes, and 5 already exceeds 3. Only an excess of one byte separates the two. |
| The two overflow guards | Unreachable on 64 bits. They became templates so they could be measured. |
| Match exceeding the output space | The "one byte short" test ended in literals, and never measured the match. |
| Length 255 without the terminating zero | None of the six corpora landed on an exact multiple of 255. |
| Match eating the final literals | The round trip does not catch it: our decompressor accepts what our compressor writes. It called for an independent format validator. |
| Distance larger than the 64 KiB window | No corpus went past 64 KiB. It called for a corpus with repetition at 66 thousand bytes. |
| Absolute ceiling on the RLE literal branch | A literal does not expand, so the bomb never went through there. |
Three of them only read outside the buffer and return the same error as the correct code. No return value check reaches them. The way out was the sentinel on the input: the source buffer is larger than the declared piece and the excess holds 0xEE. Whatever reads past the end carries the mark, and the mark shows up in the output.
The tests that decide
- Byte-for-byte round trip on six corpora, for RLE and LZ4.
- Format validator: an independent oracle that requires every block to end in literals and the final sequence to carry the last five bytes, rules that our own reader does not enforce.
- The match copy against the byte-by-byte definition, in 1,608 combinations of distance (1 to
- and length (4 to 70). The oracle is the format definition written in the dumbest way possible, and it was proven against the slow code before judging the fast one.
- Truncate at every position of a valid stream, requiring that no cut breaks or invents output.
- Replace each byte with five hostile values, across the whole stream.
- Decompression bombs for LZ4 and RLE, against the absolute ceiling and against the ratio, with and without the shield.
- Sentinel outside the declared space in every short buffer check.
- Targeted hostile input: zero distance, distance before the start, literals exceeding the remainder by one byte, endless extended length, half a distance.
Against the system reference libraries
All the test suite knew about our LZ4 was that it reread what it wrote itself, and a compressor and a decompressor with the same mistake agree perfectly. The format validator helps, but it was written by whoever wrote the code being judged: it catches what is known to be a rule.
The compression.reference probe opens the system **liblz4, zlib and libxxhash** through dlopen and compares in both directions, because each one measures one half:
| Direction | What it measures |
|---|---|
| ours -> reference | whether what we generate is real LZ4/deflate/zlib/gzip |
| reference -> ours | whether we read the real formats, and not only our own dialect |
79,864 comparisons, zero divergence. Six kinds of corpus (all the same, incompressible, tiny alphabet, short periodic, mixed with noise, and the 64 KiB window one) at ~250 sizes, from 0 to 70,000 bytes, with a fine step on the small sizes and around 65,535. It includes:
- LZ4 in both directions.
- Deflate, zlib and gzip in both directions, at three of our levels.
- The three deflate block types, forced through the zlib strategy: level 0 gives stored,
Z_FIXEDgives fixed Huffman, the default gives dynamic. Without forcing, zlib almost never emits a fixed block, and the branch would go unmeasured inside a probe that would look complete. - 34,332 calls with a damaged stream, cut at every position and with each byte replaced by five hostile values, in a buffer of exact size.
- 16,804 XXH64 checks, which close the long input path.
The libraries come in through dlopen, not through linking: they are a measurement instrument, not a product dependency. Nothing from them is distributed. Without them the probe exits with 77 and ctest marks it Skipped, visibly. A probe that declares itself passed without having measured anything is worse than no probe.
The two defects that only the reference would find
1. The fixed distance code has 32 symbols, not 30. Symbols 30 and 31 exist in the fixed code, with five bits like all the others, and mean nothing. But without them the code is incomplete and building it fails. I discarded the return value with ( void ), the symbol table stayed zeroed, and every distance decoded as 1.
A round trip against ourselves does not see this: there was no compressor of ours to disagree. zlib saw it on the first comparison.
2. The long input path of XXH64 had never been checked. Planting a defect in the final mix makes the reference fail as early as 32 bytes, while the 20 known vectors of the test suite pass cleanly. It was the open item this README declared, and it is now closed.
And it was also put under control. Defects planted on purpose, to see whether it fails. On the first attempt two survived, one of them teaching something worth more than the result:
The defect that loosens the maximum distance got past the original 2,010 comparisons. The reason is not that the reference forgives: none of the five corpora produced a match more than 65,535 away. An independent oracle is only worth as much as the corpora reach. It took a sixth corpus, designed so that the large distance was the only candidate.
The other survivor was my own mutation script with an outdated pattern: the code had changed shape and the replace matched zero times. A script that does not find its target reports "survived" with the same face as one that measured.
The fuzz target
Section 8 of the conventions asks for a fuzz target for everything that reads untrusted input, and this module is the textbook example: every decompressor here exists to receive someone else's bytes.
tests/compression_fuzz.cpp has two halves, and both matter:
**LLVMFuzzerTestOneInput**: the signature that libFuzzer, AFL++ and OSS-Fuzz expect. It is the artifact: anyone with clang links the file with -fsanitize=fuzzer and has a coverage-guided fuzzer, without changing a line. It dispatches the twelve paths that read hostile input (RLE, LZ4 block, LZ4 with prefix, LZ4 frame, raw inflate, zlib, gzip, the two with a dictionary, the entry point with detection, the checksums, and the compressor with a short buffer) and varies the limits and the output space through the fuzzer's own bytes, so that the shields are also measured.
A custom driver, which exists because this bench has no clang. It draws mutations at random over a corpus of valid streams that the library itself produces. Mutating a valid stream reaches places that chance would take an eternity to find: headers that almost close, sizes that almost fit, checksums that are off by one bit.
It is not coverage-guided, and that changes what can be claimed: it does not look for new paths, it only mistreats the ones the corpus already reaches. It is worth less than libFuzzer and much more than nothing. Coverage was attempted with what GCC 13 offers (
-fsanitize-coverage=trace-pc), and the process crashes with any hand-written hook. It was not pursued further, because it is a tooling problem and the target above is already ready for the right tool.
The long run
One hundred million inputs, five distinct seeds, under ASan and UBSan, no crash. The measured rate is ~106 thousand inputs per second.
It is five seeds and not one run five times longer: without coverage guidance, what opens new territory is the sequence of mutations, and each seed gives one.
cmake --preset linux-asan && cmake --build --preset linux-asan
tests/fuzz_long.sh # the five seeds
ETL_FUZZ_RUNS=100000000 tests/fuzz_long.shIn ctest it runs 30 thousand iterations, because nobody runs a slow test suite. The draw is deterministic: the same seed gives the same sequence, so a crash is reproduced with --seed N --runs M (the old names --semente and --voltas are still accepted).
The long run lives in a file, and it took a wrong number for that to become a rule. It used to be a command line, and the seed variable vanished: the outer shell expanded
$SEMbefore the inner one saw it, and the five runs became five copies of the same one, with the iteration count falling back to the default. The report would have said one hundred million inputs where there was one million. In a file, there is no outer shell.
And it was also put under control
A fuzzer that never finds anything proves nothing. The LZ4 literals defect was planted back (the one that checks the request against the whole input instead of what remains of it), and the target caught it, with ASan pointing at the line.
This only works because the delivery to the target goes through an allocation of exact size. std::vector grows by doubling, and a read past the declared end would fall inside the capacity (legitimate memory), leaving the fuzzer blind to exactly the class of defect it exists to catch. This happened twice in this library before it became a rule.
Under sanitizers
The entire test suite (1,949 checks, all sections) runs clean under ASan and UBSan:
cmake --preset linux-asan && cmake --build --preset linux-asan && ctest --preset linux-asanBut an instrument that never fires proves nothing, so the out-of-buffer read was planted back and it was required to catch it. On the first attempt it did not catch it, and the reason is worth more than the result:
The test buffers are oversized on purpose, so the sentinels fit. A read one byte past the end falls inside the slack itself and is perfectly legitimate in the eyes of a sanitizer. It only sees it if the allocation ends where the declared piece ends.
The two hostile loops (truncate at every position, and replace each byte) now copy the stream into an allocation of exact size before each call, which is what a fuzz target does. With that, the control started working: the planted defect makes ASan point at the line and the process exit with code 1. Without it, it exits with 0.
Not verified yet
- No reference probe runs on Windows, and a divergence that only MSVC produced would get through. This has almost happened already: the Windows
winnt.hhas a function calledRotateLeft32, and mine, with the same name, made the call ambiguous. GCC does not have that header and accepted it without complaint. What caught it was the compiler of the other system, which only runs the test suite, not the probes. - The fuzzing is not coverage-guided on this bench, because there is no clang here. The
LLVMFuzzerTestOneInputtarget is ready for libFuzzer and for OSS-Fuzz. What runs here is a mutation driver over a valid corpus. It finds what can be found that way, not what only coverage would find. - The eight items of section 8 are done. What each one measured is in the section Section 8, item by item further below. The summary is worth giving up front: the last four were not ceremony. The build matrix found three real defects, and the allocator and the ratio gate only went in after being proven with a planted defect.
- The reference probes do not run on Windows. They depend on
dlopenand on the system libraries, which are not there on Windows. What Windows measures is the test suite. The comparison against the references belongs to Linux. Since the code is the same, this covers the algorithm, and does not cover a divergence that only MSVC produced. - Streaming does deflate, zlib, gzip, LZ4 frame and RLE, in both directions. What remains (
Storeand raw LZ4 block) answerseUnsupportedAlgorithm, because neither of the two has framing that allows resuming in the middle. - The memory report only covers what exists in streaming. For the rest it returns zero, which is true (there is no object), not an invented number. And the spec asks for two numbers and forgets a third: compression puts 32 KiB of table on the stack for each block, and whoever budgets only by the object size overflows the thread stack. There is a third function for this, outside the spec, and the reason is written next to it.
- The streaming compressor has no ratio target. It splits the input into 32 KiB blocks, and a smaller block compresses less than the one-shot entry point on the same data. The test suite checks that the output turns back into the original and that zlib reads it. There is no number enforcing how much was lost.
- Whatever is left after the last gzip member is ignored, as
gzipitself does. The one-shot entry point does not say how much it consumed, so whoever needs to know that has to look at the input on their own.
---
Section 8, item by item
The first four items were already done: unit tests, differential tests (beyond what was asked, against the system reference libraries), fuzz target and sanitizers. The last four were closed later, and each one of them found something. That is what is written here: what was measured, more than what was built.
Item 7: the allocator that fails the test
tests/compression_alloc_guard.cpp, separate target, test compression.noalloc.
The module promises in every header that it does not allocate. The promise was written in prose, and prose does not fail. Now the global operator new is replaced by one that counts, and the count is armed around each path that claims to be allocation-free: the seven one-shot entry points, the two levels that walk the candidate chain, the five checksums, the chunked XXH32, the prepared dictionary, the five streams in both directions and the C layer. 41 checks, zero allocations.
The two levels with a chain came in here for the same reason as everything else: the chain is 64 KiB that zlib reserves on the heap and that here stay on the stack, and that promise only holds if someone enforces it. The one-shot entry points use the default level, which has no chain at all. The two new paths would pass through here without ever being stepped on.
Three decisions are worth recording:
- It counts, and does not abort. Section 8 asks for an allocator that "fails hard". Aborting inside a
noexceptfunction (which is the case for everything here) kills the process without saying which call it was. By counting, the scoreboard points to the path by name. - The counter proves itself.
ProveCounter()allocates on purpose and requires seeing it. Without this, anoperator newthat the linker ignored would give zero for everything and the scoreboard would be a clean lie. This is exactly the failure mode that has already blinded two instruments in this work. - Each stream checks both directions. A path that does not allocate because it did nothing cannot pass.
And the guard was proven with a planted defect, not by passing: a 32-byte allocation placed in Compress and a 48-byte one in CRleCompressor::Reset failed eight named cases, with the right byte counts in each one.
Item 8: the linked size
tools/module_size.sh <module>.
Adding up the size of the .o files answers a different question. What the customer pays is the difference between linking a program against the library using the module and linking the same program without it. The script forces each global symbol of the module with -u, which makes the linker pull in each member of the archive, and compares with the empty binary, both after strip.
On Linux, in Release:
| marginal cost | |
|---|---|
| codecs only | 102,170 B, 99 KiB |
DataChunk only | 300,574 B, 293 KiB |
| the whole module | 400,534 B, 391 KiB |
The numbers in this table were corrected once. The first version measured the size of the linked file, and the segments of an ELF are page-aligned: the file grows in steps of 4,096 bytes, so any difference smaller than that falls into the slack and disappears. The measurement had a granularity of 4 KiB and did not say so. Today the verdict comes from the sum of the loadable sections, which has byte granularity (see the header of tools/module_size.sh for how the defect showed up).
The compressors cost 99 KiB. DataChunk, which, as the first section of this file says, compresses nothing, costs three times that.
And the attribution I had written here was wrong. I said that the 293 KiB were String, Logging, Assertion and Bundle, from reading the list of undefined symbols. Measuring later, when closing section 8 of the Time module, the number showed up in full: the license guard alone costs 176,482 bytes (172 KiB). datachunk.cpp is the only file in this module that carries the line
/* <Bundle> */ _BundleGuard( __FUNCTION__, __LINE__ ); /* </Bundle> */and it pulls in the entire Bundle implementation. Most of the 293 KiB is that, not the list of modules I read in the symbol table.
Seventeen files in eleven modules carry the guard. encoding carries none, and costs 28 KiB. The time module, which has 4 KB of its own code and carries the guard, costs 179.
Where the guard should go is the owner's decision: it exists because the library is sold under the Bundle license. It is measured so that the decision has a number.
And the script refuses to report if the measurement does not respond. The first probe removed an object from the -u list and required the program to shrink. It did not shrink, and the script failed, correctly, but for the reason I had not seen: **removing an object from the -u list does not remove it from the link** if another object in the module calls it. It was an exclusion that did not exclude. Today's probe measures one object alone and enforces two inequalities: more than the empty binary, less than the module. A meter stuck on a constant number does not satisfy both.
Item 5: the baseline and the gate
tools/measure_gate.sh, and the benchmark gained --sheet (formerly --ficha, still accepted), which emits FICHA<tab>key<tab>value<tab>unit for a machine to read.
The first version of the gate did what the spec asks, literally: one round, comparison with the recorded number, fail below 95%. It failed seven measurements on a tree that had not changed, and on different keys on each run. So the instrument was measured before trusting it: ten consecutive runs, with no code change at all.
| quantity | spread |
|---|---|
| compression ratio (9 keys) | 0.0% |
| throughput (23 keys) | 16% to 55% |
taskset pinning the core changed nothing (55.1% in the worst case). The machine is a Windows desktop with WSL on top.
A 5% gate on a quantity that varies 55% is a lottery, and a gate that fails every day gets turned off the following week, which is worse than having no gate. The way out was to measure the margin and record it, key by key: the margin of each key is the larger of the spec's 5% and the spread observed in the record, with a slack of 1.2x. On a quiet machine the same command tightens by itself down to 5%, without editing a line.
From this comes the division that matters:
- Compression ratio: deterministic, and the nine keys match to the fourth decimal place between g++/Linux-Release and MSVC/Windows-Release. A single baseline, valid on any machine, gate at the spec's 5%. It is **inside
ctest** ascompression.ratiosand in CI. - Throughput: per-machine baseline, checked by hand. CI does not enforce it, and the reason is written in the file itself instead of staying implicit in a green that does not mean what it seems.
Both gates were proven with a planted defect:
HASH_BITSfrom 12 to 7 in LZ4 drops the ratio from 1.7279 to 1.0107 against a floor of 1.6415: **ctestfails. And note that the speed went up** (408 to 710 MB/s). The mutant got faster by compressing worse, and that is why a throughput-only gate would be blind to this.- With the eight-byte tail of the LZ4 matcher turned off,
comprime/LZ4/textofell from 408.8 to 307.1 MB/s against a floor of 355.3: the throughput gate fails.
That second result refuted what I had written in the script header. I had claimed that a 20% loss would go unnoticed on this machine, because ten rounds had measured a 28% spread on that key. The seven rounds of the record measured 13.1%. The margin is a sample estimate, and a small sample underestimates, which makes the key more sensitive and more prone to failing on its own, both things together.
Item 6: the build matrix
This was the one that yielded the most. Seven configurations, all built and run here:
| configuration | result |
|---|---|
| Linux Debug (g++ 13) | 44/44 |
| Linux Release | 45/45 |
| Linux ASan + UBSan | 44/44 |
| Windows x64 Debug (MSVC 19.44) | 41/41 |
| Windows x64 Release | 41/41 |
| Windows x86 Debug | 41/41 |
| Windows x86 Release | 41/41 |
The Release and x86-Debug test presets were missing. They were added to CMakePresets.json, because a configuration without a test preset is a configuration nobody runs.
x86 found three defects that years of x64 had not found:
_mm_crc32_u64does not exist on 32 bits. Thecrc32 r64, r/m64instruction is only encoded in 64-bit mode. FourC3861errors. The same eight bytes now go out in two steps of four, which is no approximation at all, because the CRC of a block is the CRC of its bytes in order._umul128likewise, inrandom.cpp(outside this module, but it blocked the whole matrix). The branch was guarded only by_MSC_VER, as if every MSVC were 64-bit. Replaced by the computation with four 32x32 products with carry.- The defect that matters:
lz4_frame.cppwrote the eight bytes of the content size by shiftingIn.size()(astd::size_t) by 32, 40, 48 and 56 bits. On 32 bits that is undefined behavior, and x86 masks the count by 31: the four high bytes came out repeating the four low ones, and the frame declared an absurd size. Fiveinflatetests, threecompresstests and one allocator test failed.
The third only shows up in Debug. In Release the optimizer folds the constant shift to zero, the frame comes out right and the whole test suite passes. And no sanitizer on x64 reaches this defect, because on 64 bits the shift is legitimate. In other words: **win-x86-debug is the only configuration on this bench that sees this class of error.** Removing it from the matrix erases the measurement.
The new 32-bit branch of CRC32C was confirmed as exercised in the usual way: by swapping the order of the two halves, which made smoke.checksum fail only on x86.
The C++17 half of the matrix is impossible, and that is now measured and not assumed. The public API of this module is made of std::span, which is C++20. Compiling the headers with -std=c++17 gives an error on the first signature. It is not a matter of adjustment: it would be a different interface. The tree had already decided on C++20 (target_compile_features( Ethereal PUBLIC cxx_std_20 )), and what is measured here is the consequence.
The C half of the matrix is done and automated. compression_c_abi.c now compiles and runs twice, in C11 and in C17 (compression.cabi and compression.cabi.c17), with C_EXTENSIONS OFF in both. The same source, on purpose: a target that only included the header would prove that it is parsed, and nothing about the rest. It was also measured that the header passes in C23 with -pedantic, and that it does not pass in C89 (double-slash comments) or in C99. Neither of the two is in the spec, and no promise is made about them.