Skip to content

perf(wasm): wire ctc-emcc native launcher into WASM cross-file - #2487

Merged
zackees merged 2 commits into
masterfrom
wasm-ctc-emcc-launcher-2485
May 18, 2026
Merged

zackees merged 2 commits into
masterfrom
wasm-ctc-emcc-launcher-2485

Conversation

@zackees

@zackees zackees commented May 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #2485. WASM counterpart of the native _resolve_fast_native_entries() win — the native build previously dropped Meson setup from 27.60s → 10.13s (-63%) and total from 47.58s → 21.66s (-54%) by skipping the Python entry-point wrapper for clang++. The WASM cross-file still used clang-tool-chain-emcc (a Python entry point with ~800ms+ startup per invocation). This wires the already-compiled ctc-emcc.exe / ctc-em++.exe native launchers in, mirroring the clang++ pattern.

The native launcher implements a three-tier strategy in C++ (user-template → flag-hash auto-cache → Python fallback), so link steps and uncached first compiles still go through Python correctly. Tier 1+2 give native-binary speed for the steady-state case.

Changes

  • ci/meson/build_config.py (+107 lines)
    • New _ensure_emcc_native_launcher() — compiles/caches ctc-emcc.exe and ctc-em++.exe via clang_tool_chain.commands.compile_native.compile_native().
    • New WasmNativeEntries dataclass and public resolve_wasm_native_entries() — returns the resolved compiler paths plus a flag indicating whether the native launcher won. Never raises — always returns a usable WasmNativeEntries (native paths OR fallback to the Python wrapper).
  • ci/wasm_build.py (+100 lines)
    • New _render_wasm_cross_file() — generates <build_dir>/wasm_cross_file.generated.ini with the resolved compiler paths (backslash-escaped for Windows).
    • Updated all three meson setup call sites (initial setup, source-list reconfigure, self-healing reconfigure) to use the generated cross-file.
    • Logs whether the native launcher or the Python fallback is active so users can verify the optimization.
  • ci/meson/wasm_cross_file.ini is preserved as-is — it's still used as a fingerprint anchor in _compute_library_fingerprint() (ci/wasm_build.py:144), and serves as readable documentation of the fallback behavior.

Fallback semantics

If compile_native() fails (e.g., clang missing, build broken), resolve_wasm_native_entries() returns the Python-wrapper paths (clang-tool-chain-emcc / clang-tool-chain-emar). WASM builds continue to work — they just don't get the speedup.

ar always uses clang-tool-chain-emar (no native ctc-emar launcher exists in clang-tool-chain's TOOL_REGISTRY). The wasm-ld launcher (ctc-wasm-ld.exe) also exists but is left for a follow-up.

Test plan

  • bash test --cpp — all tests pass (304/304 in 150.63s).
  • bash lint — no new violations introduced. (Pre-existing KBI errors in ci/wasm_build.py:362/367/1604 on master are not touched here; they should be addressed in a separate PR.)
  • bash compile wasm --examples Blink — works end-to-end (61.36s total: library 34.46s, sketch 8.56s, link 3.70s).
  • Generated cross-file inspection confirms c / cpp point at absolute ctc-emcc.exe / ctc-em++.exe paths when the native launcher resolves.
  • Fallback path exercised via monkey-patch — confirmed c = 'clang-tool-chain-emcc', cpp = 'clang-tool-chain-emcc' in the generated file when the launcher build fails.

Note on merge ordering

This PR is being opened in parallel with #2484 (stale lockfile cleanup) — both touch ensure_meson_configured() in ci/wasm_build.py. If #2484 merges first, this branch will need a small rebase.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores

    • Dynamic WASM cross-file generation per build, reducing unnecessary reconfigures by writing only when content changes and allowing repaired native launchers to be picked up automatically.
    • Improved native tool resolution for WASM: prefers native launchers with a reliable fallback to wrapper tools and consistent archiver handling, improving build robustness.
  • Refactor / Style

    • Minor code reorganizations and formatting tweaks with no user-facing behavior changes.

Review Change Stack

The native build pipeline previously replaced clang-tool-chain-cpp.EXE
(a Python entry point with ~828ms startup per invocation) with the raw
clang++ binary resolved in the Meson native file. That alone cut total
native build time 54% (Meson Setup 27.6s -> 10.1s, see PR #2480 and
predecessor work).

The WASM build still routed every emcc invocation through
clang-tool-chain-emcc (Python entry point). This change wires the
compiled ctc-emcc / ctc-em++ native launchers (built on demand via
clang_tool_chain.commands.compile_native) into a dynamically generated
WASM Meson cross-file at <build_dir>/wasm_cross_file.generated.ini.

The launcher implements a 3-tier strategy (user-template -> flag-hash
auto-cache -> Python fallback), so uncached link/preprocess steps still
work correctly via the Python emcc.py underneath.

Fallback is preserved: if launcher resolution fails for any reason the
generated cross-file falls back to clang-tool-chain-emcc, matching the
historical static cross-file content. Worst case: WASM build is no
slower than before.

The static template at ci/meson/wasm_cross_file.ini is retained as both
documentation and a stable fingerprint anchor (so structural edits to
host_machine/properties still invalidate the library cache).

Out of scope (follow-up issues):
- ctc-wasm-ld.exe wiring (separate optimization)
- ctc-emar (no native launcher exists for it yet)

Closes #2485
Refs #2480

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

coderabbitai Bot commented May 18, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Generates per-build Meson WASM cross-files and resolves native ctc-emcc/ctc-em++ launchers (with Python-wrapper fallback). Centralizes native launcher output directory and wires the generated cross-file into Meson setup paths, writing INI only when content changes. Also includes minor formatting refactors in compiler/frontend scripts.

Changes

WASM dynamic cross-file generation with native tool resolution

Layer / File(s) Summary
WASM native tool resolution and fallback
ci/meson/build_config.py
Adds WasmNativeEntries dataclass, _native_launcher_output_dir(), _ensure_emcc_native_launcher(), and resolve_wasm_native_entries() to pick native emcc/em++ launchers or fall back to Python wrappers.
Dynamic WASM cross-file generation and integration
ci/wasm_build.py
Adds _render_wasm_cross_file(build_dir) to render a per-build Meson INI using resolved tool paths (with Meson-INI escaping), writes only on content change, and uses the generated cross-file in stale-build recovery, reconfigure, and initial Meson setup paths.

Minor formatting and refactors

Layer / File(s) Summary
PIO compiler small reformat
ci/compiler/pio.py
Reformats safe_name sanitization and a log-path existence check into multi-line expressions without changing behavior.
esbuild cache-condition reformat
ci/esbuild_frontend.py
Reformats the cache-validation if expression across multiple lines; no semantic change.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

🐰 In build dirs I hop and neatly weave,

Native emcc seeds, with wrappers on leave,
Cross-file blossoms per-build, fresh and bright,
Only changed petals cause Meson to rewrite,
A tiny rabbit cheers the toolchain's light.

🚥 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 PR title accurately and specifically describes the main change: wiring the ctc-emcc native launcher into the WASM cross-file for performance optimization.
Docstring Coverage ✅ Passed Docstring coverage is 91.67% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 wasm-ctc-emcc-launcher-2485

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
ci/wasm_build.py (1)

538-549: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Refresh the generated cross-file before taking this fast path.

This return runs before _render_wasm_cross_file(), so an existing build directory never picks up a newly available ctc-emcc launcher, a repaired generated cross-file, or any future cross-file content change unless the source file list changes or --force is used. Render first, then force meson setup --reconfigure if the generated file changed.

🤖 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/wasm_build.py` around lines 538 - 549, The fast-path return when
stored_hash == current_hash skips rendering the generated cross-file and thus
misses updates; call _render_wasm_cross_file() before taking this fast path and
compare the rendered cross-file output (or its hash/timestamp) against previous
content, and if it changed, ensure you set force or otherwise trigger a meson
reconfigure (equivalent to running meson setup --reconfigure) instead of
returning True; keep the existing calls to _compute_src_file_list_hash,
_normalize_meson_private_paths and respect the force argument so only unchanged
source list AND unchanged rendered cross-file can short-circuit the configure.
🤖 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/meson/build_config.py`:
- Around line 135-145: The try/except block that calls compile_native currently
swallows all exceptions so the code silently falls back to the Python wrapper;
update the exception handling to log a warning including the exception details
before returning the fallback paths (use the same logger used elsewhere in this
module) while still calling handle_keyboard_interrupt(ki) for
KeyboardInterrupts; specifically, in the block around
compile_native/ctc_emcc/ctc_empp add a processLogger.warning or similar that
includes the exception (or traceback) and context (e.g., "native launcher
resolution failed, falling back to Python wrapper") and apply the same change to
the second try/except (lines around where the other native resolution occurs) so
both paths emit a clear warning instead of silently passing.
- Around line 52-66: Add runtime type validation by importing typechecked from
typeguard and decorating the WasmNativeEntries dataclass with `@typechecked`;
specifically add "from typeguard import typechecked" to the imports and place
`@typechecked` immediately above the `@dataclass`(slots=True) on the
WasmNativeEntries class. Replace the silent broad except blocks in
_ensure_emcc_native_launcher and resolve_wasm_native_entries: catch only the
specific exceptions you expect (e.g., subprocess.CalledProcessError,
FileNotFoundError, OSError) or re-raise a new descriptive RuntimeError with
context so failures surface (do not keep "except Exception: pass" or "except
Exception: return fallback"). Ensure error messages indicate which launcher or
resolution failed and include underlying exception text when re-raising.

In `@ci/wasm_build.py`:
- Around line 435-523: _render_wasm_cross_file currently hardcodes the full
Meson cross-file content instead of reading the checked-in static template;
update it to load the template, patch only the [binaries] section and then write
the generated file so edits to the template propagate. Concretely: keep
resolve_wasm_native_entries(PROJECT_ROOT) and _escape_meson_string usage for
entries.c/entries.cpp/entries.ar, read the static template text (the checked-in
Meson cross-file template), locate/replace or insert the [binaries] block with
the generated lines ("c = '...'", "cpp = '...'", "ar = '...'", "strip =
'true'"), preserve the rest of the template and comments, and write to
_GENERATED_CROSS_FILE_NAME only if content changed; maintain existing build_dir
creation and error handling.

---

Outside diff comments:
In `@ci/wasm_build.py`:
- Around line 538-549: The fast-path return when stored_hash == current_hash
skips rendering the generated cross-file and thus misses updates; call
_render_wasm_cross_file() before taking this fast path and compare the rendered
cross-file output (or its hash/timestamp) against previous content, and if it
changed, ensure you set force or otherwise trigger a meson reconfigure
(equivalent to running meson setup --reconfigure) instead of returning True;
keep the existing calls to _compute_src_file_list_hash,
_normalize_meson_private_paths and respect the force argument so only unchanged
source list AND unchanged rendered cross-file can short-circuit the configure.
🪄 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: abb98106-3a80-4413-a4ed-363e1363e5cd

📥 Commits

Reviewing files that changed from the base of the PR and between 1c5f873 and 78fcbe9.

📒 Files selected for processing (2)
  • ci/meson/build_config.py
  • ci/wasm_build.py

Comment thread ci/meson/build_config.py Resolved
Comment thread ci/meson/build_config.py Resolved
Comment thread ci/wasm_build.py
Comment on lines +435 to +523
# Static sections (everything other than [binaries]) are kept in the
# checked-in template; only the [binaries] section is generated based on
# whether the native ctc-emcc launcher could be resolved.
_GENERATED_CROSS_FILE_NAME = "wasm_cross_file.generated.ini"


def _escape_meson_string(value: str) -> str:
"""Escape a string for safe insertion into a Meson .ini value.

Meson INI uses single-quoted strings; backslashes need doubling and
single quotes need escaping. Windows absolute paths are the common case.
"""
return value.replace("\\", "\\\\").replace("'", "\\'")


def _render_wasm_cross_file(build_dir: Path) -> Path:
"""Generate the WASM Meson cross-file with resolved compiler paths.

Returns the absolute path of the generated file. On any resolution
failure, the generated file is functionally identical to the static
template (Python wrappers, ``clang-tool-chain-emcc``), so the WASM
build never regresses below baseline behavior.
"""
from ci.meson.build_config import resolve_wasm_native_entries

entries = resolve_wasm_native_entries(PROJECT_ROOT)

if entries.used_native_launcher:
print(f"[WASM] Using native ctc-emcc launcher: {entries.c}")
else:
print(
"[WASM] Native ctc-emcc launcher unavailable; "
"falling back to clang-tool-chain Python wrapper"
)

c_val = _escape_meson_string(entries.c)
cpp_val = _escape_meson_string(entries.cpp)
ar_val = _escape_meson_string(entries.ar)

content = (
"# ============================================================================\n"
"# Meson Cross-Compilation File for Emscripten (WASM) [AUTO-GENERATED]\n"
"# ============================================================================\n"
"# Auto-generated by ci/wasm_build.py:_render_wasm_cross_file().\n"
"# DO NOT EDIT — edit ci/meson/wasm_cross_file.ini (static template)\n"
"# and the generator instead.\n"
"#\n"
"# The [binaries] section is dynamically resolved so we can point\n"
"# meson at the compiled ctc-emcc native launcher (near-zero startup)\n"
"# when it is available, with automatic fallback to the Python\n"
"# clang-tool-chain-emcc wrapper otherwise.\n"
"# ============================================================================\n"
"\n"
"[binaries]\n"
f"c = '{c_val}'\n"
f"cpp = '{cpp_val}'\n"
f"ar = '{ar_val}'\n"
"strip = 'true'\n"
"# Note: wasm-ld is invoked by emcc during linking, not directly by meson\n"
"\n"
"[host_machine]\n"
"system = 'emscripten'\n"
"cpu_family = 'wasm32'\n"
"cpu = 'wasm32'\n"
"endian = 'little'\n"
"\n"
"[properties]\n"
"# Skip meson's compiler sanity check — emcc sometimes fails the default\n"
"# test program due to missing emscripten runtime stubs at configure time.\n"
"# The actual compilation validates the toolchain during build.\n"
"skip_sanity_check = true\n"
"\n"
"# Emscripten executables need a JS runtime to run\n"
"needs_exe_wrapper = true\n"
)

build_dir.mkdir(parents=True, exist_ok=True)
generated = build_dir / _GENERATED_CROSS_FILE_NAME

# Only write if changed — meson will not see a meaningful change and
# avoid spurious reconfigures.
try:
existing = generated.read_text(encoding="utf-8")
except OSError:
existing = None
if existing != content:
generated.write_text(content, encoding="utf-8")
return generated

@coderabbitai coderabbitai Bot May 18, 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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

ci/meson/wasm_cross_file.ini is no longer the source of truth.

_render_wasm_cross_file() hardcodes the full file and never reads CROSS_FILE, so edits to the checked-in cross-file won't reach configured builds even though the comments call it the static template. That also means a change to ci/meson/wasm_cross_file.ini can invalidate caches without changing the actual Meson cross configuration. Please render from the checked-in template or stop treating that file as authoritative.

🤖 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/wasm_build.py` around lines 435 - 523, _render_wasm_cross_file currently
hardcodes the full Meson cross-file content instead of reading the checked-in
static template; update it to load the template, patch only the [binaries]
section and then write the generated file so edits to the template propagate.
Concretely: keep resolve_wasm_native_entries(PROJECT_ROOT) and
_escape_meson_string usage for entries.c/entries.cpp/entries.ar, read the static
template text (the checked-in Meson cross-file template), locate/replace or
insert the [binaries] block with the generated lines ("c = '...'", "cpp =
'...'", "ar = '...'", "strip = 'true'"), preserve the rest of the template and
comments, and write to _GENERATED_CROSS_FILE_NAME only if content changed;
maintain existing build_dir creation and error handling.

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.

Skipping for this PR — the static wasm_cross_file.ini is still used as a fingerprint anchor in _compute_library_fingerprint (line 144), so reworking it to a template adds non-trivial scope. Will address in a follow-up that either drops the static file or properly templates it.

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 — that dual role (fingerprint anchor + template source) makes the refactor genuinely non-trivial for this PR, so deferring is the right call.

Would you like me to open a follow-up GitHub issue to track this? I can include the relevant context (the fingerprint anchor usage and the two resolution options: drop the static file or properly template it) so it doesn't get lost.

- _ensure_emcc_native_launcher: log a [WASM] warning with the exception
  text before falling back to the Python wrapper (previously a silent
  except Exception: pass masked compile failures). KeyboardInterrupt
  still routes through handle_keyboard_interrupt.
- resolve_wasm_native_entries: same logging treatment on the outer
  resolver fallback path so callers see why the native launcher was
  bypassed.
- ensure_meson_configured: render the WASM cross-file before the
  fast-path return so a freshly built or repaired native launcher is
  picked up on the next meson invocation against an existing build
  directory. No reconfigure is forced; the cheap ini write is enough.
- Apply ruff format normalizations to ci/compiler/pio.py and
  ci/esbuild_frontend.py that were flagged by bash lint.

Skipped:
- @TypeChecked on WasmNativeEntries: decorator is not used elsewhere
  in ci/meson/build_config.py and the dataclass plus consumers are
  already statically typed. Better handled in a repo-wide pass.
- Reworking the hardcoded wasm_cross_file.ini contents into a
  template: the static file is still referenced as a fingerprint
  anchor in _compute_library_fingerprint (line 144), so removing or
  templating it adds non-trivial scope to this PR. Deferred to a
  follow-up.

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

zackees commented May 18, 2026

Copy link
Copy Markdown
Member Author

Addressed the outside-diff finding about the fast-path render — ensure_meson_configured() now calls _render_wasm_cross_file() before the short-circuit return, so an existing build directory always sees the latest generated cross-file. The render is cheap (just writes a small ini), and the next meson setup invocation will pick up any newly built or repaired native launcher automatically.

@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

♻️ Duplicate comments (2)
ci/meson/build_config.py (2)

52-66: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add runtime type checking to WasmNativeEntries.

WasmNativeEntries is a @dataclass but is missing @typechecked, which is required by repo standards.

Suggested patch
+from typeguard import typechecked
...
+@typechecked
 `@dataclass`(slots=True)
 class WasmNativeEntries:
#!/bin/bash
set -euo pipefail
sed -n '1,90p' ci/meson/build_config.py | rg -n 'typeguard|typechecked|`@dataclass`|class WasmNativeEntries'

As per coding guidelines: "Use @typechecked decorator with @dataclass for runtime type validation".

🤖 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/meson/build_config.py` around lines 52 - 66, The WasmNativeEntries
dataclass lacks runtime type validation per repo standards; add the `@typechecked`
decorator above the existing `@dataclass`(slots=True) for the WasmNativeEntries
class and ensure the typechecked symbol is imported (e.g. from typeguard import
typechecked) at the top of ci/meson/build_config.py so that WasmNativeEntries(c,
cpp, ar, used_native_launcher) gets validated at runtime.

144-148: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Narrow except Exception to expected failure types in launcher fallback.

Catching Exception here can hide programming errors and silently force the slower path. Prefer expected exceptions (e.g., import/process/filesystem failures) and let unexpected exceptions surface.

#!/bin/bash
set -euo pipefail
sed -n '108,194p' ci/meson/build_config.py | nl -ba | rg -n 'except KeyboardInterrupt|except Exception'

Also applies to: 179-183

🤖 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/meson/build_config.py` around lines 144 - 148, The broad "except Exception
as e" in the native emcc launcher build fallback should be narrowed to only the
expected failure types so programming errors don't get swallowed: replace the
generic except in the try/except wrapping the native emcc launcher build (the
block that logs "[WASM] Native emcc launcher build failed; falling back to
Python wrapper: {e}") with a tuple of expected exceptions (e.g., ImportError,
OSError, FileNotFoundError, subprocess.CalledProcessError) and handle
KeyboardInterrupt/GeneratorExit by re-raising; apply the same change to the
other identical except block later (around the second fallback) so only
anticipated import/process/filesystem failures are caught and other exceptions
propagate.
🤖 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/meson/build_config.py`:
- Around line 108-110: The function _ensure_emcc_native_launcher currently
returns a tuple of two values; change it to return a small dataclass (e.g., name
it EmccLauncher or similar) with named fields (cc and cpp) to follow project
standards; update the function signature and return statements to construct and
return the dataclass, and update all call sites that destructure the tuple
(including the other related function/usage referenced nearby) to access .cc and
.cpp attributes instead of tuple indices or unpacking so callers remain clear
and type-safe.

---

Duplicate comments:
In `@ci/meson/build_config.py`:
- Around line 52-66: The WasmNativeEntries dataclass lacks runtime type
validation per repo standards; add the `@typechecked` decorator above the existing
`@dataclass`(slots=True) for the WasmNativeEntries class and ensure the
typechecked symbol is imported (e.g. from typeguard import typechecked) at the
top of ci/meson/build_config.py so that WasmNativeEntries(c, cpp, ar,
used_native_launcher) gets validated at runtime.
- Around line 144-148: The broad "except Exception as e" in the native emcc
launcher build fallback should be narrowed to only the expected failure types so
programming errors don't get swallowed: replace the generic except in the
try/except wrapping the native emcc launcher build (the block that logs "[WASM]
Native emcc launcher build failed; falling back to Python wrapper: {e}") with a
tuple of expected exceptions (e.g., ImportError, OSError, FileNotFoundError,
subprocess.CalledProcessError) and handle KeyboardInterrupt/GeneratorExit by
re-raising; apply the same change to the other identical except block later
(around the second fallback) so only anticipated import/process/filesystem
failures are caught and other exceptions propagate.
🪄 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: c580bb50-ae7c-42f5-ae62-306d122aaf38

📥 Commits

Reviewing files that changed from the base of the PR and between 78fcbe9 and 2e9a3e9.

📒 Files selected for processing (4)
  • ci/compiler/pio.py
  • ci/esbuild_frontend.py
  • ci/meson/build_config.py
  • ci/wasm_build.py
✅ Files skipped from review due to trivial changes (2)
  • ci/esbuild_frontend.py
  • ci/compiler/pio.py

Comment thread ci/meson/build_config.py
Comment on lines +108 to +110
def _ensure_emcc_native_launcher(
project_root: Path,
) -> tuple[Optional[str], Optional[str]]:

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 for multi-value launcher results.

_ensure_emcc_native_launcher() currently returns a tuple of two values. Please return a small dataclass (e.g., cc/cpp) to match project standards and improve call-site clarity.

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

Also applies to: 125-126

🤖 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/meson/build_config.py` around lines 108 - 110, The function
_ensure_emcc_native_launcher currently returns a tuple of two values; change it
to return a small dataclass (e.g., name it EmccLauncher or similar) with named
fields (cc and cpp) to follow project standards; update the function signature
and return statements to construct and return the dataclass, and update all call
sites that destructure the tuple (including the other related function/usage
referenced nearby) to access .cc and .cpp attributes instead of tuple indices or
unpacking so callers remain clear and type-safe.

@zackees
zackees merged commit b94ab3a into master May 18, 2026
19 of 20 checks passed
@zackees
zackees deleted the wasm-ctc-emcc-launcher-2485 branch May 18, 2026 23:17
zackees added a commit that referenced this pull request May 19, 2026
…auncher (#2489)

* perf(wasm): bump clang-tool-chain to 1.4.0 and wire ctc-emar native launcher

The 1.3.1 release added a native ctc-emar launcher (emtool family,
which also produces ctc-emranlib / ctc-emnm / ctc-emstrip aliases).
PR #2487 explicitly noted that the WASM cross-file's "ar" field could
not be wired to a native binary because no ctc-emar launcher existed
yet — that gap is now closed.

Bumps the pin to >=1.4.0 to also pick up:
  - 1.3.2 Linux libunwind injection fix
  - 1.3.3 macOS strip -lunwind fix in zccache shim
  - 1.4.0 PyPI entry-point rename (++ -> -cpp); does NOT affect us
    since no FastLED reference uses the renamed ++ entry points.

Changes:
  - pyproject.toml: clang-tool-chain>=1.2.9 -> >=1.4.0
  - ci/meson/build_config.py: _ensure_emcc_native_launcher now also
    returns the ctc-emar path; resolve_wasm_native_entries wires it
    into the WasmNativeEntries.ar slot, falling back to the Python
    clang-tool-chain-emar wrapper if the native binary is missing.
  - ci/wasm_build.py: log whether ctc-emar resolved or fell back.

Benchmark (single-iteration clean WASM build of examples/Blink):
  - Before (PR #2487, Python emar): 61.36s
  - After (native ctc-emar):         44.41s  (~28% reduction)

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

* refactor: replace _ensure_emcc_native_launcher tuple with EmccNativeLaunchers dataclass

Addresses CodeRabbit review on PR #2489. Project guideline is to return
dataclass structs instead of tuples or dicts for functions with multiple
return values; the previous 3-tuple return was positionally fragile and
caller-unfriendly.

No behavior change: same fields, same fallback semantics.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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.

Wire ctc-emcc native launcher into WASM cross-file (skip Python wrapper)

1 participant