Skip to content

feat(rp2350): harden pin-free RPC bring-up - #3837

Merged
zackees merged 1 commit into
masterfrom
feat/rp2350w-serial-platform
Aug 2, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/rp2350w-serial-platform

Conversation

@zackees

@zackees zackees commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

Summary

  • make RP2350/RP2350W serial RPC smoke strict about discovery, help, monotonic uptime, exact payload echo, readiness, and JSON-RPC -32601 errors
  • dispatch RP2350 mutex/semaphore support through Pico SDK mutex primitives and add generation-safe dual-core hardware validation
  • keep Wave2D pin-free, report the RP null coroutine backend as unsupported, and expose an fbuild-backed one-method RPC CLI
  • distinguish serial RPC readiness from a validated LED RX path and invalidate RX proof after runtime pin changes

Validation

  • bash lint
  • uv run pytest ci/tests/test_autoresearch_phases.py ci/tests/test_rpc_client_errors.py ci/tests/test_rpc_bench_cli.py ci/tests/test_rp2350w_board_config.py -q — 155 passed
  • bash test --cpp --clean — 279/279 unit tests and 83/83 examples passed
  • all transient Windows DLL-loader failures passed individually under --debug
  • bash compile rp2350w --examples AutoResearch — 1,117,088 bytes flash, 106,920 bytes RAM
  • clud-review Python and C++ buckets: clean

Hardware status

Live execution is intentionally pending. fbuild identifies expected RP2350W serial 2DCB876B587EA334 at COM17 as phantom/non-selectable; attached ESP32-C6 COM9 remains healthy. This PR must not merge until COM17 is physically reconnected and the Phase 2 hardware gates pass.

Refs #3832

Summary by CodeRabbit

  • New Features

    • Added RPC discovery, platform readiness, LED/RX availability, and RP dual-core concurrency diagnostics.
    • Added a command-line tool for invoking RPC methods with JSON arguments and clear status reporting.
    • Expanded support for RP platforms and coroutine capability reporting.
  • Bug Fixes

    • Pin changes now preserve state if replacement setup fails and invalidate stale validation results.
    • Improved structured JSON-RPC error reporting and SPI input validation.
    • Performance-wave testing no longer performs unnecessary GPIO setup.
  • Tests

    • Expanded coverage for RPC validation, timeouts, unsupported platforms, pin handling, and RP synchronization.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds pin-free Wave2D execution, expands AutoResearch RPC smoke validation, introduces an RP dual-core concurrency test, preserves structured JSON-RPC errors, and broadens RP mutex and semaphore support to all RP platforms.

Changes

AutoResearch execution and validation

Layer / File(s) Summary
Wave2D and pin validation state
ci/autoresearch/phases.py, ci/tests/test_autoresearch_phases.py, examples/AutoResearch/*
Wave2D mode bypasses pin discovery and GPIO checks. Pin and loopback changes invalidate LED RX and GPIO baseline state.
Structured RPC errors and benchmark CLI
ci/rpc_client.py, ci/autoresearch/rpc_bench.py, ci/tests/test_rpc_bench_cli.py, ci/tests/test_rpc_client_errors.py
RpcError preserves structured fields. RpcBench gains JSON argument parsing, failure handling, and exit codes.
RPC smoke and coroutine validation
ci/autoresearch/phases.py, ci/tests/test_autoresearch_phases.py
Smoke tests validate manifest methods, readiness fields, serial safety, concurrency results, uptime progression, and structured method-not-found errors. Unsupported coroutine backends produce successful skips.
RP concurrency RPC and platform backends
examples/AutoResearch/AutoResearchRpConcurrency.*, examples/AutoResearch/AutoResearchRemoteSystemMethods.cpp, src/platforms/..., ci/tests/test_rp2350w_board_config.py
The RP concurrency RPC coordinates dual-core semaphore and mutex operations. RP mutex and semaphore dispatch now uses FL_IS_RP and Pico SDK mutex primitives.
RP constructor initialization order
src/platforms/arm/rp/rpcommon/*
UART and PIO constructors now initialize members in declaration order without changing values.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related issues

  • FastLED issue 3832 — Covers the same RP2350W pin-free AutoResearch, RPC validation, and RP concurrency work.
  • FastLED issue 3626 — Covers related pin-free RPC smoke testing and RP readiness validation.
  • FastLED issue 3629 — Covers related RP pin-free AutoResearch validation and coroutine handling.

Possibly related PRs

Sequence Diagram(s)

sequenceDiagram
  participant SmokeTests
  participant AutoResearchRPC
  participant RPConcurrency
  participant RpcClient
  SmokeTests->>AutoResearchRPC: Discover methods and query status
  AutoResearchRPC-->>SmokeTests: Manifest and readiness data
  SmokeTests->>AutoResearchRPC: Run testRpConcurrency
  AutoResearchRPC->>RPConcurrency: Execute dual-core test
  RPConcurrency-->>AutoResearchRPC: Concurrency result
  AutoResearchRPC-->>SmokeTests: Structured test response
  SmokeTests->>RpcClient: Invoke unknown method
  RpcClient-->>SmokeTests: RpcError with JSON-RPC code
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% 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 clearly identifies the RP2350 target and the primary change: hardening pin-free RPC bring-up.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/rp2350w-serial-platform

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.

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

🧹 Nitpick comments (8)
src/platforms/mutex.h (1)

17-17: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Update the platform doc line to match the new backend.

The guard now selects the RP backend for all RP parts, and that backend uses Pico SDK mutexes instead of raw spinlocks. Line 17 still describes spinlock-based mutexes.

📝 Proposed doc fix
-/// - RP2040/RP2350: Pico SDK spinlock-based mutexes
+/// - RP2040/RP2350: Pico SDK mutex_t / recursive_mutex_t wrappers

Also applies to: 35-35

🤖 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/mutex.h` at line 17, Update the RP2040/RP2350 platform
documentation lines in the mutex header to describe Pico SDK mutexes rather than
spinlock-based mutexes, matching the backend selected by the guard for all RP
parts.
examples/AutoResearch/AutoResearchRemoteSystemMethods.cpp (1)

230-234: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider binding testRpConcurrency as an ASYNC RPC.

runRpConcurrencyTest() can block the caller for several seconds. The ready wait allows 2000 ms, the core-0 contention loop allows 2000 ms, and the core-1 completion wait allows 3000 ms. In the worst case the handler blocks about 7 s before it returns. Every other long-running method in this file uses fl::RpcMode::ASYNC with sendAsyncResponse() so the client receives an ACK first and does not time out. A multi-second synchronous handler also delays the serial pump and the watchdog service on the loop path.

♻️ Proposed change to ASYNC dispatch
-    remote.bind("testRpConcurrency", [](const fl::json& args) -> fl::json {
-        (void)args;
-        return autoresearch::runRpConcurrencyTest();
-    });
+    remote.bind("testRpConcurrency", [this](const fl::json& args) -> fl::json {
+        (void)args;
+        mRemote->sendAsyncResponse("testRpConcurrency",
+                                   autoresearch::runRpConcurrencyTest());
+        return fl::json(nullptr);
+    }, fl::RpcMode::ASYNC);
🤖 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/AutoResearch/AutoResearchRemoteSystemMethods.cpp` around lines 230 -
234, Bind testRpConcurrency with fl::RpcMode::ASYNC and move
runRpConcurrencyTest() into the asynchronous handler flow. Send the immediate
acknowledgment through sendAsyncResponse(), then deliver the test result after
completion, matching the existing long-running RPC methods in this file.
examples/AutoResearch/AutoResearchRpConcurrency.cpp (1)

77-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Name the two timeout literals.

Line 16 defines kRpConcurrencyDeadlineMs for the contention loop. Line 77 uses a bare 2000 for the core-1 ready wait and line 111 uses a bare 3000 for the completion wait. Add named constants so the three deadlines stay related when one is tuned.

♻️ Proposed constants
 constexpr uint32_t kRpConcurrencyDeadlineMs = 2000;
+constexpr uint32_t kRpCore1ReadyTimeoutMs = 2000;
+constexpr uint32_t kRpCore1DoneTimeoutMs = 3000;
-    const uint32_t readyDeadline = millis() + 2000;
+    const uint32_t readyDeadline = millis() + kRpCore1ReadyTimeoutMs;
-    const uint32_t doneDeadline = millis() + 3000;
+    const uint32_t doneDeadline = millis() + kRpCore1DoneTimeoutMs;

Also applies to: 111-111

🤖 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/AutoResearch/AutoResearchRpConcurrency.cpp` at line 77, Define named
millisecond constants for the core-1 ready wait and completion wait alongside
kRpConcurrencyDeadlineMs, then replace the bare 2000 and 3000 literals used by
the ready and completion deadline calculations with those constants. Keep the
existing timeout values and deadline behavior unchanged.
ci/tests/test_rp2350w_board_config.py (1)

66-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make the guard assertions word-boundary aware and name the failing file.

"FL_IS_RP" in source is a substring test. FL_IS_RP2040 contains FL_IS_RP, so a file that reverted to the RP2040-only macro in any spelling the first two assertions do not match still passes the third one. Spacing variants such as #ifdef FL_IS_RP2040 or #if defined( FL_IS_RP2040 ) are not covered either. A regex with word boundaries closes both gaps. The assertions also carry no message, so a failure does not identify which of the four files is at fault.

💚 Proposed test hardening
+import re
+
+
 def test_rp_platform_dispatches_real_mutex_and_semaphore_backends() -> None:
     for source_path in (
         MUTEX_DISPATCH,
         MUTEX_IMPL,
         SEMAPHORE_DISPATCH,
         SEMAPHORE_IMPL,
     ):
         source = source_path.read_text(encoding="utf-8")
-        assert "defined(FL_IS_RP2040)" not in source
-        assert "`#ifdef` FL_IS_RP2040" not in source
-        assert "FL_IS_RP" in source
+        assert not re.search(r"\bFL_IS_RP2040\b", source), (
+            f"{source_path} still guards on FL_IS_RP2040"
+        )
+        assert re.search(r"\bFL_IS_RP\b", source), (
+            f"{source_path} does not guard on FL_IS_RP"
+        )

Place the import re with the other standard-library imports at the top of the file.

As per coding guidelines: "All system imports must be at the top of the file in proper order: standard library, third-party, local".

🤖 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/tests/test_rp2350w_board_config.py` around lines 66 - 76, Update
test_rp_platform_dispatches_real_mutex_and_semaphore_backends to import re with
the other standard-library imports, replace the substring guard checks with
word-boundary-aware regex assertions that reject FL_IS_RP2040 in supported
spacing and defined forms while matching FL_IS_RP as a standalone macro, and add
the current source_path to each assertion message so failures identify the
offending file.

Source: Coding guidelines

examples/AutoResearch/AutoResearchRemoteAsyncMethods.cpp (1)

455-466: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Use #if / #else for the RP coroutine fallback.

With an unconditional return inside the RP #if, the remaining #endif-delimited code is still compiled in, which can trigger -Wunreachable-code-return. Make the fallback branch explicit and close the preprocessor guard before the lambda body.

🤖 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/AutoResearch/AutoResearchRemoteAsyncMethods.cpp` around lines 455 -
466, Update the RP fallback preprocessor block in the surrounding method to use
an explicit `#if/`#else structure: keep the null-backend response and return under
FL_IS_RP, move the existing coroutine lambda implementation into the `#else`
branch, and close the guard after that branch so the RP path does not compile
unreachable code.
ci/autoresearch/rpc_bench.py (1)

191-193: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Use the structured error code to classify method-not-found.

RpcBench.call maps an RpcError to METHOD_NOT_FOUND with the substring test "method" in msg (Line 71). That test matches many unrelated errors, for example "RPC Error -32602: Invalid params for method foo". The new RpcError.code field makes the classification exact. Prefer exc.code == -32601 in RpcBench.call, and keep the substring test only as a fallback for devices that omit the code.

♻️ Proposed change in `RpcBench.call` (outside the selected range)
         except RpcError as e:
+            if e.code == -32601:
+                return METHOD_NOT_FOUND
             msg = str(e).lower()
             if "not found" in msg or "unknown method" in msg or "method" in msg:
                 return METHOD_NOT_FOUND
             return 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/autoresearch/rpc_bench.py` around lines 191 - 193, Update RpcBench.call to
classify method-not-found using the structured RpcError code, treating exc.code
== -32601 as METHOD_NOT_FOUND. Retain the existing "method" substring check only
as a fallback when the device omits the error code, so unrelated errors such as
invalid parameters are not misclassified.
ci/tests/test_rpc_bench_cli.py (1)

22-37: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add the missing type annotations.

monkeypatch, capsys, the args parameter of FailedBench.call, and the return type of __enter__ have no annotations. The repository standard requires explicit annotations for all parameters and return types. ci/tests/test_autoresearch_phases.py already uses pytest.CaptureFixture[str] for capsys, so the same style applies here.

♻️ Proposed annotations
-def test_cli_rejects_method_reported_failure(monkeypatch, capsys) -> None:
+def test_cli_rejects_method_reported_failure(
+    monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
     class FailedBench:
         def __init__(self, _port: str, timeout: float) -> None:
             assert timeout == 3.0
 
-        def __enter__(self):
+        def __enter__(self) -> "FailedBench":
             return self
 
         def __exit__(self, *_exc: object) -> None:
             return None
 
-        def call(self, method: str, args, timeout: float):
+        def call(
+            self, method: str, args: dict[str, Any] | list[Any] | None, timeout: float
+        ) -> dict[str, Any]:

Add from typing import Any at the top if you adopt the Any usage.

As per coding guidelines: "All function parameters MUST have explicit type annotations" and "All function return types MUST have explicit type annotations".

🤖 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/tests/test_rpc_bench_cli.py` around lines 22 - 37, Add explicit type
annotations to test_cli_rejects_method_reported_failure for monkeypatch and
capsys, using the repository’s pytest.CaptureFixture[str] style for capsys and
the appropriate pytest.MonkeyPatch type for monkeypatch. Annotate
FailedBench.__enter__ with its return type and FailedBench.call args with a
suitable type, importing Any from typing if needed; preserve the existing
behavior.

Source: Coding guidelines

ci/autoresearch/phases.py (1)

2046-2057: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move the "unexpectedly returned a result" failure out of the except RpcError scope.

raise RpcError("missing method unexpectedly returned a result") is inside the try, so the except RpcError as exc clause catches it. exc.code is then None, and the handler re-raises with the wrong-code message. The run still fails, but the printed diagnosis is misleading: it reports a wrong error code when the real fault is that the device answered a missing method.

Use a sentinel so each failure reports its own cause.

♻️ Proposed refactor
+        unexpected_result = False
         try:
             await client.send(
                 "__autoresearch_missing_method__",
                 timeout=min(2.0, max(1.0, ctx.remaining_seconds(minimum=1.0))),
             )
-            raise RpcError("missing method unexpectedly returned a result")
+            unexpected_result = True
         except RpcError as exc:
             if exc.code != -32601:
                 raise RpcError(
                     "missing method returned the wrong JSON-RPC error code: "
                     f"{exc.code!r} ({exc})"
                 ) from exc
             print(
                 "REMOTE: missing-method structured error -> "
                 f"code={exc.code}, message={exc.message!r}, data={exc.data!r}"
             )
+        if unexpected_result:
+            raise RpcError("missing method unexpectedly returned a result")
🤖 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/autoresearch/phases.py` around lines 2046 - 2057, Update the
missing-method validation around client.send so the “missing method unexpectedly
returned a result” RpcError is raised outside the scope of the except RpcError
handler, using a sentinel or equivalent control flow to distinguish a successful
response from an RPC failure. Preserve the existing -32601 validation and
wrong-code diagnostic for genuine RpcError responses.
🤖 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/autoresearch/phases.py`:
- Around line 2031-2044: Update the concurrency validation in the rp_environment
gate to require both “actual” and “expected” from the testRpConcurrency
response, verify each is an integer, and only then accept matching values.
Preserve the existing boolean readiness checks and RpcError behavior for
missing, invalid, or mismatched counters.

In `@examples/AutoResearch/AutoResearchRemote.cpp`:
- Around line 377-382: Make RX-channel updates transactional in
examples/AutoResearch/AutoResearchRemote.cpp:377-382,
examples/AutoResearch/AutoResearchRemotePinMethods.cpp:298-298, and
examples/AutoResearch/AutoResearchRemotePinMethods.cpp:372-378. In the affected
update paths, stage and successfully create the replacement RX channel before
committing found_rx or invalidating validation; on factory failure, restore the
prior channel and validation state while preserving the existing pin values.
Apply the same transaction ordering in setRxPin and setPins, with no direct
change needed elsewhere.

In `@examples/AutoResearch/AutoResearchRemoteRpSpiMethods.cpp`:
- Around line 205-208: In both rpSpiLoopback and rpSpiPublicApiLoopback
handlers, defer mState->rx_channel.reset() and
mState->invalidateLedRxValidation() until after all request validation succeeds,
so invalid requests leave device state unchanged. Apply this to
examples/AutoResearch/AutoResearchRemoteRpSpiMethods.cpp lines 205-208 and
250-253.

---

Nitpick comments:
In `@ci/autoresearch/phases.py`:
- Around line 2046-2057: Update the missing-method validation around client.send
so the “missing method unexpectedly returned a result” RpcError is raised
outside the scope of the except RpcError handler, using a sentinel or equivalent
control flow to distinguish a successful response from an RPC failure. Preserve
the existing -32601 validation and wrong-code diagnostic for genuine RpcError
responses.

In `@ci/autoresearch/rpc_bench.py`:
- Around line 191-193: Update RpcBench.call to classify method-not-found using
the structured RpcError code, treating exc.code == -32601 as METHOD_NOT_FOUND.
Retain the existing "method" substring check only as a fallback when the device
omits the error code, so unrelated errors such as invalid parameters are not
misclassified.

In `@ci/tests/test_rp2350w_board_config.py`:
- Around line 66-76: Update
test_rp_platform_dispatches_real_mutex_and_semaphore_backends to import re with
the other standard-library imports, replace the substring guard checks with
word-boundary-aware regex assertions that reject FL_IS_RP2040 in supported
spacing and defined forms while matching FL_IS_RP as a standalone macro, and add
the current source_path to each assertion message so failures identify the
offending file.

In `@ci/tests/test_rpc_bench_cli.py`:
- Around line 22-37: Add explicit type annotations to
test_cli_rejects_method_reported_failure for monkeypatch and capsys, using the
repository’s pytest.CaptureFixture[str] style for capsys and the appropriate
pytest.MonkeyPatch type for monkeypatch. Annotate FailedBench.__enter__ with its
return type and FailedBench.call args with a suitable type, importing Any from
typing if needed; preserve the existing behavior.

In `@examples/AutoResearch/AutoResearchRemoteAsyncMethods.cpp`:
- Around line 455-466: Update the RP fallback preprocessor block in the
surrounding method to use an explicit `#if/`#else structure: keep the null-backend
response and return under FL_IS_RP, move the existing coroutine lambda
implementation into the `#else` branch, and close the guard after that branch so
the RP path does not compile unreachable code.

In `@examples/AutoResearch/AutoResearchRemoteSystemMethods.cpp`:
- Around line 230-234: Bind testRpConcurrency with fl::RpcMode::ASYNC and move
runRpConcurrencyTest() into the asynchronous handler flow. Send the immediate
acknowledgment through sendAsyncResponse(), then deliver the test result after
completion, matching the existing long-running RPC methods in this file.

In `@examples/AutoResearch/AutoResearchRpConcurrency.cpp`:
- Line 77: Define named millisecond constants for the core-1 ready wait and
completion wait alongside kRpConcurrencyDeadlineMs, then replace the bare 2000
and 3000 literals used by the ready and completion deadline calculations with
those constants. Keep the existing timeout values and deadline behavior
unchanged.

In `@src/platforms/mutex.h`:
- Line 17: Update the RP2040/RP2350 platform documentation lines in the mutex
header to describe Pico SDK mutexes rather than spinlock-based mutexes, matching
the backend selected by the guard for all RP parts.
🪄 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 Plus

Run ID: e72fb28d-16c1-4d68-9a5a-2e675d07f8a3

📥 Commits

Reviewing files that changed from the base of the PR and between d5c784c and 1ccb5a6.

📒 Files selected for processing (23)
  • ci/autoresearch/phases.py
  • ci/autoresearch/rpc_bench.py
  • ci/rpc_client.py
  • ci/tests/test_autoresearch_phases.py
  • ci/tests/test_rp2350w_board_config.py
  • ci/tests/test_rpc_bench_cli.py
  • ci/tests/test_rpc_client_errors.py
  • examples/AutoResearch/AutoResearch.ino
  • examples/AutoResearch/AutoResearchRemote.cpp
  • examples/AutoResearch/AutoResearchRemote.h
  • examples/AutoResearch/AutoResearchRemoteAsyncMethods.cpp
  • examples/AutoResearch/AutoResearchRemotePinMethods.cpp
  • examples/AutoResearch/AutoResearchRemoteRpSpiMethods.cpp
  • examples/AutoResearch/AutoResearchRemoteSystemMethods.cpp
  • examples/AutoResearch/AutoResearchRpConcurrency.cpp
  • examples/AutoResearch/AutoResearchRpConcurrency.h
  • src/platforms/arm/rp/mutex_rp.cpp.hpp
  • src/platforms/arm/rp/mutex_rp.h
  • src/platforms/arm/rp/rpcommon/rp_uart_peripheral.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rx_pio_channel.cpp.hpp
  • src/platforms/arm/rp/semaphore_rp.cpp.hpp
  • src/platforms/mutex.h
  • src/platforms/semaphore.h

Comment thread ci/autoresearch/phases.py Resolved

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

🧹 Nitpick comments (1)
ci/tests/test_autoresearch_phases.py (1)

2311-2315: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the repeated response(data) mock helper.

Four test methods (test_rpc_smoke_mode_validates_core_surface, test_rpc_smoke_rejects_missing_required_discovery_method, test_rpc_smoke_non_rp_target_skips_rp_concurrency, test_rpc_smoke_rejects_timeout_for_unknown_method) each define an identical local response(data) closure that builds a MagicMock with .success = True and .data = data. Move this helper to module scope (or a fixture) once, and reuse it in each test.

♻️ Proposed refactor
+def _rp_response(data: Any) -> MagicMock:
+    item = MagicMock()
+    item.success = True
+    item.data = data
+    return item
+
+
 class TestRunTestsOrSpecialMode:
     ...
     def test_rpc_smoke_mode_validates_core_surface(self) -> None:
         ...
-        def response(data):
-            item = MagicMock()
-            item.success = True
-            item.data = data
-            return item
-
         mock_client = AsyncMock()
         mock_client.send = AsyncMock(
             side_effect=[
-                response({"schema": [[name] for name in required_methods]}),
+                _rp_response({"schema": [[name] for name in required_methods]}),

(Apply the same substitution in the other three tests.)

Also applies to: 2385-2389, 2416-2420, 2488-2492

🤖 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/tests/test_autoresearch_phases.py` around lines 2311 - 2315, Extract the
duplicated response(data) MagicMock builder from the four named tests into a
single module-level helper or fixture, preserving its success and data
attributes. Remove each local closure and update all four tests to reuse the
shared helper.
🤖 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/rpc_client.py`:
- Around line 686-688: Update the error-code assignment in the RPC error
handling flow to accept only non-boolean integers, preventing JSON-RPC boolean
values from being stored in RpcError.code; preserve the existing None fallback
for all other types.

In `@examples/AutoResearch/AutoResearchRpConcurrency.cpp`:
- Around line 16-26: Add a dedicated FL_STATIC_ASSERT near the existing
watchdog-budget assertion that enforces kRpConcurrencyDeadlineMs is strictly
less than kRpCore1DoneTimeoutMs. Leave the existing aggregate budget assertion
unchanged and encode this ordering invariant using the existing timeout
constants.

---

Nitpick comments:
In `@ci/tests/test_autoresearch_phases.py`:
- Around line 2311-2315: Extract the duplicated response(data) MagicMock builder
from the four named tests into a single module-level helper or fixture,
preserving its success and data attributes. Remove each local closure and update
all four tests to reuse the shared helper.
🪄 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 Plus

Run ID: 286cabcd-7137-4f80-8b04-691e3dfe2e01

📥 Commits

Reviewing files that changed from the base of the PR and between 1ccb5a6 and e90ea54.

📒 Files selected for processing (23)
  • ci/autoresearch/phases.py
  • ci/autoresearch/rpc_bench.py
  • ci/rpc_client.py
  • ci/tests/test_autoresearch_phases.py
  • ci/tests/test_rp2350w_board_config.py
  • ci/tests/test_rpc_bench_cli.py
  • ci/tests/test_rpc_client_errors.py
  • examples/AutoResearch/AutoResearch.ino
  • examples/AutoResearch/AutoResearchRemote.cpp
  • examples/AutoResearch/AutoResearchRemote.h
  • examples/AutoResearch/AutoResearchRemoteAsyncMethods.cpp
  • examples/AutoResearch/AutoResearchRemotePinMethods.cpp
  • examples/AutoResearch/AutoResearchRemoteRpSpiMethods.cpp
  • examples/AutoResearch/AutoResearchRemoteSystemMethods.cpp
  • examples/AutoResearch/AutoResearchRpConcurrency.cpp
  • examples/AutoResearch/AutoResearchRpConcurrency.h
  • src/platforms/arm/rp/mutex_rp.cpp.hpp
  • src/platforms/arm/rp/mutex_rp.h
  • src/platforms/arm/rp/rpcommon/rp_uart_peripheral.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rx_pio_channel.cpp.hpp
  • src/platforms/arm/rp/semaphore_rp.cpp.hpp
  • src/platforms/mutex.h
  • src/platforms/semaphore.h
🚧 Files skipped from review as they are similar to previous changes (17)
  • ci/tests/test_rpc_client_errors.py
  • examples/AutoResearch/AutoResearchRpConcurrency.h
  • src/platforms/semaphore.h
  • src/platforms/mutex.h
  • examples/AutoResearch/AutoResearchRemote.h
  • examples/AutoResearch/AutoResearchRemote.cpp
  • src/platforms/arm/rp/semaphore_rp.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rp_uart_peripheral.cpp.hpp
  • examples/AutoResearch/AutoResearchRemoteAsyncMethods.cpp
  • src/platforms/arm/rp/mutex_rp.h
  • examples/AutoResearch/AutoResearchRemoteSystemMethods.cpp
  • ci/tests/test_rp2350w_board_config.py
  • examples/AutoResearch/AutoResearch.ino
  • src/platforms/arm/rp/mutex_rp.cpp.hpp
  • src/platforms/arm/rp/rpcommon/rx_pio_channel.cpp.hpp
  • ci/autoresearch/rpc_bench.py
  • ci/autoresearch/phases.py

Comment thread ci/rpc_client.py
Comment on lines +686 to +688
code=(
error_code if isinstance(error_code, int) else None
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

uv run python - <<'PY'
assert isinstance(True, int)
assert type(True) is not int
print("Python bool is an int subclass, but not an exact int.")
PY

Repository: FastLED/FastLED

Length of output: 193


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Python version:\n'
python3 --version

printf '\nPython bool/int semantics:\n'
python3 - <<'PY'
print("type(True) is int:", type(True) is int)
print("isinstance(True, int):", isinstance(True, int))
print("isinstance(False, int):", isinstance(False, int))
PY

printf '\nLocate ci/rpc_client.py and relevant context:\n'
if [ -f ci/rpc_client.py ]; then
  wc -l ci/rpc_client.py
  sed -n '630,715p' ci/rpc_client.py
else
  fd -a 'rpc_client.py' .
fi

printf '\nSearch for RpcError construction and error_code parsing:\n'
rg -n "error_code|RpcError|code=" ci/rpc_client.py

Repository: FastLED/FastLED

Length of output: 5256


Exclude bool from the integer error-code check.

Python treats bool as a subclass of int, so isinstance(True, int) is True. A malformed JSON-RPC error object with "code": true can set RpcError.code to True, which is not an integer error code.

Proposed fix
-                                    error_code if isinstance(error_code, int) else None
+                                    error_code
+                                    if isinstance(error_code, int)
+                                    and not isinstance(error_code, bool)
+                                    else None
📝 Committable suggestion

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

Suggested change
code=(
error_code if isinstance(error_code, int) else None
),
code=(
error_code
if isinstance(error_code, int)
and not isinstance(error_code, bool)
else 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/rpc_client.py` around lines 686 - 688, Update the error-code assignment in
the RPC error handling flow to accept only non-boolean integers, preventing
JSON-RPC boolean values from being stored in RpcError.code; preserve the
existing None fallback for all other types.

Comment on lines +16 to +26
constexpr int kRpConcurrencyIterations = 100;
constexpr uint32_t kRpConcurrencyDeadlineMs = 1500;
constexpr uint32_t kRpCore1ReadyTimeoutMs = 500;
constexpr uint32_t kRpCore1DoneTimeoutMs = 2000;
// AutoResearch's loop watchdog is 5 seconds. Leave a full second for JSON
// response construction and transport after every bounded diagnostic wait.
constexpr uint32_t kRpConcurrencyWatchdogBudgetMs = 4000;
FL_STATIC_ASSERT(kRpConcurrencyDeadlineMs + kRpCore1ReadyTimeoutMs +
kRpCore1DoneTimeoutMs <=
kRpConcurrencyWatchdogBudgetMs,
"RP concurrency diagnostics exceed the watchdog-safe budget");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add an explicit static assert for the core1-completion timing invariant.

gRpRequestInFlight is only cleared by loop1() when core1 finishes its increment loop (line 76). If runRpConcurrencyTest's wait for gRpCore1Done times out (lines 120-130) before core1 finishes, the function returns without resetting gRpRequestInFlight, so every subsequent testRpConcurrency call fails at the gRpRequestInFlight.exchange(true) guard until core1 eventually completes and clears it.

This is safe today only because kRpConcurrencyDeadlineMs (1500 ms, core1's own per-attempt budget) is strictly less than kRpCore1DoneTimeoutMs (2000 ms, core0's wait budget). The current FL_STATIC_ASSERT only checks the sum of the three timeouts against the watchdog budget; it does not enforce this ordering. A future constant change that keeps the sum within budget could still break the ordering and reintroduce a stuck in-flight flag.

Add a static assert that directly encodes the invariant this design depends on.

🔒️ Proposed fix
 FL_STATIC_ASSERT(kRpConcurrencyDeadlineMs + kRpCore1ReadyTimeoutMs +
                          kRpCore1DoneTimeoutMs <=
                      kRpConcurrencyWatchdogBudgetMs,
                  "RP concurrency diagnostics exceed the watchdog-safe budget");
+FL_STATIC_ASSERT(kRpConcurrencyDeadlineMs < kRpCore1DoneTimeoutMs,
+                 "core1's increment-loop budget must finish before core0's "
+                 "done-wait times out, or gRpRequestInFlight can get stuck");

Also applies to: 64-78, 120-130

🤖 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/AutoResearch/AutoResearchRpConcurrency.cpp` around lines 16 - 26,
Add a dedicated FL_STATIC_ASSERT near the existing watchdog-budget assertion
that enforces kRpConcurrencyDeadlineMs is strictly less than
kRpCore1DoneTimeoutMs. Leave the existing aggregate budget assertion unchanged
and encode this ordering invariant using the existing timeout constants.

@zackees
zackees merged commit 6480b26 into master Aug 2, 2026
17 of 19 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Aug 2, 2026
@zackees
zackees deleted the feat/rp2350w-serial-platform branch August 21, 2026 19:15
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