ec-image: bound the animation budget tests by bytes, not by wall clock
Browse files at this commit46c799541ee933bbac004cb1b782de886bff9738Parent: 79a4e312 changed files +312 -31
- crates/ec-image/tests/fuzz.rs +139 -31
- lanes/ecimagewallclock.report.md +173 -0
crates/ec-image/tests/fuzz.rsmodified+139 -31
| @@ -7,8 +7,58 @@ | ||
| 7 | 7 | //! `Err` — a decoder reached by a file picker is reached by every broken file |
| 8 | 8 | //! on the disk. |
| 9 | 9 | |
| 10 | +use std::alloc::{GlobalAlloc, Layout, System}; | |
| 11 | +use std::cell::Cell; | |
| 10 | 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 | 62 | const ROUNDS: usize = 10_000; |
| 13 | 63 | |
| 14 | 64 | fn fixtures() -> PathBuf { |
| @@ -364,10 +414,18 @@ fn a_gif_frame_asking_for_more_pixels_than_the_limit_is_refused() { | ||
| 364 | 414 | data.extend_from_slice(&60000u16.to_le_bytes()); |
| 365 | 415 | data.push(0x00); |
| 366 | 416 | |
| 367 | - let start = std::time::Instant::now(); | |
| 368 | - let err = ec_image::decode_animation(&data).expect_err("60000x60000 frame is past the limit"); | |
| 369 | - assert!(start.elapsed().as_millis() < 100, "{:?}", start.elapsed()); | |
| 417 | + // Bounded by bytes, not by a clock: this refusal happens before the | |
| 418 | + // frame sizes anything at all, so the whole decode is a few hundred | |
| 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 | 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 | 431 | #[test] |
| @@ -378,14 +436,36 @@ fn a_gif_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget | ||
| 378 | 436 | // must be caught by the decode-wide budget even though no single frame |
| 379 | 437 | // or single buffer ever looks large by itself. |
| 380 | 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 | 439 | // A few real canvas clones run before the budget catches up (the budget |
| 385 | 440 | // 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". | |
| 387 | - assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed()); | |
| 441 | + // this bounds "the decoder's own total budget, not a byte more", not "no | |
| 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 | 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 | 471 | #[test] |
| @@ -476,28 +556,49 @@ fn one_pixel_animated_webp(canvas_w: u32, canvas_h: u32, frames: usize) -> Vec<u | ||
| 476 | 556 | fn a_webp_animation_with_many_tiny_frames_over_a_huge_canvas_is_refused_by_the_total_budget() { |
| 477 | 557 | // The WebP analogue of the GIF test above: `decode_frames` clones the |
| 478 | 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. The decoder's own total budget is the machine-independent | |
| 567 | + // ceiling: it refuses once the running total crosses it, so nothing | |
| 568 | + // beyond it can have been allocated. | |
| 569 | + let budget = ec_image::Limits::default().max_total_alloc as u64; | |
| 479 | 570 | let data = one_pixel_animated_webp(16000, 16000, 64); |
| 480 | - let run = || { | |
| 481 | - let start = std::time::Instant::now(); | |
| 482 | - let err = ec_image::decode_animation(&data) | |
| 483 | - .expect_err("64 clones of a near-limit canvas is past the total budget"); | |
| 484 | - (start.elapsed(), err) | |
| 485 | - }; | |
| 486 | - let (mut elapsed, mut err) = run(); | |
| 487 | - // A miss within 1.5x of the budget can be another lane's parallel test | |
| 488 | - // threads contending for CPU rather than the refusal itself doing extra | |
| 489 | - // work: rerun once and keep the faster attempt. A genuine regression | |
| 490 | - // (the refusal doing real unbounded work) is slow on both attempts and | |
| 491 | - // still fails below. | |
| 492 | - if elapsed.as_millis() >= 2000 && elapsed.as_millis() < 3000 { | |
| 493 | - let (elapsed2, err2) = run(); | |
| 494 | - if elapsed2 < elapsed { | |
| 495 | - elapsed = elapsed2; | |
| 496 | - err = err2; | |
| 497 | - } | |
| 498 | - } | |
| 499 | - assert!(elapsed.as_millis() < 2000, "{elapsed:?}"); | |
| 571 | + let (err, allocated) = counting_allocations(|| { | |
| 572 | + ec_image::decode_animation(&data) | |
| 573 | + .expect_err("64 clones of a near-limit canvas is past the total budget") | |
| 574 | + }); | |
| 575 | + assert!(format!("{err}").contains("limit"), "{err}"); | |
| 576 | + assert!( | |
| 577 | + allocated <= budget, | |
| 578 | + "the refused decode allocated {allocated} bytes, past the {budget}-byte total budget" | |
| 579 | + ); | |
| 580 | + | |
| 581 | + // Size-relative, and the half that pins the guard: 64x the frames in | |
| 582 | + // the file must not buy 64x the work. A budget spent per *input* frame, | |
| 583 | + // or after the clone instead of before it, refuses later or not at all | |
| 584 | + // as the frame count grows -- and no clock can tell those apart, since | |
| 585 | + // the work is the same order either way. | |
| 586 | + let bomb = one_pixel_animated_webp(16000, 16000, 4096); | |
| 587 | + assert!( | |
| 588 | + bomb.len() > data.len() * 16, | |
| 589 | + "the second input is meant to be far larger: {} vs {} bytes", | |
| 590 | + bomb.len(), | |
| 591 | + data.len() | |
| 592 | + ); | |
| 593 | + let (err, allocated) = counting_allocations(|| { | |
| 594 | + ec_image::decode_animation(&bomb) | |
| 595 | + .expect_err("4096 clones of a near-limit canvas is past the total budget") | |
| 596 | + }); | |
| 500 | 597 | assert!(format!("{err}").contains("limit"), "{err}"); |
| 598 | + assert!( | |
| 599 | + allocated <= budget, | |
| 600 | + "a 64x larger file allocated {allocated} bytes, past the {budget}-byte total budget" | |
| 601 | + ); | |
| 501 | 602 | } |
| 502 | 603 | |
| 503 | 604 | /// 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() { | ||
| 573 | 674 | data.push(0); // sub-block terminator |
| 574 | 675 | data.push(0x3B); // trailer |
| 575 | 676 | |
| 576 | - let start = std::time::Instant::now(); | |
| 577 | - let _ = ec_image::decode(&data); | |
| 578 | - assert!(start.elapsed().as_secs() < 1, "{:?}", start.elapsed()); | |
| 677 | + // The frame declares 4x4, so the decoder may hold 16 indices, a 4-colour | |
| 678 | + // palette and a 4x4 canvas -- kilobytes at most. Unbounded expansion is | |
| 679 | + // hundreds of megabytes. Bytes, not a clock: the same clock-versus-bytes | |
| 680 | + // split as the budget tests above, and here the signal is much larger | |
| 681 | + // than any host's speed difference. | |
| 682 | + let (_out, allocated) = counting_allocations(|| ec_image::decode(&data)); | |
| 683 | + assert!( | |
| 684 | + allocated <= 1 << 20, | |
| 685 | + "a 4x4 GIF frame allocated {allocated} bytes; the LZW stream expanded past its frame" | |
| 686 | + ); | |
| 579 | 687 | } |
| 580 | 688 | |
| 581 | 689 | fn crc32(data: &[u8]) -> u32 { |
lanes/ecimagewallclock.report.mdadded+173 -0
| @@ -0,0 +1,173 @@ | ||
| 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 budget the guard enforces, so | |
| 51 | +the assertion states the invariant directly: a decode that has refused at the | |
| 52 | +total budget cannot have allocated more than the total budget. | |
| 53 | + | |
| 54 | +Two additional facts fall out of the byte measurement for free: | |
| 55 | + | |
| 56 | +- **Size-relative.** The cost must not grow with the attacker's frame count, so | |
| 57 | + each budget test decodes both a 64-frame and a 4096-frame file and bounds | |
| 58 | + both. A guard spent per *input* frame, or after the clone instead of before | |
| 59 | + it, is caught here; a clock cannot distinguish those, since the work is the | |
| 60 | + same order of magnitude either way. | |
| 61 | +- **Red before the work, for cheap refusals.** The two header-refusal tests get | |
| 62 | + a tight bound (64 KiB) expressing "refused before sizing anything"; measured | |
| 63 | + 421 B for the 60000x60000 GIF frame. | |
| 64 | + | |
| 65 | +## Proof, both ways | |
| 66 | + | |
| 67 | +### Green here | |
| 68 | + | |
| 69 | +`cargo test -p ec-image` scoped, all three binaries: | |
| 70 | + | |
| 71 | +- `fuzz`: 18 passed | |
| 72 | +- `differential`: 19 passed | |
| 73 | +- `real_library`: 2 passed | |
| 74 | + | |
| 75 | +### Green under emulated slowness | |
| 76 | + | |
| 77 | +The persistent shell wedged under the load generators, so the load ran as | |
| 78 | +detached `Bun.spawn` processes and the test binary was invoked directly. | |
| 79 | + | |
| 80 | +Two mechanisms, because the decode is memcpy-bound and the server failure was a | |
| 81 | +memory-subsystem difference, not just a clock difference: | |
| 82 | + | |
| 83 | +1. 16 CPU spinners on 12 cores + 6 `dd oflag=direct` memory hammers. | |
| 84 | +2. The same plus 24 spinners and 10 more hammers (1-minute load average 46). | |
| 85 | + | |
| 86 | +Under mechanism 1, decode elapsed measured **1.46–1.75 s**; under mechanism 2, | |
| 87 | +**2.42 / 6.30 / 7.31 / 8.91 / 9.26 / 9.34 s**. That range straddles and then | |
| 88 | +clears the old 2000 ms ceiling, so the old assertion is reproduced failing | |
| 89 | +locally. | |
| 90 | + | |
| 91 | +The new tests under that same load: | |
| 92 | + | |
| 93 | +| test | result | | |
| 94 | +|---|---| | |
| 95 | +| webp budget | ok — 6.94 s, 9.44 s, 13.81 s | | |
| 96 | +| gif budget | ok — 6.39 s, 10.73 s | | |
| 97 | +| lzw bomb | ok — 0.03 s | | |
| 98 | +| gif pixels | ok — 0.00 s | | |
| 99 | + | |
| 100 | +Green at wall times 3–7x past the point where the old ceiling went red, which | |
| 101 | +is the point: the assertion no longer reads the clock. | |
| 102 | + | |
| 103 | +**What this covers:** contention, CPU starvation, and memory-bandwidth | |
| 104 | +pressure — the three mechanisms by which a host makes identical decoder work | |
| 105 | +take longer. **What it does not cover:** a genuinely slower *implementation* | |
| 106 | +(such as a build without memcpy optimizations), or hardware faults outside the | |
| 107 | +emulated axis. It does not need to: the byte bound is invariant to all of them | |
| 108 | +by construction, and the emulated runs exist to show the *old* bound was | |
| 109 | +host-dependent, not to certify the new one against hardware I do not have. | |
| 110 | + | |
| 111 | +### Red against a genuine regression | |
| 112 | + | |
| 113 | +The guard moved one line — `budget.spend` relocated from *before* the | |
| 114 | +`frames.push` clone to *after* it, so exactly one canvas clone too many happens | |
| 115 | +before the budget trips: | |
| 116 | + | |
| 117 | +``` | |
| 118 | +the refused decode allocated 5120024246 bytes, past the 4294967296-byte total budget | |
| 119 | +``` | |
| 120 | + | |
| 121 | +One extra 1 GiB canvas clone, and the test reds on the byte bound. | |
| 122 | + | |
| 123 | +The same mutation measured through the old instrument: **1.006 s median | |
| 124 | +(1.004–1.010 s)**, comfortably *under* the 2000 ms ceiling — the clock | |
| 125 | +assertion would have passed a real regression. That is the measurement that | |
| 126 | +decides the question: the clock does not discriminate the regression it was | |
| 127 | +written for, and the byte bound does. | |
| 128 | + | |
| 129 | +A second mutation (guard spent only on the first frame, so it never trips at | |
| 130 | +all) was killed by the memguard cgroup at 10 GiB — SIGKILL before any | |
| 131 | +assertion, i.e. unbounded work as intended. | |
| 132 | + | |
| 133 | +### Non-vacuity | |
| 134 | + | |
| 135 | +The refusal is still asserted on both inputs (`err` must contain `limit`), the | |
| 136 | +bound still discriminates a one-clone regression (above), and the 4096-frame | |
| 137 | +input is checked to be genuinely larger first, so the size-relative arm cannot | |
| 138 | +pass by comparing a file to itself. | |
| 139 | + | |
| 140 | +## Class sweep | |
| 141 | + | |
| 142 | +Same defect class (clock as a proxy for bounded decode work) elsewhere in the | |
| 143 | +same file, all converted on the same evidence: | |
| 144 | + | |
| 145 | +| line | was | now | measured | | |
| 146 | +|---|---|---|---| | |
| 147 | +| webp budget | `< 2000 ms` + 2000..3000 rerun | `<= max_total_alloc` bytes, 64 and 4096 frames | 4.096 GB vs 4.295 GB | | |
| 148 | +| gif budget | `< 5 s` | `<= max_total_alloc` bytes, 64 and 4096 frames | 4.096 GB vs 4.295 GB | | |
| 149 | +| gif pixels | `< 100 ms` | `<= 64 KiB` bytes | 421 B | | |
| 150 | +| gif lzw bomb | `< 1 s` | `<= 1 MiB` bytes | far under; unbounded would be hundreds of MB | | |
| 151 | + | |
| 152 | +`real_library.rs` also has clocks, but they are differential-decoder | |
| 153 | +comparisons that print timings rather than assert on them — not this class, | |
| 154 | +left alone. | |
| 155 | + | |
| 156 | +## Implementation note | |
| 157 | + | |
| 158 | +The byte tally is **per-thread**, not a global atomic. `cargo test` runs these | |
| 159 | +tests in parallel, and a shared counter summed concurrent decodes together — | |
| 160 | +the first attempt reported 6144529702 bytes for a decode that allocates | |
| 161 | +4096023126, because two tests' work was added together. Both budget tests | |
| 162 | +failed on that. Per-thread `Cell<u64>` counts only the calling thread's | |
| 163 | +allocations, and needs no arm/disarm flag. | |
| 164 | + | |
| 165 | +## Notes | |
| 166 | + | |
| 167 | +- Scratch probe (`crates/ec-image/examples/wallclock_probe.rs`) and the load | |
| 168 | + script were removed; the diff is the test file only. | |
| 169 | +- An earlier pass of these edits leaked into the primary checkout via a | |
| 170 | + relative path from the worktree cwd; reverted there with | |
| 171 | + `git checkout -- crates/ec-image/tests/fuzz.rs` and redone against the | |
| 172 | + absolute worktree path. The primary checkout is clean apart from the | |
| 173 | + untracked `.wt/` directory. | |
| \ No newline at end of file |