Skip to content

feat(perf-trace): thread-local push/pop perf tracing + PARLIO sweep instrumentation - #2508

Closed
zackees wants to merge 4 commits into
masterfrom
feat/perf-trace
Closed

zackees wants to merge 4 commits into
masterfrom
feat/perf-trace

Conversation

@zackees

@zackees zackees commented May 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Continuing the work from #2494 — adds a thread-local Chrome-trace-style fl::PerfTrace framework and wires FL_PERF_SCOPE markers through CFastLED::show and the PARLIO hot path. Combined with two new JSON-RPCs in the AutoResearch sketch (setPerfTraceEnabled, getPerfTraceLog) and a ci/perf_trace_sweep.py driver, this lets autoresearch flip tracing on at runtime, run a PARLIO test, and pull a per-frame event log to verify whether the ~16 ms blocking issue from #2493 is fully resolved by the #2503 vTaskDelay-floor fix.

Replaces the ad-hoc FL_PARLIO_PROFILE=1 markers from PR #2494 with a reusable framework — subsequent drivers can be instrumented by sprinkling FL_PERF_SCOPE("name") without bespoke timing boilerplate.

Changes

src/fl/system/perf_trace.{h,cpp.hpp} (new)

  • Per-thread in-flight stack (FixedVector<PerfEvent,32>) and completed-event log (FixedVector<PerfEvent,128>) held in SingletonThreadLocal.
  • PerfEvent captures (file*, name*, line, depth, start_us, end_us); string pointers are non-owning literals (__FILE__ + macro arg).
  • Compile gate FASTLED_PERF_TRACE; runtime gate fl::PerfTrace::set_enabled(bool). When either is off, macros are no-ops with zero overhead.
  • Macros: FL_PERF_SCOPE(name) (RAII), FL_PERF_BEGIN(name) / FL_PERF_END(slot) (manual), FL_PERF_FRAME_FLUSH().
  • flush() emits one FL_INFO line per event (PT d=N dur_us=X start_us=Y name=Z @file:L) or routes via a user callback. dropped() flag surfaces overflow without corrupting the log.

Instrumentation (CFastLED::show + PARLIO hot path)

  • src/FastLED.cpp.hpp — outer show scope + nested onBeginFrame, min_micros_gate, showLedsInternal, endShowLeds.
  • src/fl/channels/manager.cpp.hpp, src/fl/channels/driver.cpp.hpp — waitForCondition scopes in the two polling loops (the deep-yield sites from ESP32-P4 PARLIO: FastLED.show() appears to block for ~16.7 ms before WS2812 data burst begins #2493).
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp — scopes in Impl::poll, Impl::beginTransmission, outer poll, beginClocklessTransmission.

AutoResearch sketch + autoresearch driver

  • examples/AutoResearch/AutoResearchRemote.cpp: setPerfTraceEnabled(bool) flips capture and clears on disable; getPerfTraceLog() returns events as compact [depth, dur_us, start_us, name, file, line] tuples and clears the log.
  • platformio.ini esp32p4 env: -D FASTLED_PERF_TRACE=1 (capture stays off at boot — autoresearch flips the runtime switch). Also flips ARDUINO_USB_MODE=1 → 0 to route Serial to the JTAG port the dev board actually exposes as COM* on Windows (same call-out as PR debug(parlio): #2493 reproducer + FL_PARLIO_PROFILE markers #2494).
  • ci/perf_trace_sweep.py (new) — pyserial-based driver script that calls setPerfTraceEnabled(true) → runTest (PARLIO) → getPerfTraceLog() and prints a table or JSON.

Tests

tests/fl/system/perf_trace.hpp (10 cases, all green):

  • disabled by default after fresh process state
  • basic begin/end records one event
  • FL_PERF_SCOPE RAII guard records on exit
  • runtime disable suppresses events even when compiled in
  • duration monotonic non-negative
  • file/line/name captured from macro site
  • stack overflow marks dropped() without corruption
  • flush emits and clears the log
  • log capacity caps event_count() and sets dropped()
  • clear() resets log, stack, and dropped flag

Verified bash test log/driver/channels/fastled_core --cpp all pass and bash compile wasm --examples Blink succeeds.

Hardware validation is blocked — see #2507

bash autoresearch esp32p4 --parlio failed twice on this dev env:

  1. fbuild path — zccache daemon timeout (~300 s) on first compile, then arduino-esp32 internal-header miss (WString.h, soc/soc_caps.h not found despite being present in the cached framework tree).
  2. Serial output — even after flashing via pio run --target upload / direct esptool, no bytes ever arrive on the COM port after device reset. Switching ARDUINO_USB_MODE to 0 (per PR debug(parlio): #2493 reproducer + FL_PARLIO_PROFILE markers #2494) didn't help. ROM-loader output IS visible, so the host-side path is alive — it's specifically post-app boot.

Both issues are tracked in #2507 with reproducers. The PR code is sound and host-side tests pass; the perf-trace sweep will run as soon as #2507 is resolved.

Related

Test plan

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Runtime performance tracing with scoped instrumentation and runtime on/off control.
    • CLI tool to run trace sweeps on ESP32-P4 with table or JSON output.
    • Arduino sketch to capture and store per-frame traces to flash.
  • Tools

    • Decoder script to parse and render binary trace dumps.
  • Tests

    • Unit tests covering tracing behavior, buffering, overflow, and flush semantics.
  • Chores

    • Build configuration updated to enable perf-trace support.

Review Change Stack

zackees and others added 2 commits May 24, 2026 08:36
Adds fl::PerfTrace — a Chrome-trace-style begin/end performance tracer
designed for diagnosing the ESP32-P4 PARLIO FastLED.show() blocking
issue tracked in #2493/#2494 (follow-up to the #2503 vTaskDelay-floor
fix). Replaces the ad-hoc FL_PARLIO_PROFILE markers from PR #2494
with a reusable framework so further drivers/code paths can be
instrumented without bespoke timing boilerplate per call site.

Module: src/fl/system/perf_trace.{h,cpp.hpp}
- Per-thread in-flight stack (FixedVector<PerfEvent,32>) + completed-event
  log (FixedVector<PerfEvent,128>), held in SingletonThreadLocal.
- PerfEvent captures (file*, name*, line, depth, start_us, end_us).
  String pointers are non-owning literals (__FILE__ + macro arg).
- Compile gate FASTLED_PERF_TRACE; runtime gate fl::PerfTrace::set_enabled.
- API: PerfTrace::begin/end, PerfScope RAII guard, flush() that emits
  one FL_INFO line per event ("PT d=N dur_us=X start_us=Y name=Z @file:L")
  or routes through a user callback. dropped() flag surfaces overflow.

Macros (perf_trace.h):
  FL_PERF_SCOPE("name")        — RAII guard
  FL_PERF_BEGIN("name")        — manual, returns slot id
  FL_PERF_END(slot)            — close a manual scope
  FL_PERF_FRAME_FLUSH()        — emit + clear the log

Instrumentation (CFastLED::show + PARLIO hot path):
- src/FastLED.cpp.hpp: top-level "show" + nested "onBeginFrame",
  "min_micros_gate", "showLedsInternal", "endShowLeds" scopes.
- src/fl/channels/manager.cpp.hpp + driver.cpp.hpp: "waitForCondition"
  scopes in both polling loops (the deep-yield sites from #2493).
- src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp:
  scopes in PARLIO poll() (impl + outer), beginTransmission, and
  beginClocklessTransmission.

Autoresearch integration (examples/AutoResearch):
- New RPC setPerfTraceEnabled(bool): flips runtime capture and clears
  on disable.
- New RPC getPerfTraceLog(): returns events as compact
  [depth, dur_us, start_us, name, file, line] tuples and clears the log.
- platformio.ini esp32p4 env now defines FASTLED_PERF_TRACE=1 so the
  scopes compile in. Capture stays off at boot until autoresearch flips
  the runtime switch — there is no per-frame overhead when disabled.

Tests (tests/fl/system/perf_trace.hpp, included from tests/fl/log.cpp):
  PerfTrace - disabled by default after fresh process state
  PerfTrace - basic begin/end records one event
  PerfTrace - FL_PERF_SCOPE RAII guard records on exit
  PerfTrace - runtime disable suppresses events even when compiled in
  PerfTrace - duration monotonic non-negative
  PerfTrace - file/line/name captured from macro site
  PerfTrace - stack overflow marks dropped() without corruption
  PerfTrace - flush emits and clears the log
  PerfTrace - log capacity caps event_count() and sets dropped()
  PerfTrace - clear() resets log, stack, and dropped flag

Refs: #2493 #2494 #2503

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

ci/perf_trace_sweep.py:
- Standalone driver script that connects to an esp32p4 over JSON-RPC
  (pyserial backend, no fbuild daemon dependency), flips
  setPerfTraceEnabled(true), runs PARLIO via runTest, pulls
  getPerfTraceLog(), and prints either a table or raw JSON.
- Complements `bash autoresearch` — focused on the perf-trace flow so
  the autoresearch fail-fast matrix doesn't drown out the event log.

platformio.ini esp32p4:
- ARDUINO_USB_MODE=1 → 0. Mode 1 sends Serial to USB-OTG (a separate
  connector); the dev board's COM port (VID 0x303A PID 0x1001) is the
  built-in USB-Serial-JTAG path, which needs mode 0. PR #2494 already
  flagged the same issue. Comment added so the next reader doesn't
  flip it back.

Refs: #2493 #2494 #2503 #2507

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

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds a compile-time-gated, runtime-controlled PerfTrace subsystem with thread-local event logs and RAII macros; instruments FastLED rendering, channel drivers, and PARLIO; exposes RPC handlers and a serial sweep CLI; provides a flash-decoder tool, an on-device PerfTraceBench sketch, and comprehensive unit tests.

Changes

Performance Tracing System

Layer / File(s) Summary
PerfTrace core API & implementation
src/fl/system/perf_trace.h, src/fl/system/perf_trace.cpp.hpp
Defines fl::PerfEvent, PerfEmitFn, fl::PerfTrace static API (enable/disable, begin/end, query, clear, flush) and fl::PerfScope; implements thread-local storage, in-flight stack, fixed-size event log, dropped-event tracking, and flush/clear semantics.
Build integration & configuration
src/fl/system/_build.cpp.hpp, platformio.ini
Includes perf_trace implementation into the unity build and enables FASTLED_PERF_TRACE=1 for the ESP env; adjusts USB/CDC/Serial build flags for serial RPC routing.
FastLED show() instrumentation
src/FastLED.cpp.hpp
Instruments CFastLED::show() with FL_PERF_SCOPE around frame start and min-micros gating; splits rendering into two scoped passes for measurement.
Channel & PARLIO instrumentation
src/fl/channels/driver.cpp.hpp, src/fl/channels/manager.cpp.hpp, src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
Adds FL_PERF_SCOPE markers to wait/poll/transmit hot paths in channel drivers and PARLIO implementations.
RPC endpoints for trace control
examples/AutoResearch/AutoResearchRemote.cpp
Registers setPerfTraceEnabled and getPerfTraceLog RPC handlers to toggle runtime capture and export compact event tuples with metadata, clearing device-side buffer after export.
CLI sweep tool
ci/perf_trace_sweep.py
Standalone script that runs configurable PARLIO performance sweeps via serial-backed JSON-RPC, collects the perf log, and prints JSON or a human-readable event table.
Flash decoder CLI
ci/perf_trace_decode.py
Parses the on-flash binary dump format produced by the example sketch into frames/events and an optional name table, with bounds checks and a renderer.
PerfTraceBench example
examples/PerfTraceBench/PerfTraceBench.ino
Arduino sketch that captures per-frame and per-event perf data while driving WS2812B strips, serializes frames/events and interned names into an on-flash binary partition, and flushes when done.
Comprehensive tests
tests/fl/system/perf_trace.hpp, tests/fl/log.cpp
Unit tests covering disabled default, single/nested scopes, runtime disable, duration sanity, metadata capture, stack overflow/dropped, flush callback, capacity capping, and clear; integrated into test aggregator.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2503: Touches wait-loop behavior in ChannelManager/IChannelDriver; both PRs modify the same wait paths.

Poem

🐰 I hopped through scopes with careful care,

Timings tucked in flash and air,
I traced each show and PARLIO beat,
Names interned and frames complete,
Hop, decode, and measure fair.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.82% 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 'feat(perf-trace): thread-local push/pop perf tracing + PARLIO sweep instrumentation' directly and clearly describes the main changes: adding thread-local performance tracing and PARLIO instrumentation.
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/perf-trace

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: 6

🤖 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 `@ci/perf_trace_sweep.py`:
- Around line 19-21: Update the usage example line that currently shows "uv run
ci/perf_trace_sweep.py --port COM25 ..." to use the repository's bash wrapper
style instead of direct Python invocation; replace the invocation pattern in the
Usage block (the usage example string) with the bash wrapper form (e.g., "bash
ci/perf_trace_sweep --port COM25 --lanes 12 --strip-size 256") so it follows the
guideline forbidding direct Python invocation.
- Around line 41-77: Change run_sweep to return a typed `@dataclass` instead of
dict[str, Any]: define a dataclass (e.g., PerfSweepResult) with fields config
(another small dataclass or TypedDict with lanes:int and strip_size:int),
run_test: Any, and log: Optional[Any]; update the run_sweep signature to ->
PerfSweepResult, construct and return an instance of PerfSweepResult where the
current dict is created, add needed imports (from dataclasses import dataclass;
from typing import Any, Optional), and update any callers (e.g., main()) to
access attributes (result.config, result.run_test, result.log) rather than dict
indexing.
- Around line 104-108: The try/except around asyncio.run(run_sweep(...)) in
main() currently catches Exception directly; add a dedicated except
KeyboardInterrupt: block before the generic except Exception to handle user
interrupts explicitly—e.g., catch KeyboardInterrupt, print a short message to
sys.stderr (or simply return a non-zero status) and return 1, then keep the
existing except Exception to log other failures; locate the try block invoking
run_sweep and insert the new except KeyboardInterrupt clause above the generic
exception handler.
- Around line 94-103: Update main to accept an optional argv (e.g., main(argv:
Optional[list[str]] = None) -> int) and pass that into parser.parse_args(argv)
so tests can supply deterministic arguments; adjust the try/except so
KeyboardInterrupt is not swallowed by re-raising it (handle except
KeyboardInterrupt: raise) and only catch other exceptions (except Exception as
e:) to log and return a non-zero exit code; reference main and parser.parse_args
to locate the changes.

In `@src/fl/system/perf_trace.cpp.hpp`:
- Around line 6-16: The PerfTrace implementation in perf_trace.cpp.hpp must be
compile-gated by FASTLED_PERF_TRACE: wrap the entire implementation (all
definitions for fl::PerfTrace, its methods, and any related free/static
functions or file-scope variables in this translation unit) in an `#ifdef`
FASTLED_PERF_TRACE / `#endif` so that when FASTLED_PERF_TRACE is not defined the
implementation is omitted; do the same pattern used in perf_trace.h (and mirror
it in _build.cpp.hpp if it contains PerfTrace code) to ensure only the FL_PERF_*
macros are no-ops in non-trace builds and no PerfTrace symbols are compiled.
- Around line 40-54: Replace the non-atomic flag detail::g_enabled with an
atomic type and use atomic ops: include "fl/stl/atomic.h", change static bool
g_enabled to static fl::atomic_bool g_enabled{false}; then update
PerfTrace::set_enabled to call detail::g_enabled.store(on,
std::memory_order_relaxed) (or fl::atomic equivalent), update
PerfTrace::is_enabled and PerfTrace::begin to use
detail::g_enabled.load(std::memory_order_relaxed) (checking the loaded value in
begin and returning -1 if false), and update the nearby comment that currently
asserts a plain bool is acceptable.
🪄 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: 62f3201a-f671-406c-8d52-159f95bbd2d5

📥 Commits

Reviewing files that changed from the base of the PR and between f7d4b0e and 374acfc.

📒 Files selected for processing (12)
  • ci/perf_trace_sweep.py
  • examples/AutoResearch/AutoResearchRemote.cpp
  • platformio.ini
  • src/FastLED.cpp.hpp
  • src/fl/channels/driver.cpp.hpp
  • src/fl/channels/manager.cpp.hpp
  • src/fl/system/_build.cpp.hpp
  • src/fl/system/perf_trace.cpp.hpp
  • src/fl/system/perf_trace.h
  • src/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpp
  • tests/fl/log.cpp
  • tests/fl/system/perf_trace.hpp

Comment thread ci/perf_trace_sweep.py
Comment on lines +19 to +21
Usage:
uv run ci/perf_trace_sweep.py --port COM25 \
--lanes 12 --strip-size 256

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

Update usage docs to avoid direct Python invocation pattern.

The usage example currently uses uv run ...; switch docs to the repo’s bash wrapper style.

As per coding guidelines, "Never use direct Python invocation like uv run python test.py; always use bash wrapper scripts like bash test".

🤖 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 `@ci/perf_trace_sweep.py` around lines 19 - 21, Update the usage example line
that currently shows "uv run ci/perf_trace_sweep.py --port COM25 ..." to use the
repository's bash wrapper style instead of direct Python invocation; replace the
invocation pattern in the Usage block (the usage example string) with the bash
wrapper form (e.g., "bash ci/perf_trace_sweep --port COM25 --lanes 12
--strip-size 256") so it follows the guideline forbidding direct Python
invocation.

Comment thread ci/perf_trace_sweep.py
Comment on lines +41 to +77
async def run_sweep(port: str, lanes: int, strip_size: int) -> dict[str, Any]:
# Use pyserial backend so we don't need the fbuild monitor daemon.
iface = create_serial_interface(port=port, baud_rate=115200, use_pyserial=True)
client = RpcClient(port=port, baudrate=115200, timeout=20.0, serial_interface=iface)
await client.connect()

try:
# 1. Turn capture on (compile-in flag already set in platformio.ini).
on = await client.send("setPerfTraceEnabled", args=[True])
if not on.get("success"):
raise RuntimeError(f"setPerfTraceEnabled failed: {on}")

# 2. Run a PARLIO test that exercises show().
result = await client.send(
"runTest",
args=[
{
"drivers": ["PARLIO"],
"laneRange": {"min": lanes, "max": lanes},
"stripSizes": [strip_size],
}
],
timeout=60.0,
)

# 3. Pull the trace log.
log = await client.send("getPerfTraceLog", args=[])

# 4. Disable capture (also clears the log on the device side).
await client.send("setPerfTraceEnabled", args=[False])

return {
"config": {"lanes": lanes, "strip_size": strip_size},
"run_test": result,
"log": log,
}
finally:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and print the relevant portion of ci/perf_trace_sweep.py
if [ -f ci/perf_trace_sweep.py ]; then
  echo "=== ci/perf_trace_sweep.py (lines around 1-120) ==="
  nl -ba ci/perf_trace_sweep.py | sed -n '1,140p'
else
  echo "Missing file: ci/perf_trace_sweep.py"
fi

# Check if the repo has the referenced Python standards file
if [ -f agents/docs/python-standards.md ]; then
  echo "=== agents/docs/python-standards.md (relevant sections) ==="
  # Print only the parts likely to mention dataclasses/return types/typechecked
  rg -n "dataclass|typed|dict\\[str, Any\\]|Return dataclass|typechecked|`@typechecked`|multiple return" agents/docs/python-standards.md || true
  nl -ba agents/docs/python-standards.md | sed -n '1,240p'
else
  echo "Missing file: agents/docs/python-standards.md"
fi

# Search for run_sweep usage to see expected return type
rg -n "run_sweep\\(" -S . || true

# Search for any existing dataclass used for sweep results
rg -n "dataclass\\b|class .*Sweep|Sweep.*Result" ci/perf_trace_sweep.py agents/docs/python-standards.md . || true

Repository: FastLED/FastLED

Length of output: 172


🏁 Script executed:

#!/bin/bash
set -euo pipefail

show_lines() {
  local file="$1"
  local start="$2"
  local end="$3"
  awk -v s="$start" -v e="$end" 'NR>=s && NR<=e {printf "%d:%s\n", NR, $0}' "$file"
}

echo "=== Check files exist ==="
ls -la ci/perf_trace_sweep.py agents/docs/python-standards.md 2>/dev/null || true

echo "=== ci/perf_trace_sweep.py (lines 1-160) ==="
if [ -f ci/perf_trace_sweep.py ]; then
  show_lines ci/perf_trace_sweep.py 1 160
fi

echo "=== agents/docs/python-standards.md (search hits + surrounding) ==="
if [ -f agents/docs/python-standards.md ]; then
  rg -n "dataclass|typechecked|Return dataclass|dict\\[str, Any\\]|multiple return" agents/docs/python-standards.md || true
  echo "--- head/tail context ---"
  show_lines agents/docs/python-standards.md 1 220
fi

echo "=== Where run_sweep is used ==="
rg -n "run_sweep\\(" -S . || true

echo "=== Look for any dataclasses in ci/perf_trace_sweep.py ==="
if [ -f ci/perf_trace_sweep.py ]; then
  rg -n "dataclass\\b|class .*\\bResult\\b|TypedDict\\b|->\\s*dict\\[" ci/perf_trace_sweep.py || true
fi

Repository: FastLED/FastLED

Length of output: 9385


Return a typed @dataclass from run_sweep instead of dict[str, Any].

ci/perf_trace_sweep.py:run_sweep currently returns a loosely-typed dict (config, run_test, log), and main() indexes into it (e.g., result["config"], result.get("log")). Per the Python standards, switch this to a @dataclass with named fields to make the structured return type explicit and safer to refactor.

🤖 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 `@ci/perf_trace_sweep.py` around lines 41 - 77, Change run_sweep to return a
typed `@dataclass` instead of dict[str, Any]: define a dataclass (e.g.,
PerfSweepResult) with fields config (another small dataclass or TypedDict with
lanes:int and strip_size:int), run_test: Any, and log: Optional[Any]; update the
run_sweep signature to -> PerfSweepResult, construct and return an instance of
PerfSweepResult where the current dict is created, add needed imports (from
dataclasses import dataclass; from typing import Any, Optional), and update any
callers (e.g., main()) to access attributes (result.config, result.run_test,
result.log) rather than dict indexing.

Comment thread ci/perf_trace_sweep.py
Comment on lines +94 to +103
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", default="COM25", help="serial port (default COM25)")
parser.add_argument("--lanes", type=int, default=12, help="number of PARLIO lanes")
parser.add_argument("--strip-size", type=int, default=256, help="LEDs per lane")
parser.add_argument(
"--json", action="store_true", help="emit raw JSON instead of a table"
)
args = parser.parse_args()

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

# Locate and print the relevant section of ci/perf_trace_sweep.py
ls -la ci/perf_trace_sweep.py || true
wc -l ci/perf_trace_sweep.py || true
python3 - <<'PY'
import itertools,sys
path="ci/perf_trace_sweep.py"
start=60
end=170
with open(path,'r',encoding='utf-8') as f:
    for i,line in enumerate(f, start=1):
        if start <= i <= end:
            print(f"{i:4d}: {line.rstrip()}")
PY

# Find all occurrences of main()/parse_args in the file
rg -n "def main\\b|parse_args\\(" ci/perf_trace_sweep.py || true

# Check for any existing argv-handling conventions in python-standards.md (if present)
if [ -f agents/docs/python-standards.md ]; then
  rg -n "parse_args|argv|ArgumentParser" agents/docs/python-standards.md || true
fi

Repository: FastLED/FastLED

Length of output: 2729


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search for the python standards file and check for parse_args / argv rules
ls -ლა agents/docs/python-standards.md agents/docs || true
if [ -f agents/docs/python-standards.md ]; then
  rg -n "parse_args|argv|ArgumentParser" agents/docs/python-standards.md || true
  rg -n "parse_args functions MUST accept" agents/docs/python-standards.md || true
fi

# Find other scripts in ci that define a main() using argparse (for consistency)
rg -n "def main\\(.*\\)->|def main\\(\\)" ci | head -n 50 || true
rg -n "ArgumentParser\\(|parse_args\\(" ci | head -n 50 || true

Repository: FastLED/FastLED

Length of output: 6035


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read python standards doc around parse_args/argv and try/except rules
if [ -f agents/docs/python-standards.md ]; then
  echo "=== agents/docs/python-standards.md (relevant sections) ==="
  rg -n "parse_args|argv|ArgumentParser" agents/docs/python-standards.md
  rg -n "KeyboardInterrupt" agents/docs/python-standards.md
  # Print a small window around the matched line(s)
  python3 - <<'PY'
import re
path="agents/docs/python-standards.md"
with open(path,'r',encoding='utf-8') as f:
    lines=f.readlines()
targets=[]
for i,l in enumerate(lines, start=1):
    if re.search(r'(parse_args|argv|ArgumentParser)', l) or 'KeyboardInterrupt' in l:
        targets.append(i)
# de-dup and keep first ~12 windows
seen=set()
for t in targets[:12]:
    if t in seen: continue
    seen.add(t)
    lo=max(1,t-8); hi=min(len(lines),t+8)
    print(f"\n--- window around line {t} ({lo}-{hi}) ---")
    for j in range(lo,hi+1):
        print(f"{j:4d}: {lines[j-1].rstrip()}")
PY
else
  echo "agents/docs/python-standards.md not found"
fi

# Print the full main() function and surrounding lines for context
python3 - <<'PY'
path="ci/perf_trace_sweep.py"
with open(path,'r',encoding='utf-8') as f:
    lines=f.readlines()
for i in range(85,135):
    if i<=len(lines):
        print(f"{i:4d}: {lines[i-1].rstrip()}")
PY

Repository: FastLED/FastLED

Length of output: 119


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Confirm file exists and show top of it
ls -la agents/docs/python-standards.md || true
head -n 80 agents/docs/python-standards.md || true

# Search for likely wording (no-messages to avoid noisy errors/exit codes)
rg -n --no-messages "parse_args|argv|ArgumentParser" agents/docs/python-standards.md || true
rg -n --no-messages "KeyboardInterrupt|try|except" agents/docs/python-standards.md | head -n 80 || true
rg -n --no-messages "optional list\\[str\\]|list\\[str\\] \\| None|list\\[str\\]|MUST accept" agents/docs/python-standards.md || true

# If file is small enough, print it entirely; otherwise print ranges around matches
wc -l agents/docs/python-standards.md
python3 - <<'PY'
path="agents/docs/python-standards.md"
with open(path,'r',encoding='utf-8') as f:
    lines=f.readlines()
# Heuristic: print around any line containing 'parse', 'arg', 'argv', or 'KeyboardInterrupt'
keys=["parse_args","argv","ArgumentParser","KeyboardInterrupt","argparse"]
idx=[i for i,l in enumerate(lines) if any(k in l for k in keys)]
if not idx:
    # fallback: show middle section
    mid=len(lines)//2
    lo=max(0,mid-60); hi=min(len(lines)-1,mid+60)
    for j in range(lo,hi+1):
        print(f"{j+1:4d}: {lines[j].rstrip()}")
else:
    for i in sorted(set(idx))[:6]:
        lo=max(0,i-60); hi=min(len(lines)-1,i+60)
        print(f"\n--- around line {i+1} ({lo+1}-{hi+1}) ---")
        for j in range(lo,hi+1):
            print(f"{j+1:4d}: {lines[j].rstrip()}")
PY

Repository: FastLED/FastLED

Length of output: 25160


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "except (Exception|BaseException)\b" ci/perf_trace_sweep.py || true
rg -n "except KeyboardInterrupt\b" ci/perf_trace_sweep.py || true

Repository: FastLED/FastLED

Length of output: 92


Make main() accept argv and preserve KeyboardInterrupt.

  • ci/perf_trace_sweep.py currently calls parser.parse_args() with no argv (lines 94-103); accept an optional list[str] and pass it to parse_args(argv) for deterministic tests.
  • main() catches Exception without re-raising KeyboardInterrupt (lines 104-108); update the exception handling so Ctrl+C isn’t swallowed.
Suggested fix
-def main() -> int:
+def main(argv: list[str] | None) -> int:
     parser = argparse.ArgumentParser(description=__doc__)
@@
-    args = parser.parse_args()
+    args = parser.parse_args(argv)
@@
 if __name__ == "__main__":
-    sys.exit(main())
+    sys.exit(main(None))
🤖 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 `@ci/perf_trace_sweep.py` around lines 94 - 103, Update main to accept an
optional argv (e.g., main(argv: Optional[list[str]] = None) -> int) and pass
that into parser.parse_args(argv) so tests can supply deterministic arguments;
adjust the try/except so KeyboardInterrupt is not swallowed by re-raising it
(handle except KeyboardInterrupt: raise) and only catch other exceptions (except
Exception as e:) to log and return a non-zero exit code; reference main and
parser.parse_args to locate the changes.

Comment thread ci/perf_trace_sweep.py
Comment on lines +104 to +108
try:
result = asyncio.run(run_sweep(args.port, args.lanes, args.strip_size))
except Exception as exc:
print(f"perf_trace_sweep failed: {exc}", file=sys.stderr)
return 1

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

Handle KeyboardInterrupt explicitly before catching Exception in ci/perf_trace_sweep.py
main() currently catches Exception directly; add a dedicated except KeyboardInterrupt branch first to satisfy the guideline.

Suggested fix
-    try:
-        result = asyncio.run(run_sweep(args.port, args.lanes, args.strip_size))
-    except Exception as exc:
+    try:
+        result = asyncio.run(run_sweep(args.port, args.lanes, args.strip_size))
+    except KeyboardInterrupt:
+        print("perf_trace_sweep interrupted by user", file=sys.stderr)
+        return 130
+    except Exception as exc:
         print(f"perf_trace_sweep failed: {exc}", file=sys.stderr)
         return 1
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
result = asyncio.run(run_sweep(args.port, args.lanes, args.strip_size))
except Exception as exc:
print(f"perf_trace_sweep failed: {exc}", file=sys.stderr)
return 1
try:
result = asyncio.run(run_sweep(args.port, args.lanes, args.strip_size))
except KeyboardInterrupt:
print("perf_trace_sweep interrupted by user", file=sys.stderr)
return 130
except Exception as exc:
print(f"perf_trace_sweep failed: {exc}", file=sys.stderr)
return 1
🧰 Tools
🪛 Ruff (0.15.13)

[warning] 106-106: Do not catch blind exception: Exception

(BLE001)

🤖 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 `@ci/perf_trace_sweep.py` around lines 104 - 108, The try/except around
asyncio.run(run_sweep(...)) in main() currently catches Exception directly; add
a dedicated except KeyboardInterrupt: block before the generic except Exception
to handle user interrupts explicitly—e.g., catch KeyboardInterrupt, print a
short message to sys.stderr (or simply return a non-zero status) and return 1,
then keep the existing except Exception to log other failures; locate the try
block invoking run_sweep and insert the new except KeyboardInterrupt clause
above the generic exception handler.

Comment on lines +6 to +16
#include "fl/system/perf_trace.h"

#include "fl/stl/chrono.h" // fl::micros
#include "fl/stl/noexcept.h"
#include "fl/stl/singleton.h" // SingletonThreadLocal
#include "fl/stl/stdio.h" // fl::sprintf
#include "fl/stl/string.h"
#include "fl/stl/vector.h" // FixedVector
#include "fl/log/log.h" // FL_INFO

namespace fl {

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
# Verify where compile-gate symbols are applied today.
rg -n "FASTLED_PERF_TRACE" src/fl/system/perf_trace.h src/fl/system/perf_trace.cpp.hpp src/fl/system/_build.cpp.hpp -C2

Repository: FastLED/FastLED

Length of output: 1497


Compile-gate the fl::PerfTrace implementation (not just FL_PERF_* macros)

src/fl/system/perf_trace.h states that when FASTLED_PERF_TRACE is not defined, all FL_PERF_* macros are no-ops and the entire module is dead code. However, the only FASTLED_PERF_TRACE gating present is in src/fl/system/perf_trace.h—there’s no corresponding #ifdef FASTLED_PERF_TRACE in src/fl/system/perf_trace.cpp.hpp (nor src/fl/system/_build.cpp.hpp), so the real PerfTrace implementation is still compiled in non-trace builds.

Proposed fix
+#ifdef FASTLED_PERF_TRACE
 namespace fl {
 ...
 } // namespace fl
+#else
+namespace fl {
+void PerfTrace::set_enabled(bool) FL_NOEXCEPT {}
+bool PerfTrace::is_enabled() FL_NOEXCEPT { return false; }
+int PerfTrace::begin(const char*, int, const char*) FL_NOEXCEPT { return -1; }
+void PerfTrace::end(int) FL_NOEXCEPT {}
+fl::size PerfTrace::event_count() FL_NOEXCEPT { return 0; }
+const PerfEvent* PerfTrace::events() FL_NOEXCEPT { return nullptr; }
+fl::size PerfTrace::stack_depth() FL_NOEXCEPT { return 0; }
+bool PerfTrace::dropped() FL_NOEXCEPT { return false; }
+void PerfTrace::clear() FL_NOEXCEPT {}
+void PerfTrace::flush(PerfEmitFn, void*) FL_NOEXCEPT {}
+} // namespace fl
+#endif
🤖 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/system/perf_trace.cpp.hpp` around lines 6 - 16, The PerfTrace
implementation in perf_trace.cpp.hpp must be compile-gated by
FASTLED_PERF_TRACE: wrap the entire implementation (all definitions for
fl::PerfTrace, its methods, and any related free/static functions or file-scope
variables in this translation unit) in an `#ifdef` FASTLED_PERF_TRACE / `#endif` so
that when FASTLED_PERF_TRACE is not defined the implementation is omitted; do
the same pattern used in perf_trace.h (and mirror it in _build.cpp.hpp if it
contains PerfTrace code) to ensure only the FL_PERF_* macros are no-ops in
non-trace builds and no PerfTrace symbols are compiled.

Comment on lines +40 to +54
static bool g_enabled = false;

} // namespace detail

void PerfTrace::set_enabled(bool on) FL_NOEXCEPT {
detail::g_enabled = on;
}

bool PerfTrace::is_enabled() FL_NOEXCEPT {
return detail::g_enabled;
}

int PerfTrace::begin(const char* file, int line, const char* name) FL_NOEXCEPT {
if (!detail::g_enabled) {
return -1;

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
# Verify shared flag access patterns and current non-atomic declaration.
rg -n "g_enabled|set_enabled\\(|is_enabled\\(|begin\\(" src/fl/system/perf_trace.cpp.hpp -C2
fd -i 'atomic*.h' src/fl/stl || true

Repository: FastLED/FastLED

Length of output: 792


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect perf_trace.cpp.hpp around the reported lines + includes/namespace boundaries
echo "---- perf_trace.cpp.hpp (top/around g_enabled) ----"
nl -ba src/fl/system/perf_trace.cpp.hpp | sed -n '1,120p'

echo "---- perf_trace.cpp.hpp (around end()) ----"
nl -ba src/fl/system/perf_trace.cpp.hpp | sed -n '120,220p'

# Inspect project's atomic header to follow local conventions (types/namespaces)
echo "---- src/fl/stl/atomic.h (head) ----"
nl -ba src/fl/stl/atomic.h | sed -n '1,200p'

Repository: FastLED/FastLED

Length of output: 172


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- perf_trace.cpp.hpp (check file exists + size) ----"
ls -l src/fl/system/perf_trace.cpp.hpp
wc -l src/fl/system/perf_trace.cpp.hpp | cat
echo

echo "---- perf_trace.cpp.hpp (lines 1-120) ----"
sed -n '1,120p' src/fl/system/perf_trace.cpp.hpp
echo

echo "---- perf_trace.cpp.hpp (lines 120-220) ----"
sed -n '120,220p' src/fl/system/perf_trace.cpp.hpp
echo

echo "---- src/fl/stl/atomic.h (check exists + size) ----"
ls -l src/fl/stl/atomic.h
wc -l src/fl/stl/atomic.h | cat
echo

echo "---- src/fl/stl/atomic.h (lines 1-200) ----"
sed -n '1,200p' src/fl/stl/atomic.h

Repository: FastLED/FastLED

Length of output: 10157


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Find usages of fl::atomic_bool / fl::atomic<...> load/store patterns
rg -n "fl::atomic_bool|atomic_bool<|fl::atomic<" src/fl/system src/fl | head -n 80

# 2) Locate where memory_order is defined for real atomics (FastLED path)
fd -a "atomic.h" src/fl | head -n 50
fd -a "shared/atomic.h" . | head -n 50

# 3) Print relevant portions of platforms/atomic.h and platforms/shared/atomic.h if present
if [ -f platforms/atomic.h ]; then
  echo "---- platforms/atomic.h (head) ----"
  sed -n '1,220p' platforms/atomic.h
fi

if [ -f platforms/shared/atomic.h ]; then
  echo "---- platforms/shared/atomic.h (head) ----"
  sed -n '1,220p' platforms/shared/atomic.h
fi

# 4) Also inspect perf_trace.h for any existing declarations/notes
ls -l src/fl/system/perf_trace.h || true
if [ -f src/fl/system/perf_trace.h ]; then
  sed -n '1,200p' src/fl/system/perf_trace.h
fi

Repository: FastLED/FastLED

Length of output: 6845


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find atomic backend files referenced by fl/stl/atomic.h
echo "---- locate platforms/atomic.h ----"
ls -l platforms/atomic.h platforms/shared/atomic.h 2>/dev/null || true

echo "---- print platforms/atomic.h (if exists) ----"
if [ -f platforms/atomic.h ]; then
  sed -n '1,260p' platforms/atomic.h
fi

echo "---- print platforms/shared/atomic.h (if exists) ----"
if [ -f platforms/shared/atomic.h ]; then
  sed -n '1,260p' platforms/shared/atomic.h
fi

# Find any usage of PerfTrace::set_enabled/is_enabled
echo "---- usages of PerfTrace::set_enabled / is_enabled ----"
rg -n "PerfTrace::set_enabled|PerfTrace::is_enabled" -S src agents || true

# Also inspect the remainder of perf_trace.cpp.hpp includes for atomic conventions
echo "---- perf_trace.cpp.hpp header section ----"
sed -n '1,80p' src/fl/system/perf_trace.cpp.hpp

Repository: FastLED/FastLED

Length of output: 3034


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the included "platforms/atomic.h" and "platforms/shared/atomic.h" within src/
fd -a "platforms/atomic.h" src || true
fd -a "platforms/shared/atomic.h" src || true

# Fallback: find any shared/atomic.h and atomic.h under a platforms directory
fd -a "shared/atomic.h" src || true
fd -a "atomic.h" src/fl/stl src/fl | rg -n "platforms/" || true

# Print whatever we find first (keep output small)
for f in $(fd -a "platforms/atomic.h" src | head -n 5); do
  echo "---- $f (head) ----"
  sed -n '1,220p' "$f"
done

for f in $(fd -a "platforms/shared/atomic.h" src | head -n 5); do
  echo "---- $f (head) ----"
  sed -n '1,220p' "$f"
done

Repository: FastLED/FastLED

Length of output: 41


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- search for AtomicReal definition ----"
rg -n "class AtomicReal|using AtomicReal|AtomicReal<" . | head -n 50

echo
echo "---- search for platforms/shared/atomic.h include target ----"
rg -n "platforms/shared/atomic.h" . || true

echo
echo "---- search for memory_order enum definition for real atomics ----"
rg -n "enum class memory_order" . | head -n 50

echo
echo "---- search for AtomicReal methods load/store ----"
rg -n "load\\(memory_order|store\\(.*memory_order|memory_order_relaxed" . | head -n 80

Repository: FastLED/FastLED

Length of output: 2641


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "---- src/platforms/shared/atomic.h (head, AtomicReal, load/store) ----"
sed -n '1,140p' src/platforms/shared/atomic.h
sed -n '140,260p' src/platforms/shared/atomic.h

echo
echo "---- src/fl/system/perf_trace.cpp.hpp includes (head) ----"
sed -n '1,40p' src/fl/system/perf_trace.cpp.hpp

echo
echo "---- check if perf_trace.cpp.hpp already includes fl/stl/atomic.h ----"
rg -n "fl/stl/atomic\\.h|atomic_bool|AtomicReal" src/fl/system/perf_trace.cpp.hpp || true

Repository: FastLED/FastLED

Length of output: 4950


Make PerfTrace’s runtime enable flag atomic to avoid a data race

detail::g_enabled is a plain static bool that’s written in PerfTrace::set_enabled() and read in is_enabled() / begin() from potentially different threads, which is undefined behavior (data race).

Proposed fix
  • Replace static bool g_enabled = false; with static fl::atomic_bool g_enabled{false}; (include fl/stl/atomic.h).
  • Update:
    • set_enabled: detail::g_enabled.store(on, /* likely relaxed */);
    • is_enabled: return detail::g_enabled.load(/* likely relaxed */);
    • begin: if (!detail::g_enabled.load(/* likely relaxed */)) return -1;
  • Adjust the nearby comment that currently claims a plain bool is “fine” despite the cross-thread flip.

Also applies to the reads at is_enabled() and begin().

🤖 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/system/perf_trace.cpp.hpp` around lines 40 - 54, Replace the
non-atomic flag detail::g_enabled with an atomic type and use atomic ops:
include "fl/stl/atomic.h", change static bool g_enabled to static
fl::atomic_bool g_enabled{false}; then update PerfTrace::set_enabled to call
detail::g_enabled.store(on, std::memory_order_relaxed) (or fl::atomic
equivalent), update PerfTrace::is_enabled and PerfTrace::begin to use
detail::g_enabled.load(std::memory_order_relaxed) (checking the loaded value in
begin and returning -1 if false), and update the nearby comment that currently
asserts a plain bool is acceptable.

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 commented May 24, 2026

Copy link
Copy Markdown
Member Author

✅ Empirical sweep complete — PARLIO blocking issue still present, dramatically worse than #2493 reported

Worked around the #2507 USB-Serial-JTAG blocker with the new examples/PerfTraceBench/PerfTraceBench.ino sketch + ci/perf_trace_decode.py host decoder. The sketch writes the perf trace log to a flash data partition; esptool read-flash pulls it back to the host. No serial dependency. Pattern borrowed from PR #2494's ParlioBench.

Setup

  • ESP32-P4-EV on COM25
  • 12 PARLIO lanes (GPIO 0–11), WS2812B
  • 256 LEDs/lane
  • 16 frames captured (steady-state numbers from frames 1–15)

Result (steady-state per frame)

Scope (file:line) depth dur_us
CFastLED::show:235 0 1,058,120
ChannelManager::waitForCondition:353 1 755,260
showLedsInternal:271 1 3,200–3,300
onBeginFrame:237 1 ~30
min_micros_gate:241 1 ~3
endShowLeds:283 1 ~6
IChannelDriver::waitForCondition:13 1 ~5

Verdict

The PARLIO blocking issue from #2493 is NOT resolved by #2503. It moved.

  • fix(channels): skip vTaskDelay(1) floor in wait-loop on ESP32-P4 (#2493 follow-up) #2503 added the task::run(0, SYSTEM) fast-yield on IChannelDriver::waitForCondition (driver.cpp.hpp:23). That worked — the inner polling loop now costs ~5 µs/frame instead of 8 ms.
  • But the per-frame budget is now dominated by the other waitForCondition — the manager's flush wait (manager.cpp.hpp:353) — at 755 ms/frame, which is ~100× the expected WS2812B drain time (~7.6 ms for 256 LEDs).
  • show() steady-state is 1.058 s/frame (~0.95 FPS) on this build for 12-lane × 256-LED WS2812B.

The 755 ms duration is suspiciously consistent across all 16 frames (max 755,500 µs on the first frame, 755,256–755,270 µs on the rest), suggesting either the manager flush is hitting a timeout or the PARLIO state machine is genuinely taking that long to report READY. The waitForCondition default timeoutMs is 1000 ms — we're consistently exiting at ~75% of that.

Frame 1 (representative)

=== frame   1  show_us=1059725  events=8 ===
  depth     dur_us      start_us  name
      2       1548       3947463  ChannelManager::waitForCondition:353
      1       1556       3947459  onBeginFrame:237
      1          4       3949017  min_micros_gate:241
      1       3297       3949032  showLedsInternal:271
      1          6       3952332  endShowLeds:283
      1          5       3952342  IChannelDriver::waitForCondition:13
      1     755259       4251908  ChannelManager::waitForCondition:353
      0    1059721       3947457  CFastLED::show:235

Note also the ~300 ms gap between the inner waitForCondition (ends 3952347) and the outer manager waitForCondition (starts 4251908). That's the un-instrumented portion of ChannelManager::flush() between waitForReadyOrDraining and waitForReady. Worth adding more scopes there to localize that 300 ms.

Next steps

  1. ESP32-P4 PARLIO: FastLED.show() appears to block for ~16.7 ms before WS2812 data burst begins #2493 is not done. Recommend reopening or filing a fresh issue for the 755 ms manager flush wait and the 300 ms unaccounted gap.
  2. The 755 ms suggests ChannelDriverPARLIO::poll() may be stuck reporting DRAINING long after the DMA peripheral is actually idle — worth instrumenting the engine's poll() and HAL-state transitions.
  3. Once fbuild: bash autoresearch esp32p4 --parlio fails to build (WString.h / soc_caps.h missing, zccache hang) #2507 is resolved, the same data path is reachable via setPerfTraceEnabled + getPerfTraceLog over RPC, no flash dance.

🤖 Generated with Claude Code.

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

🤖 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 `@ci/perf_trace_decode.py`:
- Around line 38-105: The decode() function should stop returning dicts/tuples
and instead build and return typed dataclasses: define an Event dataclass
(fields depth, line, dur_us, start_us, name_off), a Frame dataclass (frame_idx,
show_us, dropped, events: list[Event]), and a top-level Trace/DecodeResult
dataclass (version, frames: list[Frame], names: list[str]); update decode() to
append Event instances instead of tuples and construct Frame instances instead
of dicts, change the return type annotation accordingly, and update any callers
(e.g., render()) to access attributes (event.depth, frame.frame_idx, etc.)
rather than dictionary keys or tuple indices.
🪄 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: 3a028d6b-1bea-4306-bd82-9c89f0a3c4f1

📥 Commits

Reviewing files that changed from the base of the PR and between 374acfc and b94e11e.

📒 Files selected for processing (2)
  • ci/perf_trace_decode.py
  • examples/PerfTraceBench/PerfTraceBench.ino

Comment thread ci/perf_trace_decode.py
Comment on lines +38 to +105
def decode(blob: bytes) -> dict[str, Any]:
if len(blob) < HEADER_SIZE:
raise ValueError(f"too short ({len(blob)} bytes) for header")

magic, version, num_frames, total_bytes, _ = struct.unpack(
HEADER_FMT, blob[:HEADER_SIZE]
)
if magic != HEADER_MAGIC:
raise ValueError(
f"bad header magic 0x{magic:08x} (expected 0x{HEADER_MAGIC:08x})"
)

pos = HEADER_SIZE
frames: list[dict[str, Any]] = []
for _ in range(num_frames):
if pos + FRAME_SIZE > len(blob):
raise ValueError(f"truncated frame record at offset {pos}")
fm, fidx, show_us, ev_count, dropped, _pad = struct.unpack(
FRAME_FMT, blob[pos : pos + FRAME_SIZE]
)
if fm != FRAME_MAGIC:
raise ValueError(
f"bad frame magic 0x{fm:08x} at offset {pos} "
f"(expected 0x{FRAME_MAGIC:08x})"
)
pos += FRAME_SIZE
events: list[tuple[int, int, int, int, int]] = []
for _ in range(ev_count):
if pos + EVENT_SIZE > len(blob):
raise ValueError(f"truncated event record at offset {pos}")
em, depth, line, dur_us, start_us, name_off = struct.unpack(
EVENT_FMT, blob[pos : pos + EVENT_SIZE]
)
if em != EVENT_MAGIC:
raise ValueError(
f"bad event magic 0x{em:08x} at offset {pos} "
f"(expected 0x{EVENT_MAGIC:08x})"
)
pos += EVENT_SIZE
events.append((depth, line, dur_us, start_us, name_off))
frames.append(
{
"frame_idx": fidx,
"show_us": show_us,
"dropped": bool(dropped),
"events": events,
}
)

# Name table: u32 count, then [u16 len, bytes[len]] × count.
if pos + 4 > len(blob):
# Names absent — return what we have.
return {"version": version, "frames": frames, "names": []}
(name_count,) = struct.unpack_from("<I", blob, pos)
pos += 4
names: list[str] = []
for _ in range(name_count):
if pos + 2 > len(blob):
break
(nlen,) = struct.unpack_from("<H", blob, pos)
pos += 2
if pos + nlen > len(blob):
break
names.append(blob[pos : pos + nlen].decode("utf-8", errors="replace"))
pos += nlen

return {"version": version, "frames": frames, "names": names}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Identify the file and print relevant sections with line numbers
sed -n '1,220p' ci/perf_trace_decode.py | cat -n

# Search for other references/usages of decode/render in the repo
rg -n "def decode\(|def render\(|perf_trace_decode\.decode|perf_trace_decode|decode\(" -S ci/perf_trace_decode.py ci || true

# Read the referenced python standards (if present) to confirm the exact intent of the guideline
if [ -f agents/docs/python-standards.md ]; then
  rg -n "dataclass|tuple|dict|Return dataclass|multi" agents/docs/python-standards.md || true
  sed -n '1,220p' agents/docs/python-standards.md | cat -n
else
  echo "Missing agents/docs/python-standards.md"
fi

Repository: FastLED/FastLED

Length of output: 12902


Replace decoded dict/tuple model with typed @dataclass types in ci/perf_trace_decode.py.

decode() currently returns dict[str, Any] (and render() depends on string-key lookups), which conflicts with the project’s “Structured Return Types” guidance to avoid returning dict[str, Any]—use a @dataclass model instead. Also replace the positional events: list[tuple[int, int, int, int, int]] with a named @dataclass (e.g., Event) so render() doesn’t rely on tuple ordering. [lines 38-105, 107-127]

🧰 Tools
🪛 Ruff (0.15.13)

[warning] 42-42: Unpacked variable total_bytes is never used

Prefix it with an underscore or any other dummy variable pattern

(RUF059)


[warning] 87-87: Comment contains ambiguous × (MULTIPLICATION SIGN). Did you mean x (LATIN SMALL LETTER X)?

(RUF003)

🤖 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 `@ci/perf_trace_decode.py` around lines 38 - 105, The decode() function should
stop returning dicts/tuples and instead build and return typed dataclasses:
define an Event dataclass (fields depth, line, dur_us, start_us, name_off), a
Frame dataclass (frame_idx, show_us, dropped, events: list[Event]), and a
top-level Trace/DecodeResult dataclass (version, frames: list[Frame], names:
list[str]); update decode() to append Event instances instead of tuples and
construct Frame instances instead of dicts, change the return type annotation
accordingly, and update any callers (e.g., render()) to access attributes
(event.depth, frame.frame_idx, etc.) rather than dictionary keys or tuple
indices.

While re-running the perf-trace sweep with the new fbuild include-path
fix, found that adding ARDUINO_USB_CDC_ON_BOOT=1 to the esp32p4 env
drops show_us from 1,058 ms/frame to 55 ms/frame for the
12-lane × 256-LED WS2812B workload — a **19× improvement**.

ChannelManager::waitForCondition (manager.cpp.hpp:353) goes from
755 ms/frame → ~49.6 ms/frame. Still ~6.5× the expected PARLIO drain
time (~7.6 ms for 256 LEDs), so the issue from #2493 is not fully gone,
but the residual problem is now in a much different regime than what
the original ~16 ms report described.

Best guess at why: without CDC_ON_BOOT, the dev board's USB-Serial-JTAG
endpoint isn't claimed by user code, so the bootloader's UART0→JTAG
bridge stays active. The bridge spins on UART0 TX, which apparently
serializes with PARLIO completion at a level that adds ~700 ms per
frame to the manager flush wait. Enabling CDC_ON_BOOT routes Serial
through HWCDC (TinyUSB CDC over the JTAG endpoint), bypassing the UART
bridge entirely.

This does NOT fix the post-boot serial silence (#2507) — host-side
reads of COM25 still return zero bytes. But the sketch ALSO doesn't
need serial: the flash-dump path in PerfTraceBench captures everything.

Sketch change: bump the post-Serial.begin delay to 5 s with Serial.flush
in case the silence ever gets fixed and we want to see first-line output.

Refs: #2493 #2507

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

zackees commented May 24, 2026

Copy link
Copy Markdown
Member Author

🎯 Updated sweep: enabling ARDUINO_USB_CDC_ON_BOOT=1 → 19× faster show()

Re-ran the sweep after landing the fbuild include-path fix (FastLED/fbuild#273) and bumping the esp32p4 env to ARDUINO_USB_CDC_ON_BOOT=1. The PARLIO blocking issue from #2493 is mostly gone — but a smaller residual remains.

Before (no CDC_ON_BOOT)

Scope Per frame
CFastLED::show 1,058 ms (~0.95 FPS)
ChannelManager::waitForCondition:353 755 ms

After (CDC_ON_BOOT=1)

Scope Per frame
CFastLED::show 55.6 ms (~18 FPS)
ChannelManager::waitForCondition:353 49.6 ms
showLedsInternal 3.3 ms
IChannelDriver::waitForCondition 8 µs
onBeginFrame 12-19 µs

Steady-state 16 captured frames (frames 1-15):

=== frame   1  show_us=  55605  | wait353: 49640 us
=== frame   2  show_us=  55559  | wait353: 49629 us
...
=== frame  15  show_us=  55532  | wait353: 49624 us

What changed and why I think it matters

Without ARDUINO_USB_CDC_ON_BOOT=1, the dev board's USB-Serial-JTAG endpoint isn't claimed by user code, so the bootloader's UART0→JTAG bridge stays active. The bridge spins on UART0 TX, which apparently serializes with PARLIO completion at a level that adds ~700 ms per frame to the manager flush wait. Enabling CDC_ON_BOOT routes Serial through HWCDC (TinyUSB CDC over the JTAG endpoint), bypassing the UART bridge entirely.

This is a dev-environment artifact — it would not appear on a board that boots without a UART bridge active, but it's a hidden perf cliff for anyone testing on an ESP32-P4-EV with stock platformio.ini. Worth landing the CDC_ON_BOOT=1 flag for esp32p4 regardless.

Residual: 49.6 ms in waitForCondition vs ~7.6 ms expected

PARLIO drain for 256 LEDs WS2812B should be ~7.6 ms (12 lanes go in parallel). We're at 49.6 ms, ~6.5×. Suggestions:

  • The poll() state machine may stay in DRAINING longer than it needs to (worth instrumenting ParlioEngine::poll() and the HAL transition events).
  • The ~300 ms gap I noted between the inner and outer waitForCondition in the previous comment is now gone too — also explained by the CDC change.
  • The remaining 49.6 ms could be inherent to PARLIO's interrupt-driven completion + the manager's poll cadence.

Notes on autoresearch / fbuild

🤖 Generated with Claude Code

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
examples/PerfTraceBench/PerfTraceBench.ino (6)

163-171: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle append() failures; current code can silently emit corrupted/truncated dumps.

append() returns false on overflow, but callers ignore it. If the buffer fills, frame/event/name records become partially missing with no fail-fast path.

Proposed fix pattern
+static bool appendOrStop(const void* src, size_t n) {
+    if (!append(src, n)) {
+        flushed = true;  // stop capture loop
+        return false;
+    }
+    return true;
+}
...
-    append(&h, sizeof(h));
+    if (!appendOrStop(&h, sizeof(h))) return;
...
-    append(&fr, sizeof(fr));
+    if (!appendOrStop(&fr, sizeof(fr))) return;
...
-        append(&er, sizeof(er));
+        if (!appendOrStop(&er, sizeof(er))) return;

Also applies to: 221-221, 273-285

🤖 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/PerfTraceBench/PerfTraceBench.ino` around lines 163 - 171, The code
ignores append()'s boolean return which can signal buffer overflow, allowing
silent truncation; update all call sites (e.g., the loop using
g_name_count/g_name_ptrs/g_name_offsets/g_used and the other occurrences around
lines mentioned) to check append(...)'s return value and on false immediately
stop further writes and return or set an error flag so the caller can fail fast
(propagate an error code or abort dump creation). Ensure each append call in
functions handling frame/event/name records returns failure up the stack (or
triggers a single centralized error path) so partially-written records are not
left in the buffer.

233-243: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Patch header after name-table append; total_bytes is currently stale.

At Line 239, total_bytes is computed before flushToFlash() appends the name table, so header metadata under-reports payload size.

Proposed fix
-    if (g_frame >= NUM_FRAMES) {
-        // Patch header (num_frames, total_bytes) before flush.
-        Header h{};
-        h.magic = 0xFA571DEDu;
-        h.version = 1;
-        h.num_frames = static_cast<uint16_t>(NUM_FRAMES);
-        h.total_bytes = static_cast<uint32_t>(g_used - sizeof(Header));
-        memcpy(g_buf, &h, sizeof(h));
-
+    if (g_frame >= NUM_FRAMES) {
         flushToFlash();
         Serial.print("[PerfTraceBench] flushed ");
         ...
     }
 static void flushToFlash() {
     if (flushed) return;
     ...
     for (size_t i = 0; i < g_name_count; ++i) {
         ...
     }
+
+    Header h{};
+    h.magic = 0xFA571DEDu;
+    h.version = 1;
+    h.num_frames = static_cast<uint16_t>(g_frame);
+    h.total_bytes = static_cast<uint32_t>(g_used - sizeof(Header));
+    h.reserved = 0;
+    memcpy(g_buf, &h, sizeof(h));

Also applies to: 161-171

🤖 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/PerfTraceBench/PerfTraceBench.ino` around lines 233 - 243, The
header's total_bytes field is calculated before the name-table is appended, so
it under-reports payload size; update the logic in the block that checks g_frame
>= NUM_FRAMES (and the similar block around the 161-171 region) to compute
Header::total_bytes after the name-table has been appended (i.e., after
flushToFlash() or after the function that appends the name table) and then
memcpy the updated Header into g_buf; reference symbols: g_frame, NUM_FRAMES,
Header, total_bytes, g_used, g_buf, flushToFlash to locate and reorder the
assignments accordingly.

174-189: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Avoid erasing arbitrary data partitions and check flash API results.

Selecting the first writable data partition is unsafe, and esp_partition_erase_range / esp_partition_write return values are ignored. A wrong partition or failed write can silently corrupt device state or output.

Proposed hardening
-    const esp_partition_t* part = esp_partition_find_first(
-        ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, NULL);
+    const esp_partition_t* part = esp_partition_find_first(
+        ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, "perftrace");
     if (!part) {
         flushed = true;
         return;
     }
+    if (g_used > part->size) {
+        flushed = true;
+        return;
+    }
...
-    esp_partition_erase_range(part, 0, erase_size);
-    esp_partition_write(part, 0, g_buf, g_used);
+    esp_err_t err = esp_partition_erase_range(part, 0, erase_size);
+    if (err != ESP_OK) { flushed = true; return; }
+    err = esp_partition_write(part, 0, g_buf, g_used);
+    if (err != ESP_OK) { flushed = true; return; }
🤖 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/PerfTraceBench/PerfTraceBench.ino` around lines 174 - 189, Don't
pick the first data partition blindly and don't ignore flash API results: locate
a safe target partition using a specific identifier (e.g., partition label or an
explicit subtype) instead of esp_partition_find_first(NULL), validate the chosen
esp_partition_t (check type/subtype/label and that part->size is sufficient),
compute erase_size as done but cap it to part->size, then call
esp_partition_erase_range and esp_partition_write and check their esp_err_t
return values (use esp_err_to_name for logging); on any error, log the failure,
set flushed = true or return early and do not update
flush_part_offset/flush_part_size until the erase+write succeed.

125-148: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix addAllLanes() preprocessor guards to prevent out-of-bounds lane access.

Current grouped guards overrun when NUM_STRIPS is not 12 (e.g., NUM_STRIPS=3 still executes AddLane<3,3>::run()).

Proposed fix
 static void addAllLanes() {
     AddLane<0, 0>::run();
 `#if` NUM_STRIPS > 1
     AddLane<1, 1>::run();
 `#endif`
 `#if` NUM_STRIPS > 2
     AddLane<2, 2>::run();
-    AddLane<3, 3>::run();
 `#endif`
+#if NUM_STRIPS > 3
+    AddLane<3, 3>::run();
+#endif
 `#if` NUM_STRIPS > 4
     AddLane<4, 4>::run();
-    AddLane<5, 5>::run();
-    AddLane<6, 6>::run();
-    AddLane<7, 7>::run();
 `#endif`
+#if NUM_STRIPS > 5
+    AddLane<5, 5>::run();
+#endif
+#if NUM_STRIPS > 6
+    AddLane<6, 6>::run();
+#endif
+#if NUM_STRIPS > 7
+    AddLane<7, 7>::run();
+#endif
 `#if` NUM_STRIPS > 8
     AddLane<8, 8>::run();
-    AddLane<9, 9>::run();
-    AddLane<10, 10>::run();
-    AddLane<11, 11>::run();
 `#endif`
+#if NUM_STRIPS > 9
+    AddLane<9, 9>::run();
+#endif
+#if NUM_STRIPS > 10
+    AddLane<10, 10>::run();
+#endif
+#if NUM_STRIPS > 11
+    AddLane<11, 11>::run();
+#endif
 `#if` NUM_STRIPS > 12
 `#error` "Extend addAllLanes() for >12 strips"
 `#endif`
 }
🤖 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/PerfTraceBench/PerfTraceBench.ino` around lines 125 - 148, The
grouped preprocessor checks in addAllLanes() allow AddLane<N,N>::run() to be
compiled for indices >= the group threshold (e.g., NUM_STRIPS=3 still includes
AddLane<3,3>::run()), causing out-of-bounds lane access; fix by making each
AddLane<N,N>::run() guarded by its own correct condition (e.g., ensure the guard
for AddLane<3,3>::run() is based on NUM_STRIPS > 3), or replace the manual
blocks with a single pattern that emits AddLane<N,N>::run() only when N <
NUM_STRIPS (applies to all references to AddLane in addAllLanes()).

6-14: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Move this temporary bench out of examples/*.ino unless it is a permanent user-facing example.

The file is explicitly framed as a temporary debugging/workaround sketch (“delete once #2507 is resolved”), which conflicts with the .ino policy for this repo.

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

Also applies to: 16-23

🤖 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/PerfTraceBench/PerfTraceBench.ino` around lines 6 - 14,
PerfTraceBench.ino is a temporary debug sketch (notes "delete once `#2507` is
resolved") and must not live under examples/*.ino; either convert/move it: if
you want to keep it as a repo-only bench, move PerfTraceBench.ino to a
tools/bench or tests directory and change it to a standalone .cpp/.h (or test)
that builds via the repo test/tooling system, update any build/test scripts that
reference it, and remove it from examples; alternatively, if it is intended as a
permanent user-facing example, rework the sketch to meet example guidelines and
keep it under examples with a proper description and no "temporary" note —
reference the file PerfTraceBench.ino and the inline "delete once `#2507`" comment
when making the change.

78-85: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Fix EventRec.name_offset semantics/docs (offset vs index)

  • PerfTraceBench.ino writes EventRec.name_offset = intern_name(...), and intern_name() returns the interned index (e.g., line ~283), not a byte offset.
  • ci/perf_trace_decode.py treats name_off as an index (names[name_off]), while the struct/comment text describes it as a byte offset into name_table.
  • g_name_offsets[] is computed during name table building but isn’t used when emitting events; either rename/repurpose the field to name_index/“index into name_table”, or change producer+decoder to use true byte offsets.
🤖 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/PerfTraceBench/PerfTraceBench.ino` around lines 78 - 85,
EventRec.name_offset currently holds the interned name index (set by
intern_name()) but is documented/treated as a byte offset; update the producer
and decoder to use a consistent semantic: either rename the field to name_index
everywhere (struct EventRec.name_offset, the intern_name() return usage, and
decoder lookup in ci/perf_trace_decode.py) and stop computing/using
g_name_offsets, or change intern_name() to return a byte offset and make the
event emitter write g_name_offsets[index] into EventRec.name_offset while
adjusting the decoder to index into name_table by byte offset; pick one approach
and apply the change consistently across EventRec, intern_name(), g_name_offsets
construction, and ci/perf_trace_decode.py.
🤖 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.

Outside diff comments:
In `@examples/PerfTraceBench/PerfTraceBench.ino`:
- Around line 163-171: The code ignores append()'s boolean return which can
signal buffer overflow, allowing silent truncation; update all call sites (e.g.,
the loop using g_name_count/g_name_ptrs/g_name_offsets/g_used and the other
occurrences around lines mentioned) to check append(...)'s return value and on
false immediately stop further writes and return or set an error flag so the
caller can fail fast (propagate an error code or abort dump creation). Ensure
each append call in functions handling frame/event/name records returns failure
up the stack (or triggers a single centralized error path) so partially-written
records are not left in the buffer.
- Around line 233-243: The header's total_bytes field is calculated before the
name-table is appended, so it under-reports payload size; update the logic in
the block that checks g_frame >= NUM_FRAMES (and the similar block around the
161-171 region) to compute Header::total_bytes after the name-table has been
appended (i.e., after flushToFlash() or after the function that appends the name
table) and then memcpy the updated Header into g_buf; reference symbols:
g_frame, NUM_FRAMES, Header, total_bytes, g_used, g_buf, flushToFlash to locate
and reorder the assignments accordingly.
- Around line 174-189: Don't pick the first data partition blindly and don't
ignore flash API results: locate a safe target partition using a specific
identifier (e.g., partition label or an explicit subtype) instead of
esp_partition_find_first(NULL), validate the chosen esp_partition_t (check
type/subtype/label and that part->size is sufficient), compute erase_size as
done but cap it to part->size, then call esp_partition_erase_range and
esp_partition_write and check their esp_err_t return values (use esp_err_to_name
for logging); on any error, log the failure, set flushed = true or return early
and do not update flush_part_offset/flush_part_size until the erase+write
succeed.
- Around line 125-148: The grouped preprocessor checks in addAllLanes() allow
AddLane<N,N>::run() to be compiled for indices >= the group threshold (e.g.,
NUM_STRIPS=3 still includes AddLane<3,3>::run()), causing out-of-bounds lane
access; fix by making each AddLane<N,N>::run() guarded by its own correct
condition (e.g., ensure the guard for AddLane<3,3>::run() is based on NUM_STRIPS
> 3), or replace the manual blocks with a single pattern that emits
AddLane<N,N>::run() only when N < NUM_STRIPS (applies to all references to
AddLane in addAllLanes()).
- Around line 6-14: PerfTraceBench.ino is a temporary debug sketch (notes
"delete once `#2507` is resolved") and must not live under examples/*.ino; either
convert/move it: if you want to keep it as a repo-only bench, move
PerfTraceBench.ino to a tools/bench or tests directory and change it to a
standalone .cpp/.h (or test) that builds via the repo test/tooling system,
update any build/test scripts that reference it, and remove it from examples;
alternatively, if it is intended as a permanent user-facing example, rework the
sketch to meet example guidelines and keep it under examples with a proper
description and no "temporary" note — reference the file PerfTraceBench.ino and
the inline "delete once `#2507`" comment when making the change.
- Around line 78-85: EventRec.name_offset currently holds the interned name
index (set by intern_name()) but is documented/treated as a byte offset; update
the producer and decoder to use a consistent semantic: either rename the field
to name_index everywhere (struct EventRec.name_offset, the intern_name() return
usage, and decoder lookup in ci/perf_trace_decode.py) and stop computing/using
g_name_offsets, or change intern_name() to return a byte offset and make the
event emitter write g_name_offsets[index] into EventRec.name_offset while
adjusting the decoder to index into name_table by byte offset; pick one approach
and apply the change consistently across EventRec, intern_name(), g_name_offsets
construction, and ci/perf_trace_decode.py.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8381c6e8-eb36-4943-9ef1-8765241ae257

📥 Commits

Reviewing files that changed from the base of the PR and between b94e11e and 87431a4.

📒 Files selected for processing (2)
  • examples/PerfTraceBench/PerfTraceBench.ino
  • platformio.ini
✅ Files skipped from review due to trivial changes (1)
  • platformio.ini

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.

1 participant