Repository navigation
fix(autoresearch): FbuildSerialAdapter read_lines loop + I2S stress tests - #2262
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughUnconditional serial interface construction was added to schema/pin setup (no branch setting Changes
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
tests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp (1)
335-341: Handle terminalERRORinwaitReady().Right now this helper spins through all iterations for any non-
READYstate. If the driver transitions toERROR, the new stress cases fail slowly and with less useful signal than necessary. Returning immediately onERRORwill 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
📒 Files selected for processing (3)
ci/autoresearch/phases.pyci/util/serial_interface.pytests/platforms/esp/32/drivers/i2s/channel_driver_i2s.cpp
| 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) |
There was a problem hiding this comment.
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).
| except Exception as exc: | ||
| warnings.warn( | ||
| f"FbuildSerialAdapter read_lines error: {exc}", | ||
| stacklevel=2, | ||
| ) | ||
| finally: | ||
| loop.call_soon_threadsafe(queue.put_nowait, None) |
There was a problem hiding this comment.
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:
breakAs 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.
| 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); |
There was a problem hiding this comment.
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.
| 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]>
da465df to
47cc585
Compare
Summary
read_lines()returns early on the firstDatamessage. The producer thread now loops until the overall deadline expires.warnings.warn()in the adapter.Upstream fbuild bugs (write ack race, write_json_rpc ID correlation) tracked at FastLED/fbuild#49.
Closes #2261
Test plan
bash test)🤖 Generated with Claude Code
Summary by CodeRabbit
Tests
Bug Fixes
Chores