From 1f94a2d5d576b4218461fe971ed35ed44ee2c440 Mon Sep 17 00:00:00 2001 From: Guillaume Demay Date: Sun, 6 Dec 2026 20:15:42 +0100 Subject: [PATCH] perf(ci): shard sanitizer legs, LPT-pack test waves, and parallelize Step 0/5 & TSan Split out from #3210 per maintainer review (Piece 2: test harness, sharding, wave runner, Step 0/5 parallelism, worker caps). Addresses both Piece 2 review items from #3210: - Makefile.cbm (test-tsan): use explicit `if [ "$$rc1" -ne 0 ] || [ "$$rc2" -ne 0 ]; then exit 1; fi;` instead of an AND list under `set -e` so a failing `pipeline` group can never exit 0 when the second group passes. Also consolidate 4 compiler `-dM -E` probes into one CC_DEFINES probe and make LLVM_BIN lazy. - tests/test_subprocess.c: replace the 2 ms sleep with a deterministic POSIX SIGALRM drain (sigprocmask SIG_BLOCK -> setitimer disable -> sigaction SIG_IGN -> unblock/reblock -> restore) with zero sleeps or timing dependence. Harness, sharding, and lane changes: - scripts/run-test-wave.py & scripts/run-tests-parallel.sh: deterministic LPT bin-packing across PAR/FLEX/EXCL phases, FLEX tail jobs=2 (keeping extraction exclusive at jobs=1), PAR-wave --worker-cap 2 (exempting core-count-asserting suites), and fast Windows stamp_windows_build_dir. - scripts/test.sh & tests/test_{makefile_ts_runtime_dependencies,codeql_retrace,security_fuzz_harness}.sh: parallel Step 0 contracts and Step 5-6 prod guards using temp log files (avoiding Windows pipe EOF hangs), skip redundant Step 0/5-6 on secondary shards while Shard 1 runs all contracts/guards, 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 FLEX/EXCL isolation, LPT sharding, shard-manifest emission, union guard, and content-verified ccache pass-through. - .github/workflows/_test.yml & scripts/ci/require-all-green.sh: shard diag/lsan-macos/msan (2 shards each) and right-size PR shard counts with full shard-completeness union verification, wire inputs.skip_perf to diag/lsan-macos/msan, and schedule macos-15-intel first in CORE_UNIX. Signed-off-by: Guillaume Demay --- .github/workflows/_test.yml | 121 +++- Makefile.cbm | 45 +- scripts/ci/msan-lane.sh | 10 +- scripts/ci/require-all-green.sh | 6 + scripts/msan.sh | 204 ++++++- scripts/run-test-wave.py | 27 + scripts/run-tests-parallel.sh | 300 +++++++--- scripts/test.sh | 529 ++++++++++-------- tests/test_codeql_retrace.sh | 49 +- .../test_makefile_ts_runtime_dependencies.sh | 69 ++- tests/test_security_fuzz_harness.sh | 42 +- tests/test_subprocess.c | 21 + 12 files changed, 1018 insertions(+), 405 deletions(-) diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index ed60aca83e..73a31da18f 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -47,6 +47,9 @@ 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 }} + 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 }} @@ -64,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 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. @@ -121,36 +127,43 @@ 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. 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=2; N_MAC=2; N_MAC_INTEL=3; 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 - 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)"}]') + 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" @@ -369,7 +382,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,23 +422,34 @@ 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' || '' }} 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 @@ -451,7 +479,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: @@ -462,20 +494,50 @@ 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 + - 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_TEST_SHARD: ${{ matrix.shard }} + CBM_TEST_LEG: msan-clang21 + CBM_SKIP_PERF: ${{ inputs.skip_perf && '1' || '' }} run: | sudo sysctl -w vm.mmap_rnd_bits=28 || true scripts/ci/msan-lane.sh run + - 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 + 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 @@ -483,7 +545,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: @@ -510,23 +576,34 @@ 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 + CBM_SKIP_PERF: ${{ inputs.skip_perf && '1' || '' }} run: | LLVM_PREFIX="$(brew --prefix llvm@22)" scripts/test.sh CC="$LLVM_PREFIX/bin/clang" CXX="$LLVM_PREFIX/bin/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 @@ -731,7 +808,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, test-msan] if: always() runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/Makefile.cbm b/Makefile.cbm index 6fcc6aef7d..345d1a6411 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -28,8 +28,11 @@ # build path (build.sh, test.sh, direct make) and is part of each command line. # Detected from the compiler's target, not the host, so a cross compiler run # on a Mac is left untouched. +# Probe compiler predefined macros once instead of spawning 4 separate +# $(CC) -dM -E invocations on every make startup (significant on Windows). +CC_DEFINES := $(shell echo | $(CC) $(ARCHFLAGS) -dM -E - 2>/dev/null) MACOS_MIN_VERSION := 14.0 -IS_APPLE_TARGET := $(shell echo | $(CC) $(ARCHFLAGS) -dM -E - 2>/dev/null | grep -q '__APPLE__' && echo yes || echo no) +IS_APPLE_TARGET := $(if $(findstring __APPLE__,$(CC_DEFINES)),yes,no) MACOS_MIN_FLAGS := ifeq ($(IS_APPLE_TARGET),yes) MACOS_MIN_FLAGS := -mmacosx-version-min=$(MACOS_MIN_VERSION) @@ -52,7 +55,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 $(findstring __GNUC__,$(CC_DEFINES)),$(if $(findstring __clang__,$(CC_DEFINES)),,yes)),yes,no) GCC_ONLY_FLAGS := ifeq ($(IS_GCC),yes) GCC_ONLY_FLAGS := -Wno-format-truncation -Wno-unused-result \ @@ -171,7 +174,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 $(findstring define _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 @@ -1346,8 +1349,37 @@ $(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) 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; \ + pipe_suites=""; other_suites=""; daemon_suites=""; \ + for s in $(TEST_TSAN_SUITES); do \ + case "$$s" in \ + 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; \ + done; \ + 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=$$!; \ + rc1=0; rc2=0; \ + wait "$$pid_pipe" || rc1=$$?; \ + wait "$$pid_other" || rc2=$$?; \ + cat "$$tmpdir/pipe.log" "$$tmpdir/other.log"; \ + if [ "$$rc1" -ne 0 ] || [ "$$rc2" -ne 0 ]; then exit 1; fi; \ + elif [ -n "$$pipe_suites$$other_suites" ]; then \ + CBM_WORKERS=4 TSAN_OPTIONS="$(TSAN_OPTIONS)" \ + $(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; # an explicit Make invocation requires a clean rendezvous and fails rather than @@ -1479,7 +1511,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 non-lint targets do not invoke `brew --prefix` on every make run. +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..b2624fde66 100755 --- a/scripts/ci/msan-lane.sh +++ b/scripts/ci/msan-lane.sh @@ -47,7 +47,15 @@ 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 "${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" \ + "${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..971023bbab 100755 --- a/scripts/ci/require-all-green.sh +++ b/scripts/ci/require-all-green.sh @@ -76,6 +76,12 @@ 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-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 20bb8fafe7..1ef49eeb01 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,133 @@ 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, 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"] = 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["daemon_frontend"] = 65 + w["extraction"] = 60 + w["doc_mentions_b"] = 55 + w["complexity"] = 54 + w["pipeline_semantic_manifest_repro_b"] = 46 + w["mcp"] = 35 + w["mcp_supervisor"] = 18 + w["pipeline_c"] = 37 + w["httpd"] = 36 + w["edge_types_probe"] = 32 + w["pipeline_b"] = 28 + w["grammar_probe_f"] = 28 + w["grammar_probe_f_b"] = 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 + 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" + : > "$RESULTS_FILE" + # c_lsp / c_lsp_b run in TAIL_EXCL under MSan so their high shadow+origin + # memory footprint does not overlap 3 other parallel MSan suites and + # trigger swap thrashing on 16 GiB CI runners. + SERIAL_SUITES="cli cli_b subprocess watcher incremental httpd ui index_resilience mcp mcp_supervisor \ + extraction c_lsp 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="extraction c_lsp c_lsp_b" for suite in $all_suites; do case " $MSAN_EXCLUDE " in *" $suite "*) @@ -186,10 +329,65 @@ else continue ;; esac - echo "=== msan: $suite ===" - ./build/msan/test-runner "$suite" || fails="$fails $suite" + echo "$suite" >> "$ACTIVE_FILE" + 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 + 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 ' ') 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" \ + --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-test-wave.py b/scripts/run-test-wave.py index 304c3ba63e..ebda8a13d2 100755 --- a/scripts/run-test-wave.py +++ b/scripts/run-test-wave.py @@ -57,10 +57,21 @@ "store_arch", "daemon_runtime", "cli", + "cli_b", "node_creation_probe", "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 @@ -109,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, @@ -180,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") @@ -187,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: @@ -504,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 b52c514122..18d7c9019b 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. @@ -208,28 +220,139 @@ 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, 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" -v skip_perf="${CBM_SKIP_PERF:-0}" ' 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 (calibrated from live cross-platform CI runs); + # unlisted suites get default weight 5. Pure deterministic function + # 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["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["pipeline"] = 185 + w["java_type_scope_b"] = 185 + w["pipeline_c"] = 180 + w["lang_contract"] = 170 + w["pipeline_semantic_manifest_repro"] = 155 + w["java_type_scope"] = 155 + w["pipeline_semantic_manifest_repro_b"] = 150 + w["stack_overflow_c"] = 145 + 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["edge_imports"] = 110 + w["type_scope"] = 110 + w["cli_b"] = 100 + w["c_lsp"] = 100 + 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["stack_overflow_b"] = 65 + w["daemon_frontend"] = 60 + w["grammar_probe_e"] = 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["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"] = 5 + w["daemon_application"] = 5 + w["daemon_ipc"] = 2 + } + { + 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 + if (total > 1) { + # 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") { + 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]] + } } ' } @@ -261,7 +384,13 @@ 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 \ +# 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 suites cannot collide on runtime endpoints and safely overlap in the +# quiet FLEX tail (CBM_TAIL_JOBS=2). 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 mcp_supervisor \ extraction \ stack_overflow_a stack_overflow_b stack_overflow_c \ index_supervisor daemon_application daemon_runtime daemon_frontend \ @@ -269,26 +398,38 @@ SERIAL_SUITES="cli subprocess watcher incremental httpd ui index_resilience mcp is_serial() { case " $SERIAL_SUITES " in *" $1 "*) return 0 ;; *) return 1 ;; esac } +TAIL_EXCL="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_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 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 < "$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" "$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 +447,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 @@ -325,6 +466,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" \ @@ -333,42 +475,24 @@ 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" -# 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 @@ -376,8 +500,8 @@ done < "$SER_FILE" # 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/test.sh b/scripts/test.sh index 505e5ab775..f121fc7a42 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -268,169 +268,174 @@ if [ -n "$SUITES" ]; then exit "$?" 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" +# 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 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" +# 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 +fi +python3 - "$ROOT" "$BASH" "$CONTRACT_JOBS" <<'PY' +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] +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", 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), + ("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), +] + +# 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]), + ) + + 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 if [ "$CONTRACTS_ONLY" -eq 1 ]; then echo "=== test.sh: contracts-only — every contract step passed ===" @@ -456,12 +461,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 @@ -492,6 +499,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). @@ -518,70 +531,120 @@ 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 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)) + +# (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), +] + +# 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]), + ) + + 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 ===" diff --git a/tests/test_codeql_retrace.sh b/tests/test_codeql_retrace.sh index 350271febe..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 @@ -63,11 +65,13 @@ 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)) + 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", @@ -94,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_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_subprocess.c b/tests/test_subprocess.c index 50a7b4a274..bf89ca5a02 100644 --- a/tests/test_subprocess.c +++ b/tests/test_subprocess.c @@ -544,11 +544,32 @@ TEST(subprocess_spawn_backoff_resumes_after_eintr) { cbm_proc_result_t result = run_sh("exit 0", 0); uint64_t elapsed_ms = cbm_now_ms() - started_at; + /* Block SIGALRM before disarming the interval timer so no asynchronous + * delivery can race with teardown; then set SIG_IGN (POSIX mandates + * discarding any kernel-pending SIGALRM immediately) and unblock SIGALRM + * (flushing any TSan user-space pending SIGALRM against SIG_IGN) before + * restoring previous_action. Fully deterministic, zero sleep. */ + sigset_t alrm_mask; + sigset_t saved_mask; + (void)sigemptyset(&alrm_mask); + (void)sigaddset(&alrm_mask, SIGALRM); + bool masked = sigprocmask(SIG_BLOCK, &alrm_mask, &saved_mask) == 0; struct itimerval disabled = {0}; (void)setitimer(ITIMER_REAL, &disabled, NULL); if (handler_installed) { + struct sigaction ignore_action = {0}; + ignore_action.sa_handler = SIG_IGN; + (void)sigemptyset(&ignore_action.sa_mask); + (void)sigaction(SIGALRM, &ignore_action, NULL); + if (masked) { + (void)sigprocmask(SIG_UNBLOCK, &alrm_mask, NULL); + (void)sigprocmask(SIG_BLOCK, &alrm_mask, NULL); + } (void)sigaction(SIGALRM, &previous_action, NULL); } + if (masked) { + (void)sigprocmask(SIG_SETMASK, &saved_mask, NULL); + } ASSERT_TRUE(handler_installed); ASSERT_TRUE(timer_started);