Skip to content

fix(wave): prevent i32 overflow in Q15 Courant*Laplacian multiply (refs #3073) - #3083

Merged
zackees merged 2 commits into
masterfrom
fix/wave-q15-overflow
Jun 15, 2026
Merged

zackees merged 2 commits into
masterfrom
fix/wave-q15-overflow

Conversation

@zackees

@zackees zackees commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

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.hpp multiplied mCourantSq32 (i32) by the 5-point Laplacian (i32) and then shifted right by 15 for Q15 normalization. Worst-case operands:

max |Laplacian| max |mCourantSq32| max product i32 max
1D ~131,070 32,767 ~4.30e9 2.15e9
2D ~262,140 32,767 ~8.59e9 2.15e9

Default speed = 0.16 (the typical 0.1–0.3 range documented on WaveFx) keeps the product safely inside i32. But setSpeed(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-sign term that the subsequent Q15 clamp could not detect. Result: visible glitches and instability.

What this PR changes

Two-layer fix:

  1. Promote the inner-loop multiply to i64 before the >> 15 shift 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.
  2. Clamp setSpeed / constructor speed to 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)
    • Negative speed is also clamped to 0 (no physical meaning).

The header doc comments on the constructor + setSpeed now 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 behind WaveFx. 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

  • Default speed = 0.16 is unaffected.
  • Public WaveFx API and WaveSimulation (super-sampled wrapper) are unchanged.
  • Only callers explicitly passing speed > 0.5 to the 2D class (or > 1.0 to 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_real passes (5/5 cases) on host.
  • bash lint --cpp clean.
  • No source-side caller breakage — only the super-sampled wrapper instantiates these classes via fl::make_unique, which forwards transparently.
  • CI: full host test sweep + WASM build (Linux runner, no Windows zccache flake).

Out of scope (deferred follow-ups from #3073)

  • §2 — Damping division → arithmetic shift (perf, AVR/M0 hot path)
  • §3 — Fold half-duplex pass into the main update loop
  • §4 — Branchless Q15 clamp + hoisted indexing + __restrict__
  • §5 — 9-point isotropic Laplacian (super-sampled mode, opt-in)
  • §6 — Precomputed Q15 damping multiplier
  • §7 — SIMD kernels (host SSE2/AVX2, ESP32-S3 PIE, Teensy 4 DSP)

Closes #3073

Summary by CodeRabbit

  • Bug Fixes
    • Improved wave simulation stability by clamping speed inputs to the supported Courant/CFL ranges (1D: 0.0–1.0, 2D: 0.0–0.5)
    • Prevented intermediate arithmetic overflow during the Courant×Laplacian computation, reducing invalid-value risk
  • Tests
    • Added regression coverage for clamping behavior and numerical stability at the CFL limit, including multi-step impulse scenarios
  • Documentation
    • Clarified speed semantics and the exact stability bounds used by both 1D and 2D simulations

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).
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1327c676-2f56-4144-857d-c3552f28f3c4

📥 Commits

Reviewing files that changed from the base of the PR and between c2b3aa4 and dbe8261.

📒 Files selected for processing (1)
  • src/fl/math/wave/wave_simulation_real.cpp.hpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/fl/math/wave/wave_simulation_real.cpp.hpp

📝 Walkthrough

Walkthrough

WaveSimulation1D_Real and WaveSimulation2D_Real now clamp the Courant-squared speed input to their CFL stability bounds ([0,1] and [0,0.5]) in both constructors and setSpeed. The Q15 Laplacian multiply in each update() is widened to i64 before the right-shift to prevent i32 overflow. Constructors gain FL_NOEXCEPT. A new regression test file covers clamping behavior and numerical stability under worst-case saturated inputs.

Changes

WaveSimulation Q15 Overflow Fix and CFL Clamping

Layer / File(s) Summary
Header declarations and documentation update
src/fl/math/wave/wave_simulation_real.h
Adds FL_NOEXCEPT to both constructors; updates speed parameter docs to describe Courant-squared Q15 semantics and CFL clamp ranges ([0,1] for 1D, [0,0.5] for 2D) for constructors and setSpeed.
CFL clamping and i64 overflow fix
src/fl/math/wave/wave_simulation_real.cpp.hpp
Clamps courantSq in the 1D constructor and setSpeed to [0,1]; clamps speed in the 2D constructor and setSpeed to [0,0.5]. In both update() methods, promotes the Q15 Laplacian multiply operand to i64 before the >> 15 shift and casts back to i32, eliminating the latent overflow.
Regression tests for clamping and overflow stability
tests/fl/math/wave/wave_simulation_real.cpp
New test file covering setSpeed clamping to CFL bound endpoints for both 1D and 2D; single-step saturated checkerboard tests verifying all i16 results stay in the Q15 [-32768, 32767] range; 32-step 2D impulse test confirming no sample escapes Q15 bounds across time.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Bits were growing, wide and free,
An i32 too small to be!
Now i64 holds the sum,
CFL clamps keep waves from going numb.
No overflow, no broken art—
The ripples dance with stable heart! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing i32 overflow in Q15 Courant*Laplacian multiplication in the wave simulation code, with reference to the linked issue.
Linked Issues check ✅ Passed The PR fully addresses item §1 (overflow correctness) from issue #3073 by promoting multiply to i64 and clamping speed to CFL bounds for both 1D and 2D, with comprehensive test coverage for the overflow fix.
Out of Scope Changes check ✅ Passed All changes are directly scoped to item §1 (overflow fix) from issue #3073; no perf optimizations (§2–§4), algorithmic changes (§5–§6), or SIMD work (§7) are included as deferred per audit recommendations.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/wave-q15-overflow

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/fl/math/wave/wave_simulation_real.cpp.hpp (1)

274-280: 💤 Low value

Minor: 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 maximum mCourantSq32 is 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

📥 Commits

Reviewing files that changed from the base of the PR and between c8fca96 and c2b3aa4.

📒 Files selected for processing (3)
  • src/fl/math/wave/wave_simulation_real.cpp.hpp
  • src/fl/math/wave/wave_simulation_real.h
  • tests/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.
@zackees
zackees merged commit 15393b8 into master Jun 15, 2026
6 of 7 checks passed
@zackees
zackees deleted the fix/wave-q15-overflow branch June 15, 2026 18:18
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 15, 2026
zackees added a commit that referenced this pull request Jun 16, 2026
…#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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

audit(wave/diff-eq): overflow risk + perf wins in WaveSimulation Q15 stencil (behind WaveFx)

1 participant