Repository navigation
feat(NODE-1364): Unused components check - #942
andrewbattat wants to merge 51 commits into
Conversation
|
|
||
| - id: check-unused-components | ||
| name: Check for unused components | ||
| entry: bash -c '$(which bazel) run //rs/ic_os/manifest_tool -- --repo-root $(git rev-parse --show-toplevel) check-unused-components' |
There was a problem hiding this comment.
I was forced to dynamically determine the correct Bazel path using which. Otherwise, pre-commit gave the error /usr/bin/bash: /usr/local/bin/bazel: No such file or directory
See pre-commit failure without dynamically determining the Bazel path:
https://github.com/dfinity/ic/actions/runs/10426685939/job/28880092864
There was a problem hiding this comment.
It looks like the error when running bazel directly is coming from:
INFO: Running command line: bazel-bin/rs/ic_os/manifest_tool/manifest_tool --repo-root '$(git' rev-parse '--show-toplevel)' check-unused-components
error: unrecognized subcommand 'rev-parse'
The quoting looks funky here but fine in your changes. I don't know what's up 🤷, but hopefully this helps.
| - id: check-unused-components | ||
| name: Check for unused components | ||
| entry: bash -c '$(which bazel) run //rs/ic_os/manifest_tool -- --repo-root $(git rev-parse --show-toplevel) check-unused-components' |
There was a problem hiding this comment.
I'm a little paranoid about this check being in pre-commit. The check itself takes 10 seconds, but that's almost entirely bazel overhead (it takes less than a second when run with cargo).
I don't enforce pre-commit checks on every one of my local commits, but if any others do, I'm not sure how much this will slow things down.
There was a problem hiding this comment.
Doesn't it depend on the target being built and if it is cached?
Do you know if the pre-commit will run without a cache?
# without the cache
❯ time bazel run //rs/ic_os/manifest_tool -- --repo-root $(git rev-parse --show-toplevel) check-unused-components
INFO: Invocation ID: dba04f15-7167-44e3-955f-79e095ae6e83
INFO: Analyzed target //rs/ic_os/manifest_tool:manifest_tool (170 packages loaded, 2866 targets configured).
INFO: Found 1 target...
Target //rs/ic_os/manifest_tool:manifest_tool up-to-date:
bazel-bin/rs/ic_os/manifest_tool/manifest_tool
INFO: Elapsed time: 19.383s, Critical Path: 15.43s
INFO: 147 processes: 102 internal, 45 darwin-sandbox.
INFO: Build completed successfully, 147 total actions
INFO: Running command line: bazel-bin/rs/ic_os/manifest_tool/manifest_tool --repo-root /Users/raymond/dev/dfinity/ic check-unused-components
Error: Unused files found:
/Users/raymond/dev/dfinity/ic/ic-os/components/misc/something.sh
bazel run //rs/ic_os/manifest_tool -- --repo-root check-unused-components 0.02s user 0.02s system 0% cpu 19.605 total
# with the cache
❯ time bazel run //rs/ic_os/manifest_tool -- --repo-root $(git rev-parse --show-toplevel) check-unused-components
INFO: Invocation ID: b96db857-bbad-4759-ad7e-32ff444ba58c
INFO: Analyzed target //rs/ic_os/manifest_tool:manifest_tool (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //rs/ic_os/manifest_tool:manifest_tool up-to-date:
bazel-bin/rs/ic_os/manifest_tool/manifest_tool
INFO: Elapsed time: 0.663s, Critical Path: 0.08s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
INFO: Running command line: bazel-bin/rs/ic_os/manifest_tool/manifest_tool --repo-root /Users/raymond/dev/dfinity/ic check-unused-components
Error: Unused files found:
/Users/raymond/dev/dfinity/ic/ic-os/components/misc/something.sh
bazel run //rs/ic_os/manifest_tool -- --repo-root check-unused-components 0.01s user 0.02s system 4% cpu 0.693 total
There was a problem hiding this comment.
I'm a little paranoid about this check being in pre-commit.
Same here. Would it make sense to run this on CI only?
|
|
||
| - id: check-unused-components | ||
| name: Check for unused components | ||
| entry: bash -c '$(which bazel) run //rs/ic_os/manifest_tool -- --repo-root $(git rev-parse --show-toplevel) check-unused-components' |
There was a problem hiding this comment.
It looks like the error when running bazel directly is coming from:
INFO: Running command line: bazel-bin/rs/ic_os/manifest_tool/manifest_tool --repo-root '$(git' rev-parse '--show-toplevel)' check-unused-components
error: unrecognized subcommand 'rev-parse'
The quoting looks funky here but fine in your changes. I don't know what's up 🤷, but hopefully this helps.
| if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) { | ||
| if file_name.ends_with(".bzl") | ||
| || file_name.ends_with(".bazel") | ||
| || file_name.to_lowercase().starts_with("readme.") |
There was a problem hiding this comment.
Could we list the readmes in the ignored files instead, just to keep the matching complexity down?
There was a problem hiding this comment.
Personally, I think I actually like it the way it is. I can just imagine a situation where a dev adds a readme to their component and then this error goes off and they message IDX asking what this check is about and then IDX forwards them to us, and we tell them they have to touch this tool to get around the check. The current pattern matching helps prevent that, and the matching complexity isn't too bad imo.
| let repo_files: HashSet<PathBuf> = collect_repo_files(&components_path)?; | ||
| let manifest_files: HashSet<PathBuf> = collect_manifest_files(&icos_manifest); | ||
|
|
||
| let unused_files: Vec<&PathBuf> = repo_files.difference(&manifest_files).collect(); |
There was a problem hiding this comment.
Maybe we could pull the ignore logic out of collect_repo_files into its own function? This would make the flow really clear: 1. Gather all the files, 2. Strip out ignored, 3. Compare this to expected.
There was a problem hiding this comment.
Agreed! Fixed!
| } | ||
| } | ||
|
|
||
| fn get_manifest(manifest_path: &Path, components_path: &Path) -> Result<Manifest> { |
There was a problem hiding this comment.
There was a problem hiding this comment.
Agreed! Updated!
| Ok(manifest) | ||
| } | ||
|
|
||
| pub fn get_icos_manifest(repo_root: &Path) -> Result<IcosManifest> { |
There was a problem hiding this comment.
This could be raised one level up, since it is really just shuffling paths into the new call, sort of outside the logic of the parser.
There was a problem hiding this comment.
Alternatively, I could move this logic into the IcosManifest constructor, because that's effectively what get_icos_manifest is. WDYT?
| fs::create_dir(&components_path).unwrap(); | ||
|
|
||
| let mut file = File::create(&manifest_path).unwrap(); | ||
| writeln!(file, r#"Label("src/lib.rs"): "lib.rs""#).unwrap(); |
There was a problem hiding this comment.
Nice tests! Could we also mix in some of the things we'd like to ignore, like comments? You should be able to wrap that r# string into multiple lines.
| setupos_components: Manifest, | ||
| boundary_guestos_components: Manifest, | ||
| ) -> Self { | ||
| IcosManifest { |
There was a problem hiding this comment.
I wonder if this tool needs to be rigid to our component structure, of if it could be a list that keeps paths to give context when needed. I'm thinking of that test down below where we have to create empty files, but I don't think these should be optional either 🤔.
I'm not sold either way 😅.
There was a problem hiding this comment.
Yeah, I was thinking that when we restructure our components format (which may be soon if David moves forward with the sh_binary update) we would have to update this, but I think we should wait for the component structure to change. Then we'll have a clearer picture to work with.
There was a problem hiding this comment.
Can you add a description of what this does, or better yet, add a README file in rs/ic_os/manifest_tool?
There was a problem hiding this comment.
actually after looking at the implementation it looks like it's looking for source files that are not used by the components. Instead of parsing the files and listing the sources, why not delegate to bazel & git? would something like this work?
used_files=$(bazel query 'labels(srcs, //ic-os/...)' | sed 's|^//||; s|:|/|')
git ls-files ./ic-os \
| grep -v '.adoc$' | grep -v '.md$' | grep -v '.bazel$' | grep -v '.bzl$' \
| grep 'ic-os/components/networking' \
| grep -v -x -f <(echo "$used_files")
# output:
# ic-os/components/networking/dev-certs/canister_http_test_ca.key
# ic-os/components/networking/dev-certs/root_cert_gen.sh| const IGNORED_COMPONENT_FILES: &[&str] = &[ | ||
| "components/networking/dev-certs/root_cert_gen.sh", | ||
| "components/networking/dev-certs/canister_http_test_ca.key", | ||
| ]; |
There was a problem hiding this comment.
Can you add a note about why those files can be ignored?
| } | ||
| } | ||
|
|
||
| fn collect_repo_files(dir: &Path) -> Result<HashSet<PathBuf>, std::io::Error> { |
There was a problem hiding this comment.
As far as I can tell this will list all files in the repo, including potentially .gitignored files (and might recurse down big cache directories like target/). Wouldn't git ls-files work better here?
| stages: [manual] | ||
| pass_filenames: false | ||
|
|
||
| - id: check-unused-components |
There was a problem hiding this comment.
Have you considered implementing the check as a bazel test rule? It could then be run with bazel like any test (bazel test ...) and would be automatically included in the CI pipeline. Bazel would run the test in parallel with other tests.
| let manifest_contents = fs::read_to_string(manifest_path) | ||
| .with_context(|| format!("Failed to read file: {:?}", manifest_path))?; | ||
|
|
||
| let re = Regex::new(r#"Label\("(.+?)"\): "(.+?)""#)?; |
There was a problem hiding this comment.
I have mixed feelings about parsing bzl files from the tool. On the one hand, it's definitely the simper approach, however it feels very fragile in case we want to refactor how the components are listed (eg. Raymond mentioned that he'd like encapsulate related components, etc.).
A sturdier (but also more complex) approach would be writing some bazel code to collect these labels and pass them as command line args.
@Bownairo wdyt?
There was a problem hiding this comment.
@frankdavid see also my thoughts here: #942 (comment)
Upgrades `llvm` ([hermetic-llvm](https://github.com/hermeticbuild/hermetic-llvm), our hermetic C/C++ toolchain) from 0.8.16 to [0.8.27](https://github.com/hermeticbuild/hermetic-llvm/releases/tag/v0.8.27), its latest release. This moves the compiler, linker and runtimes from LLVM 22.1.8 to LLVM 23.1.2. ## Changes - **`MODULE.bazel`**: - `llvm` 0.8.16 → 0.8.27. - `rules_cc` 0.2.22 → 0.2.28 and `rules_shell` 0.6.1 → 0.10.0. llvm 0.8.27 requires `rules_cc` ≥ 0.2.25 and `rules_shell` ≥ 0.8.0, and the root module should declare what is actually resolved. These are the same one-line changes as in dfinity#12156 and dfinity#12152, so whichever of these PRs lands first, the others still merge cleanly. Those PRs cover the upstream changes of the two modules. - `rules_go` stays at 0.62.0. llvm 0.8.27 still requires 0.62.0 (through a `repo_name = None` edge), so the resolved version stays 0.62.0 and the comment above the declaration ("pulled in via the llvm module") stays true. dfinity#12148 bumps `rules_go` and rewrites that comment, and its new comment stays true with llvm 0.8.27 as well. `git merge-tree` merges this branch with the branches of dfinity#12156, dfinity#12152 and dfinity#12148, one after the other, without conflicts. - **`bazel/hermetic_llvm_unwindlib.patch`**: still needed. 0.8.27 still passes a bare `--unwindlib=none` to every link, and [hermeticbuild/hermetic-llvm#304](hermeticbuild/hermetic-llvm#304) is still open. The hunk itself is unchanged. Only its position moves from line 902 to line 1175, so the patch applies to the 0.8.27 release with zero offset and zero fuzz (`patch --dry-run -F0`). The TODO now says to drop the patch once that issue is fixed. Before, it said to drop it "on the next version bump". - **`bazel/BUILD.bazel`**: comment only. `@llvm_toolchains` now also declares `cc_runtimes_<os>` toolchains (see below). The comment now says that our `//bazel` wrappers mirror only the C/C++ toolchains, and why. ## Module graph Besides the three bumps above, `bazel mod graph` changes in two ways: - `apple_support` resolves to 2.9.1 instead of 2.5.2, as required by rules_cc 0.2.28. - llvm 0.8.27 adds `libxml2` 2.15.3, `mimalloc` 3.5.3, `windows_support` 0.4.1 and `zlib-ng` 2.3.3.bcr.2. hermetic-llvm uses them to build LLVM from source and for Windows targets, and none of them is in the dependency graph of the release artifacts (`bazel cquery 'deps(//ic-os/guestos/envs/prod:bundle-update + //publish/binaries:bundle)'`). It also depends on `zstd` 1.5.7.bcr.1, which we already declare. Resolution prints no new warnings. The only one is the existing `rules_qemu` `use_repo` warning. ## Upstream changes that touch our setup - **LLVM 22.1.8 → 23.1.2.** 0.8.19 moved to LLVM 23.1.0 ([dfinity#719](hermeticbuild/hermetic-llvm#719)), and 0.8.24 moved to 23.1.2 ([dfinity#786](hermeticbuild/hermetic-llvm#786)). 0.8.27 uses the `llvm-23.1.2-3` prebuilts ([dfinity#935](hermeticbuild/hermetic-llvm#935)). Since 0.8.17 the prebuilt compiler follows the `llvm` extension's `llvm.version` ([dfinity#653](hermeticbuild/hermetic-llvm#653)). We don't set it, so we get the module's 23.1.2. The runtimes we link statically (libc++, libc++abi, libunwind and the compiler-rt builtins) are now built from the 23.1.2 sources. So are the libunwind headers that `//bazel:libunwind_include` exposes to `//rs/canister_sandbox`. - **Every Linux ELF now has a build ID** ([dfinity#941](hermeticbuild/hermetic-llvm#941)). `-Wl,--build-id=sha1` is now a default Linux link flag, so rustc links get it too. lld computes the ID from the linked output, so it is as reproducible as the binary itself. This changes what we ship in two ways: - `//publish/binaries` and `//rs/ic_os/release` run `objcopy -R .note.gnu.build-id`, which removes the note but doesn't relink. The 36 bytes the note took stay behind as a gap, and `.dynsym` and the sections after it keep the addresses the linker gave them behind the note. So the build ID by itself changes these binaries, on top of the compiler change (see [Release artifacts](#release-artifacts)). - GuestOS installs `//rs/ic_os/os_tools/guest_disk`, `//rs/ic_os/remote_attestation/server`, `//rs/ic_os/guest_upgrade/client` and `//rs/ic_os/open_rootfs` (`:client_dev` and `:open_rootfs_dev` in dev images) straight from their `rust_binary` targets, without `objcopy`. They now ship with a build ID. HostOS and SetupOS install Rust binaries only from `//rs/ic_os/release`. This PR keeps upstream's default. Shipping binaries without a build ID again would take an explicit `--build-id=none` link flag, which is a separate decision. - **The runtimes are built with `-ffunction-sections -fdata-sections`** ([dfinity#942](hermeticbuild/hermetic-llvm#942)). `--gc-sections` can therefore drop unused runtime code from our statically linked binaries. - **`cc_library` can produce shared libraries on Linux glibc** ([dfinity#865](hermeticbuild/hermetic-llvm#865)). The toolchain now enables `supports_dynamic_linker`, which dynamically linked consumers such as `cc_test` would use. Our builds aren't affected: - We have no non-manual `cc_test`. - rules_rust links the static archives. - Our `rules_foreign_cc` targets only consume static outputs of other `rules_foreign_cc` targets (libfuse for e2fsprogs). - **Compile and link actions now get `-resource-dir=`** with execroot-relative paths ([dfinity#751](hermeticbuild/hermetic-llvm#751), [dfinity#755](hermeticbuild/hermetic-llvm#755)). Compile actions previously found the builtin headers through `-Xclang -internal-isystem`. cc-rs build scripts get these flags through `CFLAGS` and `LDFLAGS`, where rules_rust 0.75.0 already prefixes `-resource-dir=` with `${pwd}`. - **C++ runtimes toolchain on Bazel 9** ([dfinity#764](hermeticbuild/hermetic-llvm#764)). `@llvm_toolchains` now also declares `cc_runtimes_<os>` toolchains. They add libc++ as an implicit dependency of every C++ target, so that targets using Clang header modules import a single compiled libc++ module. We register our `//bazel` wrappers instead of `@llvm_toolchains//:all`, so these toolchains aren't registered, and libc++'s headers stay textual as before. The toolchain's module map still declares those headers, so `layering_check` doesn't need the runtimes toolchain either. - **glibc**: a few things stay the same: - the `gnu.2.31` constraint that `//:linux-glibc-2.31` pins; - the 2.28 default that the comment there mentions; - the 5.7.19 kernel headers for glibc 2.31. The link-time glibc stubs changed ([dfinity#849](hermeticbuild/hermetic-llvm#849), [dfinity#901](hermeticbuild/hermetic-llvm#901)). The binaries checked below still need no symbol version newer than `GLIBC_2.30`. ## Verification Unless noted, all of this ran in the dev container: - `bazel mod graph` and `bazel mod explain`: the results are described above. - `bazel build //... --nobuild`: all 3387 targets analyze. - The checks of the CI Linter job all pass: `shfmt-check`, `ruff-check`, `buf-check`, `DFINITY-capitalization-check`, `do-not-merge-check`, `buildifier-check`, `gazelle-check` and `buf-breaking-check`. After `buildifier-fix`, `shfmt-fix`, `ruff-fix` and `gazelle`, `git status` shows no changes. - I built these targets: - `//rs/replica` - `//rs/canister_sandbox`, `:sandbox_launcher` and `:compiler_sandbox` - `//rs/ic_os/networking/nss_icos` - `//:mke2fs`, `//:fuse2fs` and `//:debugfs` (rules_foreign_cc) - `//publish/binaries:replica.gz` and `//publish/binaries:canister_sandbox.gz` - `//publish/canisters:bundle` This rebuilt nearly everything: 7858 of the 10612 actions of the first build ran locally. None of the links printed a `linker stderr` warning, so the unwindlib patch still works. - `readelf -p .comment` on the replica shows `clang version 23.1.2` and `Linker: LLD 23.1.2`. - `nss_icos`, our only `rust_shared_library` (see dfinity#12135), links the static LLVM libunwind: - It defines 12 `_Unwind_*` symbols locally and leaves none undefined. - Its only `NEEDED` entries are glibc's: `libpthread`, `libdl`, `libc` and `ld-linux-x86-64`. - It loads with `dlopen(RTLD_NOW)`. - glibc floor (`objdump -T`): - `replica`, `canister_sandbox`, `sandbox_launcher`, `compiler_sandbox` and `nss_icos` need at most `GLIBC_2.30`. - So do `ic-recovery` and the six GuestOS targets listed under the build ID change above. - `mke2fs` and `debugfs` need at most `GLIBC_2.25`. - `fuse2fs` needs at most `GLIBC_2.28`. - Build IDs (`readelf -n`, `readelf -SW`): - Each of the six GuestOS targets has one build ID note, at 0x20031c, right after `.note.ABI-tag`. `guest_disk`, `remote_attestation/server`, `guest_upgrade/client` and `open_rootfs` built with master's toolchain (clang 22.1.8) have none. - `bazel cquery` shows that the GuestOS prod and dev images use these targets in the same configuration as a plain `bazel build`. - Re-linking `guest_disk` with the disk cache and remote cache reads disabled gives the same build ID and a byte-identical binary. - `//publish/binaries:replica`, `:canister_sandbox` and `:ic-recovery` have no build ID note. - On the host, the repo's `objcopy` command turns the `ic-recovery` that lld produced (the genrule's input) into the published file byte for byte, and every remaining section keeps its address. - `mke2fs` creates an ext4 image, and `debugfs` reads it back. - `bazel test` passes for: - all 60 non-manual `rust_doc_test` targets; - `//rs/canister_sandbox:backend_lib_test`, whose `backtrace.c` the cc-rs build script compiles; - `//rs/artifact_pool:artifact_pool_test`, which uses LMDB. - With `--config=fuzzing`, `//rs/fuzzers/bitcoin:deserialize_bitcoin_transaction` builds. It contains libFuzzer and the C code of secp256k1. It defines `__asan_init` exactly once and runs 100 iterations. ### Release artifacts I didn't run the byte-identity build of the IC-OS images, because a compiler change rebuilds nearly every action. Instead I compared these outputs against the unstamped master baseline (c712eb2): - **Canisters are byte-identical**: all 88 files of `//publish/canisters:bundle`. - **The Linux binaries differ**, as expected. `replica.gz` and `canister_sandbox.gz` from `//publish/binaries` differ for two reasons: - **The compiler moved from LLVM 22.1.8 to 23.1.2.** Their C code is compiled by clang 23.1.2, the statically linked runtimes are built from 23.1.2, and lld 23.1.2 links them. - **The new build ID.** `objcopy` removes the note, but not the gap it leaves: - In master's `replica` and `ic-recovery` (their `.gz` match the baseline), `.dynsym` starts at 0x200320, right after `.note.ABI-tag`. - In this PR's published `replica`, `canister_sandbox` and `ic-recovery`, `.dynsym` starts at 0x200340, after the 0x24 bytes the note took. - A controlled link on the host isolates this effect: one object linked by the host's lld 18 with `--build-id=none` and with `--build-id=sha1` gives two different files after our `objcopy` command. In the second file, `.dynsym`, `.rodata` and `.text` sit 0x20 bytes later. The IC-OS images contain these binaries, so they change as well. The GuestOS images also contain the four binaries above that keep their build ID. I didn't verify locally: - **macOS.** There, the hermetic toolchain only builds wasm32. This PR also brings apple_support 2.9.1 through rules_cc 0.2.28. - **arm64 Linux.** - **System tests and the full test suite.** The `Bazel Test arm64-*` CI jobs cover macOS and arm64 Linux, and CI runs the full build and test suite. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
NODE-1364
Creates manifest_tool
Creates components_parser module that will be used by the other manifest_tool commands
Creates check_unused_components command to make sure that every file in ic-os/components/ (except bazel, readme, and 'IGNORED_COMPONENT_FILES' files) are actually being used in one of the images (guestos, hostos, setupos, boundary-guestos)
Adds check_unused_components to pre-commit
Example of pre-commit failing for an unused component
Example of pre-commit succeeding after unused component removed
I also uncovered two unused files and deleted them: