Skip to content

Bounds-check XtcBasedEncoder and Lossless_bypass against corrupted input - #135

Closed
alexey-milovidov wants to merge 1 commit into
szcompressor:masterfrom
ClickHouse:ch-bounds-check-xtc
Closed

alexey-milovidov wants to merge 1 commit into
szcompressor:masterfrom
ClickHouse:ch-bounds-check-xtc

Conversation

@alexey-milovidov

Copy link
Copy Markdown

Problem

XtcBasedEncoder::decode and Lossless_bypass::decompress read sizes and indices from the compressed data without validating them. On corrupted or adversarial input (e.g. when fuzzing the decompressor) this leads to out-of-bounds writes/reads and a memory leak:

  • XtcBasedEncoder::decode allocates buffer.data twice — the first allocation is immediately overwritten and leaked.
  • smallIdx, read from the compressed data, indexes the fixed-size magicInts table (magicInts[smallIdx], magicInts[smallIdx - 1]) with no range check — an out-of-bounds read of a static array.
  • buffer.index, an attacker-controlled byte count read from the data, is memcpy'd into buffer.data without checking it against the buffer capacity — a heap buffer overflow.
  • The buffer.data / index-buffer allocations are not null-checked.
  • Lossless_bypass::decompress does not null-check its malloc before memcpy.

Changes

Bounds checks and null checks only; valid data is unaffected:

  • drop the leaked first buffer.data allocation;
  • reject smallIdx outside [0, LASTIDX) before indexing magicInts;
  • reject a packed size (buffer.index) larger than the buffer.data capacity before the copy loop;
  • null-check the buffer.data and index-buffer allocations;
  • null-check the Lossless_bypass allocation.

Notes

XtcBasedEncoder::decode does not receive a length for its input buffer, so the reads from the input pointer itself can not be fully bounded without threading a length through the EncoderInterface::decode signature; this change bounds the out-of-bounds writes and the static-array index, which are the memory-corruption issues.

Context

Found while integrating SZ3 as an experimental compression codec in ClickHouse and fuzzing the decompressor: ClickHouse/ClickHouse#108788

XtcBasedEncoder::decode and Lossless_bypass::decompress read sizes and indices
from the compressed data without validation, so corrupted input could write or
read out of bounds and leak memory:
 - XtcBasedEncoder::decode allocated buffer.data twice (the first allocation was
   overwritten and leaked); the index smallIdx, read from the data, indexed the
   fixed-size magicInts table out of bounds; and buffer.index, an attacker-
   controlled byte count, was memcpy'd into buffer.data without checking it
   against the buffer capacity (a heap buffer overflow). Allocations were not
   null-checked.
 - Lossless_bypass::decompress did not null-check its malloc.

Adds the missing bounds and null checks; valid data is unaffected.

Found while integrating SZ3 into ClickHouse and fuzzing the decompressor:
ClickHouse/ClickHouse#108788
ayzk added a commit that referenced this pull request Sep 1, 2026
Taking the fz-branch fixes file by file overwrote them. The magicInts index
and the packed-data size both come from the compressed stream and were used
unchecked.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 1, 2026
Bug fixes only: no compressed-format change and no interface signature change.

Covers the reviewed content of #131, #133, #134, #135, #137, #138 and #139, plus the
findings ported from the fz branch. #132 is only partly covered -- see the PR body for
the four exclusions and the measurement behind each.

31 dataset x algorithm x error-bound combinations are byte-identical to master, and every
master-produced file still decompresses to the same bytes.
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

Not taken from the PRs as written: #132's internal-buffer bound (above), and #135's
XtcBasedEncoder bounds are reinstated in a form that does not reject valid streams.

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer. Both save() and load() now reject an error bound
    mode with no branch: save() would write a blob load() cannot parse, and load() would leave
    the bound unread and shift every field below it, dataType included
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer. Both save() and load() now reject an error bound
    mode with no branch: save() would write a blob load() cannot parse, and load() would leave
    the bound unread and shift every field below it, dataType included
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

The format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer. Both save() and load() now reject an error bound
    mode with no branch: save() would write a blob load() cannot parse, and load() would leave
    the bound unread and shift every field below it, dataType included
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

Version 3.3.2 -> 3.3.3. SZ3_DATA_VERSION stays at 3.3.2: the format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer. Both save() and load() now reject an error bound
    mode with no branch: save() would write a blob load() cannot parse, and load() would leave
    the bound unread and shift every field below it, dataType included
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 15, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

Version 3.3.2 -> 3.3.3. SZ3_DATA_VERSION stays at 3.3.2: the format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config, and validating contents only where the
    config is a compressed-stream trailer. Both save() and load() now reject an error bound
    mode with no branch: save() would write a blob load() cannot parse, and load() would leave
    the bound unread and shift every field below it, dataType included
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 16, 2026
Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

Version 3.3.2 -> 3.3.3. SZ3_DATA_VERSION stays at 3.3.2: the format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config. It now takes `size_t &remaining_length` and
    reads through the bounded overload, like every other load() in the tree, so the HDF5 filter
    passes cd_nelmts rather than reading unbounded. Both save() and load() reject an error bound
    mode with no branch: save() would write a blob load() cannot parse, and load() would leave
    the bound unread and shift every field below it, dataType included
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>
@ayzk

ayzk commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

Thanks for this — the fix is carried in #145, which consolidates all eight of the open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139) into one reviewable branch, together with the defects that reviewing them turned up.

Closing here so the review happens in one place. The description of #145 records, per pull request, what was taken and where it departs from the patch as written.

@ayzk ayzk closed this Sep 16, 2026
ayzk added a commit that referenced this pull request Sep 16, 2026
…posable (#142)

* Drop 31 no-op ALWAYS_INLINE keywords + fix SDRBench dataset URLs (#140)

* Drop 31 no-op ALWAYS_INLINE keywords

Benchmarking on Anvil (EPYC 7763; GCC 10.2/11.2/14.2, AOCC clang 12) and
locally (GCC 16.2, AppleClang) shows the attribute changes nothing at 31 of
the 49 sites: the compilers already inline these, and removing the keyword
either yields a byte-identical binary or measures zero.

What the data says to keep, and why this is not a bulk removal:

  LinearQuantizer (5) + BlockwiseIterator (9) carry the entire effect.
  Downgrading just those two groups costs ~7.5%; downgrading everything
  else together costs ~0.2%. No single group crosses GCC's inlining
  threshold on its own, so per-group numbers hide this -- it only shows up
  when the two are isolated. They keep the attribute.

  Config.hpp to_lower keeps its inline: it is the only namespace-scope
  non-template among the sites, and without it the library stops linking.

  interp_akima / interp_pchip keep theirs: both are multi-line with
  branches, both currently have no callers, so the byte-identical result
  for them is vacuous and says nothing about future use.

  QuantOptimization.hpp lorenzo_predict_3d keeps its attribute; the
  function is dead code today but is expected to come back.

Deleted rather than downgraded to plain inline: 27 of the 31 are in-class
definitions (implicitly inline) and 4 are namespace-scope templates (already
weak/COMDAT), so no keyword is needed to preserve linkage.

Included here are the two on ComposedPredictor::predict/estimate_error,
which is where GCC 16 actually hard-errors: the class is itself a
PredictorInterface and may nest, so speculative devirtualization recurses
into itself until the inline budget is exhausted -- and a failed
always_inline is an error, not a warning. That is what broke the MinGW CI
job on the fz branch.

Verified: builds clean under GCC 16.2 and AppleClang; ALGO_LORENZO_REG,
ALGO_INTERP_LORENZO, ALGO_INTERP and ALGO_NOPRED all round-trip within the
error bound on the in-tree smoke file and on miranda 384x384x256.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Fix SDRBench dataset URLs: Globus endpoint moved

All eight integration-test datasets return 404. SDRBench moved to a new
Globus endpoint, changing both the host and the path prefix:

  g-8d6b0.fd635.8443.data.globus.org/ds131.2/Data-Reduction-Repo/raw-data/
  g-d0cd3f.fd635.8443.data.globus.org/raw-data/

exaalt-copper and exaalt-helium were also renamed upstream, from
SDRBENCH-exaalt-* to SDRBENCH-EXAALT-*, so the host swap alone still left
those two at 404.

New URLs taken from https://sdrbench.github.io/datasets.html and confirmed
reachable (HTTP 206 on a range request) for all eight. The integration test
matrix covers exactly these datasets, so CI on this PR is the real check
that each archive still unpacks to the filenames datasets.json expects.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>

* Add 12 CPU modules + tests; fix 10 pre-existing bugs

MGARD/SPERR fused paths kept as *FusedDecomposition and still drive
ALGO_MGARD / ALGO_SPERR; the composable compositions take the default names.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Add missing <memory> includes

libstdc++ does not provide std::make_shared transitively; the new test
translation units changed the include order enough to expose it.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Add module acceptance gate

Group-level contract checks (ModuleContract.hpp) and a header self-containment
check, both runnable and wired into CI; docs/MODULE_ACCEPTANCE.md records what a
module must satisfy to enter the library. Each check comes from a defect class
that has shipped here.

Fixes found by the two checks: 9 headers were not self-contained, and
MemoryUtil::read guarded remaining_length with assert, which Release compiles
out, so a truncated stream read past the buffer.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Make every header self-contained under libstdc++ too

The check only ran under libc++ locally, which provides more transitively; 17
headers were missing <limits>, <cmath>, <cstddef>, def.hpp or a project header.
CI now runs the check on the macOS job as well, so a clean run under one
standard library no longer passes for both.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Charge the encoded size when loading regression coefficients

RegressionPredictor::load debited remaining_length by the decoded bin count
(coeff_size * sizeof(int)) while decode() advances the cursor by the much
smaller encoded byte count, so the budget ran out early. Harmless while the
guard in MemoryUtil::read was an assert compiled out of Release builds; now
that it throws, the HDF5 filter path hit it on miranda velocity fields at
eb=1e-4.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Size the HDF5 filter's compressed buffer from SZ_compress_size_bound

sizeof(T) * num * 2 is below SZ_compress's own minimum for a small chunk, so an
explicit chunk of a few hundred elements aborted with "The buffer for
compressed data is not large enough". The integration test now covers an
explicit small chunk alongside the full and auto-chunked cases.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Add the Decomposition group contract

Six decompositions did not override size_est(), so SZGenericCompressor sized
its buffer from 0 while the quantizer's unpredictable list could be arbitrarily
large; three are fixed here and the rest already had one.

The contract also records MGARD's bound limitation: it quantizes coefficients
per level and never checks the reconstruction, so the transform's own round-off
passes through and the absolute bound holds only while max|x| * epsilon<T> << eb.

Also restores the H5Z filter's buffer headroom on top of SZ_compress's minimum.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Make Lossless_bypass respect its destination capacity

compress() memcpy'd srcLen bytes into dst regardless of dstCap, so any payload
larger than the caller's buffer was an unconditional heap overflow.
Lossless_zstd already checks and throws; bypass now does the same.

Caught by AddressSanitizer on Linux: ALGO_BIOMDXTC pairs its codec with
Lossless_bypass, so nothing shrinks the payload, and the HDF5 filter's buffer
was sized from SZ_compress's minimum, which assumes it does. glibc reported it
as "munmap_chunk(): invalid pointer"; macOS's allocator did not abort, which is
why it only showed up in CI. The filter's headroom is restored here too - it
was lost restoring a backup during an earlier A/B.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Account for the selection stream in ComposedPredictor::load

decode() advances the cursor but leaves remaining_length untouched, so the
bound check was too loose for everything read after it. Same defect class as
RegressionPredictor::load, in the opposite direction.

MemoryUtil::read now compares by division so the size computation cannot
overflow on its own.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Complete the module acceptance gate; add the module benchmark tool

Contracts now cover the Lossless group as well; its destination-capacity check
is what Lossless_bypass was missing. Adds tests for SZGenericCompressor's two
guards on get_out_range, which had none.

GranularBitRoundQuantizer's tests move out of test_quantizer_cluster.cpp into
their own file.

tools/bench/module_bench.cpp (BUILD_SZ3_BENCH=ON) measures a composition's
compression ratio, achieved error and throughput on a real dataset and prints
CSV. Module characteristics can only be measured, not authored, so this is the
piece the composition metadata will need.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Bring the docs level with the modules

modules.json was missing 8 modules; CLAUDE.md's quantizer list predated five of
them and had no preprocessor list at all. Both now also point at the acceptance
gate and the benchmark tool.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Install the group contracts; record composition constraints

ModuleContract.hpp moves to include/SZ3/testing/ so it ships with the library:
the gate is meant to apply to modules submitted from outside this tree, which
cannot reach a header under tools/test/.

modules.json gains a `composition` block on the 13 modules that constrain what
they can be composed with -- an encoder that cannot derive its own bin range, a
decomposition that only works with one encoder, bins that are not a countable
domain, the regime an error bound holds in, a measured bad pairing. These are
the facts a composition engine needs before any measured characteristic, and
each one is already enforced by a test or by the code. SZ3_ModulesJson checks
the file against the tree so the two cannot drift.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Make MGARD honour its error bound unconditionally

MGARD quantized coefficients per level and never checked the reconstruction, so
the synthesis round-off -- which scales with the field's magnitude -- passed
through. For float at eb = 1e-2 a magnitude of 1e6 reached 1.17x eb and 1e7
reached 6.25x; every other decomposition checks the value it writes back and
diverts to an unpredictable list.

Both MGARD compositions now replay the decoder's inverse transform and record
what still misses into an OutlierQuantizer, carried in save() the way
LinearQuantizer carries its unpredictable list.

Costs an inverse transform and a copy of the input on the compress side:
miranda velocityx 301 MB, 500 -> 293 MB/s compressing, decompression and
compression ratio unchanged (201.35 vs 201.36 at relative eb 1e-2).

Changes the ALGO_MGARD stream only; the other seven algorithms are byte-identical.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Record what the MGARD outlier pass costs

The bound now holds unconditionally, but not for free everywhere: outliers cost
nothing where the transform already met the bound, trade compression for the
bound where it did not, and degenerate to near-lossless on a field that leaves
the per-level quantizer saturated. The measured numbers are in the header.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Give each branch and pull request one CI run at a time

Every push added a full matrix without retiring the one in flight, so the long
integration jobs of older runs were evicted mid-test instead of finishing --
hacc and exaalt-helium died at 13-17 and 25-30 minutes across three runs while
the same jobs completed in 2h10m and 46m on a branch that was not being pushed
to repeatedly.

master and fz still keep every commit's build result; only feature branches and
superseded pull-request runs are cancelled.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Consolidate the pending bug fixes: 8 open PRs plus the fz-branch findings

Bug fixes only. Nothing here changes the compressed format or an interface
signature, and every algorithm's output is byte-identical to master's (verified
over 31 dataset/algorithm/error-bound combinations, plus decompressing files
master produced).

From the open pull requests, reviewed line by line:

  #131  Config::load read one byte past the end of the config blob
  #132  bounds-check the whole decompression path (see the two skips below)
  #133  shift-by-64 UB for a single-symbol Huffman tree
  #134  bounds-check HuffmanEncoderV2 tree loading
  #135  bounds-check XtcBasedEncoder's magicInts index; plug a leaked buffer
  #137  remaining_length accounting after Huffman decode in both predictors
  #138  non-finite float to int64_t cast UB in LinearQuantizer
  #139  scratch buffers leaked when compression throws; OMP chunk capacity was
        missing room for the size header Lossless_zstd writes

Two parts of #132 are deliberately not taken:

  - It moves the quant_inds count from after the encoder's tree to before it so
    the tree is immediately followed by its encoded stream. That is a compressed
    format change and it is not versioned, so files written by any released SZ3
    fail to decode. The bound it was buying is recovered instead by letting the
    caller supply it: HuffmanEncoder::set_decode_bound(), called by
    SZGenericCompressor once it has consumed the count, and by both predictors.
    load() no longer guesses the bound from its own buffer -- the tree and the
    stream are not required to share a buffer, and test_encoder.cpp puts them in
    separate ones.
  - It reinterprets LosslessInterface::decompress's `dstLen` as an input
    capacity when the caller provides the buffer. The declared contract is that
    it is an output, and callers do pass uninitialised values, so this fails
    nondeterministically (it broke LosslessTest.LosslessBypass here). The
    self-allocating branch, where a non-zero value is opt-in, is kept.

Also fixed while reviewing:

  - HuffmanEncoderV2 sized its dense tables from an unbounded `maxval` read
    straight from the stream; #134 bounds the node count but not this.
  - HuffmanEncoderV2's node count is an int holding a value read as 64-bit, so
    the new bound is checked with an explicit sign test rather than an implicit
    conversion.
  - test_lossless.cpp passed an uninitialised size to decompress().

From the fz branch, verified to reproduce here:

  Lossless_bypass::compress ignored its destination capacity, so any payload
  larger than the caller's buffer was an unconditional heap overflow;
  TimeSeriesDecomposition violated its error bound 1.94x on the
  null-reference-frame path; ArithmeticEncoder sign-extended a shift, corrupting
  about half of all streams; HuffmanEncoder's stateNum narrowing overflowed on a
  wide bin range; RunlengthEncoder and two decompositions had no size_est(), so
  the compressor sized its buffer from 0; KmeansUtil had reserve+operator[] UB
  and an off-by-one read; the HDF5 filter sized its buffer below SZ_compress's
  own minimum; 24 headers were not self-contained under libstdc++ or libc++;
  .gitignore's bare `test` pattern hid every test file.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Restore PR #135's XtcBasedEncoder bounds

Taking the fz-branch fixes file by file overwrote them. The magicInts index
and the packed-data size both come from the compressed stream and were used
unchecked.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Compare by division in the bounded array read

num_elements * sizeof(T1) can overflow on its own, which is the computation the
check is supposed to guard. Matches the scalar overload and PR #132.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Drop PR #132's bound on the internal decompression buffer

It bounds that buffer by SZ_compress_size_bound, which is the size of the
*output* buffer. compress() sizes the internal one as max(1000, 2 *
(decomposition.size_est() + encoder.size_est() + sizeof(Q) * bins)), so for a
64-bit bin type it is far larger and valid streams are rejected. Every module in
this tree emits int bins, so the bound happens to hold and these tests cannot
reach it -- the fz branch has three modules that do (BitplaneEncoder,
BitTruncationQuantizer, FixedPointQuantizer) and all three failed.

A corrupted declared size is still caught, after the allocation, by the zstd
frame check and the size comparison this PR adds to Lossless_zstd::decompress.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Validate config contents only for a compressed-stream trailer

PR #132 rejects N outside [1, 4] and dimensions whose product differs from the
element count. Both hold for a config read from the end of a compressed stream,
and neither holds for the HDF5 filter's cd_values: those carry placeholder zeros
that set_local fills in later, as cdvalueHelper.py says in as many words. The
check killed the whole filter -- 80 of cesm-atm's 160 integration cases aborted
with "invalid number of dimensions", across every algorithm.

The single-argument overload, which is what the filter and the OpenMP path use,
now says so explicitly and skips the content checks; the bounded overload used
by SZ_decompress keeps them.

Verified against the real cesm-atm field through the HDF5 filter: five
algorithms pass, and removing the guard reproduces the abort.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Validate config contents only for a compressed-stream trailer

The check PR #132 adds for N outside [1, 4] and for dimensions whose product
differs from the element count holds for a config read from the end of a
compressed stream, and not for the HDF5 filter's cd_values: those carry
placeholder zeros that set_local fills in later, as cdvalueHelper.py says in as
many words. It killed the whole filter -- 80 of cesm-atm's 160 and 96 of
exaalt-copper's 192 integration cases aborted with "invalid number of
dimensions", across every algorithm.

Verified against the real cesm-atm field through the HDF5 filter.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Bound the integration build's parallelism

A bare "-j" means unlimited parallel compilation. This tree now has 56
translation units against master's 9, and they pull in MGARD, SPERR and Eigen,
so the peak at link time is enough to get a 15 GB runner terminated: hacc died
three times at exit 143 immediately after "100% Linking CXX executable
sz3ToHDF5", with no error of its own, 86 GB of disk still free and every other
dataset passing.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Make the integration test's output survive a killed job

Python block-buffers stdout into the log pipe, so everything the driver prints --
including the captured output of every test it runs -- is lost when the job is
terminated. The log then stops at the last write from a subprocess, which is the
build, and says nothing about where the run actually died. hacc has failed four
times with exit 143 and a log that ends at the same line; that line is where the
visible output stops, not where the failure is, and two hypotheses I drew from it
were wrong for exactly that reason.

Runs the driver with -u, and flushes around dataset preparation so the phase is
identifiable even without it.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Stream each integration case's output instead of capturing it

capture_output=True prints the child's output only after it exits, so a case that
never returns leaves no trace of how far it got. hacc has now failed five times;
the log ends at the "command:" line for its first case -- a single 1.12 GB field
written as one chunk -- and everything that case printed is still invisible.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Bound the HDF5 filter test's small-chunk mode

The mode asked for 8-element chunks over the whole field. On a 1D field of 280
million elements that is 35 million chunks, and the HDF5 chunk index alone took
the process to 15.3 GiB of a CI runner's 16 GiB -- hacc and exaalt-helium were
killed there. Restricting the mode to a leading slice of at most 4096 chunks
brings the peak to 9.6 GiB and leaves the mode's coverage intact: an unfixed
filter still fails it on every algorithm at ordinary dataset sizes.

Also stop tracking a stray __pycache__ entry.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Register the four newer algorithms in the HDF5 cd_values helper

The helper's name-to-enum map stopped at ALGO_BIOMDXTC, so ALGO_SVD, ALGO_ZFP,
ALGO_SPERR and ALGO_MGARD could not be requested through the HDF5 filter at all.
All four round-trip correctly through the filter, on the in-tree smoke file and
on a 256x384x384 field, in every chunk mode.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Cover the HDF5 filter's compressed-buffer sizing

The filter has to size its output buffer from SZ_compress_size_bound rather than
from the raw chunk size, and nothing in the suite exercised that: a chunk small
enough for the compressed block to exceed it never appeared. This adds a third
chunk mode that asks for 8-element chunks, which the pre-fix filter rejects with
"buffer not large enough" on every algorithm.

The mode is restricted to a leading slice of at most 4096 chunks. Over a whole
field it would mean tens of millions of chunks, and the HDF5 chunk index alone
takes the process past a CI runner's memory.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Stop the docs workflow from deploying on a closed pull request

The `pull_request: [closed]` trigger runs on refs/pull/N/merge, which the github-pages
environment does not accept, so it fails every time. It first fired when #146 merged:
run 34993302305 failed while the push to fz at the same moment (34993301679) deployed
the same docs successfully. The push trigger already covers merges into fz.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Drop the two capability traits the merge made unnecessary

quantizer_size_est() detected whether a quantizer has size_est(). QuantizerInterface now
declares it with a default of zero, the way DecompositionInterface already declares its own,
so every quantizer answers and the detection is not needed. The four that had none encode
every value and have no unpredictable list, which is what zero means.

encoder_has_decode_bound detected set_decode_bound(), which decode()'s byte-budget parameter
replaced; nothing called either, and the member the setter wrote was read by a check that
could no longer fire.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Take out what the merge and the review left behind

The include unions the merge produced left five headers including the same thing twice.
Two comments in HuffmanEncoder described members the previous commit removed, one of them
sitting above an unrelated field; two of its checks repeat the loop bound `maxBits` already
enforces, one per bit of the decoded stream. InterpolationDecomposition's only change was a
comment saying the same thing at greater length, and an include it does not use; so were
the <limits> in the two predictors and the blank lines in BlockwiseIterator.

SZAlgoZFP asserts without including <cassert>; it had been getting it through a header that
no longer offers it.

module_bench has no caller — no workflow, no test, no documentation outside its own option.
It measures rather than asserts, so it cannot become a test, but it belongs with them rather
than behind an option of its own.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Fix the doubled include guard and a stray blank line

SPERRDecomposition guards on SZ3_SZ3_SPERR_DECOMPOSITION_HPP. No guard in the tree collides,
so nothing was being skipped, but the name says the file twice.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Say what the module contract covers, and list the uid it omits

The contract header claimed every module in the library passes it and pointed at a file that
does not exist. Eight do not: OutlierQuantizer deliberately, since it is a second pass held
inside three decompositions whose bins never reach SZGenericCompressor, so its range spans the
bin type instead of starting at zero.

The uid table in the add-module skill lists eight of the nine in use. A module author picking
the next free value from it lands on OutlierQuantizer's, and a uid collision is read as the
wrong quantizer's state rather than rejected.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Put the three decompositions the contract skipped under it

PaSTRI, SPERRFused and the composable SPERR implement the decomposition interface and pass
the group contract unchanged — they were simply never registered. A contract only holds what
it is pointed at, so a module outside it can be broken by an unrelated change and nothing
says so.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Put the two bit-plane encoders under the contract as well

Both are general-purpose encoders that compose with any decomposition, and both pass the
group contract unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Deduce the bin type from a typedef, and hold callers to it

QuantizerInterface takes To as a template parameter but never published it, so a decomposition
wanting to forward its quantizer's bin type had to recover it from the return type of
quantize_and_overwrite. The interface now exposes it as bin_type, which every quantizer
inherits, and quantizer_bin_t goes away with its twenty lines of explanation.

The deduction is a default argument, so it only holds while the caller leaves To alone. Passing
a To the quantizer does not emit compiled silently and narrowed every bin on assignment --
5e9 from a FixedPointQuantizer arrived as 705032704. NoPrediction already asserted against that;
MultiLevel and Blockwise now do too.

module_bench builds with the tests since it moved there, which on MinGW means building the
SPERR and MGARD pipelines it exists to compare, and those are disabled on MinGW.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Name the bin type by the interface's own word, and clear the merge residue

SZGenericCompressor recovered the bin type from the return type of compress(), the same decltype
shape quantizer_bin_t used. compress() is a pure virtual override, so that type is always the To
the decomposition declared: DecompositionInterface publishes it as bin_type and the compressor
reads it, under the interfaces' own name To.

Five quantizers did not say override on size_est(). Four are caught by -Wsuggest-override;
LinearQuantizer's is non-const, so it hid the interface's virtual rather than overriding it, and
a call through a base reference would have reported an empty unpredictable list.

The rest is residue: doubled blank lines in four headers, a comment restating the line under it,
and a Runlength doc block left above the wrong function when its duplicate size_est() went.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Find Eigen's headers when CMake found it through its config

Eigen3_DIR names the directory holding Eigen3Config.cmake, which is never the directory holding
Eigen/Dense. The check guessed one sibling, eigen-src, which is right only for the FetchContent
build tree; against an Eigen installed under a prefix -- conda, spack, a non-default homebrew --
every header that reaches stdafx.hpp was reported as not self-contained. It now walks up to the
prefix that owns Eigen/Dense.

84 headers, 0 not self-contained, against an Eigen from a mamba environment.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
ayzk added a commit that referenced this pull request Sep 16, 2026
* Include what each header uses

These headers took the standard library names they use from whatever included them first, so
they did not compile on their own and broke under a different standard library.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Bounds-check decompression against corrupted input

Consolidates the eight open bug-fix pull requests (#131 #132 #133 #134 #135 #137 #138 #139)
with the findings from reviewing them, as one change. The compressed stream is untrusted, and
several modules read lengths and counts out of it and then used them to index, allocate or
loop without checking them against anything.

Version 3.3.2 -> 3.3.3. SZ3_DATA_VERSION stays at 3.3.2: the format is unchanged. A stream written by this build is byte-identical to one written by
master, and either build reads the other's output; verified on interp/lorenzo_reg/nopred in
1D, 2D and 3D.

Encoder::decode now takes the remaining byte count
------------------------------------------------
Its signature carried the symbol count and nothing else, so an encoder could not tell how
many bytes it was allowed to touch. HuffmanEncoder read its payload length out of the stream
and walked that far; BypassEncoder memcpy'd sizeof(T) * targetLength; RunlengthEncoder read a
value and a count per run. None of them had anything to compare against.

decode() now takes `size_t &remaining_length` alongside targetLength and charges what it
consumed, the same shape load() already had. The two numbers are independent -- an entropy
coder's bitstream has no terminator, so the symbol count is what says stop, while the byte
count is what says how far it may read -- and both are available at every call site.

The symbol count stays where it is in the stream, so no bytes moved.

Other bounds
------------
  - HuffmanEncoderV2's tree loading, and XtcBasedEncoder, against corrupted input
  - ComposedPredictor's predictor selection index, and its value
  - RegressionPredictor's coefficient stream, which each block consumes N + 1 entries of
  - InterpolationDecomposition's stored dimensions, which drive a grid walk over buffers
    that conf sizes
  - the declared bin count, against the element count conf carries
  - the bins InterpolationDecomposition and TimeSeriesDecomposition walk, checked once before
    the walk rather than on each access
  - Config::load reading one byte past the config. It now takes `size_t &remaining_length` and
    reads through the bounded overload, like every other load() in the tree, so the HDF5 filter
    passes cd_nelmts rather than reading unbounded. Both save() and load() reject an error bound
    mode with no branch: save() would write a blob load() cannot parse, and load() would leave
    the bound unread and shift every field below it, dataType included
  - the HDF5 filter's compressed buffer, sized from SZ_compress_size_bound
  - ALGO_LOSSLESS's output buffer: the declared size went to ZSTD_decompress as the capacity of a
    buffer the caller owns, so a stream declaring more than conf.num elements wrote past it. The
    size check that followed ran after the write. Lossless_zstd now honours a caller's capacity

Also
----
  - Huffman's shift for single-symbol input, and the non-finite float cast in LinearQuantizer,
    were undefined behaviour; so were two signed overflows on values taken from the stream,
    the doubled state count in HuffmanEncoder::load and the doubled index in
    LinearQuantizer::recover_pred
  - scratch buffers are held as unique_ptr so an exception from the encoder or the lossless
    layer does not leak them
  - PR #132's bound on the internal decompression buffer is dropped: that buffer is sized
    from the bin count and type, which no bound derivable from conf alone covers

XtcBasedEncoder's magicInts lookups are clamped on both sides rather than rejected on one.
LASTIDX is the table's length, and the encoder walks to it whenever no entry reaches minDiff --
which is every input with fewer than two triplets, since minDiff is then still INT_MAX. Both
sides read one past the table there; rejecting it on decode alone broke ALGO_BIOMDXTC for inputs
under six elements. Its bit-packing buffer is also zeroed: it went into the compressed output
uninitialised, which is why the same input did not compress to the same bytes twice.

MDZ passed its buffer capacity to decompress() as the stream length, having discarded what
compress() returned. zstd rejected every frame, and the result was decoded from uninitialised
memory without anything noticing.

Not taken from the PRs as written: #132's internal-buffer bound (above).

Co-Authored-By: Claude Opus 5 <[email protected]>

* Close what the first pass left open in the decompression path

A review of the previous commit for necessity rather than correctness. Every item below was
reproduced before it was changed; the compressed format is still byte-identical to master's.

Bounded what the first pass only re-shaped
------------------------------------------
HuffmanEncoder::load sized its node pool from the state count stored in the stream, which it
bounded only from below. createHuffmanTree mallocs and memsets about 200 bytes per unit, so a
hundred-byte file reached 5.7 GB, and the ceiling the check permitted was hundreds of gigabytes.
Decoding never touches the code tables that count sizes, so the pool now comes from nodeCount,
which the buffer already bounds -- and the state count, its range check and the pool-capacity
check all go away.

unpad_tree's index check made indices strictly increasing, which rules out a cycle but not two
parents naming one child: a 190-byte stream with nodeCount 43 built two million nodes, and 255
would not finish. Each index is now taken once, which is what the pool size assumes.

The bin count a stream declares is capped at conf.num in SZGenericCompressor, and each decomposition
that walks a grid checks it has enough. ALGO_NOPRED and ALGO_LORENZO_REG -- the lorenzo half of the
default algorithm -- walked off the end of an empty vector, and BlockwiseDecomposition took
&quant_inds[0] before looking. conf.num is only a ceiling: SZBioMDXtcDecomposition's multi-frame
path stops at the first fill frame and legitimately emits fewer.

decode()'s new byte budget was subtracted unchecked in ArithmeticEncoder, HuffmanEncoderV2 and
XtcBasedEncoder, so an over-read wrapped it to near SIZE_MAX and unbounded every later read. They
now charge through a helper that refuses to charge more than is left. ArithmeticEncoder's decoder
also opens with an eight-byte read and keeps its cursor ahead of what it consumed, so it ran past
the end of every stream its own encoder wrote; the encoder pads by that much.

Fixed, having been introduced by the previous commit
----------------------------------------------------
XtcBasedEncoder::encode leaked both of its buffers, and decode had two throws between its
allocations and their free. Both now hold them in unique_ptr.

Lossless_bypass::decompress checked the caller's capacity only where it allocates the buffer
itself -- the path where an overrun is impossible -- and then memcpy'd srcLen bytes regardless.

Ten headers threw std::out_of_range without including <stdexcept>, in a branch whose first commit
is about headers including what they use.

InterpolationDecomposition::load reads five fields from the payload and only the dimensions were
checked. interp_id and direction_sequence_id index fixed tables, and block size and anchor stride
were guarded by asserts, which a release build compiles out. All four are checked in init() now,
where the permutation table they index is built.

The sz3 CLI sized its output buffer at twice the raw size, which is below what SZ_compress demands
for a small input -- the same sizing the HDF5 filter had. `sz3 -f -i small.f32 -3 8 8 8 -M ABS 1e-3`
aborted; it uses SZ_compress_size_bound now.

Three places wrote a bound that MemoryUtil's read() overload already applies -- HuffmanEncoder's
payload length, RunlengthEncoder's per-run pair -- and one compared sizeof against zero, which it
never is.

Also
----
SZBioMDXtcDecomposition's firstFillFrame_ and fillValue_ had no initialiser and are written to the
stream unconditionally, so a 1-D ALGO_BIOMDXTC compression produced a different file every run.

EncoderInterface::decode's documentation covers the parameter it gained, and .gitignore no longer
carries entries for directories this branch does not have.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Fix what the HDF5 filter and the fuzzer found

Config::load rejected two things it should accept. The declared config size is now a
stopping point clamped to the buffer rather than a requirement, and a config with no
dimensions is legal: the HDF5 filter takes one from cd_values and fills in the shape from
the dataset. Every read is bounds-checked either way. cdvalueHelper.py declared 40 bytes
while writing 32.

Corrupting compressed streams four ways across five algorithms turned up two more: the
Huffman tree arrays leaked when the tree turned out to be malformed, and bytes2vector
shifted in int, which silently truncates any dimension past 2^32.

Huffman decode tests `count` where a symbol is produced instead of once per bit, which is
what master did; the extra comparison cost NOPRED 6% of its decompression speed.

Two checks from the previous commit assumed more than they could. The anchor stride is a
size_t, so the -1 that means "unset" arrives as SIZE_MAX and is normalised to zero a few
lines further down; the check belongs after that, where the value is either zero or a
stride. And the bin count is not bounded by the element count: a block transform emits a
padded block per partial block and legitimately exceeds it. Each decomposition that walks a
grid still checks it has enough.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Give the lossless layer a capacity in and a length out

decompress() took one size_t by reference that meant the capacity going in and the
decompressed length coming out. A caller with no buffer had nothing to put there, so zero
came to mean "no cap" -- and a caller that did own a buffer but passed zero got an
unbounded write, which is how ALGO_LOSSLESS overran its output.

The parameter is now dstCap, by value, capacity only; the length is the return value, the
shape compress() already had. A null dst still asks the callee to allocate, and the
capacity is checked exactly when the caller owns the buffer, so nothing keys on zero.

Both implementations decide ownership once rather than testing dst twice, and zstd reports
a frame that errors and one that produces the wrong length the same way, since both mean
the stream does not decompress to what it declares.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Split the integration datasets that are too slow to be one job

hacc ran 2h09 as a single job, scale-letkf 1h00 and exaalt-helium 46m, against under half an
hour for everything else. A matrix entry may now name the fields to run, so those three are
spread over several jobs and none is much past half an hour.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants