Skip to content

fix(io): finish fl::print minimal-surface contract for hosts (closes #2668) - #2683

Merged
zackees merged 1 commit into
masterfrom
fix/cstdio-contract-2668
Jun 2, 2026
Merged

zackees merged 1 commit into
masterfrom
fix/cstdio-contract-2668

Conversation

@zackees

@zackees zackees commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

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), guarded flush, 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

File Change
src/platforms/wasm/io_wasm.cpp.hpp write_bytes emits raw bytes via fwrite(stdout) instead of printf(\"%02X \", b) hex-encoding. Prior behaviour was a contract violation (callers writing binary frames got expanded text).
src/platforms/posix/io_posix.cpp.hpp flush(0) short-circuits without calling fsync(2) so the call returns immediately per the contract. Comment documents why positive timeouts are also trivially satisfied.
src/platforms/win/io_win.cpp.hpp flush(0) explicit short-circuit; replaces the silent (void)timeoutMs swallow.
src/fl/stl/cstdio.h + src/fl/stl/cstdio.cpp.hpp New test-injection points: inject_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.cpp Five new contract cases (the hook's test-file-pairing checker requires the same-named pair, so they sit in the existing file alongside the readline/printf tests).

Test 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.py KBI002 + src/platforms/esp/32/drivers/lcd_spi/* LoggingInIramChecker x4); confirmed unrelated by stash-and-rerun.
  • Contract test cases cover exactly the five scenarios in the issue's test plan: backpressure-bounded print, flush(timeoutMs) honors deadline, flush(0) is immediate, no deadlock under a 1-byte sink, write_bytes round-trips 0x00/0xFF.

Intentionally NOT in this PR

Closes #2668.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • POSIX platform: flush(0) now returns immediately without filesystem sync.
    • Windows platform: flush behavior now properly honors timeout parameter.
    • WASM platform: Binary data serialization now preserves raw bytes instead of hex-encoding.
  • New Features

    • I/O testing framework enhanced with injectable flush and write_bytes handlers.
  • Tests

    • Added comprehensive validation tests for I/O operations.

…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.
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements injectable handlers for flush and write_bytes I/O operations and ensures platform implementations honor the flush timeout contract and binary write passthrough semantics. All changes are internal to the I/O layer with no public API surface additions.

Changes

I/O Handler Testing and Platform Contracts

Layer / File(s) Summary
Testing handler types and injection API
src/fl/stl/cstdio.h, src/fl/stl/cstdio.cpp.hpp
Introduces flush_handler_t and write_bytes_handler_t callback types under FASTLED_TESTING, adds lazy static accessors, and implements inject_flush_handler(), inject_write_bytes_handler(), clear_flush_handler(), and clear_write_bytes_handler() functions. Updates init_io_handlers() to initialize the new handler statics early.
Flush and write_bytes routing through injected handlers
src/fl/stl/cstdio.cpp.hpp
Updates flush(timeoutMs) and write_bytes(buffer, size) to consult injected test handlers before delegating to platform implementations, enabling behavioral contract verification.
Platform flush timeout and binary write contracts
src/platforms/posix/io_posix.cpp.hpp, src/platforms/win/io_win.cpp.hpp, src/platforms/wasm/io_wasm.cpp.hpp
POSIX and Windows implement explicit fast-paths for flush(0) to return immediately. WASM replaces hex-encoding with binary passthrough via fwrite to preserve null bytes and 0xFF values.
Behavioral contract tests
tests/fl/stl/cstdio.cpp
Adds test suite validating non-blocking print under backpressure, flush timeout respecting, flush(0) immediate return without handler invocation, no-deadlock on consecutive prints against minimal sink, and binary round-trip integrity including null bytes and 0xFF.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 With handlers now injected true,
And flush respects its timeout due,
Write bytes pass through, no hex in sight,
Tests guard the contract, clean and right!
I/O flows now, both fast and far. 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 PR title accurately references the completion of the host-side minimal-surface fl::print contract and links issue #2668 as the primary scope.
Linked Issues check ✅ Passed The PR implements all required host-platform objectives from #2668: write_bytes raw-byte emission (WASM), flush(0) short-circuiting (POSIX/Win), test-injection handlers, and five contract validation tests.
Out of Scope Changes check ✅ Passed All changes align with the host-side contract items explicitly deferred from #2669 and tracked in #2668; ESP32 IDF changes are intentionally excluded per PR scope.

✏️ 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/cstdio-contract-2668

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.cpp

tests/fl/stl/cstdio.cpp:4:10: fatal error: 'fl/stl/chrono.h' file not found
4 | #include "fl/stl/chrono.h"
| ^~~~~~~~~~~~~~~~~
1 error generated.
Error: the following clang command did not run successfully:
/opt/infer-linux-x86_64-v1.2.0/lib/infer/facebook-clang-plugins/clang/install/bin/clang-18
@/tmp/coderabbit-infer/ea9d82f9d27f4fbb2711b27e974c2d54213a082e-20de7188018f9c0c/tmp/clang_command_.tmp.a29731.txt
++Contents of '/tmp/coderabbit-infer/ea9d82f9d27f4fbb2711b27e974c2d54213a082e-20de7188018f9c0c/tmp/clang_command_.tmp.a29731.txt':
"-cc1" "-load"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../../facebook-clang-plugins/libtooling/build/FacebookClangPlugin.dylib"
"-add-plugin" "BiniouASTExporter" "-plugin-arg-BiniouASTExporter" "-"
"-plugin-arg-BiniouASTExporter" "PREPEND_CURRENT_DIR=1"
"-plugin-arg-BiniouASTExporter" "MAX_STRING_SIZE=65535" "-cc1" "-triple"
"x86_64-unknown-linux-gnu" "-emit-obj" "-mrelax-all" "-disable-f

... [truncated 1063 characters] ...

ang/install/lib/clang/18/include"
"-internal-isystem" "/usr/local/include" "-internal-isystem"
"/usr/lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
"-internal-externc-isystem" "/usr/include/x86_64-linux-gnu"
"-internal-externc-isystem" "/include" "-internal-externc-isystem"
"/usr/include" "-Wno-ignored-optimization-argument" "-Wno-everything"
"-fdeprecated-macro" "-ferror-limit" "19" "-fgnuc-version=4.2.1"
"-fskip-odr-check-in-gmf" "-fcxx-exceptions" "-fexceptions"
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o"
"/tmp/coderabbit-infer/20de7188018f9c0c/file.o" "-x" "c++"
"tests/fl/stl/cstdio.cpp" "-O0" "-fno-builtin" "-include"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../lib/clang_wrappers/global_defines.h"
"-Wno-everything"


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.

@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 2, 2026

@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: 3

🧹 Nitpick comments (1)
tests/fl/stl/cstdio.cpp (1)

399-439: ⚡ Quick win

Strengthen 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 if fl::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

📥 Commits

Reviewing files that changed from the base of the PR and between 0255432 and ea9d82f.

📒 Files selected for processing (6)
  • src/fl/stl/cstdio.cpp.hpp
  • src/fl/stl/cstdio.h
  • src/platforms/posix/io_posix.cpp.hpp
  • src/platforms/wasm/io_wasm.cpp.hpp
  • src/platforms/win/io_win.cpp.hpp
  • tests/fl/stl/cstdio.cpp

Comment thread src/fl/stl/cstdio.cpp.hpp Resolved
Comment thread src/fl/stl/cstdio.h
Comment on lines +180 to +189
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;

@coderabbitai coderabbitai Bot Jun 2, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@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.

Comment thread src/platforms/posix/io_posix.cpp.hpp Resolved
@zackees
zackees merged commit b38533f into master Jun 2, 2026
11 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 2, 2026
zackees added a commit that referenced this pull request Jun 2, 2026
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.
zackees added a commit that referenced this pull request Jun 2, 2026
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).
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.

fl::print: minimal-surface contract — non-blocking on missing CDC host, USJ LL fallback on ESP32 USJ chips

1 participant