Skip to content

fix(autoresearch): FbuildSerialAdapter read_lines loop + I2S stress tests - #2262

Merged
zackees merged 1 commit into
masterfrom
fix-fbuild-serial-rpc-timing
Apr 16, 2026
Merged

zackees merged 1 commit into
masterfrom
fix-fbuild-serial-rpc-timing

Conversation

@zackees

@zackees zackees commented Apr 16, 2026 •

Copy link
Copy Markdown
Member

Summary

  • FbuildSerialAdapter.read_lines() terminated after first batch (1-2 lines) — fbuild's native read_lines() returns early on the first Data message. The producer thread now loops until the overall deadline expires.
  • Reverted phases.py to use FbuildSerialAdapter (centralized daemon with reconnects/stream forking) instead of PySerialAdapter workaround.
  • Silent exception swallowing replaced with warnings.warn() in the adapter.
  • Added 18 I2S multi-lane stress tests covering 4/8/16 lanes at varying lengths, dynamic geometry changes, chipset group splitting, and failure recovery.

Upstream fbuild bugs (write ack race, write_json_rpc ID correlation) tracked at FastLED/fbuild#49.

Closes #2261

Test plan

  • Existing unit tests pass (bash test)
  • I2S stress tests pass in debug mode with ASAN/UBSAN
  • CI green

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Tests

    • Added extensive stress tests for multi-lane I2S driver scenarios, covering varied geometries, large loads, timing group combinations, and transmit/recovery cases.
  • Bug Fixes

    • Improved serial read timeout handling and surfaced errors via warnings for more reliable diagnostics.
  • Chores

    • Made serial interface initialization consistent across build paths to ensure a concrete interface is configured.

@coderabbitai

coderabbitai Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5f2d69c9-2b25-4dde-9234-f276cb087343

📥 Commits

Reviewing files that changed from the base of the PR and between da465df and 47cc585.

📒 Files selected for processing (3)
  • ci/autoresearch/phases.py
  • ci/util/serial_interface.py
  • tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp

📝 Walkthrough

Walkthrough

Unconditional serial interface construction was added to schema/pin setup (no branch setting ctx.serial_iface = None). Fbuild serial reading now loops with a monotonic deadline and warns on exceptions. Extensive I2S channel-driver stress tests were added.

Changes

Cohort / File(s) Summary
Autoresearch serial setup
ci/autoresearch/phases.py
Removed conditional branch that set ctx.serial_iface = None; create_serial_interface(...) is imported/assigned unconditionally and ctx.serial_iface is always created with use_pyserial=not use_fbuild.
Fbuild serial adapter
ci/util/serial_interface.py
FbuildSerialAdapter.read_lines(timeout) now computes a monotonic deadline and repeatedly calls self._monitor.read_lines(timeout=remaining) until the deadline; non-KeyboardInterrupt exceptions are emitted via warnings.warn; added time import.
I2S driver tests
tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp
Added numerous anonymous-namespace test helpers and ~432 lines of new FL_TEST_CASEs covering multi-lane geometries, buffer reallocation, timing-group splitting, zero-length lanes, failure recovery, rapid/steady frame sequences, and related assertions.

Sequence Diagram(s)

sequenceDiagram
    participant Runner as Runner/Caller
    participant Fbuild as FbuildSerialAdapter
    participant Monitor as _monitor
    Runner->>Fbuild: call read_lines(timeout)
    Fbuild->>Fbuild: deadline = time.monotonic() + timeout
    loop until time.monotonic() >= deadline
        Fbuild->>Monitor: read_lines(timeout=remaining)
        Monitor-->>Fbuild: lines / partial data
        alt exception (not KeyboardInterrupt)
            Fbuild-->>Runner: warnings.warn("FbuildSerialAdapter read_lines error: ...")
        end
    end
    Fbuild-->>Runner: return collected lines
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • bug: FbuildSerialAdapter 50ms read timeout drops RPC responses fbuild#49 — Changes to FbuildSerialAdapter read-loop behavior and elimination of the None branch align with fixes for early-exit/short-timeout behavior described in that issue.
  • Issue #2261 — Related symptom (dropped RPC pings) described; this PR does not enforce use_pyserial=True unconditionally, so it does not fully implement the always-PySerialAdapter fix proposed in that issue.

Poem

🐰 I hopped through ports and ticking clocks,
I looped till deadlines beat their knocks,
Warned of errors, cleared the line,
And LEDs now dance in tidy time — ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning I2S stress tests appear to be out of scope relative to issue #2261 which focuses on FbuildSerialAdapter RPC timing. The tests add 432+ lines for multi-lane I2S scenarios but lack clear connection to the linked issue. Clarify whether I2S stress tests are part of issue #2261 or a separate objective. If separate, file a distinct issue or remove from this PR to maintain focus on the RPC timing fix.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title references FbuildSerialAdapter read_lines loop and I2S stress tests, which match the main changes across multiple files.
Linked Issues check ✅ Passed Changes address issue #2261: FbuildSerialAdapter.read_lines() now loops until deadline instead of exiting early, phases.py now calls create_serial_interface with proper use_pyserial argument, and silent exceptions are replaced with warnings.

✏️ 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 fix-fbuild-serial-rpc-timing

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)
tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp (1)

335-341: Handle terminal ERROR in waitReady().

Right now this helper spins through all iterations for any non-READY state. If the driver transitions to ERROR, the new stress cases fail slowly and with less useful signal than necessary. Returning immediately on ERROR will make failures much easier to diagnose.

Suggested change
 bool waitReady(ChannelEngineI2S& driver, int maxIter = 5000) {
     for (int i = 0; i < maxIter; i++) {
-        if (driver.poll() == IChannelDriver::DriverState::READY)
+        const auto state = driver.poll();
+        if (state == IChannelDriver::DriverState::READY) {
             return true;
+        }
+        if (state == IChannelDriver::DriverState::ERROR) {
+            return false;
+        }
         fl::this_thread::yield();
     }
     return false;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp` around lines 335 -
341, The waitReady helper currently loops until READY but ignores an ERROR
state; update waitReady(ChannelEngineI2S& driver, int maxIter) to inspect
driver.poll() each iteration and if it equals IChannelDriver::DriverState::ERROR
return false immediately (instead of spinning), otherwise return true when READY
and keep the existing yield/timeout behavior—refer to the waitReady function and
the DriverState enum from driver.poll() to implement this early ERROR exit.
ci/autoresearch/phases.py (1)

910-910: Move this import to the module import block.

This new local import breaks the repository’s import-order rule, and nothing in the provided context suggests it is needed for cycle-breaking.

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 the current code and only fix it if needed.

In `@ci/autoresearch/phases.py` at line 910, The local import "from
ci.util.serial_interface import create_serial_interface" should be moved into
the module-level import block at the top of this file to comply with the
project's import-order rule; locate uses of create_serial_interface in this
module and remove the inline import, adding the same import statement to the
file's header alongside other local imports, and only keep a local import here
if it is strictly required to break an import cycle (in that case add a short
comment explaining the cycle); ensure the import remains exact:
create_serial_interface from ci.util.serial_interface.
🤖 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/util/serial_interface.py`:
- Around line 143-154: The loop in _producer currently calls
self._monitor.read_lines(...) directly which can block the adapter's
single-worker ThreadPoolExecutor (configured at max_workers=1) and starve
write() and close(); change the call so the blocking read_lines is executed off
the adapter's executor (e.g. use loop.run_in_executor(None,
self._monitor.read_lines, remaining) or
asyncio.to_thread(self._monitor.read_lines, remaining)) so the read runs on a
different thread pool and does not monopolize the adapter's executor; keep the
same deadline/remaining loop and still schedule results back to the asyncio loop
with loop.call_soon_threadsafe(queue.put_nowait, line).
- Around line 158-164: Replace the warning-and-emit-EOF behavior in
FbuildSerialAdapter.read_lines by enqueueing the actual exception so the async
consumer can re-raise it: inside the except block, call
loop.call_soon_threadsafe(queue.put_nowait, exc) (or wrap the exception in a
small Exception marker object) instead of warnings.warn, and adjust the finally
logic so you do not overwrite the exception with the None sentinel; the consumer
that reads from queue should detect an Exception instance and re-raise it rather
than treating it as EOF.

In `@tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp`:
- Around line 699-717: The test currently only checks mock.getTransmitCount() >=
1 which can pass from the initial failed attempts; capture the transmit count
before calling mock.setTransmitFailure(false) (use
I2sLcdCamPeripheralMock::instance().getTransmitCount()), then perform the
recovery sequence (driver.enqueue(...), driver.show(),
FL_REQUIRE(waitReady(driver))) and assert that mock.getTransmitCount() is
strictly greater than the captured pre-recovery count to ensure the second
show() actually caused new transmits.
- Around line 686-687: The test currently ignores the return value of
waitReady(driver) so a hung zero-length case doesn't fail; change the call to
assert the result instead (e.g., replace waitReady(driver); with a failing
assertion such as REQUIRE(waitReady(driver)) or ASSERT_TRUE(waitReady(driver))
so the test fails when waitReady() returns false/timeout). Update the call site
for waitReady(driver) in channel_driver_i2s.cpp to check its boolean result and
fail the test on false.

---

Nitpick comments:
In `@ci/autoresearch/phases.py`:
- Line 910: The local import "from ci.util.serial_interface import
create_serial_interface" should be moved into the module-level import block at
the top of this file to comply with the project's import-order rule; locate uses
of create_serial_interface in this module and remove the inline import, adding
the same import statement to the file's header alongside other local imports,
and only keep a local import here if it is strictly required to break an import
cycle (in that case add a short comment explaining the cycle); ensure the import
remains exact: create_serial_interface from ci.util.serial_interface.

In `@tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp`:
- Around line 335-341: The waitReady helper currently loops until READY but
ignores an ERROR state; update waitReady(ChannelEngineI2S& driver, int maxIter)
to inspect driver.poll() each iteration and if it equals
IChannelDriver::DriverState::ERROR return false immediately (instead of
spinning), otherwise return true when READY and keep the existing yield/timeout
behavior—refer to the waitReady function and the DriverState enum from
driver.poll() to implement this early ERROR exit.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 052968d7-36cc-4453-94e2-64b302fe8ffd

📥 Commits

Reviewing files that changed from the base of the PR and between eeef964 and da465df.

📒 Files selected for processing (3)
  • ci/autoresearch/phases.py
  • ci/util/serial_interface.py
  • tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp

Comment on lines 143 to +154
def _producer() -> None:
# fbuild's native read_lines() returns the first batch of lines
# then exits (it does NOT keep reading until timeout). We must
# loop over multiple read_lines() calls to cover the full timeout.
deadline = time.monotonic() + timeout
try:
for line in self._monitor.read_lines(timeout=timeout):
loop.call_soon_threadsafe(queue.put_nowait, line)
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
for line in self._monitor.read_lines(timeout=remaining):
loop.call_soon_threadsafe(queue.put_nowait, line)

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

Avoid monopolizing the adapter’s only worker during read_lines().

Because Line 112 configures ThreadPoolExecutor(max_workers=1) and write()/close() also use that pool, this deadline loop can block those calls for the full timeout whenever a read is active. That reintroduces request/response stalls under a long-lived reader.

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

In `@ci/util/serial_interface.py` around lines 143 - 154, The loop in _producer
currently calls self._monitor.read_lines(...) directly which can block the
adapter's single-worker ThreadPoolExecutor (configured at max_workers=1) and
starve write() and close(); change the call so the blocking read_lines is
executed off the adapter's executor (e.g. use loop.run_in_executor(None,
self._monitor.read_lines, remaining) or
asyncio.to_thread(self._monitor.read_lines, remaining)) so the read runs on a
different thread pool and does not monopolize the adapter's executor; keep the
same deadline/remaining loop and still schedule results back to the asyncio loop
with loop.call_soon_threadsafe(queue.put_nowait, line).

Comment on lines +158 to 164
except Exception as exc:
warnings.warn(
f"FbuildSerialAdapter read_lines error: {exc}",
stacklevel=2,
)
finally:
loop.call_soon_threadsafe(queue.put_nowait, 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

Propagate serial read failures instead of warning-and-closing.

After this except, the consumer only sees the None sentinel and treats the stream as finished. Real adapter failures get downgraded into EOFs or downstream RPC timeouts, which makes recovery and diagnosis much harder. Please pass the exception through the queue and re-raise it on the async side.

💡 Example direction
-        queue: asyncio.Queue[str | None] = asyncio.Queue()
+        queue: asyncio.Queue[str | BaseException | None] = asyncio.Queue()
...
-            except Exception as exc:
-                warnings.warn(
-                    f"FbuildSerialAdapter read_lines error: {exc}",
-                    stacklevel=2,
-                )
+            except Exception as exc:
+                loop.call_soon_threadsafe(queue.put_nowait, exc)
             finally:
                 loop.call_soon_threadsafe(queue.put_nowait, None)
...
-            if item is None:
+            if isinstance(item, BaseException):
+                raise item
+            if item is None:
                 break

As per coding guidelines, "Never use silent fallbacks for missing critical resources - always fail fast with descriptive errors".

🧰 Tools
🪛 Ruff (0.15.10)

[warning] 158-158: 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/serial_interface.py` around lines 158 - 164, Replace the
warning-and-emit-EOF behavior in FbuildSerialAdapter.read_lines by enqueueing
the actual exception so the async consumer can re-raise it: inside the except
block, call loop.call_soon_threadsafe(queue.put_nowait, exc) (or wrap the
exception in a small Exception marker object) instead of warnings.warn, and
adjust the finally logic so you do not overwrite the exception with the None
sentinel; the consumer that reads from queue should detect an Exception instance
and re-raise it rather than treating it as EOF.

Comment on lines +699 to +717
auto& mock = I2sLcdCamPeripheralMock::instance();
mock.setTransmitFailure(true);

for (int i = 0; i < 8; i++) {
driver.enqueue(createTestChannelData(i + 1, 50 + i * 10));
}
driver.show();
FL_REQUIRE(waitReady(driver));

// Recover
mock.setTransmitFailure(false);

for (int i = 0; i < 4; i++) {
driver.enqueue(createTestChannelData(i + 1, 30));
}
driver.show();
FL_REQUIRE(waitReady(driver));

FL_CHECK(mock.getTransmitCount() >= 1);

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

Assert the recovery path, not just any transmit attempt.

mock.getTransmitCount() >= 1 does not prove the second show() succeeded. If the failed phase is also counted as a transmit attempt, this still passes without validating recovery. Capture the count before clearing the failure and require it to increase afterward.

Suggested change
     driver.show();
     FL_REQUIRE(waitReady(driver));
 
+    const auto transmit_count_after_failure = mock.getTransmitCount();
+
     // Recover
     mock.setTransmitFailure(false);
 
     for (int i = 0; i < 4; i++) {
         driver.enqueue(createTestChannelData(i + 1, 30));
@@
     }
     driver.show();
     FL_REQUIRE(waitReady(driver));
 
-    FL_CHECK(mock.getTransmitCount() >= 1);
+    FL_CHECK(mock.getTransmitCount() > transmit_count_after_failure);
📝 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
auto& mock = I2sLcdCamPeripheralMock::instance();
mock.setTransmitFailure(true);
for (int i = 0; i < 8; i++) {
driver.enqueue(createTestChannelData(i + 1, 50 + i * 10));
}
driver.show();
FL_REQUIRE(waitReady(driver));
// Recover
mock.setTransmitFailure(false);
for (int i = 0; i < 4; i++) {
driver.enqueue(createTestChannelData(i + 1, 30));
}
driver.show();
FL_REQUIRE(waitReady(driver));
FL_CHECK(mock.getTransmitCount() >= 1);
auto& mock = I2sLcdCamPeripheralMock::instance();
mock.setTransmitFailure(true);
for (int i = 0; i < 8; i++) {
driver.enqueue(createTestChannelData(i + 1, 50 + i * 10));
}
driver.show();
FL_REQUIRE(waitReady(driver));
const auto transmit_count_after_failure = mock.getTransmitCount();
// Recover
mock.setTransmitFailure(false);
for (int i = 0; i < 4; i++) {
driver.enqueue(createTestChannelData(i + 1, 30));
}
driver.show();
FL_REQUIRE(waitReady(driver));
FL_CHECK(mock.getTransmitCount() > transmit_count_after_failure);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp` around lines 699 -
717, The test currently only checks mock.getTransmitCount() >= 1 which can pass
from the initial failed attempts; capture the transmit count before calling
mock.setTransmitFailure(false) (use
I2sLcdCamPeripheralMock::instance().getTransmitCount()), then perform the
recovery sequence (driver.enqueue(...), driver.show(),
FL_REQUIRE(waitReady(driver))) and assert that mock.getTransmitCount() is
strictly greater than the captured pre-recovery count to ensure the second
show() actually caused new transmits.

…ests

FbuildSerialAdapter.read_lines() was terminating after the first batch
of lines (1-2) because fbuild's native read_lines() returns early on
the first Data message. The producer thread now loops over multiple
read_lines() calls until the overall deadline expires, matching the
behavior callers expect.

Also:
- phases.py reverted to use FbuildSerialAdapter (centralized daemon)
  instead of PySerialAdapter workaround
- Silent exception swallowing replaced with warnings.warn()
- Added 18 I2S multi-lane stress tests (4/8/16 lanes, varying lengths,
  dynamic geometry, chipset groups, failure recovery)

Closes #2261

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@zackees
zackees force-pushed the fix-fbuild-serial-rpc-timing branch from da465df to 47cc585 Compare April 16, 2026 19:46
@zackees
zackees merged commit 9a9ed89 into master Apr 16, 2026
63 of 77 checks passed
@zackees
zackees deleted the fix-fbuild-serial-rpc-timing branch April 16, 2026 19:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(autoresearch): FbuildSerialAdapter drops RPC ping responses during GPIO pre-test

1 participant