Skip to content

feat(lint): forbid raw Serial.* in enforced example sketches; migrate AutoResearch - #2679

Merged
zackees merged 2 commits into
masterfrom
feat/example-serial-checker
Jun 1, 2026
Merged

zackees merged 2 commits into
masterfrom
feat/example-serial-checker

Conversation

@zackees

@zackees zackees commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Add a new C++ linter (ExampleSerialChecker) that flags raw Serial.print* / Serial.read* / Serial.begin calls in selected example sketches, and migrate AutoResearch.ino to the fl:: wrappers so those sketches actually benefit from the non-blocking HWCDC fixes shipped in #2669.

Why

PR #2669 added platform-aware behavior to src/platforms/arduino/io_arduino.hpp:

  • Serial.setTxTimeoutMs(0) at begin() time → HWCDC writes drop instead of stalling when no host is reading
  • if (!Serial) return; in print()/println() → non-blocking when host absent
  • flush() skipped on !Serial → avoids arduino-esp32 #7554 hang

These fixes only take effect when the sketch goes through the fl:: API. A sketch that bypasses the wrappers by calling Serial.print directly silently loses every guarantee. AutoResearch — the canonical hardware-testing harness — was bypassing them despite the rest of the sketch already using fl::println / fl::flush (via AutoResearchRemote.cpp's printJsonRaw).

What changes

File Change
ci/lint_cpp/example_serial_checker.py New checker. Flags Serial.{print,println,printf,write,read,available,peek,readStringUntil,flush,begin} in enforced paths; allows setTxBufferSize/setTxTimeoutMs (platform-specific, no fl:: equivalent); honors // ok serial - <reason> opt-out.
ci/lint_cpp/run_all_checkers.py Register in checkers_by_scope["examples"].
ci/tests/test_example_serial_checker.py 16 unit tests covering file selection, every banned method, allowed methods, opt-out marker, comment skipping.
examples/AutoResearch/AutoResearch.ino Serial.begin(115200) → fl::serial_begin(115200); !Serial → !fl::serial_ready(); setTxBufferSize/setTxTimeoutMs annotated with // ok serial - <reason>.

Scope decision: AutoResearch only (for now)

Surveyed examples/ — 53 files use raw Serial.print*. Most are tutorial sketches (Blink, Cylon, DemoReel100, Audio*) where raw Serial is the canonical Arduino-newcomer surface and migration would confuse the audience. Enforcement starts at examples/AutoResearch/ only.

Broader rollout is a separate decision — when ready, add the path prefix to ENFORCED_PATH_PREFIXES in ci/lint_cpp/example_serial_checker.py and migrate as needed.

Test plan

  • uv run python -m pytest ci/tests/test_example_serial_checker.py -v → 16/16 passing
  • uv run python ci/lint_cpp/example_serial_checker.py examples/AutoResearch/AutoResearch.ino → no violations
  • uv run python ci/lint_cpp/example_serial_checker.py (full tree) → no violations
  • bash test --cpp → 227/227 passing (cached, repo unchanged from previous run except docs/lint paths)
  • CI to confirm bash compile esp32c6 --examples AutoResearch still links

Opt-out example

Serial.setTxTimeoutMs(0);  // ok serial - platform-specific TX timeout, no fl:: equivalent

Same-line only; suppression on a separate line does NOT silence the next line (covered by test_suppression_only_on_same_line).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a static-analysis checker that enforces allowed/forbidden serial usage in example sketches.
  • Improvements

    • Updated an example sketch to use safer serial initialization helpers and preserve hardware-specific TX configuration.
  • Tests

    • Added unit tests covering detection, allowlist/suppression behavior, and comment handling for the new checker.
  • Chores

    • Integrated the new checker into the CI lint pipeline for examples.

… AutoResearch

Add ExampleSerialChecker to flag raw Serial.print* / Serial.read* / Serial.begin
in selected example sketches that should route through the fl:: wrappers. The
fl:: wrappers carry the non-blocking HWCDC fixes shipped in #2669 (Serial.set
TxTimeoutMs(0), guarded flush, host-presence skip). Bypassing them with raw
Serial calls silently loses those guarantees.

Enforcement is scoped to examples/AutoResearch/ for now -- tutorial examples
(Blink, Cylon, DemoReel100, etc.) intentionally use raw Serial as the
canonical Arduino-newcomer surface; broader rollout is a separate decision.

Allowed (no fl:: equivalent, platform-specific hardware config):
  - Serial.setTxBufferSize, Serial.setTxTimeoutMs

Opt-out: `// ok serial - <reason>` on the same line.

Files:
  - ci/lint_cpp/example_serial_checker.py: new checker
  - ci/lint_cpp/run_all_checkers.py: register in checkers_by_scope["examples"]
  - ci/tests/test_example_serial_checker.py: 16 unit tests (all pass)
  - examples/AutoResearch/AutoResearch.ino:
      Serial.begin(115200) -> fl::serial_begin(115200)
      !Serial -> !fl::serial_ready()
      setTxBufferSize/setTxTimeoutMs annotated with `// ok serial - <reason>`

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

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: 47b4fbdc-6f15-40b4-94ee-c6fa7957086b

📥 Commits

Reviewing files that changed from the base of the PR and between 311877f and c524bf6.

📒 Files selected for processing (1)
  • ci/lint_cpp/example_serial_checker.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • ci/lint_cpp/example_serial_checker.py

📝 Walkthrough

Walkthrough

This PR adds a new CI checker that enforces the use of FastLED serial helpers in example sketches by forbidding raw Serial.* method calls, allowing only whitelisted hardware-configuration methods, and supporting inline suppression. The checker integrates into the unified lint system and is validated with comprehensive unit tests. AutoResearch.ino is updated to comply by using fl::serial_begin() and fl::serial_ready() instead of raw Arduino Serial APIs.

Changes

Serial Usage Enforcement Checker

Layer / File(s) Summary
Checker rule configuration and core implementation
ci/lint_cpp/example_serial_checker.py
Defines forbidden (print, println, printf, write, read, available, peek, readStringUntil, flush, begin, etc.) and allowed (setTxBufferSize, setTxTimeoutMs) Serial methods; implements ExampleSerialChecker with path/extension filtering, comment-stripping for // and /* ... */, regex-based detection, inline // ok serial - <reason> suppression, and line-numbered violation accumulation.
Checker CLI entry point and lint system integration
ci/lint_cpp/example_serial_checker.py, ci/lint_cpp/run_all_checkers.py
Adds main() to run the checker standalone or recursively over examples/, prints per-file/line violation summaries and exit status, and registers ExampleSerialChecker in the unified C++ lint runner's examples scope.
Test suite for checker logic and configuration
ci/tests/test_example_serial_checker.py
Unit tests cover file selection by path and extension, detection of forbidden methods, allowed whitelist behavior, inline suppression semantics, and ignoring Serial usage inside single-line and block comments.
AutoResearch.ino migration to FastLED serial helpers
examples/AutoResearch/AutoResearch.ino
Replaces Serial.begin(115200) and while (!Serial ...) with fl::serial_begin(115200) and while (!fl::serial_ready() ...); retains Serial.setTxTimeoutMs(0) for ARDUINO_USB_CDC_ON_BOOT and annotates the ESP32 TX buffer sizing line.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • FastLED/FastLED#2669: Introduces Serial.setTxTimeoutMs(0) configuration for HWCDC and related serial helper changes aligned with this PR.

Poem

🐰 A rabbit hops through code and trees,

sniffing Serial calls on the breeze.
"Use fl::serial," the rabbit cries,
"Comments hide what lint defies."
Hooray — examples pass with ease!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.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 accurately describes the main changes: adding a lint rule to forbid raw Serial.* calls in enforced example sketches and migrating the AutoResearch example to use the fl:: wrappers.
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/example-serial-checker

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

🧹 Nitpick comments (2)
ci/tests/test_example_serial_checker.py (1)

65-105: 💤 Low value

Solid coverage. Once the line-scanner gaps noted in example_serial_checker.py are addressed, consider adding cases for an inline block comment alongside code (Serial.println("x"); /* note */) and two Serial.* calls on one line to lock in the expected violation counts.

🤖 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_example_serial_checker.py` around lines 65 - 105, Add tests to
cover the line-scanner gaps in example_serial_checker.py by: 1) adding a test
(e.g., test_flags_serial_inline_block_comment) that creates content containing
an inline block comment after a Serial call like 'Serial.println("x"); /* note
*/', calls checker.check_file_content(content), asserts the file is in
checker.violations and that the violation message references println (and
fl::println if applicable); and 2) adding a test (e.g.,
test_flags_two_serial_calls_one_line) that creates content with two Serial.*
calls on the same line (for example 'Serial.println("a"); Serial.read();'), runs
checker.check_file_content(content), and asserts the file is in
checker.violations and that there are two violations recorded for that path.
Ensure tests use the same _make_content helper and follow the existing assert
patterns (checking content.path in checker.violations and verifying
counts/messages).
ci/lint_cpp/example_serial_checker.py (1)

108-135: ⚡ Quick win

Harden example_serial_checker.py against false negatives in block-comment and multi-call lines.

  • Lines containing both /* and */ are fully skipped (continue at 114-116), so Serial.* appearing on the same line as an inline block comment can be ignored.
  • SERIAL_METHOD_PATTERN.search(code_part) only matches the first Serial.* per line (131), so additional Serial.* calls on the same line could be missed.
  • Current examples/AutoResearch contains no such inline /* ... */ + Serial.* cases and no multiple Serial.* calls on a single line, but this remains a silent-bypass risk for future edits.

Consider stripping just the commented portion on /* ... */ open/close lines (instead of skipping the whole line) and using finditer to iterate over all Serial.* matches in code_part.

🤖 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/lint_cpp/example_serial_checker.py` around lines 108 - 135, The loop logic
can miss Serial.* when block comments start and end on the same line and only
captures the first match per line; modify the handling around
in_multiline_comment and code_part so that when a line contains both "/*" and
"*/" you strip only the commented substring (remove the "/*...*/" segment)
instead of setting in_multiline_comment and continuing, and when tracking
multi-line comment state remove or mask comment spans rather than
unconditionally continuing; then replace SERIAL_METHOD_PATTERN.search(code_part)
with SERIAL_METHOD_PATTERN.finditer(code_part) and iterate over each match to
handle multiple Serial.* calls per line (use the matched groups as before, e.g.,
match.group(1) for the method) while preserving existing single-line '//'
stripping logic.
🤖 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/lint_cpp/example_serial_checker.py`:
- Around line 94-95: The __init__ method is missing an explicit return type;
update the constructor declaration for the class in
ci/lint_cpp/example_serial_checker.py to include the explicit return annotation
(e.g. change def __init__(self): to def __init__(self) -> None:), leaving the
existing self.violations: dict[str, list[tuple[int, str]]] assignment unchanged
so the attribute typing remains intact.
- Around line 170-177: Hoist the imports currently inside main(): move the
`import sys` statement and the `MultiCheckerFileProcessor` and
`run_checker_standalone` imports from `ci.util.check_files` to module scope;
update the top-of-file imports to include `sys` and extend the existing `from
ci.util.check_files import ...` to list `MultiCheckerFileProcessor` and
`run_checker_standalone`, and remove those in-function imports so `main()`
simply references `sys`, `MultiCheckerFileProcessor`, and
`run_checker_standalone` directly.

---

Nitpick comments:
In `@ci/lint_cpp/example_serial_checker.py`:
- Around line 108-135: The loop logic can miss Serial.* when block comments
start and end on the same line and only captures the first match per line;
modify the handling around in_multiline_comment and code_part so that when a
line contains both "/*" and "*/" you strip only the commented substring (remove
the "/*...*/" segment) instead of setting in_multiline_comment and continuing,
and when tracking multi-line comment state remove or mask comment spans rather
than unconditionally continuing; then replace
SERIAL_METHOD_PATTERN.search(code_part) with
SERIAL_METHOD_PATTERN.finditer(code_part) and iterate over each match to handle
multiple Serial.* calls per line (use the matched groups as before, e.g.,
match.group(1) for the method) while preserving existing single-line '//'
stripping logic.

In `@ci/tests/test_example_serial_checker.py`:
- Around line 65-105: Add tests to cover the line-scanner gaps in
example_serial_checker.py by: 1) adding a test (e.g.,
test_flags_serial_inline_block_comment) that creates content containing an
inline block comment after a Serial call like 'Serial.println("x"); /* note */',
calls checker.check_file_content(content), asserts the file is in
checker.violations and that the violation message references println (and
fl::println if applicable); and 2) adding a test (e.g.,
test_flags_two_serial_calls_one_line) that creates content with two Serial.*
calls on the same line (for example 'Serial.println("a"); Serial.read();'), runs
checker.check_file_content(content), and asserts the file is in
checker.violations and that there are two violations recorded for that path.
Ensure tests use the same _make_content helper and follow the existing assert
patterns (checking content.path in checker.violations and verifying
counts/messages).
🪄 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: f5f98fb3-6f39-4e90-8a46-39ed072155df

📥 Commits

Reviewing files that changed from the base of the PR and between 27a1682 and 311877f.

📒 Files selected for processing (4)
  • ci/lint_cpp/example_serial_checker.py
  • ci/lint_cpp/run_all_checkers.py
  • ci/tests/test_example_serial_checker.py
  • examples/AutoResearch/AutoResearch.ino

Comment thread ci/lint_cpp/example_serial_checker.py Resolved
Comment thread ci/lint_cpp/example_serial_checker.py Resolved
- Add explicit `-> None` return type annotation to `ExampleSerialChecker.__init__`
- Hoist `sys` and `ci.util.check_files` imports from `main()` to module scope

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@zackees
zackees merged commit 0b1d5bd into master Jun 1, 2026
9 checks passed
@zackees
zackees deleted the feat/example-serial-checker branch June 1, 2026 23:08
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 1, 2026
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