Skip to content

feat(watchdog): non-allocating reset/crash classification API + ScopedWatchdog - #2756

Merged
zackees merged 2 commits into
masterfrom
feat/watchdog-reset-classification-api
Jun 4, 2026
Merged

zackees merged 2 commits into
masterfrom
feat/watchdog-reset-classification-api

Conversation

@zackees

@zackees zackees commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Implements the design from #2755 — adds a normalized, allocation-free, no-destructor classification API on top of the existing fl::Watchdog so users no longer need bit-twiddling on platform-specific reset-cause registers. Also adds a zero-setup FL_WATCHDOG_AUTOFEED() macro that drops a RAII guard at the top of loop().

Public API surface added

// 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 caller 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 for loop()-top use
class fl::ScopedWatchdog {
public:
    ScopedWatchdog() noexcept;                          // 15 000 ms default
    explicit ScopedWatchdog(fl::u32 timeout_ms) noexcept;
    ~ScopedWatchdog() noexcept;
};

// Variadic macro — same name handles both forms
#define FL_WATCHDOG_AUTOFEED(...) \
    ::fl::ScopedWatchdog FL_WATCHDOG__CONCAT(_fl_wdt_, __LINE__) { __VA_ARGS__ }

Usage replaces the 8-line bit-twiddle in AutoResearch.ino with one line:

void loop() {
    FL_WATCHDOG_AUTOFEED();   // feeds on construction, lazily arms on first call,
                              // prints prior reset/crash info + waits 3 s on crash
    doWork();                 // destructor feeds again at end-of-scope
}

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. The first construction per process lazily arms the WDT, prints any prior-boot reset/crash diagnostic via fl::println, and pauses 3 s on a crash so the developer can read the message before loop() repaints serial.

Why fl::span<char> (caller-owned buffer) and not fl::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 via describe(out, verbose) (Tier 1, 2)
  • This is the snprintf-style pattern: caller controls capacity, method returns bytes written, truncation is safe, zero allocation

Tests

10 new test cases in tests/fl/wdt/watchdog.cpp:

  • fl::resetCauseName maps every enum value to a non-empty static view
  • describe() — terse format, verbose format, NUL termination, truncation safety, zero-sized buffer
  • lastResetInfo() default returns {lastResetCause(), 0, 0}
  • ScopedWatchdog feeds on construction and destruction
  • FL_WATCHDOG_AUTOFEED() / FL_WATCHDOG_AUTOFEED(timeout) both compile

All 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, ScopedWatchdog ctor/dtor)
  • src/fl/wdt/_build.cpp.hpp — unity build aggregator + print/delay sinks
  • 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 dispatcher (src/platforms/watchdog.impl.cpp.hpp) is unchanged — platform impls still live in their .impl.hpp files. The new TU only adds the platform-agnostic helpers.

Phase 2 follow-ups (tracked in #2755)

  • Per-platform lastResetInfo() extraction:
  • WatchdogCrashReport::describe() for the Tier 2 fault frame (multi-line)
  • CrashReport::platformDetails() Tier Max escape hatch (returns void* to platform-defined struct)

References

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Expanded watchdog API with richer reset diagnostics (cause, subcause, raw register) and a ResetInfo describe() API
    • Added RAII watchdog guard that auto-feeds, reports recoveries, detects nesting, and exposes active-scope count
    • Added convenience macro to instantiate the automatic watchdog guard
  • Tests

    • Added comprehensive tests for reset naming, describe() formatting/truncation, auto-feeding semantics, macro usage, and nesting behavior

…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]>
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: dbca1d89-62d5-4f50-a15e-28cdbba0ff1c

📥 Commits

Reviewing files that changed from the base of the PR and between 0a3e1a4 and e08a661.

📒 Files selected for processing (3)
  • src/fl/wdt/watchdog.cpp.hpp
  • src/fl/wdt/watchdog.h
  • tests/fl/wdt/watchdog.cpp

📝 Walkthrough

Walkthrough

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

Changes

Watchdog API expansion and auto-feed RAII guard

Layer / File(s) Summary
ResetInfo and Watchdog API contracts
src/fl/wdt/watchdog.h
ResetCause→string_view mapper, ResetInfo bundling cause/subcause/raw with causeName(), subcauseName(), and describe(), and Watchdog::lastResetInfo(); ScopedWatchdog declaration and FL_WATCHDOG_AUTO macro.
ResetInfo serialization and Watchdog::lastResetInfo implementations
src/fl/wdt/watchdog.cpp.hpp
ResetInfo::subcauseName() default, ResetInfo::describe() formats cause, optional parenthesized subcause, verbose raw= hex suffix, safe NUL-termination/truncation; Watchdog::lastResetInfo() default.
ScopedWatchdog initialization, nesting, and auto-feed
src/fl/wdt/watchdog.cpp.hpp
One-time per-process init calling Watchdog::begin(), recovery detection/verbose describe, optional crash-report check, 3s pause via platform helper, armed message, feed-on-construction/destruction, active-scope counter and nesting warning, activeScopeCount().
Platform helpers and unity-build wiring
src/fl/wdt/_build.cpp.hpp, src/fl/build/fl.wdt+.cpp, src/fl/_build.cpp.hpp, src/platforms/watchdog.impl.cpp.hpp, ci/lint_cpp/test_unity_build.py
New unity header defines scopedWatchdogPrintLine() and scopedWatchdogPause3s() in fl::platforms; wrapper TU added; main unity header includes watchdog unity header; impl comment documents origin; CI lint test updated to accept fl/build/fl.wdt+.cpp.
Comprehensive test coverage for all new APIs
tests/fl/wdt/watchdog.cpp
Tests for resetCauseName mapping, ResetInfo::describe terse/verbose/truncation/NUL safety, Watchdog::lastResetInfo defaults, ScopedWatchdog auto-feed (default and explicit timeouts), FL_WATCHDOG_AUTO macro compilation, and nesting counter behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2738: Related unified watchdog work touching ResetInfo/Watchdog/ScopedWatchdog components.
  • FastLED/FastLED#2442: Similar unity-build plumbing updates (build TU recognition and main unity header includes).

Poem

🐰 I hopped through code with tiny feet,

Tucked ResetInfo where causes meet,
ScopedWatchdog guards each looping beat,
A pause, a print, then all is neat,
FL_WATCHDOG_AUTO — safe and sweet.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main changes: adding a non-allocating reset/crash classification API and a ScopedWatchdog RAII helper to the watchdog module.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
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/watchdog-reset-classification-api

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

tests/fl/wdt/watchdog.cpp:12:10: fatal error: 'fl/wdt/watchdog.h' file not found
12 | #include "fl/wdt/watchdog.h"
| ^~~~~~~~~~~~~~~~~~~
1 error generated.
Error: the following clang command did not run successfully:
/opt/infer-linux-x86_64-v1.2.0/lib/infer/facebook-clang-plugins/clang/install/bin/clang-18
@/tmp/coderabbit-infer/e08a6614c265f9429cb6443d1b2b3cfd51216fe6-0b668f5123294558/tmp/clang_command_.tmp.56b91c.txt
++Contents of '/tmp/coderabbit-infer/e08a6614c265f9429cb6443d1b2b3cfd51216fe6-0b668f5123294558/tmp/clang_command_.tmp.56b91c.txt':
"-cc1" "-load"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../../facebook-clang-plugins/libtooling/build/FacebookClangPlugin.dylib"
"-add-plugin" "BiniouASTExporter" "-plugin-arg-BiniouASTExporter" "-"
"-plugin-arg-BiniouASTExporter" "PREPEND_CURRENT_DIR=1"
"-plugin-arg-BiniouASTExporter" "MAX_STRING_SIZE=65535" "-cc1" "-triple"
"x86_64-unknown-linux-gnu" "-emit-obj" "-mrelax-all" "-

... [truncated 1076 characters] ...

g/install/lib/clang/18/include"
"-internal-isystem" "/usr/local/include" "-internal-isystem"
"/usr/lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
"-internal-externc-isystem" "/usr/include/x86_64-linux-gnu"
"-internal-externc-isystem" "/include" "-internal-externc-isystem"
"/usr/include" "-Wno-ignored-optimization-argument" "-Wno-everything"
"-fdeprecated-macro" "-ferror-limit" "19" "-fgnuc-version=4.2.1"
"-fskip-odr-check-in-gmf" "-fcxx-exceptions" "-fexceptions"
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o"
"/tmp/coderabbit-infer/0b668f5123294558/file.o" "-x" "c++"
"tests/fl/wdt/watchdog.cpp" "-O0" "-fno-builtin" "-include"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../lib/clang_wrappers/global_defines.h"
"-Wno-everything"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/fl/wdt/watchdog.h (1)

95-103: 💤 Low value

Documentation format spec is slightly incomplete.

The format description implies verbose always produces "<cause> (<sub>) raw=0x<hex>", but the implementation (and tests) show subcause is only included when subcauseId != 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 && verbose

This 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

📥 Commits

Reviewing files that changed from the base of the PR and between d848871 and 0a3e1a4.

📒 Files selected for processing (8)
  • ci/lint_cpp/test_unity_build.py
  • src/fl/_build.cpp.hpp
  • src/fl/build/fl.wdt+.cpp
  • src/fl/wdt/_build.cpp.hpp
  • src/fl/wdt/watchdog.cpp.hpp
  • src/fl/wdt/watchdog.h
  • src/platforms/watchdog.impl.cpp.hpp
  • tests/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]>
@zackees

zackees commented Jun 4, 2026

Copy link
Copy Markdown
Member Author

Update — macro rename + nesting detection

Per review feedback on the macro name, FL_WATCHDOG_AUTOFEED → FL_WATCHDOG_AUTO.

Why the rename

FL_WATCHDOG_AUTOFEED implied the macro just refreshes the WDT. It actually does much more: lazy first-call WDT arm, last-crash diagnostic print, 3-second pause on crash, then feeds on both construction and destruction. FL_WATCHDOG_AUTO captures "automatic management" instead of just "automatic feed".

Naming alternatives considered

Candidate Family extensibility Reads like
FL_WATCHDOG_AUTO(timeout) ✅ All watchdog macros stay under one FL_WATCHDOG_* prefix — greppable family "watchdog in auto mode"
FL_AUTO_WATCHDOG(timeout) Splits family across FL_AUTO_* and FL_MANUAL_* "the automatic watchdog"
FL_WATCHDOG_GUARD(timeout) RAII vocab but doesn't say "auto-init" "guard a scope"
FL_WATCHDOG(timeout) Collision risk with capability macros FL_WATCHDOG_HAS_* "watchdog this scope"
FL_LOOP_WATCHDOG(timeout) Locks to loop() use only "loop's watchdog"

FL_WATCHDOG_AUTO won on family discoverability — future FL_WATCHDOG_QUIET, FL_WATCHDOG_VERBOSE, FL_WATCHDOG_MANUAL all stay in one grep-able prefix, and it matches FastLED's FL_<feature>_<modifier> convention (FL_TEST_CASE, FL_CHECK_EQ).

Single-instance enforcement added

Also 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 ScopedWatchdog instances are almost always a bug — the second one's timeout_ms argument is silently ignored (only the first instance gets to arm the WDT). Detection now happens at two levels:

Misuse Detection
Two FL_WATCHDOG_AUTO() on the same source line Compile error — the local variable name is _fl_wdt_<__LINE__>, so duplicates collide
Two FL_WATCHDOG_AUTO() on different lines but simultaneously alive (nested scopes) Runtime — active-scope counter > 1 triggers a one-shot fl::println warning, WDT still fed for safety

New observability accessor fl::ScopedWatchdog::activeScopeCount() lets tests + diagnostics inspect the counter directly.

Diff summary

  • src/fl/wdt/watchdog.h — rename macro, document single-instance rule, add activeScopeCount() declaration
  • src/fl/wdt/watchdog.cpp.hpp — counter increment/decrement in ctor/dtor, one-shot warn on nesting
  • tests/fl/wdt/watchdog.cpp — new "nesting detection counter" test validates ctor inc / dtor dec

All existing watchdog tests + new tests pass on the host stub.

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant