Repository navigation
feat(watchdog): non-allocating reset/crash classification API + ScopedWatchdog - #2756
Conversation
…dWatchdog Implements issue #2755 — adds a normalized, allocation-free, no-destructor classification API on top of the existing fl::Watchdog so the AutoResearch boot-cause diagnostic stops being eight lines of bit-twiddling. New public surface in src/fl/wdt/watchdog.h: // Tier 0 — zero-cost static names backed by string literals in flash fl::string_view fl::resetCauseName(ResetCause c) noexcept; // Tier 1 — bundled cause + platform raw register + describe() to buffer struct fl::ResetInfo { ResetCause cause; fl::u8 subcauseId; fl::u32 rawRegister; fl::string_view causeName() const noexcept; fl::string_view subcauseName() const noexcept; fl::size describe(fl::span<char> out, bool verbose = false) const noexcept; }; fl::ResetInfo fl::Watchdog::lastResetInfo() const noexcept; // Tier 1.5 — RAII guard + variadic macro for loop()-top use class fl::ScopedWatchdog { explicit ScopedWatchdog(fl::u32 timeout_ms = 15000) noexcept; ~ScopedWatchdog() noexcept; }; #define FL_WATCHDOG_AUTOFEED(...) // unique-name-per-line variadic macro ScopedWatchdog feeds the watchdog on BOTH construction and destruction so a loop iteration starts with a fresh deadline and the next iteration also starts fresh. First construction per process lazily arms the WDT, prints any prior-boot recovery diagnostic via `fl::println`, and pauses 3 s on a crash so the developer can read the message before loop() repaints serial. Implementation files (per FastLED unity-build convention): - src/fl/wdt/watchdog.cpp.hpp — the actual implementations - src/fl/wdt/_build.cpp.hpp — unity build aggregator + print sink - src/fl/build/fl.wdt+.cpp — top-level unity TU entry - src/fl/_build.cpp.hpp — wired in the new fl/wdt/ subdir - ci/lint_cpp/test_unity_build.py — registered fl.wdt+.cpp in EXPECTED_BUILD_FILES The current default `lastResetInfo()` returns `{lastResetCause(), 0, 0}` on every platform. Per-platform richer subcause/raw-register capture (e.g., SRC_SRSR bit decoding on Teensy 4) is a follow-up tracked in issue #2755. Tests added in tests/fl/wdt/watchdog.cpp: - resetCauseName() maps every enum value to a non-empty static view - describe() — terse format, verbose format, NUL termination, truncation safety, zero-sized buffer is safe - lastResetInfo() default returns {cause, 0, 0} - ScopedWatchdog feeds on construction and destruction - FL_WATCHDOG_AUTOFEED() / FL_WATCHDOG_AUTOFEED(timeout) both compile All 15+ existing watchdog tests + new tests pass on the host stub. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThe PR adds ResetInfo-based reset-cause introspection and resetCauseName(), extends Watchdog with lastResetInfo(), introduces ScopedWatchdog RAII with nesting detection and FL_WATCHDOG_AUTO macro, wires platform helpers via a unity-build header and wrapper TU, documents helper origins, updates CI unity-build expectations, and adds tests covering all new behavior. ChangesWatchdog API expansion and auto-feed RAII guard
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 Infer (1.2.0)tests/fl/wdt/watchdog.cpptests/fl/wdt/watchdog.cpp:12:10: fatal error: 'fl/wdt/watchdog.h' file not found ... [truncated 1076 characters] ... g/install/lib/clang/18/include" 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.
🧹 Nitpick comments (1)
src/fl/wdt/watchdog.h (1)
95-103: 💤 Low valueDocumentation format spec is slightly incomplete.
The format description implies
verbosealways produces"<cause> (<sub>) raw=0x<hex>", but the implementation (and tests) show subcause is only included whensubcauseId != 0. A clearer breakdown:<cause> subcauseId == 0 && !verbose <cause> (<sub>) subcauseId != 0 && !verbose <cause> raw=0x<hex> subcauseId == 0 && verbose <cause> (<sub>) raw=0x<hex> subcauseId != 0 && verboseThis is a minor doc polish—the implementation is correct.
🤖 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/wdt/watchdog.h` around lines 95 - 103, Update the documentation comment for the describe method to list all four output cases explicitly to match the implementation and tests: clarify that when verbose=false and subcauseId==0 the output is "<cause>", when verbose=false and subcauseId!=0 it's "<cause> (<sub>)", when verbose=true and subcauseId==0 it's "<cause> raw=0x<hex>", and when verbose=true and subcauseId!=0 it's "<cause> (<sub>) raw=0x<hex>". Reference the describe(fl::span<char> out, bool verbose = false) const FL_NOEXCEPT declaration and adjust the comment block above it accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/fl/wdt/watchdog.h`:
- Around line 95-103: Update the documentation comment for the describe method
to list all four output cases explicitly to match the implementation and tests:
clarify that when verbose=false and subcauseId==0 the output is "<cause>", when
verbose=false and subcauseId!=0 it's "<cause> (<sub>)", when verbose=true and
subcauseId==0 it's "<cause> raw=0x<hex>", and when verbose=true and
subcauseId!=0 it's "<cause> (<sub>) raw=0x<hex>". Reference the
describe(fl::span<char> out, bool verbose = false) const FL_NOEXCEPT declaration
and adjust the comment block above it accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 577954be-aa76-4839-82b9-b7370a3e248d
📒 Files selected for processing (8)
ci/lint_cpp/test_unity_build.pysrc/fl/_build.cpp.hppsrc/fl/build/fl.wdt+.cppsrc/fl/wdt/_build.cpp.hppsrc/fl/wdt/watchdog.cpp.hppsrc/fl/wdt/watchdog.hsrc/platforms/watchdog.impl.cpp.hpptests/fl/wdt/watchdog.cpp
… add nesting detection
The previous name FL_WATCHDOG_AUTOFEED implied the macro just refreshes the
watchdog. It actually does much more: lazy WDT arm on first call, last-crash
diagnostic print, 3-second pause on crash, then feeds on both construction and
destruction. The new name FL_WATCHDOG_AUTO captures "automatic management"
instead of just "automatic feed".
Naming chosen so the FL_WATCHDOG_* prefix groups every watchdog macro for
greppability — future variants (FL_WATCHDOG_QUIET, FL_WATCHDOG_VERBOSE,
FL_WATCHDOG_MANUAL) stay under the same prefix. Matches the FastLED convention
of FL_<feature>_<modifier> (FL_TEST_CASE, FL_CHECK_EQ).
Also: single-instance enforcement. Two simultaneously-alive ScopedWatchdog
instances are almost always a programmer error — the second one's timeout
argument is silently ignored, and the lazy first-init only ran for the first.
Both construction and destruction now track an active-scope counter; when the
counter exceeds 1, a one-shot warning is printed via fl::println so the
developer notices. The WDT is still fed in both ctor and dtor so the program
keeps running safely.
Two macros on the same source line are already a compile error because the
local variable name is stamped from __LINE__.
New public observability accessor:
static int fl::ScopedWatchdog::activeScopeCount() noexcept;
Used by the new "nesting detection counter" test to validate the counter
increments on ctor and decrements on dtor.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Update — macro rename + nesting detectionPer review feedback on the macro name, Why the rename
Naming alternatives considered
Single-instance enforcement addedAlso from the same review feedback: "what happens if we have two watchdog macros in use? this can be a serious problem, i think that we should prevent this from happening." Two simultaneously-alive
New observability accessor Diff summary
All existing watchdog tests + new tests pass on the host stub. 🤖 Generated with Claude Code |
Summary
Implements the design from #2755 — adds a normalized, allocation-free, no-destructor classification API on top of the existing
fl::Watchdogso users no longer need bit-twiddling on platform-specific reset-cause registers. Also adds a zero-setupFL_WATCHDOG_AUTOFEED()macro that drops a RAII guard at the top ofloop().Public API surface added
Usage replaces the 8-line bit-twiddle in
AutoResearch.inowith one line:ScopedWatchdogfeeds the watchdog on both construction and destruction so a loop iteration starts with a fresh deadline AND the next iteration also starts fresh. The first construction per process lazily arms the WDT, prints any prior-boot reset/crash diagnostic viafl::println, and pauses 3 s on a crash so the developer can read the message beforeloop()repaints serial.Why
fl::span<char>(caller-owned buffer) and notfl::string(allocating)The user requirement was "fl::string which doesn't allocate memory, nor destruct the memory." The closest existing types map cleanly:
fl::string_view— non-owning view, no allocation, no destructor → used for fixed enum names (Tier 0)fl::span<char>— caller-owned buffer, no allocation, no destructor → used for dynamic content viadescribe(out, verbose)(Tier 1, 2)snprintf-style pattern: caller controls capacity, method returns bytes written, truncation is safe, zero allocationTests
10 new test cases in
tests/fl/wdt/watchdog.cpp:fl::resetCauseNamemaps every enum value to a non-empty static viewdescribe()— terse format, verbose format, NUL termination, truncation safety, zero-sized bufferlastResetInfo()default returns{lastResetCause(), 0, 0}ScopedWatchdogfeeds on construction and destructionFL_WATCHDOG_AUTOFEED()/FL_WATCHDOG_AUTOFEED(timeout)both compileAll existing watchdog tests + new tests pass on the host stub.
Unity-build / build-system wiring
Following the existing
fl/X/convention:src/fl/wdt/watchdog.cpp.hpp— implementations (ResetInfo::describe,ScopedWatchdogctor/dtor)src/fl/wdt/_build.cpp.hpp— unity build aggregator + print/delay sinkssrc/fl/build/fl.wdt+.cpp— top-level unity TU entrysrc/fl/_build.cpp.hpp— wired in the newfl/wdt/subdirci/lint_cpp/test_unity_build.py— registeredfl.wdt+.cppinEXPECTED_BUILD_FILESThe dispatcher (
src/platforms/watchdog.impl.cpp.hpp) is unchanged — platform impls still live in their.impl.hppfiles. The new TU only adds the platform-agnostic helpers.Phase 2 follow-ups (tracked in #2755)
lastResetInfo()extraction:SRC_SRSRbits →subcauseId(0=WDOG3, 1=WDOG1/2, 2=LOCKUP, …) + raw registeresp_reset_reason()already structured; just lift itMCUSRbit → subcauseIdWatchdogCrashReport::describe()for the Tier 2 fault frame (multi-line)CrashReport::platformDetails()Tier Max escape hatch (returnsvoid*to platform-defined struct)References
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests