Repository navigation
Conversation
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]>
📝 WalkthroughWalkthroughAdds 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. ChangesPerformance Tracing System
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (12)
ci/perf_trace_sweep.pyexamples/AutoResearch/AutoResearchRemote.cppplatformio.inisrc/FastLED.cpp.hppsrc/fl/channels/driver.cpp.hppsrc/fl/channels/manager.cpp.hppsrc/fl/system/_build.cpp.hppsrc/fl/system/perf_trace.cpp.hppsrc/fl/system/perf_trace.hsrc/platforms/esp/32/drivers/parlio/channel_driver_parlio.cpp.hpptests/fl/log.cpptests/fl/system/perf_trace.hpp
| Usage: | ||
| uv run ci/perf_trace_sweep.py --port COM25 \ | ||
| --lanes 12 --strip-size 256 |
There was a problem hiding this comment.
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.
| 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: |
There was a problem hiding this comment.
🛠️ 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 . || trueRepository: 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
fiRepository: 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.
| 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() | ||
|
|
There was a problem hiding this comment.
🧩 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
fiRepository: 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 || trueRepository: 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()}")
PYRepository: 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()}")
PYRepository: 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 || trueRepository: FastLED/FastLED
Length of output: 92
Make main() accept argv and preserve KeyboardInterrupt.
ci/perf_trace_sweep.pycurrently callsparser.parse_args()with no argv (lines 94-103); accept an optionallist[str]and pass it toparse_args(argv)for deterministic tests.main()catchesExceptionwithout re-raisingKeyboardInterrupt(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.
| 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 |
There was a problem hiding this comment.
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.
| 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.
| #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 { |
There was a problem hiding this comment.
🧩 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 -C2Repository: 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.
| 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; |
There was a problem hiding this comment.
🧩 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 || trueRepository: 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.hRepository: 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
fiRepository: 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.hppRepository: 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"
doneRepository: 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 80Repository: 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 || trueRepository: 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;withstatic fl::atomic_bool g_enabled{false};(includefl/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
boolis “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]>
✅ Empirical sweep complete — PARLIO blocking issue still present, dramatically worse than #2493 reportedWorked around the #2507 USB-Serial-JTAG blocker with the new Setup
Result (steady-state per frame)
VerdictThe PARLIO blocking issue from #2493 is NOT resolved by #2503. It moved.
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 Frame 1 (representative)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 Next steps
🤖 Generated with Claude Code. |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
ci/perf_trace_decode.pyexamples/PerfTraceBench/PerfTraceBench.ino
| 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} | ||
|
|
There was a problem hiding this comment.
🧩 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"
fiRepository: 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]>
🎯 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 Before (no CDC_ON_BOOT)
After (CDC_ON_BOOT=1)
Steady-state 16 captured frames (frames 1-15): What changed and why I think it mattersWithout 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 Residual: 49.6 ms in waitForCondition vs ~7.6 ms expectedPARLIO drain for 256 LEDs WS2812B should be ~7.6 ms (12 lanes go in parallel). We're at 49.6 ms, ~6.5×. Suggestions:
Notes on autoresearch / fbuild
🤖 Generated with Claude Code |
There was a problem hiding this comment.
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 winHandle
append()failures; current code can silently emit corrupted/truncated dumps.
append()returnsfalseon 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 winPatch header after name-table append;
total_bytesis currently stale.At Line 239,
total_bytesis computed beforeflushToFlash()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 liftAvoid erasing arbitrary data partitions and check flash API results.
Selecting the first writable data partition is unsafe, and
esp_partition_erase_range/esp_partition_writereturn 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 winFix
addAllLanes()preprocessor guards to prevent out-of-bounds lane access.Current grouped guards overrun when
NUM_STRIPSis not 12 (e.g.,NUM_STRIPS=3still executesAddLane<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 liftMove this temporary bench out of
examples/*.inounless it is a permanent user-facing example.The file is explicitly framed as a temporary debugging/workaround sketch (“delete once
#2507is resolved”), which conflicts with the.inopolicy for this repo.As per coding guidelines,
**/*.ino: "Never create .ino files for minor testing or debugging - use test files or unit tests instead" andexamples/**/*.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 liftFix
EventRec.name_offsetsemantics/docs (offset vs index)
PerfTraceBench.inowritesEventRec.name_offset = intern_name(...), andintern_name()returns the interned index (e.g., line ~283), not a byte offset.ci/perf_trace_decode.pytreatsname_offas an index (names[name_off]), while the struct/comment text describes it as a byte offset intoname_table.g_name_offsets[]is computed during name table building but isn’t used when emitting events; either rename/repurpose the field toname_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
📒 Files selected for processing (2)
examples/PerfTraceBench/PerfTraceBench.inoplatformio.ini
✅ Files skipped from review due to trivial changes (1)
- platformio.ini
Summary
Continuing the work from #2494 — adds a thread-local Chrome-trace-style
fl::PerfTraceframework and wiresFL_PERF_SCOPEmarkers throughCFastLED::showand the PARLIO hot path. Combined with two new JSON-RPCs in the AutoResearch sketch (setPerfTraceEnabled,getPerfTraceLog) and aci/perf_trace_sweep.pydriver, 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=1markers from PR #2494 with a reusable framework — subsequent drivers can be instrumented by sprinklingFL_PERF_SCOPE("name")without bespoke timing boilerplate.Changes
src/fl/system/perf_trace.{h,cpp.hpp}(new)FixedVector<PerfEvent,32>) and completed-event log (FixedVector<PerfEvent,128>) held inSingletonThreadLocal.PerfEventcaptures(file*, name*, line, depth, start_us, end_us); string pointers are non-owning literals (__FILE__+ macro arg).FASTLED_PERF_TRACE; runtime gatefl::PerfTrace::set_enabled(bool). When either is off, macros are no-ops with zero overhead.FL_PERF_SCOPE(name)(RAII),FL_PERF_BEGIN(name)/FL_PERF_END(slot)(manual),FL_PERF_FRAME_FLUSH().flush()emits oneFL_INFOline 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— outershowscope + nestedonBeginFrame,min_micros_gate,showLedsInternal,endShowLeds.src/fl/channels/manager.cpp.hpp,src/fl/channels/driver.cpp.hpp—waitForConditionscopes 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 inImpl::poll,Impl::beginTransmission, outerpoll,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.iniesp32p4 env:-D FASTLED_PERF_TRACE=1(capture stays off at boot — autoresearch flips the runtime switch). Also flipsARDUINO_USB_MODE=1 → 0to routeSerialto 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 callssetPerfTraceEnabled(true)→runTest(PARLIO) →getPerfTraceLog()and prints a table or JSON.Tests
tests/fl/system/perf_trace.hpp(10 cases, all green):dropped()without corruptionevent_count()and setsdropped()clear()resets log, stack, and dropped flagVerified
bash test log/driver/channels/fastled_core --cppall pass andbash compile wasm --examples Blinksucceeds.Hardware validation is blocked — see #2507
bash autoresearch esp32p4 --parliofailed twice on this dev env:WString.h,soc/soc_caps.hnot found despite being present in the cached framework tree).pio run --target upload/ direct esptool, no bytes ever arrive on the COM port after device reset. SwitchingARDUINO_USB_MODEto 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
bash autoresearch esp32p4 --parliofails to build (WString.h / soc_caps.h missing, zccache hang) #2507 — meta issue: autoresearch + fbuild + esp32p4 broken (blocks empirical validation of this PR)Test plan
bash autoresearch esp32p4 --parliofails to build (WString.h / soc_caps.h missing, zccache hang) #2507: bash autoresearch esp32p4 --parlio + uv run ci/perf_trace_sweep.py --port COM25 --lanes 12 --strip-size 256 → confirm per-frame events show waitForCondition no longer dominates the show() budget.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tools
Tests
Chores