forge
Explore
Log in

Don't you dare go Hollow

Merge lane/ecimagewallclock: the animation budget tests are byte bounds, not clocks

Browse files at this commit

69db758cb6be5ccd5a424d5e1b1df8eae6240cf4Ahmet Kaan GümüşParent: a668ef2a4ec8d5
The ec-image budget test's panic on a server was its own elapsed time (3.89 s against a 2 s
ceiling): the assertion measured the host's memcpy bandwidth, not the property it was
written for (that the budget guard refuses before unbounded work). Distribution on the
workstation: 0.747-0.893 s across 15 runs for byte-identical decoder work, a ~5x spread
across hosts.

The bound is now BYTES, measured by a per-thread counting global allocator in the test
binary, asserted against the decoder's own Limits::max_total_alloc (4 GiB) -- no fitted
constant. The deciding measurement: moving budget.spend one clone later reds the byte
bound at 5120024246 bytes against the 4294967296-byte budget, while the old clock measured
the same regression at a 1.006 s median and would have PASSED its own 2000 ms ceiling.

Honesty corrections from the refutation pass, folded in before merge: the byte bound is
an independent measurement, not the guard's own tally -- spend sums declared bytes at
chosen call sites while the tally sums actual layout.size() with realloc's full new size,
and the refusal's own formatting lands inside the measured window, so the two diverge by
construction and the red proofs are tests of their correspondence, not of an identity.
The SIGKILL mutation is labelled evidence about the mutation's severity, not a proof of
the bound, and the emulated concurrency figures are marked as inferred rather than
recorded. The tally deliberately measures allocation traffic, because the host difference
this class measures is memcpy bandwidth, which is a property of traffic.

Four wall-clock bounds swept the same way (webp and gif budget at 64 and 4096 frames, a
60000x60000 frame, and the LZW bomb); the refusal is still asserted; the discrimination
is red-proven; green is proven under emulated slowness (the server condition reproduced
locally at load average 46).
crates/ec-image/tests/fuzz.rsmodified+148 -31
@@ -7,8 +7,58 @@
7 //! `Err` — a decoder reached by a file picker is reached by every broken file7 //! `Err` — a decoder reached by a file picker is reached by every broken file
8 //! on the disk.8 //! on the disk.
9 9
10+use std::alloc::{GlobalAlloc, Layout, System};
11+use std::cell::Cell;
10 use std::path::{Path, PathBuf};12 use std::path::{Path, PathBuf};
11 13
14+/// Counting allocator: the "refused without doing unbounded work" tests
15+/// below bound that work by *bytes allocated*, not by wall time. A clock is
16+/// a machine-dependent proxy for exactly the thing those tests care about --
17+/// it measures the host's memcpy bandwidth, not the decoder's behaviour --
18+/// and it was measured failing that way: the same refused WebP decode takes
19+/// 0.75-0.89 s on this desktop host and 3.89 s on a server, a 5x spread with
20+/// byte-identical decoder work, which is what reddened a 2 s ceiling.
21+/// Lives in the test binary only; the shipped crate has no allocator games.
22+///
23+/// The tally is per-thread, not global: `cargo test` runs these tests in
24+/// parallel, so a shared counter sums concurrent decodes together and
25+/// reports work none of them did.
26+struct CountingAlloc;
27+
28+std::thread_local! {
29+ static ALLOC_BYTES: Cell<u64> = const { Cell::new(0) };
30+}
31+
32+fn count_alloc(size: usize) {
33+ let _ = ALLOC_BYTES.try_with(|b| b.set(b.get() + size as u64));
34+}
35+
36+unsafe impl GlobalAlloc for CountingAlloc {
37+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
38+ count_alloc(layout.size());
39+ unsafe { System.alloc(layout) }
40+ }
41+ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
42+ unsafe { System.dealloc(ptr, layout) }
43+ }
44+ unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
45+ count_alloc(new_size);
46+ unsafe { System.realloc(ptr, layout, new_size) }
47+ }
48+}
49+
50+#[global_allocator]
51+static ALLOC: CountingAlloc = CountingAlloc;
52+
53+/// Runs `f` on this thread and returns its value together with every byte
54+/// that thread allocated while it ran. That count is the decoder's own
55+/// work, independent of how fast the host is at moving those bytes around.
56+fn counting_allocations<T>(f: impl FnOnce() -> T) -> (T, u64) {
57+ ALLOC_BYTES.with(|b| b.set(0));
58+ let out = f();
59+ (out, ALLOC_BYTES.with(Cell::get))
60+}
61+
12 const ROUNDS: usize = 10_000;62 const ROUNDS: usize = 10_000;
13 63
14 fn fixtures() -> PathBuf {64 fn fixtures() -> PathBuf {
@@ -364,10 +414,18 @@ fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() {
364 data.extend_from_slice(&60000u16.to_le_bytes());414 data.extend_from_slice(&60000u16.to_le_bytes());
365 data.push(0x00);415 data.push(0x00);
366 416
367- let start = std::time::Instant::now();417+ // Bounded by bytes, not by a clock: this refusal happens before the
368- let err = ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit");418+ // frame sizes anything at all, so the whole decode is a few hundred
369- assert!(start.elapsed().as_millis() < 100, "{:?}", start.elapsed());419+ // bytes of header parsing (measured: 421 B in 2.6 us) whatever the host's
420+ // speed. The old 100 ms clock was a machine-dependent proxy for that.
421+ let (err, allocated) = counting_allocations(|| {
422+ ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit")
423+ });
370 assert!(format!("{err}").contains("limit"), "{err}");424 assert!(format!("{err}").contains("limit"), "{err}");
425+ assert!(
426+ allocated <= 64 * 1024,
427+ "a header-only refusal allocated {allocated} bytes; it must refuse before sizing the frame"
428+ );
371 }429 }
372 430
373 #[test]431 #[test]
@@ -378,14 +436,36 @@ fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget
378 // must be caught by the decode-wide budget even though no single frame436 // must be caught by the decode-wide budget even though no single frame
379 // or single buffer ever looks large by itself.437 // or single buffer ever looks large by itself.
380 let data = one_pixel_gif(16000, 16000, 64);438 let data = one_pixel_gif(16000, 16000, 64);
381- let start = std::time::Instant::now();
382- let err = ec_image::decode_animation(&data)
383- .expect_err("64 clones of a near-limit canvas is past the total budget");
384 // A few real canvas clones run before the budget catches up (the budget439 // A few real canvas clones run before the budget catches up (the budget
385 // is spent per frame, so it can't refuse before at least one clone), so440 // is spent per frame, so it can't refuse before at least one clone), so
386- // this bounds "a handful of gigabyte copies", not "no allocation at all".441+ // this bounds "the decoder's own total budget, not a byte more", not "no
387- assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed());442+ // allocation at all". Bytes, not a clock -- see the counting allocator
443+ // above.
444+ let budget = ec_image::Limits::default().max_total_alloc as u64;
445+ let (err, allocated) = counting_allocations(|| {
446+ ec_image::decode_animation(&data)
447+ .expect_err("64 clones of a near-limit canvas is past the total budget")
448+ });
449+ assert!(format!("{err}").contains("limit"), "{err}");
450+ assert!(
451+ allocated <= budget,
452+ "refused decode allocated {allocated} bytes, past the {budget}-byte total budget"
453+ );
454+
455+ // Size-relative, and the half that pins the guard: 64x the frames in the
456+ // file must not buy 64x the work. A budget spent per *input* frame, or
457+ // after the clone instead of before it, refuses later or not at all as
458+ // the frame count grows.
459+ let bomb = one_pixel_gif(16000, 16000, 4096);
460+ let (err, allocated) = counting_allocations(|| {
461+ ec_image::decode_animation(&bomb)
462+ .expect_err("4096 clones of a near-limit canvas is past the total budget")
463+ });
388 assert!(format!("{err}").contains("limit"), "{err}");464 assert!(format!("{err}").contains("limit"), "{err}");
465+ assert!(
466+ allocated <= budget,
467+ "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget"
468+ );
389 }469 }
390 470
391 #[test]471 #[test]
@@ -476,28 +556,58 @@ fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec<u
476 fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {556 fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() {
477 // The WebP analogue of the GIF test above: `decode_frames` clones the557 // The WebP analogue of the GIF test above: `decode_frames` clones the
478 // whole composited canvas into the result once per ANMF chunk.558 // whole composited canvas into the result once per ANMF chunk.
559+ //
560+ // The bound here is *bytes*, not a clock. What this protects against is
561+ // a guard that stops refusing and lets the clone multiplier run -- 64
562+ // frames over this canvas is 64 GiB of compositing -- and a clock cannot
563+ // express that: it measures the host's memcpy bandwidth, measured at
564+ // 0.75-0.89 s on this desktop host against 3.89 s on a server for
565+ // byte-identical decoder work, which is what reddened the old 2 s
566+ // ceiling.
567+ //
568+ // The byte bound is an INDEPENDENT measurement, not the guard's own
569+ // tally: `AllocBudget::spend` sums DECLARED byte counts at chosen call
570+ // sites, while `counting_allocations` sums the ACTUAL `layout.size()` of
571+ // every allocation (and every realloc's full new size, so an
572+ // incrementally grown Vec contributes more than its final size), plus the
573+ // refusal's own formatting inside the measured window. So "refused at the
574+ // budget" does NOT by itself mean "allocated no more than the budget" --
575+ // and this test's red proof (one clone moved past the spend -> 5.12e9
576+ // bytes against the 4.29e9 budget) is exactly the check that the two
577+ // stay close enough for the budget to be a meaningful ceiling.
578+ let budget = ec_image::Limits::default().max_total_alloc as u64;
479 let data = one_pixel_animated_webp(16000, 16000, 64);579 let data = one_pixel_animated_webp(16000, 16000, 64);
480- let run = || {580+ let (err, allocated) = counting_allocations(|| {
481- let start = std::time::Instant::now();581+ ec_image::decode_animation(&data)
482- let err = ec_image::decode_animation(&data)582+ .expect_err("64 clones of a near-limit canvas is past the total budget")
483- .expect_err("64 clones of a near-limit canvas is past the total budget");583+ });
484- (start.elapsed(), err)584+ assert!(format!("{err}").contains("limit"), "{err}");
485- };585+ assert!(
486- let (mut elapsed, mut err) = run();586+ allocated <= budget,
487- // A miss within 1.5x of the budget can be another lane's parallel test587+ "the refused decode allocated {allocated} bytes, past the {budget}-byte total budget"
488- // threads contending for CPU rather than the refusal itself doing extra588+ );
489- // work: rerun once and keep the faster attempt. A genuine regression589+
490- // (the refusal doing real unbounded work) is slow on both attempts and590+ // Size-relative, and the half that pins the guard: 64x the frames in
491- // still fails below.591+ // the file must not buy 64x the work. A budget spent per *input* frame,
492- if elapsed.as_millis() >= 2000 && elapsed.as_millis() < 3000 {592+ // or after the clone instead of before it, refuses later or not at all
493- let (elapsed2, err2) = run();593+ // as the frame count grows -- and no clock can tell those apart, since
494- if elapsed2 < elapsed {594+ // the work is the same order either way.
495- elapsed = elapsed2;595+ let bomb = one_pixel_animated_webp(16000, 16000, 4096);
496- err = err2;596+ assert!(
497- }597+ bomb.len() > data.len() * 16,
498- }598+ "the second input is meant to be far larger: {} vs {} bytes",
499- assert!(elapsed.as_millis() < 2000, "{elapsed:?}");599+ bomb.len(),
600+ data.len()
601+ );
602+ let (err, allocated) = counting_allocations(|| {
603+ ec_image::decode_animation(&bomb)
604+ .expect_err("4096 clones of a near-limit canvas is past the total budget")
605+ });
500 assert!(format!("{err}").contains("limit"), "{err}");606 assert!(format!("{err}").contains("limit"), "{err}");
607+ assert!(
608+ allocated <= budget,
609+ "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget"
610+ );
501 }611 }
502 612
503 /// Build an LZW-compressed data stream that keeps expanding after the613 /// Build an LZW-compressed data stream that keeps expanding after the
@@ -573,9 +683,16 @@ fn a_gif_lzw_bomb_does_not_expand_past_its_declared_frame() {
573 data.push(0); // sub-block terminator683 data.push(0); // sub-block terminator
574 data.push(0x3B); // trailer684 data.push(0x3B); // trailer
575 685
576- let start = std::time::Instant::now();686+ // The frame declares 4x4, so the decoder may hold 16 indices, a 4-colour
577- let _ = ec_image::decode(&data);687+ // palette and a 4x4 canvas -- kilobytes at most. Unbounded expansion is
578- assert!(start.elapsed().as_secs() < 1, "{:?}", start.elapsed());688+ // hundreds of megabytes. Bytes, not a clock: the same clock-versus-bytes
689+ // split as the budget tests above, and here the signal is much larger
690+ // than any host's speed difference.
691+ let (_out, allocated) = counting_allocations(|| ec_image::decode(&data));
692+ assert!(
693+ allocated <= 1 << 20,
694+ "a 4x4 GIF frame allocated {allocated} bytes; the LZW stream expanded past its frame"
695+ );
579 }696 }
580 697
581 fn crc32(data: &[u8]) -> u32 {698 fn crc32(data: &[u8]) -> u32 {
lanes/ecimagewallclock.report.mdadded+203 -0
@@ -0,0 +1,203 @@
1+# ec-image: replace the WebP budget test's wall clock with a byte bound
2+
3+Lane: `lane/ecimagewallclock`. Touches one file, `crates/ec-image/tests/fuzz.rs`.
4+No shipped-crate change; the counting allocator lives in the test binary only.
5+
6+## The failure
7+
8+`a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget`
9+red on a server host with `3.894534671s` — the panic message *was* the duration,
10+because the assertion's own message was `"{elapsed:?}"`.
11+
12+## What the assertion was protecting against
13+
14+The decode is refused by `AllocBudget::spend` (`lib.rs:201`) the moment the
15+running total crosses `max_total_alloc` (4 GiB by default). What the test
16+protects is that the refusal happens *before* the work: `decode_frames` clones
17+the whole composited canvas once per ANMF chunk, so 64 tiny frames over a
18+16000x16000 canvas is 64 GiB of compositing if the guard stops firing.
19+
20+So the property is **bytes of work performed before the refusal**, which is a
21+deterministic function of `max_total_alloc` and the canvas size. Wall time is
22+not that property. It is the host's memcpy bandwidth for a fixed ~4 GiB of
23+traffic, which is exactly the quantity that differed between the two hosts.
24+
25+## Distribution on this workstation
26+
27+Same case, `one_pixel_animated_webp(16000, 16000, 64)`, 15 runs each:
28+
29+| build | min | median | max | raw (ms) |
30+|---|---|---|---|---|
31+| 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 |
32+| debug | 0.774 s | 0.779 s | 0.821 s | 774 776 776 777 778 779 782 789 792 821 |
33+| server (reported) | — | — | **3.895 s** | — |
34+
35+The desktop/server ratio is ~5x with byte-identical decoder work. A 2000 ms
36+ceiling calibrated on this host has ~2.5x of headroom over its own median —
37+it survives noise here and fails on any host slower than ~2.6x this one. The
38+existing 2000..3000 ms rerun escape hatch does not help: 3.895 s is outside
39+the rerun window, so the test took the slow path straight to the assertion.
40+
41+The old 5 s ceiling on the GIF sibling was in the same class: measured here at
42+0.80 s median, i.e. also a proxy for memcpy bandwidth rather than for work.
43+
44+## Decision
45+
46+Bound the work in **bytes allocated**, measured with a thread-local counting
47+global allocator in the test binary, against the decoder's *own* limit
48+(`Limits::default().max_total_alloc`). No clock survives in these tests.
49+
50+The ceiling is not a fitted constant — it is the guard's own `max_total_alloc`.
51+It is also NOT the same statement as the guard's meaning, and this lane's own
52+red proof is the counterexample: `AllocBudget::spend` sums DECLARED byte
53+counts at chosen call sites, while `counting_allocations` sums the ACTUAL
54+`layout.size()` of every allocation (and every realloc's full new size, so an
55+incrementally grown `Vec` contributes about 2N rather than N), and the refusal
56+path itself formats an `Error` inside the measured window. The two diverge:
57+relocating `spend` one clone later produced 5120024246 bytes against a
58+4294967296-byte budget — a decode that refused "at the total budget" allocated
59+more than it. So the byte bound is best described as an independent
60+measurement of actual work performed, and the red proofs as tests of the
61+correspondence between the declared budget and actual allocation — which is
62+the stronger and more accurate framing.
63+
64+The tally deliberately keeps measuring total allocation TRAFFIC (realloc's
65+full new size included) rather than switching to net-live bytes or deltas:
66+the host difference this class exists to measure is memcpy bandwidth, which
67+is a property of traffic, not of liveness. So the divergence above is the
68+measurement doing its job, not an error to close.
69+
70+Two additional facts fall out of the byte measurement for free:
71+
72+- **Size-relative.** The cost must not grow with the attacker's frame count, so
73+ each budget test decodes both a 64-frame and a 4096-frame file and bounds
74+ both. A guard spent per *input* frame, or after the clone instead of before
75+ it, is caught here; a clock cannot distinguish those, since the work is the
76+ same order of magnitude either way.
77+- **Red before the work, for cheap refusals.** The two header-refusal tests get
78+ a tight bound (64 KiB) expressing "refused before sizing anything"; measured
79+ 421 B for the 60000x60000 GIF frame.
80+
81+## Proof, both ways
82+
83+### Green here
84+
85+`cargo test -p ec-image` scoped, all three binaries:
86+
87+- `fuzz`: 18 passed
88+- `differential`: 19 passed
89+- `real_library`: 2 passed
90+
91+### Green under emulated slowness
92+
93+The persistent shell wedged under the load generators, so the load ran as
94+detached `Bun.spawn` processes and the test binary was invoked directly.
95+
96+Two mechanisms, because the decode is memcpy-bound and the server failure was a
97+memory-subsystem difference, not just a clock difference:
98+
99+1. 16 CPU spinners on 12 cores + 6 `dd oflag=direct` memory hammers.
100+2. The same plus 24 spinners and 10 more hammers (1-minute load average 46).
101+
102+The concurrency figures (spinners, hammers, load average 46) are INFERRED from
103+elapsed times, not recorded alongside the runs: the shell wedged, the load ran
104+as detached processes, and the two coincide by construction, not by measurement.
105+The elapsed numbers above are the measured part; the process counts are the
106+reconstructed part, and the distinction matters because a reader could
107+otherwise take "load 46 while the test ran" as a single observed fact.
108+
109+Under mechanism 1, decode elapsed measured **1.46–1.75 s**; under mechanism 2,
110+**2.42 / 6.30 / 7.31 / 8.91 / 9.26 / 9.34 s**. That range straddles and then
111+clears the old 2000 ms ceiling, so the old assertion is reproduced failing
112+locally.
113+
114+The new tests under that same load:
115+
116+| test | result |
117+|---|---|
118+| webp budget | ok — 6.94 s, 9.44 s, 13.81 s |
119+| gif budget | ok — 6.39 s, 10.73 s |
120+| lzw bomb | ok — 0.03 s |
121+| gif pixels | ok — 0.00 s |
122+
123+Green at wall times 3–7x past the point where the old ceiling went red, which
124+is the point: the assertion no longer reads the clock.
125+
126+**What this covers:** contention, CPU starvation, and memory-bandwidth
127+pressure — the three mechanisms by which a host makes identical decoder work
128+take longer. **What it does not cover:** a genuinely slower *implementation*
129+(such as a build without memcpy optimizations), or hardware faults outside the
130+emulated axis. It does not need to: the byte bound is invariant to all of them
131+by construction, and the emulated runs exist to show the *old* bound was
132+host-dependent, not to certify the new one against hardware I do not have.
133+
134+### Red against a genuine regression
135+
136+The guard moved one line — `budget.spend` relocated from *before* the
137+`frames.push` clone to *after* it, so exactly one canvas clone too many happens
138+before the budget trips:
139+
140+```
141+the refused decode allocated 5120024246 bytes, past the 4294967296-byte total budget
142+```
143+
144+One extra 1 GiB canvas clone, and the test reds on the byte bound.
145+
146+The same mutation measured through the old instrument: **1.006 s median
147+(1.004–1.010 s)**, comfortably *under* the 2000 ms ceiling — the clock
148+assertion would have passed a real regression. That is the measurement that
149+decides the question: the clock does not discriminate the regression it was
150+written for, and the byte bound does.
151+
152+A second mutation (guard spent only on the first frame, so it never trips at
153+all) was killed by the memguard cgroup at 10 GiB — SIGKILL before any
154+assertion. That is evidence about the MUTATION's severity, not a red proof of
155+the byte bound: the byte assertion never ran, and the memguard cgroup would
156+catch an unbounded process with or without this lane. The first mutation is
157+the only red proof of the bound.
158+
159+### Non-vacuity
160+
161+The refusal is still asserted on both inputs (`err` must contain `limit`), the
162+bound still discriminates a one-clone regression (above), and the 4096-frame
163+input is checked to be genuinely larger first, so the size-relative arm cannot
164+pass by comparing a file to itself.
165+
166+## Class sweep
167+
168+Same defect class (clock as a proxy for bounded decode work) elsewhere in the
169+same file, all converted on the same evidence:
170+
171+| line | was | now | measured |
172+|---|---|---|---|
173+| webp budget | `< 2000 ms` + 2000..3000 rerun | `<= max_total_alloc` bytes, 64 and 4096 frames | 4.096 GB vs 4.295 GB |
174+| gif budget | `< 5 s` | `<= max_total_alloc` bytes, 64 and 4096 frames | 4.096 GB vs 4.295 GB |
175+| gif pixels | `< 100 ms` | `<= 64 KiB` bytes | 421 B |
176+| gif lzw bomb | `< 1 s` | `<= 1 MiB` bytes | far under; unbounded would be hundreds of MB |
177+
178+`real_library.rs` also has clocks, but they are differential-decoder
179+comparisons that print timings rather than assert on them — not this class,
180+left alone.
181+
182+## Implementation note
183+
184+The byte tally is **per-thread**, not a global atomic. `cargo test` runs these
185+tests in parallel, and a shared counter summed concurrent decodes together —
186+the first attempt reported 6144529702 bytes for a decode that allocates
187+4096023126, because two tests' work was added together. Both budget tests
188+failed on that. Per-thread `Cell<u64>` counts only the calling thread's
189+allocations, and needs no arm/disarm flag.
190+
191+## Notes
192+
193+- Scratch probe (`crates/ec-image/examples/wallclock_probe.rs`) and the load
194+ script were removed; the diff is the test file only.
195+- An earlier pass of these edits leaked into the primary checkout via a
196+ relative path from the worktree cwd; reverted there with
197+ `git checkout -- crates/ec-image/tests/fuzz.rs` and redone against the
198+ absolute worktree path. The primary checkout is clean apart from the
199+ untracked `.wt/` directory.
200+- For the record, `crates/ec-image` is now clock-free for this class: the only
201+ remaining `elapsed()` uses feed `eprintln` rather than assertions, and the
202+ one sub-millisecond comparison that remains is on GIF frame-delay metadata,
203+ not on measured time.
\ No newline at end of file\ No newline at end of file