Repository navigation
fix(wave): prevent i32 overflow in Q15 Courant*Laplacian multiply (refs #3073) - #3083
Conversation
The explicit leapfrog wave PDE solver behind WaveFx multiplied
mCourantSq32 (i32) by the 5-point Laplacian (i32) before shifting
right by 15 for Q15 normalization. Worst-case |laplacian| in 2D is
~262,140 (saturated checkerboard) and ~131,070 in 1D. With speed
near the public API ceiling that pushed the product past INT32_MAX
(~2.15e9), wrapping to a wrong-sign term that the post-clamp could
not detect.
Two-layer fix:
1. Promote the multiply to i64 before the >>15 shift in both 1D
and 2D update() kernels. This is the safety net.
2. Clamp setSpeed/constructor speed to the CFL stability bound at
the API boundary (1D: [0, 1.0], 2D: [0, 0.5]). Values outside
the CFL limit were visually unstable anyway, so silently
clamping is the safer behavior.
Header docs updated to advertise the clamped public range. New
host-side test (tests/fl/math/wave/wave_simulation_real.cpp) covers
both the setter clamp contract and the kernel's behavior under
saturated input at the CFL boundary (single-step + 32-step impulse
response).
Default speed=0.16 (typical 0.1-0.3 range per the WaveFx header
comment) is unaffected. Only callers passing speed > 0.5 to the
2D class or > 1.0 to the 1D class see a behavior change.
Closes #3073
Refs the audit issue's "Suggested execution order" section: this
PR addresses item §1 only. Items §2-§4 (perf bundle: damp shift,
half-duplex fold-in, branchless clamp) and §5-§7 (algorithmic /
SIMD options) are deferred to follow-up PR(s).
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthrough
ChangesWaveSimulation Q15 Overflow Fix and CFL Clamping
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/fl/math/wave/wave_simulation_real.cpp.hpp (1)
274-280: 💤 Low valueMinor: overflow magnitude comment overstates worst case by 2×.
The comment states the product "can reach ~8.6e9", but that magnitude assumes
mCourantSq32= 32767 (Q15 encoding of 1.0). With the 2D CFL clamp at 0.5 (lines 176, 182), the actual maximummCourantSq32is 16383, yielding a worst-case product of ~4.3e9, which still overflows i32 (max 2.15e9) and justifies the i64 promotion.Suggest revising the comment to reflect the clamped worst case for clarity:
// Promote to i64 before the multiply: worst-case |laplacian| in // 2D is ~262,140 (saturated checkerboard), so the i32 product // |mCourantSq32 * laplacian| can reach ~4.3e9 (at CFL bound 0.5) // which overflows i32 (max 2.15e9). The i64 intermediate prevents // that latent overflow.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/fl/math/wave/wave_simulation_real.cpp.hpp` around lines 274 - 280, The comment describing the worst-case overflow scenario in the i64 promotion block incorrectly states the product can reach ~8.6e9, when accounting for the 2D CFL clamp at 0.5 (which limits mCourantSq32 to 16383), the actual worst case is ~4.3e9. Update the comment to correct this magnitude estimate to ~4.3e9 and explicitly mention the CFL bound of 0.5 to reflect the actual clamped constraint, making the comment more accurate and informative for future maintainers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/fl/math/wave/wave_simulation_real.cpp.hpp`:
- Around line 274-280: The comment describing the worst-case overflow scenario
in the i64 promotion block incorrectly states the product can reach ~8.6e9, when
accounting for the 2D CFL clamp at 0.5 (which limits mCourantSq32 to 16383), the
actual worst case is ~4.3e9. Update the comment to correct this magnitude
estimate to ~4.3e9 and explicitly mention the CFL bound of 0.5 to reflect the
actual clamped constraint, making the comment more accurate and informative for
future maintainers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b91cee71-e723-4b9a-8c34-f2ace1a26f2e
📒 Files selected for processing (3)
src/fl/math/wave/wave_simulation_real.cpp.hppsrc/fl/math/wave/wave_simulation_real.htests/fl/math/wave/wave_simulation_real.cpp
…clamp worst case CodeRabbit nit on #3083: the previous comment quoted the pre-clamp worst-case product magnitude (8.6e9 in 2D) as if it were the current state. With the CFL clamp now in place, the worst-case product is actually ~4.3e9 in both 1D and 2D — still well past i32 max (2.15e9), so the i64 promote is still required. Update both 1D and 2D comments to: 1. State the current (post-clamp) worst case explicitly. 2. Note that the i64 promote also serves as a safety net if the clamp is ever regressed (pre-clamp the 2D product really did reach ~8.6e9 — the bug we're fixing). No semantic change; comments only.
…#3116) First slice of the wave2d perf pipeline. Adds a device-side RPC handler in AutoResearchRemote.cpp that: - Constructs a fl::WaveSimulation2D_Real of requested W x H - Seeds it with a deterministic checkerboard at +/-0.5 (avoids the +/-1.0 float_to_fixed asymmetry noted in #3083) - Optionally warms up to prime caches - Times `iterations` calls to update() using fl::micros() - Returns { total_us, us_per_update, us_per_cell_per_update, fps_at_one_update_per_frame } Args (JSON-RPC): { W: 32, H: 32, // grid dimensions iterations: 100, // measurement window stencil: "NinePointIsotropic" | "FivePoint", loads_only: false // memory-bound baseline mode } `loads_only=true` swaps update() for a memory-bound baseline (reads every inner cell into a volatile sink) — the gap between the two results isolates memory cost from compute cost. This is critical for the ESP32-S3 PSRAM-vs-SRAM analysis tracked in sibling issue #3114. Input validation: refuses W/H outside [4, 1024] and iterations outside [1, 100000] — defensive against bad RPC payloads (e.g. accidentally requesting a multi-MB grid). What's NOT in this PR (deliberately): - Host-side `bash autoresearch <board> --wave2d-perf <W>x<H>` flag (Task 1 continuation). Will be a follow-up that wires the Python side to invoke this RPC and format the comparison table. - Sanity calibration probes (Task 2 of #3113). Filed as the next slice. - Compact O(h^4) stencil (research doc top recommendation). Filed separately so the perf benchmark is in place first. Refs #3113 Task 1. Verified by `bash compile wasm --examples AutoResearch` (build clean).
Addresses item §1 from #3073 (the latent correctness bug). Defers §2–§7 to follow-up PR(s) per the issue's stated execution order.
What was broken
wave_simulation_real.cpp.hppmultipliedmCourantSq32(i32) by the 5-point Laplacian (i32) and then shifted right by 15 for Q15 normalization. Worst-case operands:Default
speed = 0.16(the typical 0.1–0.3 range documented onWaveFx) keeps the product safely inside i32. ButsetSpeed(float)accepts values up to 1.0, so any caller pushing speed above ~0.25 with near-saturated grid cells could wrap to a wrong-signtermthat the subsequent Q15 clamp could not detect. Result: visible glitches and instability.What this PR changes
Two-layer fix:
i64before the>> 15shift in both 1D (update()line ~125) and 2D (update()line ~259). This is the safety net — even if the API clamp regresses, the kernel cannot overflow.setSpeed/ constructorspeedto the CFL stability bound at the API boundary:WaveSimulation1D_Real: speed ∈ [0.0, 1.0] (CFL bound for the 1D 5-point stencil)WaveSimulation2D_Real: speed ∈ [0.0, 0.5] (CFL bound for the 2D 5-point stencil)The header doc comments on the constructor +
setSpeednow advertise the clamped public range so callers know what to expect.Tests
New host-side test file
tests/fl/math/wave/wave_simulation_real.cpp— note that the wave PDE solver had zero prior test coverage despite being the math behindWaveFx. Five cases:WaveSimulation2D_Real clamps speed to CFL bound [0, 0.5]— verifies the setter contract.WaveSimulation1D_Real clamps speed to CFL bound [0, 1.0]— same for 1D.WaveSimulation2D_Real survives saturated checkerboard at max CFL— single-step kernel guard with worst-case Laplacian input.WaveSimulation1D_Real survives saturated checkerboard at max CFL— same for 1D.WaveSimulation2D_Real stays bounded across many steps at CFL bound— 32-step impulse response, confirms no accumulated overflow destabilizes the system.Compatibility
speed = 0.16is unaffected.WaveFxAPI andWaveSimulation(super-sampled wrapper) are unchanged.speed > 0.5to the 2D class (or> 1.0to the 1D class) see a behavior change — and those values were producing unstable output anyway per the von Neumann stability analysis.Test plan
bash test fl_math_wave_wave_simulation_realpasses (5/5 cases) on host.bash lint --cppclean.fl::make_unique, which forwards transparently.Out of scope (deferred follow-ups from #3073)
__restrict__Closes #3073
Summary by CodeRabbit