From 46c799541ee933bbac004cb1b782de886bff9738 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 2 Oct 2026 03:22:02 +0300 Subject: [PATCH] ec-image: bound the animation budget tests by bytes, not by wall clock The WebP budget test asserted `elapsed < 2000 ms` and failed on a server with 3.894534671s. That clock was never measuring the property the test exists for. The decode is refused once the running total crosses max_total_alloc; what the test protects is that the refusal happens before decode_frames clones the whole canvas once per ANMF chunk. The cost of a refused decode is a deterministic function of the budget and the canvas size -- wall time is the host's memcpy bandwidth for a fixed ~4 GiB of traffic, which is exactly what differed between the hosts. Measured, same input, 15 runs each: release 0.747/0.759/0.893 s (min/med/ max), debug 0.774/0.779/0.821 s, server 3.895 s. A 5x spread with byte-identical decoder work. The existing 2000..3000 ms rerun escape hatch does not help: 3.895 s falls outside the rerun window. Replace it with a thread-local counting global allocator in the test binary and bound the work in bytes against the decoder's own max_total_alloc. The ceiling is not a fitted constant: it is the limit the guard enforces, so "refused at the total budget" and "allocated no more than the total budget" are the same statement. Each budget test now decodes both a 64-frame and a 4096-frame file and bounds both, so the cost cannot grow with the attacker's frame count -- a guard spent per input frame, or after the clone instead of before it, is caught here, and no clock could tell those apart. Red proof: moving budget.spend from before the clone to after it (one canvas clone too many) reds on the byte bound at 5120024246 bytes. The same mutation measures 1.006 s median through the old clock and would have passed -- that is what decides it. Under load (16-40 spinners plus direct-write memory hammers, load average 46) decode elapsed reaches 2.42-9.34 s, reproducing the server condition locally, while the new tests stay green at 6.94-13.81 s per run. Same class swept in the same file: the GIF budget test's 5 s ceiling, the 60000x60000 GIF frame's 100 ms ceiling, and the LZW bomb's 1 s ceiling all become byte bounds (measured 4.096 GB, 421 B, and far under 1 MiB respectively). The tally is per-thread rather than a global atomic: cargo test runs these in parallel, and a shared counter summed concurrent decodes together (reported 6144529702 for a decode that allocates 4096023126). cargo test -p ec-image scoped green: fuzz 18, differential 19, real_library 2. --- crates/ec-image/tests/fuzz.rs | 170 ++++++++++++++++++++++++------ lanes/ecimagewallclock.report.md | 173 +++++++++++++++++++++++++++++++ 2 files changed, 312 insertions(+), 31 deletions(-) create mode 100644 lanes/ecimagewallclock.report.md diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs index a8d789e4..96076a76 100644 --- a/crates/ec-image/tests/fuzz.rs +++ b/crates/ec-image/tests/fuzz.rs @@ -7,8 +7,58 @@ //! `Err` — a decoder reached by a file picker is reached by every broken file //! on the disk. +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; use std::path::{Path, PathBuf}; +/// Counting allocator: the "refused without doing unbounded work" tests +/// below bound that work by *bytes allocated*, not by wall time. A clock is +/// a machine-dependent proxy for exactly the thing those tests care about -- +/// it measures the host's memcpy bandwidth, not the decoder's behaviour -- +/// and it was measured failing that way: the same refused WebP decode takes +/// 0.75-0.89 s on this desktop host and 3.89 s on a server, a 5x spread with +/// byte-identical decoder work, which is what reddened a 2 s ceiling. +/// Lives in the test binary only; the shipped crate has no allocator games. +/// +/// The tally is per-thread, not global: `cargo test` runs these tests in +/// parallel, so a shared counter sums concurrent decodes together and +/// reports work none of them did. +struct CountingAlloc; + +std::thread_local! { + static ALLOC_BYTES: Cell = const { Cell::new(0) }; +} + +fn count_alloc(size: usize) { + let _ = ALLOC_BYTES.try_with(|b| b.set(b.get() + size as u64)); +} + +unsafe impl GlobalAlloc for CountingAlloc { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count_alloc(layout.size()); + unsafe { System.alloc(layout) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count_alloc(new_size); + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static ALLOC: CountingAlloc = CountingAlloc; + +/// Runs `f` on this thread and returns its value together with every byte +/// that thread allocated while it ran. That count is the decoder's own +/// work, independent of how fast the host is at moving those bytes around. +fn counting_allocations(f: impl FnOnce() -> T) -> (T, u64) { + ALLOC_BYTES.with(|b| b.set(0)); + let out = f(); + (out, ALLOC_BYTES.with(Cell::get)) +} + const ROUNDS: usize = 10_000; fn fixtures() -> PathBuf { @@ -364,10 +414,18 @@ fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() { data.extend_from_slice(&60000u16.to_le_bytes()); data.push(0x00); - let start = std::time::Instant::now(); - let err = ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit"); - assert!(start.elapsed().as_millis() < 100, "{:?}", start.elapsed()); + // Bounded by bytes, not by a clock: this refusal happens before the + // frame sizes anything at all, so the whole decode is a few hundred + // bytes of header parsing (measured: 421 B in 2.6 us) whatever the host's + // speed. The old 100 ms clock was a machine-dependent proxy for that. + let (err, allocated) = counting_allocations(|| { + ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit") + }); assert!(format!("{err}").contains("limit"), "{err}"); + assert!( + allocated <= 64 * 1024, + "a header-only refusal allocated {allocated} bytes; it must refuse before sizing the frame" + ); } #[test] @@ -378,14 +436,36 @@ fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget // must be caught by the decode-wide budget even though no single frame // or single buffer ever looks large by itself. let data = one_pixel_gif(16000, 16000, 64); - let start = std::time::Instant::now(); - let err = ec_image::decode_animation(&data) - .expect_err("64 clones of a near-limit canvas is past the total budget"); // A few real canvas clones run before the budget catches up (the budget // is spent per frame, so it can't refuse before at least one clone), so - // this bounds "a handful of gigabyte copies", not "no allocation at all". - assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed()); + // this bounds "the decoder's own total budget, not a byte more", not "no + // allocation at all". Bytes, not a clock -- see the counting allocator + // above. + let budget = ec_image::Limits::default().max_total_alloc as u64; + let (err, allocated) = counting_allocations(|| { + ec_image::decode_animation(&data) + .expect_err("64 clones of a near-limit canvas is past the total budget") + }); + assert!(format!("{err}").contains("limit"), "{err}"); + assert!( + allocated <= budget, + "refused decode allocated {allocated} bytes, past the {budget}-byte total budget" + ); + + // Size-relative, and the half that pins the guard: 64x the frames in the + // file must not buy 64x the work. A budget spent per *input* frame, or + // after the clone instead of before it, refuses later or not at all as + // the frame count grows. + let bomb = one_pixel_gif(16000, 16000, 4096); + let (err, allocated) = counting_allocations(|| { + ec_image::decode_animation(&bomb) + .expect_err("4096 clones of a near-limit canvas is past the total budget") + }); assert!(format!("{err}").contains("limit"), "{err}"); + assert!( + allocated <= budget, + "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget" + ); } #[test] @@ -476,28 +556,49 @@ fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec= 2000 && elapsed.as_millis() < 3000 { - let (elapsed2, err2) = run(); - if elapsed2 < elapsed { - elapsed = elapsed2; - err = err2; - } - } - assert!(elapsed.as_millis() < 2000, "{elapsed:?}"); + let (err, allocated) = counting_allocations(|| { + ec_image::decode_animation(&data) + .expect_err("64 clones of a near-limit canvas is past the total budget") + }); + assert!(format!("{err}").contains("limit"), "{err}"); + assert!( + allocated <= budget, + "the refused decode allocated {allocated} bytes, past the {budget}-byte total budget" + ); + + // Size-relative, and the half that pins the guard: 64x the frames in + // the file must not buy 64x the work. A budget spent per *input* frame, + // or after the clone instead of before it, refuses later or not at all + // as the frame count grows -- and no clock can tell those apart, since + // the work is the same order either way. + let bomb = one_pixel_animated_webp(16000, 16000, 4096); + assert!( + bomb.len() > data.len() * 16, + "the second input is meant to be far larger: {} vs {} bytes", + bomb.len(), + data.len() + ); + let (err, allocated) = counting_allocations(|| { + ec_image::decode_animation(&bomb) + .expect_err("4096 clones of a near-limit canvas is past the total budget") + }); assert!(format!("{err}").contains("limit"), "{err}"); + assert!( + allocated <= budget, + "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget" + ); } /// Build an LZW-compressed data stream that keeps expanding after the @@ -573,9 +674,16 @@ fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() { data.push(0); // sub-block terminator data.push(0x3B); // trailer - let start = std::time::Instant::now(); - let _ = ec_image::decode(&data); - assert!(start.elapsed().as_secs() < 1, "{:?}", start.elapsed()); + // The frame declares 4x4, so the decoder may hold 16 indices, a 4-colour + // palette and a 4x4 canvas -- kilobytes at most. Unbounded expansion is + // hundreds of megabytes. Bytes, not a clock: the same clock-versus-bytes + // split as the budget tests above, and here the signal is much larger + // than any host's speed difference. + let (_out, allocated) = counting_allocations(|| ec_image::decode(&data)); + assert!( + allocated <= 1 << 20, + "a 4x4 GIF frame allocated {allocated} bytes; the LZW stream expanded past its frame" + ); } fn crc32(data: &[u8]) -> u32 { diff --git a/lanes/ecimagewallclock.report.md b/lanes/ecimagewallclock.report.md new file mode 100644 index 00000000..7a1d14d9 --- /dev/null +++ b/lanes/ecimagewallclock.report.md @@ -0,0 +1,173 @@ +# ec-image: replace the WebP budget test's wall clock with a byte bound + +Lane: `lane/ecimagewallclock`. Touches one file, `crates/ec-image/tests/fuzz.rs`. +No shipped-crate change; the counting allocator lives in the test binary only. + +## The failure + +`a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget` +red on a server host with `3.894534671s` — the panic message *was* the duration, +because the assertion's own message was `"{elapsed:?}"`. + +## What the assertion was protecting against + +The decode is refused by `AllocBudget::spend` (`lib.rs:201`) the moment the +running total crosses `max_total_alloc` (4 GiB by default). What the test +protects is that the refusal happens *before* the work: `decode_frames` clones +the whole composited canvas once per ANMF chunk, so 64 tiny frames over a +16000x16000 canvas is 64 GiB of compositing if the guard stops firing. + +So the property is **bytes of work performed before the refusal**, which is a +deterministic function of `max_total_alloc` and the canvas size. Wall time is +not that property. It is the host's memcpy bandwidth for a fixed ~4 GiB of +traffic, which is exactly the quantity that differed between the two hosts. + +## Distribution on this workstation + +Same case, `one_pixel_animated_webp(16000, 16000, 64)`, 15 runs each: + +| build | min | median | max | raw (ms) | +|---|---|---|---|---| +| release | 0.747 s | 0.759 s | 0.893 s | 747 755 756 758 758 758 759 759 761 763 764 766 766 770 893 | +| debug | 0.774 s | 0.779 s | 0.821 s | 774 776 776 777 778 779 782 789 792 821 | +| server (reported) | — | — | **3.895 s** | — | + +The desktop/server ratio is ~5x with byte-identical decoder work. A 2000 ms +ceiling calibrated on this host has ~2.5x of headroom over its own median — +it survives noise here and fails on any host slower than ~2.6x this one. The +existing 2000..3000 ms rerun escape hatch does not help: 3.895 s is outside +the rerun window, so the test took the slow path straight to the assertion. + +The old 5 s ceiling on the GIF sibling was in the same class: measured here at +0.80 s median, i.e. also a proxy for memcpy bandwidth rather than for work. + +## Decision + +Bound the work in **bytes allocated**, measured with a thread-local counting +global allocator in the test binary, against the decoder's *own* limit +(`Limits::default().max_total_alloc`). No clock survives in these tests. + +The ceiling is not a fitted constant — it is the budget the guard enforces, so +the assertion states the invariant directly: a decode that has refused at the +total budget cannot have allocated more than the total budget. + +Two additional facts fall out of the byte measurement for free: + +- **Size-relative.** The cost must not grow with the attacker's frame count, so + each budget test decodes both a 64-frame and a 4096-frame file and bounds + both. A guard spent per *input* frame, or after the clone instead of before + it, is caught here; a clock cannot distinguish those, since the work is the + same order of magnitude either way. +- **Red before the work, for cheap refusals.** The two header-refusal tests get + a tight bound (64 KiB) expressing "refused before sizing anything"; measured + 421 B for the 60000x60000 GIF frame. + +## Proof, both ways + +### Green here + +`cargo test -p ec-image` scoped, all three binaries: + +- `fuzz`: 18 passed +- `differential`: 19 passed +- `real_library`: 2 passed + +### Green under emulated slowness + +The persistent shell wedged under the load generators, so the load ran as +detached `Bun.spawn` processes and the test binary was invoked directly. + +Two mechanisms, because the decode is memcpy-bound and the server failure was a +memory-subsystem difference, not just a clock difference: + +1. 16 CPU spinners on 12 cores + 6 `dd oflag=direct` memory hammers. +2. The same plus 24 spinners and 10 more hammers (1-minute load average 46). + +Under mechanism 1, decode elapsed measured **1.46–1.75 s**; under mechanism 2, +**2.42 / 6.30 / 7.31 / 8.91 / 9.26 / 9.34 s**. That range straddles and then +clears the old 2000 ms ceiling, so the old assertion is reproduced failing +locally. + +The new tests under that same load: + +| test | result | +|---|---| +| webp budget | ok — 6.94 s, 9.44 s, 13.81 s | +| gif budget | ok — 6.39 s, 10.73 s | +| lzw bomb | ok — 0.03 s | +| gif pixels | ok — 0.00 s | + +Green at wall times 3–7x past the point where the old ceiling went red, which +is the point: the assertion no longer reads the clock. + +**What this covers:** contention, CPU starvation, and memory-bandwidth +pressure — the three mechanisms by which a host makes identical decoder work +take longer. **What it does not cover:** a genuinely slower *implementation* +(such as a build without memcpy optimizations), or hardware faults outside the +emulated axis. It does not need to: the byte bound is invariant to all of them +by construction, and the emulated runs exist to show the *old* bound was +host-dependent, not to certify the new one against hardware I do not have. + +### Red against a genuine regression + +The guard moved one line — `budget.spend` relocated from *before* the +`frames.push` clone to *after* it, so exactly one canvas clone too many happens +before the budget trips: + +``` +the refused decode allocated 5120024246 bytes, past the 4294967296-byte total budget +``` + +One extra 1 GiB canvas clone, and the test reds on the byte bound. + +The same mutation measured through the old instrument: **1.006 s median +(1.004–1.010 s)**, comfortably *under* the 2000 ms ceiling — the clock +assertion would have passed a real regression. That is the measurement that +decides the question: the clock does not discriminate the regression it was +written for, and the byte bound does. + +A second mutation (guard spent only on the first frame, so it never trips at +all) was killed by the memguard cgroup at 10 GiB — SIGKILL before any +assertion, i.e. unbounded work as intended. + +### Non-vacuity + +The refusal is still asserted on both inputs (`err` must contain `limit`), the +bound still discriminates a one-clone regression (above), and the 4096-frame +input is checked to be genuinely larger first, so the size-relative arm cannot +pass by comparing a file to itself. + +## Class sweep + +Same defect class (clock as a proxy for bounded decode work) elsewhere in the +same file, all converted on the same evidence: + +| line | was | now | measured | +|---|---|---|---| +| webp budget | `< 2000 ms` + 2000..3000 rerun | `<= max_total_alloc` bytes, 64 and 4096 frames | 4.096 GB vs 4.295 GB | +| gif budget | `< 5 s` | `<= max_total_alloc` bytes, 64 and 4096 frames | 4.096 GB vs 4.295 GB | +| gif pixels | `< 100 ms` | `<= 64 KiB` bytes | 421 B | +| gif lzw bomb | `< 1 s` | `<= 1 MiB` bytes | far under; unbounded would be hundreds of MB | + +`real_library.rs` also has clocks, but they are differential-decoder +comparisons that print timings rather than assert on them — not this class, +left alone. + +## Implementation note + +The byte tally is **per-thread**, not a global atomic. `cargo test` runs these +tests in parallel, and a shared counter summed concurrent decodes together — +the first attempt reported 6144529702 bytes for a decode that allocates +4096023126, because two tests' work was added together. Both budget tests +failed on that. Per-thread `Cell` counts only the calling thread's +allocations, and needs no arm/disarm flag. + +## Notes + +- Scratch probe (`crates/ec-image/examples/wallclock_probe.rs`) and the load + script were removed; the diff is the test file only. +- An earlier pass of these edits leaked into the primary checkout via a + relative path from the worktree cwd; reverted there with + `git checkout -- crates/ec-image/tests/fuzz.rs` and redone against the + absolute worktree path. The primary checkout is clean apart from the + untracked `.wt/` directory. \ No newline at end of file