Skip to content

Enforce zccache strict paths in Meson builds - #2385

Merged
zackees merged 2 commits into
masterfrom
fix-zccache-strict-paths
Apr 22, 2026
Merged

zackees merged 2 commits into
masterfrom
fix-zccache-strict-paths

Conversation

@zackees

@zackees zackees commented Apr 22, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Enable ZCCACHE_STRICT_PATHS=absolute for Meson/zccache builds so mixed separator or relative compiler paths fail locally instead of regressing silently.
  • Normalize Meson's private .p include paths in generated Ninja/compile database files after setup/reconfigure.
  • Disable Meson's implicit include directories for FastLED test/example targets and keep explicit canonical absolute forward-slash include roots.
  • Expand the Meson include-path regression test to cover zccache strict path-bearing flags, including -I, /I, -include, and related forms.

Issue #2376 status

The merged dependency updates make the original #pragma once failure stop reproducing on current master: bash test --cpp passed before this patch. However, running with zccache strict mode still failed on current master because Meson emitted private scratch includes like ci/meson/native\fastled.dll.p. This PR makes strict mode part of the Meson/zccache path and fixes the remaining path hygiene problem.

Fixes #2376.

Testing

  • uv run zccache --version -> zccache 1.3.7
  • Current master: bash test --cpp -> passed 302/302
  • Current master: ZCCACHE_STRICT_PATHS=absolute bash test --cpp --clean --force -> failed on zccache strict path rejection for Meson private .p include
  • This branch: ZCCACHE_STRICT_PATHS=absolute bash test --cpp --force --no-parallel -> passed 327/327
  • This branch: uv run pytest ci/tests/test_meson_include_paths.py -v -> passed
  • This branch: uv run test.py --examples Fire2023 --full --force with strict paths -> passed
  • git diff --check -> clean

Summary by CodeRabbit

  • Chores
    • Normalize compiler include paths so build artifacts use consistent forward-slash absolute paths across platforms
    • Enable strict path mode for the compiler cache to improve cache reliability
    • Disable automatic implicit include directories for several build targets to align include behavior with explicit settings
    • Expand and harden tests to validate include-flag parsing and strict-path compliance
    • Run normalization at key build steps and emit status messages when changes occur

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds Meson private-include path normalization (convert backslashes, resolve to absolute POSIX paths) for Meson-generated scratch -I*.p flags, sets ZCCACHE_STRICT_PATHS=absolute when zccache is active, and disables Meson implicit include directories on multiple targets. Tests updated to validate all path-bearing compiler flags.

Changes

Cohort / File(s) Summary
Build Path Normalization
ci/meson/build_config.py, ci/wasm_build.py
New normalization logic to rewrite Meson-generated scratch include flags (-I*.p) in build.ninja and compile_commands.json to absolute POSIX paths; invoked from wasm build helper and Meson setup fast-path.
zccache Environment
ci/meson/runner.py
Ensure ZCCACHE_STRICT_PATHS=absolute is set in the environment when starting a zccache session.
Meson Targets: implicit include suppression
ci/meson/native/meson.build, ci/meson/wasm/meson.build, examples/meson.build, tests/meson.build, tests/profile/meson.build
Added implicit_include_directories: false to multiple targets to prevent Meson from injecting implicit include dirs.
Meson include-root normalization
ci/meson/shared/meson.build
Normalize path_norm_root with explicit forward-slash replacement before constructing exported -I strings.
Tests: include-flag validation
ci/tests/test_meson_include_paths.py
Expanded test to tokenize and validate all path-bearing compiler flags (-I, -F, -isystem, -iquote, /I, attached forms), detect backslashes, non-absolute and dot components, and adjust failure grouping/messaging.
Test build args
tests/meson.build
Added path_norm_I_tests to cpp_args for runner and test builds so test-subdirectory headers are available.

Sequence Diagram

sequenceDiagram
    participant Build as Build Script
    participant Meson as Meson/Ninja
    participant Artifacts as build.ninja / compile_commands.json
    participant Normalizer as Normalization Handler
    participant zccache as zccache
    participant Compiler as Compiler

    Build->>Meson: setup_meson_build()
    Meson->>Artifacts: Emit build artifacts with private -I*.p flags
    Build->>Normalizer: _normalize_meson_private_paths(build_dir)
    Normalizer->>Artifacts: Read files, find -I*.p flags
    Normalizer->>Artifacts: Resolve non-absolute -> absolute (POSIX), convert '\' -> '/'
    Normalizer->>Artifacts: Write back only if changed
    Build->>zccache: Set ZCCACHE_STRICT_PATHS=absolute in env
    Compiler->>zccache: zccache validates/uses normalized paths in strict mode
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 Slashes hop from back to front,

Paths now neat, no build-time hunt,
Zccache strict and Meson kind,
Headers match — no #pragma blind,
A rabbit cheers: the build's aligned! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% 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 'Enforce zccache strict paths in Meson builds' directly describes the PR's primary objective: enabling ZCCACHE_STRICT_PATHS for Meson builds to catch path normalization issues early.
Linked Issues check ✅ Passed The PR addresses issue #2376 by normalizing Meson-generated include paths to POSIX format, disabling implicit include directories, and enforcing zccache strict paths to prevent header redefinition errors from mixed-separator paths.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing issue #2376: path normalization, zccache strict mode setup, include path testing, and disabling implicit include directories. 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-zccache-strict-paths

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

🧹 Nitpick comments (2)
ci/wasm_build.py (1)

72-77: Consider promoting _normalize_meson_private_include_paths to a public API.

This helper imports a private (_-prefixed) symbol from ci.meson.build_config. Cross-module consumption of a private name couples wasm_build.py to an internal implementation detail — if build_config.py ever renames or removes that function, this call site silently breaks.

Recommend renaming the target function to normalize_meson_private_include_paths (drop the underscore) in ci/meson/build_config.py and updating both call sites, making the contract explicit.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/wasm_build.py` around lines 72 - 77, The call site imports the private
helper _normalize_meson_private_include_paths; change the helper's name to
normalize_meson_private_include_paths in its module and update all call sites
(including the caller that currently calls
_normalize_meson_private_include_paths) to use
normalize_meson_private_include_paths so the API is explicit and
non-underscore-prefixed; ensure the renamed function signature and return
behavior remain the same and run tests to verify nothing else relies on the old
private name.
ci/tests/test_meson_include_paths.py (1)

52-55: Use explicit loops in changed Python helpers.

The new list comprehensions conflict with the repository Python guideline.

Proposed cleanup
 def _tokens_from_entry(entry: dict[str, object]) -> list[str]:
     raw_args = entry.get("arguments")
     if isinstance(raw_args, list):
-        return [str(arg) for arg in raw_args]
+        tokens: list[str] = []
+        for arg in raw_args:
+            tokens.append(str(arg))
+        return tokens
-    parts = [part for part in re.split(r"/+", path) if part]
+    parts: list[str] = []
+    for part in re.split(r"/+", path):
+        if part:
+            parts.append(part)
     if "." in parts or ".." in parts:
         return "dot path component"

As per coding guidelines, "Use explicit loops instead of list comprehensions for code clarity and debuggability".

Also applies to: 96-105

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/tests/test_meson_include_paths.py` around lines 52 - 55, Replace the list
comprehension in _tokens_from_entry with an explicit loop: when raw_args is a
list, create an empty list, iterate over raw_args, append str(arg) for each
element, and return that list (and ensure the function still returns an empty
list or None per existing behavior when raw_args is not a list); apply the same
change to the similar helper block around lines 96-105 so all list
comprehensions are converted to explicit for-loops while preserving types and
return values.
🤖 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/meson/build_config.py`:
- Around line 339-381: The current normalization logic for build_ninja and
compile_commands silently ignores OSErrors and JSON decode errors; update the
functions that use build_ninja, compile_commands and _normalize_text (and any
caller relying on changed_any) to fail fast instead: when build_ninja.read_text
or write_text raises OSError, raise a descriptive exception (include the
filename and operation) instead of passing; when
compile_commands.read_text/json.loads raises OSError or json.JSONDecodeError,
raise a descriptive exception rather than setting data=None; when writing back
normalized JSON fails, raise a descriptive error; ensure the function's return
contract is updated so callers receive an explicit error state (or propagate the
exception) so upstream code cannot continue with unnormalized paths.

In `@ci/tests/test_meson_include_paths.py`:
- Around line 49-84: The extractor misses attached forms of several strict path
flags; update _ATTACHED_PATH_PREFIXES (or build an equivalent list) so it
includes attached prefixes for every path-bearing flag checked by zccache strict
mode (e.g., add '-isystem', '-iquote', '-include-pch' alongside '-I', '-F',
'/I'), and keep the existing detection logic in _extract_strict_path_flags
(which uses token.startswith(prefix) and token[len(prefix):]) so tokens like
'-isystemC:/bad' or '-include-pchC:/bad' are recognized and appended to out;
ensure changes reference the symbols _ATTACHED_PATH_PREFIXES,
_SEPARATE_PATH_FLAGS, _extract_strict_path_flags, and _tokens_from_entry.

---

Nitpick comments:
In `@ci/tests/test_meson_include_paths.py`:
- Around line 52-55: Replace the list comprehension in _tokens_from_entry with
an explicit loop: when raw_args is a list, create an empty list, iterate over
raw_args, append str(arg) for each element, and return that list (and ensure the
function still returns an empty list or None per existing behavior when raw_args
is not a list); apply the same change to the similar helper block around lines
96-105 so all list comprehensions are converted to explicit for-loops while
preserving types and return values.

In `@ci/wasm_build.py`:
- Around line 72-77: The call site imports the private helper
_normalize_meson_private_include_paths; change the helper's name to
normalize_meson_private_include_paths in its module and update all call sites
(including the caller that currently calls
_normalize_meson_private_include_paths) to use
normalize_meson_private_include_paths so the API is explicit and
non-underscore-prefixed; ensure the renamed function signature and return
behavior remain the same and run tests to verify nothing else relies on the old
private name.
🪄 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: cdab1beb-84c7-4b21-afba-fab8f46bf41f

📥 Commits

Reviewing files that changed from the base of the PR and between 18d6481 and 1fe96dd.

📒 Files selected for processing (10)
  • ci/meson/build_config.py
  • ci/meson/native/meson.build
  • ci/meson/runner.py
  • ci/meson/shared/meson.build
  • ci/meson/wasm/meson.build
  • ci/tests/test_meson_include_paths.py
  • ci/wasm_build.py
  • examples/meson.build
  • tests/meson.build
  • tests/profile/meson.build

Comment thread ci/meson/build_config.py Resolved
Comment thread ci/tests/test_meson_include_paths.py Resolved
@zackees

zackees commented Apr 22, 2026

Copy link
Copy Markdown
Member Author

Addressed the CodeRabbit review comments in 0789152d3f:

  • normalize_meson_private_include_paths() now raises descriptive RuntimeErrors for build artifact read/write/parse failures instead of silently continuing.
  • The strict path extractor now covers attached forms for all tracked path-bearing flags, including -isystem..., -iquote..., -include-pch..., -imacros..., etc.
  • Replaced the new list comprehensions with explicit loops in the changed test helpers.
  • Promoted the Meson private path normalizer to a public helper and updated the WASM caller.

Verified locally:

  • ZCCACHE_STRICT_PATHS=absolute bash test --cpp --force --no-parallel -> passed 302/302
  • uv run pytest ci/tests/test_meson_include_paths.py -v -> passed 2/2
  • git diff --check -> clean

@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 the current code and only fix it if needed.

Inline comments:
In `@ci/meson/build_config.py`:
- Around line 313-395: normalize_meson_private_include_paths currently only
processes compile_commands.json "command" strings and uses
_MESON_PRIVATE_INCLUDE_RE which requires literal quotes, so unquoted -I*.p
tokens and the "arguments" array form are skipped; update
_MESON_PRIVATE_INCLUDE_RE to match both quoted and unquoted -I...*.p tokens
(make the surrounding quotes optional and allow no-whitespace path capture) and
extend normalize_meson_private_include_paths to also handle entries with an
"arguments" list by iterating over each element, normalizing any string elements
via _normalize_text (same logic as used for "command"), updating the list when
changed, and writing the modified JSON back (preserving the current error
handling and changed_any behavior), using the existing helpers _replacement and
_normalize_text.
🪄 Autofix (Beta)

✅ Autofix completed


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b3af38ae-3f71-4e38-98cf-656b96670f25

📥 Commits

Reviewing files that changed from the base of the PR and between 1fe96dd and 0789152.

📒 Files selected for processing (3)
  • ci/meson/build_config.py
  • ci/tests/test_meson_include_paths.py
  • ci/wasm_build.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • ci/wasm_build.py

Comment thread ci/meson/build_config.py
Comment on lines +313 to +395
_MESON_PRIVATE_INCLUDE_RE = re.compile(r'("-I)([^"]+\.p)(")')


def _is_forward_slash_absolute(path: str) -> bool:
return path.startswith("/") or re.match(r"^[A-Za-z]:/", path) is not None


def normalize_meson_private_include_paths(build_dir: Path) -> bool:
"""Normalize Meson's private ``-I*.p`` scratch includes for zccache strict mode."""

changed_any = False

def _replacement(match: re.Match[str]) -> str:
prefix, raw_path, suffix = match.groups()
normalized = raw_path.replace("\\", "/")
if _is_forward_slash_absolute(normalized):
absolute = normalized
else:
absolute = (build_dir / normalized).resolve().as_posix()
if absolute == raw_path:
return match.group(0)
return f"{prefix}{absolute}{suffix}"

def _normalize_text(content: str) -> str:
return _MESON_PRIVATE_INCLUDE_RE.sub(_replacement, content)

build_ninja = build_dir / "build.ninja"
if build_ninja.exists():
try:
content = build_ninja.read_text(encoding="utf-8")
except OSError as e:
raise RuntimeError(
f"Could not read {build_ninja} while normalizing Meson strict paths"
) from e
else:
normalized = _normalize_text(content)
if normalized != content:
try:
build_ninja.write_text(normalized, encoding="utf-8")
changed_any = True
except OSError as e:
raise RuntimeError(
f"Could not write {build_ninja} after normalizing Meson strict paths"
) from e

compile_commands = build_dir / "compile_commands.json"
if compile_commands.exists():
try:
data = json.loads(compile_commands.read_text(encoding="utf-8"))
except OSError as e:
raise RuntimeError(
f"Could not read {compile_commands} while normalizing Meson strict paths"
) from e
except json.JSONDecodeError as e:
raise RuntimeError(
f"Could not parse {compile_commands} while normalizing Meson strict paths"
) from e
if isinstance(data, list):
changed_json = False
for entry in data:
if not isinstance(entry, dict):
continue
entry_dict = cast(dict[str, object], entry)
command = entry_dict.get("command")
if not isinstance(command, str):
continue
normalized = _normalize_text(command)
if normalized != command:
entry_dict["command"] = normalized
changed_json = True
if changed_json:
try:
compile_commands.write_text(
json.dumps(data, indent=2) + "\n",
encoding="utf-8",
)
changed_any = True
except OSError as e:
raise RuntimeError(
f"Could not write {compile_commands} after normalizing Meson strict paths"
) from e

return changed_any

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether any local Meson-generated compile DBs in this tree use the
# "arguments" array form or carry unquoted -I*.p tokens that the current
# regex would miss.
fd -t f compile_commands.json .build 2>/dev/null | while read -r f; do
  echo "=== $f ==="
  python3 - "$f" <<'PY'
import json, re, sys
p = sys.argv[1]
with open(p, encoding="utf-8") as fh:
    data = json.load(fh)
fmt_args = sum(1 for e in data if isinstance(e, dict) and isinstance(e.get("arguments"), list))
fmt_cmd  = sum(1 for e in data if isinstance(e, dict) and isinstance(e.get("command"), str))
print(f"entries: {len(data)}  arguments-form: {fmt_args}  command-form: {fmt_cmd}")
unquoted_p = re.compile(r'(?<!["\'])(-I[^\s"\']+\.p)')
samples = []
for e in data:
    cmd = e.get("command") if isinstance(e, dict) else None
    if isinstance(cmd, str):
        for m in unquoted_p.findall(cmd):
            samples.append(m)
            if len(samples) >= 5: break
    if len(samples) >= 5: break
print("unquoted -I*.p samples:", samples)
PY
done

# Also sanity-check build.ninja for unquoted -I*.p occurrences.
fd -t f build.ninja .build 2>/dev/null | while read -r f; do
  echo "=== $f ==="
  rg -nP '(?<!["\x27])-I[^\s"\x27]+\.p' "$f" | head -n 5
done

Repository: FastLED/FastLED

Length of output: 41


🏁 Script executed:

# Find Meson configuration files and build-related tests
fd -t f -e meson.build -e meson_options.txt . 2>/dev/null | head -20

Repository: FastLED/FastLED

Length of output: 41


🏁 Script executed:

# Search for references to compile_commands.json in the codebase
rg -l 'compile_commands' --type py --type json --type yaml

Repository: FastLED/FastLED

Length of output: 257


🏁 Script executed:

# Look for test files related to the normalization function
fd -t f -name '*test*' . | rg -i 'meson|normal'

Repository: FastLED/FastLED

Length of output: 289


🏁 Script executed:

# Search for handling of "arguments" array in compile_commands context
rg -i 'arguments' --type py | grep -i 'compile\|command'

Repository: FastLED/FastLED

Length of output: 4107


🏁 Script executed:

# Check if there are any existing tests for normalize_meson_private_include_paths
rg -A 5 'normalize_meson_private_include_paths' --type py

Repository: FastLED/FastLED

Length of output: 1705


🏁 Script executed:

cat -n ci/tests/test_meson_include_paths.py

Repository: FastLED/FastLED

Length of output: 8496


🏁 Script executed:

# Also check the actual code location more carefully
sed -n '313,395p' ci/meson/build_config.py | cat -n

Repository: FastLED/FastLED

Length of output: 3900


🏁 Script executed:

# Check if there are any references to "arguments" in compile_commands context
rg -B 3 -A 3 '"arguments"' ci/util/fbuild_compiledb.py

Repository: FastLED/FastLED

Length of output: 41


Normalizer incompletely handles compile_commands.json "arguments" form and quoted-only -I*.p flags.

The test suite (ci/tests/test_meson_include_paths.py) explicitly handles both "command" and "arguments" forms in compile_commands.json entries (see _tokens_from_entry lines 64–74 and the test_extract_strict_path_flags_includes_attached_forms test), but the normalizer only inspects the "command" field. When Meson emits the "arguments" array form, the normalizer silently skips the entry since entry_dict.get("command") returns None, while the test framework would later detect any path violations and fail. Additionally, the regex r'("-I)([^"]+\.p)(")' requires literal quote wrapping, so unquoted -I*.p tokens in build.ninja or command strings are not matched.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/meson/build_config.py` around lines 313 - 395,
normalize_meson_private_include_paths currently only processes
compile_commands.json "command" strings and uses _MESON_PRIVATE_INCLUDE_RE which
requires literal quotes, so unquoted -I*.p tokens and the "arguments" array form
are skipped; update _MESON_PRIVATE_INCLUDE_RE to match both quoted and unquoted
-I...*.p tokens (make the surrounding quotes optional and allow no-whitespace
path capture) and extend normalize_meson_private_include_paths to also handle
entries with an "arguments" list by iterating over each element, normalizing any
string elements via _normalize_text (same logic as used for "command"), updating
the list when changed, and writing the modified JSON back (preserving the
current error handling and changed_any behavior), using the existing helpers
_replacement and _normalize_text.

@zackees
zackees merged commit 6d84315 into master Apr 22, 2026
64 of 77 checks passed
@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

Fixes Applied Successfully

Fixed 1 file(s) based on 1 unresolved review comment.

Files modified:

  • ci/meson/build_config.py

Commit: 09ab26dddbeaca833822ffd9784c81912083285c

The changes have been pushed to the fix-zccache-strict-paths branch.

Time taken: 2m 9s

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.

Test build: #pragma once fails for fl/cled_controller.h / fl/gfx/colorutils.h under PCH on Windows (clang)

1 participant