ci, iwyu: skip subtrees in compilation database #36252

Manually merged
ryanofsky merged 1 commit from pr/iwyusub into master 2026-11-07 14:01:31 +00:00 AGit
ryanofsky commented 2026-09-14 15:45:51 +00:00 (Migrated from github.com)

Problem: The IWYU CI job analyzes src/ipc/libmultiprocess/ even though its results are thrown away. Every run prints IWYU suggestions for 14 libmultiprocess files in the non-enforced pass, applies them, and then reverts them with the git restore from #36112. The suggestions also disagree with what libmultiprocess's own IWYU CI reports (it runs with -Xiwyu --error and passes), because the two jobs use different IWYU versions and mapping files. libmultiprocess is the only subtree in this situation; leveldb, crc32c, minisketch and secp256k1 are already excluded from compile_commands.json with EXPORT_COMPILE_COMMANDS OFF. #35361 reported this output and said IWYU shouldn't be running on subtrees.

Solution: Filter SHARED_EXCLUDED_SUBTREES (from test/lint/lint_ignore_dirs.py) out of compile_commands.json at the start of the IWYU section of ci/test/03_test_script.sh, so subtree sources are neither analyzed nor edited. This is done in the CI script rather than in cmake so that only IWYU is affected: clang-tidy keeps running on libmultiprocess, and no list of subtree targets has to be maintained in cmake/libmultiprocess.cmake (that approach broke -DBUILD_TESTS=OFF in #35418 and was reverted in #35523). The change is three lines in ci/test/03_test_script.sh; the rest of the diff is comments.

Testing note: You can confirm this works by checking the IWYU CI logs and confirming that output like /home/runner/work/_temp/src/ipc/libmultiprocess/src/mp/gen.cpp should add these lines: no longer appears.

**Problem:** The IWYU CI job analyzes `src/ipc/libmultiprocess/` even though its results are thrown away. Every run prints IWYU suggestions for 14 libmultiprocess files in the non-enforced pass, applies them, and then reverts them with the `git restore` from #36112. The suggestions also disagree with what libmultiprocess's own IWYU CI reports (it runs with `-Xiwyu --error` and passes), because the two jobs use different IWYU versions and mapping files. libmultiprocess is the only subtree in this situation; leveldb, crc32c, minisketch and secp256k1 are already excluded from `compile_commands.json` with `EXPORT_COMPILE_COMMANDS OFF`. #35361 reported this output and said IWYU shouldn't be running on subtrees. **Solution:** Filter `SHARED_EXCLUDED_SUBTREES` (from `test/lint/lint_ignore_dirs.py`) out of `compile_commands.json` at the start of the IWYU section of `ci/test/03_test_script.sh`, so subtree sources are neither analyzed nor edited. This is done in the CI script rather than in cmake so that only IWYU is affected: clang-tidy keeps running on libmultiprocess, and no list of subtree targets has to be maintained in `cmake/libmultiprocess.cmake` (that approach broke `-DBUILD_TESTS=OFF` in #35418 and was reverted in #35523). The change is three lines in `ci/test/03_test_script.sh`; the rest of the diff is comments. **Testing note:** You can confirm this works by checking the IWYU CI logs and confirming that output like `/home/runner/work/_temp/src/ipc/libmultiprocess/src/mp/gen.cpp should add these lines:` no longer appears.
DrahtBot commented 2026-09-14 15:46:09 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK David-Uka, hebasto
Concept ACK BrandonOdiwuor

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

No conflicts as of last run.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36252 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36252.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36252#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [David-Uka](https://github.com/bitcoin/bitcoin/pull/36252#issuecomment-5796335248), [hebasto](https://github.com/bitcoin/bitcoin/pull/36252#pullrequestreview-5318654306) | | Concept ACK | [BrandonOdiwuor](https://github.com/bitcoin/bitcoin/pull/36252#pullrequestreview-5455610061) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts No conflicts as of last run. <!--5faf32d7da4f0f540f40219e4f7537a3-->
hebasto commented 2026-09-14 15:57:38 +00:00 (Migrated from github.com)
Why not https://github.com/bitcoin/bitcoin/pull/35418#pullrequestreview-4428862711?
ryanofsky commented 2026-09-14 17:06:50 +00:00 (Migrated from github.com)

Why not #35418 (review)?

I think excluding all subtrees from IWYU is better than individually setting in CMAKE_EXPORT_COMPILE_COMMANDS inside individual subtrees because:

  • It directly addresses the fact that IWYU's instability makes it inappropriate to run on subtrees. IWYU's output changes depending on compiler version, standard libary version, IWYU version, and local mappings so it's not realistic to expect subtrees will be able to pass IWYU checks in bitcoin core, and there's not much reason to care if they do, since benefits of IWYU are faster compile times and more consistent code style, not anything safety related.

  • This approach works for all subtrees, instead of requiring every individual subtree to hardcode cmake options.

  • This approach only disables IWYU, and does not disable all other tools or checks that use the compilation database. I don't think that turning off clang-tidy, bitcoin-tidy, and other tools for all subtrees is a good idea just to prevent IWYU noise, when IWYU noise can be prevented by just running it on the right files.

> Why not [#35418 (review)](https://github.com/bitcoin/bitcoin/pull/35418#pullrequestreview-4428862711)? I think excluding all subtrees from IWYU is better than individually setting in CMAKE_EXPORT_COMPILE_COMMANDS inside individual subtrees because: - It directly addresses the fact that IWYU's instability makes it inappropriate to run on subtrees. IWYU's output changes depending on compiler version, standard libary version, IWYU version, and local mappings so it's not realistic to expect subtrees will be able to pass IWYU checks in bitcoin core, and there's not much reason to care if they do, since benefits of IWYU are faster compile times and more consistent code style, not anything safety related. - This approach works for all subtrees, instead of requiring every individual subtree to hardcode cmake options. - This approach only disables IWYU, and does not disable all other tools or checks that use the compilation database. I don't think that turning off clang-tidy, bitcoin-tidy, and other tools for all subtrees is a good idea just to prevent IWYU noise, when IWYU noise can be prevented by just running it on the right files.
maflcko (Migrated from github.com) reviewed 2026-09-17 15:44:47 +00:00
maflcko (Migrated from github.com) commented 2026-09-17 15:44:47 +00:00

Seems fine, but All of those python3 -c '...' inside bash are fine, but seem a bit hacky.

At some point we can use vanilla Python and drop the jq dep. Something like:

completely untested draft diff
 ci/test/00_setup_env_native_iwyu.sh |   2 +-
 ci/test/03_test_script.sh           |  44 +------------
 ci/test/run-iwyu.py                 | 125 ++++++++++++++++++++++++++++++++++++
 3 files changed, 127 insertions(+), 44 deletions(-)

diff --git a/ci/test/00_setup_env_native_iwyu.sh b/ci/test/00_setup_env_native_iwyu.sh
index 20240f6..9ed2a09 100755
--- a/ci/test/00_setup_env_native_iwyu.sh
+++ b/ci/test/00_setup_env_native_iwyu.sh
@@ -12,3 +12,3 @@ export IWYU_LLVM_V="23"
 export APT_LLVM_V="${IWYU_LLVM_V}"
-export PACKAGES="clang-${IWYU_LLVM_V} clang-format-${IWYU_LLVM_V} libclang-${IWYU_LLVM_V}-dev llvm-${IWYU_LLVM_V}-dev jq libboost-dev libzmq3-dev systemtap-sdt-dev qt6-base-dev qt6-tools-dev qt6-l10n-tools libqrencode-dev libsqlite3-dev libcapnp-dev capnproto"
+export PACKAGES="clang-${IWYU_LLVM_V} clang-format-${IWYU_LLVM_V} libclang-${IWYU_LLVM_V}-dev llvm-${IWYU_LLVM_V}-dev libboost-dev libzmq3-dev systemtap-sdt-dev qt6-base-dev qt6-tools-dev qt6-l10n-tools libqrencode-dev libsqlite3-dev libcapnp-dev capnproto"
 export NO_DEPENDS=1
diff --git a/ci/test/03_test_script.sh b/ci/test/03_test_script.sh
index 5793656..187834b 100755
--- a/ci/test/03_test_script.sh
+++ b/ci/test/03_test_script.sh
@@ -236,45 +236,3 @@ fi
 if [[ "${RUN_IWYU}" == true ]]; then
-  # TODO: Consider enforcing IWYU across the entire codebase.
-  FILES_WITH_ENFORCED_IWYU='/src/((bench|common|consensus|crypto|index|init|kernel|primitives|rpc|script|univalue/(lib|test)|util|zmq)/.*|node/(blockstorage|interfaces|miner|mining_args|utxo_snapshot)|test/fuzz/(kitchen_sink|minisketch|parse_univalue)|clientversion|core_io|rest|signet|init)\.cpp'
-  jq --arg patterns "$FILES_WITH_ENFORCED_IWYU" 'map(select(.file | test($patterns)))' "${BASE_BUILD_DIR}/compile_commands.json" > "${BASE_BUILD_DIR}/compile_commands_iwyu_errors.json"
-  jq --arg patterns "$FILES_WITH_ENFORCED_IWYU" 'map(select(.file | test($patterns) | not))' "${BASE_BUILD_DIR}/compile_commands.json" > "${BASE_BUILD_DIR}/compile_commands_iwyu_warnings.json"
-
-  cd "${BASE_ROOT_DIR}"
-
-  run_iwyu() {
-    mv "${BASE_BUILD_DIR}/$1" "${BASE_BUILD_DIR}/compile_commands.json"
-    {
-      python3 /include-what-you-use/mapgen/iwyu-mapgen-clang-intrin.py --lang imp "$("clang-${IWYU_LLVM_V}" -print-resource-dir)/include" > "${BASE_BUILD_DIR}/clang.intrinsics.imp"
-      python3 /include-what-you-use/iwyu_tool.py \
-             -p "${BASE_BUILD_DIR}" "${MAKEJOBS}" -- \
-             -Xiwyu --cxx17ns \
-             -Xiwyu --mapping_file="${BASE_ROOT_DIR}/contrib/devtools/iwyu/bitcoin.core.imp" \
-             -Xiwyu --mapping_file="${BASE_BUILD_DIR}/clang.intrinsics.imp" \
-             -Xiwyu --max_line_length=160 \
-             -Xiwyu --check_also='*/common/types\.h' \
-             -Xiwyu --check_also='*/consensus/*\.h' \
-             -Xiwyu --check_also='*/interfaces/*\.h' \
-             -Xiwyu --check_also='*/primitives/transaction_identifier\.h' \
-             -Xiwyu --check_also='*/rpc/protocol\.h' \
-             2>&1 || true
-    } | tee /tmp/iwyu_ci.out
-    python3 "/include-what-you-use/fix_includes.py" --nosafe_headers < /tmp/iwyu_ci.out
-    python3 -c '
-import runpy
-import subprocess
-
-subtrees = runpy.run_path("test/lint/lint_ignore_dirs.py")["SHARED_EXCLUDED_SUBTREES"]
-subprocess.run(["git", "restore", "--", *subtrees], check=True)
-'
-    git diff -U1 | ./contrib/devtools/clang-format-diff.py -binary="clang-format-${IWYU_LLVM_V}" -p1 -i -v
-  }
-
-  run_iwyu "compile_commands_iwyu_errors.json"
-  if ! ( git --no-pager diff --exit-code ); then
-    echo "^^^ ⚠️ Failure generated from IWYU"
-    false
-  fi
-
-  run_iwyu "compile_commands_iwyu_warnings.json"
-  git --no-pager diff
+  "${BASE_ROOT_DIR}/ci/test/run-iwyu.py"
 fi
diff --git a/ci/test/run-iwyu.py b/ci/test/run-iwyu.py
new file mode 100755
index 0000000..f62f789
--- /dev/null
+++ b/ci/test/run-iwyu.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+# Copyright (c) The Bitcoin Core developers
+# Distributed under the MIT software license, see the accompanying
+# file COPYING or https://opensource.org/license/mit/.
+
+import json
+import os
+import re
+import runpy
+import shlex
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+
+FILES_WITH_ENFORCED_IWYU = re.compile(
+    r"/src/((bench|common|consensus|crypto|index|init|kernel|primitives|rpc|script|univalue/(lib|test)|util|zmq)/.*"
+    r"|node/(blockstorage|interfaces|miner|mining_args|utxo_snapshot)"
+    r"|test/fuzz/(kitchen_sink|minisketch|parse_univalue)"
+    r"|clientversion|core_io|rest|signet|init)\.cpp"
+)
+
+
+def run(cmd, **kwargs):
+    print("+ " + shlex.join(cmd), flush=True)
+    kwargs.setdefault("check", True)
+    try:
+        return subprocess.run(cmd, **kwargs)
+    except Exception as error:
+        sys.exit(str(error))
+
+
+def run_iwyu(root: Path, build_dir: Path, compile_commands: str, makejobs: str, llvm_version: str):
+    shutil.move(build_dir / compile_commands, build_dir / "compile_commands.json")
+    clang_resource_dir = run(
+        [f"clang-{llvm_version}", "-print-resource-dir"],
+        stdout=subprocess.PIPE,
+        text=True,
+    ).stdout.strip()
+    run(
+        [
+            "python3",
+            "/include-what-you-use/mapgen/iwyu-mapgen-clang-intrin.py",
+            "--lang",
+            "imp",
+            f"{clang_resource_dir}/include",
+        ],
+        stdout=(build_dir / "clang.intrinsics.imp").open("w"),
+    )
+
+    iwyu_output = run(
+        [
+            "python3",
+            "/include-what-you-use/iwyu_tool.py",
+            "-p",
+            str(build_dir),
+            makejobs,
+            "--",
+            "-Xiwyu",
+            "--cxx17ns",
+            "-Xiwyu",
+            f"--mapping_file={root / 'contrib/devtools/iwyu/bitcoin.core.imp'}",
+            "-Xiwyu",
+            f"--mapping_file={build_dir / 'clang.intrinsics.imp'}",
+            "-Xiwyu",
+            "--max_line_length=160",
+            "-Xiwyu",
+            r"--check_also=*/common/types\.h",
+            "-Xiwyu",
+            r"--check_also=*/consensus/*\.h",
+            "-Xiwyu",
+            r"--check_also=*/interfaces/*\.h",
+            "-Xiwyu",
+            r"--check_also=*/primitives/transaction_identifier\.h",
+            "-Xiwyu",
+            r"--check_also=*/rpc/protocol\.h",
+        ],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.STDOUT,
+        text=True,
+        check=False,
+    )
+    Path("/tmp/iwyu_ci.out").write_text(iwyu_output.stdout)
+    print(iwyu_output.stdout, end="")
+    with Path("/tmp/iwyu_ci.out").open() as output:
+        run(
+            ["python3", "/include-what-you-use/fix_includes.py", "--nosafe_headers"],
+            stdin=output,
+        )
+
+    excluded_subtrees = runpy.run_path(str(root / "test/lint/lint_ignore_dirs.py"))["SHARED_EXCLUDED_SUBTREES"]
+    run(["git", "restore", "--", *excluded_subtrees])
+    diff = run(["git", "diff", "-U1"], stdout=subprocess.PIPE)
+    run(
+        ["./contrib/devtools/clang-format-diff.py", f"-binary=clang-format-{llvm_version}", "-p1", "-i", "-v"],
+        input=diff.stdout,
+    )
+
+
+def main():
+    root = Path(os.environ["BASE_ROOT_DIR"])
+    os.chdir(root)
+    build_dir = Path(os.environ["BASE_BUILD_DIR"])
+    all_compile_commands = json.loads((build_dir / "compile_commands.json").read_text())
+    (build_dir / "compile_commands_iwyu_errors.json").write_text(
+        json.dumps([entry for entry in all_compile_commands if FILES_WITH_ENFORCED_IWYU.search(entry["file"])])
+    )
+    (build_dir / "compile_commands_iwyu_warnings.json").write_text(
+        json.dumps([entry for entry in all_compile_commands if not FILES_WITH_ENFORCED_IWYU.search(entry["file"])])
+    )
+
+    makejobs = os.environ["MAKEJOBS"]
+    llvm_version = os.environ["IWYU_LLVM_V"]
+    run_iwyu(root, build_dir, "compile_commands_iwyu_errors.json", makejobs, llvm_version)
+    if run(["git", "diff", "--exit-code"], check=False).returncode:
+        print("^^^ ⚠️ Failure generated from IWYU")
+        raise SystemExit(1)
+
+    run_iwyu(root, build_dir, "compile_commands_iwyu_warnings.json", makejobs, llvm_version)
+    run(["git", "--no-pager", "diff"])
+
+
+if __name__ == "__main__":
+    main()
Seems fine, but All of those python3 -c '...' inside bash are fine, but seem a bit hacky. At some point we can use vanilla Python and drop the jq dep. Something like: <details><summary>completely untested draft diff</summary> ```diff ci/test/00_setup_env_native_iwyu.sh | 2 +- ci/test/03_test_script.sh | 44 +------------ ci/test/run-iwyu.py | 125 ++++++++++++++++++++++++++++++++++++ 3 files changed, 127 insertions(+), 44 deletions(-) diff --git a/ci/test/00_setup_env_native_iwyu.sh b/ci/test/00_setup_env_native_iwyu.sh index 20240f6..9ed2a09 100755 --- a/ci/test/00_setup_env_native_iwyu.sh +++ b/ci/test/00_setup_env_native_iwyu.sh @@ -12,3 +12,3 @@ export IWYU_LLVM_V="23" export APT_LLVM_V="${IWYU_LLVM_V}" -export PACKAGES="clang-${IWYU_LLVM_V} clang-format-${IWYU_LLVM_V} libclang-${IWYU_LLVM_V}-dev llvm-${IWYU_LLVM_V}-dev jq libboost-dev libzmq3-dev systemtap-sdt-dev qt6-base-dev qt6-tools-dev qt6-l10n-tools libqrencode-dev libsqlite3-dev libcapnp-dev capnproto" +export PACKAGES="clang-${IWYU_LLVM_V} clang-format-${IWYU_LLVM_V} libclang-${IWYU_LLVM_V}-dev llvm-${IWYU_LLVM_V}-dev libboost-dev libzmq3-dev systemtap-sdt-dev qt6-base-dev qt6-tools-dev qt6-l10n-tools libqrencode-dev libsqlite3-dev libcapnp-dev capnproto" export NO_DEPENDS=1 diff --git a/ci/test/03_test_script.sh b/ci/test/03_test_script.sh index 5793656..187834b 100755 --- a/ci/test/03_test_script.sh +++ b/ci/test/03_test_script.sh @@ -236,45 +236,3 @@ fi if [[ "${RUN_IWYU}" == true ]]; then - # TODO: Consider enforcing IWYU across the entire codebase. - FILES_WITH_ENFORCED_IWYU='/src/((bench|common|consensus|crypto|index|init|kernel|primitives|rpc|script|univalue/(lib|test)|util|zmq)/.*|node/(blockstorage|interfaces|miner|mining_args|utxo_snapshot)|test/fuzz/(kitchen_sink|minisketch|parse_univalue)|clientversion|core_io|rest|signet|init)\.cpp' - jq --arg patterns "$FILES_WITH_ENFORCED_IWYU" 'map(select(.file | test($patterns)))' "${BASE_BUILD_DIR}/compile_commands.json" > "${BASE_BUILD_DIR}/compile_commands_iwyu_errors.json" - jq --arg patterns "$FILES_WITH_ENFORCED_IWYU" 'map(select(.file | test($patterns) | not))' "${BASE_BUILD_DIR}/compile_commands.json" > "${BASE_BUILD_DIR}/compile_commands_iwyu_warnings.json" - - cd "${BASE_ROOT_DIR}" - - run_iwyu() { - mv "${BASE_BUILD_DIR}/$1" "${BASE_BUILD_DIR}/compile_commands.json" - { - python3 /include-what-you-use/mapgen/iwyu-mapgen-clang-intrin.py --lang imp "$("clang-${IWYU_LLVM_V}" -print-resource-dir)/include" > "${BASE_BUILD_DIR}/clang.intrinsics.imp" - python3 /include-what-you-use/iwyu_tool.py \ - -p "${BASE_BUILD_DIR}" "${MAKEJOBS}" -- \ - -Xiwyu --cxx17ns \ - -Xiwyu --mapping_file="${BASE_ROOT_DIR}/contrib/devtools/iwyu/bitcoin.core.imp" \ - -Xiwyu --mapping_file="${BASE_BUILD_DIR}/clang.intrinsics.imp" \ - -Xiwyu --max_line_length=160 \ - -Xiwyu --check_also='*/common/types\.h' \ - -Xiwyu --check_also='*/consensus/*\.h' \ - -Xiwyu --check_also='*/interfaces/*\.h' \ - -Xiwyu --check_also='*/primitives/transaction_identifier\.h' \ - -Xiwyu --check_also='*/rpc/protocol\.h' \ - 2>&1 || true - } | tee /tmp/iwyu_ci.out - python3 "/include-what-you-use/fix_includes.py" --nosafe_headers < /tmp/iwyu_ci.out - python3 -c ' -import runpy -import subprocess - -subtrees = runpy.run_path("test/lint/lint_ignore_dirs.py")["SHARED_EXCLUDED_SUBTREES"] -subprocess.run(["git", "restore", "--", *subtrees], check=True) -' - git diff -U1 | ./contrib/devtools/clang-format-diff.py -binary="clang-format-${IWYU_LLVM_V}" -p1 -i -v - } - - run_iwyu "compile_commands_iwyu_errors.json" - if ! ( git --no-pager diff --exit-code ); then - echo "^^^ ⚠️ Failure generated from IWYU" - false - fi - - run_iwyu "compile_commands_iwyu_warnings.json" - git --no-pager diff + "${BASE_ROOT_DIR}/ci/test/run-iwyu.py" fi diff --git a/ci/test/run-iwyu.py b/ci/test/run-iwyu.py new file mode 100755 index 0000000..f62f789 --- /dev/null +++ b/ci/test/run-iwyu.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +# Copyright (c) The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or https://opensource.org/license/mit/. + +import json +import os +import re +import runpy +import shlex +import shutil +import subprocess +import sys +from pathlib import Path + + +FILES_WITH_ENFORCED_IWYU = re.compile( + r"/src/((bench|common|consensus|crypto|index|init|kernel|primitives|rpc|script|univalue/(lib|test)|util|zmq)/.*" + r"|node/(blockstorage|interfaces|miner|mining_args|utxo_snapshot)" + r"|test/fuzz/(kitchen_sink|minisketch|parse_univalue)" + r"|clientversion|core_io|rest|signet|init)\.cpp" +) + + +def run(cmd, **kwargs): + print("+ " + shlex.join(cmd), flush=True) + kwargs.setdefault("check", True) + try: + return subprocess.run(cmd, **kwargs) + except Exception as error: + sys.exit(str(error)) + + +def run_iwyu(root: Path, build_dir: Path, compile_commands: str, makejobs: str, llvm_version: str): + shutil.move(build_dir / compile_commands, build_dir / "compile_commands.json") + clang_resource_dir = run( + [f"clang-{llvm_version}", "-print-resource-dir"], + stdout=subprocess.PIPE, + text=True, + ).stdout.strip() + run( + [ + "python3", + "/include-what-you-use/mapgen/iwyu-mapgen-clang-intrin.py", + "--lang", + "imp", + f"{clang_resource_dir}/include", + ], + stdout=(build_dir / "clang.intrinsics.imp").open("w"), + ) + + iwyu_output = run( + [ + "python3", + "/include-what-you-use/iwyu_tool.py", + "-p", + str(build_dir), + makejobs, + "--", + "-Xiwyu", + "--cxx17ns", + "-Xiwyu", + f"--mapping_file={root / 'contrib/devtools/iwyu/bitcoin.core.imp'}", + "-Xiwyu", + f"--mapping_file={build_dir / 'clang.intrinsics.imp'}", + "-Xiwyu", + "--max_line_length=160", + "-Xiwyu", + r"--check_also=*/common/types\.h", + "-Xiwyu", + r"--check_also=*/consensus/*\.h", + "-Xiwyu", + r"--check_also=*/interfaces/*\.h", + "-Xiwyu", + r"--check_also=*/primitives/transaction_identifier\.h", + "-Xiwyu", + r"--check_also=*/rpc/protocol\.h", + ], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + Path("/tmp/iwyu_ci.out").write_text(iwyu_output.stdout) + print(iwyu_output.stdout, end="") + with Path("/tmp/iwyu_ci.out").open() as output: + run( + ["python3", "/include-what-you-use/fix_includes.py", "--nosafe_headers"], + stdin=output, + ) + + excluded_subtrees = runpy.run_path(str(root / "test/lint/lint_ignore_dirs.py"))["SHARED_EXCLUDED_SUBTREES"] + run(["git", "restore", "--", *excluded_subtrees]) + diff = run(["git", "diff", "-U1"], stdout=subprocess.PIPE) + run( + ["./contrib/devtools/clang-format-diff.py", f"-binary=clang-format-{llvm_version}", "-p1", "-i", "-v"], + input=diff.stdout, + ) + + +def main(): + root = Path(os.environ["BASE_ROOT_DIR"]) + os.chdir(root) + build_dir = Path(os.environ["BASE_BUILD_DIR"]) + all_compile_commands = json.loads((build_dir / "compile_commands.json").read_text()) + (build_dir / "compile_commands_iwyu_errors.json").write_text( + json.dumps([entry for entry in all_compile_commands if FILES_WITH_ENFORCED_IWYU.search(entry["file"])]) + ) + (build_dir / "compile_commands_iwyu_warnings.json").write_text( + json.dumps([entry for entry in all_compile_commands if not FILES_WITH_ENFORCED_IWYU.search(entry["file"])]) + ) + + makejobs = os.environ["MAKEJOBS"] + llvm_version = os.environ["IWYU_LLVM_V"] + run_iwyu(root, build_dir, "compile_commands_iwyu_errors.json", makejobs, llvm_version) + if run(["git", "diff", "--exit-code"], check=False).returncode: + print("^^^ ⚠️ Failure generated from IWYU") + raise SystemExit(1) + + run_iwyu(root, build_dir, "compile_commands_iwyu_warnings.json", makejobs, llvm_version) + run(["git", "--no-pager", "diff"]) + + +if __name__ == "__main__": + main() ``` </details>
maflcko (Migrated from github.com) approved these changes 2026-09-17 15:45:22 +00:00
maflcko (Migrated from github.com) left a comment

lgtm. Seems fine for a minimal speed-up and minimally smaller ci log output?

lgtm. Seems fine for a minimal speed-up and minimally smaller ci log output?
David-Uka commented 2026-09-23 14:07:47 +00:00 (Migrated from github.com)

Code-review ACK 01e3eca2d8

Filtering SHARED_EXCLUDED_SUBTREES out of compile_commands.json before the IWYU run drops the libmultiprocess sources — including the generated test/mp/test/foo.capnp.c++ that makes IWYU (llvm-23) abort on a UsingShadowDecl, the crash surfaced in #36235. The follow-up git restore is still correctly kept for subtree headers associated with non-subtree TUs. I didn't run the IWYU job locally; reasoning from the diff plus @hebasto's repro and green CI.

Code-review ACK 01e3eca2d8ee755eed4488a44093759f0eddcb34 Filtering `SHARED_EXCLUDED_SUBTREES` out of `compile_commands.json` before the IWYU run drops the libmultiprocess sources — including the generated `test/mp/test/foo.capnp.c++` that makes IWYU (llvm-23) abort on a `UsingShadowDecl`, the crash surfaced in #36235. The follow-up `git restore` is still correctly kept for subtree headers associated with non-subtree TUs. I didn't run the IWYU job locally; reasoning from the diff plus @hebasto's repro and green CI.
hebasto (Migrated from github.com) approved these changes 2026-09-25 14:08:08 +00:00
hebasto (Migrated from github.com) left a comment

ACK 01e3eca2d8.

ACK 01e3eca2d8ee755eed4488a44093759f0eddcb34.
hebasto (Migrated from github.com) reviewed 2026-09-25 15:50:00 +00:00
hebasto (Migrated from github.com) commented 2026-09-25 15:50:00 +00:00

FWIW, we can use the --exclude option of the iwyu_tool.py tool:

--- a/ci/test/03_test_script.sh
+++ b/ci/test/03_test_script.sh
@@ -242,8 +242,9 @@ if [[ "${RUN_IWYU}" == true ]]; then
     mv "${BASE_BUILD_DIR}/$1" "${BASE_BUILD_DIR}/compile_commands.json"
     {
       python3 /include-what-you-use/mapgen/iwyu-mapgen-clang-intrin.py --lang imp "$("clang-${IWYU_LLVM_V}" -print-resource-dir)/include" > "${BASE_BUILD_DIR}/clang.intrinsics.imp"
+      mapfile -t IWYU_EXCLUDES < <(python3 -c 'import runpy; print("\n".join("--exclude=" + d for d in runpy.run_path("test/lint/lint_ignore_dirs.py")["SHARED_EXCLUDED_SUBTREES"]))')
       python3 /include-what-you-use/iwyu_tool.py \
-             -p "${BASE_BUILD_DIR}" "${MAKEJOBS}" -- \
+             -p "${BASE_BUILD_DIR}" "${MAKEJOBS}" "${IWYU_EXCLUDES[@]}" -- \
              -Xiwyu --cxx17ns \
              -Xiwyu --mapping_file="${BASE_ROOT_DIR}/contrib/devtools/iwyu/bitcoin.core.imp" \
              -Xiwyu --mapping_file="${BASE_BUILD_DIR}/clang.intrinsics.imp" \
FWIW, we can use the `--exclude` option of the `iwyu_tool.py` tool: ```diff --- a/ci/test/03_test_script.sh +++ b/ci/test/03_test_script.sh @@ -242,8 +242,9 @@ if [[ "${RUN_IWYU}" == true ]]; then mv "${BASE_BUILD_DIR}/$1" "${BASE_BUILD_DIR}/compile_commands.json" { python3 /include-what-you-use/mapgen/iwyu-mapgen-clang-intrin.py --lang imp "$("clang-${IWYU_LLVM_V}" -print-resource-dir)/include" > "${BASE_BUILD_DIR}/clang.intrinsics.imp" + mapfile -t IWYU_EXCLUDES < <(python3 -c 'import runpy; print("\n".join("--exclude=" + d for d in runpy.run_path("test/lint/lint_ignore_dirs.py")["SHARED_EXCLUDED_SUBTREES"]))') python3 /include-what-you-use/iwyu_tool.py \ - -p "${BASE_BUILD_DIR}" "${MAKEJOBS}" -- \ + -p "${BASE_BUILD_DIR}" "${MAKEJOBS}" "${IWYU_EXCLUDES[@]}" -- \ -Xiwyu --cxx17ns \ -Xiwyu --mapping_file="${BASE_ROOT_DIR}/contrib/devtools/iwyu/bitcoin.core.imp" \ -Xiwyu --mapping_file="${BASE_BUILD_DIR}/clang.intrinsics.imp" \ ```
First-time contributor

Base: 09e22fbbb0caafbd2167657c2a8d409ae435b2cc
Head: 01e3eca2d8ee755eed4488a44093759f0eddcb34

No verified findings are available from this partial review.

Review coverage was incomplete. The archaeology review had incomplete evidence.

Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> Base: `09e22fbbb0caafbd2167657c2a8d409ae435b2cc` Head: `01e3eca2d8ee755eed4488a44093759f0eddcb34` No verified findings are available from this partial review. Review coverage was incomplete. The archaeology review had incomplete evidence. [Full review report](<https://review.fish.foo/traces/36252-01e3eca2d8ee755eed4488a44093759f0eddcb34-419-1.html>)
BrandonOdiwuor (Migrated from github.com) reviewed 2026-10-08 11:06:59 +00:00
BrandonOdiwuor (Migrated from github.com) left a comment

Concept ACK filtering SHARED_EXCLUDED_SUBTREES out of compile_commands.json before IWYU

I also agree with the suggestion to replace the IWYU inline python3 -c with vanilla python which also eliminates the need for jq

Seems fine, but All of those python3 -c '...' inside bash are fine, but seem a bit hacky.

At some point we can use vanilla Python and drop the jq dep. Something like:

completely untested draft diff
ci/test/00_setup_env_native_iwyu.sh | 2 +-

I tested the suggested python script with a patch to skip the subtrees on github.com/BrandonOdiwuor/bitcoin@53cab06b3c (see run: https://github.com/BrandonOdiwuor/bitcoin/actions/runs/37636046096/job/112842444834)

Concept ACK filtering SHARED_EXCLUDED_SUBTREES out of compile_commands.json before IWYU I also agree with the suggestion to replace the IWYU inline python3 -c with vanilla python which also eliminates the need for `jq` > Seems fine, but All of those python3 -c '...' inside bash are fine, but seem a bit hacky. > > At some point we can use vanilla Python and drop the jq dep. Something like: > > completely untested draft diff > ci/test/00_setup_env_native_iwyu.sh | 2 +- I tested the suggested python script with a patch to skip the subtrees on https://github.com/BrandonOdiwuor/bitcoin/commit/53cab06b3c9858e7f1407ffea87a29da68a32a1c (see run: https://github.com/BrandonOdiwuor/bitcoin/actions/runs/37636046096/job/112842444834)
sedited commented 2026-11-06 11:58:53 +00:00 (Migrated from github.com)

@ryanofsky do you want to take any of the remaining comments here?

@ryanofsky do you want to take any of the remaining comments here?
maflcko commented 2026-11-06 13:27:54 +00:00 (Migrated from github.com)
TW: ai rant

Seems fine to merge, but my preference would be to not violate the AI policy in the pull description. The LLM-speak that re-hashes a random set of issues/references seems more confusing than a clear and concise human written opinion.

#35361 asked for subtrees not to be linted at all.

The discussion in https://github.com/bitcoin/bitcoin/issues/34928 is still ongoing, and it seems fine to have a belt-and-suspender lint for bugprone stuff (tidy and shellcheck?). Excluding iwyu seems fine, given the different/conflicting iwyu versions.

One-file change to the CI script.

Thanks AI for telling me I can't count to one myself.

No need to push again to this pull, but the description can basically be something like: "The iwyu version used in this repo may differ from the one in a subtree and thus produce conflicting suggestions. Fix it by excluding the subtrees from the compilation database."

Mentioning #36112 seem unrelated, because this is true, before and after this pull.

<details><summary>TW: ai rant</summary> Seems fine to merge, but my preference would be to not violate the AI policy in the pull description. The LLM-speak that re-hashes a random set of issues/references seems more confusing than a clear and concise human written opinion. > #35361 asked for subtrees not to be linted at all. The discussion in https://github.com/bitcoin/bitcoin/issues/34928 is still ongoing, and it seems fine to have a belt-and-suspender lint for bugprone stuff (tidy and shellcheck?). Excluding iwyu seems fine, given the different/conflicting iwyu versions. > One-file change to the CI script. Thanks AI for telling me I can't count to one myself. No need to push again to this pull, but the description can basically be something like: "The iwyu version used in this repo may differ from the one in a subtree and thus produce conflicting suggestions. Fix it by excluding the subtrees from the compilation database." Mentioning #36112 seem unrelated, because this is true, before and after this pull. </details>
ryanofsky (Migrated from github.com) reviewed 2026-11-06 22:42:22 +00:00
ryanofsky (Migrated from github.com) left a comment

re: sedited https://github.com/bitcoin/bitcoin/pull/36252#issuecomment-6684294053

do you want to take any of the remaining comments here?

@sedited Thanks, I'd like to leave the remaining suggestions for follow-ups. hebasto's --exclude idea and maflcko's larger rewrite would both rework the whole IWYU block, not only the subtree skip.


re: maflcko https://github.com/bitcoin/bitcoin/pull/36252#issuecomment-6685939713

@maflcko Thanks for the review. I updated the description to fix two things you pointed out: it no longer says #35361 asked for subtrees not to be linted at all (agree that is still being discussed in #34928), and it now says the change is three lines plus comments. I'd like to keep the rest, because I find a change easier to review when the description says what the code does now and how the change affects it. If any specific part is unclear, I'm happy to rewrite it.

re: sedited https://github.com/bitcoin/bitcoin/pull/36252#issuecomment-6684294053 > do you want to take any of the remaining comments here? @sedited Thanks, I'd like to leave the remaining suggestions for follow-ups. hebasto's `--exclude` idea and maflcko's larger rewrite would both rework the whole IWYU block, not only the subtree skip. --- re: maflcko https://github.com/bitcoin/bitcoin/pull/36252#issuecomment-6685939713 @maflcko Thanks for the review. I updated the description to fix two things you pointed out: it no longer says #35361 asked for subtrees not to be linted at all (agree that is still being discussed in #34928), and it now says the change is three lines plus comments. I'd like to keep the rest, because I find a change easier to review when the description says what the code does now and how the change affects it. If any specific part is unclear, I'm happy to rewrite it.
ryanofsky (Migrated from github.com) commented 2026-11-06 22:40:04 +00:00

re: https://github.com/bitcoin/bitcoin/pull/36252#discussion_r4106222875

we can use the --exclude option of the iwyu_tool.py tool

Thanks, that would work too. I kept the jq filter so the subtree skip works the same way as the FILES_WITH_ENFORCED_IWYU split right below it, which also filters compile_commands.json with jq. Switching the whole block to iwyu_tool.py options could be a nice follow-up, though the enforced/warnings split selects files instead of excluding them, so it may not map over as directly.

re: https://github.com/bitcoin/bitcoin/pull/36252#discussion_r4106222875 > we can use the `--exclude` option of the `iwyu_tool.py` tool Thanks, that would work too. I kept the `jq` filter so the subtree skip works the same way as the `FILES_WITH_ENFORCED_IWYU` split right below it, which also filters `compile_commands.json` with `jq`. Switching the whole block to `iwyu_tool.py` options could be a nice follow-up, though the enforced/warnings split selects files instead of excluding them, so it may not map over as directly.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36252
No description provided.