Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
ci(cua-perception): anchor missed release tags and read a 404 as missing (#4206)
Francesco Bonacci7bba3546fcf6
diff --git a/.github/scripts/anchor_perception_release_tag.sh b/.github/scripts/anchor_perception_release_tag.shnew file mode 100755index 0000000000..f037d60b6f--- /dev/null+++ b/.github/scripts/anchor_perception_release_tag.sh@@ -0,0 +1,141 @@+#!/usr/bin/env bash+# Anchor the merged Cua Perception version with a lightweight tag on main.+#+# Runs on every push to main from release-please.yml with the release app+# token, so the tag push starts `cd-cua-perception.yml`. When a push changes+# VERSION, the pushed commit is tagged. When VERSION is unchanged but its tag+# is missing (a previous anchor run failed), the commit that last set VERSION+# on main's first-parent history is tagged instead, so a missed tag heals on+# the next push without anyone creating it by hand.+#+# Inputs (environment): GITHUB_REPOSITORY, GITHUB_SHA, BEFORE_SHA, VERSION_PATH,+# GH_TOKEN (used by gh). Optional: RELEASE_VERSION_VALIDATOR, the command that+# validates checked-in versions (defaults to validate_release_versions.py).+set -euo pipefail++: "${GITHUB_REPOSITORY:?}" "${GITHUB_SHA:?}" "${BEFORE_SHA:?}" "${VERSION_PATH:?}"+VALIDATOR="${RELEASE_VERSION_VALIDATOR:-python3 .github/scripts/validate_release_versions.py --product perception}"++git checkout --quiet --detach "$GITHUB_SHA"++if [[ "$BEFORE_SHA" =~ ^0+$ ]]; then+ echo "Skipping Perception tag creation for the initial branch push"+ exit 0+fi+if ! git merge-base --is-ancestor "$BEFORE_SHA" "$GITHUB_SHA"; then+ echo "::error::Refusing to create a release tag for a non-fast-forward main push"+ exit 1+fi++read_version() {+ git show "$1:$VERSION_PATH" 2>/dev/null | tr -d '[:space:]' || true+}++require_increase() {+ local previous="$1" current="$2"+ python3 - "$previous" "$current" <<'PY'+import re+import sys++semver = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")+previous, current = sys.argv[1:]+previous_match = semver.fullmatch(previous)+current_match = semver.fullmatch(current)+if not previous_match or not current_match:+ raise SystemExit("Perception versions must be stable SemVer")+if tuple(map(int, current_match.groups())) <= tuple(map(int, previous_match.groups())):+ raise SystemExit(+ f"Perception version must increase: previous={previous}, current={current}"+ )+PY+}++BEFORE_VERSION=$(read_version "$BEFORE_SHA")+VERSION=$(read_version "$GITHUB_SHA")+if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ echo "::error::Refusing to tag invalid Perception version: $VERSION"+ exit 1+fi+TAG="cua-perception-v$VERSION"++# Print "<type>\t<sha>" for an existing tag, nothing when it does not exist,+# and fail on any other error. gh prints the error body on stdout for a 404,+# so the exit status and body are checked explicitly instead of trusting+# non-empty output.+read_remote_tag() {+ local body status=0+ body=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" 2>/dev/null) || status=$?+ if [[ "$status" -eq 0 ]]; then+ jq -r '[.object.type, .object.sha] | @tsv' <<<"$body"+ return 0+ fi+ if jq -e '.status == "404" or .message == "Not Found"' <<<"$body" >/dev/null 2>&1; then+ return 0+ fi+ echo "::error::Could not read $TAG (gh exit $status)" >&2+ return 1+}++require_exact_lightweight_tag() {+ local tag_record="$1" expected_sha="$2"+ local tag_type tag_sha+ IFS=$'\t' read -r tag_type tag_sha <<<"$tag_record"+ if [[ "$tag_type" != "commit" || "$tag_sha" != "$expected_sha" ]]; then+ echo "::error::$TAG already exists but is not a lightweight tag at $expected_sha"+ exit 1+ fi+}++EXISTING=$(read_remote_tag)+if [[ "$BEFORE_VERSION" == "$VERSION" ]]; then+ if [[ -n "$EXISTING" ]]; then+ echo "Perception version did not change in this main push and $TAG exists"+ exit 0+ fi+ TARGET_SHA=$(git log --first-parent -1 --format=%H "$GITHUB_SHA" -- "$VERSION_PATH")+ if [[ -z "$TARGET_SHA" ]]; then+ echo "::error::No main commit sets $VERSION_PATH to $VERSION"+ exit 1+ fi+ if [[ "$(read_version "$TARGET_SHA")" != "$VERSION" ]]; then+ echo "::error::$TARGET_SHA does not set Perception $VERSION"+ exit 1+ fi+ PARENT_VERSION=$(read_version "$TARGET_SHA^")+ if [[ -n "$PARENT_VERSION" ]]; then+ require_increase "$PARENT_VERSION" "$VERSION"+ fi+ echo "::warning::$TAG is missing; anchoring the commit that set VERSION ($TARGET_SHA)"+else+ $VALIDATOR+ if [[ -n "$BEFORE_VERSION" ]]; then+ require_increase "$BEFORE_VERSION" "$VERSION"+ fi+ TARGET_SHA="$GITHUB_SHA"+fi++git fetch --quiet origin "+refs/heads/main:refs/remotes/origin/main"+if ! git merge-base --is-ancestor "$TARGET_SHA" origin/main; then+ echo "::error::Refusing to tag a commit outside main"+ exit 1+fi++if [[ -n "$EXISTING" ]]; then+ require_exact_lightweight_tag "$EXISTING" "$TARGET_SHA"+ echo "$TAG already points to the merged Perception version"+ exit 0+fi++if ! gh api --method POST "repos/$GITHUB_REPOSITORY/git/refs" \+ -f ref="refs/tags/$TAG" \+ -f sha="$TARGET_SHA" >/dev/null; then+ # A concurrent run may have created the same immutable anchor.+ EXISTING=$(read_remote_tag)+ if [[ -z "$EXISTING" ]]; then+ echo "::error::Failed to create $TAG"+ exit 1+ fi+ require_exact_lightweight_tag "$EXISTING" "$TARGET_SHA"+fi+require_exact_lightweight_tag "$(read_remote_tag)" "$TARGET_SHA"+echo "Created $TAG at $TARGET_SHA"diff --git a/.github/scripts/tests/test_anchor_perception_release_tag.py b/.github/scripts/tests/test_anchor_perception_release_tag.pynew file mode 100644index 0000000000..b75b548c44--- /dev/null+++ b/.github/scripts/tests/test_anchor_perception_release_tag.py@@ -0,0 +1,187 @@+"""Behavioral tests for anchor_perception_release_tag.sh with a fake gh."""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import textwrap+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[3]+SCRIPT = ROOT / ".github/scripts/anchor_perception_release_tag.sh"+VERSION_PATH = "libs/cua-driver/rust/crates/cua-perception/VERSION"+REPOSITORY = "trycua/cua"++# The fake gh keeps remote tags in a JSON file. Like the real gh, a GET for a+# missing ref prints the 404 error body on stdout and exits nonzero.+FAKE_GH = textwrap.dedent(+ """\+ #!{python}+ import json, os, pathlib, sys++ store = pathlib.Path(os.environ["FAKE_GH_TAGS"])+ tags = json.loads(store.read_text()) if store.exists() else {{}}+ args = sys.argv[1:]+ with open(os.environ["FAKE_GH_LOG"], "a") as log:+ log.write(json.dumps(args) + "\\n")+ if os.environ.get("FAKE_GH_MODE") == "server-error" and "--method" not in args:+ print(json.dumps({{"message": "Server Error", "status": "500"}}))+ print("gh: Server Error (HTTP 500)", file=sys.stderr)+ raise SystemExit(1)+ if args[0] != "api":+ raise SystemExit(2)+ if "--method" in args:+ fields = dict(value.split("=", 1) for flag, value in zip(args, args[1:]) if flag == "-f")+ name = fields["ref"].removeprefix("refs/tags/")+ if name in tags:+ print(json.dumps({{"message": "Reference already exists", "status": "422"}}))+ raise SystemExit(1)+ tags[name] = {{"type": "commit", "sha": fields["sha"]}}+ store.write_text(json.dumps(tags))+ print(json.dumps({{"ref": fields["ref"]}}))+ raise SystemExit(0)+ path = args[1]+ name = path.split("/git/ref/tags/", 1)[1]+ if name not in tags:+ print(json.dumps({{"message": "Not Found", "status": "404"}}))+ print("gh: Not Found (HTTP 404)", file=sys.stderr)+ raise SystemExit(1)+ print(json.dumps({{"ref": "refs/tags/" + name, "object": tags[name]}}))+ """+)+++def git(repo: Path, *args: str) -> str:+ return subprocess.run(+ ["git", *args], cwd=repo, check=True, capture_output=True, text=True+ ).stdout.strip()+++def commit_version(repo: Path, version: str | None, message: str) -> str:+ path = repo / VERSION_PATH+ path.parent.mkdir(parents=True, exist_ok=True)+ if version is None:+ (repo / "other.txt").write_text(message)+ else:+ path.write_text(version + "\n")+ git(repo, "add", "-A")+ git(repo, "commit", "-q", "-m", message)+ return git(repo, "rev-parse", "HEAD")+++def env(tmp_path: Path) -> dict[str, object]:+ if shutil.which("jq") is None:+ pytest.skip("jq is required")+ origin = tmp_path / "origin.git"+ repo = tmp_path / "repo"+ subprocess.run(["git", "init", "-q", "--bare", "-b", "main", str(origin)], check=True)+ subprocess.run(["git", "init", "-q", "-b", "main", str(repo)], check=True)+ git(repo, "config", "user.email", "[email protected]")+ git(repo, "config", "user.name", "Test")+ git(repo, "remote", "add", "origin", str(origin))+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ fake = bin_dir / "gh"+ fake.write_text(FAKE_GH.format(python=sys.executable))+ fake.chmod(0o755)+ return {"repo": repo, "bin": bin_dir, "tags": tmp_path / "tags.json", "log": tmp_path / "gh.log"}+++def run_anchor(env: dict[str, object], before: str, sha: str, **extra: str) -> subprocess.CompletedProcess[str]:+ repo = env["repo"]+ git(repo, "push", "-q", "origin", f"{sha}:refs/heads/main", "--force")+ environment = dict(os.environ)+ environment.update({+ "PATH": f"{env['bin']}{os.pathsep}{environment['PATH']}",+ "GITHUB_REPOSITORY": REPOSITORY,+ "GITHUB_SHA": sha,+ "BEFORE_SHA": before,+ "VERSION_PATH": VERSION_PATH,+ "FAKE_GH_TAGS": str(env["tags"]),+ "FAKE_GH_LOG": str(env["log"]),+ "RELEASE_VERSION_VALIDATOR": "true",+ **extra,+ })+ return subprocess.run(+ ["bash", str(SCRIPT)], cwd=repo, env=environment, capture_output=True, text=True+ )+++def tags(env: dict[str, object]) -> dict[str, dict[str, str]]:+ path = env["tags"]+ return json.loads(path.read_text()) if path.exists() else {}+++def test_version_bump_creates_a_lightweight_tag_despite_the_404_body(env) -> None:+ first = commit_version(env["repo"], "0.2.0", "v0.2.0")+ env["tags"].write_text(json.dumps({"cua-perception-v0.2.0": {"type": "commit", "sha": first}}))+ bump = commit_version(env["repo"], "0.2.1", "release 0.2.1")+ result = run_anchor(env, first, bump)+ assert result.returncode == 0, result.stdout + result.stderr+ assert tags(env)["cua-perception-v0.2.1"] == {"type": "commit", "sha": bump}+++def test_missing_tag_heals_on_a_later_push_at_the_commit_that_set_version(env) -> None:+ first = commit_version(env["repo"], "0.2.0", "v0.2.0")+ bump = commit_version(env["repo"], "0.2.1", "release 0.2.1")+ later = commit_version(env["repo"], None, "unrelated fix")+ result = run_anchor(env, bump, later)+ assert result.returncode == 0, result.stdout + result.stderr+ assert tags(env)["cua-perception-v0.2.1"] == {"type": "commit", "sha": bump}+ assert "anchoring the commit that set VERSION" in result.stdout+ del first+++def test_unchanged_version_with_existing_tag_is_a_no_op(env) -> None:+ bump = commit_version(env["repo"], "0.2.1", "release 0.2.1")+ env["tags"].write_text(json.dumps({"cua-perception-v0.2.1": {"type": "commit", "sha": bump}}))+ later = commit_version(env["repo"], None, "unrelated fix")+ result = run_anchor(env, bump, later)+ assert result.returncode == 0, result.stdout + result.stderr+ posts = [line for line in env["log"].read_text().splitlines() if "--method" in line]+ assert posts == []+++def test_existing_tag_elsewhere_is_refused(env) -> None:+ first = commit_version(env["repo"], "0.2.0", "v0.2.0")+ bump = commit_version(env["repo"], "0.2.1", "release 0.2.1")+ env["tags"].write_text(json.dumps({"cua-perception-v0.2.1": {"type": "commit", "sha": first}}))+ result = run_anchor(env, first, bump)+ assert result.returncode == 1+ assert "is not a lightweight tag" in result.stdout+++def test_annotated_tag_is_refused(env) -> None:+ first = commit_version(env["repo"], "0.2.0", "v0.2.0")+ bump = commit_version(env["repo"], "0.2.1", "release 0.2.1")+ env["tags"].write_text(json.dumps({"cua-perception-v0.2.1": {"type": "tag", "sha": bump}}))+ assert run_anchor(env, first, bump).returncode == 1+++def test_version_decrease_is_refused(env) -> None:+ first = commit_version(env["repo"], "0.2.1", "v0.2.1")+ lower = commit_version(env["repo"], "0.2.0", "downgrade")+ result = run_anchor(env, first, lower)+ assert result.returncode == 1+ assert tags(env) == {}+++def test_other_gh_errors_fail_closed(env) -> None:+ first = commit_version(env["repo"], "0.2.0", "v0.2.0")+ bump = commit_version(env["repo"], "0.2.1", "release 0.2.1")+ result = run_anchor(env, first, bump, FAKE_GH_MODE="server-error")+ assert result.returncode != 0+ assert tags(env) == {}+++def test_initial_push_is_skipped(env) -> None:+ first = commit_version(env["repo"], "0.2.0", "v0.2.0")+ result = run_anchor(env, "0" * 40, first)+ assert result.returncode == 0+ assert tags(env) == {}diff --git a/.github/scripts/tests/test_cua_perception_release_workflow.py b/.github/scripts/tests/test_cua_perception_release_workflow.pyindex ad1469bdb0..b0ce6fa211 100644--- a/.github/scripts/tests/test_cua_perception_release_workflow.py+++ b/.github/scripts/tests/test_cua_perception_release_workflow.py@@ -46,7 +46,9 @@ def test_release_please_keeps_creating_the_lightweight_anchor_tag() -> None:package = config["packages"]["libs/cua-driver/rust/crates/cua-perception"]assert package["skip-github-release"] is Truerelease_please = (ROOT / ".github/workflows/release-please.yml").read_text()- assert 'TAG="cua-perception-v$VERSION"' in release_please+ anchor = (ROOT / ".github/scripts/anchor_perception_release_tag.sh").read_text()+ assert "run: bash .github/scripts/anchor_perception_release_tag.sh" in release_please+ assert 'TAG="cua-perception-v$VERSION"' in anchor# The anchor uses the release app token so the tag push triggers this workflow.assert "GH_TOKEN: ${{ steps.app-token.outputs.token }}" in release_pleasediff --git a/.github/scripts/tests/test_cua_perception_release_workflows.py b/.github/scripts/tests/test_cua_perception_release_workflows.pyindex d74bfbfcf7..ad3a3f23b6 100644--- a/.github/scripts/tests/test_cua_perception_release_workflows.py+++ b/.github/scripts/tests/test_cua_perception_release_workflows.py@@ -36,13 +36,17 @@ def test_release_pr_sync_uses_crate_metadata_and_updates_the_lockfile() -> None:assert "jq -r '.[\\\".\\\"]'" not in source+ANCHOR_SCRIPT = ROOT / ".github/scripts/anchor_perception_release_tag.sh"++def test_candidate_tag_is_exact_lightweight_main_anchor_without_a_release() -> None:_, workflow = load_workflow(RELEASE_WORKFLOW)steps = workflow["jobs"]["release-please"]["steps"]tag_step = step(workflow, "Anchor a merged Perception version with a lightweight tag")- script = tag_step["run"]+ assert tag_step["run"] == "bash .github/scripts/anchor_perception_release_tag.sh"+ script = ANCHOR_SCRIPT.read_text()tag_index = steps.index(tag_step)for release_step in (@@ -62,13 +66,13 @@ def test_candidate_tag_is_exact_lightweight_main_anchor_without_a_release() -> Nassert tag_step["env"]["VERSION_PATH"] == VERSION_PATHassert "validate_release_versions.py --product perception" in scriptassert 'git merge-base --is-ancestor "$BEFORE_SHA" "$GITHUB_SHA"' in script- assert 'git merge-base --is-ancestor "$GITHUB_SHA" origin/main' in script+ assert 'git merge-base --is-ancestor "$TARGET_SHA" origin/main' in scriptassert "Perception version must increase" in scriptassert 'TAG="cua-perception-v$VERSION"' in scriptassert 'tag_type" != "commit"' in script- assert 'tag_sha" != "$GITHUB_SHA"' in script+ assert 'tag_sha" != "$expected_sha"' in scriptassert '-f ref="refs/tags/$TAG"' in script- assert '-f sha="$GITHUB_SHA"' in script+ assert '-f sha="$TARGET_SHA"' in scriptassert "--method PATCH" not in scriptassert "gh release" not in scriptassert "/releases" not in scriptdiff --git a/.github/workflows/ci-cua-perception-release.yml b/.github/workflows/ci-cua-perception-release.ymlindex c6644a5ab2..f69bad9e1a 100644--- a/.github/workflows/ci-cua-perception-release.yml+++ b/.github/workflows/ci-cua-perception-release.yml@@ -5,6 +5,8 @@ on:paths:- ".github/releases/**"- ".github/scripts/perception_release.py"+ - ".github/scripts/anchor_perception_release_tag.sh"+ - ".github/scripts/tests/test_anchor_perception_release_tag.py"- ".github/scripts/perception_release_install_check.py"- ".github/scripts/tests/test_cua_perception_release_workflow.py"- ".github/scripts/tests/test_perception_release_install_check.py"@@ -27,6 +29,8 @@ on:paths:- ".github/releases/**"- ".github/scripts/perception_release.py"+ - ".github/scripts/anchor_perception_release_tag.sh"+ - ".github/scripts/tests/test_anchor_perception_release_tag.py"- ".github/scripts/perception_release_install_check.py"- ".github/scripts/tests/test_cua_perception_release_workflow.py"- ".github/scripts/tests/test_perception_release_install_check.py"@@ -93,6 +97,8 @@ jobs:.github/scripts/tests/test_cua_driver_default_distribution.py \.github/scripts/tests/test_cua_perception_release_topology.py \.github/scripts/tests/test_cua_perception_release_workflow.py \+ .github/scripts/tests/test_anchor_perception_release_tag.py \+ .github/scripts/tests/test_cua_perception_release_workflows.py \.github/scripts/tests/test_perception_release_install_check.py \.github/scripts/tests/test_verify_cua_driver_release_archives.py \.github/scripts/tests/test_release_channels.py \diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.ymlindex a5d8332530..87a2106852 100644--- a/.github/workflows/release-please.yml+++ b/.github/workflows/release-please.yml@@ -86,87 +86,9 @@ jobs:GH_TOKEN: ${{ steps.app-token.outputs.token }}BEFORE_SHA: ${{ github.event.before }}VERSION_PATH: libs/cua-driver/rust/crates/cua-perception/VERSION- run: |- set -euo pipefail- git checkout --detach "$GITHUB_SHA"-- if [[ "$BEFORE_SHA" =~ ^0+$ ]]; then- echo "Skipping Perception tag creation for the initial branch push"- exit 0- fi- if ! git merge-base --is-ancestor "$BEFORE_SHA" "$GITHUB_SHA"; then- echo "::error::Refusing to create a release tag for a non-fast-forward main push"- exit 1- fi- BEFORE_VERSION=$(git show "$BEFORE_SHA:$VERSION_PATH" 2>/dev/null | tr -d '[:space:]' || true)- VERSION=$(tr -d '[:space:]' < "$VERSION_PATH")- if [[ "$BEFORE_VERSION" == "$VERSION" ]]; then- echo "Perception version did not change in this main push"- exit 0- fi-- python3 .github/scripts/validate_release_versions.py --product perception- if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then- echo "::error::Refusing to tag invalid Perception version: $VERSION"- exit 1- fi- if [[ -n "$BEFORE_VERSION" ]]; then- python3 - "$BEFORE_VERSION" "$VERSION" <<'PY'- import re- import sys-- semver = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")- previous, current = sys.argv[1:]- previous_match = semver.fullmatch(previous)- current_match = semver.fullmatch(current)- if not previous_match or not current_match:- raise SystemExit("Perception versions must be stable SemVer")- if tuple(map(int, current_match.groups())) <= tuple(map(int, previous_match.groups())):- raise SystemExit(- f"Perception version must increase: previous={previous}, current={current}"- )- PY- fi- git fetch origin "+refs/heads/main:refs/remotes/origin/main"- if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then- echo "::error::Refusing to tag a commit outside main"- exit 1- fi-- TAG="cua-perception-v$VERSION"- read_remote_tag() {- gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" \- --jq '[.object.type, .object.sha] | @tsv' 2>/dev/null || true- }- require_exact_lightweight_tag() {- local tag_record="$1"- local tag_type tag_sha- IFS=$'\t' read -r tag_type tag_sha <<<"$tag_record"- if [[ "$tag_type" != "commit" || "$tag_sha" != "$GITHUB_SHA" ]]; then- echo "::error::$TAG already exists but is not a lightweight tag at $GITHUB_SHA"- exit 1- fi- }-- EXISTING=$(read_remote_tag)- if [[ -n "$EXISTING" ]]; then- require_exact_lightweight_tag "$EXISTING"- echo "$TAG already points to the merged Perception version"- exit 0- fi-- if ! gh api --method POST "repos/$GITHUB_REPOSITORY/git/refs" \- -f ref="refs/tags/$TAG" \- -f sha="$GITHUB_SHA" >/dev/null; then- # A concurrent run may have created the same immutable anchor.- EXISTING=$(read_remote_tag)- if [[ -z "$EXISTING" ]]; then- echo "::error::Failed to create $TAG"- exit 1- fi- require_exact_lightweight_tag "$EXISTING"- fi- require_exact_lightweight_tag "$(read_remote_tag)"+ # The tag push starts cd-cua-perception.yml, which publishes the+ # release. A missed tag heals on the next main push.+ run: bash .github/scripts/anchor_perception_release_tag.sh# release-please-action v4.4.1, embedding release-please 17.3.0.- name: Open or update automatic release pull requests