Skip to content

Add fdeflate backend - #548

Draft
Shnatsel wants to merge 10 commits into
rust-lang:mainfrom
Shnatsel:fdeflate-backend
Draft

Shnatsel wants to merge 10 commits into
rust-lang:mainfrom
Shnatsel:fdeflate-backend

Conversation

@Shnatsel

@Shnatsel Shnatsel commented May 19, 2026 •

Copy link
Copy Markdown
Member

Add support for using fdeflate as a compression/decompression backend. It's already proven in the png crate used by Chromium (among other things).

The backend priority is above miniz_oxide but below zlib and zlib-rs.

This PR is basically #545 but with more effort put into it.

It still depends on two upstream PRs, so I'm marking this a draft:

Buffer sizes are a guess for now, and will need tuning. Larger sizes will likely improve performance by reducing the frequency of copying the lookback buffer, at the cost of higher memory use. These will need to be adjusted to be in line with the other backends for the total amount of memory consumed.

@fintelia FYI

The previous writer-to-Vec bridge capped input per call but could still retain
unbounded parser data and encoded output. Its decoder stopped at internal
scratch boundaries, so a sufficiently sized caller buffer could still receive
an incomplete result. Error paths also lost consumed/produced accounting.

Drive StreamingCompressor directly and map its progress to flate2 counters and
statuses. Drain/decode repeatedly across the reusable 96 KiB scratch buffer,
decode directly into large initialized destinations when history permits, and
copy only initialized output into MaybeUninit destinations. Preserve terminal
errors and trailing input, allow zero-output calls to finish empty streams and
checksums, and reuse allocations on reset. Forbid unsafe code in this adapter.

Add regressions for exact output sizes, one-call Finish, slice/Vec transitions,
history across chunks, checksum errors, and trailing bytes. Re-enable existing
flush byte-layout tests, and gate backend-specific tests on actual selection.

The new APIs require the accompanying fdeflate series ending at
c99a7578a082ba526252559b04e49fb4e58f7092.
Keep a local Cargo patch while those commits are unpublished; the dependency
branch must contain them before that override is removed. Document this setup
and the std/Rust 1.88 requirement. no_std support remains deferred.

Validation: the complete fdeflate-backend cargo test suite passed on an isolated
export of this staged adapter, before the separate shared-writer changes.
A codec can have pending output when Write::flush requests Sync. In particular,
miniz may return a short buffer after draining old bytes without processing
that new flush request, leaving accepted input invisible to a decoder. Issuing
the flush into an already occupied output buffer also obscured completion.

Drain existing codec output before requesting Sync with a fresh buffer, and
repeat if the result fills that buffer. Respect StreamEnd and flush the wrapped
writer after all encoded bytes have been delivered.

Track a cursor into pending writer output instead of repeatedly draining the
front of its Vec. This avoids moving the remaining bytes after every short
write, retries Interrupted, and preserves progress across a WouldBlock error.
Reset the cursor when the buffer is drained or the writer is replaced.

Add regressions proving that flushing makes every input byte decodable across
levels and boundary sizes, and that a retry after partial writes, Interrupted,
and WouldBlock preserves the stream.

Validation on an isolated staged tree: the full default/miniz suite passed;
all six streaming tests also passed with fdeflate, fdeflate+zlib-rs, and
fdeflate+zlib (exercising backend precedence as well as the shared writer).
The buffering changes need coverage beyond successful one-shot round trips:
flush schedules, zero-sized destinations, unfinished resets, malformed input,
and truncation can expose counter, history, and progress bugs.

Share one exercise harness between a deterministic size/pattern/level matrix
and a libFuzzer target. Compare encoded streams and successful decodes with
miniz_oxide, bound decoding work on malformed inputs, and check consumption,
output limits, and forward progress through changing chunk sizes and flushes.
Reset both codecs after partial work or an error before testing fresh streams.

Gate the malformed-input and unfinished-reset matrix on fdeflate actually being
selected: other backends have independent differences in those cases. Add the
independent decoder as a dev/fuzz dependency, expose the fdeflate fuzz feature,
and repeat the local dependency patch in the fuzz workspace.

Validation on an isolated staged tree: the deterministic matrix passed and
cargo check built the streaming fuzz target with the fdeflate feature. Earlier
implementation validation also completed a 30-second nightly libFuzzer run
(2,481 executions) without a failure. The regular streaming contract tests
remain enabled for every backend.
Inflate's Debug implementation only reported byte counters, hiding the
buffered-output positions and terminal state needed to diagnose streaming
behavior.

Include drain_pos, decode_pos, done, and error alongside total_in and
total_out. Keep inner and scratch omitted so diagnostics do not dump the
decoder internals or buffer contents. This changes diagnostic output only.

Validation: cargo check --no-default-features --features fdeflate --offline,
cargo fmt --all -- --check, and git diff --check passed.
A bounded token buffer can describe several MiB of repeated input before
it must emit a DEFLATE block. The adapter test previously supplied 2 MiB
and assumed that one byte of output space must stop input consumption,
which is no longer true when the input fits in pending match tokens.

Use 8 MiB of repeated input so the test crosses the token limit. Retain
the assertions for partial consumption, output progress and decoding
of the finished stream. This tests backpressure without imposing the
old 128 KiB Huffman block boundary on the backend.

Validation: cargo test --offline --release --no-default-features
--features fdeflate passed the unit, integration and documentation tests
with the token-budget implementation and without the RLE optimization.
The streaming microbenchmarks emphasize random or highly repetitive
inputs and do not expose all costs of retaining tokens across batches.
Add a compression-only corpus harness for local Rust-source and executable
snapshots, plus deterministic low-alphabet and skewed byte distributions.

Measure levels 1, 4, 6 and 9 with a zlib wrapper and 32 KiB output slices.
Reuse the compressor and output allocation, include reset costs, warm up
each case, and report the median of five samples lasting at least 50 ms.
Emit elapsed time and compressed size as CSV so throughput improvements
can be considered alongside ratio changes. Source/executable snapshots
are supplied by the caller and are not checked into the repository.

Validation: the harness was run across all four workloads and levels in
the before/after token-budget comparison. It also compiles in the passing
fdeflate-backend release test suite; formatting checks passed.
@Byron

Byron commented Nov 24, 2026

Copy link
Copy Markdown
Member

Once #589 has added their benchmarks, it might be worth adapting them to run here as well.

@srijs

srijs commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Rebased this as best as I could (on the patched version of fdeflate) and ran the #589 benchmarks to compare.

Large files, MB/s of uncompressed data (higher is better), compressed size in MB:

sirocco fdeflate zlib-rs miniz_oxide
compress, level 1 198 (77.1) 154 (87.7) 183 (94.1) 143 (87.6)
compress, level 6 83 (68.9) 34 (68.8) 57 (68.9) 23 (68.1)
compress, level 9 65 (68.2) 26 (68.5) 26 (67.6) 13 (67.8)
decompress, one decompress_vec 778 631 590 324
decompress, read::DeflateDecoder 802 638 550 308

Small streams, ns per stream (lower is better), with one Compress/Decompress reused through reset:

size decompress: sirocco fdeflate zlib-rs compress: sirocco fdeflate zlib-rs
64 B 498 1,814 880 3,627 13,835 7,886
1 KiB 4,431 8,356 7,464 16,738 38,785 30,221
64 KiB 96,594 122,499 133,428 832,404 1,713,130 1,168,125

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants