Skip to content

feat(watchdog): Phase 1 — unified fl::Watchdog API + host/stub/ESP32 impls - #2738

Merged
zackees merged 5 commits into
masterfrom
feat/watchdog-unified-api
Jun 4, 2026
Merged

zackees merged 5 commits into
masterfrom
feat/watchdog-unified-api

Conversation

@zackees

@zackees zackees commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 1 of the unified cross-platform watchdog API designed in #2731.

Lands the API surface + host-testable stub impl + ESP32 refactor of the existing fl::watchdog_setup(). All other platforms route through the no-op fallback (src/platforms/shared/watchdog_noop.hpp) — their hardware impls are tracked as follow-ups in #2731.

What's in this PR

  • Public header src/fl/wdt/watchdog.h — full Tier 0 + Tier 1 + Tier 2 API surface
  • Singleton accessor FastLED.watchdog() matching the existing FastLED.channelEvents() pattern
  • Dispatcher src/platforms/watchdog.impl.cpp.hpp (matches coroutine.impl.cpp.hpp style)
  • No-op fallback src/platforms/shared/watchdog_noop.hpp (matches memory_noop.hpp / pin_noop.hpp style — codified in docs(conventions): codify noop fallback and FL_<COMPONENT>_HAS_* macro patterns #2732)
  • Stub impl src/platforms/stub/watchdog_stub.impl.hpp — thread-backed deadline timer, full Tier 0 + onTimeout support; never std::abort()s the test process so unit tests can verify safe-mode behavior end-to-end
  • WASM impl src/platforms/wasm/watchdog_wasm.impl.hpp — currently routes to no-op (emscripten timer integration is its own follow-up)
  • ESP32 impl src/platforms/esp/32/watchdog_esp32.impl.hpp — wraps the existing fl::watchdog_setup() entry point; preserves the IDF v4/v5 weak-symbol panic override + USB-CDC disconnect that fixes the Windows phantom-COM-port bug
  • Tests tests/fl/wdt/watchdog.cpp — 15 cases covering Tier 0 + Tier 1, including timeout-fires + feed-prevents-fire + safe-mode-trips-at-threshold

What's NOT in this PR

Per-platform hardware implementations for Teensy 4 (WDT_T4<WDT3>), Teensy 3.x (K20 register code), RP2040/RP2350 (hardware/watchdog.h + scratch[0..3]), nRF52 (NRF_WDT + GPREGRET), STM32 (IWDG + RTC BKP), SAMD21/51 (WDT peripheral + SmartEEPROM), AVR (avr/wdt.h + EEPROM + .init3 MCUSR fix), Apollo3 (am_hal_wdt_*), MGM240 (em_wdog.h), and the WASM emscripten-emulated impl. These are tracked as Phase 2..5 in #2731.

All of those platforms compile cleanly in this PR — they route through the no-op fallback. User code that calls FastLED.watchdog().begin(15000) works everywhere; on unsupported platforms it's a no-op that lets the sketch keep running.

Test plan

  • bash test fl_wdt_watchdog --debug — 15/15 pass on host stub impl (sanitizers enabled)
  • bash lint --cpp — clean (no banned-header, FL_NOEXCEPT, static-in-header, or sleep-for violations)
  • CI: native build + WASM build + ESP32 platform compile + AVR/Teensy compile (all route through unchanged paths or no-op)
  • Hardware verification per platform — deferred to Phase 2 follow-ups in Unified cross-platform Watchdog Timer API via FastLED.watchdog() singleton #2731

References

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a unified Watchdog API accessible from the main singleton: configurable timeout, pre-timeout callbacks, persistent bytes, reset-cause reporting, safe-mode thresholding, crash-report access, and reboot controls (behavior varies by platform).
  • Platform Support

    • Platform implementations for ESP32, WASM routing, host stub, and a no-op fallback so behavior degrades gracefully.
  • Tests

    • New unit tests for lifecycle, persistence, callbacks, crash counting, safe-mode, and stub semantics.

…impls

Lands the cross-platform watchdog API designed in #2731:

**Public surface** — `FastLED.watchdog()` accessor returning `fl::Watchdog&`,
matching the `FastLED.channelEvents()` singleton pattern. Three tiers:
- Tier 0 (universal): begin/feed/disable, lastResetCause, persist read/write,
  consecutiveCrashCount, markCleanShutdown, isInSafeMode, reboot
- Tier 1 (most platforms): onTimeout (C pointer + fl::function overload),
  setPauseOnDebug, writeCrashLog, readCrashLog, rebootIntoBootloader
- Tier 2 (advanced): setWindow, hasCrashReport, readCrashReport

**Architecture** — follows the conventions landed in #2732:
- `src/fl/wdt/watchdog.h` public header with the API + `instance()` defined
  inline so every TU resolves the singleton call
- `src/platforms/watchdog.impl.cpp.hpp` single dispatcher (matches
  coroutine.impl.cpp.hpp / channel_drivers.impl.cpp.hpp pattern)
- `src/platforms/shared/watchdog_noop.hpp` no-op fallback (matches
  memory_noop.hpp / pin_noop.hpp / simd_noop.hpp pattern)
- Per-platform `.impl.hpp` fragments included by the dispatcher

**Platform impls (Phase 1)**:
- `platforms/stub/watchdog_stub.impl.hpp` — thread-backed deadline timer,
  fully tested; the stub never std::abort()s the test process so unit
  tests can verify crash-counter / safe-mode behavior
- `platforms/wasm/watchdog_wasm.impl.hpp` — currently routes to the noop
  fallback (emscripten timer integration is its own follow-up)
- `platforms/esp/32/watchdog_esp32.impl.hpp` — wraps the existing
  `fl::watchdog_setup()` entry; preserves the weak-symbol panic override
  and USB-CDC disconnect that fix the Windows phantom-COM-port bug
- All other platforms fall through to the noop fallback for now

**Tests** — `tests/fl/wdt/watchdog.cpp` exercises the full Tier 0 + Tier 1
surface against the stub impl: singleton accessor, begin/feed/disable,
persist storage, safe-mode threshold, crash counter, timeout firing,
feeding-prevents-fire, safe-mode trip. 15/15 pass on host.

**Capability macros** (Type 3 per cpp-standards.md):
- `FL_WATCHDOG_HAS_HARDWARE` — 1 on stub + ESP32, undefined on noop platforms
- `FL_WATCHDOG_PERSIST_BYTES` — 16 on stub/ESP32, 0 on noop
- `FL_WATCHDOG_MAX_TIMEOUT_MS` — 600000 on stub, 60000 on ESP32, 0 on noop
- `FL_WATCHDOG_HAS_PRE_TIMEOUT_IRQ`, `FL_WATCHDOG_HAS_WINDOW_MODE`,
  `FL_WATCHDOG_HAS_CRASH_REPORT` — set per platform

**Phase 2+** (tracked in #2731): Teensy 4 (`WDT_T4<WDT3>`), Teensy 3.x,
RP2040/2350, nRF52, STM32, SAMD21/51, AVR, Apollo3, MGM240, WASM
emscripten-emulated impl. Each remaining platform compiles unconditionally
through the noop fallback until its hardware impl lands.

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

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4d02637e-6179-44f2-8cc1-7f9d60317407

📥 Commits

Reviewing files that changed from the base of the PR and between bb71c5f and 8c62497.

📒 Files selected for processing (4)
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp
  • src/platforms/esp/32/watchdog_esp32.impl.hpp

📝 Walkthrough

Walkthrough

Adds a unified fl::Watchdog singleton API, exposes CFastLED::watchdog(), wires a platform dispatcher, provides ESP32/stub/shared-noop/WASM implementations, integrates the unity-build include, and adds unit tests exercising lifecycle, persistence, callbacks, and safe-mode behavior.

Changes

Unified Watchdog Implementation

Layer / File(s) Summary
API contract and types
src/fl/wdt/watchdog.h
Defines ResetCause, WatchdogTimeoutCallback, WatchdogCrashReport, and fl::Watchdog singleton with tiered method declarations and capability macro contract.
FastLED public accessor
src/FastLED.h, src/FastLED.cpp.hpp
Adds CFastLED::watchdog() accessor returning fl::Watchdog::instance() with Doxygen example.
Unity-build wiring
src/platforms/_build.cpp.hpp
Adds platforms/watchdog.impl.cpp.hpp to the root Unity-build include list.
Platform implementation dispatcher
src/platforms/watchdog.impl.cpp.hpp
Conditionally includes the platform-specific watchdog implementation (WASM, stub, ESP32) or falls back to shared no-op.
ESP32 implementation
src/platforms/esp/32/watchdog_esp32.impl.hpp, src/platforms/esp/32/watchdog_esp32.h, src/platforms/esp/32/watchdog_esp32_idf4.hpp, src/platforms/esp/32/watchdog_esp32_idf5.hpp
ESP32-specific Watchdog with in-RAM persist region, reset-cause translation, crash counter tail, clamped timeouts, begin/feed/disable, C-pointer onTimeout support, watchdog_disable() teardown, and stubs for unsupported tier APIs.
Shared no-op & WASM routing
src/platforms/shared/watchdog_noop.hpp, src/platforms/wasm/watchdog_wasm.impl.hpp
Provides inert watchdog fallback, default capability macros, and routes WASM builds to the shared no-op fallback.
Host/stub implementation
src/platforms/stub/watchdog_stub.impl.hpp
Host stub with 16-byte persisted state, background timer thread to simulate expiry, callback registration, synthesized crash-report behavior, persistence, reboot path, and safe-mode logic.
Unit tests
tests/fl/wdt/watchdog.cpp
Tests singleton semantics, tier-0 lifecycle, persistence bounds, safe-mode threshold and clearing, timeout callbacks and feed behavior, crash-report semantics, and repeated-expiry safe-mode entry/exit.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

"🐰 I nibble code at dawn and hum a debug tune,
My watchful whiskers guard each timeout rune.
Crashes counted, timers fed with care,
The system wakes while I chew on air.
🥕"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main change: a unified watchdog API (Phase 1) with implementations for host/stub and ESP32 platforms, matching the core objective.
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-unified-api

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Nitpick comments (1)
src/platforms/shared/watchdog_noop.hpp (1)

33-85: ⚡ Quick win

Inline the _noop.hpp method definitions.

This header currently emits out-of-line Watchdog methods. Marking them inline keeps the file aligned with the _noop.hpp contract and avoids accidental multiple-definition trouble if it ever gets included outside the dispatcher. As per coding guidelines, src/platforms/shared/*_noop.hpp: "All functions are inline".

🤖 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/platforms/shared/watchdog_noop.hpp` around lines 33 - 85, All out-of-line
Watchdog method definitions in this noop implementation must be marked inline to
match the *_noop.hpp contract and avoid ODR/multiple-definition issues: add the
inline keyword to every definition (e.g., inline void Watchdog::begin(...),
inline void Watchdog::feed(), inline ResetCause Watchdog::lastResetCause()
const, inline bool Watchdog::lastResetWasWatchdog() const, inline fl::u8
Watchdog::persistRead(...), inline void Watchdog::persistWrite(...), inline
fl::u16 Watchdog::consecutiveCrashCount() const, inline void
Watchdog::markCleanShutdown(), inline bool Watchdog::isInSafeMode() const,
inline fl::u16 Watchdog::safeModeThreshold() const, inline void
Watchdog::setSafeModeThreshold(...), inline FL_NORETURN void Watchdog::reboot()
FL_NOEXCEPT (keep the infinite loop body), and likewise mark inline for the
Tier‑1 and Tier‑2 methods (Watchdog::onTimeout overloads, setPauseOnDebug,
writeCrashLog, readCrashLog, rebootIntoBootloader, setWindow, hasCrashReport,
readCrashReport, clearCrashReport). Ensure signatures and
FL_NOEXCEPT/FL_NORETURN annotations are unchanged.
🤖 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 `@src/fl/wdt/watchdog.h`:
- Around line 73-78: The header currently defines Watchdog::instance() and a
function-local static Watchdog (sInstance) which violates the header rule and
can trigger the Teensy __cxa_guard issue; change the header to only declare the
static method (e.g. "static Watchdog& instance() FL_NOEXCEPT;") and remove the
function body and the static sInstance, then add the single definition of
Watchdog::instance() (with the function-local static sInstance) into the
corresponding .cpp.hpp / .impl.hpp TU so the singleton is instantiated only once
in a translation unit.

In `@src/platforms/esp/32/watchdog_esp32.impl.hpp`:
- Around line 73-79: The watchdog currently never saves the chosen timeout so
later calls (e.g., in onTimeout) reinitialize the backend with the default
5000ms; modify Watchdog::begin to store the final timeout_ms into the
Esp32WatchdogState returned by platforms::esp32WatchdogState() (add/assign a
field like state.timeout_ms) and set state.armed as already done, then update
the code path in onTimeout (and the other reinit at the later block referenced)
to read and reuse state.timeout_ms when calling fl::watchdog_setup instead of
using a hardcoded default; if state.timeout_ms is unset (before any begin()),
fall back to the current default behavior (1000ms or FL_WATCHDOG_MAX_TIMEOUT_MS
clamped as in begin()).
- Around line 38-49: Esp32WatchdogState currently keeps crash_count only in
normal static RAM so it is lost across real resets; persist[] was intended to
survive resets—serialize crash_count into persist[] and restore it on
initialization. In practice: when esp32WatchdogState() first constructs (or in a
dedicated init called from it), read crash_count from persist[] (handle
endianness and ensure FL_WATCHDOG_PERSIST_BYTES >= 2) and populate
Esp32WatchdogState::crash_count; whenever code mutates crash_count (e.g., in
consecutiveCrashCount(), markCleanShutdown(), lastResetCause(), isInSafeMode()
logic sites) write the new crash_count back into persist[] (and flush/commit if
required by the underlying retention mechanism), clamp/handle overflow and keep
the in-memory and persisted values consistent. Use the struct name
Esp32WatchdogState, the static accessor esp32WatchdogState(), and the existing
persist[]/crash_count fields to locate where to load/save the value.
- Around line 86-89: The disable() implementation is a no-op but must disarm the
ESP32 watchdog so callers of Watchdog::disable() actually stop resets; update
Watchdog::disable() to reverse what Watchdog::begin()/enable() does by removing
tasks and deinitializing the ESP-IDF TWDT/task watchdog: call
esp_task_wdt_delete(...) for any tasks you registered and then
esp_task_wdt_deinit() (or twdt_deinit()/twdt_remove_task() if you used the TWDT
wrapper) and clear the internal armed flag so subsequent calls reflect state;
guard deinit calls with the same checks you use in begin()/enable() (e.g., an
"armed" or "initialized" member) and ensure calls are safe if the FreeRTOS
scheduler isn’t running.

In `@src/platforms/stub/watchdog_stub.impl.hpp`:
- Around line 35-36: The header wrongly advertises windowed watchdog support via
FL_WATCHDOG_HAS_WINDOW_MODE even though the stub does not implement setWindow()
behavior or enforce min/max timing in feed() or the timer loop; remove the
FL_WATCHDOG_HAS_WINDOW_MODE macro (and any related conditional code paths) and
ensure any window-related API (setWindow()) returns false/NO_OP until the stub
is extended to store and enforce the window in feed() and the timer loop so
callers do not assume window semantics.
- Around line 69-79: The fields reset_was_watchdog and fired are accessed from
the worker thread and from API callers without synchronization, causing data
races; fix by making these flags atomic<bool> (e.g., change declarations of
reset_was_watchdog and fired to fl::atomic<bool>) or ensure all reads/writes are
guarded by the existing mu; update any code that reads/clears them (calls that
access reset_was_watchdog, fired, and the worker thread logic) to use atomic
operations or hold mu consistently so both writer (worker) and readers
synchronize correctly.

In `@tests/fl/wdt/watchdog.cpp`:
- Around line 33-45: Replace the magic indices in the tests with values derived
from FL_WATCHDOG_PERSIST_BYTES: compute last_valid = FL_WATCHDOG_PERSIST_BYTES -
1 and first_invalid = FL_WATCHDOG_PERSIST_BYTES, then use
Watchdog::persistWrite/persistRead with last_valid to assert a successful
round-trip and with first_invalid to assert the write is ignored and read
returns 0; update the tests referencing Watchdog, persistWrite, and persistRead
to use these derived indices so the boundary (idx == FL_WATCHDOG_PERSIST_BYTES)
is actually exercised.
- Around line 112-123: Replace the non-thread-safe static volatile bool fired
with a fl::atomic<bool> fired in tests/fl/wdt/watchdog.cpp; set
fired.store(true) inside the dog.onTimeout callback and use fired.load() in the
FL_CHECK/FL_CHECK_FALSE assertions (both the block around dog.begin(50) and the
later checks at lines indicated), ensuring atomic reads/writes instead of
volatile to avoid data races.

---

Nitpick comments:
In `@src/platforms/shared/watchdog_noop.hpp`:
- Around line 33-85: All out-of-line Watchdog method definitions in this noop
implementation must be marked inline to match the *_noop.hpp contract and avoid
ODR/multiple-definition issues: add the inline keyword to every definition
(e.g., inline void Watchdog::begin(...), inline void Watchdog::feed(), inline
ResetCause Watchdog::lastResetCause() const, inline bool
Watchdog::lastResetWasWatchdog() const, inline fl::u8
Watchdog::persistRead(...), inline void Watchdog::persistWrite(...), inline
fl::u16 Watchdog::consecutiveCrashCount() const, inline void
Watchdog::markCleanShutdown(), inline bool Watchdog::isInSafeMode() const,
inline fl::u16 Watchdog::safeModeThreshold() const, inline void
Watchdog::setSafeModeThreshold(...), inline FL_NORETURN void Watchdog::reboot()
FL_NOEXCEPT (keep the infinite loop body), and likewise mark inline for the
Tier‑1 and Tier‑2 methods (Watchdog::onTimeout overloads, setPauseOnDebug,
writeCrashLog, readCrashLog, rebootIntoBootloader, setWindow, hasCrashReport,
readCrashReport, clearCrashReport). Ensure signatures and
FL_NOEXCEPT/FL_NORETURN annotations are unchanged.
🪄 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: 87cb764b-c0b4-45c5-8a09-50e0c0b09ef8

📥 Commits

Reviewing files that changed from the base of the PR and between 3df21f0 and 41d1483.

📒 Files selected for processing (10)
  • src/FastLED.cpp.hpp
  • src/FastLED.h
  • src/fl/wdt/watchdog.h
  • src/platforms/_build.cpp.hpp
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/shared/watchdog_noop.hpp
  • src/platforms/stub/watchdog_stub.impl.hpp
  • src/platforms/wasm/watchdog_wasm.impl.hpp
  • src/platforms/watchdog.impl.cpp.hpp
  • tests/fl/wdt/watchdog.cpp

Comment thread src/fl/wdt/watchdog.h Resolved
Comment thread tests/fl/wdt/watchdog.cpp Resolved
Comment thread tests/fl/wdt/watchdog.cpp Resolved
- Move Watchdog::instance() definition out of public header into each
  per-platform .impl.hpp / watchdog_noop.hpp so the function-local static
  lives in exactly one TU. Header now declares the accessor only — avoids
  the Teensy 3.x __cxa_guard ABI conflict that header-side function-local
  statics trigger across every TU that includes FastLED.h.

- ESP32: serialize crash_count into the trailing 2 bytes of persist[] so
  consecutive-crash bookkeeping survives the move to RTC_NOINIT_ATTR /
  __NOINIT_ATTR in Phase 2 without further code change. persistRead/Write
  bounds shrunk to the user-visible kUserBytes window.

- ESP32: cache the armed timeout in Esp32WatchdogState so onTimeout()
  reuses it instead of silently re-arming at 5000 ms. begin(30000) +
  onTimeout(cb) now keeps the 30 s window.

- ESP32: disable() now re-arms the backend with FL_WATCHDOG_MAX_TIMEOUT_MS
  rather than silently leaving it ticking with the previous (shorter)
  timeout. Real TWDT teardown via esp_task_wdt_deinit() is still tracked
  in #2731 Phase 2; the interim behavior at least honors "no surprise
  resets during a disable window."

- Stub: drop FL_WATCHDOG_HAS_WINDOW_MODE and return false from
  setWindow(). The stub never modeled min/max-feed enforcement — the
  macro was lying to user code that branches on the capability flag.

- Stub: convert reset_was_watchdog and fired to fl::atomic<bool>,
  resolving the data race between the timer-thread writes and API-side
  reads/clears. Eliminates flake under TSAN-like builds.

- Stub: separate intentional Watchdog::reboot() from watchdog-induced
  resets. reboot() now flips a software_reboot atomic flag — does not
  bump crash_count and does not mark the reset as watchdog-induced.
  lastResetCause() reports SOFTWARE for reboots and WATCHDOG for
  timeouts. clearCrashReport() no longer flips lastResetCause() back to
  POWER_ON.

- Tests: derive persist-boundary indices from a single-source mirror of
  FL_WATCHDOG_PERSIST_BYTES (the capability macro is private to the
  impl TU). The boundary at idx == FL_WATCHDOG_PERSIST_BYTES is now
  exercised explicitly instead of via 9999.

- Tests: replace static volatile bool fired with static fl::atomic<bool>
  fired (with .store() / .load()) in the two timeout test cases. volatile
  is not a thread-safety primitive in C++ — atomic is required for the
  worker-thread → test-thread visibility contract.

- Tests: update the setWindow case to expect false (matches the stub now
  honestly reporting "no window mode" via the dropped capability macro).

Verified: bash test fl_wdt_watchdog --debug (15/15 pass with sanitizers),
bash test --cpp (309/309 pass), bash lint clean.

Addresses CodeRabbit comments 3353133142, 3353133149, 3353133154,
3353133155, 3353133161, 3353133164, 3353133166, 3353133174, 3353133179 on
PR #2738.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/platforms/stub/watchdog_stub.impl.hpp (1)

49-49: 💤 Low value

persist.safe_mode_threshold is dead state.

StubWatchdogPersist::safe_mode_threshold is initialized to 2 in reset_if_unmagic() but is never read; isInSafeMode(), safeModeThreshold(), and setSafeModeThreshold() all operate on the mSafeModeThreshold member instead. As a result the threshold is not actually persisted across reboot() cycles, which contradicts the "survives within a single process" intent of the persist buffer. Either back the threshold getters/setters with the persist field or drop the unused field to avoid confusion.

Also applies to: 236-246

🤖 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/platforms/stub/watchdog_stub.impl.hpp` at line 49, The persist struct
member StubWatchdogPersist::safe_mode_threshold is unused (set in
reset_if_unmagic() but never read), causing safe mode threshold to not persist
across reboot(); update the implementation so getters/setters for the threshold
(isInSafeMode(), safeModeThreshold(), setSafeModeThreshold()) read from and
write to the persist field (StubWatchdogPersist::safe_mode_threshold) instead of
the in-memory mSafeModeThreshold, or alternatively remove the unused persist
field and its initialization if you prefer not to persist the threshold; ensure
reboot() continues to reload the persisted value when choosing the
persist-backed approach.
🤖 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 `@src/platforms/stub/watchdog_stub.impl.hpp`:
- Around line 109-117: The crash counter StubWatchdogPersist::crash_count is
accessed concurrently (incremented in stubWatchdogReset() and read/modified by
consecutiveCrashCount(), isInSafeMode(), markCleanShutdown()) and needs
synchronization; either (A) protect all accesses by taking the
stubWatchdogState() mutex (s.mu) around reads/writes (wrap the p.crash_count++
in s.mu in stubWatchdogReset() and update the reader functions to lock s.mu), or
(B) change crash_count to an atomic type and use atomic operations everywhere
(replace plain counter with std::atomic<uint16_t/uint32_t> and use
load/store/fetch_add in stubWatchdogReset() and the readers) so no data race
occurs.

---

Nitpick comments:
In `@src/platforms/stub/watchdog_stub.impl.hpp`:
- Line 49: The persist struct member StubWatchdogPersist::safe_mode_threshold is
unused (set in reset_if_unmagic() but never read), causing safe mode threshold
to not persist across reboot(); update the implementation so getters/setters for
the threshold (isInSafeMode(), safeModeThreshold(), setSafeModeThreshold()) read
from and write to the persist field (StubWatchdogPersist::safe_mode_threshold)
instead of the in-memory mSafeModeThreshold, or alternatively remove the unused
persist field and its initialization if you prefer not to persist the threshold;
ensure reboot() continues to reload the persisted value when choosing the
persist-backed approach.
🪄 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: 88253a5b-6839-491a-be10-ab92acd58c45

📥 Commits

Reviewing files that changed from the base of the PR and between 41d1483 and 47d151e.

📒 Files selected for processing (5)
  • src/fl/wdt/watchdog.h
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/shared/watchdog_noop.hpp
  • src/platforms/stub/watchdog_stub.impl.hpp
  • tests/fl/wdt/watchdog.cpp
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/fl/wdt/watchdog.h
  • src/platforms/shared/watchdog_noop.hpp
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • tests/fl/wdt/watchdog.cpp

zackees and others added 2 commits June 3, 2026 21:07
Addresses CodeRabbit review on PR #2738.

`StubWatchdogPersist::crash_count` was the last cross-thread field still
on plain memory after the earlier fix made `reset_was_watchdog` / `fired`
/ `software_reboot` atomic. The watchdog timer thread bumped it in
`stubWatchdogReset()` while `consecutiveCrashCount()`, `isInSafeMode()`,
and `markCleanShutdown()` read/wrote it from the test thread — a genuine
data race that TSAN would flag.

Promote `crash_count` to `fl::atomic<fl::u16>` and use a saturating CAS
loop in the worker-side increment so a concurrent `markCleanShutdown()`
reset isn't lost and the counter still pins at 0xFFFF instead of
rolling over.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses CodeRabbit follow-up on PR #2738: Watchdog::disable() on ESP32
previously re-armed the TWDT at max timeout instead of tearing it down,
which left the watchdog still capable of firing after a documented disable.

This adds a public `fl::watchdog_disable()` entry to watchdog_esp32.h that
wraps the existing internal `deinit_existing_watchdog()` helper (already
guarded against being called before the FreeRTOS scheduler runs). Defined
in both watchdog_esp32_idf4.hpp and watchdog_esp32_idf5.hpp; clears the
user callback state on teardown for both IDF versions.

Watchdog::disable() now calls fl::watchdog_disable() so the Tier-0 contract
is honored: after disable(), the watchdog truly does not fire on the
registered idle task.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 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 `@src/platforms/esp/32/watchdog_esp32.impl.hpp`:
- Around line 113-122: The disable path clears the local armed state
unconditionally after calling fl::watchdog_disable(); change this so teardown
success is required before clearing state: update the ESP-IDF backend
implementations (watchdog_esp32_idf4.hpp and watchdog_esp32_idf5.hpp) to capture
esp_task_wdt_deinit()’s esp_err_t return, have fl::watchdog_disable() return a
success/failure boolean or status, and modify Watchdog::disable() to only set
platforms::esp32WatchdogState().armed = false and armed_timeout_ms = 0 (and
clear stored callback/user_data) when fl::watchdog_disable() indicates success;
on failure leave the state and callbacks intact. Ensure all references to
fl::watchdog_disable(), esp_task_wdt_deinit(), and
platforms::esp32WatchdogState() are updated accordingly so failure is propagated
and handled.
🪄 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: 14f8ddec-eb9e-4477-ae57-4d84b1f4497a

📥 Commits

Reviewing files that changed from the base of the PR and between cab437c and bb71c5f.

📒 Files selected for processing (4)
  • src/platforms/esp/32/watchdog_esp32.h
  • src/platforms/esp/32/watchdog_esp32.impl.hpp
  • src/platforms/esp/32/watchdog_esp32_idf4.hpp
  • src/platforms/esp/32/watchdog_esp32_idf5.hpp

Addresses CodeRabbit follow-up on PR #2738: previously
fl::watchdog_disable() and Watchdog::disable() ignored
esp_task_wdt_deinit()'s esp_err_t return. Per ESP-IDF docs that call can
fail (other tasks still subscribed, already deinitialized, scheduler
not running) and on failure the TWDT remains active — so reporting
"disabled" while the WDT can still fire is wrong.

Changes:
- `deinit_existing_watchdog()` now returns bool (true iff esp_task_wdt_deinit
  returned ESP_OK, or if there was nothing to tear down)
- `fl::watchdog_disable()` returns bool, only clears the stored user
  callback/data on successful teardown
- `Watchdog::disable()` only clears `armed`/`armed_timeout_ms` on success;
  on failure the local state stays armed so subsequent calls don't lie
- The two existing internal call sites that ignored the return get an
  explicit `(void)` cast with a comment ("best-effort deinit before re-init")

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
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