Skip to content

fix(ci): repair all four emulation workflows (ESP32 QEMU + AVR8JS Uno) - #2285

Merged
zackees merged 1 commit into
masterfrom
fix-emulation-workflows-2282
Apr 18, 2026
Merged

zackees merged 1 commit into
masterfrom
fix-emulation-workflows-2282

Conversation

@zackees

@zackees zackees commented Apr 18, 2026 •

Copy link
Copy Markdown
Member

Root cause

All four failing emulation CI workflows share a single root cause: fbuild and the workflow scripts disagree about where build artifacts live.

fbuild writes artifacts to .fbuild/build/<env>/release/firmware.{elf,bin,hex}, but:

  • The QEMU and AVR8JS workflow bash scripts read .pio/build/<env>/firmware.elf / firmware.hex.
  • build_with_merged_bin reads .pio/build/<env>/{bootloader,partitions,firmware}.bin.

In every one of the failing runs, the fbuild compile actually succeeded (Compilation succeeded (fbuild) is in the logs) — the job then died because the post-build verification couldn't find the binaries at the expected legacy path.

Failing runs diagnosed

Workflow Run Real root cause
ESP32-DEV QEMU 24590847834 fbuild succeeded, .pio/build/esp32dev/bootloader.bin missing because fbuild doesn't emit it
ESP32-C3 QEMU 24590847817 same — fbuild doesn't produce bootloader.bin/partitions.bin
ESP32-S3 QEMU 24590847828 same
Uno AVR8JS 24590847799 fbuild succeeded, workflow bash looked for .pio/build/uno/firmware.elf which fbuild writes to .fbuild/build/uno/release/firmware.elf

None of these overlap with #2281 (that one is a pio check / platformio 6.1.18-vs-stable issue, not an artifact-path issue). Landing #2281 will not auto-fix any of these four workflows.

Changes in ci/compiler/pio.py

  1. _mirror_fbuild_artifacts_to_pio() (new): After a successful fbuild compile, copy firmware.elf, firmware.bin, firmware.hex, firmware.map, and build_info.json from .fbuild/build/<env>/[release/] into .pio/build/<env>/. This keeps the existing workflow bash scripts and crash decoders working without plumbing fbuild-awareness into every consumer. Unblocks the AVR8JS Uno workflow.

  2. build_with_merged_bin() — force PIO path on fbuild boards: Merged-bin builds need bootloader.bin and partitions.bin, which come from PlatformIO's ESP-IDF post-build step and are not emitted by fbuild at all. Temporarily override self.use_fbuild = False for the duration of the merged-bin build so the real PlatformIO path runs. Unblocks all three ESP32 QEMU workflows.

  3. build_with_merged_bin() — rich error on artifact-check failure: The old message was just Required binary files not found after build: ..., which hid the real cause. It now additionally prints directory listings of both the .pio/build/<env>/ and .fbuild/build/<env>/[release/] paths, plus the last 4KB of the actual compile output. Addresses the explicit acceptance criterion from CI: get all emulation tests (QEMU ESP32-DEV/C3/S3 + AVR8JS Uno) passing on master #2282 for better error surfacing.

Acceptance criteria (from #2282)

  • ESP32-DEV QEMU Test green on master (will verify after merge)
  • ESP32-C3 QEMU Test green on master (will verify after merge)
  • ESP32-S3 QEMU Test green on master (will verify after merge)
  • uno AVR8JS Test green on master (will verify after merge)
  • Build wrapper surfaces the real compile error on failure (no more silent "required binaries not found")

The four checkboxes above are "fixed in code" — they can only be confirmed green on master once the PR lands and a master run fires. I can't run QEMU/avr8js locally on Windows.

Local verification

  • bash test --cpp — 299/299 passed
  • bash lint — clean
  • Smoke test of _mirror_fbuild_artifacts_to_pio with a synthetic .fbuild tree confirms files are copied.

Related

Closes #2282

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced build error diagnostics by displaying detailed information about missing artifacts and compilation logs on failure.
  • Chores

    • Improved firmware artifact organization in multi-stage build workflows for increased build reliability.

…ed-bin

The four emulation CI workflows (ESP32-DEV/C3/S3 QEMU + Uno AVR8JS) were all
red on master because fbuild writes firmware artifacts to
`.fbuild/build/<env>/release/` while the QEMU/avr8js workflow scripts and
`build_with_merged_bin` look under the legacy `.pio/build/<env>/` path. The
builds actually succeeded but the post-build artifact checks failed.

Fixes:

1. After a successful fbuild compile, mirror `firmware.elf`, `firmware.bin`,
   `firmware.hex`, `firmware.map`, and `build_info.json` into
   `.pio/build/<env>/` so the existing workflow bash scripts and crash
   decoders keep working. This unblocks the AVR8JS Uno workflow.

2. `build_with_merged_bin` now forces the PlatformIO build path on fbuild
   boards, because fbuild does NOT produce `bootloader.bin` /
   `partitions.bin` — only PIO's ESP-IDF post-build step does. This
   unblocks the three ESP32 QEMU workflows, which all use --merged-bin.

3. When the artifact check in `build_with_merged_bin` fails anyway,
   surface a much richer error: directory listings of both the PIO and
   fbuild output paths, plus the last 4KB of the actual compile output.
   Satisfies the "no more silent 'required binaries not found'" acceptance
   criterion from #2282.

Closes #2282

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The changes add artifact mirroring from fbuild compile output to PlatformIO build directories, modify build mode handling to ensure required outputs exist, and expand error diagnostics to surface actual compilation errors instead of generic binary-not-found messages.

Changes

Cohort / File(s) Summary
Build System Improvements
ci/compiler/pio.py
Added _mirror_fbuild_artifacts_to_pio() to copy firmware artifacts between build directories; updated fbuild integration to invoke mirroring post-compile; modified build_with_merged_bin() to force PlatformIO build mode and display expanded diagnostics (artifact listings, directory contents, compile output tail) on missing binary failures.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 From fbuild to pio, our artifacts leap,
Mirroring magic through directories deep,
When binaries hide, bright errors now glow—
The rabbit debugs what we need to know! 🔍

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title references emulation workflow repair which is the primary focus, but the change summary shows modifications to ci/compiler/pio.py to mirror fbuild artifacts and improve error reporting—matching the main code changes.
Linked Issues check ✅ Passed The PR implements all acceptance criteria from #2282: mirrors fbuild artifacts to unblock AVR8JS Uno, disables fbuild for merged-bin builds to generate required ESP32 binaries, and improves error diagnostics for build failures.
Out of Scope Changes check ✅ Passed All changes in ci/compiler/pio.py are directly scoped to fixing the four emulation workflows by addressing the root cause of missing artifacts and improving error reporting.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ 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-emulation-workflows-2282

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

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

1190-1202: Restore self.initialized in the finally block too.

self.use_fbuild is saved and restored, but self.initialized is forced to False on line 1197 and never restored. Today the caller in ci/compiler/compilation_orchestrator.py creates a fresh PioCompiler per merged-bin invocation so this is latent, but if anyone ever reuses a compiler instance (or adds a retry around build_with_merged_bin), you'll get an unnecessary re-init and — more subtly — the instance will silently have switched from fbuild mode to PIO mode from the outside's perspective until the next init runs.

Cheap to make symmetric with the use_fbuild swap:

Proposed fix
         original_use_fbuild = self.use_fbuild
+        original_initialized = self.initialized
         if self.use_fbuild:
             print(
                 "build_with_merged_bin: forcing PlatformIO build path "
                 "(fbuild does not produce bootloader.bin/partitions.bin)"
             )
             self.use_fbuild = False
             self.initialized = False
         try:
             cancelled = threading.Event()
             result = self._internal_build_no_lock(example, cancelled)
         finally:
             self.use_fbuild = original_use_fbuild
+            # Only restore if we actually flipped it; otherwise keep the
+            # freshly-initialized state from the PIO build above.
+            if original_use_fbuild and not result.success:
+                self.initialized = original_initialized
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/compiler/pio.py` around lines 1190 - 1202, The code disables
self.initialized when forcing self.use_fbuild=False but only restores
use_fbuild; capture the original initialized state (e.g., original_initialized =
self.initialized) before setting self.initialized = False in
build_with_merged_bin, and restore it in the finally block alongside
self.use_fbuild (set self.initialized = original_initialized) so the compiler's
initialized flag is symmetric with the use_fbuild swap and the internal call to
_internal_build_no_lock keeps state consistent.

75-99: Consider deferring mkdir and warning when expected artifacts are absent.

Two small things:

  1. pio_artifacts_dir.mkdir(...) runs unconditionally (line 76). If fbuild produced zero artifacts, this still creates an empty .pio/build/<env>/ directory, which can mislead later checks that use path existence as a "build ran" signal.
  2. If none of firmware.elf/firmware.bin/firmware.hex were found, the function silently returns without printing anything. Since the whole point of this helper is to unblock QEMU/AVR8JS consumers, a visible warning when the expected firmware artifact is missing would save debugging time (matches the guideline of not silently falling back on missing critical resources).
Proposed refinement
-    pio_artifacts_dir = build_dir / ".pio" / "build" / environment
-    pio_artifacts_dir.mkdir(parents=True, exist_ok=True)
-
-    fbuild_release_dir = build_dir / ".fbuild" / "build" / environment / "release"
+    fbuild_release_dir = build_dir / ".fbuild" / "build" / environment / "release"
     fbuild_env_dir = build_dir / ".fbuild" / "build" / environment
 
     # firmware.* files land in the release/ subdir; metadata files like
     # build_info.json live one level up in the environment dir.
     candidates: list[tuple[Path, str]] = [
         (fbuild_release_dir / "firmware.elf", "firmware.elf"),
         (fbuild_release_dir / "firmware.bin", "firmware.bin"),
         (fbuild_release_dir / "firmware.hex", "firmware.hex"),
         (fbuild_release_dir / "firmware.map", "firmware.map"),
         (fbuild_env_dir / "build_info.json", "build_info.json"),
     ]
 
+    pio_artifacts_dir = build_dir / ".pio" / "build" / environment
     copied: list[str] = []
     for src, name in candidates:
         if src.exists():
+            pio_artifacts_dir.mkdir(parents=True, exist_ok=True)
             dst = pio_artifacts_dir / name
             shutil.copy2(src, dst)
             copied.append(name)
 
     if copied:
         print(f"Mirrored fbuild artifacts to {pio_artifacts_dir}: {', '.join(copied)}")
+    else:
+        print(
+            f"Warning: no fbuild artifacts found to mirror for environment "
+            f"{environment} (looked in {fbuild_release_dir} and {fbuild_env_dir})"
+        )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/compiler/pio.py` around lines 75 - 99, Defer creating pio_artifacts_dir
until you know you will copy files: first iterate the candidates (use the
existing candidates list and fbuild_release_dir/fbuild_env_dir) and build a list
of existing sources, but do not call pio_artifacts_dir.mkdir() unconditionally;
only mkdir and perform shutil.copy2 when there is at least one file to copy
(copied list non-empty). Additionally, if none of the firmware artifacts
(firmware.elf, firmware.bin, firmware.hex) are present, emit a visible warning
(e.g., print or logger.warn) that the expected firmware artifact is missing and
include the environment and fbuild_release_dir so downstream consumers know why
QEMU/AVR8JS may not run.
🤖 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/compiler/pio.py`:
- Around line 673-680: Update the try/except around the call to
_mirror_fbuild_artifacts_to_pio so KeyboardInterrupt is explicitly re-raised
before the broad Exception handler: add an except KeyboardInterrupt: raise block
followed by except Exception as mirror_err: ... to preserve the warning print,
referencing the existing call to _mirror_fbuild_artifacts_to_pio(self.build_dir,
environment) and the mirror_err variable for the logged message.

---

Nitpick comments:
In `@ci/compiler/pio.py`:
- Around line 1190-1202: The code disables self.initialized when forcing
self.use_fbuild=False but only restores use_fbuild; capture the original
initialized state (e.g., original_initialized = self.initialized) before setting
self.initialized = False in build_with_merged_bin, and restore it in the finally
block alongside self.use_fbuild (set self.initialized = original_initialized) so
the compiler's initialized flag is symmetric with the use_fbuild swap and the
internal call to _internal_build_no_lock keeps state consistent.
- Around line 75-99: Defer creating pio_artifacts_dir until you know you will
copy files: first iterate the candidates (use the existing candidates list and
fbuild_release_dir/fbuild_env_dir) and build a list of existing sources, but do
not call pio_artifacts_dir.mkdir() unconditionally; only mkdir and perform
shutil.copy2 when there is at least one file to copy (copied list non-empty).
Additionally, if none of the firmware artifacts (firmware.elf, firmware.bin,
firmware.hex) are present, emit a visible warning (e.g., print or logger.warn)
that the expected firmware artifact is missing and include the environment and
fbuild_release_dir so downstream consumers know why QEMU/AVR8JS may not run.
🪄 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: 93611aba-9359-4191-a646-cec8e7ba0db9

📥 Commits

Reviewing files that changed from the base of the PR and between 50b3f5c and 9015976.

📒 Files selected for processing (1)
  • ci/compiler/pio.py

Comment thread ci/compiler/pio.py
Comment on lines +673 to +680
try:
_mirror_fbuild_artifacts_to_pio(self.build_dir, environment)
except Exception as mirror_err:
# Non-fatal: legacy tooling may not work but the build succeeded.
print(
f"Warning: failed to mirror fbuild artifacts to .pio/build/{environment}: "
f"{mirror_err}"
)

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

Handle KeyboardInterrupt before the blind Exception catch.

Every other try/except in this file (e.g., lines 182-187, 254-258, 585-589, 1041-1045, 1129-1134) explicitly re-raises KeyboardInterrupt first. This block doesn't, which is both inconsistent and a guideline violation. It's also what Ruff is flagging as BLE001.

Strictly speaking KeyboardInterrupt doesn't inherit from Exception so it wouldn't be swallowed here, but the house style calls for the explicit branch — and if mirroring ever grows to call code that wraps BaseException, the blind catch becomes a real Ctrl+C hazard.

Proposed fix
             try:
                 _mirror_fbuild_artifacts_to_pio(self.build_dir, environment)
+            except KeyboardInterrupt as ki:
+                handle_keyboard_interrupt(ki)
+                raise
             except Exception as mirror_err:
                 # Non-fatal: legacy tooling may not work but the build succeeded.
                 print(
                     f"Warning: failed to mirror fbuild artifacts to .pio/build/{environment}: "
                     f"{mirror_err}"
                 )

As per coding guidelines: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions".

🧰 Tools
🪛 Ruff (0.15.10)

[warning] 675-675: 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/compiler/pio.py` around lines 673 - 680, Update the try/except around the
call to _mirror_fbuild_artifacts_to_pio so KeyboardInterrupt is explicitly
re-raised before the broad Exception handler: add an except KeyboardInterrupt:
raise block followed by except Exception as mirror_err: ... to preserve the
warning print, referencing the existing call to
_mirror_fbuild_artifacts_to_pio(self.build_dir, environment) and the mirror_err
variable for the logged message.

@zackees
zackees merged commit 5d3ca30 into master Apr 18, 2026
66 of 80 checks passed
zackees added a commit that referenced this pull request Apr 18, 2026
PR #2285 introduced `_mirror_fbuild_artifacts_to_pio` to copy firmware
artifacts from `.fbuild/build/<env>/release/` into `.pio/build/<env>/`
so QEMU and AVR8JS workflow scripts can keep finding them at the
legacy path. The mirror was called immediately after a successful
fbuild compile and BEFORE `generate_build_info_json_from_existing_build`.

Problem: on a fresh build (CI is always fresh), the `.pio/build/<env>/`
directory does not exist yet. `generate_build_info_json_from_existing_build`
invokes `pio project metadata --json-output`, which prepares that
directory by wiping and re-creating it — clobbering the firmware.elf /
firmware.hex we just copied in. After the compile returns, only
`idedata.json` remains; the workflow then fails with
"firmware.elf not found in .pio/build/<env>".

Reproduced locally on a freshly-deleted `.pio/` dir — mirror prints
success but files are gone immediately after.

Fix: swap the order. Generate build metadata first (which wipes the
dir), then mirror firmware artifacts so nothing else touches them.

Verified locally: after `bash compile uno --examples Blink` on a
fresh `.pio/`, the mirrored dir now contains firmware.elf, firmware.hex,
and idedata.json as expected.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Apr 18, 2026
fbuild's ESP32 orchestrator (>= 2.1.7) already emits bootloader.bin,
partitions.bin, and boot_app0.bin alongside firmware.bin. PR #2285
conservatively disabled fbuild for merged-bin builds based on an earlier
assumption that those artifacts were PIO-only; that assumption no longer
holds.

- Extend _mirror_fbuild_artifacts_to_pio() to also mirror the three ESP32
  boot/partition artifacts from .fbuild/build/<env>/release/ into the
  legacy .pio/build/<env>/ path.
- Drop the use_fbuild=False force-override inside build_with_merged_bin()
  so the compiler honors whichever build tool the caller asked for.

Verified locally:
- bash compile esp32s3 --examples Blink produces firmware.bin,
  bootloader.bin, partitions.bin, boot_app0.bin in both the fbuild
  release dir and the mirrored .pio/build/<env>/ path.
- esptool merge-bin produces a valid 4MB image (0xE9 magic at both
  bootloader and app offsets) directly from fbuild's artifacts.
- bash test --cpp: 300/300 pass.
- bash lint (Python): clean.

Refs #2287

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Apr 18, 2026
Replaces the Docker-based emulation CI pipeline (avr8js_docker_template.yml,
qemu_docker_template.yml) with direct `fbuild test-emu` invocations. fbuild
2.1.16+ ships a native `test-emu` subcommand that:

- Compiles the sketch and runs it under avr8js / qemu / simavr.
- Handles --timeout, --halt-on-success, --halt-on-error, --expect natively,
  replacing ~400 lines of bash+Python-inline orchestration per template.
- Auto-downloads the Espressif QEMU binary on first use, eliminating the
  espressif/idf Docker image pull.
- Auto-installs the avr8js npm package into ~/.fbuild/cache/, so the
  niteris/fastled-avr8js Docker image is no longer needed.
- Reads firmware from its own .fbuild/build/<env>/release/ layout directly,
  obviating the .pio/build/ path-mirror workarounds added in #2285 and
  patched in #2291.

Both templates drop from ~400 lines to ~150, preserving:
- The trusted/pr-code security checkout split.
- Python 3.11 + uv pinning, `uv sync` for deps.
- Halt / success / error regexes (AVR8JS: "Test setup starting" + "Test loop";
  QEMU: "Test finished.*completed.*iterations|Starting loop iteration 2" +
  "Guru Meditation|abort()").
- Artifact uploads for both success and failure paths.

Dependencies:
- FastLED/fbuild#85 (ESP32-C3 RISC-V QEMU support) — required for the
  qemu_esp32c3_test.yml path. Once merged, the C3 job starts passing.
- FastLED/fbuild#86 (avr8js auto-install robustness) — required for the
  avr8js path. Belt-and-suspenders `npm install [email protected]` added to
  the workflow as a hedge until #86 lands.

Follow-ups (not in this PR):
- Remove `_mirror_fbuild_artifacts_to_pio` (ci/compiler/pio.py:56-99) and
  its call site, plus the `use_fbuild = False` override in
  build_with_merged_bin (lines 1189-1196), once CI is confirmed green.
- Close #2291 as obsolete (mirror-ordering fix is no longer on the emulation
  code path).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Apr 18, 2026
… mirror

Replaces the ``_mirror_fbuild_artifacts_to_pio`` workaround with a direct
read from whichever backend produced the artifacts. Adds
``PioCompiler._artifacts_dir(env_name)`` returning either
``.fbuild/build/<env>/release/`` (when use_fbuild=True) or
``.pio/build/<env>/`` (PlatformIO). ``build_with_merged_bin`` and
``get_merged_bin_path`` both use the helper, so esptool merge_bin runs
against fbuild's output without any cross-directory copy.

The mirror was added in #2285 and extended in #2292 to bridge fbuild
output into ``.pio/build/`` so legacy consumers (QEMU/AVR8JS workflows,
crash decoder, ``build_with_merged_bin``) kept working. The new
``fbuild test-emu`` workflows (#2296) read fbuild's release dir
directly, leaving ``build_with_merged_bin`` as the only remaining
consumer — and that is now also fbuild-aware, so the mirror has no
callers left.

Diagnostic dump in the missing-artifacts branch now labels the active
backend's dir explicitly and lists both possible locations, so the
debug story when artifacts vanish is at least as good as before.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the fix-emulation-workflows-2282 branch August 30, 2026 22:22
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.

CI: get all emulation tests (QEMU ESP32-DEV/C3/S3 + AVR8JS Uno) passing on master

1 participant