Skip to content

feat(spi,esp32): pre-queue alternate-buffer SPI chunk for >680-LED strips (refs #2304) - #2810

Merged
zackees merged 3 commits into
masterfrom
feat/2304-spi-dma-pingpong
Jun 5, 2026
Merged

zackees merged 3 commits into
masterfrom
feat/2304-spi-dma-pingpong

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes the inter-chunk SPI gap that opens when a long WS2812B strip (>~680 LEDs) splits into multiple DMA transactions. The naive ping-pong (queue A → wait → queue B → wait → …) lets the SPI line idle for the host-task latency between chunks. Under RTOS contention that gap can exceed WS2812B's ~50 µs reset threshold and trigger a visible refresh on the strip.

Refs #2304. Hardware byte-equality + on-device timing validation deferred (call-out below).

What changed

`src/platforms/esp/32/drivers/spi/channel_driver_spi.cpp.hpp`:

  • `startFirstDma()` — when async-DMA is in use AND the encoded payload exceeds a single staging buffer, pre-encode and pre-queue buffer B immediately after queuing A. ESP-IDF's SPI driver permits multiple in-flight transactions (dev_config.queue_size = 4 was already in place); the ISR now transitions A → B without any host involvement, eliminating the inter-chunk gap. Cap is 2 in flight to keep the pipeline shallow and predictable.
  • `advancePipeline()` — in-flight detector switched from the single `mPipeline.mDmaInFlight` bool to `transAInFlight || transBInFlight` (refreshed per iteration). When one chunk completes and data remains, the just-freed buffer is refilled and re-queued, maintaining 2-in-flight as long as there's payload.
  • ESP32-C6 split-polling path (`kSpiUsePolling = true`) preserved: `spi_device_polling_start` only allows one in-flight polling transaction at a time. C6 keeps single-queue behavior; benefits from the encode/wait overlap but cannot get ISR-chained gap-free streaming without an ESP-IDF API change. Documented inline.

Tests added

`tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp` (new, ~305 lines) — host-side state-machine tests with no ESP-IDF dependency. Models the buffer-rotation invariants in plain C++ and verifies:

  1. Both A and B are queued for long strips in async mode
  2. Only A is queued for one-chunk strips
  3. Refill-on-completion is ping-pong (whichever finishes first gets refilled)
  4. At most 2 chunks in flight while data remains
  5. Final drain waits for BOTH outstanding before marking the channel complete

Test plan

  • Host-side state-machine tests (the file above)
  • On-device byte equality with the old single-queue behavior — deferred. Needs a real ESP32 + ≥1000-LED WS2812B strip.
  • On-device inter-chunk timing under RTOS contention — the original symptom (>50µs gap triggering refresh) needs to be verified gone on hardware.
    Both via `bash autoresearch --spi` on hardware. Next iteration.

Process note

The agent that drafted this PR was interrupted mid-stream when its `bash test --clean` (running from main checkout instead of the worktree) collided with stop-hook lock contention. The file deltas above are its pre-interruption work product, verified clean in the worktree at `feat/2304-spi-dma-pingpong`; main checkout was reverted of the leaked untracked test file. Recovered manually.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Reduced gaps and fixed overlap for long ESP32 LED strips by improving the SPI DMA streaming pipeline and ensuring correct transition/completion behavior (issue #2304).
    • Harmonized async vs polling behaviors so transfers are queued and completed reliably.
  • Tests

    • Added unit tests validating ping-pong DMA queueing, refill/drain sequences, queue-depth limits, byte accounting, polling vs async paths, and the #2304 regression.

…rips (refs #2304)

Closes the inter-chunk gap that opens when a long strip (>~680 LEDs)
splits into multiple SPI DMA transactions. Today the pipeline queues
chunk A, waits, encodes+queues chunk B from poll(). Between A and B
the SPI line idles for the host-task latency until poll() notices
completion — under RTOS contention that gap can exceed WS2812B's
~50 µs reset threshold and trigger a visible refresh on the strip.

What this does:

- In `startFirstDma()`, when async-DMA is in use AND the encoded
  payload exceeds a single staging buffer, pre-encode and pre-queue
  buffer B right after queuing A. ESP-IDF's SPI driver allows
  multiple in-flight transactions (`dev_config.queue_size = 4` is
  already set); the ISR transitions A → B without host involvement.
  Capped at 2 in flight to keep the pipeline shallow and predictable.

- In `advancePipeline()`, the in-flight detector is now
  `transAInFlight || transBInFlight` (refreshed per iteration) rather
  than the single `mPipeline.mDmaInFlight` boolean. When one chunk
  completes and data remains, the just-freed buffer is refilled and
  re-queued, maintaining 2-in-flight as long as there's payload.

- ESP32-C6 split-polling path (`kSpiUsePolling = true`) only allows
  one in-flight polling transaction at a time, so we keep the
  existing single-queue behaviour there. C6 still benefits from the
  encode/wait overlap but cannot get ISR-chained gap-free streaming
  without an ESP-IDF API change.

- `transAInFlight` / `transBInFlight` per-channel booleans track
  real ESP-IDF state so the completion drain matches whichever
  transaction reported done; no more guessing which slot fired.

Tests (host-side, no ESP-IDF dependency):

- `tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp`
  (new, ~305 lines) models the buffer-rotation invariants in plain C++:
  (1) both A and B queued for long strips in async mode, (2) only A
  queued for one-chunk strips, (3) refill-on-completion is ping-pong,
  (4) at most 2 chunks in flight while data remains, (5) final drain
  waits for both outstanding before marking complete.

NOT validated by this PR (deferred to hardware):

- On-device byte equality with the old single-queue behaviour.
- Inter-chunk timing under RTOS contention (the original symptom).
- Both should be exercised via `bash autoresearch --spi` on real ESP32
  hardware with a ≥1000-LED WS2812B strip — that's the next iteration.

Process note: the agent that drafted this was interrupted mid-stream
when its `bash test --clean` rebuild collided with stop-hook lock
contention on the same shared build directory. The file deltas above
are its pre-interruption work product, verified clean in the worktree;
main checkout has been reverted of the leaked untracked test file.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 5, 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: bf550af7-1a89-4f71-95eb-2f5d67f18215

📥 Commits

Reviewing files that changed from the base of the PR and between 0dcf035 and b19b18b.

📒 Files selected for processing (1)
  • tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp

📝 Walkthrough

Walkthrough

Driver pre-queues a second DMA transaction in async mode and updates STREAMING logic to track both transA/transB in-flight; a host-side PipelineModel and eight tests validate async vs polling behaviors and the #2304 LED-boundary regression.

Changes

SPI DMA Ping-Pong Pipeline Enhancement

Layer / File(s) Summary
Driver pre-queue and in-flight transaction tracking
src/platforms/esp/32/drivers/spi/channel_driver_spi.cpp.hpp
startFirstDma() conditionally encodes and queues transB immediately after transA in async mode and rolls back on queue failure; advancePipeline() STREAMING phase computes anyInFlight from `transAInFlight
Ping-pong pipeline state model and test coverage
tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp
Adds PipelineModel and eight FL_TEST_CASEs covering async single-chunk, async long-strip pre-queue, polling-only path, refill behavior on 3-chunk scenarios, queue-depth cap (<=2), byte-accounting after drain, polling drain counts, and the 682-LED boundary regression (#2304).

Sequence Diagram

sequenceDiagram
  participant Client
  participant Pipeline as SPI_Pipeline
  participant TransA as Transaction_A
  participant TransB as Transaction_B
  participant DMA

  Client->>Pipeline: startFirstDma()
  Pipeline->>Pipeline: encode Chunk A -> stagingA
  Pipeline->>TransA: queue transA
  Pipeline->>DMA: submit transA
  alt async mode && more data
    Pipeline->>Pipeline: encode Chunk B -> stagingB
    Pipeline->>TransB: queue transB
    Pipeline->>DMA: submit transB
    Pipeline->>Pipeline: set transBInFlight
  end
  
  loop advancePipeline() STREAMING
    Client->>Pipeline: stepStreaming()
    Pipeline->>Pipeline: anyInFlight = transAInFlight || transBInFlight
    alt anyInFlight
      Pipeline->>DMA: drain one completion
      Pipeline->>Pipeline: refill freed staging buffer (encode next chunk)
      Pipeline->>Pipeline: re-evaluate anyInFlight
    end
  end
  
  alt no more data && anyInFlight
    Pipeline->>Client: transition to COMPLETING / drain remaining
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Poem

🐰 I pre-queue with nimble paws tonight,
Two buffers primed to keep the colors bright,
Ping then pong, the DMA hums in tune,
No gaps between each glowing rune,
Rabbity hops, LEDs alight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% 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 clearly and concisely describes the main change: pre-queuing alternate SPI buffers for long ESP32 LED strips to fix issue #2304.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 feat/2304-spi-dma-pingpong

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Infer (1.2.0)
tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp

tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp:25:10: fatal error: 'fl/stl/cstddef.h' file not found
25 | #include "fl/stl/cstddef.h"
| ^~~~~~~~~~~~~~~~~~
1 error generated.
Error: the following clang command did not run successfully:
/opt/infer-linux-x86_64-v1.2.0/lib/infer/facebook-clang-plugins/clang/install/bin/clang-18
@/tmp/coderabbit-infer/b19b18b9f2cdbd1bed8f3ad30f9c66d70eec8de9-9d948ea0bf82c7ec/tmp/clang_command_.tmp.9b00aa.txt
++Contents of '/tmp/coderabbit-infer/b19b18b9f2cdbd1bed8f3ad30f9c66d70eec8de9-9d948ea0bf82c7ec/tmp/clang_command_.tmp.9b00aa.txt':
"-cc1" "-load"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../../facebook-clang-plugins/libtooling/build/FacebookClangPlugin.dylib"
"-add-plugin" "BiniouASTExporter" "-plugin-arg-BiniouASTExporter" "-"
"-plugin-arg-BiniouASTExporter" "PREPEND_CURRENT_DIR=1"
"-plugin-arg-BiniouASTExporter" "MAX_STRING_SIZE=65535" "-cc1" "-triple"
"x86_64-unknown-l

... [truncated 1178 characters] ...

l-isystem" "/usr/local/include" "-internal-isystem"
"/usr/lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
"-internal-externc-isystem" "/usr/include/x86_64-linux-gnu"
"-internal-externc-isystem" "/include" "-internal-externc-isystem"
"/usr/include" "-Wno-ignored-optimization-argument" "-Wno-everything"
"-fdeprecated-macro" "-ferror-limit" "19" "-fgnuc-version=4.2.1"
"-fskip-odr-check-in-gmf" "-fcxx-exceptions" "-fexceptions"
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o"
"/tmp/coderabbit-infer/9d948ea0bf82c7ec/file.o" "-x" "c++"
"tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp"
"-O0" "-fno-builtin" "-include"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../lib/clang_wrappers/global_defines.h"
"-Wno-everything"


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.

Actionable comments posted: 2

🤖 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.

Inline comments:
In `@src/platforms/esp/32/drivers/spi/channel_driver_spi.cpp.hpp`:
- Around line 1503-1525: The code pre-consumes the second LED chunk by calling
encodeChunk into ch->stagingB and decrementing ch->ledBytesRemaining/advancing
ledSource before verifying spiStart succeeded, so if spiStart fails the chunk is
lost; modify the logic around encodeChunk/ch->stagingB and spiStart so you only
commit the consumption when spiStart returns ESP_OK (i.e. set ch->transBInFlight
= true and mPipeline.mEncodeIdx = 2 and actually decrement
ch->ledBytesRemaining/advance ledSource after successful spiStart), or if you
must encode early then on spiStart failure restore state by pushing the bytes in
ch->stagingB back into the ledSource, incrementing ch->ledBytesRemaining
accordingly and leaving mPipeline.mEncodeIdx unchanged; ensure
flags/transBInFlight are only set on success (functions/fields to touch:
encodeChunk, spiStart, ch->stagingB, ch->stagingCapacity, ch->ledBytesRemaining,
ledSource handling, ch->transBInFlight, mPipeline.mEncodeIdx).

In `@tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp`:
- Around line 289-300: The test's boundary is off: 681 LEDs still fit in one
chunk so adjust the second case to use 683 LEDs (2049 LED bytes) so
PipelineModel::make(/*bytes=*/2049, ...) triggers two chunks; update the comment
math and change the assertion on big.queuedCount in the FL_TEST_CASE("Ping-pong
- 680-LED boundary regression (`#2304`)") to expect 2 after calling
big.startFirstDma(), referencing PipelineModel::make and startFirstDma to locate
the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d0c939fa-acc5-456b-a26b-1282dbcb8a4a

📥 Commits

Reviewing files that changed from the base of the PR and between 787de45 and 82e7bbc.

📒 Files selected for processing (2)
  • src/platforms/esp/32/drivers/spi/channel_driver_spi.cpp.hpp
  • tests/platforms/esp/32/drivers/spi/spi_pingpong_pipeline_logic.cpp

- channel_driver_spi.cpp.hpp: roll back ledSource/ledBytesRemaining if
  spiStart(transB) fails in the new startFirstDma() pre-queue path so the
  consumed chunk is re-encoded by the refill loop instead of being dropped
  (truncating the stream after A).
- spi_pingpong_pipeline_logic.cpp: fix the boundary-regression test math.
  A 16 KB staging buffer fits exactly 2048 LED bytes (~682 RGB LEDs), so
  the previous "681 LED → 2 chunks" case (2043 < 2048) still fit in one
  chunk. Bump the small case to 2046 bytes and the big case to 2049 bytes
  so the assertion actually exercises the pre-queue path. Rename the test
  to "682-LED boundary regression" and update the comment.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ncodeIdx (refs #2304)

The model's `stepStreaming` was choosing the refill buffer via
`encodeIdx & 1`, which produces a strict A/B alternation independent of
which buffer actually completed. With the FIFO drain rule ("A first if
both in flight"), the parity-driven refill could write into a buffer
that was still in flight — losing the original queue's identity and
leaving one queue undrained at end-of-stream.

Reproduction: the "all bytes accounted for after drain" test with
TOTAL_BYTES = 12345 produced `queuedCount=25, completedCount=24` —
exactly one chunk lost in the model.

Fix: record which buffer the drain freed and target the refill there.
That matches the real ESP-IDF SPI driver's per-buffer tracking — each
staging buffer is queued independently and the refill goes to whichever
slot just freed up. The encodeIdx counter is preserved as a queue
counter but no longer drives buffer selection.

CI failure on the original PR's CI run validates the fix path:
> FAIL: Ping-pong - all bytes accounted for after drain
>   spi_pingpong_pipeline_logic.cpp:255: 25 == 24

After the fix: queued and completed counters match at end-of-stream.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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.

1 participant