Skip to content

fix(encode): four encoder defects found by property tests and Kani - #38

Merged
Ttimmahlax merged 9 commits into
Remade-With-Rust:mainfrom
sunsided:feature/proptest-kani
Nov 23, 2026
Merged

Ttimmahlax merged 9 commits into
Remade-With-Rust:mainfrom
sunsided:feature/proptest-kani

Conversation

@sunsided

@sunsided sunsided commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds proptest property tests and Kani proofs for the encoder and decoder arithmetic, and fixes the four encoder defects they found. The most serious one silently corrupted images: with optimized Huffman tables, trellis and the streaming optimize route together, decode() returned Ok with badly wrong pixels.

Why

The fuzz targets check that malformed input never panics and that our own output decodes, but they can't see wrong-but-valid output: a file that decodes cleanly to the wrong image, or a quantized value off by one. Property tests with real oracles (streaming vs buffered output, DQT bytes vs actual divisors, exact rounded division) and Kani proofs for the small helpers cover that gap.

Key changes

  • Trellis rate tables fixed across streaming passes. Pass 1 trellised against the default Huffman tables, then the tables were replaced by optimized ones, and pass 2 trellised against those. The two passes truncated differently, so pass 2 wrote symbols the new tables had no code for: a debug panic, or in release MAE ~75–100 instead of ~18. Trellis now always rates against the default AC tables. The streaming route is picked automatically above the 256 MiB block budget.
  • QuantizationTableType::Custom clamped to 1..=255. The 8-bit DQT segment truncated larger values: 256 was written as 0, while the encoder quantized with 256.
  • HuffmanTable::new_optimized handles any code depth. Skewed symbol counts built trees deeper than the 32 levels the T.81 K.2 reference assumes, and indexing past bits[33] panicked (33 symbols, ~18.5M total counts). Merged counts are now summed in u64.
  • Exact reciprocal quantizer. A fixed 15-bit shift was off by one on ~1–3% of real coefficients. It now uses libjpeg-turbo's per-divisor shift. The scalar, AVX2 (srlv_epi32) and NEON (vshlq_u32) kernels change together, and an exhaustive test checks every divisor against every i16.
  • Tests: tests/properties.rs covers the public encode → decode round trip. In-crate proptests cover Huffman table construction. Kani harnesses cover extend/get_code, choose_idct_size and far_row.

Risks / notes

Review instructions

Start with the trellis commit (d0cafc3): it's the only fix that corrupted output silently, and the new trellis_rate_tables field in encoder.rs is the whole change. Then look at compute_reciprocal and the two SIMD kernels in quantization.rs, which carry the most risk. The u32 product reaches ~2^31.01, so check that nothing on that path does signed arithmetic. new_optimized (K.2–K.4 widening) and the Custom clamp are small. The tests in a0563f1 were written to fail first, so reading that commit shows each defect's reproduction before its fix.

Prove the small, loop-free helpers that every decode and encode leans on:

- `extend` matches T.81 F.2.2.1 for categories 1..=15
- `extend(get_code(v)) == v` for every nonzero |v| < 2^14, i.e. the
  encoder's magnitude coding and the decoder's sign extension agree
- `get_code(0)` is category 0
- `choose_idct_size` never overflows and returns 1, 2, 4 or 8 for any
  frame the parser accepts
- `far_row` stays inside the plane and next to the near row

Kani also showed `get_code` overflows on `(1i16 << 15) - 1` at
|v| >= 2^14 (category 15). The encoder never gets past category 11 for
8-bit samples, so the roundtrip proof is bounded to the reachable range.

Run with `cargo kani --lib --no-default-features`. `get_code` is
re-exported under `cfg(kani)` so the decoder-side proof can reach it.
New proptest suites (in-crate for internals, tests/properties.rs for the
public round trip). These tests FAIL on purpose until the defects are
fixed:

- streaming_optimize_matches_materialized / encoded_file_decodes:
  optimized Huffman + trellis + streaming optimize emits symbols the
  optimized table has no code for. Pass 1 trellises against the default
  tables, `optimize_huffman_table_from_stats` swaps them, pass 2
  trellises against the new ones. Debug panics ("Got zero size code");
  release decodes Ok with MAE ~75-100 instead of ~18. Hit by default
  above the 256 MiB block budget, or always with
  `set_streaming_optimize(true)`.
- custom_table_dqt_matches_request / custom_dqt_value_matches_divisor:
  `QuantizationTableType::Custom` accepts values up to 2048 but DQT is
  written 8-bit, so 256 is stored as 0, 300 as 44.
- fibonacci_depth: `new_optimized` indexes past `bits[33]` when code
  depth exceeds 32 (33 symbols, ~18.5M total count). libjpeg errors here.
- reciprocal_equals_rounded_division: the 15-bit reciprocal quantizer is
  off by one on ~1-3% of reachable coefficients (999/80 -> 13).
- total_over_u32 (debug only): `freq[v1] += freq[v2]` overflows when a
  table's total count exceeds u32::MAX.

Passing properties: optimized Huffman tables are prefix-free, cover
every used symbol, stay within 16 bits and keep the all-ones code
reserved; q100 luma round-trips within 3 levels; every encoder option
combination decodes via decode() and decode_planar(); the threaded
decoder matches the single-threaded one byte for byte.
With optimized Huffman tables, trellis and the streaming optimize route,
pass 1 trellised against the default AC tables and counted the result,
then `optimize_huffman_table_from_stats` replaced `huffman_tables` and
pass 2 trellised against the optimized ones. Different rate estimates
truncate differently, so pass 2 wrote symbols the optimized tables had
no code for: a debug panic ("Got zero size code"), and in release a
file that decodes Ok with MAE ~75-100 instead of ~18 (q39 luma, 256^2
to 4096^2). The route is chosen automatically above the 256 MiB block
budget, or always with `set_streaming_optimize(true)`.

Trellis now always rates against the default AC tables, held in their
own field that nothing replaces. That is also what the materializing
route already did, since it trellises before optimizing, so both routes
again decode to the same pixels
(`streaming_optimize_matches_materialized`).
`QuantizationTableType::Custom` clamped to 1..=2048, but the DQT segment
is written one byte per value, so `get()` truncated: 256 was declared as
0 (an invalid table), 300 as 44, while the encoder quantized with the
real value. Decoders then dequantized with a different table than the
one used to encode.

Clamp to 1..=255, the range baseline JPEG allows for 8-bit samples, and
document it on the variant. A 16-bit DQT (Pq=1) would keep the larger
values but is not valid in a baseline frame.
`new_optimized` follows T.81 K.2-K.4 literally, which sizes the code
length histogram at 33 and sorts symbols by sizes 1..=32. Skewed counts
build deeper trees than that: 33 symbols with near-Fibonacci counts
(~18.5M total, a ~19 Mpx image with adversarial content) index past
`bits[33]` and panic in debug and release. libjpeg reports an error
there; this crate aborted the caller.

Size the histogram for the deepest tree 257 symbols can form and sort
over every size, so K.3 limits any depth to 16 bits. Also merge counts
in u64: `freq[v1] += freq[v2]` overflowed (debug panic) once a table's
total exceeded u32::MAX.
The quantizer divided by multiplying with a reciprocal at a fixed 15-bit
shift. For large divisors that leaves only a few significant bits, and
the result was off by one on ~1-3% of reachable coefficients, in both
directions (999 / 80 gave 13, not 12).

Use libjpeg-turbo's per-divisor shift, `16 + floor(log2 d)`, so the
reciprocal keeps 16 significant bits. Checked exhaustively: equal to
round-half-up division for every divisor 8..=2040 and every i16
(`reciprocal_equals_rounded_division`). The product now reaches
~2^31.01, so scalar math is u32, AVX2 uses `srlv_epi32` (the low 32 bits
of `mullo_epi32` are the exact unsigned product) and NEON uses
`vmulq_u32` + `vshlq_u32`.

Measured on three 3840x2160 photos at q50/75/92: file size within
+-0.05%, PSNR unchanged to 0.003 dB, encode time unchanged. The golden
hashes for the q92 progressive and q60 trellis encodes move; baseline
q75 is unchanged.

The NEON kernel type-checks for aarch64 but has not run here (x86
only); `neon_matches_scalar` gates it on ARM.
The per-symbol counters are u32. The chroma slot of a 4:4:4 color
image of roughly 46,700x46,700 px or more can push one symbol past
u32::MAX (63 per block, Cb and Cr sharing the slot): a debug panic, or
in release a wrapped count and a wrong or missing code. Luma never gets
there, even at 65535x65535. Documented as a known limit at all three
counting sites instead of widening the hot-path counters.
CHANGES.md is what makes re-syncing with jpeg-decoder/jpeg-encoder
possible. Note which fixes are local (trellis + streaming optimize) and
which also apply to jpeg-encoder 0.7.1 (custom table clamp, Huffman
depth, reciprocal precision).
@sunsided
sunsided marked this pull request as ready for review November 23, 2026 21:19
…ings

Mutation testing showed both could be silently disabled without any
test noticing: `unread_bytes` returning 0 dropped the ExtraneousBytes
warning, and `unexpected_code` returning Ok(()) dropped BadHuffmanCode
for refinement scans and let strict mode accept the stream. Neither
warning was asserted anywhere for these cases.

- extraneous_bytes_before_marker_warn: two stray bytes at the end of a
  scan, and at the end of a restart interval, decode to the clean image
  with [ExtraneousBytes]; strict mode refuses.
- refinement_coefficient_of_size_two_is_a_bad_code: an AC refinement
  scan coding a new coefficient with size 2 decodes with
  [BadHuffmanCode] (libjpeg-turbo reads it as size 1); strict mode
  refuses with a Huffman error.

Each test fails under its mutant and passes on the real code.
@Ttimmahlax
Ttimmahlax merged commit 718de6e into Remade-With-Rust:main Nov 23, 2026
11 checks passed
@Ttimmahlax

Copy link
Copy Markdown
Contributor

Merged and released in rusty_jpeg 0.4.13. Thank you. This is the kind of bug report we can't produce ourselves: the fuzzers only prove we don't panic and that our output decodes, and every one of these was valid output that was wrong. Writing the tests to fail first made review quick. I checked each defect out of a0563f1 before looking at the fixes.

Reproduced on main before the merge:

Defect Failure on main
Trellis across streaming optimize passes streaming_optimize_matches_materialized: the two routes decode to different pixels
Optimized Huffman tables deeper than 32 levels fibonacci_depth: index out of bounds: the len is 33 but the index is 39
Custom values above 255 DQT byte 0 written while the encoder divides by 256
Fixed-shift reciprocal reciprocal_equals_rounded_division fails; over divisors 1..=255 the old formula disagrees with exact rounding on 12% of all i16 values, almost all at large magnitudes

What we checked before merging:

  • All 135 tests pass. cargo fmt and CI's clippy commands are clean, and the NEON path compiles and lints for aarch64-unknown-linux-gnu. CI's NEON job ran it.

  • compute_reciprocal: the reciprocal never exceeds 2^16 and the correction is at most d/2 + 1, so the largest product is about 2^31.04, well inside u32. The shift tops out at 26. The AVX2 (srlv_epi32) and NEON (vshlq_u32 with a negated count) kernels load the shift table at the same offsets as the reciprocal and correction tables, so their bounds are unchanged.

  • The trellis change is output-identical everywhere except the streaming route. There's no public setter for custom Huffman tables, so the materialized path already rated against the defaults.

  • Speed, main against the PR. Thin LTO, rusty_alloc, best of 5 per run, interleaved runs alternating which build goes first, re-encoding a 2000×1250 photo at 4:2:0:

    Encode main / PR PR faster in main / main control
    q75 baseline 1.021 6/8 0.999
    q92 progressive + optimized 1.041 10/20 1.009
    q75 trellis 1.032 8/8 1.043

    So no cost from the per-divisor shift. The trellis row is within that run's control noise. Output size on that photo was identical across the three encodes; the bytes differ, as you described.

For callers: encoder output bytes change slightly because quantization now rounds exactly. Custom quantization values now clamp to 1..=255 instead of writing a truncated DQT. The u32 symbol-counter limit you documented (4:4:4 at roughly 46,700×46,700 px and up) stays as a known limit.

If you're up for more of this, we'd welcome the same treatment on our other crates. Property tests against a real oracle plus Kani on the small arithmetic helpers would fit most of the Remade-With-Rust codecs and parsers, and issues or PRs on any of them are welcome. Is there a repo you'd like to look at next?

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