diff --git a/.github/query-regression-helpers-image.txt b/.github/query-regression-helpers-image.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/.github/scripts/publish-query-regression-helpers.sh b/.github/scripts/publish-query-regression-helpers.sh new file mode 100644 index 00000000000..1a02be233d9 --- /dev/null +++ b/.github/scripts/publish-query-regression-helpers.sh @@ -0,0 +1,44 @@ +#!/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. +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" +docker push "$tag" +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. +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 +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 new file mode 100644 index 00000000000..f2e13f6516e --- /dev/null +++ b/.github/scripts/query-regression-helpers.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Extract digest-pinned query regression tools from an artifact image.""" + +import argparse +import json +import re +import subprocess +from pathlib import Path + +BINARIES = ("query_perf_fixture", "query_regression_runner") +PIN = Path(__file__).resolve().parents[1] / "query-regression-helpers-image.txt" + + +def resolve_image(value, pin=PIN): + if value == "pinned": + value = pin.read_text().strip() + if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._/:@-]*@sha256:[0-9a-f]{64}", value): + raise ValueError("helpers_image requires an image@sha256 digest; publish and merge the pin-update PR before using 'pinned'") + return value + + +def run(*args): + return subprocess.check_output(args, text=True).strip() + + +def extract(image, destination): + image = resolve_image(image) + destination.mkdir(parents=True, exist_ok=True) + run("docker", "pull", image) + metadata = json.loads(run("docker", "image", "inspect", image))[0] + revision = (metadata.get("Config", {}).get("Labels") or {}).get("org.opencontainers.image.revision", "") + if not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError("Helper image is missing its source revision label") + container = run("docker", "create", image, "/query_perf_fixture", "--help") + try: + for binary in BINARIES: + target = destination / binary + run("docker", "cp", f"{container}:/{binary}", str(target)) + target.chmod(0o755) + run(str(target.resolve()), "--help") + finally: + run("docker", "rm", "--force", "--volumes", container) + provenance = {"image": image, "image_id": metadata["Id"], "source_revision": revision} + (destination / "helpers-image.json").write_text(json.dumps(provenance, indent=2) + "\n") + print(json.dumps(provenance)) + return provenance + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("image") + parser.add_argument("destination", type=Path) + args = parser.parse_args() + extract(args.image, args.destination) diff --git a/.github/scripts/update-query-regression-helpers-image.sh b/.github/scripts/update-query-regression-helpers-image.sh new file mode 100644 index 00000000000..41fdd9d751b --- /dev/null +++ b/.github/scripts/update-query-regression-helpers-image.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail +: "${HELPERS_IMAGE:?Published image digest is required}" +repository=greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/query-regression-helpers +[[ "$HELPERS_IMAGE" =~ ^${repository}@sha256:[0-9a-f]{64}$ ]] +branch="ci/update-query-regression-helpers-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" +git config user.name greptimedb-ci +git config user.email greptimedb-ci@greptime.com +git fetch origin main +git checkout -b "$branch" origin/main +pin=.github/query-regression-helpers-image.txt +printf '%s\n' "$HELPERS_IMAGE" > "$pin" +git add "$pin" +if git diff --cached --quiet; then + echo 'Helper image pin is already current.' + exit 0 +fi +git commit -s -m 'ci(query-regression): update precompiled helpers image' +git push origin "HEAD:refs/heads/$branch" +body="$(mktemp)" +trap 'rm -f -- "$body"' EXIT +cat > "$body" <&2 exit 1 fi - if [[ -n "${BASE_IMAGE}" || -n "${CANDIDATE_IMAGE}" ]]; then + if [[ -n "${BASE_IMAGE}" || -n "${CANDIDATE_IMAGE}" || -n "${HELPERS_IMAGE}" ]]; then docker info >/dev/null fi @@ -451,6 +463,7 @@ jobs: > "${GITHUB_WORKSPACE}/query-regression-trusted-scripts/query-regression-summary.py" - name: Verify runner image tools + if: ${{ inputs.base_image == '' || inputs.candidate_image == '' || inputs.helpers_image == '' }} shell: bash run: | set -euo pipefail @@ -567,6 +580,7 @@ jobs: fi - name: Prepare query regression cache + if: ${{ inputs.base_image == '' || inputs.candidate_image == '' || inputs.helpers_image == '' }} shell: bash working-directory: src run: | @@ -762,7 +776,16 @@ jobs: git reset --hard "${VERIFIED_CANDIDATE_SHA}" git clean -ffdx + - name: Extract precompiled query regression helpers + if: ${{ inputs.helpers_image != '' }} + working-directory: src + run: | + python3 .github/scripts/query-regression-helpers.py "$HELPERS_IMAGE" \ + "$GITHUB_WORKSPACE/query-regression-bins/candidate" + cat "$GITHUB_WORKSPACE/query-regression-bins/candidate/helpers-image.json" >> "$GITHUB_STEP_SUMMARY" + - name: Build candidate greptime and query regression helpers + if: ${{ inputs.candidate_image == '' || inputs.helpers_image == '' }} working-directory: src run: | set -euo pipefail @@ -770,8 +793,10 @@ jobs: if [[ -z "${CANDIDATE_IMAGE}" ]]; then cargo build --profile "${CARGO_PROFILE}" -p cmd --bin greptime fi - cargo build --profile "${CARGO_PROFILE}" -p cmd --bin query_perf_fixture --features dev-tools - cargo build --profile "${CARGO_PROFILE}" -p cmd --bin query_regression_runner --features dev-tools + if [[ -z "${HELPERS_IMAGE}" ]]; then + cargo build --profile "${CARGO_PROFILE}" -p cmd --bin query_perf_fixture --features dev-tools + cargo build --profile "${CARGO_PROFILE}" -p cmd --bin query_regression_runner --features dev-tools + fi candidate_build_elapsed="${SECONDS}" printf 'Candidate greptime and query regression helper cargo builds elapsed: %s seconds\n' "${candidate_build_elapsed}" printf -- '- Candidate greptime and query regression helper cargo builds: %s seconds\n' "${candidate_build_elapsed}" >> "${GITHUB_STEP_SUMMARY}" @@ -785,10 +810,12 @@ jobs: cp "${CARGO_TARGET_DIR}/${target_dir}/greptime" \ "${GITHUB_WORKSPACE}/query-regression-bins/candidate/greptime" fi - cp "${CARGO_TARGET_DIR}/${target_dir}/query_perf_fixture" \ - "${GITHUB_WORKSPACE}/query-regression-bins/candidate/query_perf_fixture" - cp "${CARGO_TARGET_DIR}/${target_dir}/query_regression_runner" \ - "${GITHUB_WORKSPACE}/query-regression-bins/candidate/query_regression_runner" + if [[ -z "${HELPERS_IMAGE}" ]]; then + cp "${CARGO_TARGET_DIR}/${target_dir}/query_perf_fixture" \ + "${GITHUB_WORKSPACE}/query-regression-bins/candidate/query_perf_fixture" + cp "${CARGO_TARGET_DIR}/${target_dir}/query_regression_runner" \ + "${GITHUB_WORKSPACE}/query-regression-bins/candidate/query_regression_runner" + fi - name: Run query regression id: run @@ -830,6 +857,7 @@ jobs: query-regression-work/**/logs/** query-regression-work/**/otelgen/** query-regression-summary.md + query-regression-bins/candidate/helpers-image.json machine-telemetry.log if-no-files-found: warn retention-days: 7 diff --git a/.github/workflows/release-dev-builder-images.yaml b/.github/workflows/release-dev-builder-images.yaml index 2e1041c1ff4..6d1eaf2ea6b 100644 --- a/.github/workflows/release-dev-builder-images.yaml +++ b/.github/workflows/release-dev-builder-images.yaml @@ -35,6 +35,11 @@ on: description: Rebuild the query-regression ECS runner image (and update QUERY_REGRESSION_ECS_IMAGE_ID + RUNNER_IMAGE_EPOCH) required: false default: false + release_query_regression_helpers_image: + type: boolean + description: Publish precompiled query regression helpers and open a pin-update PR + required: false + default: false update_dev_builder_image_tag: type: boolean description: Update the DEV_BUILDER_IMAGE_TAG in Makefile and create a PR @@ -451,3 +456,8 @@ jobs: echo "## Lockstep updates" >> "$GITHUB_STEP_SUMMARY" echo "- QUERY_REGRESSION_ECS_IMAGE_ID → \`${image_id}\`" >> "$GITHUB_STEP_SUMMARY" echo "- RUNNER_IMAGE_EPOCH → \`${new_epoch}\` (PR on \`${BRANCH}\`, pending review/merge)" >> "$GITHUB_STEP_SUMMARY" + + release-query-regression-helpers: + if: ${{ github.repository == 'GreptimeTeam/greptimedb' && inputs.release_query_regression_helpers_image }} + uses: ./.github/workflows/publish-query-regression-helpers.yml + secrets: inherit diff --git a/docker/query-regression-helpers/Dockerfile b/docker/query-regression-helpers/Dockerfile new file mode 100644 index 00000000000..d1a93171695 --- /dev/null +++ b/docker/query-regression-helpers/Dockerfile @@ -0,0 +1,7 @@ +# Artifact image: binaries run on the query-regression ECS host after extraction. +# Build on the same ECS image as the consumer to preserve the runtime ABI. +FROM scratch +ARG SOURCE_REVISION +LABEL org.opencontainers.image.source="https://github.com/GreptimeTeam/greptimedb" +LABEL org.opencontainers.image.revision=$SOURCE_REVISION +COPY query_perf_fixture query_regression_runner / diff --git a/tests/perf/README.md b/tests/perf/README.md index 97e27a964a2..09df31c284a 100644 --- a/tests/perf/README.md +++ b/tests/perf/README.md @@ -615,3 +615,32 @@ Additional SQL optimizer cases: `LIMIT`. - `sql_join_filter_order`: two direct-SST tables joined on a shared tag with time filters, aggregate ordering, and `LIMIT`. + +### Precompiled query-regression helpers + +`helpers_image` is optional in Query Regression (dispatch and reusable calls). +The empty default still builds both helpers from the candidate source. Set it to +`pinned` to use `.github/query-regression-helpers-image.txt`, or provide an explicit +`image@sha256:...` reference. With both database image inputs and a helper image, +the run skips all Cargo builds and build-cache preparation. PR comment admission +continues to require source builds. + +The helper image is an artifact image containing `query_perf_fixture` and +`query_regression_runner`. They are extracted and run on the host, so their child +processes can use the same database launchers and paths. Images are built on the +query-regression ECS runner; alternate runner hosts must have compatible Linux +x86_64 libraries. Extraction smoke-tests both executables and fails without a +source-build fallback. `helpers-image.json` in the report artifact records the +image digest, image ID, and source revision. Case files and orchestration still +come from the candidate ref; choose a compatible helper revision when changing +the case DSL. + +The **Publish query regression helpers** workflow builds and pushes to +`greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/query-regression-helpers`. +It runs manually or on main when helper sources, packaging, or Cargo.lock change. +After verifying the published digest, it opens a draft PR updating the pin, like +the runner-image update workflow. Review and merge that PR before using `pinned` +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. diff --git a/tests/perf/test_query_regression_helpers.py b/tests/perf/test_query_regression_helpers.py new file mode 100644 index 00000000000..ef4a8637565 --- /dev/null +++ b/tests/perf/test_query_regression_helpers.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Checks for helper image extraction and unchanged source-build defaults.""" + +import importlib.util +import json +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location("helpers", ROOT / ".github/scripts/query-regression-helpers.py") +helpers = importlib.util.module_from_spec(spec) +spec.loader.exec_module(helpers) +IMAGE = "registry/tools/helpers@sha256:" + "a" * 64 +REVISION = "b" * 40 + + +class HelpersTest(unittest.TestCase): + def test_pin_and_digest_validation(self): + with tempfile.TemporaryDirectory() as tmp: + pin = Path(tmp) / "pin" + pin.write_text(IMAGE + "\n") + self.assertEqual(helpers.resolve_image("pinned", pin), IMAGE) + for value in ("", "registry/helpers:latest", IMAGE + "\nmalicious", "--help"): + with self.subTest(value=value), self.assertRaises(ValueError): + helpers.resolve_image(value) + pin.write_text("") + with self.assertRaises(ValueError): + helpers.resolve_image("pinned", pin) + + def test_extraction_provenance_and_cleanup_on_failure(self): + for fail in (False, True): + with self.subTest(fail=fail), tempfile.TemporaryDirectory() as tmp: + destination = Path(tmp) + 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"): + if fail: + raise subprocess.CalledProcessError(1, args) + Path(args[-1]).write_bytes(b"binary") + return "" + + with patch.object(helpers, "run", side_effect=run): + if fail: + with self.assertRaises(subprocess.CalledProcessError): + helpers.extract(IMAGE, destination) + self.assertFalse((destination / "helpers-image.json").exists()) + else: + self.assertEqual(helpers.extract(IMAGE, destination), { + "image": IMAGE, "image_id": "sha256:image", "source_revision": REVISION}) + for binary in helpers.BINARIES: + self.assertIn((str(destination / binary), "--help"), calls) + self.assertEqual(calls[-1], ("docker", "rm", "--force", "--volumes", "container")) + + def test_missing_revision_fails_before_container_creation(self): + with tempfile.TemporaryDirectory() as tmp, patch.object( + helpers, "run", side_effect=["", '[{"Config": {}}]'] + ) as run: + with self.assertRaises(ValueError): + helpers.extract(IMAGE, Path(tmp)) + self.assertEqual(run.call_count, 2) + + def test_candidate_build_matrix(self): + # Execute the actual workflow shell with recorder commands. Changing + # only image inputs must preserve source defaults and skip opted-in builds. + import os + workflow = (ROOT / ".github/workflows/query-regression.yml").read_text() + step = workflow.split(" - name: Build candidate greptime and query regression helpers\n", 1)[1] + step = step.split(" - name:", 1)[0].split(" run: |\n", 1)[1] + script = "\n".join(line[10:] for line in step.splitlines()) + for candidate in ("", "server-image" ): + for image in ("", IMAGE): + with self.subTest(candidate=candidate, helpers=image), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + log = root / "commands" + for command in ("cargo", "cp", "sccache"): + path = root / command + path.write_text('#!/bin/sh\nprintf "%s\\n" "' + command + ' $*" >> "$COMMAND_LOG"\n') + path.chmod(0o755) + env = dict(os.environ, PATH=tmp + os.pathsep + os.environ["PATH"], + COMMAND_LOG=str(log), CANDIDATE_IMAGE=candidate, HELPERS_IMAGE=image, + CARGO_PROFILE="nightly", CARGO_TARGET_DIR=str(root / "target"), + GITHUB_WORKSPACE=tmp, GITHUB_STEP_SUMMARY=str(root / "summary")) + subprocess.run(["bash", "-c", script], env=env, check=True, capture_output=True) + builds = [line for line in log.read_text().splitlines() if line.startswith("cargo ")] + expected = ([] if candidate else ["greptime"]) + ([] if image else list(helpers.BINARIES)) + self.assertEqual([line.split("--bin ")[1].split()[0] for line in builds], expected) + + +if __name__ == "__main__": + unittest.main()