Skip to content

perf(autoresearch): replace sleep-based reset waits with spin-poll (#2265) - #2318

Merged
zackees merged 1 commit into
masterfrom
perf/autoresearch-spin-poll-2265
Apr 18, 2026
Merged

zackees merged 1 commit into
masterfrom
perf/autoresearch-spin-poll-2265

Conversation

@zackees

@zackees zackees commented Apr 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Replaces the fixed asyncio.sleep(boot_wait) loop inside RpcClient.connect() with a spin-poll (ci/util/boot_wait.wait_for_signal) that watches serial output for ROM-loader / Arduino setup() banners and exits immediately when one appears. Fixes #2265.

  • Validation signals watched (substring containment, any match wins):
    • BOOT_SIGNALS_ROM: entry 0x, ESP-ROM:, rst:, boot:
    • BOOT_SIGNALS_SETUP: Before Setup Start, setup() start, RESULT:, REMOTE:
  • Slow-device fallback: if no signal arrives within boot_wait the call still returns cleanly. The timeout IS the fallback — no raising, no regressions for devices that boot slowly or don't emit a banner.
  • Opt-out: callers can pass boot_signals=[] to disable spin-polling and get the legacy "sleep the full duration" behavior.

Only ci/rpc_client.py changes. All autoresearch callers (phases.py, gpio.py, net.py, ota.py, ble.py, driver_sweep.py, decode.py) inherit the speedup for free via the shared connect() entry point.

Out of scope (intentionally):

Expected speedup

Scenario Before After
Fast ESP32-S3 w/ USB-CDC, 3.0s boot_wait ~3.0s fixed <500ms (banner arrives in ~200-400ms)
Slow ESP32-S3 autoresearch, 8.0s boot_wait (gpio.py) ~8.0s fixed <1s once Before Setup Start fires
Device stuck / no banner ~boot_wait ~boot_wait (fallback — unchanged)

Rough claim: ~2s saved per autoresearch cycle on fast devices, with no regression on slow ones.

Test plan

  • uv run pytest ci/tests/test_boot_wait.py -v — 9 unit tests for the helper (early-exit, timeout-fallback, on_line mirroring, empty-patterns drain, substring-containment semantics)
  • uv run pytest ci/tests/test_rpc_client_connect_spin_poll.py -v — 3 integration tests exercising RpcClient.connect() end-to-end with a fake SerialInterface (early-exit on banner, fallback on silence, opt-out via boot_signals=[])
  • uv run pytest ci/tests/test_serial_interface_reset.py -v — unchanged, still passes
  • uv run ruff check ci/rpc_client.py ci/util/boot_wait.py ci/tests/test_boot_wait.py ci/tests/test_rpc_client_connect_spin_poll.py — clean
  • Live bash autoresearch --parlio on ESP32-S3 to confirm sub-second banner detection (requires hardware)

Pre-existing unrelated test failures in test_autoresearch_phases.py (lcd_spi arg) and test_running_process.py::test_output_formatter are not affected by this change — verified on master.

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved device boot detection with early signal matching for faster connection initialization
    • Added optional boot signals configuration for customized boot wait behavior
  • Tests

    • Added comprehensive test coverage for boot signal detection and connection timing validation

… sleeps (#2265)

Replaces the fixed ``asyncio.sleep(boot_wait)`` loop inside
``RpcClient.connect()`` with a spin-poll (``ci/util/boot_wait.wait_for_signal``)
that watches serial output for ROM-loader / Arduino ``setup()`` banners
(``entry 0x``, ``ESP-ROM:``, ``Before Setup Start``, ``REMOTE: ``) and exits
immediately when one appears.

If none of the expected signals arrive within ``boot_wait`` the call still
returns cleanly — the timeout IS the fallback, matching the legacy fixed-sleep
behavior so slow devices continue to work. Callers can pass
``boot_signals=[]`` to opt out of spin-polling entirely.

Fast devices (ESP32-S3 w/ USB-CDC) should see connect() return in a few
hundred milliseconds instead of the full 3s / 8s ``boot_wait`` used by
``phases.py`` and ``gpio.py``.

Scope deliberately limited:
- Only ``ci/rpc_client.py`` and the new ``ci/util/boot_wait.py`` helper are
  touched. Autoresearch callers (``phases.py``, ``gpio.py``, ``net.py``,
  ``ota.py``, ``ble.py``, ``driver_sweep.py``, ``decode.py``) inherit the
  speedup for free via the shared ``connect()`` entry point.
- ``gpio.py``'s DTR reset pyserial code is untouched — that's #2264 /
  fbuild upstream.
- Public CLI / RPC surface unchanged.

Tests:
- ``ci/tests/test_boot_wait.py`` — 9 unit tests covering early-exit,
  timeout-fallback, on_line mirroring, empty-patterns drain, and substring
  containment semantics.
- ``ci/tests/test_rpc_client_connect_spin_poll.py`` — 3 integration tests
  exercising ``RpcClient.connect()`` end-to-end with a fake SerialInterface:
  early-exit on banner, fallback on silence, opt-out via ``boot_signals=[]``.

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

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Introduced async boot signal polling to RpcClient.connect() via a new ci.util.boot_wait utility module. The polling mechanism detects device boot patterns in serial output and returns early on match, replacing a fixed sleep loop. Added supporting unit and integration tests validating signal detection, timeout behavior, and substring matching semantics.

Changes

Cohort / File(s) Summary
Boot Signal Detection Utility
ci/util/boot_wait.py
New async utility module with wait_for_signal() function implementing spin-poll logic with configurable timeout and interval. Defines BOOT_SIGNALS_ROM, BOOT_SIGNALS_SETUP, and BOOT_SIGNALS_ANY pattern constants for device state detection. Supports optional per-line callbacks and graceful timeout/exception handling.
RPC Client Connection Enhancement
ci/rpc_client.py
Extended RpcClient.connect() signature with optional boot_signals parameter. Replaced fixed incremental sleep loop with async boot signal polling via wait_for_signal(). Added lazy resolution of default boot signals and adjusted boot output logging to account for lines consumed during polling.
Boot Wait Utility Tests
ci/tests/test_boot_wait.py
New comprehensive unit test suite validating wait_for_signal() behavior including signal constant membership, early exit on pattern match, timeout handling, callback invocation, empty pattern list behavior, and substring matching semantics using a fake serial stand-in.
RPC Client Connection Tests
ci/tests/test_rpc_client_connect_spin_poll.py
New integration test suite measuring wall-clock timing for connect() with boot signal polling. Tests early return on boot signal detection, timeout fallback when no signal appears, and opt-out behavior when boot_signals is empty. Uses fake serial implementation simulating device responses.

Sequence Diagram

sequenceDiagram
    participant Client as RpcClient
    participant BootWait as ci.util.boot_wait
    participant Serial as SerialInterface
    participant Thread as Event/Signal

    Client->>Client: connect(boot_signals=...)
    Client->>BootWait: wait_for_signal(patterns, timeout)
    
    loop Spin-Poll Loop (until timeout or match)
        BootWait->>Serial: read_line()
        Serial-->>BootWait: line (or timeout)
        BootWait->>BootWait: check if pattern in line
        alt Pattern Matched
            BootWait-->>Client: (matched_pattern, drained_lines)
            Client->>Client: return early
        else KeyboardInterrupt
            BootWait->>Thread: handle_keyboard_interrupt()
            Thread-->>BootWait: re-raise
            BootWait-->>Client: KeyboardInterrupt
        else No Match & Timeout Expired
            BootWait-->>Client: (None, drained_lines)
            Client->>Client: proceed with drain_boot_output()
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 A spin-poll on the wire, we now inspire,
No more sleeping fixed—boot signals fire!
Early exit, patterns dance,
RPC gets its nimble chance. 🚀

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: replacing sleep-based reset waits with spin-poll optimization, and is directly related to the changeset modifications in ci/rpc_client.py and new ci/util/boot_wait.py.

✏️ 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 perf/autoresearch-spin-poll-2265

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

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

22-26: Avoid default parameters in the fake serial constructor.

banner and emit_banner should be required and supplied explicitly by each test to satisfy the Python standards. As per coding guidelines, All function parameters MUST have explicit type annotations and MUST NOT have default values.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/tests/test_rpc_client_connect_spin_poll.py` around lines 22 - 26, The fake
serial constructor (__init__) currently uses default values for parameters
banner and emit_banner; change the signature to require both parameters (remove
the defaults so banner: str and emit_banner: bool are mandatory) and update all
tests/instantiations that create this fake serial to pass explicit banner and
emit_banner arguments; ensure the __init__ body and any type annotations remain
unchanged except for removing the default values.
ci/tests/test_boot_wait.py (1)

37-37: Remove the default from _FakeSerial.__init__.

per_batch_delay: float = 0.0 violates the project’s no-default-parameter rule for Python functions; pass per_batch_delay=0.0 explicitly at call sites instead. As per coding guidelines, All function parameters MUST have explicit type annotations and MUST NOT have default values.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/tests/test_boot_wait.py` at line 37, The __init__ signature of the test
helper class _FakeSerial currently uses a default value for per_batch_delay;
remove the default so the signature becomes def __init__(self, batches:
list[list[str]], per_batch_delay: float) -> None and update every call site that
instantiates _FakeSerial (in tests within this file or test helpers) to pass
per_batch_delay explicitly (e.g., per_batch_delay=0.0 where the previous
behavior is desired); ensure the type annotation remains and no callers rely on
the previous implicit default.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@ci/rpc_client.py`:
- Around line 211-243: connect() currently defaults to BOOT_SIGNALS_ANY so
wait_for_signal can return on ROM banners like "ESP-ROM:" and treat the device
as RPC-ready; change the logic in connect() around effective_signals and
wait_for_signal so ROM/banner signals are not considered sufficient for RPC
readiness — either (A) replace BOOT_SIGNALS_ANY with a safer default set that
only includes setup/RPC-ready markers, or (B) implement a two-phase wait: first
detect device-alive ROM banners (using BOOT_SIGNALS_ANY) without returning, then
continue waiting (up to the original boot_wait deadline) for explicit
RPC/setup-ready signals before proceeding. Update references to
effective_signals, BOOT_SIGNALS_ANY, wait_for_signal and the boot_wait timeout
handling to reflect the chosen approach so connect() only returns when the RPC
dispatcher is actually ready.
- Line 266: The print statement currently uses an unnecessary f-string for a
static message; locate the print call that prints "📥 [RPC] Draining boot
output..." (the print(...) containing that exact text) and remove the leading f
so it becomes a normal string literal (print("📥 [RPC] Draining boot
output...")). Ensure no other changes are made.

In `@ci/util/boot_wait.py`:
- Around line 91-128: The loops that call iface.read_lines(...) currently
swallow all exceptions; replace the broad "except Exception:" handlers with
catching only timeout-related exceptions (e.g., asyncio.TimeoutError) so real
errors propagate (do not catch RuntimeError), and ensure asyncio is imported if
needed; specifically update both try/except blocks around the async for over
iface.read_lines (the block that appends to drained, calls on_line, checks
patterns_list and deadline) to catch asyncio.TimeoutError (treat as normal
timeout) and let RuntimeError and other real failures bubble up.

---

Nitpick comments:
In `@ci/tests/test_boot_wait.py`:
- Line 37: The __init__ signature of the test helper class _FakeSerial currently
uses a default value for per_batch_delay; remove the default so the signature
becomes def __init__(self, batches: list[list[str]], per_batch_delay: float) ->
None and update every call site that instantiates _FakeSerial (in tests within
this file or test helpers) to pass per_batch_delay explicitly (e.g.,
per_batch_delay=0.0 where the previous behavior is desired); ensure the type
annotation remains and no callers rely on the previous implicit default.

In `@ci/tests/test_rpc_client_connect_spin_poll.py`:
- Around line 22-26: The fake serial constructor (__init__) currently uses
default values for parameters banner and emit_banner; change the signature to
require both parameters (remove the defaults so banner: str and emit_banner:
bool are mandatory) and update all tests/instantiations that create this fake
serial to pass explicit banner and emit_banner arguments; ensure the __init__
body and any type annotations remain unchanged except for removing the default
values.
🪄 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: 31097440-ee68-422a-a158-93be9b11041e

📥 Commits

Reviewing files that changed from the base of the PR and between 0de676a and 0a53600.

📒 Files selected for processing (4)
  • ci/rpc_client.py
  • ci/tests/test_boot_wait.py
  • ci/tests/test_rpc_client_connect_spin_poll.py
  • ci/util/boot_wait.py

Comment thread ci/rpc_client.py
Comment on lines +211 to +243
# Resolve default boot signals lazily so tests that don't touch
# serial I/O don't import the util module.
effective_signals: tuple[str, ...] | list[str]
if boot_signals is None:
from ci.util.boot_wait import BOOT_SIGNALS_ANY

effective_signals = BOOT_SIGNALS_ANY
else:
effective_signals = boot_signals

poll_drained_lines: list[str] = []

if boot_wait > 0:
if self.verbose:
print(f"⏳ [RPC] Waiting {boot_wait}s for device boot...")
# Use async sleep to allow other tasks to run
# Poll in small increments for interrupt checking
start = time.time()
while time.time() - start < boot_wait:
self._check_interrupt()
await asyncio.sleep(0.05) # Async sleep, check interrupt every 50ms
print(f"⏳ [RPC] Waiting up to {boot_wait}s for device boot...")
from ci.util.boot_wait import wait_for_signal

def _mirror(line: str) -> None:
if self.verbose:
print(f" [boot-poll] {line[:120]}")

# Spin-poll for a boot signal. If none of the expected signals
# arrive within ``boot_wait`` the call still returns (timeout IS
# the fallback — see issue #2265), preserving the original
# "waited N seconds then moved on" behavior.
assert self._serial is not None
try:
matched, poll_drained_lines = await wait_for_signal(
self._serial,
effective_signals,
timeout=boot_wait,
on_line=_mirror if self.verbose 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.

⚠️ Potential issue | 🟠 Major

Don’t treat ROM banners as RPC readiness in connect().

Defaulting to BOOT_SIGNALS_ANY means connect() returns on "ESP-ROM:", "rst:", or "entry 0x" immediately, even though Arduino setup() and the RPC dispatcher may still be unavailable. A slow-but-chatty device will no longer get the boot_wait fallback and the first RPC can race boot completion.

Prefer setup/RPC-ready signals by default, or make ROM detection a separate “device alive” phase that continues waiting for setup readiness until the deadline.

Proposed safer default
         effective_signals: tuple[str, ...] | list[str]
         if boot_signals is None:
-            from ci.util.boot_wait import BOOT_SIGNALS_ANY
+            from ci.util.boot_wait import BOOT_SIGNALS_SETUP
 
-            effective_signals = BOOT_SIGNALS_ANY
+            effective_signals = BOOT_SIGNALS_SETUP
         else:
             effective_signals = boot_signals
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/rpc_client.py` around lines 211 - 243, connect() currently defaults to
BOOT_SIGNALS_ANY so wait_for_signal can return on ROM banners like "ESP-ROM:"
and treat the device as RPC-ready; change the logic in connect() around
effective_signals and wait_for_signal so ROM/banner signals are not considered
sufficient for RPC readiness — either (A) replace BOOT_SIGNALS_ANY with a safer
default set that only includes setup/RPC-ready markers, or (B) implement a
two-phase wait: first detect device-alive ROM banners (using BOOT_SIGNALS_ANY)
without returning, then continue waiting (up to the original boot_wait deadline)
for explicit RPC/setup-ready signals before proceeding. Update references to
effective_signals, BOOT_SIGNALS_ANY, wait_for_signal and the boot_wait timeout
handling to reflect the chosen approach so connect() only returns when the RPC
dispatcher is actually ready.

Comment thread ci/rpc_client.py

if drain_boot:
if self.verbose:
print(f"📥 [RPC] Draining boot output...")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
uv run ruff check ci/rpc_client.py --select F541

Repository: FastLED/FastLED

Length of output: 101


🏁 Script executed:

# First, check if the file exists and read the relevant section
cat -n ci/rpc_client.py | sed -n '260,275p'

Repository: FastLED/FastLED

Length of output: 838


🏁 Script executed:

# Try running ruff without uv to check for F541
ruff check ci/rpc_client.py --select F541 2>&1 || true

Repository: FastLED/FastLED

Length of output: 1283


Remove the f-string prefix; this f-string has no placeholders.

Ruff F541 correctly identifies that the f-string at line 266 has no interpolations and should be a regular string.

Proposed fix
-                print(f"📥 [RPC] Draining boot output...")
+                print("📥 [RPC] Draining boot output...")
📝 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
print(f"📥 [RPC] Draining boot output...")
print("📥 [RPC] Draining boot output...")
🧰 Tools
🪛 Ruff (0.15.10)

[error] 266-266: f-string without any placeholders

Remove extraneous f prefix

(F541)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/rpc_client.py` at line 266, The print statement currently uses an
unnecessary f-string for a static message; locate the print call that prints "📥
[RPC] Draining boot output..." (the print(...) containing that exact text) and
remove the leading f so it becomes a normal string literal (print("📥 [RPC]
Draining boot output...")). Ensure no other changes are made.

Comment thread ci/util/boot_wait.py
Comment on lines +54 to +60
async def wait_for_signal(
iface: "SerialInterface",
patterns: Iterable[str],
timeout: float,
spin_interval: float = 0.05,
on_line: "callable[[str], None] | None" = None, # type: ignore[valid-type]
) -> tuple[str | None, list[str]]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
cat > /tmp/verify_callable_annotation.py <<'PY'
from typing import get_type_hints

def bad_callback_type(cb: "callable[[str], None] | None") -> None:
    pass

try:
    get_type_hints(bad_callback_type)
except Exception as exc:
    print(type(exc).__name__)
    print(exc)
PY

uv run python /tmp/verify_callable_annotation.py

Repository: FastLED/FastLED

Length of output: 102


🏁 Script executed:

python3 /tmp/verify_callable_annotation.py <<'PY'
from typing import get_type_hints

def bad_callback_type(cb: "callable[[str], None] | None") -> None:
    pass

try:
    hints = get_type_hints(bad_callback_type)
    print("get_type_hints succeeded")
    print(f"Hints: {hints}")
except Exception as exc:
    print(f"Error: {type(exc).__name__}")
    print(f"Message: {exc}")
PY

Repository: FastLED/FastLED

Length of output: 125


🏁 Script executed:

# Read the actual file to verify the issues
head -130 ci/util/boot_wait.py | tail -80

Repository: FastLED/FastLED

Length of output: 3550


🏁 Script executed:

# Check if dataclass is already imported in the file
grep -n "^import\|^from" ci/util/boot_wait.py | head -20

Repository: FastLED/FastLED

Length of output: 175


🏁 Script executed:

# Look for exception handling blocks around lines 91-128 mentioned in scratchpad
sed -n '85,130p' ci/util/boot_wait.py

Repository: FastLED/FastLED

Length of output: 1903


Fix function signature and return type.

The type annotation "callable[[str], None]" is invalid; callable is a built-in function that cannot be subscripted. Use Callable from collections.abc instead. Additionally, this function violates Python standards by using default parameters and returning a tuple instead of a dataclass struct. Per coding guidelines: "All function parameters MUST have explicit type annotations and MUST NOT have default values" and "Return dataclass structs instead of tuples or dicts for functions with multiple return values."

Comment thread ci/util/boot_wait.py
Comment on lines +91 to +128
try:
async for line in iface.read_lines(timeout=spin_interval):
drained.append(line)
if on_line is not None:
on_line(line)
if time.monotonic() >= deadline:
break
except KeyboardInterrupt as ki:
from ci.util.global_interrupt_handler import handle_keyboard_interrupt

handle_keyboard_interrupt(ki)
raise
except Exception:
# Read timeouts are normal.
pass
await asyncio.sleep(0)
return (None, drained)

deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
async for line in iface.read_lines(timeout=spin_interval):
drained.append(line)
if on_line is not None:
on_line(line)
for pat in patterns_list:
if pat in line:
return (pat, drained)
if time.monotonic() >= deadline:
break
except KeyboardInterrupt as ki:
from ci.util.global_interrupt_handler import handle_keyboard_interrupt

handle_keyboard_interrupt(ki)
raise
except Exception:
# Read timeouts are normal — keep polling until deadline.
pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect read_lines implementations and nearby exception behavior.
rg -nP -C8 'async\s+def\s+read_lines\s*\('

# Look for explicit timeout raises/catches in serial-related code.
rg -nP -C4 '(raise\s+(asyncio\.)?TimeoutError|except\s+(asyncio\.)?TimeoutError|TimeoutError)' ci

Repository: FastLED/FastLED

Length of output: 40304


🏁 Script executed:

# Find serial_monitor implementation and its read_lines behavior
cat -n ci/util/serial_monitor.py | head -100

# Look for the actual read_lines implementation in serial_monitor
rg -nA20 'def read_lines' ci/util/serial_monitor.py

# Check what exceptions are raised in the producer/read loop
rg -nB5 -A10 'def _producer|raise.*Timeout|except.*Error' ci/util/serial_interface.py | head -80

Repository: FastLED/FastLED

Length of output: 4943


🏁 Script executed:

# Get the complete _producer function and its exception handling
sed -n '186,250p' ci/util/serial_interface.py

# Also check what serial_monitor.read_lines does
rg -nA30 'def read_lines' ci/util/serial_monitor.py

Repository: FastLED/FastLED

Length of output: 2448


🏁 Script executed:

# Find serial_monitor read_lines implementation
fd serial_monitor ci/util --type f

# If found, get the read_lines method
rg -nA25 'def read_lines' ci/util/serial_monitor.py --max-count=1

Repository: FastLED/FastLED

Length of output: 112


🏁 Script executed:

# Check pyserial_monitor.py for read_lines
rg -nA30 'def read_lines' ci/util/pyserial_monitor.py

# Also check serial_monitor.py
rg -nA30 'def read_lines' ci/util/serial_monitor.py

Repository: FastLED/FastLED

Length of output: 1382


🏁 Script executed:

# Get more of the read_lines implementation to see exception handling
sed -n '123,200p' ci/util/pyserial_monitor.py

Repository: FastLED/FastLED

Length of output: 2980


🏁 Script executed:

# Check PySerialAsyncAdapter's read_lines implementation
sed -n '105,175p' ci/util/serial_interface.py

Repository: FastLED/FastLED

Length of output: 2357


🏁 Script executed:

# Check what fbuild's SerialMonitor.read_lines raises (if available in this repo)
# and search for any TimeoutError usage in serial-related code
rg -n 'TimeoutError' ci/util/serial_interface.py ci/util/pyserial_monitor.py ci/util/boot_wait.py

# Check if asyncio.TimeoutError is used anywhere in boot_wait context
rg -nB3 -A3 'asyncio.TimeoutError|asyncio.wait_for' ci/util/boot_wait.py

Repository: FastLED/FastLED

Length of output: 41


🏁 Script executed:

# Search for RuntimeError in serial backends - these are the real errors
rg -n 'raise RuntimeError' ci/util/pyserial_monitor.py

# Check what exceptions BLE read_lines can raise
rg -nB5 -A15 'async def read_lines' ci/util/ble_interface.py | head -50

# Look at the actual boot_wait code more carefully
sed -n '80,130p' ci/util/boot_wait.py

Repository: FastLED/FastLED

Length of output: 3499


🏁 Script executed:

# Verify what exceptions are actually possible from iface.read_lines()
# by checking each backend's docstring and exception handling

# PySerialMonitor complete read_lines signature
rg -B5 'Raises:' ci/util/pyserial_monitor.py | grep -A10 'read_lines' | head -20

# BLE read_lines complete signature
rg -B5 'Raises:' ci/util/ble_interface.py | grep -A10 'read_lines' | head -20

# Check if RuntimeError propagates from the async adapters
rg -n 'RuntimeError' ci/util/serial_interface.py

Repository: FastLED/FastLED

Length of output: 41


🏁 Script executed:

# Get the full docstring for PySerialMonitor.read_lines
sed -n '123,140p' ci/util/pyserial_monitor.py

# Get BLE read_lines docstring
sed -n '98,110p' ci/util/ble_interface.py

# Check the PySerialAsyncAdapter - does it wrap exceptions?
sed -n '105,125p' ci/util/serial_interface.py

# Look for any timeout behavior in these - what really happens on timeout?
rg -n 'timeout' ci/util/pyserial_monitor.py | head -10

Repository: FastLED/FastLED

Length of output: 2518


🏁 Script executed:

# Double-check: what does PySerialAsyncAdapter do with exceptions from read_lines?
sed -n '120,130p' ci/util/serial_interface.py

# Also verify: does read_lines in pyserial_monitor ever actually raise on timeout?
# (We saw it just returns at line 149)
sed -n '145,165p' ci/util/pyserial_monitor.py

# Check if there are any other serial backend implementations
fd 'serial' ci/util --type f -name '*.py' | head -20

Repository: FastLED/FastLED

Length of output: 1508


🏁 Script executed:

# Check the full context of PySerialAsyncAdapter - what exceptions can propagate?
sed -n '100,130p' ci/util/serial_interface.py

# Verify: does PySerialMonitor.read_lines actually propagate RuntimeError?
sed -n '175,185p' ci/util/pyserial_monitor.py

Repository: FastLED/FastLED

Length of output: 1438


🏁 Script executed:

# Final verification: check if boot_wait actually receives RuntimeError
# by looking at what the adapters actually do

# Confirm PySerialAsyncAdapter just passes through exceptions
sed -n '120,128p' ci/util/serial_interface.py

# Does read_lines ever actually raise TimeoutError in any backend?
rg -n 'raise.*TimeoutError|raise asyncio.TimeoutError' ci/util/pyserial_monitor.py ci/util/ble_interface.py ci/util/serial_interface.py

# What DOES PySerialAsyncAdapter.read_lines propagate?
rg -B2 -A8 'async def read_lines' ci/util/serial_interface.py | grep -A8 'PySerialAsyncAdapter' | head -20

Repository: FastLED/FastLED

Length of output: 396


Catch only specific timeout exceptions instead of all exceptions.

Both poll loops treat every Exception from iface.read_lines() as a normal timeout. That silently hides real failures like disconnected devices, serial errors, and permission issues.

However, the timeout behavior varies by backend:

  • BLE: raises asyncio.TimeoutError on timeout (caught at line 115 in ble_interface.py)
  • PySerial: returns silently on timeout (no exception raised)
  • Real errors: Both backends raise RuntimeError for actual failures (device not connected, serial read error)

The current broad except Exception masks both normal timeouts AND critical errors. The exceptions should be handled as:

Safer approach
-            except Exception:
-                # Read timeouts are normal.
-                pass
+            except asyncio.TimeoutError:
+                # Read timeouts are normal (from BLE backend).
+                pass
@@
-        except Exception:
-            # Read timeouts are normal — keep polling until deadline.
-            pass
+        except asyncio.TimeoutError:
+            # Read timeouts are normal (from BLE backend).
+            pass

For PySerial, timeouts don't raise exceptions—the iterator just returns. For BLE, asyncio.wait_for() raises asyncio.TimeoutError. Real errors (RuntimeError from disconnected devices or serial failures) must propagate to fail fast.

🧰 Tools
🪛 Ruff (0.15.10)

[error] 103-105: try-except-pass detected, consider logging the exception

(S110)


[warning] 103-103: Do not catch blind exception: Exception

(BLE001)


[error] 126-128: try-except-pass detected, consider logging the exception

(S110)


[warning] 126-126: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/util/boot_wait.py` around lines 91 - 128, The loops that call
iface.read_lines(...) currently swallow all exceptions; replace the broad
"except Exception:" handlers with catching only timeout-related exceptions
(e.g., asyncio.TimeoutError) so real errors propagate (do not catch
RuntimeError), and ensure asyncio is imported if needed; specifically update
both try/except blocks around the async for over iface.read_lines (the block
that appends to drained, calls on_line, checks patterns_list and deadline) to
catch asyncio.TimeoutError (treat as normal timeout) and let RuntimeError and
other real failures bubble up.

@zackees

zackees commented Apr 18, 2026

Copy link
Copy Markdown
Member Author

CI status

test / build failures on this PR are caused by pre-existing audio test regressions on master (not introduced by this PR):

  • audio::Reactive - dominant frequency uses log-spaced bin centers
  • audio::Reactive - spectral metrics decay to zero on silence (FastLED#2253)
  • audio::Reactive - spectral metrics are pass-through during loud audio (FastLED#2253)
  • audio::detector::TempoAnalyzer - confidence fades in silence, BPM preserved

Root cause + fix in #2322. Once #2322 merges, this PR will rebase cleanly on top and CI should go green.

WASM check failures (esbuild could not resolve three.js vendor module) are also pre-existing on master and unrelated to this PR.

All autoresearch-specific validation in this PR's own test suite passes:

  • ci/tests/test_boot_wait.py (9 tests) ✅
  • ci/tests/test_rpc_client_connect_spin_poll.py (3 tests) ✅

@zackees
zackees merged commit 4fb52b3 into master Apr 18, 2026
62 of 83 checks passed
@zackees
zackees deleted the perf/autoresearch-spin-poll-2265 branch August 30, 2026 22:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Triage

Development

Successfully merging this pull request may close these issues.

perf(autoresearch): replace sleep-based reset waits with spin-poll validation

1 participant