Skip to content

fix(ci): probe fbuild compile-many via SUB --help (unbreaks CI fast path) - #2661

Merged
zackees merged 3 commits into
masterfrom
fix/fbuild-compile-many-detection
May 31, 2026
Merged

zackees merged 3 commits into
masterfrom
fix/fbuild-compile-many-detection

Conversation

@zackees

@zackees zackees commented May 31, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Every build_*.yml CI run on master has been logging fbuild ci and compile-many are unavailable in the installed fbuild; falling back to the legacy serial loop and silently doing per-sketch serial builds instead of using compile-many's stage-2 worker pool.
  • Root cause: _fbuild_supports_subcommand (ci/util/fbuild_runner.py:146) probed with <fbuild> help <SUB>, which clap parses as subcommand=help with <SUB> as a positional sketch arg, then rejects with exit 2 on the missing --board. Switch to <fbuild> <SUB> --help, which clap intercepts and exits 0 regardless of other required args.
  • Add a regression guard so the next refactor can't quietly re-disable compile-many.

Fixes #2660. Expected CI win on GitHub Actions (2-core runners, default sketch_jobs=min(cpus,2)=2): roughly 2× faster per-board builds, e.g. uno's 108-example run drops from ~3.5 min to ~2 min based on the current per-sketch wall times.

Test plan

  • Local probe against fbuild 2.2.6 returns True for both ci and compile-many
  • Inline pytest regression guard asserts the exact command line emitted
  • One uno CI run with the new branch shows the green path log lines (Starting compilation... followed by compile-many results: instead of the fallback message)

Summary by CodeRabbit

  • Bug Fixes

    • Restored reliable fbuild subcommand detection (fixes CI compile-many fallback).
  • Tests

    • Added a regression test to lock in the new subcommand-detection behavior.
  • New Features

    • Enriched build output with per-sketch Flash/RAM size parsing, timing, and success/failed annotations.
    • Added a batch summary showing total wall time, parallelism factor, and ok/fail counts.
  • Chores

    • Workflow step: added an install-cache key input keyed to project configuration.

`_fbuild_supports_subcommand` invoked `<fbuild> help <SUB>`, but fbuild's
clap surface parses that as subcommand=help, positional=<SUB> and exits 2
on any subcommand with required args like `--board`. The probe therefore
always returned False and CI silently fell back to the legacy per-sketch
serial loop, missing compile-many's stage-2 worker pool — visible in
every recent build_<board>.yml run as 'fbuild ci and compile-many are
unavailable in the installed fbuild; falling back to the legacy serial
loop'.

`<fbuild> <SUB> --help` is intercepted by clap before arg validation and
exits 0 regardless of other required args, so it works as a reliable
availability probe across fbuild versions.

Add a regression guard that asserts the exact command line emitted; if
the probe form drifts back to the broken `help SUB` shape, the guard
fails immediately instead of letting CI quietly half-cripple itself.

Fixes #2660
@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Fix fbuild subcommand probing to use fbuild <subcommand> --help, add parsing of per-sketch Flash/RAM strings, enrich compile-many batch timing and reporting, add a regression test for the probe form, and add a small CI cache-key input change.

Changes

Probe, log parsing, and batch reporting

Layer / File(s) Summary
Probe invocation change and regression test
ci/util/fbuild_runner.py, ci/tests/test_fbuild_compile_many.py
_fbuild_supports_subcommand now invokes fbuild <subcommand> --help; adds a pytest that clears caches, monkeypatches subprocess.run, and asserts the probe uses the subcommand-help form for ci and compile-many.
Log size parsing helpers
ci/util/fbuild_runner.py
Add Flash:/RAM: regexes and _parse_size_info_from_log(log_path) returning (flash, ram) or (None, None) when absent.
Batch timing, per-sketch durations, and reporting
ci/compiler/pio.py
Instrument batch start time, track per-sketch durations/stages, parse per-sketch flash/ram, reconstruct normalized colored SUCCESS/FAILED lines with timing and sizes, and emit final batch summary with wall-clock, parallelism, and ok/fail counts.

CI Cache Update

Layer / File(s) Summary
Add install-cache-key-extra input
.github/workflows/build_template.yml
Introduce install-cache-key-extra input to the fbuild setup action; set binary install cache key to hashFiles('pyproject.toml') and add explanatory comments.

Sequence Diagram(s)

sequenceDiagram
  participant PioCompiler as PioCompiler._build_fbuild_batch
  participant Fbuild as fbuild (compile-many)
  participant SketchLog as per-sketch log file
  participant LogParser as _parse_size_info_from_log
  participant CIConsole as console output
  PioCompiler->>Fbuild: start batch, spawn workers
  Fbuild-->>PioCompiler: per-sketch result (stage, time, log_path)
  PioCompiler->>LogParser: read log_path for Flash/RAM
  LogParser-->>PioCompiler: (flash, ram)
  PioCompiler->>CIConsole: print normalized SUCCESS/FAILED per-sketch with time and sizes
  PioCompiler->>CIConsole: print final batch summary (wall time, parallelism, ok/fail)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • FastLED/FastLED#2476: Previously touched fbuild compile-many detection and related CI paths; closely related to the probe/compile-many behavior.

Poem

"a rabbit nibbling bytes at dawn,
swapped 'help SUB' for 'SUB --help' anon,
parsed Flash and RAM with cheer,
timed the batch and printed clear —
now CI hops swift, builds carry on!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.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 title accurately summarizes the main change: fixing the fbuild probe to use SUB --help form instead of help SUB, which unbreaks the CI fast path with compile-many.
Linked Issues check ✅ Passed All code changes fully address the objectives from issue #2660: probe form corrected to fbuild --help [ci/util/fbuild_runner.py], regression test added [ci/tests/test_fbuild_compile_many.py], output normalized [ci/compiler/pio.py], and cache keying improved [.github/workflows/build_template.yml].
Out of Scope Changes check ✅ Passed All file changes are directly scoped to the core objectives: probe fix, regression test, output normalization, and workflow cache optimization. No unrelated modifications detected.

✏️ 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-compile-many-detection

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

🤖 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 `@ci/tests/test_fbuild_compile_many.py`:
- Line 256: Move the local import of subprocess out of the function and add it
to the top-level imports in ci/tests/test_fbuild_compile_many.py among the other
standard-library imports (standard-library imports first, then third-party, then
local); then remove the in-function "import subprocess" so the module uses the
top-level subprocess import instead.
🪄 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: 709a17ff-76e3-46a9-9fe8-ca17680eaaf8

📥 Commits

Reviewing files that changed from the base of the PR and between d3931c5 and 0a41434.

📒 Files selected for processing (2)
  • ci/tests/test_fbuild_compile_many.py
  • ci/util/fbuild_runner.py

detection always returned False and CI silently fell back to the
legacy serial loop. Regression guard for that bug.
"""
import subprocess

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

Move subprocess import to the top of the file.

The import is inside the function body, but the coding guidelines require all system imports at the top of the file. As per coding guidelines, "All system imports must be at the top of the file in proper order: standard library, third-party, local".

📦 Proposed fix to move import to top

Add subprocess to the imports at the top of the file (after line 3):

 from pathlib import Path
+import subprocess

 import pytest

Then remove it from inside the function:

     legacy serial loop. Regression guard for that bug.
     """
-    import subprocess
-
     monkeypatch.setattr(fbuild_runner, "get_fbuild_executable", lambda: "fbuild.exe")
📝 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
import subprocess
from pathlib import Path
import subprocess
import pytest
Suggested change
import subprocess
# (previous lines)
legacy serial loop. Regression guard for that bug.
"""
monkeypatch.setattr(fbuild_runner, "get_fbuild_executable", lambda: "fbuild.exe")
🤖 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 `@ci/tests/test_fbuild_compile_many.py` at line 256, Move the local import of
subprocess out of the function and add it to the top-level imports in
ci/tests/test_fbuild_compile_many.py among the other standard-library imports
(standard-library imports first, then third-party, then local); then remove the
in-function "import subprocess" so the module uses the top-level subprocess
import instead.

zackees added 2 commits May 31, 2026 06:35
…lock

The compile-many path was emitting only `SUCCESS: <name>` per sketch
and a single batch-level `Compilation succeeded (fbuild ci) [Xs]` line
from the runner. The serial loop, by contrast, prints a per-sketch
`build succeeded in Xs (flash: N, ram: M)` line for each sketch.
That output gap made parallel runs unreadable next to serial runs and
hid both per-sketch timing and size info.

Reconstruct an equivalent per-sketch summary from the data fbuild
already returns:
  - build_time_secs from the compile-many results table
  - flash/ram sizes parsed from each sketch's compile_many.log (the
    same Flash:/RAM: lines the serial path renders)
  - stage tag (stage1 = framework-warming sketch, stage2 = fanned-out)

Emit one final line at the bottom of the batch with the total wall
clock, the sum-of-per-sketch time, and the resulting parallelism factor
(sum / wall). Parallelism printed explicitly so it's obvious when
stage 2 actually fanned out vs. effectively ran serially — which is the
exact diagnosis the user asked for.

Sizes are kept in fbuild's display units (e.g. "2.75KB", "223 bytes")
rather than re-converted to raw bytes — the signal is "did size drift?",
not the literal byte count, and avoiding the conversion keeps fbuild
the single source of truth for unit choice across orchestrators.
…setup

After FastLED/fbuild#334 the setup action caches the installed fbuild
binary in $RUNNER_TEMP/fbuild-install and skips the pip install on a
cache hit. The install cache key intentionally omits anything matrix-
specific so every job in this repo's board matrix shares the same
binary — keying it on the pyproject.toml hash means a fbuild pin bump
invalidates the cached binary everywhere at once, with no other input
needed from us.

Until #334 merges and the action exposes the new input, GH Actions
will warn-and-ignore it; the existing behavior (re-install per job)
keeps working.

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

🧹 Nitpick comments (1)
ci/compiler/pio.py (1)

540-544: ⚡ Quick win

Drop the redundant local import time.

time is already imported at module top (Line 18), so the local re-import on Line 540 is dead and obscures the dependency. Move the _parse_size_info_from_log import to the module's top-level imports as well.

As per coding guidelines: "All system imports must be at the top of the file in proper order: standard library, third-party, local".

♻️ Proposed cleanup
-        import time
-
-        from ci.util.fbuild_runner import _parse_size_info_from_log
-
-        batch_start = time.monotonic()
+        batch_start = time.monotonic()

Add to the top-level imports:

from ci.util.fbuild_runner import _parse_size_info_from_log
🤖 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 `@ci/compiler/pio.py` around lines 540 - 544, Remove the redundant local
"import time" in the block that sets batch_start and instead move the
"_parse_size_info_from_log" import to the module top-level imports; ensure you
add "from ci.util.fbuild_runner import _parse_size_info_from_log" to the
file-level imports following the standard import ordering (standard library,
third-party, local), remove any duplicate "time" imports so the local block only
uses time.monotonic(), and update the block containing batch_start so it no
longer re-imports time or _parse_size_info_from_log.
🤖 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 `@ci/util/fbuild_runner.py`:
- Around line 202-230: Change _parse_size_info_from_log to return a small
dataclass (e.g., FbuildSizeInfo with attributes flash: str|None and ram:
str|None) instead of tuple[str|None, str|None], update the caller in pio.py (the
unpack at the current Line ~586) to accept the dataclass fields, and ensure the
function still returns FbuildSizeInfo(None, None) when missing; also modify the
try/except that reads the file to catch KeyboardInterrupt first and then OSError
(i.e., except KeyboardInterrupt: raise; except OSError: return
FbuildSizeInfo(None, None)) so the KeyboardInterrupt isn’t swallowed.

---

Nitpick comments:
In `@ci/compiler/pio.py`:
- Around line 540-544: Remove the redundant local "import time" in the block
that sets batch_start and instead move the "_parse_size_info_from_log" import to
the module top-level imports; ensure you add "from ci.util.fbuild_runner import
_parse_size_info_from_log" to the file-level imports following the standard
import ordering (standard library, third-party, local), remove any duplicate
"time" imports so the local block only uses time.monotonic(), and update the
block containing batch_start so it no longer re-imports time or
_parse_size_info_from_log.
🪄 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: 4ac9263d-036f-4552-b7b3-505d9377b5ce

📥 Commits

Reviewing files that changed from the base of the PR and between 0a41434 and 174797d.

📒 Files selected for processing (3)
  • .github/workflows/build_template.yml
  • ci/compiler/pio.py
  • ci/util/fbuild_runner.py

Comment thread ci/util/fbuild_runner.py
Comment on lines +202 to +230
def _parse_size_info_from_log(log_path: Path | None) -> tuple[str | None, str | None]:
"""Pull the (flash, ram) size strings out of an fbuild per-sketch log.

Returns (None, None) when the log is missing or doesn't contain the
Flash/RAM lines (e.g. a stage-1 fingerprint cache hit prints a shorter
log without size info). Callers should gracefully omit size in that case.
"""
if log_path is None or not log_path.exists():
return (None, None)
try:
content = log_path.read_text(encoding="utf-8", errors="ignore")
except OSError:
return (None, None)
flash: str | None = None
ram: str | None = None
for line in content.splitlines():
if flash is None:
m = _FLASH_SIZE_RE.match(line)
if m:
flash = m.group(1).strip()
continue
if ram is None:
m = _RAM_SIZE_RE.match(line)
if m:
ram = m.group(1).strip()
continue
if flash is not None and ram is not None:
break
return (flash, ram)

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

Return a dataclass instead of a tuple.

_parse_size_info_from_log returns tuple[str | None, str | None]. The repo already uses the @typechecked @dataclass`` pattern (e.g. FbuildCommandResult), so a small `FbuildSizeInfo(flash, ram)` struct would make the contract self-describing and update the unpack site in `pio.py` (Line 586) accordingly.

As per coding guidelines: "Return dataclass structs instead of tuples or dicts for functions with multiple return values".

Separately, the except OSError at Lines 213-214 does not handle KeyboardInterrupt first. It is harmless here (OSError can't swallow KeyboardInterrupt), but the codebase convention is to handle it explicitly, as per coding guidelines: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions".

♻️ Proposed dataclass return
+@typechecked
+@dataclass
+class FbuildSizeInfo:
+    """Parsed Flash/RAM size strings from an fbuild per-sketch log."""
+
+    flash: str | None
+    ram: str | None
+
+
-def _parse_size_info_from_log(log_path: Path | None) -> tuple[str | None, str | None]:
+def _parse_size_info_from_log(log_path: Path | None) -> FbuildSizeInfo:
     ...
-    if log_path is None or not log_path.exists():
-        return (None, None)
+    if log_path is None or not log_path.exists():
+        return FbuildSizeInfo(flash=None, ram=None)
     try:
         content = log_path.read_text(encoding="utf-8", errors="ignore")
+    except KeyboardInterrupt:
+        raise
     except OSError:
-        return (None, None)
+        return FbuildSizeInfo(flash=None, ram=None)
     ...
-    return (flash, ram)
+    return FbuildSizeInfo(flash=flash, ram=ram)

The caller in pio.py (Line 586) becomes:

-                    flash_str, ram_str = _parse_size_info_from_log(
-                        sketch_result.log_path
-                    )
+                    size_info = _parse_size_info_from_log(sketch_result.log_path)
+                    flash_str, ram_str = size_info.flash, size_info.ram
🤖 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 `@ci/util/fbuild_runner.py` around lines 202 - 230, Change
_parse_size_info_from_log to return a small dataclass (e.g., FbuildSizeInfo with
attributes flash: str|None and ram: str|None) instead of tuple[str|None,
str|None], update the caller in pio.py (the unpack at the current Line ~586) to
accept the dataclass fields, and ensure the function still returns
FbuildSizeInfo(None, None) when missing; also modify the try/except that reads
the file to catch KeyboardInterrupt first and then OSError (i.e., except
KeyboardInterrupt: raise; except OSError: return FbuildSizeInfo(None, None)) so
the KeyboardInterrupt isn’t swallowed.

@zackees
zackees merged commit fa147ae into master May 31, 2026
6 of 8 checks passed
@zackees

zackees commented May 31, 2026

Copy link
Copy Markdown
Member Author

Status update: the dispatch is now gated behind `FASTLED_USE_FBUILD_CI=1` (default off).

The detection probe fix on this branch made compile-many reachable for the first time in CI. teensy41 and esp32s3 immediately timed out at 30 minutes because compile-many re-builds the framework from scratch in every stage-2 sketch dir — see FastLED/fbuild#335. On uno alone it turns a ~3.5 min serial run into ~7 min.

Until fbuild#335 ships a shared framework cache, compile-many is a net regression for FastLED CI, so the dispatch path is gated and the default goes back to the legacy serial loop. Everything else on this branch — the `SUB --help` probe fix, the normalized per-sketch output, the install-cache wiring + workflow hash — stays active and useful.

To opt back in locally: `FASTLED_USE_FBUILD_CI=1 ./compile all`.

CI on this push should now mirror master's serial-loop times (uno ~3.5 min, etc).

zackees added a commit that referenced this pull request May 31, 2026
#2661 merged at 14:00 UTC enabled fbuild compile-many for the first
time. The subsequent CI runs immediately showed it as a hard
regression on master:

- uno (small framework): ~3.5 min serial → ~7 min compile-many
- teensy41 / esp32s3 (large framework): finished serial → 30 min
  BUILD FAIL Process timed out

Root cause is upstream FastLED/fbuild#335: each stage-2 sketch lives
in its own project dir (.build/pio/<board>/compile_many/<name>/) and
therefore gets its own .fbuild build dir, so the framework archive
stage-1 builds in the root dir is invisible — every stage-2 worker
re-builds the framework from scratch. The bigger the framework, the
worse the regression.

Until fbuild#335 lands a shared framework cache, gate the compile-many
dispatch behind FASTLED_USE_FBUILD_CI=1 so the default behaviour is
the known-good legacy serial loop. Everything else from #2661 — the
`SUB --help` probe fix, normalized per-sketch output, install-cache
wiring, workflow input — stays active and useful. Only the dispatch
to compile-many is gated.

Set FASTLED_USE_FBUILD_CI=1 locally to opt back in (handy for timing
experiments against the architectural fix once it lands).

Refs FastLED/fbuild#335
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.

fbuild compile-many silently disabled in CI due to wrong probe form (fbuild help SUB exits 2)

1 participant