Repository navigation
fix(io): finish fl::print minimal-surface contract for hosts (closes #2668) - #2683
Conversation
…ollow-up) PR #2669 landed the Arduino-side half of the contract from #2668 (HWCDC setTxTimeoutMs(0), guarded flush, ESP32-C6 board flags). This commit closes out the host-platform half — the items #2669 explicitly deferred to a follow-up. Host backends now match the contract: * `src/platforms/wasm/io_wasm.cpp.hpp` — write_bytes emits raw bytes via fwrite(stdout) instead of `printf("%02X ", b)` hex-encoding every byte. Prior behaviour was a contract violation: callers who wrote binary frames got expanded text instead. * `src/platforms/posix/io_posix.cpp.hpp` — flush(0) short-circuits without calling fsync(2) so flush(0) returns immediately per the contract. * `src/platforms/win/io_win.cpp.hpp` — flush(0) short-circuits and the (void)timeoutMs swallow is replaced with an explicit branch so future buffered sinks inherit the contract. Test injection layer adds the two missing handlers so the contract cases can run cross-platform under FASTLED_TESTING: * `src/fl/stl/cstdio.h` and `src/fl/stl/cstdio.cpp.hpp` — declare and wire `inject_flush_handler` / `inject_write_bytes_handler`, plus their `clear_*` companions. Tests added to `tests/fl/stl/cstdio.cpp` (the hook's test-file-pairing checker requires the same-named pair, so the contract cases sit in the existing file alongside the readline/printf tests): 1. fl::print bounded under backpressure (no busy-loop on zero-byte sink) 2. fl::flush honors timeoutMs (returns false past deadline) 3. fl::flush(0) returns immediately 4. fl::print deadlock-free against 1-byte sink (back-to-back writes) 5. fl::write_bytes round-trips 0x00/0xFF (regression guard for the WASM hex bug above) Intentionally NOT included in this PR (defensive, deferred at the issue's own "do later if needed"): * `src/platforms/esp/32/detail/usj_emergency.hpp` — IDF-side tier-2 fallback via `usb_serial_jtag_ll_*` inlines. The Arduino-side setTxTimeoutMs(0) fix from #2669 already meets the user-visible acceptance criterion ("boot banner within ~16ms of port open") per the #2668 hardware repro. Lint baseline check: `bash lint` reports the same pre-existing failures (`ci/meson/src_metadata_cache.py` KBI002 + `src/platforms/esp/32/drivers/lcd_spi/*` LoggingInIramChecker x4) both with and without this patch — confirmed by stash-and-rerun.
📝 WalkthroughWalkthroughThis PR implements injectable handlers for ChangesI/O Handler Testing and Platform Contracts
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 Infer (1.2.0)tests/fl/stl/cstdio.cpptests/fl/stl/cstdio.cpp:4:10: fatal error: 'fl/stl/chrono.h' file not found ... [truncated 1063 characters] ... ang/install/lib/clang/18/include" 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: 3
🧹 Nitpick comments (1)
tests/fl/stl/cstdio.cpp (1)
399-439: ⚡ Quick winStrengthen the flush contract tests so they fail on the current bypasses.
These cases both use handlers that return immediately, so they still pass if
fl::flush(timeoutMs)ignores the deadline internally or iffl::flush(0)routes through a handler before returning. Please make the handler observe the received timeout and fail loudly if the zero-timeout fast path is missed.🤖 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 `@tests/fl/stl/cstdio.cpp` around lines 399 - 439, The tests must make injected handlers validate the timeout they receive and fail loudly if the fast-path is missed: update the lambda passed to fl::inject_flush_handler in the "fl::flush honors timeoutMs" case (the handler that currently returns false) to assert/fail if timeoutMs == 0 (i.e. ensure the handler observes a positive deadline and rejects a zero timeout), and update the lambda in "fl::flush(0) returns immediately" to assert/fail if timeoutMs != 0 (rather than only setting handler_invoked_with_nonzero), so any routing of flush(0) through a nonzero-timeout path will immediately fail the test; keep using fl::flush, inject_flush_handler and the existing flags (handler_invoked_with_nonzero / budgetMs) to locate and change the handlers.
🤖 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 `@src/fl/stl/cstdio.cpp.hpp`:
- Around line 208-214: The flush function must preserve the zero-timeout fast
path: if timeoutMs == 0 it should immediately call and return
platforms::flush(0) before consulting any injected test handler; move the
timeoutMs==0 check to the top of fl::flush and only if timeoutMs != 0 allow
FASTLED_TESTING get_flush_handler() to run and possibly override behavior,
otherwise always short-circuit to platforms::flush(0).
In `@src/fl/stl/cstdio.h`:
- Around line 180-189: The injected write-bytes handler currently uses a raw
pointer + length; change the type alias write_bytes_handler_t to
fl::function<size_t(fl::span<const u8>)> and update the injection API signature
inject_write_bytes_handler to accept const write_bytes_handler_t& so callers use
fl::span<const u8>; leave existing fl::write_bytes(const u8*, size_t) callers to
adapt locally by constructing a fl::span<const u8> when invoking the injected
handler.
In `@src/platforms/posix/io_posix.cpp.hpp`:
- Around line 63-75: The nonzero path in flush(u32 timeoutMs) currently calls
fsync(2) directly and ignores both blocking beyond timeoutMs and fsync errors;
change flush to execute the fsync call asynchronously (e.g.,
std::async/std::thread + std::future) so you can wait_for the given timeoutMs
and enforce the deadline, then inspect the fsync return/errno: if the future
times out return false, if fsync returns -1 return false (optionally log errno),
otherwise return true; ensure the symbol names affected are flush(u32 timeoutMs)
and the usage of fsync so callers still get a boolean that reflects timeout or
error.
---
Nitpick comments:
In `@tests/fl/stl/cstdio.cpp`:
- Around line 399-439: The tests must make injected handlers validate the
timeout they receive and fail loudly if the fast-path is missed: update the
lambda passed to fl::inject_flush_handler in the "fl::flush honors timeoutMs"
case (the handler that currently returns false) to assert/fail if timeoutMs == 0
(i.e. ensure the handler observes a positive deadline and rejects a zero
timeout), and update the lambda in "fl::flush(0) returns immediately" to
assert/fail if timeoutMs != 0 (rather than only setting
handler_invoked_with_nonzero), so any routing of flush(0) through a
nonzero-timeout path will immediately fail the test; keep using fl::flush,
inject_flush_handler and the existing flags (handler_invoked_with_nonzero /
budgetMs) to locate and change the handlers.
🪄 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: 20083254-957f-4f38-a4b1-2bb1b1458494
📒 Files selected for processing (6)
src/fl/stl/cstdio.cpp.hppsrc/fl/stl/cstdio.hsrc/platforms/posix/io_posix.cpp.hppsrc/platforms/wasm/io_wasm.cpp.hppsrc/platforms/win/io_win.cpp.hpptests/fl/stl/cstdio.cpp
| using flush_handler_t = fl::function<bool(u32)>; | ||
| using write_bytes_handler_t = fl::function<size_t(const u8*, size_t)>; | ||
|
|
||
| // Inject function handlers for testing | ||
| void inject_print_handler(const print_handler_t& handler) FL_NOEXCEPT; | ||
| void inject_println_handler(const println_handler_t& handler) FL_NOEXCEPT; | ||
| void inject_available_handler(const available_handler_t& handler) FL_NOEXCEPT; | ||
| void inject_read_handler(const read_handler_t& handler) FL_NOEXCEPT; | ||
| void inject_flush_handler(const flush_handler_t& handler) FL_NOEXCEPT; | ||
| void inject_write_bytes_handler(const write_bytes_handler_t& handler) FL_NOEXCEPT; |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Use fl::span<const u8> for the injected write-bytes hook.
This new header-level test API reintroduces a raw pointer + length pair. Keeping the handler typed as fl::span<const u8> would preserve the header span convention while still letting fl::write_bytes(const u8*, size_t) adapt into it locally.
As per coding guidelines, "Use fl::span for function parameters instead of fl::vector or raw arrays".
🤖 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/fl/stl/cstdio.h` around lines 180 - 189, The injected write-bytes handler
currently uses a raw pointer + length; change the type alias
write_bytes_handler_t to fl::function<size_t(fl::span<const u8>)> and update the
injection API signature inject_write_bytes_handler to accept const
write_bytes_handler_t& so callers use fl::span<const u8>; leave existing
fl::write_bytes(const u8*, size_t) callers to adapt locally by constructing a
fl::span<const u8> when invoking the injected handler.
There was a problem hiding this comment.
Deferred. The other testing handlers (print/println/available/read) all use raw signatures - keeping write_bytes consistent with the existing pattern in the FASTLED_TESTING injection layer. A separate sweep that converts the whole layer to fl::span at once would be cleaner than a one-off change here.
There was a problem hiding this comment.
@zackees, understood — keeping write_bytes_handler_t consistent with the other raw-signature handlers in the FASTLED_TESTING injection layer makes sense. A cohesive sweep across the whole layer will be cleaner than a one-off change.
Would you like me to open a GitHub issue to track the future fl::span migration of the entire FASTLED_TESTING injection layer?
(´・ω・`)っ🐇
✏️ Learnings added
Learnt from: zackees
Repo: FastLED/FastLED PR: 2683
File: src/fl/stl/cstdio.h:180-189
Timestamp: 2026-06-02T17:57:03.887Z
Learning: In `src/fl/stl/cstdio.h`, the `FASTLED_TESTING` injection layer intentionally uses raw pointer + length signatures (e.g., `write_bytes_handler_t = fl::function<size_t(const u8*, size_t)>`) to stay consistent with all other handler types in that layer (`print_handler_t`, `println_handler_t`, `available_handler_t`, `read_handler_t`). A one-off switch to `fl::span<const u8>` for only `write_bytes_handler_t` was explicitly deferred; the preference is a full-layer sweep converting all handlers at once.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
Two of the three reviewer suggestions applied: 1. `src/fl/stl/cstdio.cpp.hpp` — fl::flush short-circuits on timeoutMs == 0 BEFORE consulting the injected handler. A misbehaving test double could otherwise turn flush(0) into a blocking call despite the public contract promising immediate return. Platform impls keep their own timeoutMs==0 short-circuit for defense in depth. 2. `src/platforms/posix/io_posix.cpp.hpp` — drop fsync(2) from flush(). fsync on a stderr pipe/socket can in principle block past the requested timeout; ::write(2, ...) already commits to the kernel synchronously for the TTY / pipe cases FastLED targets. The third suggestion (tighten test 3 to strictly assert the handler is invoked zero times for flush(0)) is deferred — applying it reliably triggers a Windows PCH path-normalization bug in the meson incremental build (cstdio.h gets seen via mixed forward/backslash paths and `#pragma once` fails to dedupe between the PCH and the test TU). The original test 3 still validates the contract (handler not invoked with a non-zero timeout), just with a weaker assertion. Tracked via a thread reply on the PR for follow-up.
After PR #2683 landed, the Stop hook surfaced 4 pre-existing master-baseline lint failures that the python_pipeline's short-circuit-on-first-fail had been hiding. None of them are caused by recent commits — they pre-date PR #2683 — but per CLAUDE.md's "fix all encountered errors" rule, sweeping them here: * `ci/meson/src_metadata_cache.py` - KBI002: bare `except KeyboardInterrupt: raise` now calls `_thread.interrupt_main()` first per repo convention. - `ty` possibly-missing-attribute: add an `assert cache is not None` after the `if cache is None: sys.exit(1)` guard so `ty` narrows `CacheEntry | None` -> `CacheEntry` for the subsequent attribute access at lines 213/215. * `src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp` and `src/platforms/esp/32/drivers/lcd_spi/lcd_spi_peripheral_esp.cpp.hpp` - LoggingInIramChecker: `FL_WARN` is not safe inside an `FL_IRAM` function (the macro pulls in the logging machinery which is not IRAM-resident). Swap the four call sites for `esp_rom_printf` — same pattern other IRAM-resident error paths already use, marked with the canonical `// ok esp_rom_printf` suppression comment. * `examples/AutoResearch/AutoResearchParlioStream.h` - PlatformIncludesChecker: AutoResearch is the canonical ESP32 PARLIO live-driver scratch sketch and intentionally pulls a deep driver header for streaming diagnostics. Suppress with the documented `// ok platform headers` marker. * `src/platforms/esp/32/drivers/parlio/parlio_engine.cpp.hpp` and `src/platforms/esp/32/drivers/usb_serial_jtag_esp32_idf.hpp` - StdintTypeChecker: three `uint32_t` references swapped for `fl::u32`. The parlio file gains `#include "fl/stl/int.h"`; the JTAG file already had `u32` in scope. `bash lint` is now clean against master HEAD on host (Windows).
Summary
Closes #2668 by completing the host-platform half of the minimal-surface print contract that #2669 deferred to a follow-up.
#2669 landed the Arduino-side half (HWCDC
setTxTimeoutMs(0), guardedflush, ESP32-C6 board flags) — that fixed the user-visible acceptance criterion (boot banner within ~16ms of port open). The remaining items the issue checklist called out for the host side and contract test are bundled here.What changed
src/platforms/wasm/io_wasm.cpp.hppwrite_bytesemits raw bytes viafwrite(stdout)instead ofprintf(\"%02X \", b)hex-encoding. Prior behaviour was a contract violation (callers writing binary frames got expanded text).src/platforms/posix/io_posix.cpp.hppflush(0)short-circuits without callingfsync(2)so the call returns immediately per the contract. Comment documents why positive timeouts are also trivially satisfied.src/platforms/win/io_win.cpp.hppflush(0)explicit short-circuit; replaces the silent(void)timeoutMsswallow.src/fl/stl/cstdio.h+src/fl/stl/cstdio.cpp.hppinject_flush_handler/inject_write_bytes_handler(+clear_*companions). Required to drive the cross-platform contract tests through the existing injection layer.tests/fl/stl/cstdio.cppTest plan
bash test cstdio— all 23 cases pass (18 pre-existing + 5 new contract cases).bash lint— same pre-existing failures as master baseline (ci/meson/src_metadata_cache.pyKBI002 +src/platforms/esp/32/drivers/lcd_spi/*LoggingInIramChecker x4); confirmed unrelated by stash-and-rerun.print,flush(timeoutMs)honors deadline,flush(0)is immediate, no deadlock under a 1-byte sink,write_bytesround-trips 0x00/0xFF.Intentionally NOT in this PR
src/platforms/esp/32/detail/usj_emergency.hppIDF-side tier-2 fallback. The Arduino-sidesetTxTimeoutMs(0)fix from fix(esp32c6): route Serial to HWCDC + non-blocking writes (#2665) #2669 already meets the user-visible acceptance criterion per the fl::print: minimal-surface contract — non-blocking on missing CDC host, USJ LL fallback on ESP32 USJ chips #2668 hardware repro. The issue's own checklist marks the deeper ESP32 IDF work as defensive ("do later if needed"), and it requires hardware verification on USJ-equipped chips that's out of scope for this host-only polish.Closes #2668.
🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
flush(0)now returns immediately without filesystem sync.flushbehavior now properly honors timeout parameter.New Features
Tests