diff --git a/.github/scripts/build-query-regression-helpers.sh b/.github/scripts/build-query-regression-helpers.sh new file mode 100644 index 00000000000..6b6cdb6fcde --- /dev/null +++ b/.github/scripts/build-query-regression-helpers.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail +: "${CARGO_TARGET_DIR:?CARGO_TARGET_DIR must be configured by the runner}" +revision="$(git rev-parse HEAD)" +tag="query-regression-helpers:${revision}" +staging="$(mktemp -d)" +trap 'rm -rf -- "$staging"' EXIT +cargo build --profile nightly -p cmd --features dev-tools \ + --bin query_perf_fixture --bin query_regression_runner +for binary in query_perf_fixture query_regression_runner; do + "$CARGO_TARGET_DIR/nightly/$binary" --help >/dev/null + cp "$CARGO_TARGET_DIR/nightly/$binary" "$staging/$binary" +done +mkdir -p helpers-image helpers-validation +docker build --provenance=false --build-arg "SOURCE_REVISION=$revision" \ + --file docker/query-regression-helpers/Dockerfile --tag "$tag" "$staging" +container="$(docker create "$tag" /query_perf_fixture --help)" +trap 'docker rm --force --volumes "$container"; rm -rf -- "$staging"' EXIT +mkdir -p "$staging/extracted" +for binary in query_perf_fixture query_regression_runner; do + docker cp "$container:/$binary" "$staging/extracted/$binary" + chmod +x "$staging/extracted/$binary" + "$staging/extracted/$binary" --help >/dev/null + cmp "$staging/$binary" "$staging/extracted/$binary" +done +# Hold the revision and cases constant: compare source-built versus extracted +# fixture normalization twice. Keep the raw outputs as workflow artifacts. +printf '%s\n' "$revision" > helpers-validation/source-revision.txt +for iteration in 1 2; do + while IFS= read -r case; do + name="$(basename "$(dirname "$case")")" + for mode in source image; do + binary="$staging/query_perf_fixture" + [[ "$mode" != image ]] || binary="$staging/extracted/query_perf_fixture" + "$binary" plan --case "$case" > "helpers-validation/${name}-${iteration}-${mode}.json" + done + cmp "helpers-validation/${name}-${iteration}-source.json" \ + "helpers-validation/${name}-${iteration}-image.json" + done < <(find tests/perf/query_cases -name case.toml -type f | sort) +done +(cd "$staging" && sha256sum query_perf_fixture query_regression_runner) > helpers-image/SHA256SUMS +printf '%s\n' "$revision" > helpers-image/source-revision.txt +docker save "$tag" --output helpers-image/image.tar diff --git a/.github/scripts/publish-query-regression-helpers.sh b/.github/scripts/publish-query-regression-helpers.sh index 83d9d15e0fa..b867455f498 100644 --- a/.github/scripts/publish-query-regression-helpers.sh +++ b/.github/scripts/publish-query-regression-helpers.sh @@ -1,56 +1,28 @@ #!/usr/bin/env bash set -euo pipefail -: "${CARGO_TARGET_DIR:?CARGO_TARGET_DIR must be configured by the runner}" -revision="$(git rev-parse HEAD)" repository=greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/query-regression-helpers -# A rerun gets a distinct tag; consumers always use the registry digest. +revision="$(cat helpers-image/source-revision.txt)" +[[ "$revision" == "$GITHUB_SHA" ]] tag="${repository}:${revision}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" -staging="$(mktemp -d)" -trap 'rm -rf -- "$staging"' EXIT -cargo build --profile nightly -p cmd --features dev-tools \ - --bin query_perf_fixture --bin query_regression_runner -for binary in query_perf_fixture query_regression_runner; do - "$CARGO_TARGET_DIR/nightly/$binary" --help >/dev/null - cp "$CARGO_TARGET_DIR/nightly/$binary" "$staging/$binary" -done -docker build --build-arg "SOURCE_REVISION=$revision" \ - --file docker/query-regression-helpers/Dockerfile --tag "$tag" "$staging" -# ACR token exchange can time out even after docker login succeeds. Retry -# publication without rebuilding the binaries or changing the image tag. -for attempt in 1 2 3; do - if timeout 600 docker push "$tag"; then - break - fi - if [[ "$attempt" == 3 ]]; then - echo "Helper image push failed after $attempt attempts." >&2 - exit 1 - fi - echo "Helper image push failed (attempt $attempt/3); retrying in 15 seconds." >&2 - sleep 15 -done -image="$(docker image inspect "$tag" --format '{{index .RepoDigests 0}}')" -[[ "$image" == "$repository@sha256:"* ]] -# Verify the published artifact through the same extraction path as consumers. -python3 .github/scripts/query-regression-helpers.py "$image" "$staging/extracted" -for binary in query_perf_fixture query_regression_runner; do - cmp "$staging/$binary" "$staging/extracted/$binary" -done -# Hold the revision and cases constant: compare source-built versus extracted -# fixture normalization twice. Keep the raw outputs as workflow artifacts. +# Match release-dev-builder-images.yaml: publish ACR images with Skopeo from +# a hosted runner. A failed publish can reuse the completed build artifact. mkdir -p helpers-validation -printf '%s\n' "$revision" > helpers-validation/source-revision.txt -printf '%s\n' "$image" > helpers-validation/image.txt -for iteration in 1 2; do - while IFS= read -r case; do - name="$(basename "$(dirname "$case")")" - for mode in source image; do - binary="$staging/query_perf_fixture" - [[ "$mode" != image ]] || binary="$staging/extracted/query_perf_fixture" - "$binary" plan --case "$case" > "helpers-validation/${name}-${iteration}-${mode}.json" - done - cmp "helpers-validation/${name}-${iteration}-source.json" \ - "helpers-validation/${name}-${iteration}-image.json" - done < <(find tests/perf/query_cases -name case.toml -type f | sort) -done +docker run --rm \ + -v "${DOCKER_CONFIG:-$HOME/.docker}:/root/.docker:ro" \ + -v "$PWD/helpers-image:/image:ro" \ + -v "$PWD/helpers-validation:/result" \ + -e REGISTRY_AUTH_FILE=/root/.docker/config.json \ + quay.io/skopeo/stable:latest --command-timeout 20m copy --retry-times 3 \ + --digestfile /result/digest.txt \ + docker-archive:/image/image.tar "docker://$tag" +digest="$(cat helpers-validation/digest.txt)" +[[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] +image="$repository@$digest" +# The ECS build tested these exact bytes. Verify them again from the registry; +# hosted runners need not share the ECS runtime library versions. +python3 .github/scripts/query-regression-helpers.py "$image" helpers-validation/extracted \ + --checksums helpers-image/SHA256SUMS +jq -e --arg revision "$revision" '.source_revision == $revision' \ + helpers-validation/extracted/helpers-image.json >/dev/null printf 'image=%s\n' "$image" >> "$GITHUB_OUTPUT" printf 'Published helpers: `%s` (source `%s`)\n' "$image" "$revision" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/scripts/query-regression-helpers.py b/.github/scripts/query-regression-helpers.py index f2e13f6516e..8e25c9f840c 100644 --- a/.github/scripts/query-regression-helpers.py +++ b/.github/scripts/query-regression-helpers.py @@ -16,6 +16,7 @@ """Extract digest-pinned query regression tools from an artifact image.""" import argparse +import hashlib import json import re import subprocess @@ -37,7 +38,13 @@ def run(*args): return subprocess.check_output(args, text=True).strip() -def extract(image, destination): +def extract(image, destination, checksums=None): + expected = None + if checksums is not None: + entries = [line.split() for line in checksums.read_text().splitlines()] + expected = {name: digest for digest, name in entries} + if set(expected) != set(BINARIES) or len(entries) != len(BINARIES): + raise ValueError("Checksums must contain exactly the two helper binaries") image = resolve_image(image) destination.mkdir(parents=True, exist_ok=True) run("docker", "pull", image) @@ -51,7 +58,13 @@ def extract(image, destination): target = destination / binary run("docker", "cp", f"{container}:/{binary}", str(target)) target.chmod(0o755) - run(str(target.resolve()), "--help") + if expected is None: + run(str(target.resolve()), "--help") + else: + with target.open("rb") as file: + actual = hashlib.file_digest(file, "sha256").hexdigest() + if actual != expected[binary]: + raise ValueError(f"Published helper checksum mismatch: {binary}") finally: run("docker", "rm", "--force", "--volumes", container) provenance = {"image": image, "image_id": metadata["Id"], "source_revision": revision} @@ -64,5 +77,6 @@ if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image") parser.add_argument("destination", type=Path) + parser.add_argument("--checksums", type=Path, help="Verify build checksums instead of executing on this host") args = parser.parse_args() - extract(args.image, args.destination) + extract(args.image, args.destination, args.checksums) diff --git a/.github/scripts/update-query-regression-helpers-image.sh b/.github/scripts/update-query-regression-helpers-image.sh index 41fdd9d751b..230c0d0b8c4 100644 --- a/.github/scripts/update-query-regression-helpers-image.sh +++ b/.github/scripts/update-query-regression-helpers-image.sh @@ -29,7 +29,7 @@ ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID} ## What's changed and what's your intention? Update the query-regression helper image to \`$HELPERS_IMAGE\`, built from \`$GITHUB_SHA\`. -The publishing job extracted both binaries from the published digest, ran their help commands, and checked that they matched the build outputs. +The ECS build smoke-tested both packaged binaries and compared fixture plans. The publishing job extracted both binaries from the published digest and verified their SHA-256 checksums against those build outputs. Runs opting into \`helpers_image: pinned\` use this version after merge. Source-build defaults are unchanged. ## PR Checklist diff --git a/.github/workflows/publish-query-regression-helpers.yml b/.github/workflows/publish-query-regression-helpers.yml index 536ff0d8996..e899fcb8ae3 100644 --- a/.github/workflows/publish-query-regression-helpers.yml +++ b/.github/workflows/publish-query-regression-helpers.yml @@ -13,6 +13,7 @@ on: - docker/query-regression-helpers/** - .github/workflows/publish-query-regression-helpers.yml - .github/scripts/publish-query-regression-helpers.sh + - .github/scripts/build-query-regression-helpers.sh - Cargo.lock permissions: @@ -60,12 +61,10 @@ jobs: runner-uid: ${{ vars.QUERY_REGRESSION_RUNNER_UID || '1001' }} runner-gid: ${{ vars.QUERY_REGRESSION_RUNNER_GID || '1001' }} - publish: + build: needs: provision runs-on: ${{ needs.provision.outputs.label }} timeout-minutes: 150 - outputs: - image: ${{ steps.publish.outputs.image }} env: CARGO_HOME: /home/runner/.cargo CARGO_TARGET_DIR: /home/runner/query-regression-target @@ -78,21 +77,55 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false + - name: Build and validate helpers + run: bash .github/scripts/build-query-regression-helpers.sh + - name: Upload reusable helper image + uses: actions/upload-artifact@v4 + with: + name: helpers-image + path: helpers-image/ + compression-level: 1 + retention-days: 7 + if-no-files-found: error + - name: Upload build validation evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: helpers-build-validation + path: helpers-validation/ + if-no-files-found: warn + + publish: + needs: build + runs-on: ubuntu-latest + timeout-minutes: 45 + outputs: + image: ${{ steps.publish.outputs.image }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + name: helpers-image + path: helpers-image/ - name: Login to registry uses: docker/login-action@v3 with: registry: greptime-registry.cn-hangzhou.cr.aliyuncs.com username: ${{ secrets.ALICLOUD_USERNAME }} password: ${{ secrets.ALICLOUD_PASSWORD }} - - name: Build, verify and publish helpers + - name: Publish and verify helpers id: publish run: bash .github/scripts/publish-query-regression-helpers.sh - - name: Upload helper validation evidence + - name: Upload publication validation evidence if: always() uses: actions/upload-artifact@v4 with: - name: helpers-validation - path: helpers-validation/ + name: helpers-publish-validation + path: | + helpers-validation/digest.txt + helpers-validation/extracted/helpers-image.json if-no-files-found: warn update-pin: @@ -110,7 +143,7 @@ jobs: teardown: if: ${{ always() && needs.provision.outputs.instance_id != '' }} - needs: [provision, publish] + needs: [provision, build] runs-on: ubuntu-latest timeout-minutes: 15 steps: diff --git a/tests/perf/README.md b/tests/perf/README.md index 09df31c284a..fc4e326d7e9 100644 --- a/tests/perf/README.md +++ b/tests/perf/README.md @@ -644,3 +644,12 @@ for the first time (the initial pin is deliberately empty). No mutable `latest` tag is consumed and publication alone does not change the version used by runs. The existing **Release builder images** workflow can also invoke publication via `release_query_regression_helpers_image`, including for initial branch testing. + +Helper publication separates the ECS build from the hosted registry upload. +The ECS job smoke-tests the packaged binaries and compares fixture plans twice, +then retains the image archive and binary checksums as `helpers-image` for seven +days. The hosted job uses Skopeo (as in builder-image publishing), reads back the +published digest, and checks both binaries against those checksums. If upload +fails, rerun failed jobs to reuse the completed build artifact without compiling +again. Runtime compatibility is checked on ECS; the hosted publishing job only +compares bytes because its system libraries can differ. diff --git a/tests/perf/test_query_regression_helpers.py b/tests/perf/test_query_regression_helpers.py index 9810c9f4366..06a6acb2750 100644 --- a/tests/perf/test_query_regression_helpers.py +++ b/tests/perf/test_query_regression_helpers.py @@ -15,6 +15,7 @@ """Checks for helper image extraction and unchanged source-build defaults.""" +import hashlib import importlib.util import json import subprocess @@ -83,31 +84,44 @@ class HelpersTest(unittest.TestCase): helpers.extract(IMAGE, Path(tmp)) self.assertEqual(run.call_count, 2) - def test_publish_retries_same_tag_and_stops_after_three_failures(self): - import os - script = (ROOT / ".github/scripts/publish-query-regression-helpers.sh").read_text() - retry = script.split("for attempt in 1 2 3; do", 1)[1].split('image="', 1)[0] - retry = "set -euo pipefail\ntag=registry/helpers:revision\nfor attempt in 1 2 3; do" + retry - for failures in (0, 1, 3): - with self.subTest(failures=failures), tempfile.TemporaryDirectory() as tmp: + def test_published_checksums_and_mismatch_cleanup(self): + for valid in (True, False): + with self.subTest(valid=valid), tempfile.TemporaryDirectory() as tmp: root = Path(tmp) - docker = root / "docker" - docker.write_text("""#!/bin/sh -printf '%s\\n' "$*" >> "$PUSH_LOG" -attempt=$(wc -l < "$PUSH_LOG") -[ "$attempt" -gt "$FAILURES" ] -""") - docker.chmod(0o755) - sleep = root / "sleep" - sleep.write_text("#!/bin/sh\nexit 0\n") - sleep.chmod(0o755) - log = root / "pushes" - env = dict(os.environ, PATH=tmp + os.pathsep + os.environ["PATH"], - PUSH_LOG=str(log), FAILURES=str(failures)) - result = subprocess.run(["bash", "-c", retry], env=env, capture_output=True) - self.assertEqual(result.returncode, 1 if failures == 3 else 0) - self.assertEqual(log.read_text().splitlines(), - ["push registry/helpers:revision"] * min(failures + 1, 3)) + checksum = hashlib.sha256(b"binary" if valid else b"wrong").hexdigest() + checksums = root / "SHA256SUMS" + checksums.write_text("".join(f"{checksum} {name}\n" for name in helpers.BINARIES)) + calls = [] + + def run(*args): + calls.append(args) + if args[:3] == ("docker", "image", "inspect"): + return json.dumps([{"Id": "sha256:image", "Config": {"Labels": { + "org.opencontainers.image.revision": REVISION}}}]) + if args[:2] == ("docker", "create"): + return "container" + if args[:2] == ("docker", "cp"): + Path(args[-1]).write_bytes(b"binary") + return "" + + with patch.object(helpers, "run", side_effect=run): + if valid: + helpers.extract(IMAGE, root / "bins", checksums) + else: + with self.assertRaisesRegex(ValueError, "checksum mismatch"): + helpers.extract(IMAGE, root / "bins", checksums) + self.assertFalse((root / "bins/helpers-image.json").exists()) + self.assertTrue(all(call[0] == "docker" for call in calls)) + self.assertEqual(calls[-1], ("docker", "rm", "--force", "--volumes", "container")) + + def test_checksum_manifest_requires_both_helpers(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + checksums = root / "SHA256SUMS" + checksums.write_text("0" * 64 + " query_perf_fixture\n") + with patch.object(helpers, "run") as run, self.assertRaises(ValueError): + helpers.extract(IMAGE, root, checksums) + run.assert_not_called() def test_candidate_build_matrix(self): # Execute the actual workflow shell with recorder commands. Changing