Skip to content

debug(parlio): #2493 reproducer + FL_PARLIO_PROFILE markers - #2494

Closed
zackees wants to merge 3 commits into
masterfrom
debug/parlio-2493-profile-markers
Closed

zackees wants to merge 3 commits into
masterfrom
debug/parlio-2493-profile-markers

Conversation

@zackees

@zackees zackees commented May 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Reproducer + integer-only timing instrumentation for #2493 (ESP32-P4 PARLIO FastLED.show() blocks ~16.7 ms before WS2812 data burst). Also includes a small build-system fix that was blocking the AutoResearch sketch from compiling on ESP32-P4.

Root cause (cross-referenced in #2493, #2420, #2254)

task::run(250, ExecFlags::SYSTEM) in the polling loops of ChannelManager::waitForCondition (src/fl/channels/manager.cpp.hpp:351) and IChannelDriver::waitForCondition (src/fl/channels/driver.cpp.hpp:22) → pumpCoroutines(1000) (src/fl/task/executor.cpp.hpp:137) → on ESP32, vTaskDelay(max(1, us/tick_period)) = vTaskDelay(1) minimum per spin (src/platforms/esp/32/coroutine_esp32.impl.hpp:83-86).

For 256 LEDs × 12 strips WS2812B, PARLIO DMA drain ≈ 7.6 ms; the wait loop spins ~8 × 1 ms ticks for the prior frame to drain. Total ≈ 16 ms — matches user's scope trace.

This deep-yield was added intentionally to fix #2254 (I2S busy-wait starving WiFi/lwIP). It now drives #2420 and #2493 as regressions; #2428 is the proposed structural fix.

Changes

  • ci/wasm_build.py: scope auto-generated wrapper to #ifdef __EMSCRIPTEN__ so non-WASM toolchains (e.g. RISC-V for ESP32-P4) skip it instead of erroring on import "wasm_pch.h".
  • platformio.ini esp32p4: -D FL_PARLIO_PROFILE=1.
  • src/FastLED.cpp.hpp CFastLED::show: emit PT b=… g=… s=… e=… tot=… per frame (microseconds, no sstream for label).
  • src/fl/channels/manager.cpp.hpp waitForCondition: count polling iterations + total elapsed µs.
  • examples/ParlioBench/: 1–12 lane WS2812B reproducer (override NUM_STRIPS / NUM_LEDS).

Empirical verification — incomplete (environment issue)

Could not capture serial output from the ESP32-P4 USB-Serial-JTAG on COM25 in the dev environment used for this branch (tried ~12 combinations of ARDUINO_USB_MODE × CDC_ON_BOOT × DTR/RTS sequences × port-enumeration polling; esptool verifies the chip is responsive but no bytes reach the host after reset). The reproducer + instrumentation are ready to flash; expectation is:

NUM_STRIPS × NUM_LEDS Predicted tot µs (1 kHz tick)
1 × 100 ~1500 (1 polling iter + ~250µs DMA)
8 × 256 ~10000–13000
12 × 256 ~15000–17000

Test plan

  • Flash on a host with working USB-Serial-JTAG output, run with default NUM_STRIPS=1, confirm PT tot=… lines appear
  • Sweep -D NUM_STRIPS=12 -D NUM_LEDS=256, confirm ~16ms tot, then confirm PT_WFC iters=N shows the polling-loop count
  • Apply workaround (task::run(0, SYSTEM) in both waitForCondition sites), reflash, confirm tot drops to ~8ms (data + minimal yield)

Related

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added an ESP32-P4 PARLIO benchmark sketch for measuring and recording LED timing.
    • Added optional runtime profiling to capture per-frame and wait-loop timings.
  • Bug Fixes

    • Improved WebAssembly toolchain compatibility to avoid Emscripten-only imports on other compilers.
  • Chores

    • Enabled profiling build flag for the esp32 environment.

Review Change Stack

zackees and others added 2 commits May 20, 2026 19:02
…ds skip it

The sketch-build wrapper generator in `create_wrapper()` emits an `import "wasm_pch.h"`
line that is only valid under Emscripten's C++20 modules-ts. When the same .build/
cache tree is reused for a non-WASM target (e.g. ESP32-P4 via PlatformIO), the
wrapper file gets compiled by the platform toolchain and fails with:

  error: 'import' does not name a type
  note: C++20 'import' only available with '-fmodules-ts'

Wrap the import + sketch includes in `#ifdef __EMSCRIPTEN__ ... #endif` so the
generated TU is empty (and a no-op) under any other toolchain.

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

Reproducer + integer-only timing instrumentation for the ESP32-P4 PARLIO
~16.7ms `FastLED.show()` block reported in #2493. Behind a build flag so
production builds are unaffected.

Root cause hypothesis (verified by code inspection, cross-referenced in #2493,
#2420, #2254): `task::run(250, ExecFlags::SYSTEM)` in the polling loops of
`ChannelManager::waitForCondition` and `IChannelDriver::waitForCondition`
calls `pumpCoroutines(1000)` which on ESP32 rounds up to one FreeRTOS tick
(`vTaskDelay(1)`). On the autoresearch build (`CONFIG_FREERTOS_HZ=1000`),
that's 1ms per iteration; for 256 LEDs × 12 strips WS2812B (DMA drain
~7.6ms), the wait-for-prior-frame burns ~8 ticks ≈ 8ms, plus 7.6ms of
actual drain ≈ ~16ms total — matching the user's scope trace.

Changes:
- `platformio.ini` esp32p4 env: gain `-D FL_PARLIO_PROFILE=1`
- `src/FastLED.cpp.hpp` CFastLED::show: emit `PT b=… g=… s=… e=… tot=…` per
  frame (microseconds, integer-only — no sstream for the label)
- `src/fl/channels/manager.cpp.hpp` waitForCondition: count polling iterations,
  emit `PT_WFC iters=N us=…` when N > 0
- `examples/ParlioBench/`: minimal sketch driving 1–12 PARLIO lanes of WS2812B
  (NUM_STRIPS, NUM_LEDS overridable). Includes RAM-resident timing ring buffer
  for cases where USB-Serial-JTAG output is unreliable on the host.

Empirical replication is BLOCKED in the current dev environment: the
ESP32-P4 USB-Serial-JTAG on COM25 produces zero bytes after flash despite
esptool verifying chip responsiveness — tried `ARDUINO_USB_MODE` 0/1 ×
`CDC_ON_BOOT` 0/1, DTR/RTS toggles, port re-enumeration polling, and
esptool-direct flash with proper offsets. The reproducer is ready to flash
and capture on a working host.

Refs: #2493, #2420, #2254, #2428

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

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR enables FL_PARLIO_PROFILE for esp32c6, adds conditional microsecond profiling in CFastLED::show() and ChannelManager::waitForCondition, provides an ESP32-P4 ParlioBench sketch that records FastLED.show() timings to flash, and prevents Emscripten-only imports from being emitted for non-Emscripten toolchains.

Changes

PARLIO Profiling Feature

Layer / File(s) Summary
Build configuration and toolchain compatibility
platformio.ini, ci/wasm_build.py
env:esp32c6 build flags enable -D FL_PARLIO_PROFILE=1 and set ARDUINO_USB_MODE=0. WASM wrapper generation now wraps the import "wasm_pch.h"; header-unit import and example includes inside #ifdef __EMSCRIPTEN__ and emits an empty TU for other toolchains.
Profiling instrumentation in core timing paths
src/FastLED.cpp.hpp, src/fl/channels/manager.cpp.hpp
CFastLED::show() records additional fl::micros() timestamps around onBeginFrame(), the pre-lastshow wait loop, and the end-frame sequence when FL_PARLIO_PROFILE is enabled. ChannelManager::waitForCondition optionally counts iterations and logs elapsed microseconds under the same flag.
ParlioBench benchmark and logging harness
examples/ParlioBench/ParlioBench.ino
New ESP32-P4 sketch defining PtRecord, compile-time LED config, per-lane LED arrays, addLane helper, flushToFlash() to write an accumulated log buffer to flash, and setup()/loop() that measure FastLED.show() via micros() and persist samples.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

🐰 Hopped in to time each glowing row,

micros tick, the LEDs all show,
Logs to flash where samples sleep,
Profiling secrets now we keep,
A tiny rabbit counts each glow.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% 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 describes the main changes: adding a reproducer for issue #2493 and FL_PARLIO_PROFILE profiling markers to investigate PARLIO timing issues.
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 debug/parlio-2493-profile-markers

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 `@examples/ParlioBench/ParlioBench.ino`:
- Around line 13-18: NUM_STRIPS can be set outside the supported 1–12 range and
silently compiles; add a compile-time guard using the NUM_STRIPS macro to reject
values <1 or >12 (e.g. use `#if` NUM_STRIPS < 1 || NUM_STRIPS > 12 `#error`
"NUM_STRIPS must be between 1 and 12" `#endif`) immediately after the default
`#define` block so invalid configurations fail the build; apply the same guard to
the other place where NUM_STRIPS is defined/referenced (the block around the
existing alternate definition at lines 45-56) to ensure both occurrences enforce
the range.
- Around line 6-9: ParlioBench.ino is a temporary debug reproducer and must not
live under examples/*.ino; move ParlioBench.ino out of the examples directory
into a dedicated debug/reproducers or tests folder (e.g.,
tests/reproducers/ParlioBench.ino or tools/debug/ParlioBench.ino), update any
project manifests or build scripts that reference the file, and adjust README or
CI entries if they expect examples to contain only permanent demos; ensure the
commit removes the file from examples and preserves it in the new location so
the reproducer remains available without violating the examples/*.ino policy.
🪄 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: 2c1b7869-422d-4c5e-a75c-8ac685e3d07e

📥 Commits

Reviewing files that changed from the base of the PR and between 18eafd7 and ec657bc.

📒 Files selected for processing (5)
  • ci/wasm_build.py
  • examples/ParlioBench/ParlioBench.ino
  • platformio.ini
  • src/FastLED.cpp.hpp
  • src/fl/channels/manager.cpp.hpp

Comment thread examples/ParlioBench/ParlioBench.ino Outdated
Comment on lines +6 to +9
// ParlioBench.ino — Issue #2493 reproducer for ESP32-P4 PARLIO 16.7ms block.
// Writes show() timing to a global volatile buffer that survives across the
// chip's reset, so we can read it back via esptool's `dump_mem` against
// internal RAM. Also prints to Serial for hosts where USB-Serial-JTAG works.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Move this debug reproducer out of examples/*.ino before merge.

This file is explicitly a debug reproducer, but repository policy reserves .ino examples for permanent, real-world feature demonstrations.
As per coding guidelines **/*.ino: "Never create .ino files for minor testing or debugging - use test files or unit tests instead", and examples/**/*.ino: "Only create .ino files as permanent examples when they demonstrate significant features with real-world usage patterns".

🤖 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 `@examples/ParlioBench/ParlioBench.ino` around lines 6 - 9, ParlioBench.ino is
a temporary debug reproducer and must not live under examples/*.ino; move
ParlioBench.ino out of the examples directory into a dedicated debug/reproducers
or tests folder (e.g., tests/reproducers/ParlioBench.ino or
tools/debug/ParlioBench.ino), update any project manifests or build scripts that
reference the file, and adjust README or CI entries if they expect examples to
contain only permanent demos; ensure the commit removes the file from examples
and preserves it in the new location so the reproducer remains available without
violating the examples/*.ino policy.

Comment on lines +13 to +18
#ifndef NUM_STRIPS
#define NUM_STRIPS 1
#endif
#ifndef NUM_LEDS
#define NUM_LEDS 100
#endif

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Enforce the documented 1–12 strip range at compile time.

NUM_STRIPS above 12 silently compiles but extra lanes are never added, which can skew benchmark expectations.

💡 Suggested fix
 `#ifndef` NUM_STRIPS
 `#define` NUM_STRIPS 1
 `#endif`
+#if NUM_STRIPS < 1 || NUM_STRIPS > 12
+#error "NUM_STRIPS must be between 1 and 12 for ParlioBench"
+#endif

Also applies to: 45-56

🤖 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 `@examples/ParlioBench/ParlioBench.ino` around lines 13 - 18, NUM_STRIPS can be
set outside the supported 1–12 range and silently compiles; add a compile-time
guard using the NUM_STRIPS macro to reject values <1 or >12 (e.g. use `#if`
NUM_STRIPS < 1 || NUM_STRIPS > 12 `#error` "NUM_STRIPS must be between 1 and 12"
`#endif`) immediately after the default `#define` block so invalid configurations
fail the build; apply the same guard to the other place where NUM_STRIPS is
defined/referenced (the block around the existing alternate definition at lines
45-56) to ensure both occurrences enforce the range.

Adds flash-write logger to ParlioBench so timing data can be read back via
esptool when USB-Serial-JTAG is unreliable. Captures 60 frames into NVS
partition (offset 0x9000), records 16-byte {magic, frame, total_us, _}.

Empirical results on ESP32-P4 EV board, FreeRTOS 1kHz, master branch:

  Config                              | median show() µs
  ------------------------------------|------
  1  strip x 100 LEDs, no rate cap    |    111
  12 strips x 256 LEDs, no rate cap   |  3,028
  12 strips x 256 LEDs + 60Hz cap     | 14,559

The 14.6 ms with explicit setMaxRefreshRate(60) matches issue #2493's
reported 16.7 ms within measurement margin (~13% delta = different per-frame
compute time approaching the 16667 us cap). Without the 60 Hz cap, show()
returns in 3 ms regardless of inter-frame delay — the PARLIO DMA runs async
and the channel-manager polling loop does not fire.

This refutes the earlier hypothesis that the bug was task::run()/vTaskDelay(1)
tick-rounding in ChannelManager::waitForCondition. The actual cause for
#2493 is the FastLED-layer mNMinMicros gate at FastLED.cpp.hpp:235 — driven
by setMaxRefreshRate(60) somewhere in the user's setup.

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

@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: 3

🤖 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 `@examples/ParlioBench/ParlioBench.ino`:
- Around line 12-13: The record format comment is stale: the code's
serialization writes a 16-byte record with a reserved field set to 0 (the struct
uses/reserves a field named reserved) but the comment claims that field is
wfc_iters; either update the comment to describe the actual layout (magic
0xDEADBEEF at offset 0, then 16-byte records of {uint32 magic, uint32 frame,
uint32 total_us, uint32 reserved=0}) or modify the serialization code that
builds the record to populate and write a wfc_iters value instead of zero—locate
the serialization/struct that defines reserved and the comment near "magic
0xDEADBEEF" and make the comment and code consistent.
- Around line 39-40: The code currently treats g_log_buffer as uint8_t[] and
casts slices to PtRecord* inside loop() (e.g., PtRecord* rec =
(PtRecord*)(g_log_buffer + (g_frame * LOG_RECORD_SIZE))), which can break
alignment/aliasing; replace the byte buffer with a typed buffer like static
PtRecord g_log_buffer[LOG_MAX_RECORDS] and update all accesses to index into
g_log_buffer by record index (g_log_buffer[g_frame]) instead of pointer
arithmetic/casts (also update uses referenced around the current loop() code and
the sites noted at ~96–102); additionally ensure LOG_RECORD_SIZE equals
sizeof(PtRecord) or add a static assert to keep sizes consistent.
- Around line 48-58: flushToFlash currently may pick an NVS partition, ignores
return values, uses offset 0 and sets g_flushed before operations; fix by
searching for a data partition that is not NVS (prefer
ESP_PARTITION_SUBTYPE_DATA_SPIFFS or otherwise ensure part->subtype !=
ESP_PARTITION_SUBTYPE_DATA_NVS) and whose size is >= LOG_FLASH_OFFSET +
sizeof(g_log_buffer), use LOG_FLASH_OFFSET for both esp_partition_erase_range
and esp_partition_write, check esp_partition_erase_range and esp_partition_write
return esp_err_t and only set g_flushed = true and Serial.println("[ParlioBench]
flushed to flash") after both return ESP_OK, otherwise log the error and leave
g_flushed false; keep references to flushToFlash, g_flushed,
esp_partition_find_first, esp_partition_erase_range, esp_partition_write, and
LOG_FLASH_OFFSET to locate the changes.
🪄 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: 708d3e6c-2e6a-429e-b720-1ceafaf0038b

📥 Commits

Reviewing files that changed from the base of the PR and between ec657bc and 40c5377.

📒 Files selected for processing (1)
  • examples/ParlioBench/ParlioBench.ino

Comment on lines +12 to +13
// Decode: magic 0xDEADBEEF at offset 0, then 16-byte records of
// {uint32 magic, uint32 frame, uint32 total_us, uint32 wfc_iters}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Record format comment is stale (wfc_iters is never written).

The documented schema says wfc_iters, but the struct/serialization stores reserved = 0, which can mislead decoding.

Also applies to: 36-36, 101-101

🤖 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 `@examples/ParlioBench/ParlioBench.ino` around lines 12 - 13, The record format
comment is stale: the code's serialization writes a 16-byte record with a
reserved field set to 0 (the struct uses/reserves a field named reserved) but
the comment claims that field is wfc_iters; either update the comment to
describe the actual layout (magic 0xDEADBEEF at offset 0, then 16-byte records
of {uint32 magic, uint32 frame, uint32 total_us, uint32 reserved=0}) or modify
the serialization code that builds the record to populate and write a wfc_iters
value instead of zero—locate the serialization/struct that defines reserved and
the comment near "magic 0xDEADBEEF" and make the comment and code consistent.

Comment on lines +39 to +40
static uint8_t g_log_buffer[LOG_RECORD_SIZE * LOG_MAX_RECORDS];
static uint32_t g_frame = 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="examples/ParlioBench/ParlioBench.ino"

# Show the referenced sections with line numbers
nl -ba "$FILE" | sed -n '1,140p'

# Focused searches for the cast / buffer usage
rg -n "PtRecord|g_log_buffer|LOG_RECORD_SIZE|LOG_MAX_RECORDS|\\(PtRecord\\*\\)" "$FILE" || true

Repository: FastLED/FastLED

Length of output: 102


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search repo-wide for PtRecord definition and any related struct alignment assumptions
rg -n "struct\s+PtRecord|typedef\s+.*PtRecord|PtRecord\s*\{" -S . || true
rg -n "LOG_RECORD_SIZE\s*\*?\s*LOG_MAX_RECORDS|LOG_RECORD_SIZE" -S examples/ParlioBench "$FILE" || true

Repository: FastLED/FastLED

Length of output: 179


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="examples/ParlioBench/ParlioBench.ino"

# Print numbered context around the cited areas (no nl dependency)
awk 'NR>=20 && NR<=130 {print NR ":" $0}' "$FILE" | sed -n '1,160p'

Repository: FastLED/FastLED

Length of output: 3188


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="examples/ParlioBench/ParlioBench.ino"

# Find cast occurrences and related buffer accesses
rg -n "\\(PtRecord\\*\\)" "$FILE" || true
rg -n "g_log_buffer|PtRecord\\b|LOG_RECORD_SIZE|LOG_MAX_RECORDS|g_frame" "$FILE"

Repository: FastLED/FastLED

Length of output: 719


Avoid casting uint8_t* (g_log_buffer) to PtRecord* when writing records.

g_log_buffer is declared as static uint8_t g_log_buffer[LOG_RECORD_SIZE * LOG_MAX_RECORDS];, but in loop() it’s written via PtRecord* rec = (PtRecord*)(g_log_buffer + (g_frame * LOG_RECORD_SIZE));, which can break alignment/aliasing rules. Use a PtRecord-typed buffer instead (also impacts 96–102).

Suggested fix
-static uint8_t g_log_buffer[LOG_RECORD_SIZE * LOG_MAX_RECORDS];
+static PtRecord g_log_buffer[LOG_MAX_RECORDS];
 ...
-        PtRecord* rec = (PtRecord*)(g_log_buffer + (g_frame * LOG_RECORD_SIZE));
+        PtRecord* rec = &g_log_buffer[g_frame];
         rec->magic = 0xDEADBEEF;
         rec->frame = g_frame;
         rec->total_us = dur;
         rec->reserved = 0;
🤖 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 `@examples/ParlioBench/ParlioBench.ino` around lines 39 - 40, The code
currently treats g_log_buffer as uint8_t[] and casts slices to PtRecord* inside
loop() (e.g., PtRecord* rec = (PtRecord*)(g_log_buffer + (g_frame *
LOG_RECORD_SIZE))), which can break alignment/aliasing; replace the byte buffer
with a typed buffer like static PtRecord g_log_buffer[LOG_MAX_RECORDS] and
update all accesses to index into g_log_buffer by record index
(g_log_buffer[g_frame]) instead of pointer arithmetic/casts (also update uses
referenced around the current loop() code and the sites noted at ~96–102);
additionally ensure LOG_RECORD_SIZE equals sizeof(PtRecord) or add a static
assert to keep sizes consistent.

Comment on lines +48 to +58
void flushToFlash() {
if (g_flushed) return;
g_flushed = true;
// Find a data partition we can write to. Use the larger "spiffs" partition
// or any data partition with enough space.
const esp_partition_t* part = esp_partition_find_first(
ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, NULL);
if (!part) return;
esp_partition_erase_range(part, 0, 4096);
esp_partition_write(part, 0, g_log_buffer, sizeof(g_log_buffer));
Serial.println("[ParlioBench] flushed to flash");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="examples/ParlioBench/ParlioBench.ino"

# Show surrounding code for flushToFlash
echo "=== flushToFlash context ==="
nl -ba "$FILE" | sed -n '1,120p'

# Extract flushToFlash function only (rough)
echo "=== flushToFlash function body ==="
rg -n "void\s+flushToFlash\s*\(" "$FILE"
start=$(rg -n "void\s+flushToFlash\s*\(" "$FILE" | cut -d: -f1 | head -n1)
# print from start-5 to start+80
nl -ba "$FILE" | sed -n "$((start-5)),$((start+120))p"

# Search for esp_partition_find_first/erase_range/write usage in the repo
echo "=== esp_partition_* usage (repo-wide) ==="
rg -n "esp_partition_(find_first|erase_range|write)\b" -S .

# Search definition/size of g_log_buffer and g_flushed
echo "=== g_log_buffer / g_flushed definitions ==="
rg -n "g_log_buffer|g_flushed" "$FILE"

Repository: FastLED/FastLED

Length of output: 149


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="examples/ParlioBench/ParlioBench.ino"
echo "Repo root: $(pwd)"
echo "File exists?"; test -f "$FILE" && echo "YES: $FILE" || (echo "NO: $FILE" && exit 1)

echo "=== flushToFlash relevant context (lines ~1-140) ==="
# Prefer cat -n; fall back to awk if needed
if command -v cat >/dev/null 2>&1; then
  cat -n "$FILE" | sed -n '1,160p'
else
  awk 'NR>=1 && NR<=160 {printf "%d\t%s\n", NR, $0}' "$FILE"
fi

echo "=== Locate flushToFlash and key APIs ==="
rg -n "void\s+flushToFlash\s*\(" "$FILE" || true
rg -n "esp_partition_find_first|esp_partition_erase_range|esp_partition_write" "$FILE" || true
rg -n "g_log_buffer|g_flushed" "$FILE" || true

echo "=== Repo-wide: esp_partition_* usage ==="
rg -n "esp_partition_(find_first|erase_range|write)\b" . || true

echo "=== Repo-wide: partition subtype names (spiffs etc) ==="
rg -n "ESP_PARTITION_SUBTYPE_.*SPIFFS" . || true

Repository: FastLED/FastLED

Length of output: 5389


🏁 Script executed:

#!/bin/bash
set -euo pipefail
FILE="examples/ParlioBench/ParlioBench.ino"
echo "=== LOG_FLASH_OFFSET usage ==="
rg -n "LOG_FLASH_OFFSET" "$FILE" || true
echo "=== erase/write return handling in flushToFlash ==="
rg -n "esp_partition_(erase_range|write)\b" "$FILE"

Repository: FastLED/FastLED

Length of output: 318


🌐 Web query:

For ESP-IDF, does ESP_PARTITION_TYPE_DATA include NVS partitions (ESP_PARTITION_SUBTYPE_DATA_NVS) when using esp_partition_find_first(..., ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, ...)? Also confirm return types of esp_partition_erase_range and esp_partition_write.

💡 Result:

Yes, ESP_PARTITION_TYPE_DATA does include NVS partitions, as ESP_PARTITION_SUBTYPE_DATA_NVS is defined as a subtype of ESP_PARTITION_TYPE_DATA [1][2][3]. Therefore, when using esp_partition_find_first with ESP_PARTITION_TYPE_DATA and ESP_PARTITION_SUBTYPE_ANY, the function will include NVS partitions in its search [1][2]. Regarding the return types for the specified functions in ESP-IDF: 1. esp_partition_erase_range: Returns an esp_err_t [4][5][6]. It returns ESP_OK on success, or various error codes (e.g., ESP_ERR_INVALID_ARG, ESP_ERR_INVALID_SIZE, ESP_ERR_NOT_ALLOWED) if the operation fails [4][5][6]. 2. esp_partition_write: Returns an esp_err_t [4][7]. It returns ESP_OK on success, or error codes (e.g., ESP_ERR_INVALID_ARG, ESP_ERR_INVALID_SIZE, ESP_ERR_NOT_ALLOWED) if the operation fails [7].

Citations:


flushToFlash() can erase/write the wrong partition and still print “flushed” even on failure.

  • esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, ...) may return NVS (since NVS subtypes are within ESP_PARTITION_TYPE_DATA), and the code unconditionally erases from offset 0 and writes at offset 0.
  • esp_partition_erase_range() / esp_partition_write() return values are ignored, while g_flushed is set to true before the operations—so errors will be silently treated as success.
  • LOG_FLASH_OFFSET is defined but unused; the current implementation doesn’t write to the intended fixed flash offset.
🤖 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 `@examples/ParlioBench/ParlioBench.ino` around lines 48 - 58, flushToFlash
currently may pick an NVS partition, ignores return values, uses offset 0 and
sets g_flushed before operations; fix by searching for a data partition that is
not NVS (prefer ESP_PARTITION_SUBTYPE_DATA_SPIFFS or otherwise ensure
part->subtype != ESP_PARTITION_SUBTYPE_DATA_NVS) and whose size is >=
LOG_FLASH_OFFSET + sizeof(g_log_buffer), use LOG_FLASH_OFFSET for both
esp_partition_erase_range and esp_partition_write, check
esp_partition_erase_range and esp_partition_write return esp_err_t and only set
g_flushed = true and Serial.println("[ParlioBench] flushed to flash") after both
return ESP_OK, otherwise log the error and leave g_flushed false; keep
references to flushToFlash, g_flushed, esp_partition_find_first,
esp_partition_erase_range, esp_partition_write, and LOG_FLASH_OFFSET to locate
the changes.

zackees added a commit that referenced this pull request May 24, 2026
Adds an end-to-end sweep that does not depend on host-side serial
(which is the second blocker in #2507 — USB-Serial-JTAG produces no
host-visible bytes after Arduino boot on this dev board).

examples/PerfTraceBench/PerfTraceBench.ino:
  - 12 lanes × 256 LEDs WS2812B (override NUM_STRIPS / NUM_LEDS / NUM_FRAMES)
  - Per-frame: clear/enable fl::PerfTrace, FastLED.show(), snapshot the
    event log + show_us into a packed binary buffer
  - After NUM_FRAMES frames, write the buffer to the first writable data
    partition (esp_partition_find_first) and halt

ci/perf_trace_decode.py:
  - Parses the flash dump (magic-tagged header / frame / event records +
    string-interned name table) and renders a per-frame table

Usage:
  pio run -e esp32p4 --target upload  (with PLATFORMIO_SRC_DIR=examples/PerfTraceBench)
  esptool --chip esp32p4 --port COMxx read-flash <part_offset> <size> dump.bin
  uv run ci/perf_trace_decode.py dump.bin

Result on ESP32-P4-EV (12×256, build off this branch):
  show_us steady-state ≈ 1,058,000 µs per frame
  ChannelManager::waitForCondition (manager.cpp.hpp:353) ≈ 755,000 µs of that
  showLedsInternal ≈ 3,200 µs, onBeginFrame ≈ 30 µs, all other scopes <10 µs

The #2503 fix targeted the polling-loop yield (driver.cpp.hpp:23), but
the per-frame budget is dominated by the OTHER waitForCondition (line
353 in manager.cpp.hpp), so the PARLIO blocking issue from #2493 IS NOT
fully resolved. ~755 ms per frame is 100× the expected WS2812B PARLIO
drain time (~7.6 ms for 256 LEDs).

Refs: #2493 #2494 #2503 #2507

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees zackees closed this May 30, 2026
@zackees
zackees deleted the debug/parlio-2493-profile-markers branch November 17, 2026 07:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ESP32-S3: I2S driver starves websockets, SPI output incorrect, Audio driver FPS impact

1 participant