From a18206f7e67473b0978a54ab2b393227ca7a872a Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sat, 5 Dec 2026 21:39:16 +0100 Subject: [PATCH 01/11] perf(ci): parallelize and cache first-party builds, cppcheck, and language-count grep Signed-off-by: Guillaume Demay --- .github/workflows/_lint.yml | 15 ++- .github/workflows/_test.yml | 15 ++- .github/workflows/pr.yml | 41 ++++-- .github/workflows/test-impact-artifact.yml | 14 ++- Makefile.cbm | 140 +++++++++++++++------ scripts/lint.sh | 11 ++ tests/test_language_count_contract.sh | 7 +- 7 files changed, 193 insertions(+), 50 deletions(-) diff --git a/.github/workflows/_lint.yml b/.github/workflows/_lint.yml index bddcee7df2..72d7f7bacd 100644 --- a/.github/workflows/_lint.yml +++ b/.github/workflows/_lint.yml @@ -65,8 +65,21 @@ jobs: - name: Add cppcheck to PATH run: echo "/opt/cppcheck/bin" >> "$GITHUB_PATH" + # Incremental cppcheck build directory: keyed on .cppcheck + Makefile.cbm + # (which lists LINT_SRCS and all flags), so any config/file-list change + # starts clean while unchanged TUs reuse verified .a1/.ctu-info state and + # cppcheck still runs full whole-program CTU analysis. + - name: cppcheck analysis cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.cppcheck-build + key: cppcheck-build-2.20.0-${{ hashFiles('.cppcheck', 'Makefile.cbm') }}-${{ github.ref }}-${{ github.sha }} + restore-keys: | + cppcheck-build-2.20.0-${{ hashFiles('.cppcheck', 'Makefile.cbm') }}-${{ github.ref }}- + cppcheck-build-2.20.0-${{ hashFiles('.cppcheck', 'Makefile.cbm') }}- + - name: Lint (cppcheck + clang-format, no clang-tidy — enforced locally) - run: scripts/lint.sh --ci CLANG_FORMAT=clang-format-20 + run: scripts/lint.sh --ci CLANG_FORMAT=clang-format-20 CPPCHECK_BUILD_DIR="${{ github.workspace }}/.cppcheck-build" # Memory-analyzer gate (user decision 2026-08-03: runner cost accepted). # Path-sensitive clang-analyzer over the memory checks only: leak paths, diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index ed60aca83e..4285d5f3a5 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -251,7 +251,7 @@ jobs: CBM_SKIP_PERF: ${{ inputs.skip_perf && '1' || '' }} CBM_TEST_SELECTION_DIR: ${{ inputs.test_selection != '' && runner.os == 'Linux' && runner.arch == 'X64' && format('{0}/test-selection', runner.temp) || inputs.test_selection != '' && inputs.test_selection_portable && format('{0}/test-selection/portable', runner.temp) || '' }} CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1500M + CCACHE_MAXSIZE: 2500M # Every shard of a leg builds the identical runner, so one shard's # cache carries the complete object set: shard 1 (or the unsharded @@ -405,6 +405,8 @@ jobs: - name: Test (clang-21, ASan+UBSan + off-by-default ASan checks) env: ASAN_OPTIONS: "detect_stack_use_after_return=1:strict_string_checks=1:detect_stack_use_after_scope=1" + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 2500M run: | scripts/test.sh CC=clang-21 CXX=clang++-21 \ SANITIZE="-fsanitize=address,undefined -fno-omit-frame-pointer -fno-optimize-sibling-calls" @@ -510,9 +512,12 @@ jobs: - name: Test (Homebrew clang, ASan + LeakSanitizer) env: ASAN_OPTIONS: "detect_leaks=1:halt_on_error=1" + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 2500M run: | LLVM_PREFIX="$(brew --prefix llvm@22)" - scripts/test.sh CC="$LLVM_PREFIX/bin/clang" CXX="$LLVM_PREFIX/bin/clang++" + export PATH="$LLVM_PREFIX/bin:$PATH" + scripts/test.sh CC=clang CXX=clang++ # Same step as in test-unix: the complete logs of the suites that did # not end green, only when the job failed. @@ -581,7 +586,7 @@ jobs: scripts/test.sh --tsan CC=${{ matrix.cc }} CXX=${{ matrix.cxx }} env: CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1500M + CCACHE_MAXSIZE: 2500M - name: ccache stats if: always() @@ -681,7 +686,7 @@ jobs: # The portable view, as on test-unix's arm64 and macOS legs. CBM_TEST_SELECTION_DIR: ${{ inputs.test_selection != '' && inputs.test_selection_portable && format('{0}/test-selection/portable', runner.temp) || '' }} CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1500M + CCACHE_MAXSIZE: 2500M - name: ccache stats if: always() @@ -801,7 +806,7 @@ jobs: run: scripts/build.sh --with-ui CC=clang CXX=clang++ TEST_SEAMS=1 env: CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1500M + CCACHE_MAXSIZE: 2500M - name: Windows regression guards (#636/#357, #618, #548, #423/#20) shell: pwsh diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 1d8994ec55..7112c6cc15 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -75,10 +75,21 @@ jobs: persist-credentials: false - name: Check out the merge base's selection tooling run: git worktree add --detach "$RUNNER_TEMP/base-tooling" HEAD^1 + - name: Compiler cache (content-verified) + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-select-ubuntu-24.04-gcc-${{ github.ref }}-${{ github.sha }} + restore-keys: | + ccache-select-ubuntu-24.04-gcc-${{ github.ref }}- + ccache-select-ubuntu-24.04-gcc- - name: Build the merge base's engine timeout-minutes: 20 + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 1500M run: | - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache cd "$RUNNER_TEMP/base-tooling" scripts/build.sh CC=gcc CXX=g++ - name: Select the tests @@ -252,7 +263,8 @@ jobs: unzip # Verified compiler cache — content-keyed, stale hits impossible by - # construction (see scripts/env.sh). + # construction (see scripts/env.sh). Cross-ref fallback matches _test.yml + # so fresh PRs start warm from main's cache instead of building cold. - name: Compiler cache (content-verified) uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: @@ -260,6 +272,7 @@ jobs: key: ccache-smoke-${{ matrix.os }}-${{ github.ref }}-${{ github.sha }} restore-keys: | ccache-smoke-${{ matrix.os }}-${{ github.ref }}- + ccache-smoke-${{ matrix.os }}- - name: Build prod + smoke (Ubuntu) if: matrix.os == 'ubuntu-latest' @@ -268,7 +281,7 @@ jobs: scripts/smoke-local.sh "$(pwd)/build/c/codebase-memory-mcp" env: CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1000M + CCACHE_MAXSIZE: 1500M SMOKE_REQUIRE_WRAPPERS: "1" - name: Build prod + smoke (macOS) @@ -279,7 +292,7 @@ jobs: scripts/smoke-local.sh "$(pwd)/build/c/codebase-memory-mcp" env: CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1000M + CCACHE_MAXSIZE: 1500M SMOKE_REQUIRE_WRAPPERS: "1" - name: Build prod + smoke (Windows) @@ -290,7 +303,7 @@ jobs: SMOKE_ARCH=amd64 bash test-infrastructure/vm/vm-smoke.sh env: CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1000M + CCACHE_MAXSIZE: 1500M SMOKE_REQUIRE_WRAPPERS: "1" # ── Waste sanitizer, REPORT-ONLY: memory + CPU waste on this repository and @@ -334,11 +347,22 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: scripts/ci/test-impact-shadow.sh --fetch-release "$RUNNER_TEMP/cbm-bin" + - name: Compiler cache (content-verified) + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-shadow-ubuntu-latest-gcc-${{ github.ref }}-${{ github.sha }} + restore-keys: | + ccache-shadow-ubuntu-latest-gcc-${{ github.ref }}- + ccache-shadow-ubuntu-latest-gcc- - name: Build the binary from this checkout (download failed) if: ${{ steps.release.outcome == 'failure' }} timeout-minutes: 20 + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 1500M run: | - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache scripts/build.sh CC=gcc CXX=g++ mkdir -p "$RUNNER_TEMP/cbm-bin" cp build/c/codebase-memory-mcp "$RUNNER_TEMP/cbm-bin/" @@ -349,8 +373,11 @@ jobs: - name: Build this checkout's engine if: ${{ steps.release.outcome != 'failure' }} timeout-minutes: 20 + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 1500M run: | - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache scripts/build.sh CC=gcc CXX=g++ - name: Select with the team artifact (engine shadow) env: diff --git a/.github/workflows/test-impact-artifact.yml b/.github/workflows/test-impact-artifact.yml index a0a53061c5..6fb1c2a007 100644 --- a/.github/workflows/test-impact-artifact.yml +++ b/.github/workflows/test-impact-artifact.yml @@ -46,13 +46,25 @@ jobs: - name: Install build deps and LLVM 21 (coverage toolchain) timeout-minutes: 10 run: | - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang-21 llvm-21 libclang-rt-21-dev + - name: Compiler cache (content-verified) + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-impact-ubuntu-24.04-${{ github.ref }}-${{ github.sha }} + restore-keys: | + ccache-impact-ubuntu-24.04-${{ github.ref }}- + ccache-impact-ubuntu-24.04- + - name: Build the production binary and the coverage runner + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 2500M run: | scripts/build.sh CC=gcc CXX=g++ make -f Makefile.cbm test-runner-cov COV_LLVM_BIN=/usr/lib/llvm-21/bin -j"$(nproc)" diff --git a/Makefile.cbm b/Makefile.cbm index 6fcc6aef7d..900b33e14d 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -1058,15 +1058,57 @@ PP_OBJ_TSAN = $(BUILD_DIR)/tsan_preprocessor.o # ── Targets ────────────────────────────────────────────────────── -.PHONY: test-coverage-flush test test-par test-repro test-foundation test-tsan test-daemon-smoke test-runner-cov cbm-cov cbm cbm-with-ui frontend embed clean-c lint lint-tidy lint-tidy-diff lint-cppcheck lint-format security fuzz +.PHONY: test-coverage-flush test test-par test-repro test-foundation test-tsan test-daemon-smoke test-runner-cov cbm-cov cbm cbm-with-ui frontend embed clean-c lint lint-tidy lint-tidy-diff lint-cppcheck lint-format security fuzz build-config-check test-build-config-check tsan-build-config-check $(BUILD_DIR): mkdir -p $(BUILD_DIR) +# ── First-party & test per-object compilation ──────────────────── +# Compile each C translation unit independently with -c -MMD -MP instead of +# passing hundreds of .c files to one $(CC) -o binary invocation. That lets +# `make -j` compile across all cores and lets content-verified ccache cache +# every unchanged TU across runs (multi-file -o binary bypasses ccache). +# Distinct object prefixes isolate compilation flag sets: +# t/ CFLAGS_TEST + -Itests -Itests/repro (test-runner, test-repro-runner, +# cbm-fuzz, test-foundation) +# i/ CFLAGS_IMAGE_PROBE + -Itests (test-runner-image-probe; no coverage) +# s/ CFLAGS_TSAN + -Itests -Itests/repro (test-runner-tsan + tsan probe) +# p/ CFLAGS_PROD (codebase-memory-mcp, cbm-with-ui) +CORE_C_SRCS = $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) +CORE_C_SRCS_WITH_ASSETS = $(PROD_SRCS_WITH_ASSETS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) + +TEST_CORE_OBJS = $(patsubst %.c,$(BUILD_DIR)/t/%.o,$(CORE_C_SRCS)) +TEST_SUITE_OBJS = $(patsubst %.c,$(BUILD_DIR)/t/%.o,$(ALL_TEST_SRCS)) +TEST_RUNNER_OBJS = $(TEST_SUITE_OBJS) $(TEST_CORE_OBJS) +TEST_FOUNDATION_OBJS = $(patsubst %.c,$(BUILD_DIR)/t/%.o,$(TEST_FOUNDATION_SRCS) $(FOUNDATION_SRCS)) +TEST_REPRO_OBJS = $(patsubst %.c,$(BUILD_DIR)/t/%.o,$(TEST_REPRO_SRCS)) $(TEST_CORE_OBJS) +FUZZ_OBJ = $(patsubst %.c,$(BUILD_DIR)/t/%.o,$(FUZZ_SRC)) + +IMAGE_PROBE_TEST_OBJS = $(patsubst %.c,$(BUILD_DIR)/i/%.o,$(IMAGE_PROBE_SRCS)) +IMAGE_PROBE_TSAN_OBJS = $(patsubst %.c,$(BUILD_DIR)/s/%.o,$(IMAGE_PROBE_SRCS)) +TSAN_RUNNER_OBJS = $(patsubst %.c,$(BUILD_DIR)/s/%.o,$(ALL_TEST_SRCS) $(CORE_C_SRCS)) + +PROD_BIN_OBJS = $(patsubst %.c,$(BUILD_DIR)/p/%.o,$(MAIN_SRC) $(CORE_C_SRCS)) +PROD_UI_BIN_OBJS = $(patsubst %.c,$(BUILD_DIR)/p/%.o,$(MAIN_SRC) $(CORE_C_SRCS_WITH_ASSETS)) + +TEST_BUILD_CONFIG_SIG := SANITIZE=$(SANITIZE)|TEST_COVERAGE=$(TEST_COVERAGE)|CXX_STDLIB_FLAGS=$(CXX_STDLIB_FLAGS) +test-build-config-check: +$(BUILD_DIR)/.test-build-config: test-build-config-check | $(BUILD_DIR) + @printf '%s\n' '$(TEST_BUILD_CONFIG_SIG)' > $@.tmp + @if cmp -s $@.tmp $@; then rm -f $@.tmp; \ + else mv -f $@.tmp $@; rm -f $(BUILD_DIR)/test-runner $(BUILD_DIR)/test-runner-image-probe; fi + +TSAN_BUILD_CONFIG_SIG := TSAN_SANITIZE=$(TSAN_SANITIZE) +tsan-build-config-check: +$(BUILD_DIR)/.tsan-build-config: tsan-build-config-check | $(BUILD_DIR) + @printf '%s\n' '$(TSAN_BUILD_CONFIG_SIG)' > $@.tmp + @if cmp -s $@.tmp $@; then rm -f $@.tmp; \ + else mv -f $@.tmp $@; rm -f $(BUILD_DIR)/test-runner-tsan $(BUILD_DIR)/test-runner-tsan-image-probe; fi + # ── Foundation-only test (fast, no extraction) ─────────────────── -$(BUILD_DIR)/test-foundation: $(TEST_FOUNDATION_SRCS) $(FOUNDATION_SRCS) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_TEST) -o $@ $(TEST_FOUNDATION_SRCS) $(FOUNDATION_SRCS) $(LDFLAGS_TEST) +$(BUILD_DIR)/test-foundation: $(TEST_FOUNDATION_OBJS) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) $(TEST_COVERAGE_FLAGS) -o $@ $(TEST_FOUNDATION_OBJS) $(LDFLAGS_TEST) test-foundation: $(BUILD_DIR)/test-foundation cd "$(CURDIR)" && $(BUILD_DIR)/test-foundation @@ -1241,18 +1283,17 @@ IMAGE_PROBE_SRCS = tests/image_probe_main.c tests/image_probe_roles.c \ CFLAGS_IMAGE_PROBE = $(filter-out $(TEST_COVERAGE_FLAGS) $(TEST_COVERAGE_DEFINE),$(CFLAGS_TEST)) # TRE_OBJ_* is empty except on Windows, where compat_regex.c is backed by TRE. -$(BUILD_DIR)/test-runner-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) $(TRE_OBJ_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_IMAGE_PROBE) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) \ +$(BUILD_DIR)/test-runner-image-probe: $(IMAGE_PROBE_TEST_OBJS) $(MIMALLOC_OBJ_TEST) $(TRE_OBJ_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) -o $@ $(IMAGE_PROBE_TEST_OBJS) $(MIMALLOC_OBJ_TEST) \ $(TRE_OBJ_TEST) $(LDFLAGS_TEST) -$(BUILD_DIR)/test-runner-tsan-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_TSAN) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) \ +$(BUILD_DIR)/test-runner-tsan-image-probe: $(IMAGE_PROBE_TSAN_OBJS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) -o $@ $(IMAGE_PROBE_TSAN_OBJS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) \ $(LDFLAGS_TSAN) -$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-image-probe - $(CC) $(CFLAGS_TEST) -Itests -Itests/repro -o $@ \ - $(ALL_TEST_SRCS) $(PROD_SRCS) \ - $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ +$(BUILD_DIR)/test-runner: $(TEST_RUNNER_OBJS) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-image-probe + $(CC) $(TEST_COVERAGE_FLAGS) -o $@ \ + $(TEST_RUNNER_OBJS) \ $(OBJS_VENDORED_TEST) \ $(LDFLAGS_TEST) @@ -1277,10 +1318,9 @@ test-focused: $(BUILD_DIR)/test-runner # Mirrors test-runner's link line but uses repro_main.c (own main + counters) # and TEST_REPRO_SRCS instead of ALL_TEST_SRCS. Exits non-zero while any bug is # still reproduced (the expected state); bug-repro.yml surfaces it as a board. -$(BUILD_DIR)/test-repro-runner: $(TEST_REPRO_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_TEST) -Itests -o $@ \ - $(TEST_REPRO_SRCS) $(PROD_SRCS) \ - $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ +$(BUILD_DIR)/test-repro-runner: $(TEST_REPRO_OBJS) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) $(TEST_COVERAGE_FLAGS) -o $@ \ + $(TEST_REPRO_OBJS) \ $(OBJS_VENDORED_TEST) \ $(LDFLAGS_TEST) @@ -1337,10 +1377,9 @@ TSAN_OPTIONS ?= halt_on_error=1:report_thread_leaks=0 # Normal ASan/native/soak paths remain uncapped. High-worker TSan diagnostics # invoke test-runner-tsan directly so release gates cannot drift accidentally. -$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-tsan-image-probe - $(CC) $(CFLAGS_TSAN) -Itests -Itests/repro -o $@ \ - $(ALL_TEST_SRCS) $(PROD_SRCS) \ - $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ +$(BUILD_DIR)/test-runner-tsan: $(TSAN_RUNNER_OBJS) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-tsan-image-probe + $(CC) -o $@ \ + $(TSAN_RUNNER_OBJS) \ $(OBJS_VENDORED_TSAN) \ $(LDFLAGS_TSAN) @@ -1434,10 +1473,9 @@ $(BUILD_DIR)/.build-config: build-config-check | $(BUILD_DIR) else mv -f $@.tmp $@; rm -f $(BUILD_DIR)/codebase-memory-mcp; \ echo "=== build config changed -> full rebuild: $(BUILD_CONFIG_SIG) ==="; fi -$(BUILD_DIR)/codebase-memory-mcp: $(MAIN_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_PROD) $(BUILD_DIR)/.build-config $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_PROD) -o $@ \ - $(MAIN_SRC) $(PROD_SRCS) \ - $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ +$(BUILD_DIR)/codebase-memory-mcp: $(PROD_BIN_OBJS) $(OBJS_VENDORED_PROD) $(BUILD_DIR)/.build-config $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) $(TEST_COVERAGE_FLAGS) -o $@ \ + $(PROD_BIN_OBJS) \ $(OBJS_VENDORED_PROD) \ $(LDFLAGS) @@ -1462,10 +1500,10 @@ frontend: embed: frontend scripts/embed-frontend.sh graph-ui/dist $(BUILD_DIR)/embedded -cbm-with-ui: embed $(OBJS_VENDORED_PROD) - $(CC) $(CFLAGS_PROD) -o $(BUILD_DIR)/codebase-memory-mcp \ - $(MAIN_SRC) $(PROD_SRCS_WITH_ASSETS) \ - $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ +cbm-with-ui: embed $(OBJS_VENDORED_PROD) $(filter-out $(BUILD_DIR)/p/src/ui/embedded_assets.o,$(PROD_UI_BIN_OBJS)) | $(BUILD_DIR)/p/src/ui + $(CC) $(CFLAGS_PROD) -MMD -MP -MF $(BUILD_DIR)/p/src/ui/embedded_assets.d -c -o $(BUILD_DIR)/p/src/ui/embedded_assets.o src/ui/embedded_assets.c + $(CC) $(TEST_COVERAGE_FLAGS) -o $(BUILD_DIR)/codebase-memory-mcp \ + $(PROD_UI_BIN_OBJS) \ $(OBJS_VENDORED_PROD) \ $(wildcard $(BUILD_DIR)/embedded/embed_*.o) \ $(LDFLAGS) @@ -1484,6 +1522,7 @@ CLANG_TIDY ?= $(shell [ -x "$(LLVM_BIN)/clang-tidy" ] && echo "$(LLVM_BIN)/clang CLANG_FORMAT ?= $(shell [ -x "$(LLVM_BIN)/clang-format" ] && echo "$(LLVM_BIN)/clang-format" || echo clang-format) CPPCHECK ?= cppcheck CPPCHECK_JOBS ?= 2 +CPPCHECK_BUILD_DIR ?= # macOS SDK sysroot (needed for Homebrew LLVM to find system headers) SYSROOT = $(shell xcrun --show-sdk-path 2>/dev/null) @@ -1509,13 +1548,21 @@ lint-tidy-diff: @scripts/lint-tidy-diff.sh "$(CLANG_TIDY)" $(LINT_SRCS) -- $(CFLAGS_COMMON) $(SYSROOT_FLAG) # cppcheck: complementary analysis (config in .cppcheck). A build directory -# retains whole-program analysis with parallel workers; each run owns its state. +# retains whole-program analysis with parallel workers. When CPPCHECK_BUILD_DIR +# is unset each run uses a fresh temp dir; CI passes a persistent cached dir +# keyed on .cppcheck + Makefile.cbm so cppcheck re-analyzes only changed TUs +# (verified by cppcheck's own source + header hashes) plus full CTU analysis. lint-cppcheck: @echo "=== cppcheck ===" @set -e; \ - cppcheck_dir=$$(mktemp -d "$${TMPDIR:-/tmp}/cbm-cppcheck.XXXXXX"); \ - trap 'status=$$?; rm -rf "$$cppcheck_dir" || :; exit "$$status"' EXIT; \ - trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM; \ + if [ -n "$(CPPCHECK_BUILD_DIR)" ]; then \ + cppcheck_dir="$(CPPCHECK_BUILD_DIR)"; \ + mkdir -p "$$cppcheck_dir"; \ + else \ + cppcheck_dir=$$(mktemp -d "$${TMPDIR:-/tmp}/cbm-cppcheck.XXXXXX"); \ + trap 'status=$$?; rm -rf "$$cppcheck_dir" || :; exit "$$status"' EXIT; \ + trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM; \ + fi; \ $(CPPCHECK) -j$(CPPCHECK_JOBS) --cppcheck-build-dir="$$cppcheck_dir" \ --enable=warning,style,performance,portability \ --std=c11 --language=c \ @@ -1737,10 +1784,9 @@ fuzz: # Linux leaves out UBSan's C++ runtime, but the C++ objects (preprocessor, # simplecpp) carry -fsanitize=vptr checks that need it # (__ubsan_vptr_type_cache, __ubsan_handle_dynamic_type_cache_miss). -$(BUILD_DIR)/cbm-fuzz: $(FUZZ_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_TEST) -fsanitize=fuzzer -fsanitize-link-c++-runtime -o $@ \ - $(FUZZ_SRC) $(PROD_SRCS) \ - $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ +$(BUILD_DIR)/cbm-fuzz: $(FUZZ_OBJ) $(TEST_CORE_OBJS) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) $(TEST_COVERAGE_FLAGS) -fsanitize=fuzzer -fsanitize-link-c++-runtime -o $@ \ + $(FUZZ_OBJ) $(TEST_CORE_OBJS) \ $(OBJS_VENDORED_TEST) \ $(LDFLAGS_TEST) @@ -1785,3 +1831,27 @@ security: cbm scripts/security-fuzz.sh $(BUILD_DIR)/codebase-memory-mcp scripts/security-vendored.sh @echo "=== All security checks passed ===" + +# Placed after .SECONDEXPANSION and every *_SRCS definition so $$(@D), +# all object paths, and depfiles expand accurately. +ALL_FIRST_PARTY_OBJS = $(sort $(TEST_RUNNER_OBJS) $(TEST_REPRO_OBJS) $(FUZZ_OBJ) \ + $(IMAGE_PROBE_TEST_OBJS) $(TSAN_RUNNER_OBJS) \ + $(PROD_BIN_OBJS) $(PROD_UI_BIN_OBJS)) +OBJ_SUBDIRS = $(patsubst %/,%,$(sort $(dir $(ALL_FIRST_PARTY_OBJS)))) + +$(OBJ_SUBDIRS): + @mkdir -p $@ + +$(BUILD_DIR)/t/%.o: %.c $(BUILD_DIR)/.test-build-config | $$(@D) + $(CC) $(CFLAGS_TEST) -Itests -Itests/repro -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + +$(BUILD_DIR)/i/%.o: %.c $(BUILD_DIR)/.test-build-config | $$(@D) + $(CC) $(CFLAGS_IMAGE_PROBE) -Itests -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + +$(BUILD_DIR)/s/%.o: %.c $(BUILD_DIR)/.tsan-build-config | $$(@D) + $(CC) $(CFLAGS_TSAN) -Itests -Itests/repro -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + +$(BUILD_DIR)/p/%.o: %.c $(BUILD_DIR)/.build-config | $$(@D) + $(CC) $(CFLAGS_PROD) -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + +-include $(ALL_FIRST_PARTY_OBJS:.o=.d) diff --git a/scripts/lint.sh b/scripts/lint.sh index b2220af673..fe300b1ef0 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -61,6 +61,17 @@ print_env "lint.sh" echo "=== no-skips policy (tests pass or fail) ===" bash "$ROOT/scripts/check-no-test-skips.sh" +# Default cppcheck parallelism to all detected CPU cores unless overridden. +HAS_CPPCHECK_JOBS=false +for arg in "${MAKE_ARGS[@]+"${MAKE_ARGS[@]}"}"; do + case "$arg" in + CPPCHECK_JOBS=*) HAS_CPPCHECK_JOBS=true ;; + esac +done +if ! $HAS_CPPCHECK_JOBS; then + MAKE_ARGS+=("CPPCHECK_JOBS=$NPROC") +fi + if $CI_ONLY; then echo "=== CI mode: cppcheck + clang-format ===" make -j2 -f Makefile.cbm lint-ci "${MAKE_ARGS[@]+"${MAKE_ARGS[@]}"}" diff --git a/tests/test_language_count_contract.sh b/tests/test_language_count_contract.sh index 93d171d6fc..946719fb12 100644 --- a/tests/test_language_count_contract.sh +++ b/tests/test_language_count_contract.sh @@ -120,7 +120,12 @@ while IFS= read -r path; do "SURFACES so it stays in step with the registry, or to EXEMPT with a" \ "note saying what its number actually counts." >&2 failures=$((failures + 1)) -done < <(git grep -IlE '[0-9]{2,3} languages|languages-[0-9]{2,3}' || true) +# Generated tree-sitter parser.c tables (~1.5 GB across 164 grammars) never +# carry product-count prose; skipping them cuts this scan ~20x on Windows while +# still checking MANIFEST.md, docs, manifests, scripts, and all source files. +done < <(git grep -IlE '[0-9]{2,3} languages|languages-[0-9]{2,3}' -- \ + ':(glob,exclude)internal/cbm/vendored/grammars/**/parser.c' \ + ':(glob,exclude)tools/**/parser.c' || true) if ((failures > 0)); then echo "FAIL: $failures language-count contract violation(s)" >&2 From 2a2218e7f96161792c70b4be1a4a3fd2e3e964ee Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sat, 5 Dec 2026 23:14:00 +0100 Subject: [PATCH 02/11] perf(ci): parallelize contracts/msan/tsan, LPT shard all legs, fix smoke Phase 15 hang Follow-up CI speed optimizations targeting ~10-15 min end-to-end wall time with zero quality or coverage reduction: - scripts/smoke-test.sh: fix Phase 15 300 s hang on non-UI PR smoke builds (track and kill stdin-holder sleep PID; use a 30 s wall-clock deadline with bounded curl timeouts so Windows refuses don't turn 150 iterations into 300 s) - Makefile.cbm: consolidate 4 compiler -dM -E probes into 1 CC_DEFINES probe and make LLVM_BIN lazy (4x faster make startup on Windows Step 0f/0z1); run non-daemon and daemon TSan suites concurrently in test-tsan - scripts/test.sh + tests/test_{makefile_ts_runtime_dependencies,codeql_retrace,security_fuzz_harness}.sh: run all 46 Step 0 contract scripts in parallel (LPT order, isolated process groups, deterministic canonical output, CBM_CONTRACTS_SEQUENTIAL=1 fallback) and parallelize slow Windows contract internals - scripts/msan.sh + scripts/ci/msan-lane.sh: run MSan suites in parallel via run-test-wave.py with union guard and wire content-verified ccache - scripts/run-tests-parallel.sh + tests/test_{c_lsp,doc_mentions,test_impact_git,java_type_scope,main}.c: split the 4 heaviest parallel suites in half (matching pipeline_b) and use deterministic LPT bin-packing with separate PAR/FLEX/EXCL sharding - .github/workflows/_test.yml + _lint.yml + scripts/ci/require-all-green.sh: wire inputs.skip_perf to diag/lsan-macos/msan (matching unix/windows), shard unix/windows/diag/lsan-macos with full verify-shard-union proofs, cache MSan ccache, and add .cppcheck-scoped fallback key for cppcheck-build Signed-off-by: Guillaume Demay --- .github/workflows/_lint.yml | 16 +- .github/workflows/_test.yml | 98 ++++-- Makefile.cbm | 41 ++- scripts/ci/msan-lane.sh | 8 +- scripts/ci/require-all-green.sh | 4 + scripts/msan.sh | 85 ++++- scripts/run-tests-parallel.sh | 169 ++++++---- scripts/smoke-test.sh | 53 +++- scripts/test.sh | 292 ++++++++---------- tests/test_c_lsp.c | 5 + tests/test_codeql_retrace.sh | 6 +- tests/test_doc_mentions.c | 5 + tests/test_java_type_scope.c | 5 + tests/test_main.c | 8 + .../test_makefile_ts_runtime_dependencies.sh | 69 +++-- tests/test_security_fuzz_harness.sh | 42 ++- tests/test_test_impact_git.c | 5 + 17 files changed, 602 insertions(+), 309 deletions(-) diff --git a/.github/workflows/_lint.yml b/.github/workflows/_lint.yml index 72d7f7bacd..550aa86940 100644 --- a/.github/workflows/_lint.yml +++ b/.github/workflows/_lint.yml @@ -65,18 +65,20 @@ jobs: - name: Add cppcheck to PATH run: echo "/opt/cppcheck/bin" >> "$GITHUB_PATH" - # Incremental cppcheck build directory: keyed on .cppcheck + Makefile.cbm - # (which lists LINT_SRCS and all flags), so any config/file-list change - # starts clean while unchanged TUs reuse verified .a1/.ctu-info state and - # cppcheck still runs full whole-program CTU analysis. + # Incremental cppcheck build directory: primary key pins both .cppcheck + # and Makefile.cbm, with a .cppcheck-scoped fallback so unrelated + # Makefile.cbm edits keep warm .a1/.ctu-info state (cppcheck hashes each + # TU's source, headers, and flags internally) while .cppcheck changes + # start clean and whole-program CTU analysis always runs. - name: cppcheck analysis cache uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ github.workspace }}/.cppcheck-build - key: cppcheck-build-2.20.0-${{ hashFiles('.cppcheck', 'Makefile.cbm') }}-${{ github.ref }}-${{ github.sha }} + key: cppcheck-build-2.20.0-${{ hashFiles('.cppcheck') }}-${{ hashFiles('Makefile.cbm') }}-${{ github.ref }}-${{ github.sha }} restore-keys: | - cppcheck-build-2.20.0-${{ hashFiles('.cppcheck', 'Makefile.cbm') }}-${{ github.ref }}- - cppcheck-build-2.20.0-${{ hashFiles('.cppcheck', 'Makefile.cbm') }}- + cppcheck-build-2.20.0-${{ hashFiles('.cppcheck') }}-${{ hashFiles('Makefile.cbm') }}-${{ github.ref }}- + cppcheck-build-2.20.0-${{ hashFiles('.cppcheck') }}-${{ hashFiles('Makefile.cbm') }}- + cppcheck-build-2.20.0-${{ hashFiles('.cppcheck') }}- - name: Lint (cppcheck + clang-format, no clang-tidy — enforced locally) run: scripts/lint.sh --ci CLANG_FORMAT=clang-format-20 CPPCHECK_BUILD_DIR="${{ github.workspace }}/.cppcheck-build" diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index 4285d5f3a5..d0fc918ee2 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -47,6 +47,8 @@ jobs: unix: ${{ steps.set.outputs.unix }} windows: ${{ steps.set.outputs.windows }} tsan: ${{ steps.set.outputs.tsan }} + diag: ${{ steps.set.outputs.diag }} + lsan: ${{ steps.set.outputs.lsan }} has_unix: ${{ steps.set.outputs.has_unix }} has_windows: ${{ steps.set.outputs.has_windows }} has_tsan: ${{ steps.set.outputs.has_tsan }} @@ -121,36 +123,45 @@ jobs: fi # Suite sharding (opt-in via the shard_suites input): each platform's # C-suite run is split across N runner jobs. CBM_TEST_SHARD="i/N" - # slices deterministically inside run-tests-parallel.sh; each - # shard's union guard proves it ran exactly its slice; shards are - # minted HERE from one expansion so a missing shard cannot be - # configured silently; and the shard-completeness job re-proves the - # cross-shard union at runtime. Ubuntu runners are plentiful (3 - # shards); Windows gets 2 (every extra shard re-pays ~5 min of - # MSYS2 setup); macOS stays at 1 — mac legs are not the critical - # path and mac runner concurrency ceilings are the tightest. - # The pr profile shards less: a PR runs few legs and every shard - # re-pays its setup, so x86 and Windows run whole and only arm64, - # the slowest leg (~72 min unsharded), splits in two. + # slices deterministically via LPT bin-packing inside + # run-tests-parallel.sh; each shard's union guard proves it ran + # exactly its slice; shards are minted HERE from one expansion so a + # missing shard cannot be configured silently; and the + # shard-completeness job re-proves the cross-shard union at runtime. + # With per-object ccache builds (~1 min warm) and parallel Step 0 + # contracts (<1 min), per-shard setup overhead is small, so sharding + # Windows (x4), Ubuntu x86/arm64, macOS, diag, and lsan-macos keeps + # every leg near ~10 min while respecting GitHub's 20 total / 5 macOS + # concurrent runner limits. case "$SHARD_PROFILE" in - standard) N_X86=3; N_ARM=3; N_WIN=2 ;; - pr) N_X86=1; N_ARM=2; N_WIN=1 ;; + standard) N_X86=3; N_ARM=3; N_MAC=2; N_MAC_INTEL=4; N_WIN=4; N_DIAG=2; N_LSAN=2 ;; + pr) N_X86=2; N_ARM=3; N_MAC=2; N_MAC_INTEL=4; N_WIN=4; N_DIAG=2; N_LSAN=2 ;; *) echo "::error::unknown shard_profile '$SHARD_PROFILE'"; exit 1 ;; esac if [ "$SHARDS" = "true" ]; then - UNIX=$(jq -c --argjson x86 "$N_X86" --argjson arm "$N_ARM" '[.[] | . as $e + UNIX=$(jq -c --argjson x86 "$N_X86" --argjson arm "$N_ARM" \ + --argjson mac "$N_MAC" --argjson mac_intel "$N_MAC_INTEL" '[.[] | . as $e | (if ($e.os | startswith("ubuntu")) then (if ($e.os | endswith("-arm")) then $arm else $x86 end) + elif ($e.os == "macos-15-intel") then $mac_intel + elif ($e.os | startswith("macos")) then $mac else 1 end) as $n | range(1; $n + 1) as $i | $e + {shard: "\($i)/\($n)"}]' <<< "$UNIX") WIN=$(jq -c --argjson n "$N_WIN" '[.[] | . as $e | range(1; $n + 1) as $i | $e + {shard: "\($i)/\($n)"}]' <<< "$WIN") + DIAG=$(jq -cn --argjson n "$N_DIAG" '[range(1; $n + 1) as $i | {shard: "\($i)/\($n)"}]') + LSAN=$(jq -cn --argjson n "$N_LSAN" '[range(1; $n + 1) as $i | {shard: "\($i)/\($n)"}]') + else + DIAG='[{"shard":"1/1"}]' + LSAN='[{"shard":"1/1"}]' fi echo "unix={\"include\":$UNIX}" >> "$GITHUB_OUTPUT" echo "windows={\"include\":$WIN}" >> "$GITHUB_OUTPUT" echo "tsan={\"include\":$TSAN}" >> "$GITHUB_OUTPUT" + echo "diag={\"include\":$DIAG}" >> "$GITHUB_OUTPUT" + echo "lsan={\"include\":$LSAN}" >> "$GITHUB_OUTPUT" # GitHub rejects an empty matrix, so a job whose legs were all # deselected is skipped through these flags instead. echo "has_unix=$(jq 'length > 0' <<< "$UNIX")" >> "$GITHUB_OUTPUT" @@ -369,7 +380,11 @@ jobs: # parallel suite — catches what an older compiler-rt can miss. Same # canonical scripts/test.sh wave as every other leg. test-diag: + needs: setup-matrix if: ${{ inputs.lanes == 'all' || contains(fromJSON(inputs.lanes), 'diag') }} + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.setup-matrix.outputs.diag) }} # Pinned for the same reason as the lint jobs: the pinned diagnostic # toolchain below installs from llvm-toolchain-noble-21. runs-on: ubuntu-24.04 @@ -405,25 +420,36 @@ jobs: - name: Test (clang-21, ASan+UBSan + off-by-default ASan checks) env: ASAN_OPTIONS: "detect_stack_use_after_return=1:strict_string_checks=1:detect_stack_use_after_scope=1" + CBM_TEST_SHARD: ${{ matrix.shard }} + CBM_TEST_LEG: diag-clang21 + CBM_SKIP_PERF: ${{ inputs.skip_perf && '1' || '' }} CCACHE_DIR: ${{ github.workspace }}/.ccache CCACHE_MAXSIZE: 2500M run: | scripts/test.sh CC=clang-21 CXX=clang++-21 \ SANITIZE="-fsanitize=address,undefined -fno-omit-frame-pointer -fno-optimize-sibling-calls" + - name: Shard manifest (completeness proof) + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: shard-manifest-diag-${{ strategy.job-index }} + path: build/c/test-logs/shard-manifest.txt + if-no-files-found: warn + # Same step as in test-unix: the complete logs of the suites that did # not end green, only when the job failed. - name: Failing suite logs if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: suite-logs-diag + name: suite-logs-diag-${{ strategy.job-index }} path: build/c/test-logs/failed/ retention-days: 7 if-no-files-found: warn - name: Compiler cache (save) - if: always() + if: always() && (matrix.shard == null || startsWith(matrix.shard, '1/')) uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ github.workspace }}/.ccache @@ -468,16 +494,35 @@ jobs: - name: Build MSan image (cached layers) run: scripts/ci/msan-lane.sh build + - name: Compiler cache (content-verified, restore) + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-msan-${{ github.ref }}-${{ github.sha }} + restore-keys: | + ccache-msan-${{ github.ref }}- + ccache-msan- + - name: MSan suite (exclusions per scripts/msan.sh) # Reduce mmap ASLR entropy on the host first, as the TSan leg does: with # the runner kernel's higher default the MSan runtime tries to re-exec # itself with ADDR_NO_RANDOMIZE, which the container's seccomp profile # refuses, and it aborts ("CHECK failed: msan_linux.cpp:193 ... # personality") before any test runs. The container shares this kernel. + env: + CBM_SKIP_PERF: ${{ inputs.skip_perf && '1' || '' }} + CCACHE_MAXSIZE: 2500M run: | sudo sysctl -w vm.mmap_rnd_bits=28 || true scripts/ci/msan-lane.sh run + - name: Compiler cache (save) + if: always() + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-msan-${{ github.ref }}-${{ github.sha }} + # macOS leak coverage. LeakSanitizer runs by default under ASan on Linux, so # test-unix's ubuntu legs have always had it; on macOS it is off by default # and Apple's clang refuses to turn it on, which left an entire platform with @@ -485,7 +530,11 @@ jobs: # so this leg is the ordinary ASan suite built with that toolchain and run # with detect_leaks=1. Mirrors the local `make -f Makefile.cbm test-lsan`. test-lsan-macos: + needs: setup-matrix if: ${{ inputs.lanes == 'all' || contains(fromJSON(inputs.lanes), 'lsan-macos') }} + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.setup-matrix.outputs.lsan) }} runs-on: macos-latest timeout-minutes: 120 steps: @@ -512,6 +561,9 @@ jobs: - name: Test (Homebrew clang, ASan + LeakSanitizer) env: ASAN_OPTIONS: "detect_leaks=1:halt_on_error=1" + CBM_TEST_SHARD: ${{ matrix.shard }} + CBM_TEST_LEG: lsan-macos-clang22 + CBM_SKIP_PERF: ${{ inputs.skip_perf && '1' || '' }} CCACHE_DIR: ${{ github.workspace }}/.ccache CCACHE_MAXSIZE: 2500M run: | @@ -519,19 +571,27 @@ jobs: export PATH="$LLVM_PREFIX/bin:$PATH" scripts/test.sh CC=clang CXX=clang++ + - name: Shard manifest (completeness proof) + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: shard-manifest-lsan-macos-${{ strategy.job-index }} + path: build/c/test-logs/shard-manifest.txt + if-no-files-found: warn + # Same step as in test-unix: the complete logs of the suites that did # not end green, only when the job failed. - name: Failing suite logs if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: suite-logs-lsan-macos + name: suite-logs-lsan-macos-${{ strategy.job-index }} path: build/c/test-logs/failed/ retention-days: 7 if-no-files-found: warn - name: Compiler cache (save) - if: always() + if: always() && (matrix.shard == null || startsWith(matrix.shard, '1/')) uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ github.workspace }}/.ccache @@ -736,7 +796,7 @@ jobs: # catches it. Runs and gates on unsharded topologies too (every leg then # contributes one 1/1 manifest whose slice must equal the full list). shard-completeness: - needs: [test-unix, test-windows] + needs: [test-unix, test-windows, test-diag, test-lsan-macos] if: always() runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/Makefile.cbm b/Makefile.cbm index 900b33e14d..a791671f83 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -29,7 +29,11 @@ # Detected from the compiler's target, not the host, so a cross compiler run # on a Mac is left untouched. MACOS_MIN_VERSION := 14.0 -IS_APPLE_TARGET := $(shell echo | $(CC) $(ARCHFLAGS) -dM -E - 2>/dev/null | grep -q '__APPLE__' && echo yes || echo no) +# Probe target/compiler predefined macros ONCE per make invocation instead of +# running 4 separate preprocessor subshells (noticeable on Windows MSYS2, where +# each clang startup costs seconds and Step 0f/0z1 invoke make >25 times). +CC_DEFINES := $(shell echo | $(CC) $(ARCHFLAGS) -dM -E - 2>/dev/null) +IS_APPLE_TARGET := $(if $(filter __APPLE__,$(CC_DEFINES)),yes,no) MACOS_MIN_FLAGS := ifeq ($(IS_APPLE_TARGET),yes) MACOS_MIN_FLAGS := -mmacosx-version-min=$(MACOS_MIN_VERSION) @@ -52,7 +56,7 @@ TS_SRC = $(CBM_DIR)/vendored/ts_runtime/src # GCC-only warning suppressions (Clang rejects unknown -Wno-* with -Werror). # Detect GCC by checking for __GNUC__ without __clang__ — handles all versions. -IS_GCC := $(shell echo | $(CC) -dM -E - 2>/dev/null | grep -q '__GNUC__' && ! echo | $(CC) -dM -E - 2>/dev/null | grep -q '__clang__' && echo yes || echo no) +IS_GCC := $(if $(and $(filter __GNUC__,$(CC_DEFINES)),$(if $(filter __clang__,$(CC_DEFINES)),,yes)),yes,no) GCC_ONLY_FLAGS := ifeq ($(IS_GCC),yes) GCC_ONLY_FLAGS := -Wno-format-truncation -Wno-unused-result \ @@ -171,7 +175,7 @@ CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -DCBM_SANITIZED_BUILD=1 -g -O1 \ # advapi32 (owner-only activation-candidate ACLs), plus # --allow-multiple-definition (MinGW CRT symbol clashes). # Auto-detected via compiler; no manual override needed. -IS_MINGW := $(shell echo | $(CC) -dM -E - 2>/dev/null | grep -q 'define _WIN32 ' && echo yes || echo no) +IS_MINGW := $(if $(filter _WIN32,$(CC_DEFINES)),yes,no) WIN32_LIBS := # Route Windows allocations through mimalloc (#581). mimalloc's own static # override is gated on _MSC_VER, which clang/MinGW never defines, so it @@ -1385,8 +1389,32 @@ $(BUILD_DIR)/test-runner-tsan: $(TSAN_RUNNER_OBJS) $(OBJS_VENDORED_TSAN) $(PROJE test-tsan: $(BUILD_DIR)/test-runner-tsan @echo "ThreadSanitizer workers: 4" - cd $(CURDIR) && CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ - $(BUILD_DIR)/test-runner-tsan $(TEST_TSAN_SUITES) + @cd $(CURDIR) && set -e; \ + daemon_suites=""; other_suites=""; \ + for s in $(TEST_TSAN_SUITES); do \ + case "$$s" in \ + mcp|daemon|daemon_*) daemon_suites="$$daemon_suites $$s" ;; \ + *) other_suites="$$other_suites $$s" ;; \ + esac; \ + done; \ + if [ -n "$$daemon_suites" ] && [ -n "$$other_suites" ]; then \ + tmpdir=$$(mktemp -d "$${TMPDIR:-/tmp}/cbm-tsan.XXXXXX"); \ + trap 'rm -rf "$$tmpdir"' EXIT; \ + CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ + $(BUILD_DIR)/test-runner-tsan $$other_suites >"$$tmpdir/other.log" 2>&1 & \ + pid_other=$$!; \ + CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ + $(BUILD_DIR)/test-runner-tsan $$daemon_suites >"$$tmpdir/daemon.log" 2>&1 & \ + pid_daemon=$$!; \ + rc1=0; rc2=0; \ + wait "$$pid_other" || rc1=$$?; \ + wait "$$pid_daemon" || rc2=$$?; \ + cat "$$tmpdir/other.log" "$$tmpdir/daemon.log"; \ + [ "$$rc1" -eq 0 ] && [ "$$rc2" -eq 0 ]; \ + else \ + CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ + $(BUILD_DIR)/test-runner-tsan $(TEST_TSAN_SUITES); \ + fi # Real-binary POSIX lifecycle smoke. The endpoint is deliberately account-wide; # an explicit Make invocation requires a clean rendezvous and fails rather than @@ -1517,7 +1545,8 @@ clean-c: # clang-tidy and clang-format: use Homebrew LLVM on macOS, overridable via make args # e.g. make lint-format CLANG_FORMAT=clang-format-18 -LLVM_BIN := $(shell brew --prefix llvm 2>/dev/null)/bin +# Lazy (=) so `brew --prefix` is only invoked by lint/diag targets, not every build. +LLVM_BIN = $(shell brew --prefix llvm 2>/dev/null)/bin CLANG_TIDY ?= $(shell [ -x "$(LLVM_BIN)/clang-tidy" ] && echo "$(LLVM_BIN)/clang-tidy" || echo clang-tidy) CLANG_FORMAT ?= $(shell [ -x "$(LLVM_BIN)/clang-format" ] && echo "$(LLVM_BIN)/clang-format" || echo clang-format) CPPCHECK ?= cppcheck diff --git a/scripts/ci/msan-lane.sh b/scripts/ci/msan-lane.sh index c8e4f3a101..bcc897c0c2 100755 --- a/scripts/ci/msan-lane.sh +++ b/scripts/ci/msan-lane.sh @@ -47,7 +47,13 @@ run_suite() { # Only `cli` is still excluded, and scripts/msan.sh warns that the lane is # partial while anything is. echo "=== MSan suite (exclusions per scripts/msan.sh) ===" - docker run --rm -v "$PWD:/src" -w /src "$IMAGE" + env_args=() + [ -n "${CBM_SKIP_PERF:-}" ] && env_args+=(-e "CBM_SKIP_PERF=$CBM_SKIP_PERF") + [ -n "${CBM_MSAN_JOBS:-}" ] && env_args+=(-e "CBM_MSAN_JOBS=$CBM_MSAN_JOBS") + [ -n "${CCACHE_MAXSIZE:-}" ] && env_args+=(-e "CCACHE_MAXSIZE=$CCACHE_MAXSIZE") + [ -n "${CBM_NO_CCACHE:-}" ] && env_args+=(-e "CBM_NO_CCACHE=$CBM_NO_CCACHE") + docker run --rm -v "$PWD:/src" -w /src -e "CCACHE_DIR=/src/.ccache" \ + "${env_args[@]+"${env_args[@]}"}" "$IMAGE" } case "$MODE" in diff --git a/scripts/ci/require-all-green.sh b/scripts/ci/require-all-green.sh index 149eef2dab..db6713952e 100755 --- a/scripts/ci/require-all-green.sh +++ b/scripts/ci/require-all-green.sh @@ -76,6 +76,10 @@ if 'LANES' in os.environ: def lane_of(name): if name in single: return single[name] + if name.startswith('test / test-diag ('): + return 'diag' + if name.startswith('test / test-lsan-macos ('): + return 'lsan-macos' if name.startswith('test / test-package-wrappers'): return 'pkg-wrappers' if name == 'memwaste' or name.startswith('memwaste / '): diff --git a/scripts/msan.sh b/scripts/msan.sh index 20bb8fafe7..e91823e776 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -51,6 +51,20 @@ MSAN_SAN="-fsanitize=memory $MSAN_ORIGIN_FLAG -fno-omit-frame-pointer -isystem $ # without _GNU_SOURCE and zstd loses qsort_r. ZSTD_EXTRA="-D_GNU_SOURCE -include stdint.h" +# Verified compiler cache (when ccache is installed in the image and not +# disabled): CCACHE_COMPILERCHECK=content keys every entry on compiler content +# plus preprocessed source, so stale hits are impossible by construction. +USE_CCACHE=0 +if [ "${CBM_NO_CCACHE:-0}" != "1" ] && command -v ccache >/dev/null 2>&1; then + USE_CCACHE=1 + export CCACHE_COMPILERCHECK=content + export CCACHE_DIR="${CCACHE_DIR:-$ROOT/.ccache}" + export CCACHE_MAXSIZE="${CCACHE_MAXSIZE:-2500M}" + if [ -d /usr/lib/ccache ]; then + export PATH="/usr/lib/ccache:$PATH" + fi +fi + # Always clean: make does not encode flags into dependencies, so a build dir # populated under different stdlib/sanitizer flags silently mixes objects # (observed: a stage-1 probe's libstdc++ objects surviving into the libc++ @@ -63,6 +77,9 @@ make -j"$(nproc)" -f Makefile.cbm build/msan/test-runner \ ZSTD_EXTRA_CFLAGS="$ZSTD_EXTRA" \ CXX_STDLIB_FLAGS="-stdlib=libc++ -nostdinc++ -isystem $MSAN_PREFIX/include/c++/v1" \ CXX_STDLIB="-L$MSAN_PREFIX/lib -Wl,-rpath,$MSAN_PREFIX/lib -lc++ -lc++abi" +if [ "$USE_CCACHE" -eq 1 ]; then + ccache -s || true +fi # fast_unwind_on_fatal=1: a report's stack is walked with frame pointers (this # build keeps them, -fno-omit-frame-pointer) instead of the default slow @@ -178,7 +195,28 @@ else echo "WARNING: running a PARTIAL sanitizer lane — excluded: $MSAN_EXCLUDE" >&2 echo "WARNING: a green result here does NOT mean the tree is MSan-clean." >&2 fi - fails="" + # Run the non-excluded suites in parallel via the canonical parent-owned + # wave scheduler (scripts/run-test-wave.py), keeping the exact same + # FLEX/EXCL tail isolation and union guard as scripts/run-tests-parallel.sh. + LOGDIR="build/msan/test-logs" + rm -rf "$LOGDIR" + mkdir -p "$LOGDIR" + PAR_FILE="$LOGDIR/suites-parallel.txt" + FLEX_FILE="$LOGDIR/suites-tail-flex.txt" + EXCL_FILE="$LOGDIR/suites-tail-excl.txt" + EXPECT_FILE="$LOGDIR/suites-expect.txt" + RESULTS_FILE="$LOGDIR/results.txt" + : > "$PAR_FILE" + : > "$FLEX_FILE" + : > "$EXCL_FILE" + : > "$RESULTS_FILE" + SERIAL_SUITES="cli subprocess watcher incremental httpd ui index_resilience mcp \ + extraction \ + stack_overflow_a stack_overflow_b stack_overflow_c \ + index_supervisor daemon_application daemon_runtime daemon_frontend \ + daemon_bootstrap daemon_ipc" + TAIL_EXCL="cli mcp index_supervisor daemon_application daemon_runtime \ + daemon_frontend daemon_bootstrap daemon_ipc extraction" for suite in $all_suites; do case " $MSAN_EXCLUDE " in *" $suite "*) @@ -186,10 +224,51 @@ else continue ;; esac - echo "=== msan: $suite ===" - ./build/msan/test-runner "$suite" || fails="$fails $suite" + case " $SERIAL_SUITES " in + *" $suite "*) + case " $TAIL_EXCL " in + *" $suite "*) echo "$suite" >> "$EXCL_FILE" ;; + *) echo "$suite" >> "$FLEX_FILE" ;; + esac + ;; + *) echo "$suite" >> "$PAR_FILE" ;; + esac done + cat "$PAR_FILE" "$FLEX_FILE" "$EXCL_FILE" > "$EXPECT_FILE" + MSAN_JOBS="${CBM_MSAN_JOBS:-$(nproc)}" + echo "=== MSan parallel wave: $(wc -l < "$EXPECT_FILE" | tr -d ' ') suites, $MSAN_JOBS jobs ===" + run_msan_wave() { + local sfile="$1" jobs="$2" + python3 "$ROOT/scripts/run-test-wave.py" \ + --suite-file "$sfile" \ + --log-dir "$LOGDIR" \ + --results-file "$RESULTS_FILE" \ + --jobs "$jobs" \ + --timeout "${CBM_SUITE_TIMEOUT:-900}" \ + --slow-timeout "${CBM_SUITE_TIMEOUT_SLOW:-3600}" \ + --kill-grace 15 \ + ./build/msan/test-runner + } + run_msan_wave "$PAR_FILE" "$MSAN_JOBS" + run_msan_wave "$FLEX_FILE" "${CBM_TAIL_JOBS:-2}" + run_msan_wave "$EXCL_FILE" 1 + + # Union guard: every non-excluded suite produced exactly one result. + MISSING=$(comm -23 <(sort "$EXPECT_FILE") <(awk '{print $1}' "$RESULTS_FILE" | sort -u)) + EXTRA=$(comm -13 <(sort "$EXPECT_FILE") <(awk '{print $1}' "$RESULTS_FILE" | sort -u)) + DUPES=$(awk '{print $1}' "$RESULTS_FILE" | sort | uniq -d) + if [ -n "$MISSING" ] || [ -n "$EXTRA" ] || [ -n "$DUPES" ]; then + echo "FAIL: MSan suite union mismatch (missing=[$MISSING] extra=[$EXTRA] dupes=[$DUPES])" >&2 + exit 1 + fi + echo "── 8 slowest MSan suites ──" + sort -t '=' -k6,6 -rn "$RESULTS_FILE" | head -8 + fails=$(awk '$2 != "rc=0" { printf " %s", $1 }' "$RESULTS_FILE") if [ -n "$fails" ]; then + for f in $fails; do + echo "=== MSan failure log: $f ===" >&2 + tail -80 "$LOGDIR/$f.log" >&2 || true + done echo "=== MSan lane FAILED suites:$fails ===" >&2 exit 1 fi diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index b52c514122..2bcc794f2e 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -208,28 +208,92 @@ if [ -n "${CBM_TEST_SHARD:-}" ]; then fi fi -# Deal the known-heavy suites round-robin FIRST so no shard receives a -# second heavy suite before every shard holds one — shard wall time is -# bounded by its heaviest member, and naive modulo can stack store_arch and -# daemon_runtime (the two slowest sanitized suites) onto one job. +# Assign suites to shards by deterministic Longest-Processing-Time-First (LPT) +# greedy bin-packing using empirical cross-platform suite weights, and emit +# each shard's slice in descending weight order so run-test-wave.py starts the +# heaviest suites at t=0 rather than straggling on idle cores at wave end. +# Because PAR, FLEX, and EXCL are sharded separately below, heavy exclusive +# suites (cli, mcp, daemon_frontend, daemon_runtime, extraction) are also +# balanced independently across shards instead of stacking onto one job. shard_filter() { awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" ' BEGIN { - nh = split("store_arch daemon_runtime incremental cli extraction " \ - "watcher daemon_ipc subprocess httpd py_lsp_stress " \ - "grammar_regression mcp daemon_frontend pipeline pipeline_b", h, " ") + # Empirical weights (relative seconds across CI legs); unlisted + # suites get default weight 5. Pure deterministic function of + # (suite list, idx, total) so every shard agrees identically. + w["incremental"] = 1600 + w["cli"] = 930 + w["complexity"] = 920 + w["pipeline"] = 890 + w["stack_overflow_b"] = 865 + w["pipeline_b"] = 820 + w["php_member_walk"] = 800 + w["test_impact_git"] = 700 + w["test_impact_git_b"] = 640 + w["c_lsp"] = 660 + w["c_lsp_b"] = 655 + w["pipeline_semantic_manifest_repro"] = 660 + w["doc_mentions"] = 530 + w["doc_mentions_b"] = 520 + w["test_impact_engine"] = 505 + w["java_type_scope"] = 470 + w["java_type_scope_b"] = 465 + w["mcp"] = 450 + w["grammar_probe_f"] = 405 + w["test_impact_tree"] = 385 + w["edge_types_probe"] = 370 + w["stack_overflow_a"] = 360 + w["doc_mentions_jvm"] = 335 + w["type_scope"] = 320 + w["daemon_frontend"] = 315 + w["include_path"] = 270 + w["cypher"] = 260 + w["edge_imports"] = 240 + w["doc_mentions_cost"] = 235 + w["lang_contract"] = 230 + w["py_lsp"] = 215 + w["lsp_resolution_probe"] = 215 + w["watcher"] = 210 + w["test_impact_classify"] = 200 + w["daemon_runtime"] = 180 + w["store_arch"] = 160 + w["extraction"] = 150 + w["grammar_regression"] = 140 + w["py_lsp_stress"] = 140 + w["httpd"] = 130 + w["subprocess"] = 120 + w["daemon_ipc"] = 100 + w["daemon_application"] = 90 + w["index_supervisor"] = 80 + w["daemon_bootstrap"] = 60 + } + { + lines[NR] = $0 + wt[NR] = ($0 in w) ? w[$0] : 5 } - { present[$0] = NR; lines[NR] = $0 } END { - # Deal heavies in WEIGHT order (the static list above), not file - # order: the point is that the two slowest suites land on - # different shards, which file-order dealing does not guarantee. - n = 0 - for (i = 1; i <= nh; i++) - if (h[i] in present) { order[++n] = h[i]; taken[h[i]] = 1 } - for (i = 1; i <= NR; i++) - if (!(lines[i] in taken)) order[++n] = lines[i] - for (i = 1; i <= n; i++) if ((i - 1) % total == idx - 1) print order[i] + # Sort indices by descending weight, tie-breaking by original order + # (insertion sort on ~200 suites is instantaneous and portable across + # gawk/mawk/BSD awk without requiring gawk-specific asort). + for (i = 1; i <= NR; i++) { + ord[i] = i + k = i + while (k > 1 && wt[ord[k]] > wt[ord[k - 1]]) { + tmp = ord[k] + ord[k] = ord[k - 1] + ord[k - 1] = tmp + k-- + } + } + for (s = 1; s <= total; s++) load[s] = 0 + for (i = 1; i <= NR; i++) { + best = 1 + for (s = 2; s <= total; s++) { + if (load[s] < load[best]) best = s + } + load[best] += wt[ord[i]] + if (best == idx) print lines[ord[i]] + } } ' } @@ -269,26 +333,51 @@ SERIAL_SUITES="cli subprocess watcher incremental httpd ui index_resilience mcp is_serial() { case " $SERIAL_SUITES " in *" $1 "*) return 0 ;; *) return 1 ;; esac } +# Tail scheduling in two phases. The FLEX suites are timing-shaped but do +# not rendezvous through the shared per-account daemon runtime namespace, +# so a small fixed overlap (CBM_TAIL_JOBS, default 2) is safe and converts +# idle cores into wall time — the old fully-serial tail ran them one at a +# time on an idle machine. The EXCL group (daemon-family plus the suites +# that drive daemon one-shots or supervisor rendezvous) then runs strictly +# sequentially on a machine exactly as quiet as the old tail gave it. +# extraction is in this group for a DIFFERENT reason than the rest: it does not +# rendezvous through the daemon namespace, it measures a scaling ratio, and even +# the FLEX group's small fixed overlap is load the measurement would absorb. +# Strictly sequential is what makes its verdict a function of the code instead +# of the scheduler. +TAIL_EXCL="cli mcp index_supervisor daemon_application daemon_runtime \ + daemon_frontend daemon_bootstrap daemon_ipc extraction" +is_tail_excl() { + case " $TAIL_EXCL " in *" $1 "*) return 0 ;; *) return 1 ;; esac +} PAR_FILE="$LOGDIR/suites-parallel.txt" -SER_FILE="$LOGDIR/suites-serial.txt" +FLEX_FILE="$LOGDIR/suites-tail-flex.txt" +EXCL_FILE="$LOGDIR/suites-tail-excl.txt" : > "$PAR_FILE" -: > "$SER_FILE" +: > "$FLEX_FILE" +: > "$EXCL_FILE" while IFS= read -r sname; do if is_serial "$sname"; then - echo "$sname" >> "$SER_FILE" + if is_tail_excl "$sname"; then + echo "$sname" >> "$EXCL_FILE" + else + echo "$sname" >> "$FLEX_FILE" + fi else echo "$sname" >> "$PAR_FILE" fi done < "$SUITES_FILE" -# The parallel wave and the serial tail are sharded separately: every shard -# keeps its own quiet tail for the deadline-sensitive suites (its runner is -# a whole machine, so the tail is at least as quiet as before sharding). +# Shard the parallel wave, flex tail, and exclusive tail separately via LPT +# bin-packing so every shard gets balanced work in all three phases and keeps +# its own quiet tail for deadline-sensitive suites. shard_filter < "$PAR_FILE" > "$PAR_FILE.shard" && mv "$PAR_FILE.shard" "$PAR_FILE" -shard_filter < "$SER_FILE" > "$SER_FILE.shard" && mv "$SER_FILE.shard" "$SER_FILE" +shard_filter < "$FLEX_FILE" > "$FLEX_FILE.shard" && mv "$FLEX_FILE.shard" "$FLEX_FILE" +shard_filter < "$EXCL_FILE" > "$EXCL_FILE.shard" && mv "$EXCL_FILE.shard" "$EXCL_FILE" SHARD_EXPECT="$LOGDIR/suites-shard.txt" -cat "$PAR_FILE" "$SER_FILE" > "$SHARD_EXPECT" +cat "$PAR_FILE" "$FLEX_FILE" "$EXCL_FILE" > "$SHARD_EXPECT" NSHARD=$(wc -l < "$SHARD_EXPECT" | tr -d ' ') +NTAIL=$(( $(wc -l < "$FLEX_FILE" | tr -d ' ') + $(wc -l < "$EXCL_FILE" | tr -d ' ') )) # Machine-checkable manifest for CI's cross-shard completeness job: it # proves at runtime that the shards of one leg agree on N and on the full @@ -306,7 +395,7 @@ NSHARD=$(wc -l < "$SHARD_EXPECT" | tr -d ' ') echo "--- slice ---" cat "$SHARD_EXPECT" } > "$LOGDIR/shard-manifest.txt" -echo "=== parallel test run: $NSHARD of $NSUITES suites (shard ${SHARD_INDEX}/${SHARD_TOTAL}, $(wc -l < "$SER_FILE" | tr -d ' ') serial-tail), $JOBS jobs ===" +echo "=== parallel test run: $NSHARD of $NSUITES suites (shard ${SHARD_INDEX}/${SHARD_TOTAL}, $NTAIL serial-tail), $JOBS jobs ===" # Leave the logs of every non-green suite in $LOGDIR/failed for CI to upload # when the job fails. An EXIT trap rather than a call next to the summary @@ -341,34 +430,6 @@ run_wave() { run_wave "$PAR_FILE" "$JOBS" -# Tail scheduling in two phases. The FLEX suites are timing-shaped but do -# not rendezvous through the shared per-account daemon runtime namespace, -# so a small fixed overlap (CBM_TAIL_JOBS, default 2) is safe and converts -# idle cores into wall time — the old fully-serial tail ran them one at a -# time on an idle machine. The EXCL group (daemon-family plus the suites -# that drive daemon one-shots or supervisor rendezvous) then runs strictly -# sequentially on a machine exactly as quiet as the old tail gave it. -# extraction is in this group for a DIFFERENT reason than the rest: it does not -# rendezvous through the daemon namespace, it measures a scaling ratio, and even -# the FLEX group's small fixed overlap is load the measurement would absorb. -# Strictly sequential is what makes its verdict a function of the code instead -# of the scheduler. -TAIL_EXCL="cli mcp index_supervisor daemon_application daemon_runtime \ - daemon_frontend daemon_bootstrap daemon_ipc extraction" -is_tail_excl() { - case " $TAIL_EXCL " in *" $1 "*) return 0 ;; *) return 1 ;; esac -} -FLEX_FILE="$LOGDIR/suites-tail-flex.txt" -EXCL_FILE="$LOGDIR/suites-tail-excl.txt" -: > "$FLEX_FILE" -: > "$EXCL_FILE" -while IFS= read -r sname; do - if is_tail_excl "$sname"; then - echo "$sname" >> "$EXCL_FILE" - else - echo "$sname" >> "$FLEX_FILE" - fi -done < "$SER_FILE" # Wave suites spawn Cygwin-family tooling that can rewrite the build # directory's DACL behind the first stamp (observed: an arm shard whose # tail held the install-flow suites failed the source-directory policy diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.sh index 8a9017495e..dd6566e368 100755 --- a/scripts/smoke-test.sh +++ b/scripts/smoke-test.sh @@ -4223,30 +4223,52 @@ UI_PORT=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0 # the UI does not pin the process, so stdio EOF ends it cleanly (rc=0) before # the poll can see it serve — the drive-listing guard holds a pipe for the # same reason. Equals-form flags match that guard's proven invocation. -sleep 300 | "$BINARY" --ui=true --port="$UI_PORT" > /dev/null 2>&1 & +# Track the stdin-holder sleep PID so cleanup stops it immediately instead of +# leaving `wait "$UI_PID"` blocked for the full 300 s sleep after the server +# exits or is killed. +UI_SLEEP_PID_FILE=$(smoke_mktemp_file) +rm -f "$UI_SLEEP_PID_FILE" +( + sleep 300 & + echo "$!" > "$UI_SLEEP_PID_FILE" + wait +) | "$BINARY" --ui=true --port="$UI_PORT" > /dev/null 2>&1 & UI_PID=$! -# Readiness poll instead of a fixed sleep: SKIP is legitimate ONLY when the -# process exited (the documented no-embedded-assets case); a slow start on a -# loaded runner must not masquerade as it. The UI binds ~6s after launch even -# on a fast host (measured against the release artifact), so the window -# matches the drive-listing guard's 25s, not a 10s sprint. + +stop_ui_server() { + kill "$UI_PID" 2>/dev/null || true + if [ -s "$UI_SLEEP_PID_FILE" ]; then + kill "$(cat "$UI_SLEEP_PID_FILE")" 2>/dev/null || true + fi + wait "$UI_PID" 2>/dev/null || true + rm -f "$UI_SLEEP_PID_FILE" +} + +# Readiness poll with a real 30 s wall-clock deadline (not an iteration count: +# on Windows a refused localhost connect takes ~2 s, turning 150 iterations +# into 300 s). SKIP is legitimate ONLY when the process exited or serves no +# embedded UI; a slow start on a loaded runner still gets the full 30 s window. UI_READY=0 -for _ in $(seq 1 150); do +UI_DEADLINE=$((SECONDS + 30)) +while [ "$SECONDS" -lt "$UI_DEADLINE" ]; do if ! kill -0 "$UI_PID" 2>/dev/null; then break; fi - if curl --noproxy '*' -sf "http://127.0.0.1:$UI_PORT/" -o /dev/null 2>/dev/null; then UI_READY=1; break; fi + if curl --noproxy '*' --connect-timeout 1 --max-time 2 -sf "http://127.0.0.1:$UI_PORT/" -o /dev/null 2>/dev/null; then UI_READY=1; break; fi sleep 0.2 done if [ "$UI_READY" -eq 1 ] || kill -0 "$UI_PID" 2>/dev/null; then # 15a: GET / returns 200 with HTML content - UI_BODY=$(curl --noproxy '*' -sf "http://127.0.0.1:$UI_PORT/" 2>/dev/null || echo "") + UI_BODY=$(curl --noproxy '*' --connect-timeout 1 --max-time 2 -sf "http://127.0.0.1:$UI_PORT/" 2>/dev/null || echo "") if echo "$UI_BODY" | grep -qi "/dev/null || true + stop_ui_server exit 1 fi @@ -4255,20 +4277,23 @@ if [ "$UI_READY" -eq 1 ] || kill -0 "$UI_PID" 2>/dev/null; then # old probe POSTed an MCP initialize at /rpc, but the UI's /rpc speaks the # UI's own narrow query protocol, not MCP — the probe asserted a request # the endpoint never answered; protocol depth belongs to the UI guards.) - RPC_BODY=$(curl --noproxy '*' -sf "http://127.0.0.1:$UI_PORT/api/ui-config" 2>/dev/null || echo "") + RPC_BODY=$(curl --noproxy '*' --connect-timeout 1 --max-time 2 -sf "http://127.0.0.1:$UI_PORT/api/ui-config" 2>/dev/null || echo "") if echo "$RPC_BODY" | grep -q "{"; then echo "OK 15b: /api/ui-config returns JSON" elif [ -z "$RPC_BODY" ]; then + if [ "$SMOKE_REQUIRE_UI" = "1" ]; then + stop_ui_server + fi smoke_ui_missing "15b" "/api/ui-config not reachable" else echo "FAIL 15b: /api/ui-config did not return JSON" - kill "$UI_PID" 2>/dev/null || true + stop_ui_server exit 1 fi - kill "$UI_PID" 2>/dev/null || true - wait "$UI_PID" 2>/dev/null || true + stop_ui_server else + stop_ui_server smoke_ui_missing "Phase 15" "binary exited immediately (no UI assets embedded)" fi diff --git a/scripts/test.sh b/scripts/test.sh index 505e5ab775..f9caccb822 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -269,168 +269,136 @@ if [ -n "$SUITES" ]; then fi # Step 0: fast build/security harness regressions run before the compiler-heavy -# suite. The Windows package surface is static here; native launcher behavior is -# exercised by scripts/test-windows.ps1. -echo "=== Step 0a: build directory safety contract ===" -bash "$ROOT/tests/test_build_dir_safety.sh" - -echo "=== Step 0b: Windows VM worktree sync contract ===" -bash "$ROOT/tests/test_vm_worktree_manifest.sh" - -echo "=== Step 0c: UI development proxy security contract ===" -bash "$ROOT/tests/test_ui_dev_proxy_security.sh" - -echo "=== Step 0d: daemon soak recovery contract ===" -bash "$ROOT/tests/test_soak_daemon_recovery_contract.sh" - -echo "=== Step 0d2: soak harness runtime isolation contract (#1696) ===" -bash "$ROOT/tests/test_soak_runtime_isolation_contract.sh" - -echo "=== Step 0e: Windows launcher bundle contract ===" -bash "$ROOT/tests/test_windows_bundle_contract.sh" - -echo "=== Step 0e2: activation refusal diagnostic contract ===" -bash "$ROOT/tests/test_activation_diagnostic_contract.sh" - -echo "=== Step 0e3: security gate fail-closed contract ===" -bash "$ROOT/tests/test_security_gate_fail_closed.sh" - -echo "=== Step 0e4: memory-analyzer gate warning-suffix contract (#2442) ===" -bash "$ROOT/tests/test_lint_mem_gate.sh" - -echo "=== Step 0f: tree-sitter runtime Makefile dependencies ===" -bash "$ROOT/tests/test_makefile_ts_runtime_dependencies.sh" - -echo "=== Step 0g: security fuzz harness self-test ===" -bash "$ROOT/tests/test_security_fuzz_harness.sh" - -echo "=== Step 0g2: memlab harness runtime isolation contract (#1696) ===" -bash "$ROOT/tests/test_memlab_runtime_isolation_contract.sh" - -echo "=== Step 0h: smoke release-fixture contract ===" -bash "$ROOT/tests/test_smoke_fixture_contract.sh" - -echo "=== Step 0i: parallel suite scheduler contract ===" -bash "$ROOT/tests/test_parallel_harness_contract.sh" - -# Step 0i2: a red suite's summary must show the sanitizer report and the test -# that was running, not only "FAIL" lines and a shadow-byte legend. Drives the -# real summary functions with fabricated suite logs, so it runs everywhere. -echo "=== Step 0i2: suite failure-report contract ===" -bash "$ROOT/tests/test_failure_report_contract.sh" - -echo "=== Step 0i3: benchmark harness runtime isolation contract (#1696) ===" -bash "$ROOT/tests/test_benchmark_runtime_isolation_contract.sh" - -echo "=== Step 0j: venue parity contract (one harness, every venue) ===" -bash "$ROOT/tests/test_venue_parity_contract.sh" - -echo "=== Step 0k: spawn console-window contract (#1427) ===" -bash "$ROOT/tests/test_spawn_no_window_contract.sh" - -echo "=== Step 0l: release archive extractor contract ===" -bash "$ROOT/tests/test_release_archive_extractor_contract.sh" - -echo "=== Step 0m: VirusTotal release-notes + evidence contract ===" -bash "$ROOT/tests/test_vt_release_notes_contract.sh" - -echo "=== Step 0n: VirusTotal gate policy contract ===" -bash "$ROOT/tests/test_vt_gate_policy_contract.sh" - -echo "=== Step 0o: MCPB bundle contract (#1246) ===" -bash "$ROOT/tests/test_mcpb_bundle_contract.sh" - -echo "=== Step 0p: MCPB registry entries contract (#1246) ===" -bash "$ROOT/tests/test_mcpb_registry_entries_contract.sh" - -echo "=== Step 0q: release candidate derivation contract ===" -bash "$ROOT/tests/test_release_candidate_derivation_contract.sh" - -echo "=== Step 0r: VirusTotal candidate-selection contract ===" -bash "$ROOT/tests/test_vt_candidate_selection_contract.sh" - -echo "=== Step 0s: release gate-chain ordering contract ===" -bash "$ROOT/tests/test_release_gate_chain_contract.sh" - -echo "=== Step 0s2: release plan (version, channel, environment) contract ===" -bash "$ROOT/tests/test_release_plan_contract.sh" - -echo "=== Step 0s3: release-candidate reconcile contract ===" -bash "$ROOT/tests/test_rc_reconcile_contract.sh" - -echo "=== Step 0s4: release retry policy contract ===" -bash "$ROOT/tests/test_release_retry_policy_contract.sh" - -echo "=== Step 0s4b: release retry controller contract ===" -bash "$ROOT/tests/test_release_retry_controller_contract.sh" - -echo "=== Step 0s5: release flow wiring contract ===" -bash "$ROOT/tests/test_release_rc_flow_contract.sh" - -echo "=== Step 0t: test runtime isolation contract (#1691) ===" -bash "$ROOT/tests/test_runtime_isolation_contract.sh" - -echo "=== Step 0t2: smoke harness runtime isolation contract (#1696) ===" -bash "$ROOT/tests/test_smoke_runtime_isolation_contract.sh" - -echo "=== Step 0u: shell line-ending contract ===" -bash "$ROOT/tests/test_shell_line_endings.sh" - -echo "=== Step 0v: nomic blob generator contract ===" -bash "$ROOT/tests/test_nomic_blob_generator_contract.sh" - -echo "=== Step 0w: published language-count contract ===" -bash "$ROOT/tests/test_language_count_contract.sh" - -echo "=== Step 0x: packaging version-metadata contract ===" -bash "$ROOT/tests/test_version_metadata_contract.sh" - -echo "=== Step 0x2: installer Android/Termux guard contract (#1202) ===" -bash "$ROOT/tests/test_install_android_guard.sh" - -# Step 0y: the Windows leg must not decide its verdict from an exit status that -# the ssh/msys2_shell chain can mangle — a channel that turns 0 into 1 can turn -# 1 into 0, and that direction reports a RED Windows leg as green. Runs -# everywhere (it drives synthetic logs, no VM needed) because the guard it pins -# is what every Windows verdict rests on. -echo "=== Step 0y: VM leg verdict contract ===" -bash "$ROOT/tests/test_vm_verdict_contract.sh" - -echo "=== Step 0y2: isolated Windows venue contract ===" -bash "$ROOT/tests/test_vm_isolation_contract.sh" - -echo "=== Step 0y3: setup scripts install through the installers' verified path ===" -bash "$ROOT/tests/test_setup_scripts_contract.sh" - -# Step 0z: PR CI runs only the lanes scripts/ci/select-lanes.sh selects, so a -# wrong selection is a silent gate loss. The decision table, and the replay of -# every September 2026 PR push and real failure against it. -echo "=== Step 0z: PR lane selector contract ===" -bash "$ROOT/tests/test_select_lanes.sh" -echo "=== Step 0z1: CodeQL retraces affected prebuilt objects ===" -bash "$ROOT/tests/test_codeql_retrace.sh" -echo "=== Step 0z2: lane selector history replay ===" -bash "$ROOT/scripts/test-impact/replay-selector.sh" -echo "=== Step 0z3: lane-aware aggregate gates (ci-ok, shard union) ===" -bash "$ROOT/tests/test_lane_gate_contract.sh" -echo "=== Step 0z4: lane wiring (PRs select, dry run and release run all) ===" -bash "$ROOT/tests/test_lane_wiring_contract.sh" -echo "=== Step 0z5: test-impact shadow prediction contract ===" -bash "$ROOT/tests/test_test_impact_predict.sh" -# Step 0z6: the per-test coverage map must never report a test as executing -# less than it did: every case where the builder cannot know (a killed forked -# child, an unreadable profile, a failed suite) has to come out `incomplete`. -echo "=== Step 0z6: per-test coverage map builder contract ===" -bash "$ROOT/tests/test_coverage_map.sh" -# Step 0z7: a push's incremental coverage map carries the suites it did not -# re-run onto the new image's function table; a wrong remap would hand the PR -# selection a map that claims tests ran functions they never touched. -echo "=== Step 0z7: incremental coverage map merge contract ===" -bash "$ROOT/tests/test_coverage_merge.sh" -# Step 0z8: the one place a test-impact answer becomes what PR CI runs. Only a -# well-formed, self-consistent selection may narrow; everything else runs all. -echo "=== Step 0z8: test selection (answer -> runner filter) contract ===" -bash "$ROOT/tests/test_test_impact_selection.sh" +# suite. Each contract script is self-contained (reads the repo read-only and +# isolates any scratch files under mktemp), so running them in parallel across +# $NPROC workers cuts Step 0 wall time by ~4x (especially on Windows MSYS2) +# with identical coverage and deterministic Step 0a..0z8 output ordering. +# Set CBM_CONTRACTS_SEQUENTIAL=1 to run them serially. +CONTRACT_JOBS="$NPROC" +if [ "${CBM_CONTRACTS_SEQUENTIAL:-0}" = "1" ]; then + CONTRACT_JOBS=1 +fi +python3 - "$ROOT" "$BASH" "$CONTRACT_JOBS" <<'PY' +from __future__ import annotations + +import concurrent.futures +import os +import pathlib +import subprocess +import sys + +root = pathlib.Path(sys.argv[1]) +bash_bin = sys.argv[2] +jobs = max(1, int(sys.argv[3])) + +# (canonical banner, script path relative to repo root, weight for LPT order) +CONTRACTS = [ + ("Step 0a: build directory safety contract", "tests/test_build_dir_safety.sh", 10), + ("Step 0b: Windows VM worktree sync contract", "tests/test_vm_worktree_manifest.sh", 2), + ("Step 0c: UI development proxy security contract", "tests/test_ui_dev_proxy_security.sh", 1), + ("Step 0d: daemon soak recovery contract", "tests/test_soak_daemon_recovery_contract.sh", 1), + ("Step 0d2: soak harness runtime isolation contract (#1696)", "tests/test_soak_runtime_isolation_contract.sh", 8), + ("Step 0e: Windows launcher bundle contract", "tests/test_windows_bundle_contract.sh", 1), + ("Step 0e2: activation refusal diagnostic contract", "tests/test_activation_diagnostic_contract.sh", 1), + ("Step 0e3: security gate fail-closed contract", "tests/test_security_gate_fail_closed.sh", 1), + ("Step 0e4: memory-analyzer gate warning-suffix contract (#2442)", "tests/test_lint_mem_gate.sh", 1), + ("Step 0f: tree-sitter runtime Makefile dependencies", "tests/test_makefile_ts_runtime_dependencies.sh", 136), + ("Step 0g: security fuzz harness self-test", "tests/test_security_fuzz_harness.sh", 61), + ("Step 0g2: memlab harness runtime isolation contract (#1696)", "tests/test_memlab_runtime_isolation_contract.sh", 3), + ("Step 0h: smoke release-fixture contract", "tests/test_smoke_fixture_contract.sh", 2), + ("Step 0i: parallel suite scheduler contract", "tests/test_parallel_harness_contract.sh", 10), + ("Step 0i2: suite failure-report contract", "tests/test_failure_report_contract.sh", 4), + ("Step 0i3: benchmark harness runtime isolation contract (#1696)", "tests/test_benchmark_runtime_isolation_contract.sh", 7), + ("Step 0j: venue parity contract (one harness, every venue)", "tests/test_venue_parity_contract.sh", 6), + ("Step 0k: spawn console-window contract (#1427)", "tests/test_spawn_no_window_contract.sh", 1), + ("Step 0l: release archive extractor contract", "tests/test_release_archive_extractor_contract.sh", 2), + ("Step 0m: VirusTotal release-notes + evidence contract", "tests/test_vt_release_notes_contract.sh", 2), + ("Step 0n: VirusTotal gate policy contract", "tests/test_vt_gate_policy_contract.sh", 9), + ("Step 0o: MCPB bundle contract (#1246)", "tests/test_mcpb_bundle_contract.sh", 10), + ("Step 0p: MCPB registry entries contract (#1246)", "tests/test_mcpb_registry_entries_contract.sh", 1), + ("Step 0q: release candidate derivation contract", "tests/test_release_candidate_derivation_contract.sh", 3), + ("Step 0r: VirusTotal candidate-selection contract", "tests/test_vt_candidate_selection_contract.sh", 4), + ("Step 0s: release gate-chain ordering contract", "tests/test_release_gate_chain_contract.sh", 1), + ("Step 0s2: release plan (version, channel, environment) contract", "tests/test_release_plan_contract.sh", 4), + ("Step 0s3: release-candidate reconcile contract", "tests/test_rc_reconcile_contract.sh", 1), + ("Step 0s4: release retry policy contract", "tests/test_release_retry_policy_contract.sh", 3), + ("Step 0s4b: release retry controller contract", "tests/test_release_retry_controller_contract.sh", 1), + ("Step 0s5: release flow wiring contract", "tests/test_release_rc_flow_contract.sh", 1), + ("Step 0t: test runtime isolation contract (#1691)", "tests/test_runtime_isolation_contract.sh", 2), + ("Step 0t2: smoke harness runtime isolation contract (#1696)", "tests/test_smoke_runtime_isolation_contract.sh", 2), + ("Step 0u: shell line-ending contract", "tests/test_shell_line_endings.sh", 1), + ("Step 0v: nomic blob generator contract", "tests/test_nomic_blob_generator_contract.sh", 1), + ("Step 0w: published language-count contract", "tests/test_language_count_contract.sh", 14), + ("Step 0x: packaging version-metadata contract", "tests/test_version_metadata_contract.sh", 5), + ("Step 0x2: installer Android/Termux guard contract (#1202)", "tests/test_install_android_guard.sh", 1), + ("Step 0y: VM leg verdict contract", "tests/test_vm_verdict_contract.sh", 2), + ("Step 0y2: isolated Windows venue contract", "tests/test_vm_isolation_contract.sh", 1), + ("Step 0y3: setup scripts install through the installers' verified path", "tests/test_setup_scripts_contract.sh", 1), + ("Step 0z: PR lane selector contract", "tests/test_select_lanes.sh", 26), + ("Step 0z1: CodeQL retraces affected prebuilt objects", "tests/test_codeql_retrace.sh", 168), + ("Step 0z2: lane selector history replay", "scripts/test-impact/replay-selector.sh", 1), + ("Step 0z3: lane-aware aggregate gates (ci-ok, shard union)", "tests/test_lane_gate_contract.sh", 10), + ("Step 0z4: lane wiring (PRs select, dry run and release run all)", "tests/test_lane_wiring_contract.sh", 1), + ("Step 0z5: test-impact shadow prediction contract", "tests/test_test_impact_predict.sh", 2), + ("Step 0z6: per-test coverage map builder contract", "tests/test_coverage_map.sh", 12), + ("Step 0z7: incremental coverage map merge contract", "tests/test_coverage_merge.sh", 1), + ("Step 0z8: test selection (answer -> runner filter) contract", "tests/test_test_impact_selection.sh", 4), +] + +def run_one(item: tuple[int, str, str]) -> tuple[int, int, str]: + idx, _label, rel = item + popen_kw: dict[str, object] = {} + if os.name == "nt": + popen_kw["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP + else: + popen_kw["start_new_session"] = True + proc = subprocess.run( + [bash_bin, str(root / rel)], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + **popen_kw, + ) + return idx, proc.returncode, proc.stdout + +# Schedule heaviest contracts first (LPT) to avoid long tail stragglers. +scheduled = sorted( + [(idx, label, rel, weight) for idx, (label, rel, weight) in enumerate(CONTRACTS)], + key=lambda x: (-x[3], x[0]), +) + +results: dict[int, tuple[int, str]] = {} +if jobs == 1: + for idx, (label, rel, _weight) in enumerate(CONTRACTS): + print(f"=== {label} ===", flush=True) + _, rc, out = run_one((idx, label, rel)) + if out: + sys.stdout.write(out) + sys.stdout.flush() + if rc != 0: + sys.exit(rc) +else: + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + futs = [pool.submit(run_one, (idx, label, rel)) for idx, label, rel, _ in scheduled] + for fut in concurrent.futures.as_completed(futs): + idx, rc, out = fut.result() + results[idx] = (rc, out) + + failed = [] + for idx, (label, rel, _weight) in enumerate(CONTRACTS): + rc, out = results[idx] + print(f"=== {label} ===", flush=True) + if out: + sys.stdout.write(out) + if rc != 0: + failed.append((label, rel, rc)) + if failed: + for label, rel, rc in failed: + print(f"FAIL: {label} ({rel}) exited {rc}", file=sys.stderr) + sys.exit(1) +PY if [ "$CONTRACTS_ONLY" -eq 1 ]; then echo "=== test.sh: contracts-only — every contract step passed ===" diff --git a/tests/test_c_lsp.c b/tests/test_c_lsp.c index a7a46eb556..0d212d126d 100644 --- a/tests/test_c_lsp.c +++ b/tests/test_c_lsp.c @@ -17547,6 +17547,11 @@ SUITE(c_lsp) { RUN_TEST(clsp_pattern_multi_declarator_same_line); RUN_TEST(clsp_pattern_struct_ptr_arrow_chain); RUN_TEST(clsp_pattern_constexpr_variable); +} + +/* Second half of the C/C++ LSP suite, run as its own parallel unit so the + * 778-test suite does not straggle on slower CI runners (matches pipeline_b). */ +SUITE(c_lsp_b) { RUN_TEST(clsp_pattern_inline_variable); RUN_TEST(clsp_pattern_string_view_param); RUN_TEST(clsp_pattern_initializer_list_constructor); diff --git a/tests/test_codeql_retrace.sh b/tests/test_codeql_retrace.sh index 350271febe..3d596d805a 100644 --- a/tests/test_codeql_retrace.sh +++ b/tests/test_codeql_retrace.sh @@ -63,8 +63,10 @@ with tempfile.TemporaryDirectory(prefix="cbm-codeql-retrace-") as directory: raise RuntimeError(f"{args}: exit {proc.returncode}\n{proc.stdout}\n{proc.stderr}") return proc.stdout - make = ["make", "--no-print-directory", "-f", "Makefile.cbm", "cbm-third-party", - "BUILD_DIR=build/c", "CC=" + os.environ.get("CC", "cc")] + jobs = str(max(1, os.cpu_count() or 1)) + make = ["make", f"-j{jobs}", "--no-print-directory", "-f", "Makefile.cbm", + "cbm-third-party", "BUILD_DIR=build/c", + "CC=" + os.environ.get("CC", "cc")] def compiled(output): return set(re.findall(r" -c -o build/c/([^\s]+\.o)(?:\s|$)", output)) diff --git a/tests/test_doc_mentions.c b/tests/test_doc_mentions.c index 43259fc024..80df584c50 100644 --- a/tests/test_doc_mentions.c +++ b/tests/test_doc_mentions.c @@ -10520,6 +10520,11 @@ SUITE(doc_mentions) { RUN_TEST(doc_mentions_cs_scan_nested_holes); RUN_TEST(doc_mentions_cs_scan_holes_stack); RUN_TEST(doc_mentions_incremental_project_files); +} + +/* Second half of doc_mentions (C# and later cases), split for parallel + * scheduling parity across CI shards (matches pipeline_b). */ +SUITE(doc_mentions_b) { RUN_TEST(doc_mentions_cs_lookup_order); RUN_TEST(doc_mentions_cs_type_parameters); RUN_TEST(doc_mentions_cs_usings); diff --git a/tests/test_java_type_scope.c b/tests/test_java_type_scope.c index 2649781e46..cd41a0d684 100644 --- a/tests/test_java_type_scope.c +++ b/tests/test_java_type_scope.c @@ -2890,6 +2890,11 @@ SUITE(java_type_scope) { RUN_TEST(java_type_scope_owner_spelled_supertype_parallel); RUN_TEST(java_type_scope_library_split_package_sequential); RUN_TEST(java_type_scope_library_split_package_parallel); +} + +/* Second half of java_type_scope, split so both halves run concurrently across + * workers and shards (matches pipeline_b). */ +SUITE(java_type_scope_b) { RUN_TEST(java_type_scope_interface_call_sequential); RUN_TEST(java_type_scope_interface_call_parallel); RUN_TEST(java_type_scope_inherited_overload_sequential); diff --git a/tests/test_main.c b/tests/test_main.c index e3ef07cd76..4af92b03ac 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -1621,6 +1621,7 @@ extern void suite_test_impact_profiles(void); extern void suite_test_impact_changes(void); extern void suite_test_impact_origins(void); extern void suite_test_impact_git(void); +extern void suite_test_impact_git_b(void); extern void suite_test_impact_tree(void); extern void suite_test_impact_tree_read(void); extern void suite_test_impact_inventory(void); @@ -1687,6 +1688,7 @@ extern void suite_artifact(void); extern void suite_sqlite_writer(void); extern void suite_go_lsp(void); extern void suite_c_lsp(void); +extern void suite_c_lsp_b(void); extern void suite_php_lsp(void); extern void suite_member_walk(void); extern void suite_php_member_walk(void); @@ -1705,6 +1707,7 @@ extern void suite_java_lsp(void); extern void suite_java_lsp_coverage(void); extern void suite_java_typed_calls(void); extern void suite_java_type_scope(void); +extern void suite_java_type_scope_b(void); extern void suite_kotlin_lsp(void); extern void suite_kotlin_typed_calls(void); extern void suite_rust_lsp(void); @@ -1717,6 +1720,7 @@ extern void suite_traces(void); extern void suite_configlink(void); extern void suite_doclinks(void); extern void suite_doc_mentions(void); +extern void suite_doc_mentions_b(void); extern void suite_doc_mentions_cost(void); extern void suite_doc_mentions_msbuild(void); extern void suite_doc_links_md(void); @@ -2466,6 +2470,7 @@ int main(int argc, char **argv) { RUN_SELECTED_SUITE(test_impact_changes); RUN_SELECTED_SUITE(test_impact_origins); RUN_SELECTED_SUITE(test_impact_git); + RUN_SELECTED_SUITE(test_impact_git_b); RUN_SELECTED_SUITE(test_impact_tree); RUN_SELECTED_SUITE(test_impact_tree_read); RUN_SELECTED_SUITE(test_impact_inventory); @@ -2570,6 +2575,7 @@ int main(int argc, char **argv) { RUN_SELECTED_SUITE(type_rep); RUN_SELECTED_SUITE(go_lsp); RUN_SELECTED_SUITE(c_lsp); + RUN_SELECTED_SUITE(c_lsp_b); RUN_SELECTED_SUITE(php_lsp); RUN_SELECTED_SUITE(member_walk); RUN_SELECTED_SUITE(php_member_walk); @@ -2589,6 +2595,7 @@ int main(int argc, char **argv) { RUN_SELECTED_SUITE(java_lsp_coverage); RUN_SELECTED_SUITE(java_typed_calls); RUN_SELECTED_SUITE(java_type_scope); + RUN_SELECTED_SUITE(java_type_scope_b); /* Architecture + ADR + Louvain */ RUN_SELECTED_SUITE(store_arch); @@ -2607,6 +2614,7 @@ int main(int argc, char **argv) { /* Doc-comment references -> MENTIONS */ RUN_SELECTED_SUITE(doc_mentions); + RUN_SELECTED_SUITE(doc_mentions_b); RUN_SELECTED_SUITE(doc_mentions_cost); RUN_SELECTED_SUITE(doc_mentions_msbuild); RUN_SELECTED_SUITE(doc_links_md); diff --git a/tests/test_makefile_ts_runtime_dependencies.sh b/tests/test_makefile_ts_runtime_dependencies.sh index 9d19807869..7eec306014 100644 --- a/tests/test_makefile_ts_runtime_dependencies.sh +++ b/tests/test_makefile_ts_runtime_dependencies.sh @@ -9,20 +9,12 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)" WORKDIR="$(mktemp -d)" trap 'rm -rf "$WORKDIR"' EXIT -BUILD_DIR="$WORKDIR/build" -mkdir -p "$BUILD_DIR" - DEPENDENCIES=( internal/cbm/vendored/ts_runtime/src/stack.c internal/cbm/vendored/ts_runtime/src/stack.h internal/cbm/vendored/ts_runtime/src/unicode/utf8.h internal/cbm/vendored/ts_runtime/include/tree_sitter/api.h ) -TARGETS=( - "$BUILD_DIR/ts_runtime.o" - "$BUILD_DIR/tsan_ts_runtime.o" - "$BUILD_DIR/prod_ts_runtime.o" -) cd "$ROOT" @@ -31,26 +23,49 @@ for dependency in "${DEPENDENCIES[@]}"; do echo "FAIL: expected tree-sitter runtime dependency is missing: $dependency" exit 1 fi +done + +# Probe all 4 dependencies concurrently (each into its own temp build dir) so +# make startup overhead overlaps across cores, especially on Windows MSYS2. +pids=() +dep_idx=0 +for dependency in "${DEPENDENCIES[@]}"; do + dep_idx=$((dep_idx + 1)) + ( + dep_dir="$WORKDIR/build-$dep_idx" + mkdir -p "$dep_dir" + for target_name in ts_runtime.o tsan_ts_runtime.o prod_ts_runtime.o; do + target="$dep_dir/$target_name" + # Make the object newer than its currently-declared prerequisites. + # -W then asks make whether changing the unity-included file would + # rebuild it, without compiling or modifying the source tree. + touch "$target" - for target in "${TARGETS[@]}"; do - # Make the object newer than its currently-declared prerequisites. -W - # then asks make whether changing the unity-included file would rebuild - # it, without compiling or modifying the source tree. - touch "$target" - - status=0 - make -f Makefile.cbm -q -W "$dependency" \ - BUILD_DIR="$BUILD_DIR" "$target" || status=$? - - if [[ $status -eq 0 ]]; then - echo "FAIL: $target would stay stale after changing $dependency" - exit 1 - fi - if [[ $status -ne 1 ]]; then - echo "FAIL: make dependency probe failed for $target and $dependency (exit $status)" - exit 1 - fi - done + status=0 + make -f Makefile.cbm -q -W "$dependency" \ + BUILD_DIR="$dep_dir" "$target" || status=$? + + if [[ $status -eq 0 ]]; then + echo "FAIL: $target would stay stale after changing $dependency" + exit 1 + fi + if [[ $status -ne 1 ]]; then + echo "FAIL: make dependency probe failed for $target and $dependency (exit $status)" + exit 1 + fi + done + ) & + pids+=("$!") +done + +failed=0 +for pid in "${pids[@]}"; do + if ! wait "$pid"; then + failed=1 + fi done +if [[ $failed -ne 0 ]]; then + exit 1 +fi echo "PASS: all tree-sitter runtime unity objects track included sources and headers" diff --git a/tests/test_security_fuzz_harness.sh b/tests/test_security_fuzz_harness.sh index 79f43ad3e7..ac8416978f 100644 --- a/tests/test_security_fuzz_harness.sh +++ b/tests/test_security_fuzz_harness.sh @@ -18,12 +18,6 @@ exit 0 EOF chmod +x "$INIT_ONLY" -if "$ROOT/scripts/security-fuzz.sh" "$INIT_ONLY" \ - > "$WORKDIR/init-only.out" 2>&1; then - echo "FAIL: security-fuzz accepted a process that never consumed the adversarial payload" - exit 1 -fi - ECHO_ONLY="$WORKDIR/echo-only-mcp" cat > "$ECHO_ONLY" <<'EOF' #!/usr/bin/env bash @@ -35,12 +29,6 @@ done EOF chmod +x "$ECHO_ONLY" -if "$ROOT/scripts/security-fuzz.sh" "$ECHO_ONLY" \ - > "$WORKDIR/echo-only.out" 2>&1; then - echo "FAIL: security-fuzz accepted an echoed request as an acknowledgement" - exit 1 -fi - # One python3 process answers the requests; the harness needs python3 for its # interactive case anyway. A shell `read` of the 1 MB request costs seconds # where the shell runs emulated, and the harness's 10-second hang limit then @@ -79,12 +67,38 @@ CALLER_RUNTIME="$WORKDIR/caller-runtime" ENV_LOG="$WORKDIR/environment.log" mkdir -p "$CALLER_HOME" "$CALLER_CACHE" "$CALLER_RUNTIME" -if ! HOME="$CALLER_HOME" \ +# Run the three independent fixture harnesses concurrently; each creates its +# own isolated runtime root inside security-fuzz.sh. +"$ROOT/scripts/security-fuzz.sh" "$INIT_ONLY" > "$WORKDIR/init-only.out" 2>&1 & +INIT_PID=$! + +"$ROOT/scripts/security-fuzz.sh" "$ECHO_ONLY" > "$WORKDIR/echo-only.out" 2>&1 & +ECHO_PID=$! + +HOME="$CALLER_HOME" \ CBM_CACHE_DIR="$CALLER_CACHE" \ CBM_RUNTIME_DIR="$CALLER_RUNTIME" \ CBM_FUZZ_ENV_PROBE="$ENV_LOG" \ "$ROOT/scripts/security-fuzz.sh" "$ENV_PROBE" \ - > "$WORKDIR/environment.out" 2>&1; then + > "$WORKDIR/environment.out" 2>&1 & +ENV_PID=$! + +init_rc=0 +wait "$INIT_PID" || init_rc=$? +echo_rc=0 +wait "$ECHO_PID" || echo_rc=$? +env_rc=0 +wait "$ENV_PID" || env_rc=$? + +if [[ $init_rc -eq 0 ]]; then + echo "FAIL: security-fuzz accepted a process that never consumed the adversarial payload" + exit 1 +fi +if [[ $echo_rc -eq 0 ]]; then + echo "FAIL: security-fuzz accepted an echoed request as an acknowledgement" + exit 1 +fi +if [[ $env_rc -ne 0 ]]; then echo "FAIL: environment-probe fixture was rejected" cat "$WORKDIR/environment.out" exit 1 diff --git a/tests/test_test_impact_git.c b/tests/test_test_impact_git.c index 4f9fe1cc2b..830e2ac0dc 100644 --- a/tests/test_test_impact_git.c +++ b/tests/test_test_impact_git.c @@ -2452,6 +2452,11 @@ SUITE(test_impact_git) { RUN_TEST(test_git_facts_rejects_local_shallow_state); RUN_TEST(test_git_facts_rejects_history_override_added_after_open); RUN_TEST(test_git_facts_cancellation_after_open_is_latched); +} + +/* Second half of test_impact_git (ancestor_changes and blob_batch cases), + * split so both halves run concurrently across workers and shards. */ +SUITE(test_impact_git_b) { RUN_TEST(test_git_ancestor_changes_requires_ancestor_of_actual_merge_base); RUN_TEST(test_git_ancestor_changes_preserves_earlier_paths_reversion_and_pinned_head); RUN_TEST(test_git_ancestor_changes_equalities_and_empty_reversion_are_distinct); From 14f5a0a32d39980441478ddf991efd2286e1e71f Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 00:17:44 +0100 Subject: [PATCH 03/11] perf(ci): split lsp_all builds, dedup shards, fix diag ccache, shard msan Signed-off-by: Guillaume Demay --- .github/workflows/_test.yml | 52 +++++++++-- Makefile.cbm | 100 +++++++++++++------- scripts/ci/msan-lane.sh | 2 + scripts/ci/require-all-green.sh | 2 + scripts/msan.sh | 113 ++++++++++++++++++++++- scripts/run-tests-parallel.sh | 156 ++++++++++++++++++++------------ scripts/test.sh | 44 +++++++-- tests/test_c_lsp.c | 11 ++- tests/test_complexity.c | 5 + tests/test_doc_mentions.c | 10 +- tests/test_grammar_probe_f.c | 5 + tests/test_main.c | 8 ++ tests/test_pipeline.c | 10 ++ tests/test_stack_overflow.c | 4 +- 14 files changed, 404 insertions(+), 118 deletions(-) diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index d0fc918ee2..8627017a5d 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -49,6 +49,7 @@ jobs: tsan: ${{ steps.set.outputs.tsan }} diag: ${{ steps.set.outputs.diag }} lsan: ${{ steps.set.outputs.lsan }} + msan: ${{ steps.set.outputs.msan }} has_unix: ${{ steps.set.outputs.has_unix }} has_windows: ${{ steps.set.outputs.has_windows }} has_tsan: ${{ steps.set.outputs.has_tsan }} @@ -66,11 +67,14 @@ jobs: # The lane names unix-macos14 and tsan-mac are kept as lane keys # (select-lanes.sh, ci-ok and the lane contracts key on them); both # run on macos-15 because GitHub retires the macos-14 image on 2026-11-02. + # List macos-15-intel FIRST so it claims scarce macOS runner slots + # (5 concurrent macOS jobs max on GitHub hosted) at t=0 of Wave 2 + # instead of starving 15+ minutes behind Ubuntu and arm64 macOS legs. CORE_UNIX='[ - {"os":"ubuntu-latest","cc":"gcc","cxx":"g++","lane":"unix-x86"}, - {"os":"ubuntu-24.04-arm","cc":"gcc","cxx":"g++","lane":"unix-arm64"}, + {"os":"macos-15-intel","cc":"cc","cxx":"c++","lane":"unix-macos-intel"}, {"os":"macos-15","cc":"cc","cxx":"c++","lane":"unix-macos14"}, - {"os":"macos-15-intel","cc":"cc","cxx":"c++","lane":"unix-macos-intel"} + {"os":"ubuntu-latest","cc":"gcc","cxx":"g++","lane":"unix-x86"}, + {"os":"ubuntu-24.04-arm","cc":"gcc","cxx":"g++","lane":"unix-arm64"} ]' # Broad matrix legs are REQUIRED gates (no optional/continue-on-error # escape hatches): the release dry run must be all-green, every platform. @@ -134,8 +138,8 @@ jobs: # every leg near ~10 min while respecting GitHub's 20 total / 5 macOS # concurrent runner limits. case "$SHARD_PROFILE" in - standard) N_X86=3; N_ARM=3; N_MAC=2; N_MAC_INTEL=4; N_WIN=4; N_DIAG=2; N_LSAN=2 ;; - pr) N_X86=2; N_ARM=3; N_MAC=2; N_MAC_INTEL=4; N_WIN=4; N_DIAG=2; N_LSAN=2 ;; + standard) N_X86=3; N_ARM=2; N_MAC=2; N_MAC_INTEL=3; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; + pr) N_X86=2; N_ARM=2; N_MAC=2; N_MAC_INTEL=3; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; *) echo "::error::unknown shard_profile '$SHARD_PROFILE'"; exit 1 ;; esac if [ "$SHARDS" = "true" ]; then @@ -153,15 +157,18 @@ jobs: | $e + {shard: "\($i)/\($n)"}]' <<< "$WIN") DIAG=$(jq -cn --argjson n "$N_DIAG" '[range(1; $n + 1) as $i | {shard: "\($i)/\($n)"}]') LSAN=$(jq -cn --argjson n "$N_LSAN" '[range(1; $n + 1) as $i | {shard: "\($i)/\($n)"}]') + MSAN=$(jq -cn --argjson n "$N_MSAN" '[range(1; $n + 1) as $i | {shard: "\($i)/\($n)"}]') else DIAG='[{"shard":"1/1"}]' LSAN='[{"shard":"1/1"}]' + MSAN='[{"shard":"1/1"}]' fi echo "unix={\"include\":$UNIX}" >> "$GITHUB_OUTPUT" echo "windows={\"include\":$WIN}" >> "$GITHUB_OUTPUT" echo "tsan={\"include\":$TSAN}" >> "$GITHUB_OUTPUT" echo "diag={\"include\":$DIAG}" >> "$GITHUB_OUTPUT" echo "lsan={\"include\":$LSAN}" >> "$GITHUB_OUTPUT" + echo "msan={\"include\":$MSAN}" >> "$GITHUB_OUTPUT" # GitHub rejects an empty matrix, so a job whose legs were all # deselected is skipped through these flags instead. echo "has_unix=$(jq 'length > 0' <<< "$UNIX")" >> "$GITHUB_OUTPUT" @@ -403,6 +410,11 @@ jobs: echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang-21 + # ccache was installed before clang-21, so update-ccache-symlinks did + # not create masquerade links for clang-21/clang++-21; without them + # CC=clang-21 bypasses ccache completely (~11m cold build every run). + sudo ln -sf /usr/bin/ccache /usr/lib/ccache/clang-21 + sudo ln -sf /usr/bin/ccache /usr/lib/ccache/clang++-21 - name: Compiler cache (content-verified, restore) uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -455,6 +467,12 @@ jobs: path: ${{ github.workspace }}/.ccache key: ccache-diag-${{ github.ref }}-${{ github.sha }} + - name: ccache stats + if: always() + run: ccache -s || true + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + # MemorySanitizer lane (stage 2). Uninitialized READS are the one # memory-error class no other lane covers dynamically. The image carries # MSan-instrumented libc++/libc++abi/libunwind + zlib (vendored C deps @@ -479,7 +497,11 @@ jobs: # Per-cause detail lives in scripts/msan.sh, which is the single authoritative # list both venues now share. test-msan: + needs: setup-matrix if: ${{ inputs.lanes == 'all' || contains(fromJSON(inputs.lanes), 'msan') }} + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.setup-matrix.outputs.msan) }} runs-on: ubuntu-latest timeout-minutes: 180 steps: @@ -510,14 +532,24 @@ jobs: # refuses, and it aborts ("CHECK failed: msan_linux.cpp:193 ... # personality") before any test runs. The container shares this kernel. env: + CBM_TEST_SHARD: ${{ matrix.shard }} + CBM_TEST_LEG: msan-clang21 CBM_SKIP_PERF: ${{ inputs.skip_perf && '1' || '' }} CCACHE_MAXSIZE: 2500M run: | sudo sysctl -w vm.mmap_rnd_bits=28 || true scripts/ci/msan-lane.sh run - - name: Compiler cache (save) + - name: Shard manifest (completeness proof) if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: shard-manifest-msan-${{ strategy.job-index }} + path: build/msan/test-logs/shard-manifest.txt + if-no-files-found: warn + + - name: Compiler cache (save) + if: always() && (matrix.shard == null || startsWith(matrix.shard, '1/')) uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ github.workspace }}/.ccache @@ -597,6 +629,12 @@ jobs: path: ${{ github.workspace }}/.ccache key: ccache-lsan-${{ github.ref }}-${{ github.sha }} + - name: ccache stats + if: always() + run: ccache -s || true + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + test-tsan: needs: setup-matrix if: ${{ needs.setup-matrix.outputs.has_tsan == 'true' }} @@ -796,7 +834,7 @@ jobs: # catches it. Runs and gates on unsharded topologies too (every leg then # contributes one 1/1 manifest whose slice must equal the full list). shard-completeness: - needs: [test-unix, test-windows, test-diag, test-lsan-macos] + needs: [test-unix, test-windows, test-diag, test-lsan-macos, test-msan] if: always() runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/Makefile.cbm b/Makefile.cbm index a791671f83..d67e3ad073 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -436,17 +436,43 @@ EXTRACTION_SRCS = \ $(CBM_DIR)/resolve_stats.c \ $(CBM_DIR)/extract_scope.c -# LSP resolvers (compiled as one unit via lsp_all.c) +# LSP resolvers (30 independent translation units listed in lsp_all.c; +# compiled per-file with -c -MMD -MP so cold builds parallelize across cores, +# ccache caches unchanged resolvers across edits, and CodeQL traces LSP files +# in parallel). internal/cbm/lsp_all.c remains for Go/CGo compatibility. LSP_SRCS = $(CBM_DIR)/lsp_all.c +LSP_SPLIT_SRCS = \ + $(CBM_DIR)/lsp/type_rep.c \ + $(CBM_DIR)/lsp/scope.c \ + $(CBM_DIR)/lsp/type_registry.c \ + $(CBM_DIR)/lsp/member_walk.c \ + $(CBM_DIR)/lsp/go_lsp.c \ + $(CBM_DIR)/lsp/generated/go_stdlib_data.c \ + $(CBM_DIR)/lsp/c_lsp.c \ + $(CBM_DIR)/lsp/generated/c_stdlib_data.c \ + $(CBM_DIR)/lsp/generated/cpp_stdlib_data.c \ + $(CBM_DIR)/lsp/php_lsp.c \ + $(CBM_DIR)/lsp/generated/php_stdlib_data.c \ + $(CBM_DIR)/lsp/perl_lsp.c \ + $(CBM_DIR)/lsp/generated/perl_stdlib_data.c \ + $(CBM_DIR)/lsp/ruby_lsp.c \ + $(CBM_DIR)/lsp/generated/ruby_stdlib_data.c \ + $(CBM_DIR)/lsp/generated/python_stdlib_data.c \ + $(CBM_DIR)/lsp/py_lsp.c \ + $(CBM_DIR)/lsp/ts_lsp.c \ + $(CBM_DIR)/lsp/cs_lsp.c \ + $(CBM_DIR)/lsp/generated/cs_stdlib_data.c \ + $(CBM_DIR)/lsp/java_lsp.c \ + $(CBM_DIR)/lsp/generated/java_stdlib_data.c \ + $(CBM_DIR)/lsp/generated/kotlin_stdlib_data.c \ + $(CBM_DIR)/lsp/kotlin_lsp.c \ + $(CBM_DIR)/lsp/generated/rust_stdlib_data.c \ + $(CBM_DIR)/lsp/generated/rust_crates_seed.c \ + $(CBM_DIR)/lsp/rust_cargo.c \ + $(CBM_DIR)/lsp/rust_proc_macros.c \ + $(CBM_DIR)/lsp/rust_rustdoc.c \ + $(CBM_DIR)/lsp/rust_lsp.c -# Header/source dependencies of the lsp_all unity object. lsp_all.c #includes -# every lsp/*.c resolver, which in turn include cbm.h — and CBMCall is copied -# BY VALUE across the lsp -> pipeline boundary (cbm_calls_push). This object is -# compiled standalone and linked in, NOT recompiled with the rest on every link, -# so it must list the headers/sources it pulls in. Without this, a changed struct -# layout (e.g. a new CBMCall field) leaves a stale lsp_all.o with the old layout — -# an ODR mismatch that under-reads the by-value struct copy. Explicit because this -# Makefile does not use compiler auto-dependency (-MMD) generation. LSP_UNITY_DEPS = $(CBM_DIR)/lsp_all.c \ $(wildcard $(CBM_DIR)/lsp/*.c $(CBM_DIR)/lsp/*.h \ $(CBM_DIR)/lsp/generated/*.c $(CBM_DIR)/*.h) @@ -1050,14 +1076,14 @@ GRAMMAR_CFLAGS_TEST = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_I GRAMMAR_CFLAGS_TSAN = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \ -DCBM_ENABLE_TEST_SEAMS=1 -DCBM_SANITIZED_BUILD=1 $(TSAN_SANITIZE) -# Object files for grammars + ts_runtime + lsp_all + preprocessor +# Object files for grammars + ts_runtime + per-file LSP + preprocessor GRAMMAR_OBJS_TEST = $(patsubst $(CBM_DIR)/%.c,$(BUILD_DIR)/%.o,$(GRAMMAR_SRCS)) TS_RUNTIME_OBJ_TEST = $(BUILD_DIR)/ts_runtime.o -LSP_OBJ_TEST = $(BUILD_DIR)/lsp_all.o +LSP_OBJ_TEST = $(patsubst %.c,$(BUILD_DIR)/tl/%.o,$(LSP_SPLIT_SRCS)) PP_OBJ_TEST = $(BUILD_DIR)/preprocessor.o GRAMMAR_OBJS_TSAN = $(patsubst $(CBM_DIR)/%.c,$(BUILD_DIR)/tsan_%.o,$(GRAMMAR_SRCS)) TS_RUNTIME_OBJ_TSAN = $(BUILD_DIR)/tsan_ts_runtime.o -LSP_OBJ_TSAN = $(BUILD_DIR)/tsan_lsp_all.o +LSP_OBJ_TSAN = $(patsubst %.c,$(BUILD_DIR)/sl/%.o,$(LSP_SPLIT_SRCS)) PP_OBJ_TSAN = $(BUILD_DIR)/tsan_preprocessor.o # ── Targets ────────────────────────────────────────────────────── @@ -1142,9 +1168,6 @@ $(BUILD_DIR)/%.o: $(CBM_DIR)/%.c $(GRAMMAR_UNITY_DEPS) | $(BUILD_DIR) $(BUILD_DIR)/ts_runtime.o: $(TS_RUNTIME_DEPS) | $(BUILD_DIR) $(CC) $(GRAMMAR_CFLAGS_TEST) -c -o $@ $< -$(BUILD_DIR)/lsp_all.o: $(LSP_UNITY_DEPS) | $(BUILD_DIR) - $(CC) $(GRAMMAR_CFLAGS_TEST) $(SANITIZE) $(TEST_COVERAGE_FLAGS) -c -o $@ $< - $(BUILD_DIR)/preprocessor.o: $(CBM_DIR)/preprocessor.cpp | $(BUILD_DIR) $(CXX) $(CXXFLAGS_TEST) -w -I$(CBM_DIR)/vendored -c -o $@ $< @@ -1154,9 +1177,6 @@ $(BUILD_DIR)/tsan_%.o: $(CBM_DIR)/%.c $(GRAMMAR_UNITY_DEPS) | $(BUILD_DIR) $(BUILD_DIR)/tsan_ts_runtime.o: $(TS_RUNTIME_DEPS) | $(BUILD_DIR) $(CC) $(GRAMMAR_CFLAGS_TSAN) -c -o $@ $< -$(BUILD_DIR)/tsan_lsp_all.o: $(LSP_UNITY_DEPS) | $(BUILD_DIR) - $(CC) $(GRAMMAR_CFLAGS_TSAN) -c -o $@ $< - $(BUILD_DIR)/tsan_preprocessor.o: $(CBM_DIR)/preprocessor.cpp | $(BUILD_DIR) $(CXX) $(CXXFLAGS_TSAN) -w -I$(CBM_DIR)/vendored -c -o $@ $< @@ -1390,30 +1410,35 @@ $(BUILD_DIR)/test-runner-tsan: $(TSAN_RUNNER_OBJS) $(OBJS_VENDORED_TSAN) $(PROJE test-tsan: $(BUILD_DIR)/test-runner-tsan @echo "ThreadSanitizer workers: 4" @cd $(CURDIR) && set -e; \ - daemon_suites=""; other_suites=""; \ + pipe_suites=""; other_suites=""; daemon_suites=""; \ for s in $(TEST_TSAN_SUITES); do \ case "$$s" in \ mcp|daemon|daemon_*) daemon_suites="$$daemon_suites $$s" ;; \ + pipeline) pipe_suites="$$pipe_suites $$s" ;; \ *) other_suites="$$other_suites $$s" ;; \ esac; \ done; \ - if [ -n "$$daemon_suites" ] && [ -n "$$other_suites" ]; then \ + if [ -n "$$pipe_suites" ] && [ -n "$$other_suites" ]; then \ tmpdir=$$(mktemp -d "$${TMPDIR:-/tmp}/cbm-tsan.XXXXXX"); \ trap 'rm -rf "$$tmpdir"' EXIT; \ + CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ + $(BUILD_DIR)/test-runner-tsan $$pipe_suites >"$$tmpdir/pipe.log" 2>&1 & \ + pid_pipe=$$!; \ CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ $(BUILD_DIR)/test-runner-tsan $$other_suites >"$$tmpdir/other.log" 2>&1 & \ pid_other=$$!; \ - CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ - $(BUILD_DIR)/test-runner-tsan $$daemon_suites >"$$tmpdir/daemon.log" 2>&1 & \ - pid_daemon=$$!; \ rc1=0; rc2=0; \ - wait "$$pid_other" || rc1=$$?; \ - wait "$$pid_daemon" || rc2=$$?; \ - cat "$$tmpdir/other.log" "$$tmpdir/daemon.log"; \ + wait "$$pid_pipe" || rc1=$$?; \ + wait "$$pid_other" || rc2=$$?; \ + cat "$$tmpdir/pipe.log" "$$tmpdir/other.log"; \ [ "$$rc1" -eq 0 ] && [ "$$rc2" -eq 0 ]; \ - else \ + elif [ -n "$$pipe_suites$$other_suites" ]; then \ CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ - $(BUILD_DIR)/test-runner-tsan $(TEST_TSAN_SUITES); \ + $(BUILD_DIR)/test-runner-tsan $$pipe_suites $$other_suites; \ + fi; \ + if [ -n "$$daemon_suites" ]; then \ + CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ + $(BUILD_DIR)/test-runner-tsan $$daemon_suites; \ fi # Real-binary POSIX lifecycle smoke. The endpoint is deliberately account-wide; @@ -1427,7 +1452,7 @@ test-daemon-smoke: $(BUILD_DIR)/codebase-memory-mcp # Grammar/TS/LSP objects for production (compiled with relaxed warnings, -O2) GRAMMAR_OBJS_PROD = $(patsubst $(CBM_DIR)/%.c,$(BUILD_DIR)/prod_%.o,$(GRAMMAR_SRCS)) TS_RUNTIME_OBJ_PROD = $(BUILD_DIR)/prod_ts_runtime.o -LSP_OBJ_PROD = $(BUILD_DIR)/prod_lsp_all.o +LSP_OBJ_PROD = $(patsubst %.c,$(BUILD_DIR)/pl/%.o,$(LSP_SPLIT_SRCS)) PP_OBJ_PROD = $(BUILD_DIR)/prod_preprocessor.o # Every prod object whose flags carry a BUILD_CONFIG_SIG variable @@ -1443,9 +1468,6 @@ $(BUILD_DIR)/prod_%.o: $(CBM_DIR)/%.c $(GRAMMAR_UNITY_DEPS) $(BUILD_DIR)/.build- $(BUILD_DIR)/prod_ts_runtime.o: $(TS_RUNTIME_DEPS) $(BUILD_DIR)/.build-config | $(BUILD_DIR) $(CC) $(GRAMMAR_CFLAGS) -c -o $@ $< -$(BUILD_DIR)/prod_lsp_all.o: $(LSP_UNITY_DEPS) $(BUILD_DIR)/.build-config | $(BUILD_DIR) - $(CC) $(GRAMMAR_CFLAGS) $(TEST_COVERAGE_FLAGS) -c -o $@ $< - $(BUILD_DIR)/prod_preprocessor.o: $(CBM_DIR)/preprocessor.cpp $(BUILD_DIR)/.build-config | $(BUILD_DIR) $(CXX) $(CXXFLAGS_PROD) -w -I$(CBM_DIR)/vendored -c -o $@ $< @@ -1866,7 +1888,8 @@ security: cbm ALL_FIRST_PARTY_OBJS = $(sort $(TEST_RUNNER_OBJS) $(TEST_REPRO_OBJS) $(FUZZ_OBJ) \ $(IMAGE_PROBE_TEST_OBJS) $(TSAN_RUNNER_OBJS) \ $(PROD_BIN_OBJS) $(PROD_UI_BIN_OBJS)) -OBJ_SUBDIRS = $(patsubst %/,%,$(sort $(dir $(ALL_FIRST_PARTY_OBJS)))) +ALL_LSP_OBJS = $(LSP_OBJ_TEST) $(LSP_OBJ_TSAN) $(LSP_OBJ_PROD) +OBJ_SUBDIRS = $(patsubst %/,%,$(sort $(dir $(ALL_FIRST_PARTY_OBJS) $(ALL_LSP_OBJS)))) $(OBJ_SUBDIRS): @mkdir -p $@ @@ -1883,4 +1906,13 @@ $(BUILD_DIR)/s/%.o: %.c $(BUILD_DIR)/.tsan-build-config | $$(@D) $(BUILD_DIR)/p/%.o: %.c $(BUILD_DIR)/.build-config | $$(@D) $(CC) $(CFLAGS_PROD) -MMD -MP -MF $(@:.o=.d) -c -o $@ $< --include $(ALL_FIRST_PARTY_OBJS:.o=.d) +$(BUILD_DIR)/tl/%.o: %.c $(BUILD_DIR)/.test-build-config | $$(@D) + $(CC) $(GRAMMAR_CFLAGS_TEST) -DCBM_PYTHON_STDLIB_GENERATED=1 $(TEST_COVERAGE_FLAGS) -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + +$(BUILD_DIR)/sl/%.o: %.c $(BUILD_DIR)/.tsan-build-config | $$(@D) + $(CC) $(GRAMMAR_CFLAGS_TSAN) -DCBM_PYTHON_STDLIB_GENERATED=1 -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + +$(BUILD_DIR)/pl/%.o: %.c $(BUILD_DIR)/.build-config | $$(@D) + $(CC) $(GRAMMAR_CFLAGS) -DCBM_PYTHON_STDLIB_GENERATED=1 $(TEST_COVERAGE_FLAGS) -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + +-include $(ALL_FIRST_PARTY_OBJS:.o=.d) $(ALL_LSP_OBJS:.o=.d) diff --git a/scripts/ci/msan-lane.sh b/scripts/ci/msan-lane.sh index bcc897c0c2..b2624fde66 100755 --- a/scripts/ci/msan-lane.sh +++ b/scripts/ci/msan-lane.sh @@ -50,6 +50,8 @@ run_suite() { env_args=() [ -n "${CBM_SKIP_PERF:-}" ] && env_args+=(-e "CBM_SKIP_PERF=$CBM_SKIP_PERF") [ -n "${CBM_MSAN_JOBS:-}" ] && env_args+=(-e "CBM_MSAN_JOBS=$CBM_MSAN_JOBS") + [ -n "${CBM_TEST_SHARD:-}" ] && env_args+=(-e "CBM_TEST_SHARD=$CBM_TEST_SHARD") + [ -n "${CBM_TEST_LEG:-}" ] && env_args+=(-e "CBM_TEST_LEG=$CBM_TEST_LEG") [ -n "${CCACHE_MAXSIZE:-}" ] && env_args+=(-e "CCACHE_MAXSIZE=$CCACHE_MAXSIZE") [ -n "${CBM_NO_CCACHE:-}" ] && env_args+=(-e "CBM_NO_CCACHE=$CBM_NO_CCACHE") docker run --rm -v "$PWD:/src" -w /src -e "CCACHE_DIR=/src/.ccache" \ diff --git a/scripts/ci/require-all-green.sh b/scripts/ci/require-all-green.sh index db6713952e..971023bbab 100755 --- a/scripts/ci/require-all-green.sh +++ b/scripts/ci/require-all-green.sh @@ -80,6 +80,8 @@ if 'LANES' in os.environ: return 'diag' if name.startswith('test / test-lsan-macos ('): return 'lsan-macos' + if name.startswith('test / test-msan ('): + return 'msan' if name.startswith('test / test-package-wrappers'): return 'pkg-wrappers' if name == 'memwaste' or name.startswith('memwaste / '): diff --git a/scripts/msan.sh b/scripts/msan.sh index e91823e776..3cf4d5400b 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -197,15 +197,110 @@ else fi # Run the non-excluded suites in parallel via the canonical parent-owned # wave scheduler (scripts/run-test-wave.py), keeping the exact same - # FLEX/EXCL tail isolation and union guard as scripts/run-tests-parallel.sh. + # FLEX/EXCL tail isolation, deterministic LPT sharding, shard-manifest + # emission, and union guard as scripts/run-tests-parallel.sh. + SHARD_INDEX=1 + SHARD_TOTAL=1 + if [ -n "${CBM_TEST_SHARD:-}" ]; then + if ! printf '%s' "$CBM_TEST_SHARD" | grep -qE '^[0-9]+/[0-9]+$'; then + echo "FATAL: CBM_TEST_SHARD must be i/N, got '$CBM_TEST_SHARD'" >&2 + exit 1 + fi + SHARD_INDEX="${CBM_TEST_SHARD%%/*}" + SHARD_TOTAL="${CBM_TEST_SHARD##*/}" + if [ "$SHARD_TOTAL" -lt 1 ] || [ "$SHARD_INDEX" -lt 1 ] || + [ "$SHARD_INDEX" -gt "$SHARD_TOTAL" ]; then + echo "FATAL: CBM_TEST_SHARD out of range: $CBM_TEST_SHARD" >&2 + exit 1 + fi + fi + + msan_shard_filter() { + local phase="${1:-par}" + awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" ' + BEGIN { + w["incremental"] = 1200 + w["c_lsp_b"] = 340 + w["complexity"] = 260 + w["complexity_b"] = 255 + w["doc_mentions"] = 240 + w["doc_mentions_b"] = 235 + w["doc_mentions_jvm"] = 215 + w["pipeline"] = 185 + w["c_lsp"] = 175 + w["java_type_scope_b"] = 150 + w["java_type_scope"] = 145 + w["extraction"] = 130 + w["stack_overflow_b"] = 115 + w["stack_overflow_c"] = 105 + w["pipeline_b"] = 100 + w["pipeline_c"] = 95 + w["pipeline_semantic_manifest_repro"] = 95 + w["pipeline_semantic_manifest_repro_b"] = 90 + w["stack_overflow_a"] = 88 + w["daemon_frontend"] = 65 + w["php_member_walk"] = 60 + w["edge_types_probe"] = 50 + w["mcp"] = 50 + w["httpd"] = 36 + w["grammar_probe_f"] = 28 + w["grammar_probe_f_b"] = 25 + w["daemon_runtime"] = 25 + w["watcher"] = 12 + w["subprocess"] = 10 + w["index_supervisor"] = 8 + } + { + lines[NR] = $0 + wt[NR] = ($0 in w) ? w[$0] : 5 + } + END { + for (i = 1; i <= NR; i++) { + ord[i] = i + k = i + while (k > 1 && wt[ord[k]] > wt[ord[k - 1]]) { + tmp = ord[k] + ord[k] = ord[k - 1] + ord[k - 1] = tmp + k-- + } + } + for (s = 1; s <= total; s++) load[s] = 0 + for (i = 1; i <= NR; i++) { + if (phase == "flex") { + best = total + for (s = total - 1; s >= 1; s--) { + if (load[s] < load[best]) best = s + } + } else if (phase == "excl" && total > 1) { + best = 2 + for (s = 3; s <= total; s++) { + if (load[s] < load[best]) best = s + } + if (load[1] < load[best]) best = 1 + } else { + best = 1 + for (s = 2; s <= total; s++) { + if (load[s] < load[best]) best = s + } + } + load[best] += wt[ord[i]] + if (best == idx) print lines[ord[i]] + } + } + ' + } + LOGDIR="build/msan/test-logs" rm -rf "$LOGDIR" mkdir -p "$LOGDIR" + ACTIVE_FILE="$LOGDIR/suites-active.txt" PAR_FILE="$LOGDIR/suites-parallel.txt" FLEX_FILE="$LOGDIR/suites-tail-flex.txt" EXCL_FILE="$LOGDIR/suites-tail-excl.txt" EXPECT_FILE="$LOGDIR/suites-expect.txt" RESULTS_FILE="$LOGDIR/results.txt" + : > "$ACTIVE_FILE" : > "$PAR_FILE" : > "$FLEX_FILE" : > "$EXCL_FILE" @@ -224,6 +319,7 @@ else continue ;; esac + echo "$suite" >> "$ACTIVE_FILE" case " $SERIAL_SUITES " in *" $suite "*) case " $TAIL_EXCL " in @@ -234,9 +330,22 @@ else *) echo "$suite" >> "$PAR_FILE" ;; esac done + msan_shard_filter par < "$PAR_FILE" > "$PAR_FILE.shard" && mv "$PAR_FILE.shard" "$PAR_FILE" + msan_shard_filter flex < "$FLEX_FILE" > "$FLEX_FILE.shard" && mv "$FLEX_FILE.shard" "$FLEX_FILE" + msan_shard_filter excl < "$EXCL_FILE" > "$EXCL_FILE.shard" && mv "$EXCL_FILE.shard" "$EXCL_FILE" cat "$PAR_FILE" "$FLEX_FILE" "$EXCL_FILE" > "$EXPECT_FILE" + + { + echo "leg=${CBM_TEST_LEG:-msan-clang21}" + echo "shard=${SHARD_INDEX}/${SHARD_TOTAL}" + echo "list_sha256=$(sort "$ACTIVE_FILE" | { sha256sum 2>/dev/null || shasum -a 256; } | awk '{print $1}')" + echo "selection_sha256=none" + echo "--- slice ---" + cat "$EXPECT_FILE" + } > "$LOGDIR/shard-manifest.txt" + MSAN_JOBS="${CBM_MSAN_JOBS:-$(nproc)}" - echo "=== MSan parallel wave: $(wc -l < "$EXPECT_FILE" | tr -d ' ') suites, $MSAN_JOBS jobs ===" + echo "=== MSan parallel wave: $(wc -l < "$EXPECT_FILE" | tr -d ' ') of $(wc -l < "$ACTIVE_FILE" | tr -d ' ') suites (shard ${SHARD_INDEX}/${SHARD_TOTAL}), $MSAN_JOBS jobs ===" run_msan_wave() { local sfile="$1" jobs="$2" python3 "$ROOT/scripts/run-test-wave.py" \ diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index 2bcc794f2e..2808b59c54 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -212,60 +212,83 @@ fi # greedy bin-packing using empirical cross-platform suite weights, and emit # each shard's slice in descending weight order so run-test-wave.py starts the # heaviest suites at t=0 rather than straggling on idle cores at wave end. -# Because PAR, FLEX, and EXCL are sharded separately below, heavy exclusive -# suites (cli, mcp, daemon_frontend, daemon_runtime, extraction) are also -# balanced independently across shards instead of stacking onto one job. +# Because PAR, FLEX, and EXCL are sharded separately below, each phase uses a +# phase-aware Shard-1 bias and tie-break direction so heavy suites do not stack +# onto Shard 1 (which also runs Step 0 contracts and Step 5 prod guards). shard_filter() { - awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" ' + local phase="${1:-par}" + awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" ' BEGIN { - # Empirical weights (relative seconds across CI legs); unlisted - # suites get default weight 5. Pure deterministic function of - # (suite list, idx, total) so every shard agrees identically. - w["incremental"] = 1600 - w["cli"] = 930 - w["complexity"] = 920 - w["pipeline"] = 890 - w["stack_overflow_b"] = 865 - w["pipeline_b"] = 820 - w["php_member_walk"] = 800 - w["test_impact_git"] = 700 - w["test_impact_git_b"] = 640 - w["c_lsp"] = 660 - w["c_lsp_b"] = 655 - w["pipeline_semantic_manifest_repro"] = 660 - w["doc_mentions"] = 530 - w["doc_mentions_b"] = 520 - w["test_impact_engine"] = 505 - w["java_type_scope"] = 470 - w["java_type_scope_b"] = 465 - w["mcp"] = 450 - w["grammar_probe_f"] = 405 - w["test_impact_tree"] = 385 - w["edge_types_probe"] = 370 - w["stack_overflow_a"] = 360 - w["doc_mentions_jvm"] = 335 - w["type_scope"] = 320 - w["daemon_frontend"] = 315 - w["include_path"] = 270 - w["cypher"] = 260 - w["edge_imports"] = 240 - w["doc_mentions_cost"] = 235 - w["lang_contract"] = 230 - w["py_lsp"] = 215 - w["lsp_resolution_probe"] = 215 - w["watcher"] = 210 - w["test_impact_classify"] = 200 - w["daemon_runtime"] = 180 - w["store_arch"] = 160 - w["extraction"] = 150 - w["grammar_regression"] = 140 - w["py_lsp_stress"] = 140 - w["httpd"] = 130 - w["subprocess"] = 120 - w["daemon_ipc"] = 100 - w["daemon_application"] = 90 - w["index_supervisor"] = 80 + # Empirical weights (calibrated from live cross-platform CI runs); + # unlisted suites get default weight 5. Pure deterministic function + # of (suite list, phase, idx, total) so every shard agrees identically. + w["incremental"] = 1200 + w["pipeline"] = 370 + w["php_member_walk"] = 325 + w["complexity"] = 120 + w["complexity_b"] = 120 + w["edge_types_probe"] = 220 + w["grammar_probe_f"] = 210 + w["grammar_probe_f_b"] = 205 + w["test_impact_git_b"] = 205 + w["test_impact_engine"] = 205 + w["pipeline_b"] = 205 + w["pipeline_c"] = 200 + w["doc_mentions"] = 200 + w["doc_mentions_b"] = 200 + w["c_lsp_b"] = 200 + w["test_impact_git"] = 180 + w["lang_contract"] = 170 + w["cli"] = 170 + w["daemon_runtime"] = 165 + w["stack_overflow_b"] = 165 + w["pipeline_semantic_manifest_repro"] = 155 + w["java_type_scope"] = 155 + w["pipeline_semantic_manifest_repro_b"] = 150 + w["stack_overflow_c"] = 145 + w["daemon_frontend"] = 125 + w["test_impact_tree"] = 120 + w["repro_reference_precision"] = 120 + w["include_path"] = 115 + w["edge_imports"] = 110 + w["type_scope"] = 110 + w["c_lsp"] = 105 + w["java_type_scope_b"] = 105 + w["lsp_resolution_probe"] = 95 + w["node_creation_probe"] = 90 + w["doc_mentions_jvm"] = 85 + w["matrix_new_constructs"] = 80 + w["mcp"] = 75 + w["doc_mentions_rs"] = 75 + w["grammar_probe_d"] = 75 + w["grammar_probe_e"] = 60 w["daemon_bootstrap"] = 60 + w["doc_mentions_go"] = 58 + w["grammar_probe_a"] = 58 + w["doc_mentions_cost"] = 56 + w["pipeline_frozen"] = 54 + w["edge_structural"] = 54 + w["test_impact_classify"] = 52 + w["cypher"] = 50 + w["py_lsp"] = 48 + w["convergence_probe"] = 48 + w["pipeline_conventions"] = 48 + w["doc_links_md"] = 48 + w["artifact"] = 48 + w["stack_overflow_a"] = 42 + w["conditional_variants"] = 42 + w["site_bind"] = 42 + w["watcher"] = 40 + w["grammar_probe_g"] = 38 + w["grammar_probe_b"] = 38 + w["test_impact_tree_read"] = 34 + w["test_impact_inventory"] = 32 + w["extraction"] = 30 + w["httpd"] = 28 + w["subprocess"] = 18 + w["index_supervisor"] = 10 + w["daemon_application"] = 5 + w["daemon_ipc"] = 2 } { lines[NR] = $0 @@ -286,10 +309,29 @@ shard_filter() { } } for (s = 1; s <= total; s++) load[s] = 0 + if (total > 1) { + # Offset Shard 1 for Step 0 contracts + Step 5 prod guards. + if (phase == "par") load[1] = 1000 + else if (phase == "flex") load[1] = 60 + else if (phase == "excl") load[1] = 20 + } for (i = 1; i <= NR; i++) { - best = 1 - for (s = 2; s <= total; s++) { - if (load[s] < load[best]) best = s + if (phase == "flex") { + best = total + for (s = total - 1; s >= 1; s--) { + if (load[s] < load[best]) best = s + } + } else if (phase == "excl" && total > 1) { + best = 2 + for (s = 3; s <= total; s++) { + if (load[s] < load[best]) best = s + } + if (load[1] < load[best]) best = 1 + } else { + best = 1 + for (s = 2; s <= total; s++) { + if (load[s] < load[best]) best = s + } } load[best] += wt[ord[i]] if (best == idx) print lines[ord[i]] @@ -371,9 +413,9 @@ done < "$SUITES_FILE" # Shard the parallel wave, flex tail, and exclusive tail separately via LPT # bin-packing so every shard gets balanced work in all three phases and keeps # its own quiet tail for deadline-sensitive suites. -shard_filter < "$PAR_FILE" > "$PAR_FILE.shard" && mv "$PAR_FILE.shard" "$PAR_FILE" -shard_filter < "$FLEX_FILE" > "$FLEX_FILE.shard" && mv "$FLEX_FILE.shard" "$FLEX_FILE" -shard_filter < "$EXCL_FILE" > "$EXCL_FILE.shard" && mv "$EXCL_FILE.shard" "$EXCL_FILE" +shard_filter par < "$PAR_FILE" > "$PAR_FILE.shard" && mv "$PAR_FILE.shard" "$PAR_FILE" +shard_filter flex < "$FLEX_FILE" > "$FLEX_FILE.shard" && mv "$FLEX_FILE.shard" "$FLEX_FILE" +shard_filter excl < "$EXCL_FILE" > "$EXCL_FILE.shard" && mv "$EXCL_FILE.shard" "$EXCL_FILE" SHARD_EXPECT="$LOGDIR/suites-shard.txt" cat "$PAR_FILE" "$FLEX_FILE" "$EXCL_FILE" > "$SHARD_EXPECT" NSHARD=$(wc -l < "$SHARD_EXPECT" | tr -d ' ') diff --git a/scripts/test.sh b/scripts/test.sh index f9caccb822..5ce7ddbbe3 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -268,12 +268,35 @@ if [ -n "$SUITES" ]; then exit "$?" fi +# Secondary shards (CBM_TEST_SHARD=i/N with i > 1) run on the identical OS, +# arch, compiler, and commit as shard 1/N. Shard 1/N runs and gates all +# leg-level static contracts (Step 0) and binary/security guards (Steps 2b, 2c, +# 3a, 5, 6); skipping those duplicate steps on shards 2..N saves 3-7.5 minutes +# per secondary shard with zero coverage loss (ci-ok + shard-completeness +# require shard 1/N to pass). +SECONDARY_SHARD=0 +if [ "$CONTRACTS_ONLY" -eq 0 ] && [ "${CBM_TEST_SEQUENTIAL:-0}" != "1" ] && + [ -n "${CBM_TEST_SHARD:-}" ]; then + case "$CBM_TEST_SHARD" in + [0-9]*/[0-9]*) + shard_i="${CBM_TEST_SHARD%%/*}" + shard_n="${CBM_TEST_SHARD##*/}" + if [ "$shard_n" -gt 1 ] && [ "$shard_i" -gt 1 ]; then + SECONDARY_SHARD=1 + fi + ;; + esac +fi + # Step 0: fast build/security harness regressions run before the compiler-heavy # suite. Each contract script is self-contained (reads the repo read-only and # isolates any scratch files under mktemp), so running them in parallel across # $NPROC workers cuts Step 0 wall time by ~4x (especially on Windows MSYS2) # with identical coverage and deterministic Step 0a..0z8 output ordering. # Set CBM_CONTRACTS_SEQUENTIAL=1 to run them serially. +if [ "$SECONDARY_SHARD" -eq 1 ]; then + echo "=== Step 0: skipped on secondary shard $CBM_TEST_SHARD (gated by shard 1) ===" +else CONTRACT_JOBS="$NPROC" if [ "${CBM_CONTRACTS_SEQUENTIAL:-0}" = "1" ]; then CONTRACT_JOBS=1 @@ -399,6 +422,7 @@ else: print(f"FAIL: {label} ({rel}) exited {rc}", file=sys.stderr) sys.exit(1) PY +fi if [ "$CONTRACTS_ONLY" -eq 1 ]; then echo "=== test.sh: contracts-only — every contract step passed ===" @@ -424,12 +448,14 @@ assert_test_runner_build_config "$BUILD_DIR/test-runner" "$EXPECTED_SANITIZED" # assert that about the runner executing it. Runs against the runner just built # and BEFORE the suites: it takes seconds, and a selection that silently drops # tests is a property of the harness every later result depends on. -echo "=== Step 2b: per-test selection regression (CBM_TEST_ONLY) ===" -CBM_TEST_RUNNER="$ROOT/$BUILD_DIR/test-runner" bash "$ROOT/tests/test_harness_test_only.sh" -# Step 2c: PR CI's test selection (smart CI) through the parallel harness — the -# selected suites only, unknown suites and tests fail, conditional ones drop. -echo "=== Step 2c: parallel-harness test selection regression ===" -CBM_TEST_RUNNER="$ROOT/$BUILD_DIR/test-runner" bash "$ROOT/tests/test_harness_selection.sh" +if [ "$SECONDARY_SHARD" -eq 0 ]; then + echo "=== Step 2b: per-test selection regression (CBM_TEST_ONLY) ===" + CBM_TEST_RUNNER="$ROOT/$BUILD_DIR/test-runner" bash "$ROOT/tests/test_harness_test_only.sh" + # Step 2c: PR CI's test selection (smart CI) through the parallel harness — the + # selected suites only, unknown suites and tests fail, conditional ones drop. + echo "=== Step 2c: parallel-harness test selection regression ===" + CBM_TEST_RUNNER="$ROOT/$BUILD_DIR/test-runner" bash "$ROOT/tests/test_harness_selection.sh" +fi # PR CI's test selection (smart CI, the select-tests job) narrows the parallel # suite step and nothing else (scripts/run-tests-parallel.sh). A selection that @@ -460,6 +486,12 @@ else make -f Makefile.cbm test-par ${MAKE_ARGS[@]+"${MAKE_ARGS[@]}"} fi +if [ "$SECONDARY_SHARD" -eq 1 ]; then + echo "=== Steps 3a/5/6: skipped on secondary shard $CBM_TEST_SHARD (gated by shard 1) ===" + echo "=== All tests passed ===" + exit 0 +fi + # Step 3a: the runner must ignore an inherited git repository environment # (#2003: the pre-commit hook exports GIT_DIR, which overrides `git -C` and # pointed fixture git commands at the committer's real repository). diff --git a/tests/test_c_lsp.c b/tests/test_c_lsp.c index 0d212d126d..6009e6390c 100644 --- a/tests/test_c_lsp.c +++ b/tests/test_c_lsp.c @@ -17168,6 +17168,12 @@ SUITE(c_lsp) { RUN_TEST(clsp_issue1527_cross_file_memo_failures_propagate); RUN_TEST(clsp_issue1546_cross_entry_points_read_crlf_string_splice); RUN_TEST(clsp_issue1527_long_binary_chain_is_not_nesting); +} + +/* Second half of the C/C++ LSP suite, run as its own parallel unit so the + * two heaviest chain-resolution stress tests execute on separate workers + * instead of serializing in one suite (matches pipeline_b). */ +SUITE(c_lsp_b) { RUN_TEST(clsp_issue1527_long_receiver_chain_is_not_nesting); RUN_TEST(clsp_c_reassigned_function_pointer_calls_join_exact_occurrences); RUN_TEST(clsp_c_nested_function_pointer_shadow_restores_outer_target); @@ -17547,11 +17553,6 @@ SUITE(c_lsp) { RUN_TEST(clsp_pattern_multi_declarator_same_line); RUN_TEST(clsp_pattern_struct_ptr_arrow_chain); RUN_TEST(clsp_pattern_constexpr_variable); -} - -/* Second half of the C/C++ LSP suite, run as its own parallel unit so the - * 778-test suite does not straggle on slower CI runners (matches pipeline_b). */ -SUITE(c_lsp_b) { RUN_TEST(clsp_pattern_inline_variable); RUN_TEST(clsp_pattern_string_view_param); RUN_TEST(clsp_pattern_initializer_list_constructor); diff --git a/tests/test_complexity.c b/tests/test_complexity.c index f314e66fd5..d2227cf30e 100644 --- a/tests/test_complexity.c +++ b/tests/test_complexity.c @@ -2471,6 +2471,11 @@ SUITE(complexity) { RUN_TEST(complexity_go_route_bindings_are_near_linear); RUN_TEST(complexity_name_rows_answer_as_a_scan_does); RUN_TEST(complexity_python_pass_import_join_is_linear); +} + +/* Second half of complexity, split so the 41-test scaling battery runs across + * two parallel workers/shards instead of straggling on sanitizer legs. */ +SUITE(complexity_b) { RUN_TEST(complexity_python_pass_wide_from_import_is_linear); RUN_TEST(complexity_go_import_uses_are_linear); RUN_TEST(complexity_go_pass_registration_is_linear); diff --git a/tests/test_doc_mentions.c b/tests/test_doc_mentions.c index 80df584c50..5693099474 100644 --- a/tests/test_doc_mentions.c +++ b/tests/test_doc_mentions.c @@ -10512,6 +10512,11 @@ SUITE(doc_mentions) { RUN_TEST(doc_mentions_incremental_equals_full); RUN_TEST(doc_mentions_parallel_equals_sequential); RUN_TEST(doc_mentions_cs_scan_dollar_run); +} + +/* Second half of doc_mentions, split at the ~50%-runtime boundary for parallel + * scheduling parity across CI shards (matches pipeline_b). */ +SUITE(doc_mentions_b) { RUN_TEST(doc_mentions_cs_shared_doc_sources); RUN_TEST(doc_mentions_cs_shared_doc_once); RUN_TEST(doc_mentions_cs_shared_doc_replay); @@ -10520,11 +10525,6 @@ SUITE(doc_mentions) { RUN_TEST(doc_mentions_cs_scan_nested_holes); RUN_TEST(doc_mentions_cs_scan_holes_stack); RUN_TEST(doc_mentions_incremental_project_files); -} - -/* Second half of doc_mentions (C# and later cases), split for parallel - * scheduling parity across CI shards (matches pipeline_b). */ -SUITE(doc_mentions_b) { RUN_TEST(doc_mentions_cs_lookup_order); RUN_TEST(doc_mentions_cs_type_parameters); RUN_TEST(doc_mentions_cs_usings); diff --git a/tests/test_grammar_probe_f.c b/tests/test_grammar_probe_f.c index f28aeddc7e..741698bcbe 100644 --- a/tests/test_grammar_probe_f.c +++ b/tests/test_grammar_probe_f.c @@ -8198,6 +8198,11 @@ SUITE(grammar_probe_f) { RUN_TEST(probe_terragrunt_stack_reads); RUN_TEST(probe_terragrunt_stack_includes); RUN_TEST(probe_ansible_files_import_what_they_name); +} + +/* Second half of grammar_probe_f, split so the 206-test infra/config probe + * does not bottleneck Windows CI shards (matches pipeline_b). */ +SUITE(grammar_probe_f_b) { RUN_TEST(probe_terraform_kubernetes_objects_are_resources); RUN_TEST(probe_kustomize_name_prefix_makes_variants); RUN_TEST(probe_ansible_tasks_are_functions); diff --git a/tests/test_main.c b/tests/test_main.c index 4af92b03ac..c93a9e9c12 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -1597,6 +1597,7 @@ extern void suite_workspace(void); extern void suite_platform(void); extern void suite_diagnostics(void); extern void suite_complexity(void); +extern void suite_complexity_b(void); extern void suite_subprocess(void); extern void suite_private_file_lock(void); extern void suite_lock_registry(void); @@ -1665,11 +1666,13 @@ extern void suite_graph_buffer(void); extern void suite_registry(void); extern void suite_pipeline(void); extern void suite_pipeline_b(void); +extern void suite_pipeline_c(void); extern void suite_pipeline_objectscript_timeout(void); extern void suite_pipeline_conventions(void); extern void suite_pipeline_frozen(void); extern void suite_importance(void); extern void suite_pipeline_semantic_manifest_repro(void); +extern void suite_pipeline_semantic_manifest_repro_b(void); extern void suite_cross_repo(void); extern void suite_index_resilience(void); extern void suite_index_format(void); @@ -1790,6 +1793,7 @@ extern void suite_grammar_probe_c(void); extern void suite_grammar_probe_d(void); extern void suite_grammar_probe_e(void); extern void suite_grammar_probe_f(void); +extern void suite_grammar_probe_f_b(void); extern void suite_grammar_probe_g(void); extern void suite_incremental(void); extern void suite_semantic(void); @@ -2441,6 +2445,7 @@ int main(int argc, char **argv) { RUN_SELECTED_SUITE(platform); RUN_SELECTED_SUITE(diagnostics); RUN_SELECTED_SUITE(complexity); + RUN_SELECTED_SUITE(complexity_b); RUN_SELECTED_SUITE(subprocess); RUN_SELECTED_SUITE(private_file_lock); RUN_SELECTED_SUITE(lock_registry); @@ -2527,12 +2532,14 @@ int main(int argc, char **argv) { RUN_SELECTED_SUITE(registry); RUN_SELECTED_SUITE(pipeline); RUN_SELECTED_SUITE(pipeline_b); + RUN_SELECTED_SUITE(pipeline_c); RUN_SELECTED_SUITE(pipeline_objectscript_timeout); RUN_SELECTED_SUITE(pipeline_conventions); RUN_SELECTED_SUITE(pipeline_frozen); RUN_SELECTED_SUITE(importance); RUN_SELECTED_SUITE(index_format); RUN_SELECTED_SUITE(pipeline_semantic_manifest_repro); + RUN_SELECTED_SUITE(pipeline_semantic_manifest_repro_b); RUN_SELECTED_SUITE(call_reference_contract); RUN_SELECTED_SUITE(call_reference_language_complex_contract); RUN_SELECTED_SUITE(repro_call_scope_usages); @@ -2707,6 +2714,7 @@ int main(int argc, char **argv) { RUN_SELECTED_SUITE(grammar_probe_d); RUN_SELECTED_SUITE(grammar_probe_e); RUN_SELECTED_SUITE(grammar_probe_f); + RUN_SELECTED_SUITE(grammar_probe_f_b); RUN_SELECTED_SUITE(grammar_probe_g); RUN_SELECTED_SUITE_PERF(incremental); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index 785895ec82..9ca968a70a 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -40570,6 +40570,11 @@ SUITE(pipeline_b) { RUN_TEST(gitdiff_parse_hunks_no_newline_marker); RUN_TEST(gitdiff_parse_hunks_mode_change); RUN_TEST(gitdiff_parse_hunks_deletion); +} + +/* Third slice of the pipeline suite, split from pipeline_b so each slice stays + * well under ~200s even on Windows ASan shards. */ +SUITE(pipeline_c) { /* Config helpers */ RUN_TEST(configures_is_env_var_name); RUN_TEST(configures_normalize_config_key); @@ -40852,6 +40857,11 @@ SUITE(pipeline_semantic_manifest_repro) { RUN_TEST(helm_parse_error_spoils); RUN_TEST(helm_captures_after_a_huge_capture); RUN_TEST(helm_includes_of_one_name_in_a_loop); +} + +/* Second half of pipeline_semantic_manifest_repro, split for parallel + * scheduling parity across CI shards. */ +SUITE(pipeline_semantic_manifest_repro_b) { RUN_TEST(incremental_compose_dotenv_change_rebuilds); RUN_TEST(incremental_dockerfile_edit_keeps_docker_build_edges); RUN_TEST(incremental_second_build_declarer_keeps_the_edge); diff --git a/tests/test_stack_overflow.c b/tests/test_stack_overflow.c index 8402b0f683..63a3db39aa 100644 --- a/tests/test_stack_overflow.c +++ b/tests/test_stack_overflow.c @@ -901,8 +901,6 @@ SUITE(stack_overflow_b) { RUN_TEST(lsp_ts_inherited_method_lookup); RUN_TEST(lsp_python_deep_nesting_no_crash); RUN_TEST(lsp_go_deep_nesting_no_crash); - RUN_TEST(lsp_php_deep_nesting_no_crash); - RUN_TEST(lsp_kotlin_deep_nesting_no_crash); cbm_shutdown(); } @@ -910,6 +908,8 @@ SUITE(stack_overflow_b) { SUITE(stack_overflow_c) { cbm_init(); + RUN_TEST(lsp_php_deep_nesting_no_crash); + RUN_TEST(lsp_kotlin_deep_nesting_no_crash); RUN_TEST(js_calls_exceed_512); RUN_TEST(python_calls_exceed_512); RUN_TEST(go_calls_exceed_1024); From d96fc0df95f66eb76fb22acf6feddb12ec09639d Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 00:57:13 +0100 Subject: [PATCH 04/11] perf(ci): split cli suite, rebalance pipeline_b/c and msan shards, tune macos slots Signed-off-by: Guillaume Demay --- .github/workflows/_test.yml | 2 +- scripts/msan.sh | 40 +++++++++++++++++------------------ scripts/run-test-wave.py | 1 + scripts/run-tests-parallel.sh | 15 +++++++------ tests/test_cli.c | 34 +++++++++++++++++++++++------ tests/test_main.c | 2 ++ tests/test_pipeline.c | 10 ++++----- 7 files changed, 65 insertions(+), 39 deletions(-) diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index 8627017a5d..aae65210bb 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -139,7 +139,7 @@ jobs: # concurrent runner limits. case "$SHARD_PROFILE" in standard) N_X86=3; N_ARM=2; N_MAC=2; N_MAC_INTEL=3; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; - pr) N_X86=2; N_ARM=2; N_MAC=2; N_MAC_INTEL=3; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; + pr) N_X86=2; N_ARM=2; N_MAC=2; N_MAC_INTEL=2; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; *) echo "::error::unknown shard_profile '$SHARD_PROFILE'"; exit 1 ;; esac if [ "$SHARDS" = "true" ]; then diff --git a/scripts/msan.sh b/scripts/msan.sh index 3cf4d5400b..d78abfbb11 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -167,7 +167,7 @@ echo "=== MSan lane: $(clang --version | head -1) ===" # LESSON FROM (A): an MSan abort that is not a use-of-uninitialized-value # report is a reporting failure until proven otherwise. Look for the read # first (fast unwinding prints it), not for a stack limit. -MSAN_EXCLUDE="${MSAN_EXCLUDE-cli}" +MSAN_EXCLUDE="${MSAN_EXCLUDE-cli cli_b}" if [ "$#" -gt 0 ]; then ./build/msan/test-runner "$@" @@ -220,28 +220,28 @@ else awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" ' BEGIN { w["incremental"] = 1200 - w["c_lsp_b"] = 340 - w["complexity"] = 260 - w["complexity_b"] = 255 - w["doc_mentions"] = 240 - w["doc_mentions_b"] = 235 - w["doc_mentions_jvm"] = 215 - w["pipeline"] = 185 - w["c_lsp"] = 175 - w["java_type_scope_b"] = 150 - w["java_type_scope"] = 145 + w["c_lsp_b"] = 305 + w["doc_mentions_jvm"] = 210 + w["c_lsp"] = 155 + w["stack_overflow_b"] = 140 w["extraction"] = 130 - w["stack_overflow_b"] = 115 - w["stack_overflow_c"] = 105 - w["pipeline_b"] = 100 - w["pipeline_c"] = 95 - w["pipeline_semantic_manifest_repro"] = 95 - w["pipeline_semantic_manifest_repro_b"] = 90 - w["stack_overflow_a"] = 88 + w["pipeline"] = 95 + w["stack_overflow_c"] = 85 + w["java_type_scope"] = 85 + w["complexity_b"] = 85 + w["doc_mentions"] = 80 + w["doc_mentions_b"] = 75 + w["stack_overflow_a"] = 72 w["daemon_frontend"] = 65 w["php_member_walk"] = 60 + w["complexity"] = 55 + w["pipeline_b"] = 50 + w["pipeline_c"] = 50 w["edge_types_probe"] = 50 w["mcp"] = 50 + w["pipeline_semantic_manifest_repro"] = 48 + w["pipeline_semantic_manifest_repro_b"] = 46 + w["java_type_scope_b"] = 45 w["httpd"] = 36 w["grammar_probe_f"] = 28 w["grammar_probe_f_b"] = 25 @@ -305,12 +305,12 @@ else : > "$FLEX_FILE" : > "$EXCL_FILE" : > "$RESULTS_FILE" - SERIAL_SUITES="cli subprocess watcher incremental httpd ui index_resilience mcp \ + SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp \ extraction \ stack_overflow_a stack_overflow_b stack_overflow_c \ index_supervisor daemon_application daemon_runtime daemon_frontend \ daemon_bootstrap daemon_ipc" - TAIL_EXCL="cli mcp index_supervisor daemon_application daemon_runtime \ + TAIL_EXCL="cli cli_b mcp index_supervisor daemon_application daemon_runtime \ daemon_frontend daemon_bootstrap daemon_ipc extraction" for suite in $all_suites; do case " $MSAN_EXCLUDE " in diff --git a/scripts/run-test-wave.py b/scripts/run-test-wave.py index 304c3ba63e..c4303f4f77 100755 --- a/scripts/run-test-wave.py +++ b/scripts/run-test-wave.py @@ -57,6 +57,7 @@ "store_arch", "daemon_runtime", "cli", + "cli_b", "node_creation_probe", "grammar_probe_b", ) diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index 2808b59c54..1f67e40f64 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -239,11 +239,11 @@ shard_filter() { w["c_lsp_b"] = 200 w["test_impact_git"] = 180 w["lang_contract"] = 170 - w["cli"] = 170 - w["daemon_runtime"] = 165 w["stack_overflow_b"] = 165 + w["cli"] = 155 w["pipeline_semantic_manifest_repro"] = 155 w["java_type_scope"] = 155 + w["cli_b"] = 150 w["pipeline_semantic_manifest_repro_b"] = 150 w["stack_overflow_c"] = 145 w["daemon_frontend"] = 125 @@ -262,7 +262,6 @@ shard_filter() { w["doc_mentions_rs"] = 75 w["grammar_probe_d"] = 75 w["grammar_probe_e"] = 60 - w["daemon_bootstrap"] = 60 w["doc_mentions_go"] = 58 w["grammar_probe_a"] = 58 w["doc_mentions_cost"] = 56 @@ -285,9 +284,11 @@ shard_filter() { w["test_impact_inventory"] = 32 w["extraction"] = 30 w["httpd"] = 28 + w["daemon_runtime"] = 25 w["subprocess"] = 18 w["index_supervisor"] = 10 w["daemon_application"] = 5 + w["daemon_bootstrap"] = 3 w["daemon_ipc"] = 2 } { @@ -311,9 +312,9 @@ shard_filter() { for (s = 1; s <= total; s++) load[s] = 0 if (total > 1) { # Offset Shard 1 for Step 0 contracts + Step 5 prod guards. - if (phase == "par") load[1] = 1000 + if (phase == "par") load[1] = 1600 else if (phase == "flex") load[1] = 60 - else if (phase == "excl") load[1] = 20 + else if (phase == "excl") load[1] = 40 } for (i = 1; i <= NR; i++) { if (phase == "flex") { @@ -367,7 +368,7 @@ shard_filter() { # that 40 sits >=2x from both the linear and quadratic signals, so inflating it # would move the test toward the very thing it exists to catch. Quiet is the # fix, and at ~22s the suite is cheap to run alone. -SERIAL_SUITES="cli subprocess watcher incremental httpd ui index_resilience mcp \ +SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp \ extraction \ stack_overflow_a stack_overflow_b stack_overflow_c \ index_supervisor daemon_application daemon_runtime daemon_frontend \ @@ -387,7 +388,7 @@ is_serial() { # the FLEX group's small fixed overlap is load the measurement would absorb. # Strictly sequential is what makes its verdict a function of the code instead # of the scheduler. -TAIL_EXCL="cli mcp index_supervisor daemon_application daemon_runtime \ +TAIL_EXCL="cli cli_b mcp index_supervisor daemon_application daemon_runtime \ daemon_frontend daemon_bootstrap daemon_ipc extraction" is_tail_excl() { case " $TAIL_EXCL " in *" $1 "*) return 0 ;; *) return 1 ;; esac diff --git a/tests/test_cli.c b/tests/test_cli.c index 4fba446f50..bf769986a1 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -21795,15 +21795,28 @@ TEST(cli_index_exit_partial_without_denominator_is_not_graded) { PASS(); } -SUITE(cli) { +static bool cli_suite_setup(const char *tag) { if (!th_secure_runtime_parent_new(g_cli_suite_runtime_parent, - sizeof(g_cli_suite_runtime_parent), "cli-suite")) { + sizeof(g_cli_suite_runtime_parent), tag)) { printf(" %sFAIL%s: could not create private CLI activation runtime\n", tf_red(), tf_reset()); tf_fail_count++; - return; + return false; } cbm_cli_set_activation_runtime_parent_for_test(g_cli_suite_runtime_parent); + return true; +} + +static void cli_suite_teardown(void) { + cbm_cli_set_activation_runtime_parent_for_test(NULL); + test_rmdir_r(g_cli_suite_runtime_parent); + g_cli_suite_runtime_parent[0] = '\0'; +} + +SUITE(cli) { + if (!cli_suite_setup("cli-suite")) { + return; + } RUN_TEST(cli_suite_uses_private_activation_runtime); RUN_TEST(cli_update_only_names_an_installer_that_exists_issue1632); @@ -22055,6 +22068,17 @@ SUITE(cli) { RUN_TEST(cli_cline_data_dir_only_redirects_data_state); RUN_TEST(cli_warp_installs_shared_skill_without_mcp_or_permissions); RUN_TEST(cli_owned_durable_profiles_preserve_user_files); + cli_suite_teardown(); +} + +/* Second half of the CLI suite, split at the ~50%-runtime boundary so the + * exclusive serial tail balances across CI shards instead of serializing all + * 415 CLI tests onto one runner. */ +SUITE(cli_b) { + if (!cli_suite_setup("cli-suite-b")) { + return; + } + RUN_TEST(cli_tiered_codex_profiles_migrate_preserve_and_uninstall); RUN_TEST(cli_tiered_opencode_profiles_migrate_v0108_render); RUN_TEST(cli_tiered_vibe_installs_matching_agent_prompt_sets); @@ -22329,7 +22353,5 @@ SUITE(cli) { RUN_TEST(cli_index_exit_negative_threshold_disables_the_check); RUN_TEST(cli_index_exit_unreadable_threshold_falls_back_to_default); RUN_TEST(cli_index_exit_partial_without_denominator_is_not_graded); - cbm_cli_set_activation_runtime_parent_for_test(NULL); - test_rmdir_r(g_cli_suite_runtime_parent); - g_cli_suite_runtime_parent[0] = '\0'; + cli_suite_teardown(); } diff --git a/tests/test_main.c b/tests/test_main.c index c93a9e9c12..f1094d71a8 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -1741,6 +1741,7 @@ extern void suite_diagrams(void); extern void suite_openapi(void); extern void suite_infrascan(void); extern void suite_cli(void); +extern void suite_cli_b(void); extern void suite_runtime_settings(void); extern void suite_agent_clients(void); extern void suite_agent_profiles(void); @@ -2643,6 +2644,7 @@ int main(int argc, char **argv) { /* CLI (install, update, config) */ RUN_SELECTED_SUITE(cli); + RUN_SELECTED_SUITE(cli_b); RUN_SELECTED_SUITE(runtime_settings); RUN_SELECTED_SUITE(agent_clients); RUN_SELECTED_SUITE(agent_profiles); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index 9ca968a70a..ab28966daf 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -40493,6 +40493,11 @@ SUITE(pipeline_b) { RUN_TEST(pipeline_python_base_rebound_in_compound_class_is_a_stated_limit_parallel); RUN_TEST(pipeline_python_base_type_checking_import_binds_nothing); RUN_TEST(pipeline_python_base_type_checking_import_binds_nothing_parallel); +} + +/* Third slice of the pipeline suite, split at the ~50%-runtime boundary of + * pipeline_b so each slice stays well under ~200s on Windows ASan shards. */ +SUITE(pipeline_c) { RUN_TEST(pipeline_python_base_type_checking_reimport_is_matched_by_position); RUN_TEST(pipeline_python_base_type_checking_reimport_is_matched_by_position_parallel); RUN_TEST(pipeline_python_base_type_checking_import_dropped_from_the_list); @@ -40570,11 +40575,6 @@ SUITE(pipeline_b) { RUN_TEST(gitdiff_parse_hunks_no_newline_marker); RUN_TEST(gitdiff_parse_hunks_mode_change); RUN_TEST(gitdiff_parse_hunks_deletion); -} - -/* Third slice of the pipeline suite, split from pipeline_b so each slice stays - * well under ~200s even on Windows ASan shards. */ -SUITE(pipeline_c) { /* Config helpers */ RUN_TEST(configures_is_env_var_name); RUN_TEST(configures_normalize_config_key); From 986f09e01026edc3b9ba63ec1707d8a3c96c0ba3 Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 01:35:51 +0100 Subject: [PATCH 05/11] perf(ci): rebalance shard offsets, MSan weights, CLI split, and x86/win sharding Signed-off-by: Guillaume Demay --- .github/workflows/_test.yml | 4 ++-- scripts/msan.sh | 24 ++++++++++++------------ scripts/run-tests-parallel.sh | 7 +++---- tests/test_cli.c | 21 ++++++++++----------- 4 files changed, 27 insertions(+), 29 deletions(-) diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index aae65210bb..a0b2e449be 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -138,8 +138,8 @@ jobs: # every leg near ~10 min while respecting GitHub's 20 total / 5 macOS # concurrent runner limits. case "$SHARD_PROFILE" in - standard) N_X86=3; N_ARM=2; N_MAC=2; N_MAC_INTEL=3; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; - pr) N_X86=2; N_ARM=2; N_MAC=2; N_MAC_INTEL=2; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; + standard) N_X86=3; N_ARM=2; N_MAC=2; N_MAC_INTEL=3; N_WIN=6; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; + pr) N_X86=3; N_ARM=2; N_MAC=2; N_MAC_INTEL=2; N_WIN=6; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; *) echo "::error::unknown shard_profile '$SHARD_PROFILE'"; exit 1 ;; esac if [ "$SHARDS" = "true" ]; then diff --git a/scripts/msan.sh b/scripts/msan.sh index d78abfbb11..128a341bc2 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -220,29 +220,29 @@ else awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" ' BEGIN { w["incremental"] = 1200 - w["c_lsp_b"] = 305 - w["doc_mentions_jvm"] = 210 - w["c_lsp"] = 155 + w["c_lsp_b"] = 350 + w["pipeline"] = 215 + w["complexity"] = 165 w["stack_overflow_b"] = 140 w["extraction"] = 130 - w["pipeline"] = 95 + w["java_type_scope"] = 90 w["stack_overflow_c"] = 85 - w["java_type_scope"] = 85 - w["complexity_b"] = 85 - w["doc_mentions"] = 80 - w["doc_mentions_b"] = 75 + w["pipeline_c"] = 75 w["stack_overflow_a"] = 72 + w["complexity_b"] = 65 w["daemon_frontend"] = 65 w["php_member_walk"] = 60 - w["complexity"] = 55 - w["pipeline_b"] = 50 - w["pipeline_c"] = 50 - w["edge_types_probe"] = 50 + w["doc_mentions_b"] = 55 w["mcp"] = 50 w["pipeline_semantic_manifest_repro"] = 48 w["pipeline_semantic_manifest_repro_b"] = 46 + w["doc_mentions_jvm"] = 45 w["java_type_scope_b"] = 45 + w["pipeline_b"] = 40 + w["doc_mentions"] = 38 w["httpd"] = 36 + w["c_lsp"] = 35 + w["edge_types_probe"] = 32 w["grammar_probe_f"] = 28 w["grammar_probe_f_b"] = 25 w["daemon_runtime"] = 25 diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index 1f67e40f64..54bd0ce466 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -240,10 +240,10 @@ shard_filter() { w["test_impact_git"] = 180 w["lang_contract"] = 170 w["stack_overflow_b"] = 165 - w["cli"] = 155 + w["cli"] = 160 w["pipeline_semantic_manifest_repro"] = 155 w["java_type_scope"] = 155 - w["cli_b"] = 150 + w["cli_b"] = 155 w["pipeline_semantic_manifest_repro_b"] = 150 w["stack_overflow_c"] = 145 w["daemon_frontend"] = 125 @@ -312,9 +312,8 @@ shard_filter() { for (s = 1; s <= total; s++) load[s] = 0 if (total > 1) { # Offset Shard 1 for Step 0 contracts + Step 5 prod guards. - if (phase == "par") load[1] = 1600 + if (phase == "par") load[1] = 450 else if (phase == "flex") load[1] = 60 - else if (phase == "excl") load[1] = 40 } for (i = 1; i <= NR; i++) { if (phase == "flex") { diff --git a/tests/test_cli.c b/tests/test_cli.c index bf769986a1..89b7c54654 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -21910,6 +21910,16 @@ SUITE(cli) { RUN_TEST(cli_windows_update_hands_off_to_install_script); RUN_TEST(cli_uninstall_removes_only_its_own_windows_user_path_entry_issue2117); #endif + cli_suite_teardown(); +} + +/* Second half of the CLI suite, split right after the daemon-activation + * battery so both halves balance evenly across x86, arm64, and Intel macOS + * CI shards instead of serializing all 415 CLI tests onto one runner. */ +SUITE(cli_b) { + if (!cli_suite_setup("cli-suite-b")) { + return; + } /* Version (2 tests — selfupdate_test.go) */ RUN_TEST(cli_compare_versions); @@ -22068,17 +22078,6 @@ SUITE(cli) { RUN_TEST(cli_cline_data_dir_only_redirects_data_state); RUN_TEST(cli_warp_installs_shared_skill_without_mcp_or_permissions); RUN_TEST(cli_owned_durable_profiles_preserve_user_files); - cli_suite_teardown(); -} - -/* Second half of the CLI suite, split at the ~50%-runtime boundary so the - * exclusive serial tail balances across CI shards instead of serializing all - * 415 CLI tests onto one runner. */ -SUITE(cli_b) { - if (!cli_suite_setup("cli-suite-b")) { - return; - } - RUN_TEST(cli_tiered_codex_profiles_migrate_preserve_and_uninstall); RUN_TEST(cli_tiered_opencode_profiles_migrate_v0108_render); RUN_TEST(cli_tiered_vibe_installs_matching_agent_prompt_sets); From 7c83c7c813e431fba7bbf14d7b4b3c8ef441b0ab Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 02:06:15 +0100 Subject: [PATCH 06/11] perf(ci): parallelize Step 5-6 & retrace, split long-tail suites, isolate TSan, sparse-checkout gates Signed-off-by: Guillaume Demay --- .github/workflows/_memwaste.yml | 26 ++++- .github/workflows/_test.yml | 1 + .github/workflows/codeql.yml | 19 +++- .github/workflows/pr.yml | 8 +- Makefile.cbm | 4 +- scripts/msan.sh | 21 ++-- scripts/run-tests-parallel.sh | 34 ++++--- scripts/test.sh | 167 +++++++++++++++++++------------- tests/test_codeql_retrace.sh | 43 ++++++-- tests/test_doc_mentions.c | 12 +++ tests/test_main.c | 8 ++ tests/test_pipeline.c | 6 ++ tests/test_test_impact_git.c | 6 ++ 13 files changed, 251 insertions(+), 104 deletions(-) diff --git a/.github/workflows/_memwaste.yml b/.github/workflows/_memwaste.yml index cb5c508440..5e79a2f0ac 100644 --- a/.github/workflows/_memwaste.yml +++ b/.github/workflows/_memwaste.yml @@ -38,8 +38,19 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install deps timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev python3 clang llvm + run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev python3 clang llvm ccache + - name: Compiler cache (content-verified) + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-memwaste-event-linux-${{ github.ref }}-${{ github.sha }} + restore-keys: | + ccache-memwaste-event-linux-${{ github.ref }}- + ccache-memwaste-event-linux- - name: Event lane on this repository + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 1500M run: | # `cmd | tee` reports TEE's status: without this a failing lane # (a missing exec bit, a build error) passes the step and only @@ -68,10 +79,21 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install deps timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev python3 clang llvm + run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev python3 clang llvm ccache + - name: Compiler cache (content-verified) + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-memwaste-scaling-linux-${{ github.ref }}-${{ github.sha }} + restore-keys: | + ccache-memwaste-scaling-linux-${{ github.ref }}- + ccache-memwaste-scaling-linux- - name: CPU scaling lane (src/ at 2x against 4x) # Report-only: the script exits 1 when it flags a super-linear function. continue-on-error: true + env: + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 1500M run: | # `cmd | tee` reports TEE's status: without this a failing lane # (a missing exec bit, a build error) passes the step and only diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index a0b2e449be..7af04dbf08 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -845,6 +845,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: repo + sparse-checkout: scripts/ci - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index ac0f9d9a95..33d39a9780 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -96,7 +96,20 @@ jobs: - name: Install build dependencies if: ${{ matrix.language == 'c-cpp' }} timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev + run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache + + # Compiler cache ONLY for the untraced vendored prebuild below; the traced + # CodeQL build step keeps job-level CBM_NO_CCACHE=1 so every traced unit + # actually invokes the compiler. + - name: Compiler cache for untraced third-party prebuild + if: ${{ matrix.language == 'c-cpp' && inputs.light }} + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ github.workspace }}/.ccache + key: ccache-codeql-vendored-${{ github.ref }}-${{ github.sha }} + restore-keys: | + ccache-codeql-vendored-${{ github.ref }}- + ccache-codeql-vendored- # PR c-cpp: compile the third-party objects (tree-sitter grammars, # sqlite, mimalloc, lz4, zstd, the tree-sitter runtime: ~1.3 GB of @@ -104,6 +117,10 @@ jobs: # traced build below compiles first-party code only ... - name: Build third-party objects (PR scan, untraced) if: ${{ matrix.language == 'c-cpp' && inputs.light }} + env: + CBM_NO_CCACHE: "0" + CCACHE_DIR: ${{ github.workspace }}/.ccache + CCACHE_MAXSIZE: 1500M run: scripts/build.sh --vendored-only # ... except the vendored files this PR changes: those are rebuilt diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 7112c6cc15..5eb1fc7476 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -56,7 +56,6 @@ jobs: # base, never from the PR: a change cannot narrow its own tests by # changing what selects them. Dry runs and releases never pass a selection. select-tests: - needs: [changes] if: ${{ (vars.TEST_IMPACT_MODE || 'gate') == 'gate' }} runs-on: ubuntu-24.04 timeout-minutes: 30 @@ -190,6 +189,9 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + sparse-checkout: | + scripts/ci + .github/codeql # The pulls/files API lists at most 3000 files: the PR's own count lets # the selector notice a cut list and select everything instead. @@ -449,6 +451,10 @@ jobs: # Needs a checkout (unlike before): the gate logic lives in the canonical # scripts/ci entry, not inline YAML (venue-parity contract). - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: | + scripts/ci + .github/codeql - name: List this run's jobs env: GH_TOKEN: ${{ github.token }} diff --git a/Makefile.cbm b/Makefile.cbm index d67e3ad073..3a0bb4a489 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -1381,7 +1381,7 @@ test-repro: $(BUILD_DIR)/test-repro-runner # written by the configuring thread, read AND CALLED by connection # workers), now fixed with atomics in log.c. Excluding the suite is what # had hidden it. -TEST_TSAN_SUITES ?= mem slab_alloc parallel worker_pool watcher httpd pipeline \ +TEST_TSAN_SUITES ?= mem slab_alloc parallel worker_pool watcher httpd pipeline pipeline_d \ diagnostics mcp mcp_mutation_guard subprocess daemon daemon_application \ daemon_runtime daemon_ipc daemon_frontend # halt_on_error: a race is a bug, stop at the first one. @@ -1413,7 +1413,7 @@ test-tsan: $(BUILD_DIR)/test-runner-tsan pipe_suites=""; other_suites=""; daemon_suites=""; \ for s in $(TEST_TSAN_SUITES); do \ case "$$s" in \ - mcp|daemon|daemon_*) daemon_suites="$$daemon_suites $$s" ;; \ + watcher|httpd|subprocess|mcp|mcp_mutation_guard|daemon|daemon_*) daemon_suites="$$daemon_suites $$s" ;; \ pipeline) pipe_suites="$$pipe_suites $$s" ;; \ *) other_suites="$$other_suites $$s" ;; \ esac; \ diff --git a/scripts/msan.sh b/scripts/msan.sh index 128a341bc2..55405f97e9 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -221,31 +221,36 @@ else BEGIN { w["incremental"] = 1200 w["c_lsp_b"] = 350 - w["pipeline"] = 215 + w["doc_mentions_b"] = 310 w["complexity"] = 165 - w["stack_overflow_b"] = 140 + w["pipeline_semantic_manifest_repro"] = 162 + w["doc_mentions_d"] = 150 w["extraction"] = 130 + w["pipeline_d"] = 115 + w["java_type_scope_b"] = 108 + w["pipeline"] = 105 w["java_type_scope"] = 90 w["stack_overflow_c"] = 85 w["pipeline_c"] = 75 w["stack_overflow_a"] = 72 w["complexity_b"] = 65 w["daemon_frontend"] = 65 - w["php_member_walk"] = 60 - w["doc_mentions_b"] = 55 - w["mcp"] = 50 - w["pipeline_semantic_manifest_repro"] = 48 + w["php_member_walk"] = 57 + w["stack_overflow_b"] = 47 w["pipeline_semantic_manifest_repro_b"] = 46 + w["mcp"] = 45 w["doc_mentions_jvm"] = 45 - w["java_type_scope_b"] = 45 w["pipeline_b"] = 40 - w["doc_mentions"] = 38 w["httpd"] = 36 w["c_lsp"] = 35 w["edge_types_probe"] = 32 w["grammar_probe_f"] = 28 w["grammar_probe_f_b"] = 25 + w["doc_mentions_e"] = 25 w["daemon_runtime"] = 25 + w["doc_mentions"] = 15 + w["test_impact_git_b"] = 15 + w["test_impact_git_c"] = 15 w["watcher"] = 12 w["subprocess"] = 10 w["index_supervisor"] = 8 diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index 54bd0ce466..f0a8bd3cbb 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -223,37 +223,41 @@ shard_filter() { # unlisted suites get default weight 5. Pure deterministic function # of (suite list, phase, idx, total) so every shard agrees identically. w["incremental"] = 1200 - w["pipeline"] = 370 w["php_member_walk"] = 325 - w["complexity"] = 120 - w["complexity_b"] = 120 + w["stack_overflow_b"] = 230 + w["c_lsp_b"] = 220 w["edge_types_probe"] = 220 - w["grammar_probe_f"] = 210 - w["grammar_probe_f_b"] = 205 - w["test_impact_git_b"] = 205 - w["test_impact_engine"] = 205 - w["pipeline_b"] = 205 - w["pipeline_c"] = 200 - w["doc_mentions"] = 200 - w["doc_mentions_b"] = 200 - w["c_lsp_b"] = 200 + w["pipeline_b"] = 210 + w["grammar_probe_f"] = 200 + w["grammar_probe_f_b"] = 200 + w["test_impact_engine"] = 200 + w["pipeline_d"] = 195 + w["pipeline"] = 185 + w["java_type_scope_b"] = 185 + w["pipeline_c"] = 180 w["test_impact_git"] = 180 + w["doc_mentions_e"] = 175 w["lang_contract"] = 170 - w["stack_overflow_b"] = 165 w["cli"] = 160 w["pipeline_semantic_manifest_repro"] = 155 w["java_type_scope"] = 155 w["cli_b"] = 155 w["pipeline_semantic_manifest_repro_b"] = 150 w["stack_overflow_c"] = 145 + w["doc_mentions_b"] = 135 w["daemon_frontend"] = 125 + w["complexity"] = 120 + w["complexity_b"] = 120 w["test_impact_tree"] = 120 w["repro_reference_precision"] = 120 w["include_path"] = 115 + w["doc_mentions"] = 115 + w["doc_mentions_d"] = 115 + w["test_impact_git_b"] = 115 w["edge_imports"] = 110 w["type_scope"] = 110 w["c_lsp"] = 105 - w["java_type_scope_b"] = 105 + w["test_impact_git_c"] = 100 w["lsp_resolution_probe"] = 95 w["node_creation_probe"] = 90 w["doc_mentions_jvm"] = 85 @@ -312,7 +316,7 @@ shard_filter() { for (s = 1; s <= total; s++) load[s] = 0 if (total > 1) { # Offset Shard 1 for Step 0 contracts + Step 5 prod guards. - if (phase == "par") load[1] = 450 + if (phase == "par") load[1] = 350 else if (phase == "flex") load[1] = 60 } for (i = 1; i <= NR; i++) { diff --git a/scripts/test.sh b/scripts/test.sh index 5ce7ddbbe3..60f8e676c6 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -358,7 +358,7 @@ CONTRACTS = [ ("Step 0y2: isolated Windows venue contract", "tests/test_vm_isolation_contract.sh", 1), ("Step 0y3: setup scripts install through the installers' verified path", "tests/test_setup_scripts_contract.sh", 1), ("Step 0z: PR lane selector contract", "tests/test_select_lanes.sh", 26), - ("Step 0z1: CodeQL retraces affected prebuilt objects", "tests/test_codeql_retrace.sh", 168), + ("Step 0z1: CodeQL retraces affected prebuilt objects", "tests/test_codeql_retrace.sh", 35), ("Step 0z2: lane selector history replay", "scripts/test-impact/replay-selector.sh", 1), ("Step 0z3: lane-aware aggregate gates (ci-ok, shard union)", "tests/test_lane_gate_contract.sh", 10), ("Step 0z4: lane wiring (PRs select, dry run and release run all)", "tests/test_lane_wiring_contract.sh", 1), @@ -518,70 +518,105 @@ fi echo "=== Step 5: parent-death watchdog regression (#406/#407) ===" make -j"$NPROC" -f Makefile.cbm cbm TEST_SEAMS=1 ${MAKE_ARGS[@]+"${MAKE_ARGS[@]}"} WATCHDOG_BINARY="$ROOT/$BUILD_DIR/codebase-memory-mcp" -CBM_TEST_BINARY="$WATCHDOG_BINARY" bash "$ROOT/tests/test_parent_watchdog.sh" - -# Step 5-alloc: the production allocator object Step 5 just built. The unit -# suites link mimalloc's debug build without the global override, so they cannot -# see free(NULL) before the allocator's constructor (mimalloc #1341, PR #2562) -# or the vendored local patches; this links small fixtures against -# prod_mimalloc.o itself. -echo "=== Step 5-alloc: production allocator contract (mimalloc #1341 + local patches) ===" -bash "$ROOT/tests/test_prod_allocator_contract.sh" "$ROOT/$BUILD_DIR" - -# Step 5a: that watchdog is also the SMALLEST-stack thread in the image, which -# makes it the first casualty when static TLS grows — glibc takes the TLS block -# out of each thread's own stack allocation. Checked here, against the binary -# Step 5 just built, because the failure it prevents surfaces nowhere near its -# cause (PR #2233: a thread-local cache in an extraction file stopped the index -# worker from starting, on x86-64 only). -echo "=== Step 5a: static-TLS budget against the smallest thread stack ===" -bash "$ROOT/tests/test_thread_stack_tls_contract.sh" "$WATCHDOG_BINARY" - -# Step 5b: worker-mode parent-death watchdog (#845). A supervised index worker -# (`cli --index-worker …`) whose supervisor dies must self-exit instead of -# indexing on as an orphan. Reuses the prod binary built in Step 5. -echo "=== Step 5b: worker-mode watchdog regression (#845) ===" -CBM_TEST_BINARY="$WATCHDOG_BINARY" bash "$ROOT/tests/test_worker_watchdog.sh" - -# Step 5c: a worker-delivered MCP error is transport success. The outer CLI -# still exits nonzero for the user-facing tool error, but the supervisor must -# preserve that response instead of misreporting exit_nonzero as a file crash. -echo "=== Step 5c: worker error-response transport regression ===" -CBM_TEST_BINARY="$WATCHDOG_BINARY" bash "$ROOT/tests/test_worker_error_response.sh" - -# Step 5d (#1388) is DELIBERATELY NOT GATING HERE — see -# tests/test_hook_conflict_notice.sh for the full what-was-tried record. -# Summary: the test forces a client/daemon build mismatch via the -# CBM_TEST_HOOK_CLIENT_BUILD seam and asserts the stdout systemMessage. It is -# reliably green locally against a seam-bearing binary, but on every CI leg the -# forced mismatch raises no cohort conflict at all: the seam is present (the -# test asserts that up front), the forced fingerprint is well-formed (64 hex), -# and `daemon status` reports an active daemon on a DIFFERENT build - yet the -# client joins silently. Until that local-vs-CI divergence in the cohort -# admission path is understood, gating on it would make an unexplained red, and -# skipping it silently would hide the gap. Run it by hand: -# make -f Makefile.cbm cbm TEST_SEAMS=1 && bash tests/test_hook_conflict_notice.sh - -# Step 5e: watcher_enabled kill-switch process regression (#335). Reuses the -# prod binary built in Step 5; drives a real daemon against an isolated cache -# and proves watcher_enabled=false stops the watcher from being built, started -# or registered, while auto_index and manual index_repository keep working. -# Every wait is a bounded poll on an asserted state (a closed daemon lifecycle), -# never a fixed sleep — see the header of the test for why. -echo "=== Step 5e: watcher_enabled kill-switch regression (#335) ===" -CBM_TEST_BINARY="$WATCHDOG_BINARY" bash "$ROOT/tests/test_watcher_disabled.sh" - -# Step 5f: a supervised worker is scoped to the request the daemon admitted, -# never to the CBM_ALLOWED_ROOT it inherited from the daemon starter's -# environment. Reuses the prod binary built in Step 5. -echo "=== Step 5f: worker request-scope regression ===" -CBM_TEST_BINARY="$WATCHDOG_BINARY" bash "$ROOT/tests/test_worker_session_scope.sh" - -# Step 6: security-strings URL allow-list regression. The MSYS2 CLANG64 toolchain -# bakes its package-tracker URL into the static Windows .exe; the binary string -# audit must allow-list it (Windows-only — Linux smoke never saw it). -echo "=== Step 6: security-strings allow-list regression ===" -bash "$ROOT/tests/test_security_strings_allowlist.sh" -bash "$ROOT/tests/test_destructive_ordering_contract.sh" + +# Steps 5, 5-alloc, 5a, 5b, 5c, 5e, 5f, 6 are independent read-only-binary +# regression guards (each isolates its cache/runtime via cbm_test_runtime_init +# or mktemp). Running them concurrently across $NPROC workers (LPT-ordered, +# Step 5e first) cuts ~1m of serial tail on macOS/LSan/Intel while preserving +# identical coverage and canonical deterministic banner output order. +# Step 5d (#1388) remains deliberately non-gating — see tests/test_hook_conflict_notice.sh. +STEP5_JOBS="$NPROC" +if [ "${CBM_CONTRACTS_SEQUENTIAL:-0}" = "1" ]; then + STEP5_JOBS=1 +fi +python3 - "$ROOT" "$BASH" "$STEP5_JOBS" "$WATCHDOG_BINARY" "$ROOT/$BUILD_DIR" <<'PY' +from __future__ import annotations + +import concurrent.futures +import os +import subprocess +import sys + +root, bash_bin, jobs_s, binary, build_dir = sys.argv[1:6] +jobs = max(1, int(jobs_s)) + +# (banner or None if already printed, cmd list, extra env dict, weight for LPT) +GUARDS = [ + (None, [bash_bin, f"{root}/tests/test_parent_watchdog.sh"], {"CBM_TEST_BINARY": binary}, 18), + ("Step 5-alloc: production allocator contract (mimalloc #1341 + local patches)", + [bash_bin, f"{root}/tests/test_prod_allocator_contract.sh", build_dir], {}, 2), + ("Step 5a: static-TLS budget against the smallest thread stack", + [bash_bin, f"{root}/tests/test_thread_stack_tls_contract.sh", binary], {}, 1), + ("Step 5b: worker-mode watchdog regression (#845)", + [bash_bin, f"{root}/tests/test_worker_watchdog.sh"], {"CBM_TEST_BINARY": binary}, 12), + ("Step 5c: worker error-response transport regression", + [bash_bin, f"{root}/tests/test_worker_error_response.sh"], {"CBM_TEST_BINARY": binary}, 18), + ("Step 5e: watcher_enabled kill-switch regression (#335)", + [bash_bin, f"{root}/tests/test_watcher_disabled.sh"], {"CBM_TEST_BINARY": binary}, 60), + ("Step 5f: worker request-scope regression", + [bash_bin, f"{root}/tests/test_worker_session_scope.sh"], {"CBM_TEST_BINARY": binary}, 10), + ("Step 6: security-strings allow-list regression", + [bash_bin, "-ec", + 'bash "$1/tests/test_security_strings_allowlist.sh" && bash "$1/tests/test_destructive_ordering_contract.sh"', + "_", root], {}, 11), +] + +def run_one(item): + idx, _banner, cmd, extra_env = item + env = dict(os.environ) + env.update(extra_env) + popen_kw = {} + if os.name == "nt": + popen_kw["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP + else: + popen_kw["start_new_session"] = True + proc = subprocess.run( + cmd, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + **popen_kw, + ) + return idx, proc.returncode, proc.stdout + +scheduled = sorted( + [(idx, b, c, e, w) for idx, (b, c, e, w) in enumerate(GUARDS)], + key=lambda x: (-x[4], x[0]), +) + +results = {} +if jobs == 1: + for idx, (banner, cmd, extra_env, _w) in enumerate(GUARDS): + if banner: + print(f"=== {banner} ===", flush=True) + _, rc, out = run_one((idx, banner, cmd, extra_env)) + if out: + sys.stdout.write(out) + sys.stdout.flush() + if rc != 0: + sys.exit(rc) +else: + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + futs = [pool.submit(run_one, (idx, b, c, e)) for idx, b, c, e, _ in scheduled] + for fut in concurrent.futures.as_completed(futs): + idx, rc, out = fut.result() + results[idx] = (rc, out) + failed = [] + for idx, (banner, _cmd, _env, _w) in enumerate(GUARDS): + rc, out = results[idx] + if banner: + print(f"=== {banner} ===", flush=True) + if out: + sys.stdout.write(out) + if rc != 0: + failed.append((banner or "Step 5: parent-death watchdog regression (#406/#407)", rc)) + if failed: + for label, rc in failed: + print(f"FAIL: {label} exited {rc}", file=sys.stderr) + sys.exit(1) +PY echo "=== All tests passed ===" diff --git a/tests/test_codeql_retrace.sh b/tests/test_codeql_retrace.sh index 3d596d805a..3d4b04a4f2 100644 --- a/tests/test_codeql_retrace.sh +++ b/tests/test_codeql_retrace.sh @@ -5,9 +5,11 @@ set -euo pipefail ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}" python3 - "$ROOT" "$BASH" <<'PY' +import concurrent.futures import os import pathlib import re +import shutil import subprocess import sys import tempfile @@ -68,8 +70,8 @@ with tempfile.TemporaryDirectory(prefix="cbm-codeql-retrace-") as directory: "cbm-third-party", "BUILD_DIR=build/c", "CC=" + os.environ.get("CC", "cc")] - def compiled(output): - return set(re.findall(r" -c -o build/c/([^\s]+\.o)(?:\s|$)", output)) + def compiled(output, build_dir="build/c"): + return set(re.findall(rf" -c -o {re.escape(build_dir)}/([^\s]+\.o)(?:\s|$)", output)) prebuilt = compiled(run(make)) expected = {"prod_mimalloc.o", "prod_sqlite3.o", "prod_grammar_go.o", @@ -96,15 +98,38 @@ with tempfile.TemporaryDirectory(prefix="cbm-codeql-retrace-") as directory: ("first-party only", ["src/main.c"], set()), ("duplicate changes", ["internal/cbm/grammar_go.c", "internal/cbm/grammar_go.c"], {"prod_grammar_go.o"}), ] - for label, paths, expected_objects in cases: - write("changed.txt", "\n".join(paths) + "\n") - run([bash, "scripts/ci/codeql-retrace-vendored.sh", "--changed", "changed.txt", "retrace.txt"]) - retrace = (work / "retrace.txt").read_text(encoding="utf-8").splitlines() - actual = compiled(run(make + [arg for path in retrace for arg in ("-W", path)])) + + # Run all 13 retrace cases concurrently into isolated build dirs seeded from + # the prebuilt objects so Make startup overhead overlaps across cores + # (especially on Windows MSYS2) while preserving real compilation + rules. + def run_case(item): + idx, label, paths, expected_objects = item + case_build = f"build/case-{idx}" + shutil.copytree(work / "build/c", work / case_build) + changed_file = f"changed-{idx}.txt" + retrace_file = f"retrace-{idx}.txt" + write(changed_file, "\n".join(paths) + "\n") + run([bash, "scripts/ci/codeql-retrace-vendored.sh", "--changed", changed_file, retrace_file]) + retrace = (work / retrace_file).read_text(encoding="utf-8").splitlines() + case_make = ["make", "-j1", "--no-print-directory", "-f", "Makefile.cbm", + "cbm-third-party", f"BUILD_DIR={case_build}", + "CC=" + os.environ.get("CC", "cc")] + actual = compiled(run(case_make + [arg for path in retrace for arg in ("-W", path)]), case_build) if actual != expected_objects: - failures.append(f"{label}: expected {sorted(expected_objects)}, compiled {sorted(actual)}") + return idx, f"{label}: expected {sorted(expected_objects)}, compiled {sorted(actual)}", None + return idx, None, f"PASS {label}: {len(actual)}/{len(prebuilt)} third-party objects retraced" + + workers = max(1, min(len(cases), int(jobs))) + results = {} + with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: + for idx, err, msg in pool.map(run_case, [(i, l, p, e) for i, (l, p, e) in enumerate(cases)]): + results[idx] = (err, msg) + for idx in range(len(cases)): + err, msg = results[idx] + if err: + failures.append(err) else: - print(f"PASS {label}: {len(actual)}/{len(prebuilt)} third-party objects retraced") + print(msg) if failures: print("CODEQL RETRACE CONTRACT VIOLATED:\n " + "\n ".join(failures)) sys.exit(1) diff --git a/tests/test_doc_mentions.c b/tests/test_doc_mentions.c index 5693099474..fbe9608075 100644 --- a/tests/test_doc_mentions.c +++ b/tests/test_doc_mentions.c @@ -10495,6 +10495,12 @@ SUITE(doc_mentions) { RUN_TEST(doc_mentions_cs_control_scopes); RUN_TEST(doc_mentions_cs_control_publication); RUN_TEST(doc_mentions_cs_utf8_surfaces); +} + +/* Second half of doc_mentions, split after doc_mentions_cs_utf8_surfaces so + * doc_mentions_cs_control_publication and doc_mentions_cs_namespace_publication + * run concurrently across Windows and Unix CI shards. */ +SUITE(doc_mentions_e) { RUN_TEST(doc_mentions_cs_namespace_publication); RUN_TEST(doc_mentions_cs_scope_parse_errors); RUN_TEST(doc_mentions_cs_norm_type); @@ -10524,6 +10530,12 @@ SUITE(doc_mentions_b) { RUN_TEST(doc_mentions_cs_scan_header_reads); RUN_TEST(doc_mentions_cs_scan_nested_holes); RUN_TEST(doc_mentions_cs_scan_holes_stack); +} + +/* Continuation of doc_mentions_b, split right after doc_mentions_cs_scan_holes_stack + * so that heavy scanner stress test runs concurrently with the remaining 40 + * resolver/incremental tests under MSan and across CI shards. */ +SUITE(doc_mentions_d) { RUN_TEST(doc_mentions_incremental_project_files); RUN_TEST(doc_mentions_cs_lookup_order); RUN_TEST(doc_mentions_cs_type_parameters); diff --git a/tests/test_main.c b/tests/test_main.c index f1094d71a8..c5989d47b7 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -1623,6 +1623,7 @@ extern void suite_test_impact_changes(void); extern void suite_test_impact_origins(void); extern void suite_test_impact_git(void); extern void suite_test_impact_git_b(void); +extern void suite_test_impact_git_c(void); extern void suite_test_impact_tree(void); extern void suite_test_impact_tree_read(void); extern void suite_test_impact_inventory(void); @@ -1665,6 +1666,7 @@ extern void suite_discover(void); extern void suite_graph_buffer(void); extern void suite_registry(void); extern void suite_pipeline(void); +extern void suite_pipeline_d(void); extern void suite_pipeline_b(void); extern void suite_pipeline_c(void); extern void suite_pipeline_objectscript_timeout(void); @@ -1723,7 +1725,9 @@ extern void suite_traces(void); extern void suite_configlink(void); extern void suite_doclinks(void); extern void suite_doc_mentions(void); +extern void suite_doc_mentions_e(void); extern void suite_doc_mentions_b(void); +extern void suite_doc_mentions_d(void); extern void suite_doc_mentions_cost(void); extern void suite_doc_mentions_msbuild(void); extern void suite_doc_links_md(void); @@ -2477,6 +2481,7 @@ int main(int argc, char **argv) { RUN_SELECTED_SUITE(test_impact_origins); RUN_SELECTED_SUITE(test_impact_git); RUN_SELECTED_SUITE(test_impact_git_b); + RUN_SELECTED_SUITE(test_impact_git_c); RUN_SELECTED_SUITE(test_impact_tree); RUN_SELECTED_SUITE(test_impact_tree_read); RUN_SELECTED_SUITE(test_impact_inventory); @@ -2532,6 +2537,7 @@ int main(int argc, char **argv) { /* Pipeline (M8) */ RUN_SELECTED_SUITE(registry); RUN_SELECTED_SUITE(pipeline); + RUN_SELECTED_SUITE(pipeline_d); RUN_SELECTED_SUITE(pipeline_b); RUN_SELECTED_SUITE(pipeline_c); RUN_SELECTED_SUITE(pipeline_objectscript_timeout); @@ -2622,7 +2628,9 @@ int main(int argc, char **argv) { /* Doc-comment references -> MENTIONS */ RUN_SELECTED_SUITE(doc_mentions); + RUN_SELECTED_SUITE(doc_mentions_e); RUN_SELECTED_SUITE(doc_mentions_b); + RUN_SELECTED_SUITE(doc_mentions_d); RUN_SELECTED_SUITE(doc_mentions_cost); RUN_SELECTED_SUITE(doc_mentions_msbuild); RUN_SELECTED_SUITE(doc_links_md); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index ab28966daf..dc068d8ac5 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -40272,6 +40272,12 @@ SUITE(pipeline) { RUN_TEST(pipeline_jvm_tail_lookup_work_grows_linearly); RUN_TEST(pipeline_needs_engine_lookup_work_grows_linearly); RUN_TEST(pipeline_kotlin_operator_lookup_work_grows_linearly); +} + +/* Second half of SUITE(pipeline), split at the ~50%-runtime boundary so both + * halves execute concurrently across CI shards and TSan Phase 1 without + * leaving a single long-tail pipeline process on Windows/MSan/TSan. */ +SUITE(pipeline_d) { RUN_TEST(pipeline_lsp_index_find_agrees_with_the_matcher); RUN_TEST(pipeline_lsp_index_built_without_tail_asks_the_matcher); RUN_TEST(pipeline_lsp_index_own_caller_disagreement_ends_the_lookup); diff --git a/tests/test_test_impact_git.c b/tests/test_test_impact_git.c index 830e2ac0dc..a696348baa 100644 --- a/tests/test_test_impact_git.c +++ b/tests/test_test_impact_git.c @@ -2467,6 +2467,12 @@ SUITE(test_impact_git_b) { RUN_TEST(test_git_ancestor_changes_output_and_cumulative_limits_publish_no_prefix); RUN_TEST(test_git_ancestor_changes_repeated_calls_share_existing_command_budget); RUN_TEST(test_git_ancestor_changes_history_and_external_driver_guards_apply); +} + +/* Third slice of test_impact_git (blob_batch cases), split at the ~50%-runtime + * boundary from ancestor_changes so both run concurrently across workers and + * macOS/LSan/Windows CI shards. */ +SUITE(test_impact_git_c) { RUN_TEST(test_git_blob_batch_native_bytes_and_both_object_formats); RUN_TEST(test_git_blob_batch_keeps_request_order_duplicates_and_raw_paths); RUN_TEST(test_git_blob_batch_pinned_revisions_and_cache_history_guards); From e063bb229667b5a371deca1a693805711b0931cc Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 02:42:01 +0100 Subject: [PATCH 07/11] fix(ci): use temp log files in parallel Step 0/5-6 (avoid Windows pipe EOF hang) and calibrate MSan/LSan weights Signed-off-by: Guillaume Demay --- scripts/msan.sh | 36 ++--- scripts/run-tests-parallel.sh | 6 +- scripts/test.sh | 242 +++++++++++++++++++--------------- 3 files changed, 157 insertions(+), 127 deletions(-) diff --git a/scripts/msan.sh b/scripts/msan.sh index 55405f97e9..9e06811ae9 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -220,34 +220,36 @@ else awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" ' BEGIN { w["incremental"] = 1200 - w["c_lsp_b"] = 350 - w["doc_mentions_b"] = 310 - w["complexity"] = 165 - w["pipeline_semantic_manifest_repro"] = 162 - w["doc_mentions_d"] = 150 - w["extraction"] = 130 + w["c_lsp_b"] = 375 + w["doc_mentions_jvm"] = 185 + w["pipeline_semantic_manifest_repro"] = 184 + w["c_lsp"] = 154 + w["stack_overflow_c"] = 147 + w["php_member_walk"] = 144 + w["doc_mentions_cost"] = 120 w["pipeline_d"] = 115 - w["java_type_scope_b"] = 108 - w["pipeline"] = 105 - w["java_type_scope"] = 90 - w["stack_overflow_c"] = 85 - w["pipeline_c"] = 75 + w["stack_overflow_b"] = 96 + w["java_type_scope"] = 93 + w["pipeline"] = 89 w["stack_overflow_a"] = 72 w["complexity_b"] = 65 w["daemon_frontend"] = 65 - w["php_member_walk"] = 57 - w["stack_overflow_b"] = 47 + w["doc_mentions_b"] = 58 + w["complexity"] = 54 + w["java_type_scope_b"] = 52 w["pipeline_semantic_manifest_repro_b"] = 46 w["mcp"] = 45 - w["doc_mentions_jvm"] = 45 - w["pipeline_b"] = 40 + w["pipeline_c"] = 37 w["httpd"] = 36 - w["c_lsp"] = 35 w["edge_types_probe"] = 32 + w["pipeline_b"] = 28 w["grammar_probe_f"] = 28 w["grammar_probe_f_b"] = 25 - w["doc_mentions_e"] = 25 + w["extraction"] = 25 w["daemon_runtime"] = 25 + w["doc_mentions_d"] = 24 + w["test_impact_git"] = 22 + w["doc_mentions_e"] = 20 w["doc_mentions"] = 15 w["test_impact_git_b"] = 15 w["test_impact_git_c"] = 15 diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index f0a8bd3cbb..2a5d32478c 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -224,6 +224,7 @@ shard_filter() { # of (suite list, phase, idx, total) so every shard agrees identically. w["incremental"] = 1200 w["php_member_walk"] = 325 + w["doc_mentions_e"] = 240 w["stack_overflow_b"] = 230 w["c_lsp_b"] = 220 w["edge_types_probe"] = 220 @@ -236,7 +237,6 @@ shard_filter() { w["java_type_scope_b"] = 185 w["pipeline_c"] = 180 w["test_impact_git"] = 180 - w["doc_mentions_e"] = 175 w["lang_contract"] = 170 w["cli"] = 160 w["pipeline_semantic_manifest_repro"] = 155 @@ -262,7 +262,7 @@ shard_filter() { w["node_creation_probe"] = 90 w["doc_mentions_jvm"] = 85 w["matrix_new_constructs"] = 80 - w["mcp"] = 75 + w["mcp"] = 100 w["doc_mentions_rs"] = 75 w["grammar_probe_d"] = 75 w["grammar_probe_e"] = 60 @@ -316,7 +316,7 @@ shard_filter() { for (s = 1; s <= total; s++) load[s] = 0 if (total > 1) { # Offset Shard 1 for Step 0 contracts + Step 5 prod guards. - if (phase == "par") load[1] = 350 + if (phase == "par") load[1] = 260 else if (phase == "flex") load[1] = 60 } for (i = 1; i <= NR; i++) { diff --git a/scripts/test.sh b/scripts/test.sh index 60f8e676c6..f121fc7a42 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -307,8 +307,10 @@ from __future__ import annotations import concurrent.futures import os import pathlib +import shutil import subprocess import sys +import tempfile root = pathlib.Path(sys.argv[1]) bash_bin = sys.argv[2] @@ -368,59 +370,70 @@ CONTRACTS = [ ("Step 0z8: test selection (answer -> runner filter) contract", "tests/test_test_impact_selection.sh", 4), ] -def run_one(item: tuple[int, str, str]) -> tuple[int, int, str]: - idx, _label, rel = item - popen_kw: dict[str, object] = {} - if os.name == "nt": - popen_kw["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP - else: - popen_kw["start_new_session"] = True - proc = subprocess.run( - [bash_bin, str(root / rel)], - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - encoding="utf-8", - errors="replace", - **popen_kw, +# Redirect each child to a temp file rather than a PIPE so an orphaned +# grandchild (e.g. Windows pipe-holder helper) can never block subprocess.run +# waiting for pipe EOF after the contract script itself has exited. +# Use mkdtemp + ignore_errors cleanup so an inherited Windows handle cannot +# raise WinError 32 on teardown. +log_root = tempfile.mkdtemp(prefix="cbm-step0-") +try: + log_dir = pathlib.Path(log_root) + + def run_one(item: tuple[int, str, str]) -> tuple[int, int, str]: + idx, _label, rel = item + popen_kw: dict[str, object] = {} + if os.name == "nt": + popen_kw["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP + else: + popen_kw["start_new_session"] = True + log_path = log_dir / f"step0-{idx}.log" + with open(log_path, "wb") as lf: + proc = subprocess.run( + [bash_bin, str(root / rel)], + stdout=lf, + stderr=subprocess.STDOUT, + **popen_kw, + ) + out = log_path.read_text(encoding="utf-8", errors="replace") + return idx, proc.returncode, out + + # Schedule heaviest contracts first (LPT) to avoid long tail stragglers. + scheduled = sorted( + [(idx, label, rel, weight) for idx, (label, rel, weight) in enumerate(CONTRACTS)], + key=lambda x: (-x[3], x[0]), ) - return idx, proc.returncode, proc.stdout - -# Schedule heaviest contracts first (LPT) to avoid long tail stragglers. -scheduled = sorted( - [(idx, label, rel, weight) for idx, (label, rel, weight) in enumerate(CONTRACTS)], - key=lambda x: (-x[3], x[0]), -) - -results: dict[int, tuple[int, str]] = {} -if jobs == 1: - for idx, (label, rel, _weight) in enumerate(CONTRACTS): - print(f"=== {label} ===", flush=True) - _, rc, out = run_one((idx, label, rel)) - if out: - sys.stdout.write(out) - sys.stdout.flush() - if rc != 0: - sys.exit(rc) -else: - with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: - futs = [pool.submit(run_one, (idx, label, rel)) for idx, label, rel, _ in scheduled] - for fut in concurrent.futures.as_completed(futs): - idx, rc, out = fut.result() - results[idx] = (rc, out) - - failed = [] - for idx, (label, rel, _weight) in enumerate(CONTRACTS): - rc, out = results[idx] - print(f"=== {label} ===", flush=True) - if out: - sys.stdout.write(out) - if rc != 0: - failed.append((label, rel, rc)) - if failed: - for label, rel, rc in failed: - print(f"FAIL: {label} ({rel}) exited {rc}", file=sys.stderr) - sys.exit(1) + + results: dict[int, tuple[int, str]] = {} + if jobs == 1: + for idx, (label, rel, _weight) in enumerate(CONTRACTS): + print(f"=== {label} ===", flush=True) + _, rc, out = run_one((idx, label, rel)) + if out: + sys.stdout.write(out) + sys.stdout.flush() + if rc != 0: + sys.exit(rc) + else: + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + futs = [pool.submit(run_one, (idx, label, rel)) for idx, label, rel, _ in scheduled] + for fut in concurrent.futures.as_completed(futs): + idx, rc, out = fut.result() + results[idx] = (rc, out) + + failed = [] + for idx, (label, rel, _weight) in enumerate(CONTRACTS): + rc, out = results[idx] + print(f"=== {label} ===", flush=True) + if out: + sys.stdout.write(out) + if rc != 0: + failed.append((label, rel, rc)) + if failed: + for label, rel, rc in failed: + print(f"FAIL: {label} ({rel}) exited {rc}", file=sys.stderr) + sys.exit(1) +finally: + shutil.rmtree(log_root, ignore_errors=True) PY fi @@ -534,8 +547,11 @@ from __future__ import annotations import concurrent.futures import os +import pathlib +import shutil import subprocess import sys +import tempfile root, bash_bin, jobs_s, binary, build_dir = sys.argv[1:6] jobs = max(1, int(jobs_s)) @@ -561,62 +577,74 @@ GUARDS = [ "_", root], {}, 11), ] -def run_one(item): - idx, _banner, cmd, extra_env = item - env = dict(os.environ) - env.update(extra_env) - popen_kw = {} - if os.name == "nt": - popen_kw["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP - else: - popen_kw["start_new_session"] = True - proc = subprocess.run( - cmd, - env=env, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - encoding="utf-8", - errors="replace", - **popen_kw, +# Redirect each guard to a temp file rather than a PIPE: on Windows, +# test_parent_watchdog.sh spawns an orphaned `sleep 3600` pipe-holder by design +# (to prevent EOF on stdin), which inherits stdout and would block a PIPE +# reader for 3600s after test_parent_watchdog.sh itself has exited cleanly. +# Use mkdtemp + ignore_errors cleanup so an inherited Windows handle cannot +# raise WinError 32 on teardown. +log_root = tempfile.mkdtemp(prefix="cbm-step5-") +try: + log_dir = pathlib.Path(log_root) + + def run_one(item): + idx, _banner, cmd, extra_env = item + env = dict(os.environ) + env.update(extra_env) + popen_kw = {} + if os.name == "nt": + popen_kw["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP + else: + popen_kw["start_new_session"] = True + log_path = log_dir / f"step5-{idx}.log" + with open(log_path, "wb") as lf: + proc = subprocess.run( + cmd, + env=env, + stdout=lf, + stderr=subprocess.STDOUT, + **popen_kw, + ) + out = log_path.read_text(encoding="utf-8", errors="replace") + return idx, proc.returncode, out + + scheduled = sorted( + [(idx, b, c, e, w) for idx, (b, c, e, w) in enumerate(GUARDS)], + key=lambda x: (-x[4], x[0]), ) - return idx, proc.returncode, proc.stdout - -scheduled = sorted( - [(idx, b, c, e, w) for idx, (b, c, e, w) in enumerate(GUARDS)], - key=lambda x: (-x[4], x[0]), -) - -results = {} -if jobs == 1: - for idx, (banner, cmd, extra_env, _w) in enumerate(GUARDS): - if banner: - print(f"=== {banner} ===", flush=True) - _, rc, out = run_one((idx, banner, cmd, extra_env)) - if out: - sys.stdout.write(out) - sys.stdout.flush() - if rc != 0: - sys.exit(rc) -else: - with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: - futs = [pool.submit(run_one, (idx, b, c, e)) for idx, b, c, e, _ in scheduled] - for fut in concurrent.futures.as_completed(futs): - idx, rc, out = fut.result() - results[idx] = (rc, out) - failed = [] - for idx, (banner, _cmd, _env, _w) in enumerate(GUARDS): - rc, out = results[idx] - if banner: - print(f"=== {banner} ===", flush=True) - if out: - sys.stdout.write(out) - if rc != 0: - failed.append((banner or "Step 5: parent-death watchdog regression (#406/#407)", rc)) - if failed: - for label, rc in failed: - print(f"FAIL: {label} exited {rc}", file=sys.stderr) - sys.exit(1) + + results = {} + if jobs == 1: + for idx, (banner, cmd, extra_env, _w) in enumerate(GUARDS): + if banner: + print(f"=== {banner} ===", flush=True) + _, rc, out = run_one((idx, banner, cmd, extra_env)) + if out: + sys.stdout.write(out) + sys.stdout.flush() + if rc != 0: + sys.exit(rc) + else: + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + futs = [pool.submit(run_one, (idx, b, c, e)) for idx, b, c, e, _ in scheduled] + for fut in concurrent.futures.as_completed(futs): + idx, rc, out = fut.result() + results[idx] = (rc, out) + failed = [] + for idx, (banner, _cmd, _env, _w) in enumerate(GUARDS): + rc, out = results[idx] + if banner: + print(f"=== {banner} ===", flush=True) + if out: + sys.stdout.write(out) + if rc != 0: + failed.append((banner or "Step 5: parent-death watchdog regression (#406/#407)", rc)) + if failed: + for label, rc in failed: + print(f"FAIL: {label} exited {rc}", file=sys.stderr) + sys.exit(1) +finally: + shutil.rmtree(log_root, ignore_errors=True) PY echo "=== All tests passed ===" From b26eb2696cea02d0009193ed0fd443d9d301fed7 Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 03:12:37 +0100 Subject: [PATCH 08/11] perf(ci): isolate c_lsp_b under MSan to eliminate swap thrashing and balance daemon/perf shard weights Signed-off-by: Guillaume Demay --- scripts/msan.sh | 40 +++++++++++++++++++---------------- scripts/run-tests-parallel.sh | 20 +++++++++--------- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/scripts/msan.sh b/scripts/msan.sh index 9e06811ae9..8d39ee9515 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -219,24 +219,25 @@ else local phase="${1:-par}" awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" ' BEGIN { - w["incremental"] = 1200 - w["c_lsp_b"] = 375 - w["doc_mentions_jvm"] = 185 - w["pipeline_semantic_manifest_repro"] = 184 - w["c_lsp"] = 154 - w["stack_overflow_c"] = 147 - w["php_member_walk"] = 144 - w["doc_mentions_cost"] = 120 - w["pipeline_d"] = 115 - w["stack_overflow_b"] = 96 - w["java_type_scope"] = 93 - w["pipeline"] = 89 + w["incremental"] = 10 + w["c_lsp_b"] = 150 + w["doc_mentions_jvm"] = 140 + w["pipeline_semantic_manifest_repro"] = 120 + w["c_lsp"] = 120 + w["php_member_walk"] = 120 + w["doc_mentions_cost"] = 110 + w["stack_overflow_c"] = 100 + w["complexity_b"] = 100 + w["pipeline_d"] = 90 + w["java_type_scope_b"] = 90 + w["stack_overflow_b"] = 85 + w["java_type_scope"] = 85 + w["pipeline"] = 80 w["stack_overflow_a"] = 72 - w["complexity_b"] = 65 w["daemon_frontend"] = 65 - w["doc_mentions_b"] = 58 + w["extraction"] = 60 + w["doc_mentions_b"] = 55 w["complexity"] = 54 - w["java_type_scope_b"] = 52 w["pipeline_semantic_manifest_repro_b"] = 46 w["mcp"] = 45 w["pipeline_c"] = 37 @@ -245,7 +246,6 @@ else w["pipeline_b"] = 28 w["grammar_probe_f"] = 28 w["grammar_probe_f_b"] = 25 - w["extraction"] = 25 w["daemon_runtime"] = 25 w["doc_mentions_d"] = 24 w["test_impact_git"] = 22 @@ -312,13 +312,17 @@ else : > "$FLEX_FILE" : > "$EXCL_FILE" : > "$RESULTS_FILE" + # c_lsp_b runs in TAIL_EXCL under MSan so its high shadow+origin memory + # footprint does not overlap 3 other parallel MSan suites and trigger swap + # thrashing on 16 GiB CI runners (which previously slowed co-running suites + # 4-5x on whichever shard drew c_lsp_b). SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp \ - extraction \ + extraction c_lsp_b \ stack_overflow_a stack_overflow_b stack_overflow_c \ index_supervisor daemon_application daemon_runtime daemon_frontend \ daemon_bootstrap daemon_ipc" TAIL_EXCL="cli cli_b mcp index_supervisor daemon_application daemon_runtime \ - daemon_frontend daemon_bootstrap daemon_ipc extraction" + daemon_frontend daemon_bootstrap daemon_ipc extraction c_lsp_b" for suite in $all_suites; do case " $MSAN_EXCLUDE " in *" $suite "*) diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index 2a5d32478c..eae9bc2b3f 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -217,16 +217,16 @@ fi # onto Shard 1 (which also runs Step 0 contracts and Step 5 prod guards). shard_filter() { local phase="${1:-par}" - awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" ' + awk -v idx="$SHARD_INDEX" -v total="$SHARD_TOTAL" -v phase="$phase" -v skip_perf="${CBM_SKIP_PERF:-0}" ' BEGIN { # Empirical weights (calibrated from live cross-platform CI runs); # unlisted suites get default weight 5. Pure deterministic function - # of (suite list, phase, idx, total) so every shard agrees identically. - w["incremental"] = 1200 + # of (suite list, phase, idx, total, skip_perf) so every shard agrees identically. + w["incremental"] = (skip_perf == "1") ? 1 : 1200 w["php_member_walk"] = 325 + w["c_lsp_b"] = 270 w["doc_mentions_e"] = 240 w["stack_overflow_b"] = 230 - w["c_lsp_b"] = 220 w["edge_types_probe"] = 220 w["pipeline_b"] = 210 w["grammar_probe_f"] = 200 @@ -238,16 +238,17 @@ shard_filter() { w["pipeline_c"] = 180 w["test_impact_git"] = 180 w["lang_contract"] = 170 - w["cli"] = 160 + w["cli"] = 185 + w["daemon_runtime"] = 155 w["pipeline_semantic_manifest_repro"] = 155 w["java_type_scope"] = 155 - w["cli_b"] = 155 + w["cli_b"] = 145 + w["complexity_b"] = 145 w["pipeline_semantic_manifest_repro_b"] = 150 w["stack_overflow_c"] = 145 w["doc_mentions_b"] = 135 w["daemon_frontend"] = 125 w["complexity"] = 120 - w["complexity_b"] = 120 w["test_impact_tree"] = 120 w["repro_reference_precision"] = 120 w["include_path"] = 115 @@ -262,6 +263,7 @@ shard_filter() { w["node_creation_probe"] = 90 w["doc_mentions_jvm"] = 85 w["matrix_new_constructs"] = 80 + w["daemon_bootstrap"] = 75 w["mcp"] = 100 w["doc_mentions_rs"] = 75 w["grammar_probe_d"] = 75 @@ -288,11 +290,9 @@ shard_filter() { w["test_impact_inventory"] = 32 w["extraction"] = 30 w["httpd"] = 28 - w["daemon_runtime"] = 25 w["subprocess"] = 18 w["index_supervisor"] = 10 w["daemon_application"] = 5 - w["daemon_bootstrap"] = 3 w["daemon_ipc"] = 2 } { @@ -316,7 +316,7 @@ shard_filter() { for (s = 1; s <= total; s++) load[s] = 0 if (total > 1) { # Offset Shard 1 for Step 0 contracts + Step 5 prod guards. - if (phase == "par") load[1] = 260 + if (phase == "par") load[1] = 180 else if (phase == "flex") load[1] = 60 } for (i = 1; i <= NR; i++) { From c2c67ce793321381c74cf421cde9f09f204ccb7b Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 05:18:26 +0100 Subject: [PATCH 09/11] perf(ci): -O2/-g1/lld builds, fixture & tail parallelism, DAG & smoke speedups Deep multi-layer CI acceleration with zero coverage/sanitizer reduction and zero production src/internal changes: 1. Compiler, linker & sanitizer codegen (Makefile.cbm, Dockerfile.msan, cache-warm.yml): - Compile vendored + first-party test/TSan/MSan objects at -O2 (keeping test-suite TUs tests/*.c at -O1 via GNU Make 3.81 rule ordering) and -g1 (DEBUG_INFO ?= -g1, portable line tables + inline frames). - Auto-probe -fuse-ld=lld on Linux LDFLAGS_TEST/LDFLAGS_TSAN and install lld/lld-21 (added as a late Docker layer with buildx restore-keys so cached libc++/zlib layers are preserved). - Suppress dead ASan UAR prologues only on vendored non-diag test objects (diag keeps full UAR). - Warm cbm TEST_SEAMS=1 (2500M) in cache-warm.yml. 2. Test-fixture 500-800 MB copy/hash/git-spawn elimination (tests/): - Use 1.9 MB test-runner-image-probe instead of 500-800 MB test-runner in macOS cli update tests, daemon_runtime blocking-git probe, and test_impact_git diff-driver probes. - Arm existing runtime fingerprint hash stub for same-binary lifecycle tests in daemon_bootstrap, daemon_frontend, cli_scope, and daemon_runtime Phase 1; reorder daemon_runtime cache-reset tests to the end so real hashing runs once. - Template-cache immutable base SHA-1/SHA-256 repos in test_impact_git (~2,600 git spawns -> ~150). - Add 10s TSParseOptions.progress_callback cap on Windows so_parse_crashes matching POSIX alarm(10). - Split SUITE(mcp) into PAR-wave mcp (422 in-process tests) and FLEX-tail mcp_supervisor (22 fork/worker/deadline tests). 3. Harness, tail scheduling, Windows ACLs & smoke speedups (scripts/): - Move per-suite-isolated daemon/cli/mcp_supervisor suites from TAIL_EXCL (jobs=1) to FLEX_FILE (jobs=2), keeping only extraction (+ MSan c_lsp_b) exclusive. - Cap PAR-wave CBM_WORKERS=2 (exempting default-core-count suites) to avoid 4x oversubscription. - Fast Windows stamp_windows_build_dir (native whoami.exe SID + cached SID + *.exe only without /T over 1,500 .o/.d files). - Smoke: COPYFILE_DISABLE=1 GZIP=-1 local archive, CoW binary copies, drop dead retired-install copy, warm daemon across Phases 3b-5, parallel smoke-wrappers, Phase 15 stderr early-exit. - Parallelize leg K and leg 2K in memwaste-scaling.py (deterministic counter counts unchanged). 4. GitHub Actions DAG, sparse checkouts & caching (.github/workflows/): - Cache merge-base selection binary by HEAD^1 SHA in pr.yml (saved by test-impact-artifact.yml). - Blobless sparse checkouts on _lint.yml (excluding 1.28 GB parser.c), test-package-wrappers, test-ui (+ npm cache), codeql.yml, and memwaste scaling-linux; merge duplicate apt-get updates; Homebrew bottle cache + no-auto-update on macOS legs. - Right-size PR shard counts (N_X86=2, N_WIN=4) to fit GitHub's 20-runner cap without starvation. - CodeQL: wait-for-processing: true + upload-database: !inputs.light + sleep 5+5 (was 60+15). Signed-off-by: Guillaume Demay --- .github/workflows/_lint.yml | 44 ++++--- .github/workflows/_memwaste.yml | 7 ++ .github/workflows/_test.yml | 67 ++++++++--- .github/workflows/cache-warm.yml | 14 +-- .github/workflows/codeql.yml | 32 ++++- .github/workflows/pr.yml | 21 +++- .github/workflows/test-impact-artifact.yml | 18 ++- Makefile.cbm | 100 ++++++++++++---- scripts/memwaste-scaling.py | 12 +- scripts/msan.sh | 8 +- scripts/run-test-wave.py | 26 ++++ scripts/run-tests-parallel.sh | 132 ++++++++++++--------- scripts/smoke-local.sh | 5 +- scripts/smoke-test.sh | 36 ++++-- scripts/smoke-wrappers.sh | 51 ++++++-- test-infrastructure/Dockerfile.msan | 7 ++ tests/image_probe_main.c | 114 ++++++++++++++++++ tests/image_probe_roles.c | 18 +++ tests/test_cli.c | 57 +++++---- tests/test_daemon_bootstrap.c | 11 ++ tests/test_daemon_frontend.c | 12 ++ tests/test_daemon_runtime.c | 95 +++++++-------- tests/test_image_probe.h | 5 +- tests/test_main.c | 2 + tests/test_mcp.c | 56 +++++---- tests/test_stack_overflow.c | 44 ++++++- tests/test_test_impact_git.c | 127 +++++++++++++++++--- 27 files changed, 849 insertions(+), 272 deletions(-) diff --git a/.github/workflows/_lint.yml b/.github/workflows/_lint.yml index 550aa86940..5d128ecc2f 100644 --- a/.github/workflows/_lint.yml +++ b/.github/workflows/_lint.yml @@ -30,6 +30,16 @@ jobs: timeout-minutes: 45 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Exclude 1.28 GB of generated grammar parser.c tables and tools/graph-ui + # while keeping scanner.c + headers for lint-vendored-scanners. + filter: blob:none + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/internal/cbm/vendored/grammars/*/parser.c + !/tools/ + !/graph-ui/ # Tests must pass or fail — no SKIPs except genuinely platform-specific # ones (SKIP_PLATFORM / #ifdef). Fails the lint phase on any plain SKIP(). @@ -37,16 +47,13 @@ jobs: run: bash scripts/check-no-test-skips.sh - name: Install build deps - timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev cmake - - - name: Install LLVM 20 timeout-minutes: 10 run: | - wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc - echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-20 main" | sudo tee /etc/apt/sources.list.d/llvm-20.list - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update - sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang-format-20 + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0 + wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc >/dev/null + echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-20 main" | sudo tee /etc/apt/sources.list.d/llvm-20.list >/dev/null + sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update + sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev cmake clang-format-20 - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 id: cppcheck-cache @@ -96,18 +103,23 @@ jobs: timeout-minutes: 60 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + filter: blob:none + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/internal/cbm/vendored/grammars/ + !/tools/ + !/graph-ui/ - name: Install build deps - timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev - - - name: Install LLVM 21 (pinned analyzer toolchain) timeout-minutes: 10 run: | - wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc - echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update - sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang-tidy-21 + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0 + wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc >/dev/null + echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list >/dev/null + sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update + sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev clang-tidy-21 - name: Memory-analyzer gate run: scripts/ci/lint-mem.sh clang-tidy-21 diff --git a/.github/workflows/_memwaste.yml b/.github/workflows/_memwaste.yml index 5e79a2f0ac..7fe1a8be77 100644 --- a/.github/workflows/_memwaste.yml +++ b/.github/workflows/_memwaste.yml @@ -77,6 +77,13 @@ jobs: timeout-minutes: 60 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + filter: blob:none + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/tools/ + !/graph-ui/ - name: Install deps timeout-minutes: 10 run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev python3 clang llvm ccache diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index 7af04dbf08..f79cae0d52 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -139,7 +139,7 @@ jobs: # concurrent runner limits. case "$SHARD_PROFILE" in standard) N_X86=3; N_ARM=2; N_MAC=2; N_MAC_INTEL=3; N_WIN=6; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; - pr) N_X86=3; N_ARM=2; N_MAC=2; N_MAC_INTEL=2; N_WIN=6; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; + pr) N_X86=2; N_ARM=2; N_MAC=2; N_MAC_INTEL=2; N_WIN=4; N_DIAG=2; N_LSAN=2; N_MSAN=2 ;; *) echo "::error::unknown shard_profile '$SHARD_PROFILE'"; exit 1 ;; esac if [ "$SHARDS" = "true" ]; then @@ -192,7 +192,7 @@ jobs: - name: Install deps (Ubuntu) if: startsWith(matrix.os, 'ubuntu') timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache + run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache lld # Ubuntu 23.10+ ships kernel.apparmor_restrict_unprivileged_userns=1, which # blocks unshare(CLONE_NEWUSER) for unprivileged users. Without this, the @@ -222,6 +222,11 @@ jobs: - name: Install ccache (macOS) if: startsWith(matrix.os, 'macos') + env: + HOMEBREW_NO_AUTO_UPDATE: "1" + HOMEBREW_NO_INSTALL_CLEANUP: "1" + HOMEBREW_NO_ENV_HINTS: "1" + HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: "1" run: command -v ccache >/dev/null 2>&1 || brew install ccache # Verified compiler cache: CCACHE_COMPILERCHECK=content keys every entry @@ -333,6 +338,13 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + filter: blob:none + sparse-checkout-cone-mode: false + sparse-checkout: | + pkg + scripts + tests/test_smoke_wrapper_run.py - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: @@ -365,10 +377,17 @@ jobs: timeout-minutes: 20 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + filter: blob:none + sparse-checkout: | + graph-ui + scripts/ci - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: "22" + cache: npm + cache-dependency-path: graph-ui/package-lock.json - name: CodeAtlasWeb leg (install, unit, style, promises, acceptance, build) run: scripts/ci/test-ui.sh @@ -399,20 +418,18 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Install deps - timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache - - - name: Install LLVM 21 (pinned diagnostic toolchain) + - name: Install deps and LLVM 21 (pinned diagnostic toolchain) timeout-minutes: 10 run: | - wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc - echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update - sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang-21 - # ccache was installed before clang-21, so update-ccache-symlinks did - # not create masquerade links for clang-21/clang++-21; without them - # CC=clang-21 bypasses ccache completely (~11m cold build every run). + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0 + wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc >/dev/null + echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list >/dev/null + sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update + sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache clang-21 lld-21 + sudo ln -sf /usr/bin/ld.lld-21 /usr/bin/ld.lld + # ccache was installed alongside clang-21, so ensure masquerade links + # exist for clang-21/clang++-21; without them CC=clang-21 bypasses + # ccache completely (~11m cold build every run). sudo ln -sf /usr/bin/ccache /usr/lib/ccache/clang-21 sudo ln -sf /usr/bin/ccache /usr/lib/ccache/clang++-21 @@ -512,6 +529,8 @@ jobs: with: path: /tmp/.buildx-msan key: buildx-msan-${{ hashFiles('test-infrastructure/Dockerfile.msan') }} + restore-keys: | + buildx-msan- - name: Build MSan image (cached layers) run: scripts/ci/msan-lane.sh build @@ -578,7 +597,18 @@ jobs: # runner drew the 23 bottle, and passed on the ones that drew 22). A # test verdict must be a function of the code, not of the image snapshot; # moving to a newer major is a deliberate one-line bump here. + - name: Homebrew bottle cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/Library/Caches/Homebrew + key: brew-lsan-llvm22-macos-arm64-v1 + - name: Install LSan-capable toolchain + env: + HOMEBREW_NO_AUTO_UPDATE: "1" + HOMEBREW_NO_INSTALL_CLEANUP: "1" + HOMEBREW_NO_ENV_HINTS: "1" + HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: "1" run: brew install llvm@22 ccache - name: Compiler cache (content-verified, restore) @@ -649,11 +679,16 @@ jobs: - name: Install deps (Ubuntu) if: runner.os == 'Linux' timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang zlib1g-dev ccache + run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang zlib1g-dev ccache lld - name: Install deps (macOS) if: runner.os == 'macOS' - run: brew install ccache + env: + HOMEBREW_NO_AUTO_UPDATE: "1" + HOMEBREW_NO_INSTALL_CLEANUP: "1" + HOMEBREW_NO_ENV_HINTS: "1" + HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: "1" + run: command -v ccache >/dev/null 2>&1 || brew install ccache - name: Compiler cache (content-verified) uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 diff --git a/.github/workflows/cache-warm.yml b/.github/workflows/cache-warm.yml index 736ce0ef02..ddea98417a 100644 --- a/.github/workflows/cache-warm.yml +++ b/.github/workflows/cache-warm.yml @@ -37,7 +37,7 @@ jobs: - name: Install deps (Ubuntu) if: startsWith(matrix.os, 'ubuntu') timeout-minutes: 10 - run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache + run: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache lld - name: Install ccache (macOS) if: startsWith(matrix.os, 'macos') @@ -52,14 +52,14 @@ jobs: ccache-test-${{ matrix.os }}-${{ matrix.cc }}-${{ github.ref }}- ccache-test-${{ matrix.os }}-${{ matrix.cc }}- - - name: Build (test runner + product, no tests) + - name: Build (test runner + product with test seams, no tests) run: | source scripts/env.sh make -j"$(getconf _NPROCESSORS_ONLN)" -f Makefile.cbm \ - build/c/test-runner cbm CC=${{ matrix.cc }} CXX=${{ matrix.cxx }} + build/c/test-runner cbm TEST_SEAMS=1 CC=${{ matrix.cc }} CXX=${{ matrix.cxx }} env: CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1500M + CCACHE_MAXSIZE: 2500M - name: ccache stats run: ccache -sv || ccache -s @@ -103,13 +103,13 @@ jobs: ccache-test-windows-latest-CLANG64-${{ github.ref }}- ccache-test-windows-latest-CLANG64- - - name: Build (test runner + product, no tests) + - name: Build (test runner + product with test seams, no tests) run: | source scripts/env.sh - make -j"$(nproc)" -f Makefile.cbm build/c/test-runner cbm CC=clang CXX=clang++ + make -j"$(nproc)" -f Makefile.cbm build/c/test-runner cbm TEST_SEAMS=1 CC=clang CXX=clang++ env: CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_MAXSIZE: 1500M + CCACHE_MAXSIZE: 2500M - name: ccache stats run: ccache -sv || ccache -s diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 33d39a9780..3fbed3c93b 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -87,11 +87,30 @@ jobs: # only what a traced compiler invocation actually compiles. CBM_NO_CCACHE: "1" steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Checkout (c-cpp) + if: ${{ matrix.language == 'c-cpp' }} + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # The PR scan reads the merge commit's first parent (the base) to # find the vendored files the PR changes. fetch-depth: ${{ inputs.light && 2 || 1 }} + filter: blob:none + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/tools/ + + - name: Checkout (non-C languages) + if: ${{ matrix.language != 'c-cpp' }} + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 1 + filter: blob:none + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/internal/cbm/vendored/ + !/tools/ - name: Install build dependencies if: ${{ matrix.language == 'c-cpp' }} @@ -149,6 +168,8 @@ jobs: uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4 with: category: "/language:${{ matrix.language }}" + upload-database: ${{ !inputs.light }} + wait-for-processing: true # Alert policy: the default branch carries ZERO open code-scanning # alerts. Any open alert on the analysed ref fails this leg: on main the @@ -196,10 +217,13 @@ jobs: esac printf '%s' "$body" } - echo "Waiting 60s for alert API to settle..." - sleep 60 + # Perform CodeQL Analysis runs with wait-for-processing: true, so + # SARIF ingestion has already completed; keep two short back-to-back + # reads to confirm the alert list has settled without paying 75 s of + # blind sleep on every leg. + sleep 5 ALERTS=$(count_open_alerts) || exit 1 - sleep 15 + sleep 5 ALERTS2=$(count_open_alerts) || exit 1 [ "$ALERTS" -lt "$ALERTS2" ] && ALERTS=$ALERTS2 if [ "$ALERTS" -gt 0 ]; then diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 5eb1fc7476..f4e1209b9a 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -73,8 +73,24 @@ jobs: fetch-depth: 0 persist-credentials: false - name: Check out the merge base's selection tooling - run: git worktree add --detach "$RUNNER_TEMP/base-tooling" HEAD^1 + id: base + run: | + git worktree add --detach "$RUNNER_TEMP/base-tooling" HEAD^1 + echo "sha=$(git rev-parse HEAD^1)" >> "$GITHUB_OUTPUT" + - name: Merge-base selection binary cache + id: select-bin + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/cbm-select-bin + key: cbm-select-bin-ubuntu-24.04-gcc-${{ steps.base.outputs.sha }} + - name: Stage cached merge-base binary + if: steps.select-bin.outputs.cache-hit == 'true' + run: | + mkdir -p "$RUNNER_TEMP/base-tooling/build/c" + cp "$RUNNER_TEMP/cbm-select-bin/codebase-memory-mcp" "$RUNNER_TEMP/base-tooling/build/c/codebase-memory-mcp" + chmod +x "$RUNNER_TEMP/base-tooling/build/c/codebase-memory-mcp" - name: Compiler cache (content-verified) + if: steps.select-bin.outputs.cache-hit != 'true' uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ github.workspace }}/.ccache @@ -83,6 +99,7 @@ jobs: ccache-select-ubuntu-24.04-gcc-${{ github.ref }}- ccache-select-ubuntu-24.04-gcc- - name: Build the merge base's engine + if: steps.select-bin.outputs.cache-hit != 'true' timeout-minutes: 20 env: CCACHE_DIR: ${{ github.workspace }}/.ccache @@ -91,6 +108,8 @@ jobs: APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache cd "$RUNNER_TEMP/base-tooling" scripts/build.sh CC=gcc CXX=g++ + mkdir -p "$RUNNER_TEMP/cbm-select-bin" + cp build/c/codebase-memory-mcp "$RUNNER_TEMP/cbm-select-bin/codebase-memory-mcp" - name: Select the tests id: select env: diff --git a/.github/workflows/test-impact-artifact.yml b/.github/workflows/test-impact-artifact.yml index 6fb1c2a007..568b2859a2 100644 --- a/.github/workflows/test-impact-artifact.yml +++ b/.github/workflows/test-impact-artifact.yml @@ -46,11 +46,12 @@ jobs: - name: Install build deps and LLVM 21 (coverage toolchain) timeout-minutes: 10 run: | - APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0; sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update && sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache - wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc - echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list + APT_RETRIES=3; [ -f /etc/apt/apt-mirrors.txt ] && APT_RETRIES=0 + wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc >/dev/null + echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list >/dev/null sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 --error-on=any update - sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y clang-21 llvm-21 libclang-rt-21-dev + sudo apt-get -o Acquire::Retries=$APT_RETRIES -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y zlib1g-dev ccache clang-21 llvm-21 libclang-rt-21-dev lld-21 + sudo ln -sf /usr/bin/ld.lld-21 /usr/bin/ld.lld - name: Compiler cache (content-verified) uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -67,8 +68,17 @@ jobs: CCACHE_MAXSIZE: 2500M run: | scripts/build.sh CC=gcc CXX=g++ + mkdir -p "$RUNNER_TEMP/cbm-select-bin" + cp build/c/codebase-memory-mcp "$RUNNER_TEMP/cbm-select-bin/codebase-memory-mcp" make -f Makefile.cbm test-runner-cov COV_LLVM_BIN=/usr/lib/llvm-21/bin -j"$(nproc)" + - name: Save merge-base selection binary cache for PR select-tests + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/cbm-select-bin + key: cbm-select-bin-ubuntu-24.04-gcc-${{ github.sha }} + - name: Publish the bundle env: GH_TOKEN: ${{ github.token }} diff --git a/Makefile.cbm b/Makefile.cbm index 3a0bb4a489..5bae3d0c38 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -121,6 +121,15 @@ CFLAGS_PROD = $(CFLAGS_COMMON) -O2 -DCBM_BIND_TS_ALLOCATOR=1 $(TEST_SEAM_DEFINE) CXXFLAGS_PROD = $(CXXFLAGS_COMMON) -O2 $(MEMWASTE_VENDOR_CFLAGS) $(TEST_COVERAGE_FLAGS) # Test flags: debug + sanitizers (override SANITIZE= to disable on Windows) +# -g1 emits line tables + inline frames (equivalent to -gline-tables-only on +# Clang and portable to GCC/Apple Clang/MinGW), cutting DWARF size ~75-85% +# while preserving full file:line sanitizer stack traces. +DEBUG_INFO ?= -g1 +# Compile vendored + first-party test/TSan/MSan objects at -O2 (matching +# production CFLAGS_PROD) while keeping test-suite TUs (tests/*.c) at -O1 to +# preserve literal negative-test codegen across 200+ test files. +TEST_OPT ?= -O2 +TEST_SUITE_OPT ?= -O1 SANITIZE = -fsanitize=address,undefined -fno-omit-frame-pointer EDITOR_TEST_DEFINES = -DCBM_JSON_LIKE_ENABLE_TEST_API=1 \ -DCBM_TOML_EDIT_ENABLE_TEST_API=1 -DCBM_YAML_ENABLE_TEST_API=1 \ @@ -143,11 +152,13 @@ CALL_REFERENCE_LOOKUP_TEST_DEFINE = -DCBM_CALL_REFERENCE_LOOKUP_TEST_API=1 INCREMENTAL_TEST_DEFINE = -DCBM_INCREMENTAL_TEST_API=1 COVERAGE_MARKER_TEST_DEFINE = -DCBM_COVERAGE_MARKER_TEST_API=1 MEM_CORE_TEST_DEFINE = -DCBM_MEM_TEST_API=1 -CFLAGS_TEST = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(SANITIZED_DEFINE) \ +CFLAGS_TEST_BASE = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(SANITIZED_DEFINE) \ $(KOTLIN_DEDUP_TEST_DEFINE) $(CALL_REFERENCE_LOOKUP_TEST_DEFINE) \ $(INCREMENTAL_TEST_DEFINE) $(COVERAGE_MARKER_TEST_DEFINE) $(MEM_CORE_TEST_DEFINE) $(TEST_COVERAGE_DEFINE) \ - -g -O1 $(SANITIZE) $(TEST_COVERAGE_FLAGS) -CXXFLAGS_TEST = $(CXXFLAGS_COMMON) $(SANITIZED_DEFINE) -g -O1 $(SANITIZE) $(TEST_COVERAGE_FLAGS) \ + $(DEBUG_INFO) $(SANITIZE) $(TEST_COVERAGE_FLAGS) +CFLAGS_TEST = $(CFLAGS_TEST_BASE) $(TEST_OPT) +CFLAGS_TEST_SUITES = $(CFLAGS_TEST_BASE) $(TEST_SUITE_OPT) +CXXFLAGS_TEST = $(CXXFLAGS_COMMON) $(SANITIZED_DEFINE) $(DEBUG_INFO) $(TEST_OPT) $(SANITIZE) $(TEST_COVERAGE_FLAGS) \ $(CXX_STDLIB_FLAGS) # TSan (can't combine with ASan) @@ -163,11 +174,13 @@ TSAN_SANITIZE = -fsanitize=thread -fno-omit-frame-pointer # C++ alike (CXXFLAGS_TSAN here, GRAMMAR_CFLAGS_TEST/TSAN below). Vendored flag # sets are left alone: mimalloc, sqlite3, tre, zstd, lz4 and tree-sitter read no # macro of ours. -CFLAGS_TSAN = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(KOTLIN_DEDUP_TEST_DEFINE) \ +CFLAGS_TSAN_BASE = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(KOTLIN_DEDUP_TEST_DEFINE) \ $(CALL_REFERENCE_LOOKUP_TEST_DEFINE) $(INCREMENTAL_TEST_DEFINE) \ $(COVERAGE_MARKER_TEST_DEFINE) $(MEM_CORE_TEST_DEFINE) \ - -DCBM_SANITIZED_BUILD=1 -g -O1 $(TSAN_SANITIZE) -CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -DCBM_SANITIZED_BUILD=1 -g -O1 \ + -DCBM_SANITIZED_BUILD=1 $(DEBUG_INFO) $(TSAN_SANITIZE) +CFLAGS_TSAN = $(CFLAGS_TSAN_BASE) $(TEST_OPT) +CFLAGS_TSAN_SUITES = $(CFLAGS_TSAN_BASE) $(TEST_SUITE_OPT) +CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -DCBM_SANITIZED_BUILD=1 $(DEBUG_INFO) $(TEST_OPT) \ $(TSAN_SANITIZE) # Windows needs ws2_32 (Winsock), psapi (GetProcessMemoryInfo), shell32 @@ -338,11 +351,37 @@ endif # because there the shim is what makes mimalloc own the allocations at all. # C++ stdlib selection: MSan builds must link an MSan-instrumented libc++ # instead of the system libstdc++ (scripts/msan.sh overrides both vars). +# Fast multi-threaded linker for Linux test/TSan/MSan runners when lld is +# installed; production LDFLAGS keeps default ld for STATIC=1 and binary +# composition parity. +TEST_LD_FLAGS := +ifeq ($(IS_LINUX),yes) +ifneq ($(IS_MINGW),yes) +ifeq ($(shell echo 'int main(void){return 0;}' | $(CC) -x c - -fuse-ld=lld -o /dev/null 2>/dev/null && echo yes),yes) +TEST_LD_FLAGS := -fuse-ld=lld +endif +endif +endif +# Non-diag ASan lanes run with detect_stack_use_after_return=0 (scripts/test.sh), +# yet compilers still emit per-function runtime UAR prologues in vendored C +# (grammars, tree-sitter, sqlite3, lz4, zstd). Suppress dead UAR prologues on +# vendored objects only; first-party code and the diag lane (which sets +# -fno-optimize-sibling-calls and detect_stack_use_after_return=1) stay untouched. +VENDOR_ASAN_UAR_FLAGS := +ifneq ($(findstring address,$(SANITIZE)),) +ifeq ($(findstring -fno-optimize-sibling-calls,$(SANITIZE)),) +ifeq ($(IS_GCC),yes) +VENDOR_ASAN_UAR_FLAGS := $(shell echo 'int f(void){return 0;}' | $(CC) -x c - -fsanitize=address --param=asan-use-after-return=0 -c -o /dev/null 2>/dev/null && echo '--param=asan-use-after-return=0') +else +VENDOR_ASAN_UAR_FLAGS := $(shell echo 'int f(void){return 0;}' | $(CC) -x c - -fsanitize=address -fsanitize-address-use-after-return=never -c -o /dev/null 2>/dev/null && echo '-fsanitize-address-use-after-return=never') +endif +endif +endif CXX_STDLIB ?= -lstdc++ CXX_STDLIB_FLAGS ?= LDFLAGS = -lm $(CXX_STDLIB) -lpthread -lz $(WIN32_LIBS) $(STATIC_FLAGS) $(MIMALLOC_WRAP_FLAGS) $(MEMWASTE_LDFLAGS) $(ELF_HARDENING_FLAGS) -LDFLAGS_TEST = -lm $(CXX_STDLIB) -lpthread -lz $(SANITIZE) $(WIN32_LIBS) $(MIMALLOC_WRAP_FLAGS) $(ELF_HARDENING_FLAGS) -LDFLAGS_TSAN = -lm $(CXX_STDLIB) -lpthread -lz $(TSAN_SANITIZE) $(WIN32_LIBS) $(MIMALLOC_WRAP_FLAGS) $(ELF_HARDENING_FLAGS) +LDFLAGS_TEST = -lm $(CXX_STDLIB) -lpthread -lz $(SANITIZE) $(WIN32_LIBS) $(MIMALLOC_WRAP_FLAGS) $(ELF_HARDENING_FLAGS) $(TEST_LD_FLAGS) +LDFLAGS_TSAN = -lm $(CXX_STDLIB) -lpthread -lz $(TSAN_SANITIZE) $(WIN32_LIBS) $(MIMALLOC_WRAP_FLAGS) $(ELF_HARDENING_FLAGS) $(TEST_LD_FLAGS) # ── Source files ───────────────────────────────────────────────── @@ -732,7 +771,7 @@ MIMALLOC_CFLAGS = -std=c11 -O2 -w \ -Ivendored/mimalloc/src \ -DMI_OVERRIDE=1 -DMI_DEBUG=0 -DMI_PROFILE=0 \ $(MIMALLOC_OVERRIDE_DEFINE) $(MIMALLOC_WIN_DEFINE) -MIMALLOC_CFLAGS_TEST = -std=c11 -g -O1 -w \ +MIMALLOC_CFLAGS_TEST = -std=c11 $(DEBUG_INFO) $(TEST_OPT) -w \ -Ivendored/mimalloc/include \ -Ivendored/mimalloc/src \ -DMI_OVERRIDE=0 $(MIMALLOC_WIN_DEFINE) @@ -772,7 +811,7 @@ SQLITE3_OMIT_FLAGS = -DSQLITE_OMIT_LOAD_EXTENSION SQLITE3_SRC = vendored/sqlite3/sqlite3.c SQLITE3_CFLAGS = -std=c11 -O2 -w -DSQLITE_DQS=0 -DSQLITE_THREADSAFE=1 -DSQLITE_ENABLE_FTS5 \ $(SQLITE3_OMIT_FLAGS) $(MEMWASTE_VENDOR_CFLAGS) -SQLITE3_CFLAGS_TEST = -std=c11 -g -O1 -w -DSQLITE_DQS=0 -DSQLITE_THREADSAFE=1 -DSQLITE_ENABLE_FTS5 \ +SQLITE3_CFLAGS_TEST = -std=c11 $(DEBUG_INFO) $(TEST_OPT) -w -DSQLITE_DQS=0 -DSQLITE_THREADSAFE=1 -DSQLITE_ENABLE_FTS5 \ $(SQLITE3_OMIT_FLAGS) # TRE regex (vendored, Windows only — POSIX uses system ) @@ -1071,9 +1110,10 @@ BUILD_DIR = build/c # references fails to link. GRAMMAR_CFLAGS_TEST always carries the define. GRAMMAR_CFLAGS = -std=c11 -D_DEFAULT_SOURCE -O2 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \ $(TEST_SEAM_DEFINE) $(MEMWASTE_VENDOR_CFLAGS) -GRAMMAR_CFLAGS_TEST = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \ - -DCBM_ENABLE_TEST_SEAMS=1 $(SANITIZED_DEFINE) $(SANITIZE) -GRAMMAR_CFLAGS_TSAN = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \ +LSP_CFLAGS_TEST = -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \ + -DCBM_ENABLE_TEST_SEAMS=1 $(SANITIZED_DEFINE) $(SANITIZE) +GRAMMAR_CFLAGS_TEST = $(LSP_CFLAGS_TEST) $(VENDOR_ASAN_UAR_FLAGS) +GRAMMAR_CFLAGS_TSAN = -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \ -DCBM_ENABLE_TEST_SEAMS=1 -DCBM_SANITIZED_BUILD=1 $(TSAN_SANITIZE) # Object files for grammars + ts_runtime + per-file LSP + preprocessor @@ -1121,14 +1161,14 @@ TSAN_RUNNER_OBJS = $(patsubst %.c,$(BUILD_DIR)/s/%.o,$(ALL_TEST_SRCS) $(CORE_C_S PROD_BIN_OBJS = $(patsubst %.c,$(BUILD_DIR)/p/%.o,$(MAIN_SRC) $(CORE_C_SRCS)) PROD_UI_BIN_OBJS = $(patsubst %.c,$(BUILD_DIR)/p/%.o,$(MAIN_SRC) $(CORE_C_SRCS_WITH_ASSETS)) -TEST_BUILD_CONFIG_SIG := SANITIZE=$(SANITIZE)|TEST_COVERAGE=$(TEST_COVERAGE)|CXX_STDLIB_FLAGS=$(CXX_STDLIB_FLAGS) +TEST_BUILD_CONFIG_SIG := SANITIZE=$(SANITIZE)|TEST_COVERAGE=$(TEST_COVERAGE)|CXX_STDLIB_FLAGS=$(CXX_STDLIB_FLAGS)|DEBUG_INFO=$(DEBUG_INFO)|TEST_OPT=$(TEST_OPT)|TEST_SUITE_OPT=$(TEST_SUITE_OPT) test-build-config-check: $(BUILD_DIR)/.test-build-config: test-build-config-check | $(BUILD_DIR) @printf '%s\n' '$(TEST_BUILD_CONFIG_SIG)' > $@.tmp @if cmp -s $@.tmp $@; then rm -f $@.tmp; \ else mv -f $@.tmp $@; rm -f $(BUILD_DIR)/test-runner $(BUILD_DIR)/test-runner-image-probe; fi -TSAN_BUILD_CONFIG_SIG := TSAN_SANITIZE=$(TSAN_SANITIZE) +TSAN_BUILD_CONFIG_SIG := TSAN_SANITIZE=$(TSAN_SANITIZE)|DEBUG_INFO=$(DEBUG_INFO)|TEST_OPT=$(TEST_OPT)|TEST_SUITE_OPT=$(TEST_SUITE_OPT) tsan-build-config-check: $(BUILD_DIR)/.tsan-build-config: tsan-build-config-check | $(BUILD_DIR) @printf '%s\n' '$(TSAN_BUILD_CONFIG_SIG)' > $@.tmp @@ -1211,7 +1251,7 @@ SQLITE3_OBJ_TSAN = $(BUILD_DIR)/tsan_sqlite3.o SQLITE3_OBJ_PROD = $(BUILD_DIR)/prod_sqlite3.o $(BUILD_DIR)/sqlite3.o: $(SQLITE3_SRC) | $(BUILD_DIR) - $(CC) $(SQLITE3_CFLAGS_TEST) $(SANITIZE) -c -o $@ $< + $(CC) $(SQLITE3_CFLAGS_TEST) $(SANITIZE) $(VENDOR_ASAN_UAR_FLAGS) -c -o $@ $< $(BUILD_DIR)/tsan_sqlite3.o: $(SQLITE3_SRC) | $(BUILD_DIR) $(CC) $(SQLITE3_CFLAGS_TEST) $(TSAN_SANITIZE) -c -o $@ $< @@ -1256,13 +1296,13 @@ endif LZ4_OBJ_TEST = $(BUILD_DIR)/test_lz4.o $(BUILD_DIR)/test_lz4hc.o LZ4_OBJ_TSAN = $(BUILD_DIR)/tsan_lz4.o $(BUILD_DIR)/tsan_lz4hc.o $(BUILD_DIR)/test_lz4.o: $(CBM_DIR)/vendored/lz4/lz4.c | $(BUILD_DIR) - $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(SANITIZE) -w -I$(CBM_DIR) -c -o $@ $< + $(CC) -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) $(SANITIZE) $(VENDOR_ASAN_UAR_FLAGS) -w -I$(CBM_DIR) -c -o $@ $< $(BUILD_DIR)/test_lz4hc.o: $(CBM_DIR)/vendored/lz4/lz4hc.c | $(BUILD_DIR) - $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(SANITIZE) -w -I$(CBM_DIR)/vendored/lz4 -c -o $@ $< + $(CC) -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) $(SANITIZE) $(VENDOR_ASAN_UAR_FLAGS) -w -I$(CBM_DIR)/vendored/lz4 -c -o $@ $< $(BUILD_DIR)/tsan_lz4.o: $(CBM_DIR)/vendored/lz4/lz4.c | $(BUILD_DIR) - $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(TSAN_SANITIZE) -w -I$(CBM_DIR) -c -o $@ $< + $(CC) -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) $(TSAN_SANITIZE) -w -I$(CBM_DIR) -c -o $@ $< $(BUILD_DIR)/tsan_lz4hc.o: $(CBM_DIR)/vendored/lz4/lz4hc.c | $(BUILD_DIR) - $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(TSAN_SANITIZE) -w -I$(CBM_DIR)/vendored/lz4 -c -o $@ $< + $(CC) -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) $(TSAN_SANITIZE) -w -I$(CBM_DIR)/vendored/lz4 -c -o $@ $< # Vendored zstd (test build) # ZSTD_EXTRA_CFLAGS: hook for sanitizer lanes. The MSan lane needs @@ -1276,9 +1316,9 @@ $(BUILD_DIR)/tsan_lz4hc.o: $(CBM_DIR)/vendored/lz4/lz4hc.c | $(BUILD_DIR) ZSTD_OBJ_TEST = $(BUILD_DIR)/test_zstd.o ZSTD_OBJ_TSAN = $(BUILD_DIR)/tsan_zstd.o $(BUILD_DIR)/test_zstd.o: $(CBM_DIR)/vendored/zstd/zstd.c | $(BUILD_DIR) - $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(SANITIZE) $(ZSTD_EXTRA_CFLAGS) -w -I$(CBM_DIR)/vendored/zstd -c -o $@ $< + $(CC) -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) $(SANITIZE) $(VENDOR_ASAN_UAR_FLAGS) $(ZSTD_EXTRA_CFLAGS) -w -I$(CBM_DIR)/vendored/zstd -c -o $@ $< $(BUILD_DIR)/tsan_zstd.o: $(CBM_DIR)/vendored/zstd/zstd.c | $(BUILD_DIR) - $(CC) -std=c11 -D_DEFAULT_SOURCE -g -O1 $(TSAN_SANITIZE) -w -I$(CBM_DIR)/vendored/zstd -c -o $@ $< + $(CC) -std=c11 -D_DEFAULT_SOURCE $(DEBUG_INFO) $(TEST_OPT) $(TSAN_SANITIZE) -w -I$(CBM_DIR)/vendored/zstd -c -o $@ $< # nomic-embed-code pretrained vector blob UNIXCODER_OBJ = $(BUILD_DIR)/unixcoder_blob.o @@ -1382,7 +1422,7 @@ test-repro: $(BUILD_DIR)/test-repro-runner # workers), now fixed with atomics in log.c. Excluding the suite is what # had hidden it. TEST_TSAN_SUITES ?= mem slab_alloc parallel worker_pool watcher httpd pipeline pipeline_d \ - diagnostics mcp mcp_mutation_guard subprocess daemon daemon_application \ + diagnostics mcp mcp_supervisor mcp_mutation_guard subprocess daemon daemon_application \ daemon_runtime daemon_ipc daemon_frontend # halt_on_error: a race is a bug, stop at the first one. # @@ -1413,7 +1453,7 @@ test-tsan: $(BUILD_DIR)/test-runner-tsan pipe_suites=""; other_suites=""; daemon_suites=""; \ for s in $(TEST_TSAN_SUITES); do \ case "$$s" in \ - watcher|httpd|subprocess|mcp|mcp_mutation_guard|daemon|daemon_*) daemon_suites="$$daemon_suites $$s" ;; \ + watcher|httpd|subprocess|mcp|mcp_supervisor|mcp_mutation_guard|daemon|daemon_*) daemon_suites="$$daemon_suites $$s" ;; \ pipeline) pipe_suites="$$pipe_suites $$s" ;; \ *) other_suites="$$other_suites $$s" ;; \ esac; \ @@ -1894,12 +1934,22 @@ OBJ_SUBDIRS = $(patsubst %/,%,$(sort $(dir $(ALL_FIRST_PARTY_OBJS) $(ALL_LSP_OBJ $(OBJ_SUBDIRS): @mkdir -p $@ +# GNU Make 3.81 (macOS) resolves pattern rules in declaration order, not +# shortest stem: keep t/tests/%.o and s/tests/%.o BEFORE t/%.o and s/%.o so +# test-suite TUs compile at TEST_SUITE_OPT (-O1) while first-party production +# sources compile at TEST_OPT (-O2). +$(BUILD_DIR)/t/tests/%.o: tests/%.c $(BUILD_DIR)/.test-build-config | $$(@D) + $(CC) $(CFLAGS_TEST_SUITES) -Itests -Itests/repro -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + $(BUILD_DIR)/t/%.o: %.c $(BUILD_DIR)/.test-build-config | $$(@D) $(CC) $(CFLAGS_TEST) -Itests -Itests/repro -MMD -MP -MF $(@:.o=.d) -c -o $@ $< $(BUILD_DIR)/i/%.o: %.c $(BUILD_DIR)/.test-build-config | $$(@D) $(CC) $(CFLAGS_IMAGE_PROBE) -Itests -MMD -MP -MF $(@:.o=.d) -c -o $@ $< +$(BUILD_DIR)/s/tests/%.o: tests/%.c $(BUILD_DIR)/.tsan-build-config | $$(@D) + $(CC) $(CFLAGS_TSAN_SUITES) -Itests -Itests/repro -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + $(BUILD_DIR)/s/%.o: %.c $(BUILD_DIR)/.tsan-build-config | $$(@D) $(CC) $(CFLAGS_TSAN) -Itests -Itests/repro -MMD -MP -MF $(@:.o=.d) -c -o $@ $< @@ -1907,7 +1957,7 @@ $(BUILD_DIR)/p/%.o: %.c $(BUILD_DIR)/.build-config | $$(@D) $(CC) $(CFLAGS_PROD) -MMD -MP -MF $(@:.o=.d) -c -o $@ $< $(BUILD_DIR)/tl/%.o: %.c $(BUILD_DIR)/.test-build-config | $$(@D) - $(CC) $(GRAMMAR_CFLAGS_TEST) -DCBM_PYTHON_STDLIB_GENERATED=1 $(TEST_COVERAGE_FLAGS) -MMD -MP -MF $(@:.o=.d) -c -o $@ $< + $(CC) $(LSP_CFLAGS_TEST) -DCBM_PYTHON_STDLIB_GENERATED=1 $(TEST_COVERAGE_FLAGS) -MMD -MP -MF $(@:.o=.d) -c -o $@ $< $(BUILD_DIR)/sl/%.o: %.c $(BUILD_DIR)/.tsan-build-config | $$(@D) $(CC) $(GRAMMAR_CFLAGS_TSAN) -DCBM_PYTHON_STDLIB_GENERATED=1 -MMD -MP -MF $(@:.o=.d) -c -o $@ $< diff --git a/scripts/memwaste-scaling.py b/scripts/memwaste-scaling.py index ea8f1b0602..1cb532e1af 100644 --- a/scripts/memwaste-scaling.py +++ b/scripts/memwaste-scaling.py @@ -30,6 +30,7 @@ from __future__ import annotations import argparse +from concurrent.futures import ThreadPoolExecutor import json import os import re @@ -198,8 +199,15 @@ def main() -> int: shutil.rmtree(os.path.join(work, sub), ignore_errors=True) k = args.replicas - small, info_k = run_leg(binary, profdata, corpus, work, k) - large, info_2k = run_leg(binary, profdata, corpus, work, 2 * k) + # The two legs run in completely isolated workdirs, cache dirs, runtime dirs, + # and profraw dirs, and the verdict compares deterministic clang execution + # COUNTS (not wall time), so running leg K and leg 2K concurrently preserves + # exact counts while cutting scaling-lane wall time. + with ThreadPoolExecutor(max_workers=2) as pool: + fut_small = pool.submit(run_leg, binary, profdata, corpus, work, k) + fut_large = pool.submit(run_leg, binary, profdata, corpus, work, 2 * k) + small, info_k = fut_small.result() + large, info_2k = fut_large.result() total_k = sum(small.values()) total_2k = sum(large.values()) diff --git a/scripts/msan.sh b/scripts/msan.sh index 8d39ee9515..b9deb8dae3 100755 --- a/scripts/msan.sh +++ b/scripts/msan.sh @@ -239,7 +239,8 @@ else w["doc_mentions_b"] = 55 w["complexity"] = 54 w["pipeline_semantic_manifest_repro_b"] = 46 - w["mcp"] = 45 + w["mcp"] = 35 + w["mcp_supervisor"] = 18 w["pipeline_c"] = 37 w["httpd"] = 36 w["edge_types_probe"] = 32 @@ -316,13 +317,12 @@ else # footprint does not overlap 3 other parallel MSan suites and trigger swap # thrashing on 16 GiB CI runners (which previously slowed co-running suites # 4-5x on whichever shard drew c_lsp_b). - SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp \ + SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp_supervisor \ extraction c_lsp_b \ stack_overflow_a stack_overflow_b stack_overflow_c \ index_supervisor daemon_application daemon_runtime daemon_frontend \ daemon_bootstrap daemon_ipc" - TAIL_EXCL="cli cli_b mcp index_supervisor daemon_application daemon_runtime \ - daemon_frontend daemon_bootstrap daemon_ipc extraction c_lsp_b" + TAIL_EXCL="extraction c_lsp_b" for suite in $all_suites; do case " $MSAN_EXCLUDE " in *" $suite "*) diff --git a/scripts/run-test-wave.py b/scripts/run-test-wave.py index c4303f4f77..ebda8a13d2 100755 --- a/scripts/run-test-wave.py +++ b/scripts/run-test-wave.py @@ -62,6 +62,16 @@ "grammar_probe_b", ) ) +# Suites that assert cbm_default_worker_count(true) == info.total_cores or +# test default worker-count sizing without unsetting CBM_WORKERS first. +UNCAP_WORKER_SUITES = frozenset( + ( + "system_info", + "platform", + "worker_pool", + "parallel", + ) +) POLL_SECONDS = 0.05 # WHY: the Windows descendant probe below is a cold `powershell.exe` + CIM @@ -110,6 +120,12 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--timeout", required=True, type=int) parser.add_argument("--slow-timeout", required=True, type=int) parser.add_argument("--kill-grace", required=True, type=int) + parser.add_argument( + "--worker-cap", + type=int, + default=0, + help="Optional CBM_WORKERS cap for parallel wave suites (0 = inherit)", + ) parser.add_argument( "--test-post-exit-barrier-dir", type=pathlib.Path, @@ -181,6 +197,7 @@ def start_suite( runner_command: list[str], log_dir: pathlib.Path, timeout: int, + worker_cap: int = 0, ) -> ActiveSuite | None: log_path = log_dir / f"{suite}.log" log_file = log_path.open("wb") @@ -188,6 +205,14 @@ def start_suite( "stdout": log_file, "stderr": subprocess.STDOUT, } + if ( + worker_cap > 0 + and "CBM_WORKERS" not in os.environ + and suite not in UNCAP_WORKER_SUITES + ): + env = dict(os.environ) + env["CBM_WORKERS"] = str(worker_cap) + popen_args["env"] = env if os.name == "nt": popen_args["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP else: @@ -505,6 +530,7 @@ def run_wave(args: argparse.Namespace) -> None: list(args.runner_command), args.log_dir, timeout, + worker_cap=args.worker_cap, ) if started is None: record_start_failure(suite, args.log_dir, args.results_file) diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index eae9bc2b3f..790de76cd2 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -58,6 +58,7 @@ mkdir -p "$LOGDIR" # setup. Two idempotent steps: protect the DIRECTORY (inheritance flags are # directory-only — a /T re-root leaves files with empty deny-all DACLs), # then /reset the children to re-inherit the clean set. +WIN_STAMP_SID="" stamp_windows_build_dir() { local when="$1" case "$(uname -s 2>/dev/null)" in @@ -66,33 +67,41 @@ stamp_windows_build_dir() { esac local runner_dir_w me norm_out stamp_out reset_out runner_dir_w="$(cygpath -w "$(dirname "$RUNNER")")" - # Qualify the account with its domain. Git Bash resolves `whoami` to - # coreutils, which prints a bare name, and icacls resolves a bare name - # against the machine first: on a host whose name equals the user's - # (COMPUTERNAME=BUILD, user build) the grant lands on an empty principal - # (BUILD\) and, combined with /inheritance:r above, locks this script out - # of its own log directory. - # Identify the account by SID, never by name. icacls resolves a bare name - # against the machine first, so a host whose name equals the user's grants - # to an empty principal (#1532); and a USERDOMAIN-qualified name is - # UNRESOLVABLE on a workgroup machine — "WORKGROUP\test: No mapping between - # account names and security IDs was done" — which fails the grant outright - # and silently leaves the tree writable by Authenticated Users. A SID has - # neither ambiguity, and the SYSTEM/Administrators grants below already use - # this form. Name lookup remains only as a fallback where PowerShell is - # unavailable. - me="$(powershell.exe -NoProfile -NonInteractive -Command \ - '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value' 2>/dev/null | - tr -d '\r\n')" - case "${me}" in - S-1-*) me="*${me}" ;; - *) - me="$(whoami | tr -d '\r')" - if [ -n "${USERDOMAIN:-}" ]; then - me="${USERDOMAIN}\\${me}" + # Identify the account by SID, never by name (see #1532). Cache the SID + # across pre-wave and pre-tail calls and prefer native Windows whoami.exe + # (~30 ms) over cold PowerShell (~3-4 s), falling back to PowerShell if + # whoami.exe is unavailable. + if [ -n "$WIN_STAMP_SID" ]; then + me="$WIN_STAMP_SID" + else + local win_whoami="" + if [ -n "${SYSTEMROOT:-}" ]; then + win_whoami="$(cygpath -u "$SYSTEMROOT")/System32/whoami.exe" fi - ;; - esac + if [ -n "$win_whoami" ] && [ -x "$win_whoami" ]; then + me="$("$win_whoami" /user /fo csv /nh 2>/dev/null | tr -d '\r\n' | sed -E 's/^"[^"]*","([^"]*)".*/\1/')" + else + me="" + fi + case "${me}" in + S-1-*) ;; + *) + me="$(powershell.exe -NoProfile -NonInteractive -Command \ + '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value' 2>/dev/null | + tr -d '\r\n')" + ;; + esac + case "${me}" in + S-1-*) me="*${me}" ;; + *) + me="$(whoami | tr -d '\r')" + if [ -n "${USERDOMAIN:-}" ]; then + me="${USERDOMAIN}\\${me}" + fi + ;; + esac + WIN_STAMP_SID="$me" + fi # Normalize FIRST: some runner images stamp EXPLICIT (non-inherited) # Authenticated-Users ACEs onto the workspace tree, which /inheritance:r # cannot strip and /grant:r does not touch (it replaces only the granted @@ -104,8 +113,11 @@ stamp_windows_build_dir() { stamp_out=$(MSYS2_ARG_CONV_EXCL='*' icacls "$runner_dir_w" /inheritance:r \ /grant:r "${me}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' \ /Q 2>&1) || echo "WARN: build-dir DACL stamp ($when) failed (user=$me dir=$runner_dir_w): $stamp_out" - reset_out=$(MSYS2_ARG_CONV_EXCL='*' icacls "${runner_dir_w}\\*" /reset /T /C /Q 2>&1) || - echo "WARN: build-dir child DACL reset ($when) failed: $(printf '%s' "$reset_out" | tail -2)" + # Windows activation policy only checks the build directory itself and its + # executable candidates (*.exe); avoid recursing (/T) across ~1,500 .o/.d + # and log files in build/c/ subtrees on every shard. + reset_out=$(MSYS2_ARG_CONV_EXCL='*' icacls "${runner_dir_w}\\*.exe" /reset /C /Q 2>&1) || + echo "WARN: build-dir exe DACL reset ($when) failed: $(printf '%s' "$reset_out" | tail -2)" # The stamp is load-bearing for the install-flow suites: verify it and say # so, in either direction — a silent stamp once cost a full CI round to # even see WHETHER it had run. @@ -226,7 +238,6 @@ shard_filter() { w["php_member_walk"] = 325 w["c_lsp_b"] = 270 w["doc_mentions_e"] = 240 - w["stack_overflow_b"] = 230 w["edge_types_probe"] = 220 w["pipeline_b"] = 210 w["grammar_probe_f"] = 200 @@ -236,37 +247,32 @@ shard_filter() { w["pipeline"] = 185 w["java_type_scope_b"] = 185 w["pipeline_c"] = 180 - w["test_impact_git"] = 180 w["lang_contract"] = 170 - w["cli"] = 185 - w["daemon_runtime"] = 155 w["pipeline_semantic_manifest_repro"] = 155 w["java_type_scope"] = 155 - w["cli_b"] = 145 - w["complexity_b"] = 145 w["pipeline_semantic_manifest_repro_b"] = 150 + w["complexity_b"] = 145 w["stack_overflow_c"] = 145 w["doc_mentions_b"] = 135 - w["daemon_frontend"] = 125 w["complexity"] = 120 w["test_impact_tree"] = 120 w["repro_reference_precision"] = 120 w["include_path"] = 115 w["doc_mentions"] = 115 w["doc_mentions_d"] = 115 - w["test_impact_git_b"] = 115 w["edge_imports"] = 110 w["type_scope"] = 110 w["c_lsp"] = 105 - w["test_impact_git_c"] = 100 w["lsp_resolution_probe"] = 95 w["node_creation_probe"] = 90 w["doc_mentions_jvm"] = 85 w["matrix_new_constructs"] = 80 - w["daemon_bootstrap"] = 75 - w["mcp"] = 100 + w["mcp"] = 75 w["doc_mentions_rs"] = 75 w["grammar_probe_d"] = 75 + w["cli"] = 75 + w["cli_b"] = 65 + w["stack_overflow_b"] = 65 w["grammar_probe_e"] = 60 w["doc_mentions_go"] = 58 w["grammar_probe_a"] = 58 @@ -286,12 +292,19 @@ shard_filter() { w["watcher"] = 40 w["grammar_probe_g"] = 38 w["grammar_probe_b"] = 38 + w["mcp_supervisor"] = 35 w["test_impact_tree_read"] = 34 w["test_impact_inventory"] = 32 w["extraction"] = 30 w["httpd"] = 28 + w["daemon_runtime"] = 28 + w["daemon_frontend"] = 28 + w["test_impact_git"] = 25 + w["test_impact_git_b"] = 20 + w["test_impact_git_c"] = 20 w["subprocess"] = 18 w["index_supervisor"] = 10 + w["daemon_bootstrap"] = 8 w["daemon_application"] = 5 w["daemon_ipc"] = 2 } @@ -371,7 +384,14 @@ shard_filter() { # that 40 sits >=2x from both the linear and quadratic signals, so inflating it # would move the test toward the very thing it exists to catch. Quiet is the # fix, and at ~22s the suite is cheap to run alone. -SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp \ +# Each suite process receives its own isolated HOME and CBM_RUNTIME_DIR from +# tf_setup_cache_sentinel() (tests/test_main.c), so daemon-family, cli, and +# mcp_supervisor suites cannot collide on runtime endpoints and safely overlap +# in the quiet FLEX tail (CBM_TAIL_JOBS=2). Pure in-process `mcp` tests run in +# the main parallel wave; fork/worker/deadline tests live in `mcp_supervisor`. +# Only `extraction` (whose 20x scaling-ratio guard must observe an idle CPU) +# stays strictly exclusive (jobs=1). +SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp_supervisor \ extraction \ stack_overflow_a stack_overflow_b stack_overflow_c \ index_supervisor daemon_application daemon_runtime daemon_frontend \ @@ -379,20 +399,7 @@ SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilienc is_serial() { case " $SERIAL_SUITES " in *" $1 "*) return 0 ;; *) return 1 ;; esac } -# Tail scheduling in two phases. The FLEX suites are timing-shaped but do -# not rendezvous through the shared per-account daemon runtime namespace, -# so a small fixed overlap (CBM_TAIL_JOBS, default 2) is safe and converts -# idle cores into wall time — the old fully-serial tail ran them one at a -# time on an idle machine. The EXCL group (daemon-family plus the suites -# that drive daemon one-shots or supervisor rendezvous) then runs strictly -# sequentially on a machine exactly as quiet as the old tail gave it. -# extraction is in this group for a DIFFERENT reason than the rest: it does not -# rendezvous through the daemon namespace, it measures a scaling ratio, and even -# the FLEX group's small fixed overlap is load the measurement would absorb. -# Strictly sequential is what makes its verdict a function of the code instead -# of the scheduler. -TAIL_EXCL="cli cli_b mcp index_supervisor daemon_application daemon_runtime \ - daemon_frontend daemon_bootstrap daemon_ipc extraction" +TAIL_EXCL="extraction" is_tail_excl() { case " $TAIL_EXCL " in *" $1 "*) return 0 ;; *) return 1 ;; esac } @@ -460,6 +467,7 @@ trap 'collect_failed_suite_logs "$LOGDIR" "$RESULTS_FILE" "$SHARD_EXPECT"' EXIT run_wave() { local suite_file="$1" local jobs="$2" + local worker_cap="${3:-0}" if ! python3 "$SCHEDULER" \ --suite-file "$suite_file" \ --log-dir "$LOGDIR" \ @@ -468,13 +476,23 @@ run_wave() { --timeout "${CBM_SUITE_TIMEOUT:-900}" \ --slow-timeout "${CBM_SUITE_TIMEOUT_SLOW:-3600}" \ --kill-grace 15 \ + --worker-cap "$worker_cap" \ "$RUNNER"; then echo "FAIL: parallel suite scheduler infrastructure failed" >&2 exit 1 fi } -run_wave "$PAR_FILE" "$JOBS" +# Cap per-suite internal worker threads during the full-width PAR wave so +# N parallel suite processes do not oversubscribe cores (4*4=16 threads on +# 4-core runners) while staying >= PL_PARALLEL_MIN_WORKERS (2) so parallel +# pipeline paths stay 100% exercised. Suites asserting default core count are +# exempted inside run-test-wave.py. +PAR_WORKER_CAP="${CBM_PAR_WORKER_CAP:-2}" +if [ "$JOBS" -le 1 ]; then + PAR_WORKER_CAP=0 +fi +run_wave "$PAR_FILE" "$JOBS" "$PAR_WORKER_CAP" # Wave suites spawn Cygwin-family tooling that can rewrite the build # directory's DACL behind the first stamp (observed: an arm shard whose @@ -483,8 +501,8 @@ run_wave "$PAR_FILE" "$JOBS" # Re-stamp at the tail boundary so the deadline-sensitive tail — which # hosts those suites — always starts from the verified-clean shape. stamp_windows_build_dir pre-tail -run_wave "$FLEX_FILE" "${CBM_TAIL_JOBS:-2}" -run_wave "$EXCL_FILE" 1 +run_wave "$FLEX_FILE" "${CBM_TAIL_JOBS:-2}" 0 +run_wave "$EXCL_FILE" 1 0 # ── Union guard: every suite in this shard's slice produced exactly one # result. The slice is deterministic, so N green shard jobs = full coverage; diff --git a/scripts/smoke-local.sh b/scripts/smoke-local.sh index 888348ae9c..19ded7bd95 100755 --- a/scripts/smoke-local.sh +++ b/scripts/smoke-local.sh @@ -131,9 +131,10 @@ fi # Member set and ORDER mirror scripts/package-release.sh (the Windows # single-binary contract locks that order); a fixture with a different inventory -# would smoke a release layout we never ship. +# would smoke a release layout we never ship. Use fast gzip level 1 for the +# ephemeral local fixture archive (~5-8x faster compression on ~300 MB binaries). EXPECTED_ARTIFACT="codebase-memory-mcp-${OS}-${ARCH}.tar.gz" -tar -czf "$FIXTURE_DIR/$EXPECTED_ARTIFACT" -C "$FIXTURE_DIR" \ +COPYFILE_DISABLE=1 GZIP=-1 tar -czf "$FIXTURE_DIR/$EXPECTED_ARTIFACT" -C "$FIXTURE_DIR" \ codebase-memory-mcp LICENSE install.sh THIRD_PARTY_NOTICES.md # Linux install/update resolves the portable release asset even when this local diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.sh index dd6566e368..5faec3c6d6 100755 --- a/scripts/smoke-test.sh +++ b/scripts/smoke-test.sh @@ -110,10 +110,15 @@ smoke_rmtree() { } # Every platform ships ONE binary, Windows included: a fixture copy is complete -# with nothing beside it. +# with nothing beside it. Prefer copy-on-write clones where supported (APFS / +# Btrfs / XFS) to avoid repeatedly copying ~300 MB binaries during smoke runs. copy_smoke_binary() { local destination="$1" - cp "$BINARY" "$destination" + if [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then + cp -c "$BINARY" "$destination" 2>/dev/null || cp "$BINARY" "$destination" + else + cp --reflink=auto "$BINARY" "$destination" 2>/dev/null || cp "$BINARY" "$destination" + fi } # A fixture home that belongs to a Claude Code user. An empty ~/.claude is not @@ -651,6 +656,12 @@ fi rm -rf "$CFG_HOME" echo "OK: config get returns defaults and errors on unknown keys" +# Keep a warm account daemon across Phases 3b-5 (all use the main smoke cache +# namespace) so ~25 sequential CLI/MCP probes reuse one daemon instead of +# paying 2-3 s of cold bootstrap + self-image hashing per command. Phases 1b, +# 2, 3z3, 6-14, 15, and 16 still run cold; retired cleanly before Phase 6. +"$BINARY" daemon start >/dev/null 2>&1 || true + echo "OK: search_graph found $TOTAL result(s) for 'compute'" # 3b: trace_path — verify compute has callers @@ -1191,6 +1202,8 @@ echo "OK: Content-Length framing works (OpenCode compatible)" rm -f "$MCP_CL_INPUT" "$MCP_CL_OUTPUT" "$MCP_TOOL_OUTPUT" +retire_account_daemon "phase5-warm-cleanup" + echo "" echo "=== Phase 6: CLI subcommands ===" @@ -3750,18 +3763,11 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then # copy is immediately able to render and remove its own integrations. if [[ "$BINARY" == *.exe ]]; then cp "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe" - mkdir -p "$UPDATE_HOME/retired-install" - cp "$BINARY" "$UPDATE_HOME/retired-install/codebase-memory-mcp.exe" else - cp "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp" + copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp" chmod 755 "$UPDATE_HOME/.local/bin/codebase-memory-mcp" - mkdir -p "$UPDATE_HOME/retired-install" - cp "$BINARY" "$UPDATE_HOME/retired-install/codebase-memory-mcp" - chmod 755 "$UPDATE_HOME/retired-install/codebase-memory-mcp" if [ "$(uname -s)" = "Darwin" ]; then codesign --sign - --force "$UPDATE_HOME/.local/bin/codebase-memory-mcp" 2>/dev/null || true - codesign --sign - --force "$UPDATE_HOME/retired-install/codebase-memory-mcp" \ - 2>/dev/null || true fi fi @@ -4227,12 +4233,13 @@ UI_PORT=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0 # leaving `wait "$UI_PID"` blocked for the full 300 s sleep after the server # exits or is killed. UI_SLEEP_PID_FILE=$(smoke_mktemp_file) +UI_STDERR_FILE=$(smoke_mktemp_file) rm -f "$UI_SLEEP_PID_FILE" ( sleep 300 & echo "$!" > "$UI_SLEEP_PID_FILE" wait -) | "$BINARY" --ui=true --port="$UI_PORT" > /dev/null 2>&1 & +) | "$BINARY" --ui=true --port="$UI_PORT" > /dev/null 2>"$UI_STDERR_FILE" & UI_PID=$! stop_ui_server() { @@ -4241,17 +4248,22 @@ stop_ui_server() { kill "$(cat "$UI_SLEEP_PID_FILE")" 2>/dev/null || true fi wait "$UI_PID" 2>/dev/null || true - rm -f "$UI_SLEEP_PID_FILE" + rm -f "$UI_SLEEP_PID_FILE" "$UI_STDERR_FILE" } # Readiness poll with a real 30 s wall-clock deadline (not an iteration count: # on Windows a refused localhost connect takes ~2 s, turning 150 iterations # into 300 s). SKIP is legitimate ONLY when the process exited or serves no # embedded UI; a slow start on a loaded runner still gets the full 30 s window. +# When SMOKE_REQUIRE_UI != 1 and the binary already logged that it was built +# without UI support, stop polling immediately instead of waiting out 30 s. UI_READY=0 UI_DEADLINE=$((SECONDS + 30)) while [ "$SECONDS" -lt "$UI_DEADLINE" ]; do if ! kill -0 "$UI_PID" 2>/dev/null; then break; fi + if [ "$SMOKE_REQUIRE_UI" != "1" ] && grep -qi "without UI support" "$UI_STDERR_FILE" 2>/dev/null; then + break + fi if curl --noproxy '*' --connect-timeout 1 --max-time 2 -sf "http://127.0.0.1:$UI_PORT/" -o /dev/null 2>/dev/null; then UI_READY=1; break; fi sleep 0.2 done diff --git a/scripts/smoke-wrappers.sh b/scripts/smoke-wrappers.sh index 99a385ea26..23f359cd22 100644 --- a/scripts/smoke-wrappers.sh +++ b/scripts/smoke-wrappers.sh @@ -155,12 +155,47 @@ smoke_go() { ran go "$dir/run.log" "$rc" } -for wrapper in "${WRAPPERS[@]}"; do - case "$wrapper" in - npm) smoke_npm ;; - pypi) smoke_pypi ;; - go) smoke_go ;; - *) echo "unknown wrapper: $wrapper" >&2; exit 2 ;; - esac -done +# Each wrapper uses its own isolated workdir ($WORK/) and talks to the +# multi-threaded smoke fixture server; run them concurrently when multiple +# wrappers are selected. +if [ "${#WRAPPERS[@]}" -le 1 ]; then + for wrapper in "${WRAPPERS[@]}"; do + case "$wrapper" in + npm) smoke_npm ;; + pypi) smoke_pypi ;; + go) smoke_go ;; + *) echo "unknown wrapper: $wrapper" >&2; exit 2 ;; + esac + done +else + PIDS=() + NAMES=() + for wrapper in "${WRAPPERS[@]}"; do + case "$wrapper" in + npm|pypi|go) ;; + *) echo "unknown wrapper: $wrapper" >&2; exit 2 ;; + esac + done + for wrapper in "${WRAPPERS[@]}"; do + ( + FAILED=0 + case "$wrapper" in + npm) smoke_npm ;; + pypi) smoke_pypi ;; + go) smoke_go ;; + esac + exit "$FAILED" + ) >"$WORK/$wrapper.out" 2>&1 & + PIDS+=("$!") + NAMES+=("$wrapper") + done + for i in "${!PIDS[@]}"; do + wrc=0 + wait "${PIDS[$i]}" || wrc=$? + cat "$WORK/${NAMES[$i]}.out" + if [ "$wrc" -ne 0 ]; then + FAILED=1 + fi + done +fi exit "$FAILED" diff --git a/test-infrastructure/Dockerfile.msan b/test-infrastructure/Dockerfile.msan index 144abf2790..1c2d537a42 100644 --- a/test-infrastructure/Dockerfile.msan +++ b/test-infrastructure/Dockerfile.msan @@ -104,6 +104,13 @@ RUN retry sh -c 'rm -rf /tmp/zlib && git clone --depth 1 --branch v1.3.1 https:/ && make -j"$(nproc)" install \ && rm -rf /tmp/zlib +# Fast multi-threaded linker in its own layer after the expensive libc++/zlib +# builds so Docker buildx reuses those cached layers via restore-keys. +RUN retry apt-get -o Acquire::Retries=3 --error-on=any update \ + && retry apt-get -o Acquire::Retries=3 install -y --no-install-recommends lld-21 \ + && ln -sf /usr/bin/ld.lld-21 /usr/bin/ld.lld \ + && rm -rf /var/lib/apt/lists/* + # Symbolizer path in its own (last) layer so adding tools never invalidates # the expensive libc++ build layers above. libclang-rt-21-dev is installed # explicitly with the compiler: it is only a Recommends of clang, which diff --git a/tests/image_probe_main.c b/tests/image_probe_main.c index 636e789fd4..5382199baf 100644 --- a/tests/image_probe_main.c +++ b/tests/image_probe_main.c @@ -4,10 +4,120 @@ * test runner. Its roles live in tests/image_probe_roles.c. */ #include "test_image_probe.h" +#include "foundation/compat.h" +#include "foundation/compat_fs.h" +#include "foundation/platform.h" +#include #include +#include #include +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +#define PROBE_BLOCKING_GIT_MARKER_ENV "CBM_TEST_RUNTIME_BLOCKING_GIT_PID_FILE" + +#ifdef _WIN32 +static bool probe_invoked_as_windows_git_module(void) { + wchar_t image[32768]; + DWORD image_length = GetModuleFileNameW(NULL, image, (DWORD)(sizeof(image) / sizeof(image[0]))); + if (image_length == 0 || image_length >= (DWORD)(sizeof(image) / sizeof(image[0]))) { + return false; + } + const wchar_t *base = image; + for (const wchar_t *cursor = image; *cursor; cursor++) { + if (*cursor == L'/' || *cursor == L'\\') { + base = cursor + 1; + } + } + return CompareStringOrdinal(base, -1, L"git.exe", -1, TRUE) == CSTR_EQUAL; +} + +static BOOL WINAPI probe_blocking_git_control_handler(DWORD event) { + return event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT; +} +#endif + +static bool probe_invoked_as_blocking_git(const char *argv0) { + if (!getenv(PROBE_BLOCKING_GIT_MARKER_ENV)) { + return false; + } +#ifdef _WIN32 + (void)argv0; + return probe_invoked_as_windows_git_module(); +#else + if (!argv0 || !argv0[0]) { + return false; + } + const char *base = argv0; + for (const char *cursor = argv0; *cursor; cursor++) { + if (*cursor == '/' || *cursor == '\\') { + base = cursor + 1; + } + } + return strcmp(base, "git") == 0 || strcmp(base, "git.exe") == 0 || strcmp(base, "GIT.EXE") == 0; +#endif +} + +static int probe_maybe_run_blocking_git(int argc, char **argv) { + (void)argc; +#ifdef _WIN32 + bool windows_git_module = probe_invoked_as_windows_git_module(); + if (windows_git_module && !getenv(PROBE_BLOCKING_GIT_MARKER_ENV)) { + (void)puts("TF_BLOCKING_GIT_DIAGNOSTIC marker_environment_missing"); + (void)fflush(stdout); + return 32; + } +#endif + if (!argv || !probe_invoked_as_blocking_git(argv[0])) { + return -1; + } + const char *marker_path = getenv(PROBE_BLOCKING_GIT_MARKER_ENV); + errno = 0; +#ifdef _WIN32 + SetLastError(ERROR_SUCCESS); +#endif + FILE *marker = cbm_fopen(marker_path, "wbx"); + if (!marker) { +#ifdef _WIN32 + int marker_errno = errno; + DWORD marker_error = GetLastError(); + bool marker_exists = cbm_file_exists(marker_path); + (void)printf("TF_BLOCKING_GIT_DIAGNOSTIC marker_open_failed errno=%d win_error=%lu " + "exists=%d\n", + marker_errno, (unsigned long)marker_error, marker_exists ? 1 : 0); + (void)fflush(stdout); + return marker_exists ? 0 : 30; +#else + return cbm_file_exists(marker_path) ? 0 : 30; +#endif + } +#ifdef _WIN32 + unsigned long long process_id = (unsigned long long)GetCurrentProcessId(); +#else + unsigned long long process_id = (unsigned long long)getpid(); +#endif + bool published = + fprintf(marker, "%llu\n", process_id) > 0 && fflush(marker) == 0 && fclose(marker) == 0; + if (!published) { + return 31; + } +#ifdef _WIN32 + (void)SetConsoleCtrlHandler(probe_blocking_git_control_handler, TRUE); +#else + (void)signal(SIGTERM, SIG_IGN); + (void)signal(SIGINT, SIG_IGN); +#endif + for (;;) { + cbm_usleep(100000); + } +} + #if defined(__has_feature) #if __has_feature(memory_sanitizer) #define PROBE_MSAN_MIMALLOC_OUTPUT 1 @@ -41,6 +151,10 @@ int main(int argc, char **argv) { mi_register_output(probe_msan_mi_output, NULL); probe_msan_mi_output_live = true; #endif + int git_rc = probe_maybe_run_blocking_git(argc, argv); + if (git_rc >= 0) { + return git_rc; + } /* An install verifies the candidate it staged by running it with * --version (src/cli/cli.c); the probe stands in for that binary. */ if (argc == 2 && strcmp(argv[1], "--version") == 0) { diff --git a/tests/image_probe_roles.c b/tests/image_probe_roles.c index 918b504efc..1b9b1d90b4 100644 --- a/tests/image_probe_roles.c +++ b/tests/image_probe_roles.c @@ -318,6 +318,21 @@ static int probe_role_serve(int argc, char **argv) { return freed ? 0 : 34; } +static int probe_role_git_facts_diff_probe(int argc, char **argv) { + if (argc < 3 || !argv[2]) { + return 96; + } + FILE *file = cbm_fopen(argv[2], "wb"); + if (!file) { + return 96; + } + bool ok = fwrite("invoked\n", 1, 8, file) == 8; + if (fclose(file) != 0) { + ok = false; + } + return ok ? 0 : 96; +} + int tf_image_probe_dispatch(int argc, char **argv) { if (argc < 2 || !argv || !argv[1]) { return -1; @@ -338,5 +353,8 @@ int tf_image_probe_dispatch(int argc, char **argv) { if (strcmp(role, "__cbm_runtime_mapped_hello_client") == 0) { return probe_role_mapped_hello(argc, argv); } + if (strcmp(role, "__cbm_git_facts_diff_probe") == 0) { + return probe_role_git_facts_diff_probe(argc, argv); + } return -1; } diff --git a/tests/test_cli.c b/tests/test_cli.c index 89b7c54654..c325eb1d06 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -1384,6 +1384,11 @@ TEST(cli_activation_quiesce_does_not_wait_on_bootstrap_startup) { cbm_version_cohort_lease_t *lease = NULL; cbm_daemon_conflict_t conflict; cbm_daemon_ipc_startup_lock_t *startup = NULL; +#ifdef CBM_ENABLE_TEST_SEAMS + static const char participant_stub_digest[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = + "4444444444444444444444444444444444444444444444444444444444444444"; + cbm_daemon_runtime_fingerprint_cache_set_hash_stub_for_testing(participant_stub_digest); +#endif bool setup = endpoint && manager && cbm_daemon_runtime_process_build_fingerprint((uint64_t)getpid(), fingerprint) && @@ -1673,8 +1678,9 @@ typedef struct { char *old_home; char *old_cache; char *old_shell; - bool env_saved; /* HOME, CBM_CACHE_DIR and SHELL were saved for finish */ - char failed_step[160]; /* the setup step that failed, "" when ready */ + bool env_saved; /* HOME, CBM_CACHE_DIR and SHELL were saved for finish */ + bool fingerprint_stub_armed; /* runtime hash stub active for this fixture */ + char failed_step[160]; /* the setup step that failed, "" when ready */ } cli_scope_fixture_t; static _Noreturn void cli_scope_host_child(const cli_scope_fixture_t *fixture, int ready_fd, @@ -1791,6 +1797,12 @@ static char cli_scope_wait_ready(int fd) { * ASSERT_TRUE(ready) is never a silent failure. Returns false. */ static bool cli_scope_setup_failed(cli_scope_fixture_t *fixture, const char *tag, const char *step, int os_error) { +#ifdef CBM_ENABLE_TEST_SEAMS + if (fixture->fingerprint_stub_armed) { + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); + fixture->fingerprint_stub_armed = false; + } +#endif snprintf(fixture->failed_step, sizeof(fixture->failed_step), "%s", step); if (os_error != 0) { (void)fprintf(stderr, "cli scope fixture %s: setup failed at %s: %s\n", tag, step, @@ -1878,6 +1890,16 @@ static bool cli_scope_fixture_start(cli_scope_fixture_t *fixture, const char *ta } cbm_normalize_path_sep(canonical_cache); cbm_sha256_hex(canonical_cache, strlen(canonical_cache), fixture->host_cache_fingerprint); +#ifdef CBM_ENABLE_TEST_SEAMS + /* Both the parent and the forked host child execute this same runner + * binary; stubbing only the full-image SHA-256 avoids hashing hundreds of + * MB per cli_scope fixture while keeping all kernel PID/path/cohort checks. */ + static const char scope_stub_digest[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = + "5555555555555555555555555555555555555555555555555555555555555555"; + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); + cbm_daemon_runtime_fingerprint_cache_set_hash_stub_for_testing(scope_stub_digest); + fixture->fingerprint_stub_armed = true; +#endif if (!cbm_daemon_runtime_process_build_fingerprint((uint64_t)getpid(), fixture->self_build)) { /* Fails when the runner's file no longer matches its running image, * e.g. a rebuild replaced it mid-run. */ @@ -2018,6 +2040,12 @@ static int cli_scope_fixture_finish(cli_scope_fixture_t *fixture) { if (fixture->previous_supervisor_build[0]) { cbm_index_supervisor_set_build_fingerprint_for_test(fixture->previous_supervisor_build); } +#ifdef CBM_ENABLE_TEST_SEAMS + if (fixture->fingerprint_stub_armed) { + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); + fixture->fingerprint_stub_armed = false; + } +#endif /* Restore only what start saved: a setup that failed before saving left * HOME, CBM_CACHE_DIR and SHELL untouched, and restoring "nothing saved" * would unset them for every later test in the suite. */ @@ -3840,22 +3868,13 @@ TEST(cli_update_agent_configs_finish_before_guard_release) { const char *asset_name = "codebase-memory-mcp-linux-amd64-portable.tar.gz"; #endif #endif -#ifdef __APPLE__ - /* Use the structurally real test runner rather than re-signing an Apple - * platform binary. Turning /usr/bin/true's arm64e/platform signature into - * an ad-hoc signature is OS-policy-dependent on older macOS runners. */ - char native_fixture_path[CBM_SZ_4K] = {0}; - uint32_t native_fixture_size = (uint32_t)sizeof(native_fixture_path); - ASSERT_EQ(_NSGetExecutablePath(native_fixture_path, &native_fixture_size), 0); - const char *native_fixture = native_fixture_path; -#else - /* The image probe built beside this runner (tests/test_image_probe.h) - * answers --version under any name. /bin/true does not on every host: a - * multicall coreutils (Nix) or BusyBox (Alpine) selects its applet from - * argv[0], so a copy staged as codebase-memory-mcp fails the check. */ + /* Use the small image probe built beside this runner (tests/test_image_probe.h) + * on both Linux and macOS: it is a real, locally built executable that + * answers --version under any name (unlike multicall /bin/true or Apple + * platform binaries) without gzipping, SHA-256 hashing, and re-signing the + * ~500 MB sanitized test runner. */ char native_fixture[1024] = {0}; ASSERT_TRUE(th_image_probe_path(native_fixture, sizeof(native_fixture))); -#endif FILE *native_file = fopen(native_fixture, "rb"); ASSERT_NOT_NULL(native_file); ASSERT_EQ(fseek(native_file, 0, SEEK_END), 0); @@ -3990,20 +4009,16 @@ TEST(cli_update_names_the_failing_staging_step_and_os_error) { #else const char *asset_name = "codebase-memory-mcp-darwin-amd64.tar.gz"; #endif - char native_fixture_path[CBM_SZ_4K] = {0}; - uint32_t native_fixture_size = (uint32_t)sizeof(native_fixture_path); - ASSERT_EQ(_NSGetExecutablePath(native_fixture_path, &native_fixture_size), 0); - const char *native_fixture = native_fixture_path; #else #if defined(__aarch64__) const char *asset_name = "codebase-memory-mcp-linux-arm64-portable.tar.gz"; #else const char *asset_name = "codebase-memory-mcp-linux-amd64-portable.tar.gz"; +#endif #endif /* The image probe, as in cli_update_agent_configs_finish_before_guard_release. */ char native_fixture[1024] = {0}; ASSERT_TRUE(th_image_probe_path(native_fixture, sizeof(native_fixture))); -#endif FILE *native_file = fopen(native_fixture, "rb"); ASSERT_NOT_NULL(native_file); ASSERT_EQ(fseek(native_file, 0, SEEK_END), 0); diff --git a/tests/test_daemon_bootstrap.c b/tests/test_daemon_bootstrap.c index 040459c7b4..7b9badc25d 100644 --- a/tests/test_daemon_bootstrap.c +++ b/tests/test_daemon_bootstrap.c @@ -1088,6 +1088,14 @@ TEST(daemon_bootstrap_fails_fast_when_daemon_dies_at_publication) { cbm_mkdir_p(cache, 0700) && cbm_setenv("CBM_CACHE_DIR", cache, 1) == 0; char self_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; +#ifdef CBM_ENABLE_TEST_SEAMS + /* Avoid full-image SHA-256 of the multi-hundred-MB sanitized runner in both + * parent and forked host; kernel identity checks still run unchanged. */ + static const char enospc_stub_digest[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = + "2222222222222222222222222222222222222222222222222222222222222222"; + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); + cbm_daemon_runtime_fingerprint_cache_set_hash_stub_for_testing(enospc_stub_digest); +#endif bool identity_ready = environment_ready && cbm_daemon_runtime_process_build_fingerprint( (uint64_t)getpid(), self_build); static bootstrap_enospc_host_t host; @@ -1115,6 +1123,9 @@ TEST(daemon_bootstrap_fails_fast_when_daemon_dies_at_publication) { } int nonzero_exits = 0; bootstrap_enospc_reap(&host, &nonzero_exits); +#ifdef CBM_ENABLE_TEST_SEAMS + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); +#endif static char log[BOOTSTRAP_ENOSPC_LOG_CAP]; log[0] = '\0'; diff --git a/tests/test_daemon_frontend.c b/tests/test_daemon_frontend.c index 7e5c540ba3..b15388682f 100644 --- a/tests/test_daemon_frontend.c +++ b/tests/test_daemon_frontend.c @@ -2001,6 +2001,15 @@ TEST(daemon_local_participant_monitor_joins_before_manager_teardown) { } SUITE(daemon_frontend) { +#ifdef CBM_ENABLE_TEST_SEAMS + /* Every daemon_frontend test runs in-process or forks this same runner; + * stubbing only the full-image SHA-256 avoids repeatedly hashing hundreds + * of MB per fork while keeping all kernel identity checks live. */ + static const char frontend_stub_digest[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = + "3333333333333333333333333333333333333333333333333333333333333333"; + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); + cbm_daemon_runtime_fingerprint_cache_set_hash_stub_for_testing(frontend_stub_digest); +#endif RUN_TEST(daemon_frontend_recognizes_exact_cancellation_notification); RUN_TEST(daemon_frontend_correlates_cancellation_to_exact_request); RUN_TEST(daemon_frontend_cancelled_index_reply_offers_async_issue2144); @@ -2025,4 +2034,7 @@ SUITE(daemon_frontend) { RUN_TEST(daemon_frontend_stdout_backpressure_maintenance_stops_and_cancels_session); #endif RUN_TEST(daemon_local_participant_monitor_joins_before_manager_teardown); +#ifdef CBM_ENABLE_TEST_SEAMS + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); +#endif } diff --git a/tests/test_daemon_runtime.c b/tests/test_daemon_runtime.c index e58a92aec8..66c2cf998d 100644 --- a/tests/test_daemon_runtime.c +++ b/tests/test_daemon_runtime.c @@ -245,18 +245,6 @@ typedef struct { wchar_t file_name[1]; } runtime_test_windows_rename_info_t; -static bool runtime_test_windows_copy_self(const char *destination) { - wchar_t source[32768]; - DWORD source_length = - GetModuleFileNameW(NULL, source, (DWORD)(sizeof(source) / sizeof(source[0]))); - wchar_t *destination_wide = cbm_path_to_wide(destination); - bool copied = source_length > 0 && - source_length < (DWORD)(sizeof(source) / sizeof(source[0])) && destination_wide && - CopyFileW(source, destination_wide, TRUE) != 0; - free(destination_wide); - return copied; -} - static bool runtime_test_windows_wait_image_probe(HANDLE process) { if (!process) { return false; @@ -494,19 +482,6 @@ static bool runtime_test_self_image_path(char source[RUNTIME_TEST_PATH_CAP]) { } #endif -static bool runtime_test_copy_self_image(const char *destination) { -#ifdef _WIN32 - return runtime_test_windows_copy_self(destination); -#elif defined(__APPLE__) || defined(__linux__) - char source[RUNTIME_TEST_PATH_CAP]; - return runtime_test_self_image_path(source) && - runtime_test_copy_executable(source, destination); -#else - (void)destination; - return false; -#endif -} - /* The image probe beside this runner (tests/test_image_probe.h): the small * executable the copied-image tests copy, hash and run instead of this runner. * NULL, said once on stderr, when it was not built. */ @@ -4386,7 +4361,7 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_oth git_written < (int)sizeof(fake_git) && marker_written > 0 && marker_written < (int)sizeof(marker) && cbm_mkdir_p(root, 0700) && cbm_mkdir_p(cache, 0700) && cbm_mkdir_p(bin, 0700) && - runtime_test_copy_self_image(fake_git); + runtime_test_copy_probe_image(fake_git); char path_bin[RUNTIME_TEST_PATH_CAP] = {0}; #ifdef _WIN32 @@ -5956,6 +5931,17 @@ TEST(daemon_runtime_stop_refuses_while_committed_clients_exist) { } SUITE(daemon_runtime) { +#ifdef CBM_ENABLE_TEST_SEAMS + /* Phase 1: in-process and same-binary lifecycle/IPC/cancellation tests. + * Stubbing only the full-image SHA-256 avoids hashing the multi-hundred-MB + * sanitized runner during fixture startup while keeping every kernel + * process/image-identity check live. Disarmed before Phase 2 below. */ + static const char runtime_stub_digest[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = + "6666666666666666666666666666666666666666666666666666666666666666"; + runtime_self_build[0] = '\0'; + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); + cbm_daemon_runtime_fingerprint_cache_set_hash_stub_for_testing(runtime_stub_digest); +#endif RUN_TEST(daemon_runtime_permanent_service_survives_last_disconnect_until_stop); RUN_TEST(daemon_runtime_stop_refuses_while_committed_clients_exist); RUN_TEST(daemon_host_early_coordination_failure_is_durable); @@ -5967,37 +5953,14 @@ SUITE(daemon_runtime) { RUN_TEST(daemon_host_failed_listener_reservation_starts_no_background_work); RUN_TEST(daemon_host_persistent_cleanup_release_failure_is_process_bounded); RUN_TEST(daemon_host_forced_shutdown_is_logged_flushed_and_process_bounded); -#endif - RUN_TEST(daemon_runtime_kernel_process_fingerprint_is_stable_and_fail_closed); -#ifdef _WIN32 - RUN_TEST(daemon_runtime_process_fingerprint_supports_extended_length_image); -#endif -#ifdef __APPLE__ - RUN_TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active); -#endif - RUN_TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed); -#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) - RUN_TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path); -#endif - RUN_TEST(daemon_runtime_fingerprint_cache_hit_miss_key_roll); - RUN_TEST(daemon_runtime_fingerprint_cache_skips_image_changed_under_hash); - RUN_TEST(daemon_runtime_process_fingerprint_hashes_own_image_once_per_process); -#if defined(__APPLE__) || defined(__linux__) - RUN_TEST(daemon_runtime_process_fingerprint_caches_only_own_image); #endif RUN_TEST(daemon_runtime_convenience_service_owns_participant_guard); RUN_TEST(daemon_runtime_host_loop_stops_on_coordination_file_loss); RUN_TEST(daemon_runtime_rendezvous_layout_is_frozen_and_detailed_abi_independent); RUN_TEST(daemon_runtime_exact_hello_issues_connection_bound_identity); - RUN_TEST(daemon_runtime_image_rejection_reaches_client_issue1383); - RUN_TEST(daemon_runtime_unverifiable_image_is_admitted_issue1539); - RUN_TEST(daemon_runtime_verified_peer_copy_is_hashed_once_issue1955); RUN_TEST(daemon_runtime_unexpected_frame_payload_is_freed_once); RUN_TEST(daemon_runtime_activation_rejects_forged_and_malformed_without_stop); RUN_TEST(daemon_runtime_activation_ack_snapshots_then_interrupts_all_clients); -#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) - RUN_TEST(daemon_runtime_activation_accepts_authenticated_different_build); -#endif RUN_TEST(daemon_runtime_future_generation_gets_stable_explicit_conflict); RUN_TEST(daemon_runtime_matching_clients_share_one_service_endpoint); RUN_TEST(daemon_runtime_same_version_different_build_is_visible_and_logged); @@ -6031,4 +5994,38 @@ SUITE(daemon_runtime) { RUN_TEST(daemon_runtime_mute_endpoint_holder_pid_is_reported); RUN_TEST(daemon_runtime_application_busy_cap_and_malformed_are_isolated); RUN_TEST(daemon_runtime_malformed_and_zero_cancel_close_only_offending_connections); + +#ifdef CBM_ENABLE_TEST_SEAMS + /* Phase 2: real-image and cross-binary (image-probe) authentication tests. + * Disarm the stub and clear runtime_self_build so the own-image hash is + * computed once for real and cached across all Phase 2 tests. */ + cbm_daemon_runtime_fingerprint_cache_reset_for_testing(); + runtime_self_build[0] = '\0'; +#endif + RUN_TEST(daemon_runtime_kernel_process_fingerprint_is_stable_and_fail_closed); +#ifdef _WIN32 + RUN_TEST(daemon_runtime_process_fingerprint_supports_extended_length_image); +#endif +#ifdef __APPLE__ + RUN_TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active); +#endif + RUN_TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed); +#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) + RUN_TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path); +#endif + RUN_TEST(daemon_runtime_image_rejection_reaches_client_issue1383); + RUN_TEST(daemon_runtime_unverifiable_image_is_admitted_issue1539); + RUN_TEST(daemon_runtime_verified_peer_copy_is_hashed_once_issue1955); +#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) + RUN_TEST(daemon_runtime_activation_accepts_authenticated_different_build); +#endif + + /* Phase 3: fingerprint-cache reset/key-roll unit tests run last so they + * never evict the own-image fingerprint cached for Phase 2. */ + RUN_TEST(daemon_runtime_fingerprint_cache_hit_miss_key_roll); + RUN_TEST(daemon_runtime_fingerprint_cache_skips_image_changed_under_hash); + RUN_TEST(daemon_runtime_process_fingerprint_hashes_own_image_once_per_process); +#if defined(__APPLE__) || defined(__linux__) + RUN_TEST(daemon_runtime_process_fingerprint_caches_only_own_image); +#endif } diff --git a/tests/test_image_probe.h b/tests/test_image_probe.h index be975dc68d..4f0267e53f 100644 --- a/tests/test_image_probe.h +++ b/tests/test_image_probe.h @@ -22,7 +22,10 @@ * __cbm_runtime_activation_client * __cbm_runtime_mapped_hello_client * __cbm_runtime_image_holder [] - * The probe's main also answers --version (install verification runs it). + * __cbm_git_facts_diff_probe + * The probe's main also answers --version (install verification runs it) and + * the blocking-git probe when invoked as git/git.exe with + * CBM_TEST_RUNTIME_BLOCKING_GIT_PID_FILE set. */ #include "foundation/compat_fs.h" /* cbm_fopen: the probe path may be non-ASCII */ diff --git a/tests/test_main.c b/tests/test_main.c index c5989d47b7..b625fb7e93 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -1636,6 +1636,7 @@ extern void suite_test_impact_runner_filter(void); extern void suite_store_search(void); extern void suite_cypher(void); extern void suite_mcp(void); +extern void suite_mcp_supervisor(void); extern void suite_mcp_mutation_guard(void); extern void suite_index_supervisor(void); extern void suite_daemon(void); @@ -2502,6 +2503,7 @@ int main(int argc, char **argv) { /* MCP Server (M9) */ RUN_SELECTED_SUITE(mcp); + RUN_SELECTED_SUITE(mcp_supervisor); RUN_SELECTED_SUITE(mcp_mutation_guard); RUN_SELECTED_SUITE(index_supervisor); diff --git a/tests/test_mcp.c b/tests/test_mcp.c index f7114286f6..d329ae112a 100644 --- a/tests/test_mcp.c +++ b/tests/test_mcp.c @@ -29233,22 +29233,15 @@ SUITE(mcp) { RUN_TEST(search_graph_oversized_name_pattern_is_tool_error); RUN_TEST(search_code_file_pattern_prefilter_boundaries); RUN_TEST(search_code_windows_scope_prefilter_removes_pipeline_filter); - RUN_TEST(search_code_cancel_cleans_supervised_scan); RUN_TEST(search_code_unscoped_argv_scans_metachar_filenames_issue2634); RUN_TEST(search_code_unscoped_argv_no_match_is_success_issue2634); RUN_TEST(search_code_unscoped_argv_honours_file_pattern_issue2634); RUN_TEST(server_handle_logs_timeout_without_query); RUN_TEST(search_code_output_limit_fails_closed_and_cleans_scan); - RUN_TEST(search_code_scan_deadline_fails_closed_and_resets); - RUN_TEST(search_code_scan_deadline_override_is_per_server); RUN_TEST(search_code_scan_setup_failures_respect_cause_precedence); - RUN_TEST(search_code_scan_live_child_deadline_is_bounded_and_fails_closed); RUN_TEST(search_code_scan_in_process_writes_grep_records); RUN_TEST(search_code_scan_in_process_binary_and_crlf); RUN_TEST(search_code_scan_in_process_limits_and_failures); - RUN_TEST(search_code_scan_cancellation_precedes_zero_deadline); - RUN_TEST(search_code_scan_deadline_precedes_output_limit); - RUN_TEST(search_code_scan_hook_rejection_is_contained_and_cleans_up); RUN_TEST(search_code_scratch_creation_error_releases_path_filter); RUN_TEST(search_code_scoped_exit_one_is_not_no_match); RUN_TEST(search_code_no_match_is_empty_for_direct_and_scoped_routes); @@ -29284,22 +29277,9 @@ SUITE(mcp) { RUN_TEST(tool_index_repository_unknown_project_name_still_requires_repo_path); RUN_TEST(tool_index_repository_dot_uses_absolute_project_key_and_preserves_adr); RUN_TEST(index_repository_relative_path_uses_explicit_session_root); - RUN_TEST(index_repository_supervisor_uses_canonical_session_path); RUN_TEST(index_repository_cli_name_override_issue823); RUN_TEST(index_repository_over_budget_reports_named_reason); - RUN_TEST(index_supervisor_unsafe_clean_is_never_fallback_or_recovery); - RUN_TEST(index_supervisor_gate_requires_marked_host_issue845); - RUN_TEST(index_supervisor_start_failure_is_fail_closed_in_real_host); - RUN_TEST(index_supervisor_clean_exit_without_response_response_issue1300); - RUN_TEST(index_worker_resource_limit_is_trusted_structured_and_not_retried); - RUN_TEST(index_worker_limit_never_reported_after_its_own_publication); - RUN_TEST(index_worker_resource_response_reports_preservation_for_the_request); - RUN_TEST(index_bg_paths_route_through_supervisor_issue832); RUN_TEST(sequential_service_edge_props_are_valid_json_issue898); - RUN_TEST(index_second_inprocess_run_survives_issue773); - RUN_TEST(index_recovery_parallel_quarantines_crasher); - RUN_TEST(index_recovery_quarantines_exit_nonzero); - RUN_TEST(index_recovery_systemic_exit_nonzero_gives_up); RUN_TEST(tool_manage_adr_not_found_rich_error); RUN_TEST(tool_manage_adr_get_accepts_abs_path); RUN_TEST(tool_manage_adr_get_accepts_symlink_path); @@ -29360,11 +29340,6 @@ SUITE(mcp) { RUN_TEST(parse_file_uri_null_out_path); RUN_TEST(parse_file_uri_zero_size); - /* Poll/getline FILE* buffering fix */ -#ifndef _WIN32 - RUN_TEST(mcp_server_run_rapid_messages); -#endif - /* Snippet resolution (port of snippet_test.go) */ RUN_TEST(snippet_exact_qn); RUN_TEST(snippet_doc_candidates_both_directions); @@ -29392,7 +29367,6 @@ SUITE(mcp) { /* auto_watch gate (distilled from PR #625) */ RUN_TEST(mcp_auto_watch_default_registers_watcher_on_connect); RUN_TEST(mcp_auto_watch_false_skips_watcher_on_connect); - RUN_TEST(mcp_auto_watch_false_skips_supervised_autoindex_issue853); RUN_TEST(autoindex_skip_reports_numeric_limit_issue1466); RUN_TEST(autoindex_limit_guards_non_git_root_issue713); RUN_TEST(autoindex_limit_admits_non_git_root_under_limit_issue713); @@ -29420,6 +29394,36 @@ SUITE(mcp) { RUN_TEST(search_code_drops_walker_hits_that_resolve_outside_root); } +/* Subprocess, fork, supervisor, recovery, and deadline-sensitive MCP tests. + * Kept separate from the ~400 pure in-process tests in SUITE(mcp) so `mcp` + * runs in the full parallel wave while these run in the quiet FLEX tail. */ +SUITE(mcp_supervisor) { + RUN_TEST(search_code_cancel_cleans_supervised_scan); + RUN_TEST(search_code_scan_deadline_fails_closed_and_resets); + RUN_TEST(search_code_scan_deadline_override_is_per_server); + RUN_TEST(search_code_scan_live_child_deadline_is_bounded_and_fails_closed); + RUN_TEST(search_code_scan_cancellation_precedes_zero_deadline); + RUN_TEST(search_code_scan_deadline_precedes_output_limit); + RUN_TEST(search_code_scan_hook_rejection_is_contained_and_cleans_up); + RUN_TEST(index_repository_supervisor_uses_canonical_session_path); + RUN_TEST(index_supervisor_unsafe_clean_is_never_fallback_or_recovery); + RUN_TEST(index_supervisor_gate_requires_marked_host_issue845); + RUN_TEST(index_supervisor_start_failure_is_fail_closed_in_real_host); + RUN_TEST(index_supervisor_clean_exit_without_response_response_issue1300); + RUN_TEST(index_worker_resource_limit_is_trusted_structured_and_not_retried); + RUN_TEST(index_worker_limit_never_reported_after_its_own_publication); + RUN_TEST(index_worker_resource_response_reports_preservation_for_the_request); + RUN_TEST(index_bg_paths_route_through_supervisor_issue832); + RUN_TEST(index_second_inprocess_run_survives_issue773); + RUN_TEST(index_recovery_parallel_quarantines_crasher); + RUN_TEST(index_recovery_quarantines_exit_nonzero); + RUN_TEST(index_recovery_systemic_exit_nonzero_gives_up); + RUN_TEST(mcp_auto_watch_false_skips_supervised_autoindex_issue853); +#ifndef _WIN32 + RUN_TEST(mcp_server_run_rapid_messages); +#endif +} + /* Kept separate so daemon-coordination regressions can be iterated without * running the much larger MCP behavior suite. */ SUITE(mcp_mutation_guard) { diff --git a/tests/test_stack_overflow.c b/tests/test_stack_overflow.c index 63a3db39aa..081a3ef94a 100644 --- a/tests/test_stack_overflow.c +++ b/tests/test_stack_overflow.c @@ -11,6 +11,7 @@ */ #include "test_framework.h" #include "cbm.h" +#include "foundation/compat.h" #include "lang_specs.h" /* cbm_ts_language — direct-parse GLR cap regression (#913) */ #include "lsp/ts_lsp.h" @@ -460,16 +461,57 @@ static void so_parse_alarm_exit(int sig) { * the extract-level guard skips pathologically nested Perl before it reaches the * parser, so only a direct parse exercises the cap. Windows runs in-process (a * real crash aborts the runner — a visible failure), mirroring so_extract_crashes. */ +#if defined(_WIN32) +typedef struct { + const char *data; + uint32_t length; +} so_win_input_t; + +static const char *so_win_input_read(void *payload, uint32_t byte_index, TSPoint position, + uint32_t *bytes_read) { + (void)position; + const so_win_input_t *in = (const so_win_input_t *)payload; + if (byte_index >= in->length) { + *bytes_read = 0; + return NULL; + } + *bytes_read = in->length - byte_index; + return in->data + byte_index; +} + +static bool so_win_parse_deadline_reached(TSParseState *state) { + const uint64_t *deadline_ms = (const uint64_t *)state->payload; + return cbm_now_ms() >= *deadline_ms; +} +#endif + static bool so_parse_crashes(const char *content, CBMLanguage lang) { const TSLanguage *ts_lang = cbm_ts_language(lang); if (!ts_lang) { return false; } #if defined(_WIN32) + /* Match POSIX's 10 s ceiling: when CBM_TS_STACK_MERGE_MAX_DEPTH regresses, + * recursive stack merge overflows Windows' ~1 MB native stack within the + * first second and aborts immediately; past the cap, cancelling the + * ambiguity-exploded GLR grind at 10 s keeps Windows coverage identical to + * POSIX without burning ~200 s of pointless post-cap grind. */ TSParser *parser = ts_parser_new(); if (parser) { ts_parser_set_language(parser, ts_lang); - TSTree *tree = ts_parser_parse_string(parser, NULL, content, (uint32_t)strlen(content)); + so_win_input_t input_buf = {.data = content, .length = (uint32_t)strlen(content)}; + TSInput input = { + .payload = &input_buf, + .read = so_win_input_read, + .encoding = TSInputEncodingUTF8, + .decode = NULL, + }; + uint64_t deadline_ms = cbm_now_ms() + 10000U; + TSParseOptions options = { + .payload = &deadline_ms, + .progress_callback = so_win_parse_deadline_reached, + }; + TSTree *tree = ts_parser_parse_with_options(parser, NULL, input, options); if (tree) { ts_tree_delete(tree); } diff --git a/tests/test_test_impact_git.c b/tests/test_test_impact_git.c index a696348baa..ad8e830ed4 100644 --- a/tests/test_test_impact_git.c +++ b/tests/test_test_impact_git.c @@ -2,12 +2,15 @@ * No implementation helpers or command-count assumptions are used. */ #include "test_framework.h" #include "test_helpers.h" +#include "test_image_probe.h" #include #include +#include #include #include #include #include +#include #include enum { GF_PATH = 4096, GF_SMALL = 512 }; @@ -254,18 +257,66 @@ static bool gf_config(gf_fixture_t *fx, const char *key, const char *value) { return gf_git(fx, argv, NULL, 0); } -/* A--P---M(topic/HEAD) - * \ / - * Q--+--B(base) - * merge-base(M,B)=Q, which deliberately differs from first-parent(M)=P. - * Raw commit objects give fixed timestamps/identities without changing env. */ -static bool gf_fixture_open(gf_fixture_t *fx, bool sha256) { +/* Cache the immutable base repository (once for SHA-1 and once for SHA-256 per + * test-runner process) so every test gets its own fresh, isolated copy in <1ms + * instead of spawning 53 git subprocesses ~50 times (~2,600 spawns/run). */ +typedef struct { + bool ready; + gf_fixture_t base; +} gf_template_t; + +static gf_template_t gf_templates[2]; +static bool gf_atexit_registered; + +static void gf_cleanup_templates(void) { + for (int i = 0; i < 2; i++) { + if (gf_templates[i].base.home[0]) { + (void)th_rmtree(gf_templates[i].base.home); + gf_templates[i].base.home[0] = '\0'; + } + gf_templates[i].ready = false; + } +} + +static bool gf_copy_tree(const char *src, const char *dst, int depth) { + if (depth > 16 || th_mkdir_p(dst) != 0) { + return false; + } + cbm_dir_t *dir = cbm_opendir(src); + if (!dir) { + return false; + } + char *child_src = malloc(GF_PATH); + char *child_dst = malloc(GF_PATH); + bool ok = child_src != NULL && child_dst != NULL; + cbm_dirent_t *ent; + while (ok && (ent = cbm_readdir(dir)) != NULL) { + if (strcmp(ent->name, ".") == 0 || strcmp(ent->name, "..") == 0) { + continue; + } + ok = gf_path(child_src, src, ent->name) && gf_path(child_dst, dst, ent->name); + if (!ok) { + break; + } + if (ent->is_dir) { + ok = gf_copy_tree(child_src, child_dst, depth + 1); + } else { + ok = cbm_clone_or_copy_file(child_src, child_dst) == 0; + } + } + free(child_src); + free(child_dst); + cbm_closedir(dir); + return ok; +} + +static bool gf_fixture_build_raw(gf_fixture_t *fx, bool sha256, const char *prefix) { memset(fx, 0, sizeof(*fx)); const char *resolved = cbm_find_cli("git", cbm_get_home_dir()); if (!resolved || !gf_absolute(resolved) || strlen(resolved) >= sizeof(fx->git)) return false; memcpy(fx->git, resolved, strlen(resolved) + 1); - const char *home = th_mktempdir("cbm-git-facts"); + const char *home = th_mktempdir(prefix); if (!home || strlen(home) >= sizeof(fx->home)) return false; memcpy(fx->home, home, strlen(home) + 1); @@ -305,6 +356,42 @@ static bool gf_fixture_open(gf_fixture_t *fx, bool sha256) { fprintf(stderr, "Git facts fixture setup failed (%s, native Git: %s)\n", sha256 ? "required SHA-256" : "SHA-1", fx->git); (void)th_rmtree(fx->home); + fx->home[0] = '\0'; + } + return ok; +} + +/* A--P---M(topic/HEAD) + * \ / + * Q--+--B(base) + * merge-base(M,B)=Q, which deliberately differs from first-parent(M)=P. + * Raw commit objects give fixed timestamps/identities without changing env. */ +static bool gf_fixture_open(gf_fixture_t *fx, bool sha256) { + int slot = sha256 ? 1 : 0; + if (!gf_templates[slot].ready) { + if (!gf_fixture_build_raw(&gf_templates[slot].base, sha256, "cbm-git-facts-tpl")) { + return false; + } + gf_templates[slot].ready = true; + if (!gf_atexit_registered) { + (void)atexit(gf_cleanup_templates); + gf_atexit_registered = true; + } + } + *fx = gf_templates[slot].base; + fx->home[0] = '\0'; + const char *home = th_mktempdir("cbm-git-facts"); + if (!home || strlen(home) >= sizeof(fx->home)) + return false; + memcpy(fx->home, home, strlen(home) + 1); + bool ok = gf_path(fx->repo, fx->home, "repo") && gf_path(fx->capture, fx->home, "stdout.bin") && + gf_path(fx->log, fx->home, "stderr.log") && + gf_path(fx->object_file, fx->home, "object.bin") && + gf_copy_tree(gf_templates[slot].base.repo, fx->repo, 0) && + gf_config(fx, "core.worktree", fx->repo); + if (!ok) { + (void)th_rmtree(fx->home); + fx->home[0] = '\0'; } return ok; } @@ -640,7 +727,7 @@ TEST(test_git_facts_required_sha256_objects_and_identity) { TEST(test_git_facts_never_runs_external_diff_or_textconv) { gf_fixture_t fx; ASSERT_TRUE(gf_fixture_open(&fx, false)); - char binary[GF_PATH], marker[GF_PATH], command[GF_PATH * 3]; + char binary[GF_PATH], marker[GF_PATH], command[GF_PATH * 3], probe_src[GF_PATH]; bool prepared = gf_path(binary, fx.home, #ifdef _WIN32 "diff-probe.exe" @@ -648,11 +735,12 @@ TEST(test_git_facts_never_runs_external_diff_or_textconv) { "diff-probe" #endif ) && - gf_path(marker, fx.home, "driver-invoked") && gf_runner_binary; + gf_path(marker, fx.home, "driver-invoked") && + th_image_probe_path(probe_src, sizeof(probe_src)); if (prepared) { cbm_normalize_path_sep(binary); cbm_normalize_path_sep(marker); - prepared = cbm_copy_file(gf_runner_binary, binary) == 0; + prepared = cbm_clone_or_copy_file(probe_src, binary) == 0; } if (prepared) th_make_executable(binary); @@ -1712,15 +1800,22 @@ TEST(test_git_ancestor_changes_history_and_external_driver_guards_apply) { } ASSERT_TRUE(gfa_topology_stays_pinned()); gf_fixture_t fx;ASSERT_TRUE(gf_fixture_open(&fx,false)); - char binary[GF_PATH],marker[GF_PATH],command[GF_PATH*3],attributes_path[GF_PATH]; - bool prepared=gf_path(binary,fx.home, + char binary[GF_PATH], marker[GF_PATH], command[GF_PATH * 3], attributes_path[GF_PATH], + probe_src[GF_PATH]; + bool prepared = gf_path(binary, fx.home, #ifdef _WIN32 - "ancestor-diff-probe.exe" + "ancestor-diff-probe.exe" #else - "ancestor-diff-probe" + "ancestor-diff-probe" #endif - ) && gf_path(marker,fx.home,"ancestor-driver-invoked") && gf_runner_binary; - if(prepared){cbm_normalize_path_sep(binary);cbm_normalize_path_sep(marker);prepared=cbm_copy_file(gf_runner_binary,binary)==0;} + ) && + gf_path(marker, fx.home, "ancestor-driver-invoked") && + th_image_probe_path(probe_src, sizeof(probe_src)); + if (prepared) { + cbm_normalize_path_sep(binary); + cbm_normalize_path_sep(marker); + prepared = cbm_clone_or_copy_file(probe_src, binary) == 0; + } if(prepared)th_make_executable(binary); const char attributes[]="p.txt diff=fixturetrap\n"; prepared=prepared && gf_path(attributes_path,fx.repo,".gitattributes") && gf_write(attributes_path,attributes,sizeof(attributes)-1) && gf_driver_command(command,sizeof(command),binary,marker); From 3498078756680b99fbb92273ee63a9d77061c2c5 Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 06:08:58 +0100 Subject: [PATCH 10/11] fix(ci): complete wrapper sparse checkout, IPv4 npm order, TSan SIGALRM drain, and LPT weights - Include install.ps1, install.sh, and LICENSE in test-package-wrappers sparse checkout (windows-launcher.test.js reads install.ps1). - Set NODE_OPTIONS=--dns-result-order=ipv4first on test-ui to avoid transient Ubuntu runner IPv6 ENETUNREACH against registry.npmjs.org. - Drain any queued SIGALRM via SIG_IGN before restoring SIG_DFL in subprocess_spawn_backoff_resumes_after_eintr (fixes intermittent exit 142 under macOS TSan). - Re-calibrate LPT weights and Shard-1 bias (90/25) from live -O2/-g1 CI measurements. Signed-off-by: Guillaume Demay --- .github/workflows/_test.yml | 7 +++++++ scripts/run-tests-parallel.sh | 22 +++++++++++----------- tests/test_subprocess.c | 8 ++++++++ 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index f79cae0d52..7e8cd826e1 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -345,6 +345,9 @@ jobs: pkg scripts tests/test_smoke_wrapper_run.py + install.ps1 + install.sh + LICENSE - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: @@ -390,6 +393,10 @@ jobs: cache-dependency-path: graph-ui/package-lock.json - name: CodeAtlasWeb leg (install, unit, style, promises, acceptance, build) + env: + # Hosted Ubuntu runners intermittently advertise unreachable IPv6 + # routes to registry.npmjs.org (ENETUNREACH); prefer IPv4 first. + NODE_OPTIONS: "--dns-result-order=ipv4first" run: scripts/ci/test-ui.sh # ThreadSanitizer data-race gate. The threaded production surfaces (watcher, diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index 790de76cd2..a0a279c58e 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -236,7 +236,6 @@ shard_filter() { # of (suite list, phase, idx, total, skip_perf) so every shard agrees identically. w["incremental"] = (skip_perf == "1") ? 1 : 1200 w["php_member_walk"] = 325 - w["c_lsp_b"] = 270 w["doc_mentions_e"] = 240 w["edge_types_probe"] = 220 w["pipeline_b"] = 210 @@ -244,6 +243,7 @@ shard_filter() { w["grammar_probe_f_b"] = 200 w["test_impact_engine"] = 200 w["pipeline_d"] = 195 + w["c_lsp_b"] = 185 w["pipeline"] = 185 w["java_type_scope_b"] = 185 w["pipeline_c"] = 180 @@ -262,7 +262,8 @@ shard_filter() { w["doc_mentions_d"] = 115 w["edge_imports"] = 110 w["type_scope"] = 110 - w["c_lsp"] = 105 + w["cli_b"] = 100 + w["c_lsp"] = 100 w["lsp_resolution_probe"] = 95 w["node_creation_probe"] = 90 w["doc_mentions_jvm"] = 85 @@ -270,9 +271,8 @@ shard_filter() { w["mcp"] = 75 w["doc_mentions_rs"] = 75 w["grammar_probe_d"] = 75 - w["cli"] = 75 - w["cli_b"] = 65 w["stack_overflow_b"] = 65 + w["daemon_frontend"] = 60 w["grammar_probe_e"] = 60 w["doc_mentions_go"] = 58 w["grammar_probe_a"] = 58 @@ -292,19 +292,19 @@ shard_filter() { w["watcher"] = 40 w["grammar_probe_g"] = 38 w["grammar_probe_b"] = 38 - w["mcp_supervisor"] = 35 w["test_impact_tree_read"] = 34 w["test_impact_inventory"] = 32 w["extraction"] = 30 w["httpd"] = 28 - w["daemon_runtime"] = 28 - w["daemon_frontend"] = 28 w["test_impact_git"] = 25 + w["daemon_runtime"] = 20 + w["cli"] = 20 w["test_impact_git_b"] = 20 w["test_impact_git_c"] = 20 w["subprocess"] = 18 + w["mcp_supervisor"] = 10 w["index_supervisor"] = 10 - w["daemon_bootstrap"] = 8 + w["daemon_bootstrap"] = 5 w["daemon_application"] = 5 w["daemon_ipc"] = 2 } @@ -328,9 +328,9 @@ shard_filter() { } for (s = 1; s <= total; s++) load[s] = 0 if (total > 1) { - # Offset Shard 1 for Step 0 contracts + Step 5 prod guards. - if (phase == "par") load[1] = 180 - else if (phase == "flex") load[1] = 60 + # Offset Shard 1 for parallel Step 0 contracts (~25s) + Step 5 prod guards (~40s). + if (phase == "par") load[1] = 90 + else if (phase == "flex") load[1] = 25 } for (i = 1; i <= NR; i++) { if (phase == "flex") { diff --git a/tests/test_subprocess.c b/tests/test_subprocess.c index 50a7b4a274..578fa444ae 100644 --- a/tests/test_subprocess.c +++ b/tests/test_subprocess.c @@ -547,6 +547,14 @@ TEST(subprocess_spawn_backoff_resumes_after_eintr) { struct itimerval disabled = {0}; (void)setitimer(ITIMER_REAL, &disabled, NULL); if (handler_installed) { + /* Discard any already-queued SIGALRM (kernel or TSan user-space signal + * buffer) before restoring SIG_DFL, or a late delivery kills the next + * test with SIGALRM (exit 142) under macOS TSan. */ + struct sigaction ignore_action = {0}; + ignore_action.sa_handler = SIG_IGN; + (void)sigemptyset(&ignore_action.sa_mask); + (void)sigaction(SIGALRM, &ignore_action, NULL); + cbm_usleep(2000); (void)sigaction(SIGALRM, &previous_action, NULL); } From ae770ac4dbcb6415e878818508b63f88363878fe Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 06:37:19 +0100 Subject: [PATCH 11/11] fix(ci): widen test-ui sparse checkout and balance shard LPT weights Keep src/ and scripts/ in the test-ui and test-package-wrappers sparse checkouts (still skipping 1.48 GB of vendored grammars and tools) so UI security policy tests can read src/ui/httpd.c. Calibrate MSan/Shard-1 LPT weights in run-tests-parallel.sh from warm-cache -O2/-g1 runs, and restore sequential leg execution in memwaste-scaling.py to avoid dual-indexer RAM/atomic-counter contention on 4-vCPU runners. Signed-off-by: Guillaume Demay --- .github/workflows/_test.yml | 16 ++++++++-------- scripts/memwaste-scaling.py | 12 ++---------- scripts/run-tests-parallel.sh | 12 ++++++------ 3 files changed, 16 insertions(+), 24 deletions(-) diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index 7e8cd826e1..75452a03a6 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -342,12 +342,10 @@ jobs: filter: blob:none sparse-checkout-cone-mode: false sparse-checkout: | - pkg - scripts - tests/test_smoke_wrapper_run.py - install.ps1 - install.sh - LICENSE + /* + !/internal/cbm/vendored/ + !/tools/ + !/graph-ui/ - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: @@ -382,9 +380,11 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: filter: blob:none + sparse-checkout-cone-mode: false sparse-checkout: | - graph-ui - scripts/ci + /* + !/internal/cbm/vendored/ + !/tools/ - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: diff --git a/scripts/memwaste-scaling.py b/scripts/memwaste-scaling.py index 1cb532e1af..ea8f1b0602 100644 --- a/scripts/memwaste-scaling.py +++ b/scripts/memwaste-scaling.py @@ -30,7 +30,6 @@ from __future__ import annotations import argparse -from concurrent.futures import ThreadPoolExecutor import json import os import re @@ -199,15 +198,8 @@ def main() -> int: shutil.rmtree(os.path.join(work, sub), ignore_errors=True) k = args.replicas - # The two legs run in completely isolated workdirs, cache dirs, runtime dirs, - # and profraw dirs, and the verdict compares deterministic clang execution - # COUNTS (not wall time), so running leg K and leg 2K concurrently preserves - # exact counts while cutting scaling-lane wall time. - with ThreadPoolExecutor(max_workers=2) as pool: - fut_small = pool.submit(run_leg, binary, profdata, corpus, work, k) - fut_large = pool.submit(run_leg, binary, profdata, corpus, work, 2 * k) - small, info_k = fut_small.result() - large, info_2k = fut_large.result() + small, info_k = run_leg(binary, profdata, corpus, work, k) + large, info_2k = run_leg(binary, profdata, corpus, work, 2 * k) total_k = sum(small.values()) total_2k = sum(large.values()) diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.sh index a0a279c58e..dbaeecc04b 100644 --- a/scripts/run-tests-parallel.sh +++ b/scripts/run-tests-parallel.sh @@ -237,13 +237,15 @@ shard_filter() { w["incremental"] = (skip_perf == "1") ? 1 : 1200 w["php_member_walk"] = 325 w["doc_mentions_e"] = 240 + w["c_lsp_b"] = 235 + w["doc_mentions_b"] = 225 w["edge_types_probe"] = 220 + w["complexity_b"] = 215 w["pipeline_b"] = 210 w["grammar_probe_f"] = 200 w["grammar_probe_f_b"] = 200 w["test_impact_engine"] = 200 w["pipeline_d"] = 195 - w["c_lsp_b"] = 185 w["pipeline"] = 185 w["java_type_scope_b"] = 185 w["pipeline_c"] = 180 @@ -251,9 +253,7 @@ shard_filter() { w["pipeline_semantic_manifest_repro"] = 155 w["java_type_scope"] = 155 w["pipeline_semantic_manifest_repro_b"] = 150 - w["complexity_b"] = 145 w["stack_overflow_c"] = 145 - w["doc_mentions_b"] = 135 w["complexity"] = 120 w["test_impact_tree"] = 120 w["repro_reference_precision"] = 120 @@ -328,9 +328,9 @@ shard_filter() { } for (s = 1; s <= total; s++) load[s] = 0 if (total > 1) { - # Offset Shard 1 for parallel Step 0 contracts (~25s) + Step 5 prod guards (~40s). - if (phase == "par") load[1] = 90 - else if (phase == "flex") load[1] = 25 + # Offset Shard 1 for Step 0 contracts + Step 5 prod guards + ccache save (~70s wall * 4 cores). + if (phase == "par") load[1] = 240 + else if (phase == "flex") load[1] = 35 } for (i = 1; i <= NR; i++) { if (phase == "flex") {