Repository navigation
feat(ci): backend flag-drift detector for fbuild <-> PlatformIO (refs #2410) - #2801
Conversation
…2410) Prototype script ci/check_backend_flag_drift.py that drives both backends against a single board + sketch, captures each backend's build_info JSON, normalizes them into a common shape (cc_flags / cxx_flags / defines / includes with path-specific tokens stripped) and diffs. Exit codes: 0 - normalized flags agree -> no drift 1 - drift detected (structured report on stdout) 2 - hard failure (compile failed, missing build_info, etc) Run against teensy41 build_infos already on disk (fbuild's top-level build_info_teensy41.json and PIO's .build/pio/teensy41/build_info_Blink.json) the diff cleanly surfaces the kind of mismatch #2410 was concerned about: [cc_flags] drift: + (fbuild only) -Os + (fbuild only) -flto=auto - (pio only) -O2 [cxx_flags] drift: + (fbuild only) -flto=auto - (pio only) -fno-exceptions - (pio only) -fno-rtti - (pio only) -Wno-psabi - (pio only) -fpermissive [defines] drift: + (fbuild only) ARDUINO=10819 - (pio only) ARDUINO=10805 + (fbuild only) TEENSYDUINO=159 - (pio only) TEENSYDUINO=160 7 unit tests covering normalization, include-path canonicalization, PLATFORMIO version-stamp collapsing, fbuild combined-flag splitting, and end-to-end drift detection. No CI workflow is wired up yet -- that's a deliberate follow-up so the script can prove itself locally first. Follow-ups (tracked in #2410): - Matrix over every shipped board (esp32*, teensy*, avr, rp2040, ...) - Wire a CI job that posts drift as a check annotation, then promote to a required gate once the matrix is stable. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a CLI that compiles a board with fbuild and PlatformIO (or reuses snapshots), normalizes both backends' flags into comparable sets (cc/cxx/defines/includes), computes set differences, prints a structured report, and exits 0 (clean), 1 (drift), or 2 (failure). Includes unit and end-to-end tests for normalization and reporting. ChangesBackend compiler-flag drift detection
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
ci/tests/test_check_backend_flag_drift.py (1)
27-27: 💤 Low valueConsider adding a descriptive assertion message.
The assertion provides fail-fast behavior, but a descriptive error message would improve debuggability when the script file is missing or malformed.
💡 Proposed improvement
- assert spec is not None and spec.loader is not None + assert spec is not None and spec.loader is not None, ( + f"Failed to load {_SCRIPT_PATH}: spec or loader is None" + )🤖 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_check_backend_flag_drift.py` at line 27, The assertion "assert spec is not None and spec.loader is not None" lacks a descriptive message; update it to include a clear failure message describing the expected module spec and loader (e.g., mention the target script path or module name and that it was missing or malformed) so test failures show why spec or spec.loader was None; locate the assertion in test_check_backend_flag_drift.py and modify the assert to include that message referencing spec and spec.loader.ci/check_backend_flag_drift.py (3)
91-113: ⚡ Quick winAdd the repo-standard
@typecheckeddecorator to both dataclasses.
NormalizedFlagsandDriftReportcurrently skip the runtime validation required for dataclass models in this repo, so bad field types will be accepted until much later in the drift pipeline.As per coding guidelines, "Use
@typecheckeddecorator with@dataclassfor 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/check_backend_flag_drift.py` around lines 91 - 113, The dataclasses NormalizedFlags and DriftReport are missing the repo-standard `@typechecked` runtime type validation; add the `@typechecked` decorator directly above both class definitions (for NormalizedFlags and DriftReport) so their fields are validated at runtime, and ensure you import typechecked where decorators are aggregated in this module if not already present.
203-221: ⚡ Quick winReturn a small dataclass here instead of a positional 3-tuple.
The current return contract is order-dependent only, which makes the caller easy to misuse and violates the repository rule for multi-value returns.
As per coding guidelines, "Return dataclass structs instead of tuples or dicts for functions with multiple return values".
🤖 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/check_backend_flag_drift.py` around lines 203 - 221, The function _split_fbuild_combined_flags currently returns a positional 3-tuple (pure, defines, includes); replace that with a small dataclass (e.g., name SplitFlags or FBuildFlags) containing typed fields pure: list[str], defines: list[str], includes: list[str], update the function signature and return type to return that dataclass instance instead of a tuple, and update all callers to access fields by name (instance.pure, instance.defines, instance.includes); ensure imports for dataclass/typing are added and adjust any type-checks or destructuring to use the new dataclass.
41-48: ⚡ Quick winUse
subprocess.list2cmdline()for the logged command string.
' '.join(cmd)loses quoting/escaping, so paths or examples with spaces are printed as a different command than the one actually executed.Suggested change
+import subprocess ... - print(f"\n>>> Compiling [{backend}]: {' '.join(cmd)}", flush=True) + print( + f"\n>>> Compiling [{backend}]: {subprocess.list2cmdline(cmd)}", + flush=True, + )As per coding guidelines, "Use subprocess.list2cmdline() for all command line construction instead of string join".
Also applies to: 397-408
🤖 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/check_backend_flag_drift.py` around lines 41 - 48, The code logs executed command lists using "' '.join(cmd)" which loses proper quoting/escaping; import subprocess and replace those joins with subprocess.list2cmdline(cmd) wherever commands are turned into strings for logging (e.g., inside RunningProcess usage and any function/variable that constructs or logs a `cmd` list around the sections referenced and the block at lines ~397-408). Update the top imports to include subprocess and ensure every logged command string uses subprocess.list2cmdline(cmd) instead of manual joining so paths/arguments with spaces are preserved.
🤖 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/check_backend_flag_drift.py`:
- Around line 130-137: The current _should_ignore_flag treats only standalone
path flags themselves as noise, but the operand that follows (e.g., header.h
after -include) must also be skipped during normalization to avoid false drift;
update the token-processing loop that builds cc_clean/cxx_clean (the code that
calls _should_ignore_flag) so that when it sees a flag in _STANDALONE_PATH_FLAGS
it consumes and discards the next argv token as well, while preserving the
existing startswith checks against _PATH_LIKE_FLAG_PREFIXES; apply the same fix
to the other occurrence around the block referenced (lines ~279-284) to ensure
both normalization sites skip the operand after standalone path flags.
- Around line 237-245: The code currently falls back to the first top-level
record when board is missing from raw (inside the "if board not in raw:"
branch), which can silently accept the wrong snapshot; replace that fallback
with a fail-fast ValueError that always raises when board is absent, including
the requested board name and the actual top-level keys from raw in the error
message (i.e., remove the len(raw)==1 path and raise with f"{backend} build_info
missing requested board '{board}'; found top-level keys: {sorted(raw)}").
- Around line 515-549: Wrap the file reads and JSON parsing for fbuild_info and
pio_info (where fbuild_bi_path.read_text() / json.loads(...) are called) in
try/except that catches KeyboardInterrupt first and then other exceptions,
printing the existing error message to stderr and returning exit code 2 on
failure; likewise ensure normalize_build_info calls remain in their try/except
but follow the same ordering (KeyboardInterrupt first) so any
unreadable/malformed build_info or normalization error maps to return 2;
references: fbuild_bi_path, pio_bi_path, fbuild_info, pio_info,
normalize_build_info, _find_build_info, _run_compile.
In `@ci/tests/test_check_backend_flag_drift.py`:
- Around line 23-31: Add an explicit return type to the _load_script_module
function by annotating it to return types.ModuleType (e.g. def
_load_script_module() -> ModuleType:), and ensure you import ModuleType from the
types module (from types import ModuleType) at the top of the file so the
annotation resolves; keep the function body unchanged and only add the import
and the return type annotation.
---
Nitpick comments:
In `@ci/check_backend_flag_drift.py`:
- Around line 91-113: The dataclasses NormalizedFlags and DriftReport are
missing the repo-standard `@typechecked` runtime type validation; add the
`@typechecked` decorator directly above both class definitions (for
NormalizedFlags and DriftReport) so their fields are validated at runtime, and
ensure you import typechecked where decorators are aggregated in this module if
not already present.
- Around line 203-221: The function _split_fbuild_combined_flags currently
returns a positional 3-tuple (pure, defines, includes); replace that with a
small dataclass (e.g., name SplitFlags or FBuildFlags) containing typed fields
pure: list[str], defines: list[str], includes: list[str], update the function
signature and return type to return that dataclass instance instead of a tuple,
and update all callers to access fields by name (instance.pure,
instance.defines, instance.includes); ensure imports for dataclass/typing are
added and adjust any type-checks or destructuring to use the new dataclass.
- Around line 41-48: The code logs executed command lists using "' '.join(cmd)"
which loses proper quoting/escaping; import subprocess and replace those joins
with subprocess.list2cmdline(cmd) wherever commands are turned into strings for
logging (e.g., inside RunningProcess usage and any function/variable that
constructs or logs a `cmd` list around the sections referenced and the block at
lines ~397-408). Update the top imports to include subprocess and ensure every
logged command string uses subprocess.list2cmdline(cmd) instead of manual
joining so paths/arguments with spaces are preserved.
In `@ci/tests/test_check_backend_flag_drift.py`:
- Line 27: The assertion "assert spec is not None and spec.loader is not None"
lacks a descriptive message; update it to include a clear failure message
describing the expected module spec and loader (e.g., mention the target script
path or module name and that it was missing or malformed) so test failures show
why spec or spec.loader was None; locate the assertion in
test_check_backend_flag_drift.py and modify the assert to include that message
referencing spec and spec.loader.
🪄 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: fb5c553d-654b-42d9-9151-595f0c66058d
📒 Files selected for processing (2)
ci/check_backend_flag_drift.pyci/tests/test_check_backend_flag_drift.py
- normalize_build_info: fail fast with descriptive ValueError when the requested board key is absent (no silent fallback to first top-level record); add a unit test guarding the new behavior. - _clean_flags: new normalization helper that drops both standalone path flags (-include, -o, -c, -imacros, -MMD, -MD, -MP) AND the argv operand that follows them. Also consumes operands for bare -MF/-MT/-MQ (the glued -MFfile.d form is still caught by the existing _PATH_LIKE_FLAG_PREFIXES check). Prevents pure path noise like header.h / main.d from masquerading as drift signal. Added test_clean_flags_drops_operand_after_standalone_path_flag. - _split_fbuild_combined_flags: return a typed SplitFlags dataclass instead of a 3-tuple (per repo "no tuple returns" convention). - NormalizedFlags / DriftReport / SplitFlags: add @TypeChecked decorator for runtime validation (per repo dataclass convention). - main: wrap json.loads(read_text()) for both fbuild and pio snapshots in try/except (KeyboardInterrupt first, per project policy), mapping OSError / JSONDecodeError to documented exit code 2 instead of an uncaught traceback. - _run_compile: log the command with subprocess.list2cmdline() so paths/examples with spaces are printed exactly as executed. - test helper: add ModuleType return annotation on _load_script_module() and a descriptive failure message on the spec/loader assertion. No behavioral change to clean-vs-drift verdicts on the teensy41 snapshot; lint and the 9-test unit suite both pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
@coderabbitai — addressed all 4 nitpicks from the review along with the 4 actionable comments in commit 2b871cc:
Lint ( |
|
Tip For best results, initiate chat on the files or code changes.
Great work, and glad the 9-test suite + lint are green. 🐇 |
…2410 / #2413) (#3155) B4 of meta #3122. Closes the canonical-board-coverage gap on #2410 by wiring the existing ci/check_backend_flag_drift.py (shipped in #2801, refs #2410) into a dedicated GitHub Actions workflow for **teensy40** — the canonical broken case cited in #2413 ("fbuild silently drifted from PlatformIO and broke Teensy 4.x for 50+ consecutive master CI runs ... the `.progmem` section-type conflict in `colorpalettes.h:23`"). Workflow contract: - Triggers on pushes to master + PRs that touch the flag-drift script, the compile orchestrator, T4 platform code, or the workflow itself. - Drives both backends to build `Blink` for teensy40, captures build_info_*.json from each, runs the drift script. - Writes a report to .build/drift/teensy40_drift.txt, surfaces it in the workflow summary (so reviewers see drift inline on the PR), and uploads as an artifact (30-day retention) for later analysis. Drift gating: - `continue-on-error: true` for now — drift surfaces visibly but does not block merges. The right next step is to gate merges on drift *after* a clean-slate run confirms the existing flag set is the intended one; today's PR makes drift legible, not mandatory. Reasoning behind the single-board scope: - Doing all 5+ envs at once would obscure which board the drift came from in the summary view. Starting with teensy40 closes the original reported bug; future PRs can add per-board workflows (or refactor to a matrix) once the contract is proven. Validation: - `bash lint` — clean (Python pipeline, ESLint, TypeScript, C++, meson, platformio-internal-usage all pass). - Workflow won't actually run until the PR is open and master is hit; first execution will populate the artifact + summary that prove the contract end-to-end. Refs #3122 B4, #2410, #2413, #2801 (script).
Summary
Prototype script
ci/check_backend_flag_drift.pythat catches the class of bug described in #2410 — fbuild silently drifting from PlatformIO and breaking a single board (Teensy 4.x) for 50+ consecutive master CI runs while teensy30/31/LC stayed green on PIO and masked the failure.What this PR ships (single-board prototype, teensy41-validated):
ci/check_backend_flag_drift.py— drivesci/ci-compile.pyonce with--fbuildand once with--pioagainst the same board + sketch (default:Blink), snapshots each backend'sbuild_info_<example>.json, normalizes both into a common (cc_flags, cxx_flags, defines, includes) shape with path-specific tokens stripped, and diffs.0= clean,1= drift detected,2= hard failure (compile broke / missing build_info).--board <name>(required),--example <name>(default Blink),--timeout <secs>,--skip-build,--project-root <path>.ci/tests/test_check_backend_flag_drift.py— 7 unit tests covering normalization, include-path canonicalization across the fbuild vs PIO cache roots, PLATFORMIO version-stamp collapsing, fbuild's combined-D/-Isplitting, and end-to-end drift detection.Sample output — running the diff core against
build_info_teensy41.json(fbuild) and.build/pio/teensy41/build_info_Blink.json(PIO) already on disk in this repo surfaces real, actionable drift that matches the #2410 narrative:The
-flto=autoonly-in-fbuild plus-std=gnu11only-in-fbuild are exactly the kind of mismatch that can produce confusing late-link errors like the.progmemsection-type conflict the issue references.Deferred to follow-up PRs (out of scope here, tracked in #2410)
esp32*,teensy*family,avr,rp2040, ...). The script is already board-parametric (--board <name>), so a small wrapper that fans out acrossci/boards.pyis the natural next step..github/workflows/check_flag_drift.ymlthat runs this on PRs (and master) as a non-required check first, posts the drift as an annotation, then flips to a required gate once the matrix is stable. Doing the CI wiring in the same PR risked gating master on a brand-new script before it had a chance to prove itself, so it's deliberately split.Why not extract flags from
pio run -v?Both fbuild and PIO already emit fully-structured
build_info_*.json(fbuild dumps top-level forbash compileruns; PIO writes one viapio project metadata --json-outputfromci.compiler.build_config.generate_build_info_json_from_existing_build). Parsing the JSON is robust, while parsingpio run -vtext would be brittle across PIO versions. This PR uses the JSON path.Test plan
bash lintcleanuv run pytest ci/tests/test_check_backend_flag_drift.py -v-> 7/7 PASSEDuv run python ci/check_backend_flag_drift.py --board teensy41after merge, which will fan out to two real compiles (each takes a few minutes; out of scope for the loop run that authored this PR)refs #2410
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
--skip-buildwill attempt to reuse an existing snapshot; exits with failure if none is available.Tests