From d65ab6a0d6d26d1d9e8826da67f596694382ab44 Mon Sep 17 00:00:00 2001 From: LeonMMcoset Date: Mon, 23 Nov 2026 12:44:56 +0000 Subject: [PATCH 1/7] ci: parallelize heavy regressions and improve cache reuse --- .github/CI.md | 50 ++++++--- .github/workflows/ci.yml | 124 ++++++++++++++++++++-- scripts/ci/cache-prune.py | 116 +++++++++++++++++++++ scripts/reliefos/Makefile.tests | 38 ++++++- tests/build/test-ci.sh | 2 +- tools/ci.py | 4 +- tools/ci_test_shards.py | 84 +++++++++++++++ tools/tests/test_ci.py | 12 ++- tools/tests/test_ci_cache_prune.py | 121 +++++++++++++++++++++ tools/tests/test_ci_test_shards.py | 162 +++++++++++++++++++++++++++++ 10 files changed, 687 insertions(+), 26 deletions(-) create mode 100644 scripts/ci/cache-prune.py create mode 100644 tools/ci_test_shards.py create mode 100644 tools/tests/test_ci_cache_prune.py create mode 100644 tools/tests/test_ci_test_shards.py diff --git a/.github/CI.md b/.github/CI.md index 88fa068a..496d7077 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -7,13 +7,15 @@ flowchart TD B --> D[Documentation: Sphinx 5 / 7 / 9] B --> L[Restore verified downloads and compiler cache] L --> E[Build images and Pages once] - E --> F[Host and build regressions] + E --> F[Product and core regressions] + B --> R[Isolated regressions: kernel / auth / pages] F --> G[Record commit and SHA-256 / upload products] G --> H[BIOS: disk / live / installer] G --> I[UEFI: disk / live / installer] B --> J[CI result] C --> J D --> J + R --> J H --> J I --> J J --> K[Deploy the verified Pages artifact on main] @@ -40,18 +42,29 @@ filter's file-count limit. Manual runs default to validation only. Checking ## Products, signatures and deployment -The build job runs `make all pages` and `make test` in one working tree. This -lets product-dependent regressions consume the current SDK, libraries and -staging tree without transferring the entire compiler output between jobs. +The build job runs `make all pages` and then +`make RELIEFOS_CI_TEST_GROUP=core test` in one working tree. This lets +product-dependent regressions consume the current SDK, libraries and staging +tree without transferring the entire compiler output between jobs. Common runner dependencies live in `scripts/ci/install.sh` and the local setup action. The build checkout includes full Git history for kernel rollback regressions. Host development packages include FFmpeg, Cairo, GLib and Xvfb. -Builds start alongside workflow checks and the documentation matrix; the final -gate still requires all selected stages. `make -j"$(nproc)" test` passes the -jobserver through the contract runner to nested Make processes. Suites remain -sequential because some temporarily probe shared source files. Each suite logs -its elapsed seconds, and a dry run never executes its scripts. +Three focused regression jobs start alongside the product build, workflow +checks and documentation matrix. `test-ci-kernel` covers concurrent and +incremental builds, the kernel adapter, header boundaries, reproducibility and +submodule rollback; `test-ci-auth` covers authentication staging; +`test-ci-pages` covers complete site assembly. Each job has its own checkout +and output tree and builds only its group's prerequisites. The final gate +requires the product build, every regression group and both boot jobs. + +`tools/ci_test_shards.py` owns the test partition and supplies the workflow +matrix. It checks that each focused suite exists and belongs to exactly one +group; new suites join core automatically. Ordinary `make test` continues to +run every suite. `make -j"$(nproc)"` passes the jobserver through the contract +runner to nested Make processes. Suites within a group remain sequential +because some temporarily probe shared source files. Each suite logs its +elapsed seconds, and a dry run never executes its scripts. The download cache covers both repositories' `cache/downloads`, keyed by both dependency locks and runner platform. A fallback can supply unchanged archives @@ -61,10 +74,16 @@ so a later test failure does not throw them away. ReliefNT fetch is already delegated by the parent and is not repeated. `ccache` wraps the standard compiler names for the build and its nested tests. -Its cache is limited to 1 GiB, checks compiler contents, and retains the default -header, flag and working-directory checks. Path rewriting stays disabled so -Kbuild source/dependency records retain their native paths. Each run saves a new cache, even -after a test failure, and reports hits/misses in the run summary. No output +Compiler caches have separate keys for the product build (4G), kernel tests +(2G), authentication tests (1G) and Pages tests (1G). They check compiler +contents and retain the default header, flag and working-directory checks. +Path rewriting stays disabled so Kbuild source/dependency records retain their +native paths. Each run saves a new cache, even after a test failure, and reports +hits/misses in the run summary. A main-only maintenance job retains at most two +snapshots per role/platform/ref and applies an 8 GiB budget to the new compiler +cache namespace, always preserving the latest main snapshot for each role and +platform. It leaves download, legacy and unrelated caches alone. Only this +maintenance job receives Actions write permission; PR checks do not. No output tree, signed APK, image or private key is restored from a build cache. GitHub's cache ref scope separates PR caches from the default branch. The pinned actionlint binary has a separate platform/version cache; warm runs avoid @@ -78,7 +97,9 @@ directory and is removed before artifact upload, including on failure. `ci/manifest.json` records the source commit, kernel release, sizes and SHA-256 of all three boot media, `.config` and `kernel-install/install.bundle.json`. -The exact same installer must appear in Pages. The public Pages tree contains +The exact same installer must appear in Pages. Image transfer uses ZIP +compression level 1; the manifest continues to identify the uncompressed +image bytes. The public Pages tree contains the manifest as `build-manifest.json`. Boot jobs verify all five files both before and after running; they call the existing acceptance runner directly and never invoke Make or rebuild an image. @@ -101,6 +122,7 @@ superseded PR runs. GitHub Release publication remains a separate procedure. actionlint shellcheck scripts/ci/*.sh sh tests/build/test-ci.sh +python3 tools/ci_test_shards.py --check ``` The workflow pins third-party action commits and actionlint's version. Full diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 893ee519..b4131c32 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,7 @@ jobs: build: ${{ steps.scope.outputs.build }} docs: ${{ steps.scope.outputs.docs }} publish: ${{ steps.scope.outputs.publish }} + test-groups: ${{ steps.groups.outputs.groups }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -45,6 +46,11 @@ jobs: - name: Select checks for this commit id: scope run: python3 tools/ci.py changes + - name: Select every focused regression group + id: groups + run: | + groups=$(python3 tools/ci_test_shards.py --groups-json) + printf 'groups=%s\n' "$groups" >> "$GITHUB_OUTPUT" checks: name: Workflow and orchestration checks @@ -77,7 +83,7 @@ jobs: - name: Check CI scripts run: | shellcheck scripts/ci/*.sh - python3 -m unittest discover -s tools/tests -p test_ci.py -v + python3 -m unittest discover -s tools/tests -p 'test_ci*.py' -v documentation: name: Documentation @@ -96,7 +102,7 @@ jobs: # Kbuild's native source/dependency records retain their absolute paths. CCACHE_BASEDIR: '' CCACHE_COMPILERCHECK: content - CCACHE_MAXSIZE: 1G + CCACHE_MAXSIZE: 4G steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -122,8 +128,9 @@ jobs: uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3 with: path: ${{ env.CCACHE_DIR }} - key: ccache-v1-${{ runner.os }}-${{ runner.arch }}-${{ github.run_id }}-${{ github.run_attempt }} + key: ccache-v2-${{ runner.os }}-${{ runner.arch }}-build-${{ github.run_id }}-${{ github.run_attempt }} restore-keys: | + ccache-v2-${{ runner.os }}-${{ runner.arch }}-build- ccache-v1-${{ runner.os }}-${{ runner.arch }}- - name: Reset compiler cache statistics run: ccache --zero-stats @@ -161,11 +168,11 @@ jobs: run: | mkdir -p out/x86_64/release/ci make -j"$(nproc)" APK_SIGNING_KEY="$APK_SIGNING_KEY" all pages 2>&1 | tee out/x86_64/release/ci/build.log - - name: Run host and build regressions + - name: Run product and core regressions timeout-minutes: 60 run: | mkdir -p out/tmp - TMPDIR="$PWD/out/tmp" make -j"$(nproc)" APK_SIGNING_KEY="$APK_SIGNING_KEY" test 2>&1 | tee out/x86_64/release/ci/regressions.log + TMPDIR="$PWD/out/tmp" make -j"$(nproc)" APK_SIGNING_KEY="$APK_SIGNING_KEY" RELIEFOS_CI_TEST_GROUP=core test 2>&1 | tee out/x86_64/release/ci/regressions.log - name: Verify products and record their identity run: | qemu-img info out/x86_64/release/images/reliefos.vmdk @@ -198,7 +205,7 @@ jobs: out/x86_64/release/ci/manifest.json include-hidden-files: true if-no-files-found: error - compression-level: 0 + compression-level: 1 retention-days: 3 - name: Upload verified Pages tree if: needs.changes.outputs.publish == 'true' @@ -219,6 +226,91 @@ jobs: if-no-files-found: warn retention-days: 7 + regressions: + name: Regressions (${{ matrix.group }}) + needs: changes + if: needs.changes.outputs.build == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + group: ${{ fromJSON(needs.changes.outputs.test-groups) }} + env: + CCACHE_DIR: ${{ github.workspace }}/cache/ccache + CCACHE_BASEDIR: '' + CCACHE_COMPILERCHECK: content + CCACHE_MAXSIZE: ${{ matrix.group == 'kernel' && '2G' || '1G' }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + submodules: recursive + persist-credentials: false + - uses: ./.github/actions/setup + with: + profile: build + - name: Restore locked dependency downloads + id: download-cache + uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3 + with: + path: | + cache/downloads + kernel/reliefnt/cache/downloads + key: downloads-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('configs/dependencies.lock.json', 'kernel/reliefnt/configs/dependencies.lock.json') }} + restore-keys: | + downloads-v1-${{ runner.os }}-${{ runner.arch }}- + - name: Restore compiler cache for this group + id: compiler-cache + uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3 + with: + path: ${{ env.CCACHE_DIR }} + key: ccache-v2-${{ runner.os }}-${{ runner.arch }}-${{ matrix.group }}-${{ github.run_id }}-${{ github.run_attempt }} + restore-keys: | + ccache-v2-${{ runner.os }}-${{ runner.arch }}-${{ matrix.group }}- + - name: Prepare build configuration + env: + INSTALLER_ROOT_SIZE_MIB: ${{ inputs.installer_root_size_mib || '32' }} + run: bash scripts/ci/configure.sh + - name: Save verified dependency downloads + if: steps.download-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3 + with: + path: | + cache/downloads + kernel/reliefnt/cache/downloads + key: ${{ steps.download-cache.outputs.cache-primary-key }} + - name: Validate the complete test partition + run: python3 tools/ci_test_shards.py --check + - name: Reset compiler cache statistics + run: ccache --zero-stats + - name: Run isolated regression group + env: + TEST_GROUP: ${{ matrix.group }} + run: | + mkdir -p out/tmp out/x86_64/release/ci + TMPDIR="$PWD/out/tmp" make -j"$(nproc)" "test-ci-$TEST_GROUP" 2>&1 | tee "out/x86_64/release/ci/regressions-$TEST_GROUP.log" + - name: Report compiler cache usage + if: ${{ !cancelled() && steps.compiler-cache.outcome == 'success' }} + run: ccache --show-stats | tee -a "$GITHUB_STEP_SUMMARY" + - name: Save compiler cache for this group + if: ${{ !cancelled() && steps.compiler-cache.outcome == 'success' }} + uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3 + with: + path: ${{ env.CCACHE_DIR }} + key: ${{ steps.compiler-cache.outputs.cache-primary-key }} + - name: Preserve regression diagnostics + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: regression-diagnostics-${{ matrix.group }}-${{ github.sha }} + path: | + out/x86_64/release/logs + out/x86_64/release/ci + out/kbuild-migration + if-no-files-found: warn + retention-days: 7 + smoke: name: Boot (${{ matrix.firmware }}) needs: build @@ -262,7 +354,7 @@ jobs: ci: name: CI result - needs: [changes, checks, documentation, build, smoke] + needs: [changes, checks, documentation, build, regressions, smoke] if: always() runs-on: ubuntu-24.04 timeout-minutes: 5 @@ -275,6 +367,24 @@ jobs: NEEDS_JSON: ${{ toJSON(needs) }} run: python3 tools/ci.py summary + cache-maintenance: + name: Maintain compiler cache snapshots + needs: [build, regressions] + if: ${{ !cancelled() && github.event_name == 'push' && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + actions: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Prune superseded compiler cache snapshots + env: + GH_TOKEN: ${{ github.token }} + run: python3 scripts/ci/cache-prune.py --repo "$GITHUB_REPOSITORY" --apply + deploy: name: Deploy verified Pages needs: [changes, ci] diff --git a/scripts/ci/cache-prune.py b/scripts/ci/cache-prune.py new file mode 100644 index 00000000..4fb59bac --- /dev/null +++ b/scripts/ci/cache-prune.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Bound CI compiler-cache snapshots while retaining the newest main caches.""" +import argparse +from datetime import datetime +import json +import os +import re +import subprocess +import sys + + +PREFIX = "ccache-v2-" +KEY = re.compile(r"ccache-v2-([A-Za-z0-9]+)-([A-Za-z0-9]+)-(build|kernel|auth|pages)-[0-9]+-[0-9]+") +MAIN = "refs/heads/main" +GIB = 1024 ** 3 + + +def timestamp(value): + result = datetime.fromisoformat(value.replace("Z", "+00:00")) + if result.tzinfo is None: + raise ValueError("Cache timestamp must include a timezone") + return result + + +def plan(caches, *, budget=8 * GIB, keep=2): + """Return eligible deletions without touching downloads or protected main caches.""" + if budget < 0 or keep < 1: + raise ValueError("Cache budget must be nonnegative and keep must be positive") + managed = {} + for item in caches: + match = KEY.fullmatch(item["key"]) + if match is None: + continue + if (type(item["id"]) is not int or item["id"] <= 0 or + type(item["size_in_bytes"]) is not int or item["size_in_bytes"] < 0 or + not isinstance(item["ref"], str)): + raise ValueError("Invalid compiler-cache metadata") + created = timestamp(item["created_at"]) + accessed = timestamp(item.get("last_accessed_at") or item["created_at"]) + record = dict(item, platform_role=match.groups(), created=created, accessed=accessed) + previous = managed.get(item["id"]) + if previous is not None and previous != record: + raise ValueError("Inconsistent duplicate cache metadata") + managed[item["id"]] = record + groups = {} + protected = set() + ordered = sorted(managed.values(), key=lambda c: (c["created"], c["id"]), reverse=True) + for item in ordered: + identity = item["platform_role"] + group = groups.setdefault((identity, item["ref"]), []) + if item["ref"] == MAIN and not group: + protected.add(item["id"]) + group.append(item) + selected = {item["id"] for group in groups.values() for item in group[keep:]} + before = sum(item["size_in_bytes"] for item in managed.values()) + remaining = before - sum(managed[id]["size_in_bytes"] for id in selected) + eligible = sorted((item for item in managed.values() + if item["id"] not in protected | selected), + key=lambda c: (c["accessed"], c["created"], c["id"])) + for item in eligible: + if remaining <= budget: + break + selected.add(item["id"]) + remaining -= item["size_in_bytes"] + return {"delete": sorted(selected), "protected": sorted(protected), + "before": before, "remaining": remaining} + + +def gh_api(endpoint, *, method="GET"): + return json.loads(subprocess.check_output( + ["gh", "api", endpoint, "--method", method], text=True)) + + +def list_caches(repository, api=gh_api): + result = [] + page = 1 + while True: + data = api(f"repos/{repository}/actions/caches?key={PREFIX}&per_page=100&page={page}") + items = data["actions_caches"] + result.extend(items) + if len(items) < 100: + return result + page += 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY")) + parser.add_argument("--budget-gib", type=int, default=8) + parser.add_argument("--keep", type=int, default=2) + parser.add_argument("--apply", action="store_true", help="Delete the selected snapshots (main push only)") + args = parser.parse_args(argv) + if not args.repo or not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", args.repo): + raise ValueError("Expected an owner/repository name") + if args.apply and (os.environ.get("GITHUB_REF") != MAIN or + os.environ.get("GITHUB_EVENT_NAME") != "push" or + os.environ.get("GITHUB_REPOSITORY") != args.repo): + raise ValueError("Cache deletion requires a push workflow on its own main branch") + result = plan(list_caches(args.repo), budget=args.budget_gib * GIB, keep=args.keep) + print(json.dumps(dict(result, apply=args.apply), sort_keys=True)) + if args.apply: + for id in result["delete"]: + # The delete endpoint returns an empty 204 response. + subprocess.run(["gh", "api", f"repos/{args.repo}/actions/caches/{id}", + "--method", "DELETE"], check=True) + if result["remaining"] > args.budget_gib * GIB: + print("Newest main snapshots exceed the budget; they remain protected.") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except (ValueError, KeyError, TypeError, OSError, subprocess.CalledProcessError) as error: + print(f"Cache maintenance: {error}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/reliefos/Makefile.tests b/scripts/reliefos/Makefile.tests index 5cafbc5a..cbb34585 100644 --- a/scripts/reliefos/Makefile.tests +++ b/scripts/reliefos/Makefile.tests @@ -20,6 +20,29 @@ RELIEFOS_HOST_TEST_SANITISED += $(O_HOST)/tests-sanitised/test_locale_conf # test-brand-identity.sh is the ReliefOS/ReliefNT rename gate (plan task 1) and # is picked up by this wildcard on purpose: every test-build run audits names. RELIEFOS_BUILD_TESTS := $(sort $(wildcard $(RELIEFOS_SRC)/tests/build/test-*.sh)) +# Local `make test` keeps the complete inventory. CI runs its core in the image +# build and the explicit heavy groups in independent runner/source checkouts. +# The selector validates all shards before filtering, so a renamed/missing +# offloaded suite fails before a partial test run can be reported as complete. +RELIEFOS_CI_TEST_GROUP ?= all +ifneq ($(words $(RELIEFOS_CI_TEST_GROUP)),1) +$(error RELIEFOS_CI_TEST_GROUP must be all or core) +endif +ifeq ($(filter $(RELIEFOS_CI_TEST_GROUP),all core),) +$(error RELIEFOS_CI_TEST_GROUP must be all or core; use test-ci-kernel/auth/pages for focused groups) +endif +RELIEFOS_CI_SELECTOR := $(RELIEFOS_SRC)/tools/ci_test_shards.py +define RELIEFOS_CI_SELECT_TESTS +$(eval reliefos_ci_selected := $(shell $(RELIEFOS_TEST_PYTHON) '$(RELIEFOS_CI_SELECTOR)' --root '$(RELIEFOS_SRC)' --group $(1) || echo __CI_SHARD_ERROR__))$(if $(filter __CI_SHARD_ERROR__,$(reliefos_ci_selected)),$(error CI test shard validation failed),$(addprefix $(RELIEFOS_SRC)/tests/build/,$(reliefos_ci_selected))) +endef +RELIEFOS_SELECTED_BUILD_TESTS := $(RELIEFOS_BUILD_TESTS) +ifeq ($(RELIEFOS_CI_TEST_GROUP),core) +RELIEFOS_SELECTED_BUILD_TESTS := $(call RELIEFOS_CI_SELECT_TESTS,core) +endif +ifneq ($(filter test-ci-kernel test-ci-auth test-ci-pages test-ci-validate,$(MAKECMDGOALS)),) +# Validate while parsing, before any expensive prerequisite can start. +reliefos_ci_validated := $(call RELIEFOS_CI_SELECT_TESTS,all) +endif # Suites that are too long to run on every change but must not be forgotten: # repeated -j1/-j8 comparisons and, later, guest boots. Plan section 13 forbids # presenting an unrun long test as a skipped pass, so they are a separate goal. @@ -91,9 +114,22 @@ leonos-test-tools-plain: reliefos-test-tools-plain leonos-test-tools-sanitised: reliefos-test-tools-sanitised test-build: sdk rootfs-raw $(HOST_RUNTIME_DEVELOPMENT_PRODUCTS) test-tools $(RELIEFOS_HOST_TOOLS) $(INITRAMFS_BUSYBOX_ELF) $(INITRAMFS_BUSYBOX_LINKS) $(RELIEFOS_KERNEL_RECOVERY) $(HEADER_EXPORT_MANIFEST) - +@$(call RELIEFOS_RUN_CONTRACT_TESTS,$(RELIEFOS_BUILD_TESTS)) + +@$(call RELIEFOS_RUN_CONTRACT_TESTS,$(RELIEFOS_SELECTED_BUILD_TESTS)) @$(RELIEFOS_TEST_PYTHON) $(RELIEFOS_SRC)/tools/test_xorg_qemu.py --source-only +.PHONY: test-ci-validate test-ci-kernel test-ci-auth test-ci-pages +test-ci-validate: + @$(RELIEFOS_TEST_PYTHON) '$(RELIEFOS_CI_SELECTOR)' --root '$(RELIEFOS_SRC)' --check + +# These contracts build their own disposable outputs; staging the complete +# SDK/rootfs first would duplicate the image build for every CI shard. +test-ci-kernel test-ci-auth: test-ci-validate $(RELIEFOS_HOST_TOOLS) + +@$(call RELIEFOS_RUN_CONTRACT_TESTS,$(call RELIEFOS_CI_SELECT_TESTS,$(patsubst test-ci-%,%,$@))) + +# Pages uses the real native module/initramfs producers and static verifier. +test-ci-pages: test-ci-validate $(RELIEFOS_HOST_TOOLS) $(INITRAMFS_BUSYBOX_ELF) $(INITRAMFS_BUSYBOX_LINKS) $(RELIEFOS_KERNEL_RECOVERY) + +@$(call RELIEFOS_RUN_CONTRACT_TESTS,$(call RELIEFOS_CI_SELECT_TESTS,pages)) + test-long: $(RELIEFOS_HOST_TOOLS) grub-host grub-efi +@$(call RELIEFOS_RUN_CONTRACT_TESTS,$(RELIEFOS_LONG_TESTS)) diff --git a/tests/build/test-ci.sh b/tests/build/test-ci.sh index a92be23a..a26c8bdc 100644 --- a/tests/build/test-ci.sh +++ b/tests/build/test-ci.sh @@ -1,4 +1,4 @@ #!/bin/sh set -eu src=$(CDPATH= cd -- "$(dirname "$0")/../.." && pwd) -exec python3 -m unittest discover -s "$src/tools/tests" -p test_ci.py -v +exec python3 -m unittest discover -s "$src/tools/tests" -p 'test_ci*.py' -v diff --git a/tools/ci.py b/tools/ci.py index 0fe4fd69..f80c3e68 100644 --- a/tools/ci.py +++ b/tools/ci.py @@ -24,7 +24,7 @@ "scripts/reliefos/Makefile.site", "tools/build/docs-page.sh", "tools/test_documentation.py", ".github/workflows/check-docs.yml", ".github/workflows/ci.yml", ".github/actions/", ) -STAGES = ("changes", "checks", "documentation", "build", "smoke") +STAGES = ("changes", "checks", "documentation", "build", "regressions", "smoke") def matches(path, patterns): @@ -146,7 +146,7 @@ def summary(needs): if outputs.get("docs") == "true": required.add("documentation") if outputs.get("build") == "true": - required.update(("build", "smoke")) + required.update(("build", "regressions", "smoke")) passed = valid_scope and set(needs) == set(STAGES) lines = ["## ReliefOS CI", "", "| Stage | Required | Result |", "| --- | --- | --- |"] for name in STAGES: diff --git a/tools/ci_test_shards.py b/tools/ci_test_shards.py new file mode 100644 index 00000000..06f800ab --- /dev/null +++ b/tools/ci_test_shards.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Partition the complete build-test inventory without dropping new suites.""" +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path +import re +import sys + + +OFFLOADED_TESTS = { + "kernel": ( + "test-concurrency.sh", + "test-incremental.sh", + "test-kernel-adapter.sh", + "test-header-boundary.sh", + "test-reproducible.sh", + "test-submodule-contract.sh", + "test-submodule-rollback-build.sh", + ), + "auth": ("test-auth-stage.sh",), + "pages": ("test-pages.sh",), +} +GROUPS = ("all", "core", "kernel", "auth", "pages") + + +def partition(root: Path, offloaded=None) -> dict[str, tuple[str, ...]]: + """Validate explicit shards; unassigned present and future suites are core.""" + offloaded = OFFLOADED_TESTS if offloaded is None else offloaded + if set(offloaded) != set(GROUPS[2:]): + raise ValueError("Expected exactly the kernel, auth and pages test shards") + directory = root / "tests/build" + inventory = tuple(sorted(path.name for path in directory.glob("test-*.sh") if path.is_file())) + if not inventory: + raise ValueError(f"No build test suites found in {directory}") + assigned = [] + for group, names in offloaded.items(): + if not names: + raise ValueError(f"Empty explicit test shard: {group}") + for name in names: + if not isinstance(name, str) or not re.fullmatch(r"test-[A-Za-z0-9_-]+\.sh", name): + raise ValueError(f"Invalid build suite name in {group}: {name!r}") + if name not in inventory: + raise ValueError(f"Missing build suite in {group}: {name}") + assigned.append(name) + duplicates = sorted(name for name, count in Counter(assigned).items() if count != 1) + if duplicates: + raise ValueError("Build suites assigned more than once: " + ", ".join(duplicates)) + result = {group: tuple(sorted(names)) for group, names in offloaded.items()} + result["core"] = tuple(name for name in inventory if name not in assigned) + combined = tuple(name for group in GROUPS[1:] for name in result[group]) + if len(combined) != len(inventory) or set(combined) != set(inventory): + raise ValueError("CI test shards do not cover the complete build-test inventory") + result["all"] = inventory + return result + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) + command = parser.add_mutually_exclusive_group(required=True) + command.add_argument("--group", choices=GROUPS) + command.add_argument("--check", action="store_true") + command.add_argument("--groups-json", action="store_true", + help="Emit the validated focused-job matrix") + arguments = parser.parse_args(argv) + try: + groups = partition(arguments.root) + except (OSError, ValueError) as error: + parser.exit(1, f"CI test shards: {error}\n") + if arguments.groups_json: + print(json.dumps(list(GROUPS[2:]))) + elif arguments.check: + print("Validated " + ", ".join(f"{group}={len(groups[group])}" for group in GROUPS[1:]) + + f"; all {len(groups['all'])} build suites are assigned exactly once") + else: + print(" ".join(groups[arguments.group])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/tests/test_ci.py b/tools/tests/test_ci.py index 0b6c5c83..0b1ffc65 100644 --- a/tools/tests/test_ci.py +++ b/tools/tests/test_ci.py @@ -162,7 +162,7 @@ def needs(self, build=True, docs=True): result = {name: {"result": "success"} for name in ci.STAGES} result["changes"]["outputs"] = {"build": str(build).lower(), "docs": str(docs).lower(), "publish": "false"} if not build: - for name in ("build", "smoke"): + for name in ("build", "regressions", "smoke"): result[name]["result"] = "skipped" if not docs: result["documentation"]["result"] = "skipped" @@ -188,6 +188,16 @@ def test_missing_job_or_invalid_scope_fails_gate(self): needs["changes"]["outputs"]["build"] = "" self.assertFalse(ci.summary(needs)[0]) + def test_product_success_does_not_replace_regression_results(self): + for result in ("failure", "cancelled", "skipped", "missing"): + with self.subTest(result=result): + needs = self.needs() + if result == "missing": + del needs["regressions"] + else: + needs["regressions"]["result"] = result + self.assertFalse(ci.summary(needs)[0]) + def test_publication_cannot_skip_product_or_documentation_checks(self): for build, docs in ((False, True), (True, False), (False, False)): needs = self.needs(build, docs) diff --git a/tools/tests/test_ci_cache_prune.py b/tools/tests/test_ci_cache_prune.py new file mode 100644 index 00000000..eb81c61a --- /dev/null +++ b/tools/tests/test_ci_cache_prune.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Compiler-cache pruning preserves main warm starts and unrelated caches.""" +import importlib.util +import os +from pathlib import Path +import unittest +from unittest.mock import patch + + +spec = importlib.util.spec_from_file_location( + "ci_cache_prune", Path(__file__).parents[2] / "scripts/ci/cache-prune.py") +prune = importlib.util.module_from_spec(spec) +spec.loader.exec_module(prune) + + +def cache(id, *, role="build", ref=prune.MAIN, size=10, key=None, created=None, accessed=None): + return {"id": id, "key": key or f"ccache-v2-Linux-X64-{role}-{id}-1", "ref": ref, + "size_in_bytes": size, "created_at": created or f"2026-11-{id:02d}T00:00:00Z", + "last_accessed_at": accessed or created or f"2026-11-{id:02d}T00:00:00Z"} + + +class SelectionTests(unittest.TestCase): + def test_only_our_exact_snapshot_namespace_is_eligible(self): + untouched = [cache(1, key="ccache-v1-Linux-X64-1-1"), + cache(2, key="downloads-v1-Linux-X64-lock"), + cache(3, key="ccache-v2-unrecognized-key"), + cache(4, key="ccache-v2-Linux-X64-unknown-4-1")] + result = prune.plan(untouched + [cache(5), cache(6)], budget=0) + self.assertEqual(result["delete"], [5]) + self.assertEqual(result["protected"], [6]) + self.assertEqual(result["before"], 20) + + def test_newest_main_snapshot_is_protected_for_every_role_and_platform(self): + items = [cache(1), cache(2), cache(3, role="kernel"), cache(4, role="auth"), + cache(5, role="pages"), cache(6, key="ccache-v2-Linux-ARM64-build-6-1"), + cache(7, ref="refs/pull/123/merge")] + result = prune.plan(items, budget=0) + self.assertEqual(result["protected"], [2, 3, 4, 5, 6]) + self.assertEqual(result["delete"], [1, 7]) + self.assertEqual(result["remaining"], 50) + + def test_duplicate_limit_uses_creation_time_per_ref_and_role(self): + items = [cache(1), cache(2), cache(3), cache(4, ref="refs/pull/12/merge"), + cache(5, ref="refs/pull/12/merge"), cache(6, ref="refs/pull/12/merge"), + cache(7, role="kernel")] + result = prune.plan(items, budget=1000, keep=2) + self.assertEqual(result["delete"], [1, 4]) + self.assertEqual(result["protected"], [3, 7]) + self.assertEqual(result["remaining"], 50) + + def test_budget_uses_last_access_after_removing_duplicate_snapshots(self): + items = [cache(1), cache(2), cache(3), + cache(4, ref="refs/pull/12/merge", accessed="2026-11-09T00:00:00Z"), + cache(5, role="kernel", ref="refs/pull/13/merge", + accessed="2026-11-08T00:00:00Z")] + # 1 is an old duplicate, 2 has the oldest access, then 5 before 4. + self.assertEqual(prune.plan(items, budget=20)["delete"], [1, 2, 5]) + + def test_timezone_offsets_are_compared_as_instants(self): + items = [cache(1, created="2026-11-01T10:00:00+09:00"), + cache(2, created="2026-11-01T02:00:00Z")] + self.assertEqual(prune.plan(items, budget=0)["protected"], [2]) + + def test_repeated_pages_do_not_double_count_and_bad_metadata_fails_closed(self): + item = cache(1) + self.assertEqual(prune.plan([item, item])["before"], 10) + bad = dict(item, size_in_bytes=-1) + with self.assertRaises(ValueError): + prune.plan([bad]) + with self.assertRaises(ValueError): + prune.plan([item, dict(item, size_in_bytes=20)]) + with self.assertRaises(ValueError): + prune.plan([cache(1, created="2026-11-01T00:00:00")]) + with self.assertRaises(ValueError): + prune.plan([item], keep=0) + with self.assertRaises(ValueError): + prune.plan([item], budget=-1) + + +class ApiTests(unittest.TestCase): + def test_all_metadata_pages_are_read(self): + calls = [] + first = [cache(1)] * 100 + second = [cache(2)] + + def api(endpoint): + calls.append(endpoint) + return {"actions_caches": first if endpoint.endswith("page=1") else second} + + self.assertEqual(prune.list_caches("owner/repo", api), first + second) + self.assertEqual(calls, [ + "repos/owner/repo/actions/caches?key=ccache-v2-&per_page=100&page=1", + "repos/owner/repo/actions/caches?key=ccache-v2-&per_page=100&page=2"]) + + def test_default_cli_is_dry_run_and_main_only_apply_is_explicit(self): + with patch.object(prune, "list_caches", return_value=[cache(1), cache(2)]), \ + patch.object(prune.subprocess, "run") as delete, \ + patch.dict(os.environ, {}, clear=True): + self.assertEqual(prune.main(["--repo", "owner/repo", "--keep", "1"]), 0) + delete.assert_not_called() + with self.assertRaises(ValueError): + prune.main(["--repo", "owner/repo", "--apply"]) + + def test_apply_deletes_only_selected_ids_and_never_the_protected_snapshot(self): + environment = {"GITHUB_REF": prune.MAIN, "GITHUB_EVENT_NAME": "push", + "GITHUB_REPOSITORY": "owner/repo"} + with patch.object(prune, "list_caches", return_value=[cache(1), cache(2)]), \ + patch.object(prune.subprocess, "run") as delete, \ + patch.dict(os.environ, environment, clear=True): + self.assertEqual(prune.main(["--keep", "1", "--apply"]), 0) + delete.assert_called_once_with([ + "gh", "api", "repos/owner/repo/actions/caches/1", "--method", "DELETE"], check=True) + with self.assertRaises(ValueError): + prune.main(["--repo", "other/repo", "--apply"]) + os.environ["GITHUB_EVENT_NAME"] = "pull_request" + with self.assertRaises(ValueError): + prune.main(["--apply"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_ci_test_shards.py b/tools/tests/test_ci_test_shards.py new file mode 100644 index 00000000..b617aee1 --- /dev/null +++ b/tools/tests/test_ci_test_shards.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Exercise complete shard coverage and the production contract-test harness.""" +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +SELECTOR = ROOT / "tools/ci_test_shards.py" +spec = importlib.util.spec_from_file_location("ci_test_shards", SELECTOR) +shards = importlib.util.module_from_spec(spec) +spec.loader.exec_module(shards) + + +def make_inventory(root): + directory = root / "tests/build" + directory.mkdir(parents=True) + for name in (*sum(shards.OFFLOADED_TESTS.values(), ()), "test-core.sh"): + (directory / name).write_text("#!/bin/sh\nset -eu\nprintf '%s\\n' \"${0##*/}\" >> \"$OBSERVED\"\n") + return directory + + +class PartitionTests(unittest.TestCase): + def test_repository_inventory_is_covered_exactly_once(self): + groups = shards.partition(ROOT) + inventory = {path.name for path in (ROOT / "tests/build").glob("test-*.sh")} + combined = [name for group in shards.GROUPS[1:] for name in groups[group]] + self.assertEqual(set(combined), inventory) + self.assertEqual(len(combined), len(inventory)) + self.assertEqual(set(groups["all"]), inventory) + + def test_new_suites_automatically_join_core(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + directory = make_inventory(root) + (directory / "test-new-component.sh").touch() + groups = shards.partition(root) + self.assertEqual(groups["core"], ("test-core.sh", "test-new-component.sh")) + + def test_missing_or_renamed_explicit_suite_fails_closed(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + directory = make_inventory(root) + (directory / "test-pages.sh").rename(directory / "test-new-pages.sh") + with self.assertRaisesRegex(ValueError, "Missing build suite.*test-pages.sh"): + shards.partition(root) + + def test_duplicate_unknown_empty_and_unsafe_configuration_is_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + make_inventory(root) + mappings = [dict(shards.OFFLOADED_TESTS, extra=("test-core.sh",)), + dict(shards.OFFLOADED_TESTS, auth=()), + dict(shards.OFFLOADED_TESTS, auth=("test-pages.sh",)), + dict(shards.OFFLOADED_TESTS, pages=("../test-pages.sh",))] + for mapping in mappings: + with self.subTest(mapping=mapping), self.assertRaises(ValueError): + shards.partition(root, mapping) + + def test_unknown_cli_group_is_rejected(self): + result = subprocess.run([sys.executable, str(SELECTOR), "--group", "typo"], + capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + + def test_groups_json_matches_all_focused_groups_and_validates_inventory(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + directory = make_inventory(root) + arguments = [sys.executable, str(SELECTOR), "--root", str(root), "--groups-json"] + result = subprocess.run(arguments, capture_output=True, text=True, check=True) + self.assertEqual(json.loads(result.stdout), list(shards.OFFLOADED_TESTS)) + (directory / "test-pages.sh").unlink() + failed = subprocess.run(arguments, capture_output=True, text=True) + self.assertNotEqual(failed.returncode, 0) + self.assertEqual(failed.stdout, "") + + +class MakeShardTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.inventory = make_inventory(self.root) + tools = self.root / "tools" + tools.mkdir() + (tools / "ci_test_shards.py").write_bytes(SELECTOR.read_bytes()) + self.observed = self.root / "observed" + self.makefile = self.root / "Makefile" + self.makefile.write_text( + f"RELIEFOS_SRC := {self.root}\nO := {self.root}/out\nO_HOST := $(O)/host\n" + "RELIEFOS_LOG_SHELL = :\n" + f"include {ROOT}/scripts/reliefos/Makefile.tests\n" + "sdk rootfs-raw:\n\t@echo unexpected full image prerequisite >&2; exit 77\n" + "selection:\n\t@printf '%s\\n' $(notdir $(RELIEFOS_SELECTED_BUILD_TESTS))\n") + self.environment = {key: value for key, value in os.environ.items() + if key not in {"MAKEFLAGS", "MFLAGS", "MAKELEVEL", "MAKEOVERRIDES", + "RELIEFOS_CI_TEST_GROUP"}} + self.environment["OBSERVED"] = str(self.observed) + + def run_make(self, *arguments, check=True): + return subprocess.run(["make", "--no-print-directory", "-f", str(self.makefile), + "-j2", *arguments], cwd=self.root, env=self.environment, + capture_output=True, text=True, check=check) + + def test_default_selection_is_full_and_core_excludes_only_offloaded_suites(self): + default = self.run_make("selection").stdout.splitlines() + core = self.run_make("RELIEFOS_CI_TEST_GROUP=core", "selection").stdout.splitlines() + self.assertEqual(set(default), {path.name for path in self.inventory.glob("test-*.sh")}) + self.assertEqual(core, ["test-core.sh"]) + + def test_focused_targets_execute_their_exact_group_without_full_image_prerequisites(self): + for group in ("kernel", "auth", "pages"): + with self.subTest(group=group): + self.observed.unlink(missing_ok=True) + result = self.run_make("test-ci-" + group) + self.assertEqual(self.observed.read_text().splitlines(), sorted(shards.OFFLOADED_TESTS[group])) + self.assertIn("all 10 build suites are assigned exactly once", result.stdout) + + def test_invalid_group_and_missing_suite_fail_before_running_any_suite(self): + for value in ("typo", "core extra", ""): + with self.subTest(value=value): + result = self.run_make("RELIEFOS_CI_TEST_GROUP=" + value, "test-ci-kernel", check=False) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.observed.exists()) + (self.inventory / "test-auth-stage.sh").unlink() + result = self.run_make("test-ci-kernel", check=False) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Missing build suite", result.stderr) + self.assertFalse(self.observed.exists()) + + def test_focused_dry_query_touch_modes_do_not_execute_suites(self): + for option in ("-n", "-q", "-t"): + with self.subTest(option=option): + self.run_make(option, "test-ci-pages", check=False) + self.assertFalse(self.observed.exists()) + + def test_nonzero_exit_and_counted_failure_both_fail_focused_gate(self): + path = self.inventory / "test-pages.sh" + for script in ("#!/bin/sh\nexit 1\n", "#!/bin/sh\nprintf 'FAIL - counted failure\\n'\n"): + with self.subTest(script=script): + path.write_text(script) + result = self.run_make("test-ci-pages", check=False) + self.assertNotEqual(result.returncode, 0) + self.assertIn("reported a failure", result.stdout) + + def test_focused_submake_retains_jobserver(self): + child = self.root / "child.mk" + child.write_text("check:\n\t@printf '%s\\n' '$(MAKEFLAGS)' > \"$$OBSERVED\"\n") + (self.inventory / "test-auth-stage.sh").write_text( + f"#!/bin/sh\nset -eu\nmake --no-print-directory -f '{child}' check\n") + result = self.run_make("test-ci-auth") + self.assertNotIn("jobserver unavailable", result.stderr) + self.assertRegex(self.observed.read_text(), r"(?:^| )-j2(?: |$)") + + +if __name__ == "__main__": + unittest.main() From 04df3fa1a5477d2ad34a36d67e815b764b84bf36 Mon Sep 17 00:00:00 2001 From: LeonMMcoset Date: Mon, 23 Nov 2026 12:49:03 +0000 Subject: [PATCH 2/7] ci: tolerate cache snapshots already evicted by GitHub --- scripts/ci/cache-prune.py | 21 ++++++++++++-- tools/tests/test_ci_cache_prune.py | 45 +++++++++++++++++++++++++++--- 2 files changed, 59 insertions(+), 7 deletions(-) diff --git a/scripts/ci/cache-prune.py b/scripts/ci/cache-prune.py index 4fb59bac..405e8463 100644 --- a/scripts/ci/cache-prune.py +++ b/scripts/ci/cache-prune.py @@ -83,6 +83,23 @@ def list_caches(repository, api=gh_api): page += 1 +def delete_cache(repository, id): + """A cache evicted after listing is already in the requested absent state.""" + result = subprocess.run( + ["gh", "api", f"repos/{repository}/actions/caches/{id}", + "--method", "DELETE", "--include", "--silent"], capture_output=True, text=True) + if result.returncode == 0: + return + first_line = result.stdout.splitlines()[0] if result.stdout else "" + status = re.fullmatch(r"HTTP/\d+(?:\.\d+)? (\d{3})(?: .*)?", first_line) + if status is not None and status[1] == "404": + print(f"Cache {id} is already absent.") + return + if result.stderr: + print(result.stderr, file=sys.stderr, end="") + result.check_returncode() + + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY")) @@ -100,9 +117,7 @@ def main(argv=None): print(json.dumps(dict(result, apply=args.apply), sort_keys=True)) if args.apply: for id in result["delete"]: - # The delete endpoint returns an empty 204 response. - subprocess.run(["gh", "api", f"repos/{args.repo}/actions/caches/{id}", - "--method", "DELETE"], check=True) + delete_cache(args.repo, id) if result["remaining"] > args.budget_gib * GIB: print("Newest main snapshots exceed the budget; they remain protected.") return 0 diff --git a/tools/tests/test_ci_cache_prune.py b/tools/tests/test_ci_cache_prune.py index eb81c61a..dd6a3150 100644 --- a/tools/tests/test_ci_cache_prune.py +++ b/tools/tests/test_ci_cache_prune.py @@ -3,6 +3,7 @@ import importlib.util import os from pathlib import Path +import subprocess import unittest from unittest.mock import patch @@ -94,7 +95,7 @@ def api(endpoint): def test_default_cli_is_dry_run_and_main_only_apply_is_explicit(self): with patch.object(prune, "list_caches", return_value=[cache(1), cache(2)]), \ - patch.object(prune.subprocess, "run") as delete, \ + patch.object(prune, "delete_cache") as delete, \ patch.dict(os.environ, {}, clear=True): self.assertEqual(prune.main(["--repo", "owner/repo", "--keep", "1"]), 0) delete.assert_not_called() @@ -105,11 +106,10 @@ def test_apply_deletes_only_selected_ids_and_never_the_protected_snapshot(self): environment = {"GITHUB_REF": prune.MAIN, "GITHUB_EVENT_NAME": "push", "GITHUB_REPOSITORY": "owner/repo"} with patch.object(prune, "list_caches", return_value=[cache(1), cache(2)]), \ - patch.object(prune.subprocess, "run") as delete, \ + patch.object(prune, "delete_cache") as delete, \ patch.dict(os.environ, environment, clear=True): self.assertEqual(prune.main(["--keep", "1", "--apply"]), 0) - delete.assert_called_once_with([ - "gh", "api", "repos/owner/repo/actions/caches/1", "--method", "DELETE"], check=True) + delete.assert_called_once_with("owner/repo", 1) with self.assertRaises(ValueError): prune.main(["--repo", "other/repo", "--apply"]) os.environ["GITHUB_EVENT_NAME"] = "pull_request" @@ -117,5 +117,42 @@ def test_apply_deletes_only_selected_ids_and_never_the_protected_snapshot(self): prune.main(["--apply"]) +class DeletionTests(unittest.TestCase): + def result(self, status, *, stderr=""): + return subprocess.CompletedProcess( + ["gh", "api"], 0 if status == 204 else 1, + stdout=f"HTTP/2.0 {status} Response\nContent-Length: 0\n\n", stderr=stderr) + + def test_success_and_already_evicted_cache_both_succeed(self): + for status in (204, 404): + with self.subTest(status=status), \ + patch.object(prune.subprocess, "run", return_value=self.result(status)) as request: + prune.delete_cache("owner/repo", 1) + request.assert_called_once_with([ + "gh", "api", "repos/owner/repo/actions/caches/1", "--method", "DELETE", + "--include", "--silent"], capture_output=True, text=True) + + def test_auth_rate_limit_and_server_failures_are_preserved(self): + for status in (401, 403, 429, 500, 503): + with self.subTest(status=status), \ + patch.object(prune.subprocess, "run", return_value=self.result(status)), \ + self.assertRaises(subprocess.CalledProcessError) as error: + prune.delete_cache("owner/repo", 1) + self.assertIn(f"HTTP/2.0 {status}", error.exception.stdout) + + def test_failure_classification_uses_response_headers_not_stderr(self): + response = self.result(403, stderr="gh: requested cache 404 was forbidden\n") + with patch.object(prune.subprocess, "run", return_value=response), \ + patch.object(prune.sys.stderr, "write"), \ + self.assertRaises(subprocess.CalledProcessError): + prune.delete_cache("owner/repo", 1) + for stdout in ("", "404 Not Found\n", '{"message":"HTTP/2.0 404 Not Found"}'): + response = subprocess.CompletedProcess(["gh", "api"], 1, stdout=stdout, stderr="") + with self.subTest(stdout=stdout), \ + patch.object(prune.subprocess, "run", return_value=response), \ + self.assertRaises(subprocess.CalledProcessError): + prune.delete_cache("owner/repo", 1) + + if __name__ == "__main__": unittest.main() From 8bc7a64c12e8056cc5cd94260232165bbf5752ba Mon Sep 17 00:00:00 2001 From: LeonMMcoset Date: Mon, 23 Nov 2026 12:54:29 +0000 Subject: [PATCH 3/7] ci: install only the dependencies each regression group uses --- .github/CI.md | 2 + .github/actions/setup/action.yml | 6 +-- .github/workflows/ci.yml | 2 +- scripts/ci/install.sh | 14 ++++- tools/tests/test_ci_setup.py | 88 ++++++++++++++++++++++++++++++++ 5 files changed, 107 insertions(+), 5 deletions(-) create mode 100644 tools/tests/test_ci_setup.py diff --git a/.github/CI.md b/.github/CI.md index 496d7077..7523d51a 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -57,6 +57,8 @@ submodule rollback; `test-ci-auth` covers authentication staging; `test-ci-pages` covers complete site assembly. Each job has its own checkout and output tree and builds only its group's prerequisites. The final gate requires the product build, every regression group and both boot jobs. +Focused groups install the compiler, native tools and their specific test +dependencies; they do not install the product build's FFmpeg and GUI stack. `tools/ci_test_shards.py` owns the test partition and supplies the workflow matrix. It checks that each focused suite exists and belongs to exactly one diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index d95df110..f1c1233b 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -2,7 +2,7 @@ name: Prepare ReliefOS runner description: Install the shared build or boot-test environment on Ubuntu 24.04. inputs: profile: - description: Runner profile (build or smoke) + description: Runner profile (build, kernel, auth, pages or smoke) required: true runs: using: composite @@ -13,7 +13,7 @@ runs: SETUP_PROFILE: ${{ inputs.profile }} run: bash scripts/ci/install.sh "$SETUP_PROFILE" - name: Enable APK staging namespaces - if: inputs.profile == 'build' + if: inputs.profile != 'smoke' shell: bash run: | for setting in kernel.apparmor_restrict_unprivileged_userns kernel.unprivileged_userns_clone; do @@ -25,7 +25,7 @@ runs: done unshare -Ur true - name: Enable compiler cache - if: inputs.profile == 'build' + if: inputs.profile != 'smoke' shell: bash run: | sudo update-ccache-symlinks diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b4131c32..21d3e6aa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -249,7 +249,7 @@ jobs: persist-credentials: false - uses: ./.github/actions/setup with: - profile: build + profile: ${{ matrix.group }} - name: Restore locked dependency downloads id: download-cache uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3 diff --git a/scripts/ci/install.sh b/scripts/ci/install.sh index 7fbcee2a..8a9f0e6c 100644 --- a/scripts/ci/install.sh +++ b/scripts/ci/install.sh @@ -16,10 +16,22 @@ case "${1:-}" in libswresample-dev libswscale-dev ) ;; + kernel|auth|pages) + # Focused suites build native tools and disposable kernel/runtime fixtures; + # they do not launch guests or compile the desktop/media applications. + packages=( + build-essential clang libclang-rt-dev llvm lld ccache bison flex gperf gettext + git make perl libncurses-dev bc pkg-config autoconf automake libtool libtool-bin + gawk ncurses-bin texinfo curl file patch xz-utils openssl python3 libext2fs-dev + ) + if [[ "$1" == pages ]]; then + packages+=(python3-sphinx python3-pil) + fi + ;; smoke) packages=(qemu-system-x86 qemu-utils ovmf python3-pil tesseract-ocr) ;; - *) echo 'Usage: install.sh build|smoke' >&2; exit 2 ;; + *) echo 'Usage: install.sh build|kernel|auth|pages|smoke' >&2; exit 2 ;; esac sudo apt-get update diff --git a/tools/tests/test_ci_setup.py b/tools/tests/test_ci_setup.py new file mode 100644 index 00000000..67a476df --- /dev/null +++ b/tools/tests/test_ci_setup.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""CI setup installs the selected suite's dependencies without touching the host.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +INSTALL = ROOT / "scripts/ci/install.sh" + + +class SetupTests(unittest.TestCase): + def run_setup(self, *arguments, fail=None): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + log = directory / "calls.jsonl" + sudo = directory / "sudo" + sudo.write_text(f"#!{sys.executable}\n" + + "import json,os,sys\n" + "with open(os.environ['TEST_APT_LOG'],'a') as output:\n" + " output.write(json.dumps(sys.argv[1:])+'\\n')\n" + "if len(sys.argv)>2 and sys.argv[2]==os.environ.get('TEST_APT_FAIL'):\n" + " sys.exit(42)\n") + sudo.chmod(0o755) + environment = dict(os.environ, PATH=str(directory) + os.pathsep + os.environ["PATH"], + TEST_APT_LOG=str(log), TEST_APT_FAIL=fail or "") + result = subprocess.run(["bash", str(INSTALL), *arguments], capture_output=True, + text=True, env=environment, check=False) + calls = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + return result, calls + + def packages(self, profile): + result, calls = self.run_setup(profile) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(calls[0], ["apt-get", "update"]) + self.assertEqual(calls[1][:4], ["apt-get", "install", "--yes", "--no-install-recommends"]) + self.assertEqual(len(calls), 2) + packages = calls[1][4:] + self.assertEqual(len(packages), len(set(packages)), "duplicate install requests") + return set(packages) + + def test_focused_profiles_keep_compilers_native_tools_and_crypto(self): + required = {"build-essential", "clang", "libclang-rt-dev", "llvm", "lld", "ccache", + "bison", "flex", "gperf", "gettext", "git", "make", "libncurses-dev", + "pkg-config", "autoconf", "automake", "libtool", "libtool-bin", + "openssl", "python3", "libext2fs-dev"} + for profile in ("kernel", "auth", "pages"): + with self.subTest(profile=profile): + packages = self.packages(profile) + self.assertTrue(required <= packages, required - packages) + self.assertTrue(packages.isdisjoint({"ffmpeg", "libavformat-dev", "libavcodec-dev", + "qemu-system-x86", "qemu-utils", "ovmf", + "grub-common", "grub-pc-bin", "grub-efi-amd64-bin", + "xvfb", "libx11-dev"})) + + def test_only_pages_focused_profile_needs_sphinx(self): + self.assertTrue({"python3-sphinx", "python3-pil"} <= self.packages("pages")) + for profile in ("kernel", "auth"): + self.assertNotIn("python3-sphinx", self.packages(profile)) + + def test_full_build_and_smoke_keep_their_existing_runtime_requirements(self): + self.assertTrue({"ffmpeg", "libavformat-dev", "libavcodec-dev", "libavutil-dev", + "libswresample-dev", "libswscale-dev", "qemu-system-x86", "ovmf", + "grub-common", "xvfb", "python3-sphinx"} <= self.packages("build")) + self.assertEqual(self.packages("smoke"), + {"qemu-system-x86", "qemu-utils", "ovmf", "python3-pil", "tesseract-ocr"}) + + def test_invalid_profile_never_runs_package_manager(self): + for arguments in ((), ("unknown",), ("",)): + result, calls = self.run_setup(*arguments) + self.assertEqual(result.returncode, 2) + self.assertEqual(calls, []) + + def test_update_and_install_failures_propagate(self): + result, calls = self.run_setup("kernel", fail="update") + self.assertEqual(result.returncode, 42) + self.assertEqual(calls, [["apt-get", "update"]]) + result, calls = self.run_setup("pages", fail="install") + self.assertEqual(result.returncode, 42) + self.assertEqual(len(calls), 2) + + +if __name__ == "__main__": + unittest.main() From eb45ebc68c58a54adf8d1190aadd1d02c4588852 Mon Sep 17 00:00:00 2001 From: LeonMMcoset Date: Mon, 23 Nov 2026 13:07:41 +0000 Subject: [PATCH 4/7] ci: retain build doctor tools in the kernel regression environment --- .github/CI.md | 3 +++ scripts/ci/install.sh | 8 ++++++++ tools/tests/test_ci_setup.py | 11 +++++++++-- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/.github/CI.md b/.github/CI.md index 7523d51a..951cff5c 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -59,6 +59,9 @@ and output tree and builds only its group's prerequisites. The final gate requires the product build, every regression group and both boot jobs. Focused groups install the compiler, native tools and their specific test dependencies; they do not install the product build's FFmpeg and GUI stack. +The kernel group also installs image and boot tools because its concurrency +contract checks that the complete `make doctor` can run while a build holds +the output lock. `tools/ci_test_shards.py` owns the test partition and supplies the workflow matrix. It checks that each focused suite exists and belongs to exactly one diff --git a/scripts/ci/install.sh b/scripts/ci/install.sh index 8a9f0e6c..7be0a165 100644 --- a/scripts/ci/install.sh +++ b/scripts/ci/install.sh @@ -26,6 +26,14 @@ case "${1:-}" in ) if [[ "$1" == pages ]]; then packages+=(python3-sphinx python3-pil) + elif [[ "$1" == kernel ]]; then + # The concurrency suite verifies that the public, read-only `doctor` + # entry remains usable while another build owns the output directory. + # Its complete image/run checks need real tools even without guest boots. + packages+=( + e2fsprogs squashfs-tools dosfstools mtools xorriso qemu-utils qemu-system-x86 + grub-common fdisk fakeroot zip ovmf + ) fi ;; smoke) diff --git a/tools/tests/test_ci_setup.py b/tools/tests/test_ci_setup.py index 67a476df..af515aa0 100644 --- a/tools/tests/test_ci_setup.py +++ b/tools/tests/test_ci_setup.py @@ -53,10 +53,17 @@ def test_focused_profiles_keep_compilers_native_tools_and_crypto(self): packages = self.packages(profile) self.assertTrue(required <= packages, required - packages) self.assertTrue(packages.isdisjoint({"ffmpeg", "libavformat-dev", "libavcodec-dev", - "qemu-system-x86", "qemu-utils", "ovmf", - "grub-common", "grub-pc-bin", "grub-efi-amd64-bin", + "grub-pc-bin", "grub-efi-amd64-bin", "xvfb", "libx11-dev"})) + def test_kernel_profile_supports_the_full_doctor_contract(self): + image_tools = {"e2fsprogs", "squashfs-tools", "dosfstools", "mtools", "xorriso", + "qemu-utils", "qemu-system-x86", "grub-common", "fdisk", "fakeroot", + "zip", "ovmf"} + self.assertTrue(image_tools <= self.packages("kernel")) + for profile in ("auth", "pages"): + self.assertTrue(image_tools.isdisjoint(self.packages(profile))) + def test_only_pages_focused_profile_needs_sphinx(self): self.assertTrue({"python3-sphinx", "python3-pil"} <= self.packages("pages")) for profile in ("kernel", "auth"): From d9965a93a7b76d8773ed93d6fc4cd4576a314997 Mon Sep 17 00:00:00 2001 From: LeonMMcoset Date: Mon, 23 Nov 2026 13:20:56 +0000 Subject: [PATCH 5/7] ci: reject wildcard names in test group selection --- scripts/reliefos/Makefile.tests | 2 +- tools/tests/test_ci_test_shards.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/reliefos/Makefile.tests b/scripts/reliefos/Makefile.tests index cbb34585..92426e1e 100644 --- a/scripts/reliefos/Makefile.tests +++ b/scripts/reliefos/Makefile.tests @@ -28,7 +28,7 @@ RELIEFOS_CI_TEST_GROUP ?= all ifneq ($(words $(RELIEFOS_CI_TEST_GROUP)),1) $(error RELIEFOS_CI_TEST_GROUP must be all or core) endif -ifeq ($(filter $(RELIEFOS_CI_TEST_GROUP),all core),) +ifeq ($(filter all core,$(RELIEFOS_CI_TEST_GROUP)),) $(error RELIEFOS_CI_TEST_GROUP must be all or core; use test-ci-kernel/auth/pages for focused groups) endif RELIEFOS_CI_SELECTOR := $(RELIEFOS_SRC)/tools/ci_test_shards.py diff --git a/tools/tests/test_ci_test_shards.py b/tools/tests/test_ci_test_shards.py index b617aee1..4719b8aa 100644 --- a/tools/tests/test_ci_test_shards.py +++ b/tools/tests/test_ci_test_shards.py @@ -122,7 +122,7 @@ def test_focused_targets_execute_their_exact_group_without_full_image_prerequisi self.assertIn("all 10 build suites are assigned exactly once", result.stdout) def test_invalid_group_and_missing_suite_fail_before_running_any_suite(self): - for value in ("typo", "core extra", ""): + for value in ("typo", "core extra", "", "%"): with self.subTest(value=value): result = self.run_make("RELIEFOS_CI_TEST_GROUP=" + value, "test-ci-kernel", check=False) self.assertNotEqual(result.returncode, 0) From c75ad492d4017bb807e35fdab47b57d806e9280e Mon Sep 17 00:00:00 2001 From: LeonMMcoset Date: Mon, 23 Nov 2026 13:37:30 +0000 Subject: [PATCH 6/7] test(ci): observe installer startup without optional exec diagnostics --- tools/test_dual_boot_qemu.py | 27 ++++++++++----- tools/tests/test_ci_boot.py | 66 ++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 9 deletions(-) create mode 100644 tools/tests/test_ci_boot.py diff --git a/tools/test_dual_boot_qemu.py b/tools/test_dual_boot_qemu.py index 1ded30be..7b0fa9f6 100644 --- a/tools/test_dual_boot_qemu.py +++ b/tools/test_dual_boot_qemu.py @@ -194,6 +194,23 @@ def wait_xdm(probe, process, name, timeout, expected="login"): raise AssertionError(f"Missing XDM {expected} state; observed {observed}") +def wait_installer_language(probe, serial, process, timeout): + """Observe the actual wizard without depending on optional exec debug logs.""" + deadline, stable = time.monotonic() + timeout, 0 + while time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError("QEMU exited before the installer language page") + text = serial.read_text(errors="replace") if serial.exists() else "" + if "KERNEL PANIC" in text or "Kernel Panic" in text: + raise AssertionError("Kernel panic before the installer language page") + page = probe.visible_page(probe.frame("installer")) + stable = stable + 1 if page == 0 else 0 + if stable >= 2: + return + time.sleep(.5) + raise AssertionError("Installer language page did not appear") + + def boot_matrix(args, output): """Reach the kernel and corresponding user environment on each same media.""" results = [] @@ -209,15 +226,7 @@ def boot_matrix(args, output): wait_for(serial, process, lambda text: boot_evidence(text, firmware, args.expected_release, cpus=2), f"{name} kernel/PID1", args.timeout) if medium == "installer": - wait_for(serial, process, lambda text: "path=/usr/lib/reliefos/apps/installer/installer.elf" in text, - "installer executable", args.timeout) - deadline = time.monotonic() + args.timeout - while time.monotonic() < deadline: - if probe.visible_page(probe.frame("installer")) == 0: - break - time.sleep(.5) - else: - raise AssertionError("Installer language page did not appear") + wait_installer_language(probe, serial, process, args.timeout) else: wait_for(serial, process, lambda text: "VT graphics vt=1 enabled=1" in text, "graphical login", args.timeout) diff --git a/tools/tests/test_ci_boot.py b/tools/tests/test_ci_boot.py new file mode 100644 index 00000000..d8a2f867 --- /dev/null +++ b/tools/tests/test_ci_boot.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Boot acceptance observes the installer when exec diagnostics are disabled.""" +import importlib.util +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import Mock, patch + + +TOOLS = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("dual_boot_ci", TOOLS / "test_dual_boot_qemu.py") +boot = importlib.util.module_from_spec(spec) +# These waits need only the supplied probes. Keep the lightweight workflow +# checks independent of Pillow, QMP and a guest-image environment. +with patch.dict(sys.modules, {"test_installer_accounts_qemu": Mock(), + "test_vt_qemu": Mock()}): + spec.loader.exec_module(boot) + + +class InstallerBootTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.serial = Path(temporary.name) / "serial.log" + self.serial.write_text("[reliefnt] PID 1 path=/init\n[reliefnt] boot complete:\n") + self.probe = Mock() + self.process = Mock() + self.process.poll.return_value = None + + def wait(self): + with patch.object(boot.time, "monotonic", side_effect=(0, 0, 1, 2, 3, 5)), \ + patch.object(boot.time, "sleep"): + boot.wait_installer_language(self.probe, self.serial, self.process, 4) + + def test_two_fresh_language_frames_pass_without_exec_debug_log(self): + self.probe.visible_page.side_effect = (None, 0, None, 0, 0) + with patch.object(boot.time, "monotonic", side_effect=(0, 0, 1, 2, 3, 4)), \ + patch.object(boot.time, "sleep"): + boot.wait_installer_language(self.probe, self.serial, self.process, 5) + self.assertEqual(self.probe.frame.call_count, 5) + self.assertNotIn("installer.elf", self.serial.read_text()) + + def test_exec_log_alone_or_wrong_page_cannot_pass(self): + self.serial.write_text("path=/usr/lib/reliefos/apps/installer/installer.elf\n") + for page in (None, 1, 10): + with self.subTest(page=page): + self.probe.visible_page.side_effect = None + self.probe.visible_page.return_value = page + with self.assertRaisesRegex(AssertionError, "language page did not appear"): + self.wait() + + def test_process_exit_or_kernel_panic_fails_even_if_page_is_visible(self): + self.probe.visible_page.return_value = 0 + self.process.poll.return_value = 1 + with self.assertRaisesRegex(RuntimeError, "QEMU exited"): + self.wait() + self.process.poll.return_value = None + for message in ("KERNEL PANIC", "Kernel Panic"): + self.serial.write_text(message) + with self.assertRaisesRegex(AssertionError, "Kernel panic"): + self.wait() + + +if __name__ == "__main__": + unittest.main() From 34766499665dbd5da27f49b3279e076d819d3b18 Mon Sep 17 00:00:00 2001 From: LeonMMcoset Date: Mon, 23 Nov 2026 13:49:22 +0000 Subject: [PATCH 7/7] fix(ci): defer core selection for unrelated Make goals --- scripts/reliefos/Makefile.tests | 4 +++- tools/tests/test_ci_test_shards.py | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/scripts/reliefos/Makefile.tests b/scripts/reliefos/Makefile.tests index 92426e1e..65eb739e 100644 --- a/scripts/reliefos/Makefile.tests +++ b/scripts/reliefos/Makefile.tests @@ -37,7 +37,9 @@ $(eval reliefos_ci_selected := $(shell $(RELIEFOS_TEST_PYTHON) '$(RELIEFOS_CI_SE endef RELIEFOS_SELECTED_BUILD_TESTS := $(RELIEFOS_BUILD_TESTS) ifeq ($(RELIEFOS_CI_TEST_GROUP),core) -RELIEFOS_SELECTED_BUILD_TESTS := $(call RELIEFOS_CI_SELECT_TESTS,core) +# Select only when the contract-test recipe needs the inventory. Other goals +# may forward a guest/kernel Python path that is not a host interpreter. +RELIEFOS_SELECTED_BUILD_TESTS = $(call RELIEFOS_CI_SELECT_TESTS,core) endif ifneq ($(filter test-ci-kernel test-ci-auth test-ci-pages test-ci-validate,$(MAKECMDGOALS)),) # Validate while parsing, before any expensive prerequisite can start. diff --git a/tools/tests/test_ci_test_shards.py b/tools/tests/test_ci_test_shards.py index 4719b8aa..23c74481 100644 --- a/tools/tests/test_ci_test_shards.py +++ b/tools/tests/test_ci_test_shards.py @@ -96,6 +96,7 @@ def setUp(self): "RELIEFOS_LOG_SHELL = :\n" f"include {ROOT}/scripts/reliefos/Makefile.tests\n" "sdk rootfs-raw:\n\t@echo unexpected full image prerequisite >&2; exit 77\n" + "unrelated:\n\t@echo unrelated goal passed\n" "selection:\n\t@printf '%s\\n' $(notdir $(RELIEFOS_SELECTED_BUILD_TESTS))\n") self.environment = {key: value for key, value in os.environ.items() if key not in {"MAKEFLAGS", "MFLAGS", "MAKELEVEL", "MAKEOVERRIDES", @@ -113,6 +114,12 @@ def test_default_selection_is_full_and_core_excludes_only_offloaded_suites(self) self.assertEqual(set(default), {path.name for path in self.inventory.glob("test-*.sh")}) self.assertEqual(core, ["test-core.sh"]) + def test_core_selection_does_not_require_host_python_for_unrelated_goals(self): + result = self.run_make("RELIEFOS_CI_TEST_GROUP=core", + "RELIEFOS_TEST_PYTHON=/selected/kernel-python", "unrelated") + self.assertIn("unrelated goal passed", result.stdout) + self.assertNotIn("not found", result.stderr) + def test_focused_targets_execute_their_exact_group_without_full_image_prerequisites(self): for group in ("kernel", "auth", "pages"): with self.subTest(group=group):