:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): fix sandbox agent smoke image handoff and retries (#106811)
Alessandro Pogliaghi771bd3d7004f
diff --git a/.github/actions/wait-for-check/action.yml b/.github/actions/wait-for-check/action.ymlindex d0bed7950a5a..7be2d3e859ac 100644--- a/.github/actions/wait-for-check/action.yml+++ b/.github/actions/wait-for-check/action.yml@@ -22,6 +22,9 @@ inputs:required: falsedefault: '30'outputs:+ details-url:+ description: 'URL of the completed check run'+ value: ${{ steps.poll.outputs.details-url }}conclusion:description: >-Conclusion of the completed check (success, failure, cancelled, ...).@@ -49,6 +52,7 @@ runs:fi# A transient API error must not fail the wait — log it and retry# until the deadline. Callers decide what a timed_out conclusion means.+ check=""conclusion=""while [ "$SECONDS" -lt "$TIMEOUT_SECONDS" ]; do# Server-side check_name filtering narrows the response; the jq@@ -60,14 +64,16 @@ runs:# workflow run), so take the newest run (check run IDs are# monotonic) and report it only once it completes — an older# completed run must not mask a newer one still in flight.- if conclusion=$(gh api -X GET "repos/${GITHUB_REPOSITORY}/commits/${REF}/check-runs" \+ if check=$(gh api -X GET "repos/${GITHUB_REPOSITORY}/commits/${REF}/check-runs" \-f check_name="$CHECK_NAME" -f filter=latest \- --jq '[.check_runs[] | select(.name == env.CHECK_NAME and .app.slug == "github-actions")] | max_by(.id) | select(.status == "completed") | .conclusion // empty'); then+ --jq '[.check_runs[] | select(.name == env.CHECK_NAME and .app.slug == "github-actions")] | max_by(.id) | select(.status == "completed") | {conclusion, details_url}'); then+ conclusion=$(jq -r '.conclusion // empty' <<< "$check")if [ -n "$conclusion" ]; thenbreakfiecho "Check \"$CHECK_NAME\" has not completed yet; retrying in ${INTERVAL_SECONDS}s..."else+ check=""conclusion=""echo "GitHub API error while looking up check \"$CHECK_NAME\"; retrying in ${INTERVAL_SECONDS}s..."fi@@ -80,3 +86,4 @@ runs:conclusion="${conclusion:-timed_out}"echo "Check \"$CHECK_NAME\" conclusion: $conclusion"echo "conclusion=$conclusion" >> "$GITHUB_OUTPUT"+ echo "details-url=$(jq -r '.details_url // empty' <<< "$check")" >> "$GITHUB_OUTPUT"diff --git a/.github/scripts/test_sandbox_agent_release.py b/.github/scripts/test_sandbox_agent_release.pynew file mode 100644index 000000000000..f6f8b9b30740--- /dev/null+++ b/.github/scripts/test_sandbox_agent_release.py@@ -0,0 +1,217 @@+import os+import json+import subprocess+from pathlib import Path++import pytest++import yaml++ROOT = Path(__file__).resolve().parents[2]+UPDATE = ".github/workflows/update-sandbox-agent-version.yml"+BUILD = ".github/workflows/cd-sandbox-base-image.yml"+WAIT = ".github/actions/wait-for-check/action.yml"+HEAD = "a" * 40+DIGEST = "sha256:" + "b" * 64++GH = """+gh() {+ case "$*" in+ *"/check-runs "*) jq "${@: -1}" <<< "$CHECKS" ;;+ *"/jobs?"*) printf '%s' "$JOBS" ;;+ "api "*"/actions/jobs/"*) printf '%s' "$JOB" ;;+ "api "*"/actions/runs/"*) printf '%s' "$WORKFLOW_RUN" ;;+ "run download "*)+ printf '%s' "$*" > "$RUNNER_TEMP/download"+ if [ "${DOWNLOAD_STATUS:-0}" != 0 ]; then return 1; fi+ mkdir -p "$RUNNER_TEMP/sandbox-base-image"+ cp "$RUNNER_TEMP/sandbox-base-image.json" "$RUNNER_TEMP/sandbox-base-image/"+ ;;+ *) return 1 ;;+ esac+}+sleep() { SECONDS=$((SECONDS + $1)); }+"""+++def script(source: str, step_id: str, job: str = "update-sandbox-agent-version") -> str:+ workflow = yaml.safe_load((ROOT / source).read_text())+ steps = workflow["jobs"][job]["steps"] if "jobs" in workflow else workflow["runs"]["steps"]+ return str(next(step["run"] for step in steps if step.get("id") == step_id))+++def run(tmp_path: Path, body: str, **env: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ ["bash", "-e", "-o", "pipefail", "-c", GH + body],+ cwd=tmp_path,+ env={+ "PATH": os.environ["PATH"],+ "GITHUB_OUTPUT": str(tmp_path / "output"),+ "RUNNER_TEMP": str(tmp_path),+ "GITHUB_REPOSITORY": "PostHog/posthog",+ **env,+ },+ capture_output=True,+ text=True,+ timeout=5,+ )+++ "status,conclusion", [("completed", "success"), ("completed", "failure"), ("in_progress", None)]+)+def test_wait_returns_the_latest_check_and_its_url(tmp_path: Path, status: str, conclusion: str | None) -> None:+ check = {"name": "Sandbox Base Image Smoke", "app": {"slug": "github-actions"}}+ checks = [+ {**check, "id": 1, "status": "completed", "conclusion": "success", "details_url": "old"},+ {**check, "id": 2, "status": status, "conclusion": conclusion, "details_url": "https://example.com/jobs/2"},+ ]+ result = run(+ tmp_path,+ script(WAIT, "poll"),+ CHECKS=json.dumps({"check_runs": checks}),+ CHECK_NAME="Sandbox Base Image Smoke",+ REF=HEAD,+ TIMEOUT_SECONDS="1",+ INTERVAL_SECONDS="1",+ )+ assert result.returncode == 0, result.stderr+ output = (tmp_path / "output").read_text()+ assert f"conclusion={conclusion or 'timed_out'}\n" in output+ assert f"details-url={'https://example.com/jobs/2' if conclusion else ''}\n" in output+++def image_env() -> dict[str, str]:+ branch = "chore/bump-sandbox-agent-version-2.0.1"+ return {+ "SHA": HEAD,+ "BRANCH": branch,+ "PR": "123",+ "CHECK_URL": "https://example.com/actions/runs/456/job/789",+ "JOB": json.dumps(+ {"head_sha": HEAD, "workflow_name": "Tasks Sandbox Container Image CD", "run_id": 456, "run_attempt": 2}+ ),+ "WORKFLOW_RUN": json.dumps(+ {+ "head_sha": HEAD,+ "event": "pull_request",+ "path": BUILD,+ "head_branch": branch,+ "head_repository": {"full_name": "PostHog/posthog"},+ "pull_requests": [{"number": 123, "base": {"ref": "master"}}],+ }+ ),+ "JOBS": json.dumps(+ [+ {+ "jobs": [+ {+ "name": "Build and push Tasks Sandbox container image",+ "run_attempt": attempt,+ "started_at": f"2026-01-01T00:0{minute}:00Z",+ "completed_at": f"2026-01-01T00:0{minute}:30Z",+ }+ for attempt, minute in ((1, 1), (2, 1), (3, 3))+ ]+ }+ ]+ ),+ }+++ "build_attempt,artifact_head,digest,download_status",+ [+ (1, HEAD, DIGEST, "0"),+ (2, HEAD, DIGEST, "0"),+ (1, "c" * 40, DIGEST, "0"),+ (1, HEAD, "invalid", "0"),+ (1, HEAD, DIGEST, "1"),+ ],+)+def test_gateway_uses_the_built_digest_on_partial_reruns(+ tmp_path: Path, image_env: dict[str, str], build_attempt: int, artifact_head: str, digest: str, download_status: str+) -> None:+ if build_attempt == 2:+ jobs = json.loads(image_env["JOBS"])+ jobs[0]["jobs"][1].update(started_at="2026-01-01T00:02:00Z", completed_at="2026-01-01T00:02:30Z")+ image_env["JOBS"] = json.dumps(jobs)+ recorded = run(+ tmp_path, script(BUILD, "image-metadata", "sandbox_base_build"), HEAD_SHA=artifact_head, DIGEST=digest+ )+ assert recorded.returncode == 0, recorded.stderr+ result = run(tmp_path, script(UPDATE, "image"), **image_env, DOWNLOAD_STATUS=download_status)+ assert f"--name sandbox-base-image-{build_attempt} " in (tmp_path / "download").read_text()+ if artifact_head == HEAD and digest == DIGEST and download_status == "0":+ assert result.returncode == 0, result.stderr+ assert (tmp_path / "output").read_text() == f"image=ghcr.io/posthog/posthog-sandbox-base@{DIGEST}\n"+ else:+ assert result.returncode != 0+ assert not (tmp_path / "output").exists()+++ "run_fields",+ [+ {"head_sha": "c" * 40},+ {"event": "push"},+ {"path": ".github/workflows/another-image.yml"},+ {"head_branch": "another-branch-at-the-same-commit"},+ {"head_repository": {"full_name": "someone/posthog"}},+ {"pull_requests": [{"number": 456, "base": {"ref": "master"}}]},+ {"pull_requests": [{"number": 123, "base": {"ref": "another-base"}}]},+ {+ "pull_requests": [+ {"number": 123, "base": {"ref": "master"}},+ {"number": 456, "base": {"ref": "another-base"}},+ ]+ },+ ],+)+def test_gateway_rejects_image_runs_outside_the_bump_pr(+ tmp_path: Path, image_env: dict[str, str], run_fields: dict[str, object]+) -> None:+ workflow_run = json.loads(image_env["WORKFLOW_RUN"])+ workflow_run.update(run_fields)+ image_env["WORKFLOW_RUN"] = json.dumps(workflow_run)+ result = run(tmp_path, script(UPDATE, "image"), **image_env)+ assert result.returncode != 0+ assert not (tmp_path / "download").exists()+ assert not (tmp_path / "output").exists()+++def test_packaging_smoke_uses_each_platform_digest(tmp_path: Path) -> None:+ image = "ghcr.io/posthog/posthog-sandbox-base"+ digests = {"amd64": "sha256:" + "c" * 64, "arm64": "sha256:" + "d" * 64}+ dockerfile = tmp_path / "products/tasks/backend/sandbox/images/Dockerfile.sandbox-base"+ dockerfile.parent.mkdir(parents=True)+ dockerfile.write_text("ARG AGENT_VERSION=2.0.1\n")+ manifest = {+ "manifests": [+ {"platform": {"os": "linux", "architecture": arch}, "digest": digest} for arch, digest in digests.items()+ ]+ }+ docker = """+docker() {+ case "$*" in+ "manifest inspect "*) printf '%s' "$MANIFEST" ;;+ "run "*)+ printf '%s %s\\n' "$4" "$5" >> "$RUNNER_TEMP/containers"+ printf '%s' "$PINNED"+ ;;+ *) return 1 ;;+ esac+}+"""+ result = run(+ tmp_path,+ docker + script(BUILD, "smoke", "sandbox_base_build"),+ IMAGE=f"{image}@{DIGEST}",+ MANIFEST=json.dumps(manifest),+ PINNED="2.0.1",+ )+ assert result.returncode == 0, result.stderr+ assert (tmp_path / "containers").read_text().splitlines() == [+ f"linux/{arch} {image}@{digest}" for arch, digest in digests.items() for _ in range(2)+ ]diff --git a/.github/workflows/cd-sandbox-base-image.yml b/.github/workflows/cd-sandbox-base-image.ymlindex 34eccf00150b..588d0165ad4b 100644--- a/.github/workflows/cd-sandbox-base-image.yml+++ b/.github/workflows/cd-sandbox-base-image.yml@@ -394,22 +394,47 @@ jobs:tags: ${{ github.ref == 'refs/heads/master' && format('ghcr.io/posthog/posthog-sandbox-streamlit:master,ghcr.io/posthog/posthog-sandbox-streamlit:{0}', github.sha) || format('ghcr.io/posthog/posthog-sandbox-streamlit:{0}', github.sha) }}platforms: linux/arm64,linux/amd64+ - name: Record the base image digest+ id: image-metadata+ if: ${{ !cancelled() && steps.build.outcome == 'success' && github.event_name == 'pull_request' }}+ env:+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ DIGEST: ${{ steps.build.outputs.digest }}+ run: |+ jq -n '{head_sha: env.HEAD_SHA, digest: env.DIGEST}' > "$RUNNER_TEMP/sandbox-base-image.json"++ - name: Upload the base image digest+ id: image-artifact+ if: ${{ !cancelled() && steps.image-metadata.outcome == 'success' }}+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f+ with:+ name: sandbox-base-image-${{ github.run_attempt }}+ path: ${{ runner.temp }}/sandbox-base-image.json+ if-no-files-found: error+- name: Smoke the installed agent on both architecturesid: smoke- if: ${{ !cancelled() && steps.build.outcome == 'success' && (github.event_name == 'pull_request' || vars.CD_DEPLOY_ENABLED == 'true') }}+ if: >-+ !cancelled() && steps.build.outcome == 'success' &&+ ((github.event_name == 'pull_request' && steps.image-artifact.outcome == 'success') ||+ (github.event_name != 'pull_request' && vars.CD_DEPLOY_ENABLED == 'true'))env:- IMAGE: ghcr.io/posthog/posthog-sandbox-base:${{ github.sha }}+ IMAGE: ghcr.io/posthog/posthog-sandbox-base@${{ steps.build.outputs.digest }}run: |pinned=$(sed -n 's/^ARG AGENT_VERSION=//p' products/tasks/backend/sandbox/images/Dockerfile.sandbox-base)+ manifest=$(docker manifest inspect "$IMAGE")for platform in linux/amd64 linux/arm64; doecho "::group::$platform"- installed=$(docker run --rm --platform "$platform" "$IMAGE" \+ digest=$(jq -er --arg platform "$platform" '.manifests[] |+ select((.platform.os + "/" + .platform.architecture) == $platform) | .digest' <<< "$manifest")+ platform_image="${IMAGE%@*}@$digest"+ installed=$(docker run --rm --platform "$platform" "$platform_image" \node -p "require('/scripts/node_modules/@posthog/agent/package.json').version")if [ "$installed" != "$pinned" ]; thenecho "::error::$platform image has @posthog/agent $installed, Dockerfile pins $pinned"exit 1fi- docker run --rm --platform "$platform" "$IMAGE" \+ docker run --rm --platform "$platform" "$platform_image" \/scripts/node_modules/.bin/agent-server --help >/dev/nullecho "@posthog/agent $installed starts on $platform"echo "::endgroup::"diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 4b3949786d9e..3ab34056d9ea 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -9,6 +9,9 @@ on:- .github/scripts/**- .github/auto-assign-labels.json- .github/workflows/ci-scripts.yml+ - .github/workflows/cd-sandbox-base-image.yml+ - .github/workflows/update-sandbox-agent-version.yml+ - .github/actions/wait-for-check/**- .github/actions/setup-uv/**# trunk-impacted-targets.test.js reads proto/ and fails on a tree the# table does not declare, so adding one has to run these tests.diff --git a/.github/workflows/update-sandbox-agent-version.yml b/.github/workflows/update-sandbox-agent-version.ymlindex 1f1db8604d63..4a5813159da9 100644--- a/.github/workflows/update-sandbox-agent-version.yml+++ b/.github/workflows/update-sandbox-agent-version.yml@@ -26,6 +26,7 @@ jobs:runs-on: ubuntu-24.04timeout-minutes: 125permissions:+ actions: readcontents: readpackages: read@@ -366,13 +367,43 @@ jobs:echo "::error::Sandbox Base Image Smoke concluded $CONCLUSION on $SHA, so PR #$PR waits for a person"exit 1+ - name: Resolve the smoked image+ id: image+ if: steps.state.outputs.action == 'bump'+ env:+ GH_TOKEN: ${{ github.token }}+ CHECK_URL: ${{ steps.smoke.outputs.details-url }}+ SHA: ${{ steps.commit.outputs.commit-hash }}+ PR: ${{ steps.pr.outputs.number }}+ run: |+ job=$(gh api "repos/${GITHUB_REPOSITORY}/actions/jobs/${CHECK_URL##*/}")+ jq -e '.head_sha == env.SHA and .workflow_name == "Tasks Sandbox Container Image CD"' <<< "$job" >/dev/null+ run_id=$(jq -er .run_id <<< "$job")+ workflow_run=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/$run_id")+ jq -e --argjson pr "$PR" '.head_sha == env.SHA and .event == "pull_request" and+ .path == ".github/workflows/cd-sandbox-base-image.yml" and+ .head_branch == env.BRANCH and .head_repository.full_name == env.GITHUB_REPOSITORY and+ (.pull_requests | length == 1 and .[0].number == $pr and .[0].base.ref == "master")' <<< "$workflow_run" >/dev/null+ attempt=$(jq -er .run_attempt <<< "$job")+ build_attempt=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/$run_id/jobs?filter=all&per_page=100" \+ --paginate --slurp | jq -er --argjson attempt "$attempt" '[.[].jobs[] |+ select(.name == "Build and push Tasks Sandbox container image" and .run_attempt <= $attempt)] |+ group_by([.started_at, .completed_at]) | map(min_by(.run_attempt)) |+ max_by(.run_attempt).run_attempt // empty')+ gh run download "$run_id" --repo "$GITHUB_REPOSITORY" \+ --name "sandbox-base-image-$build_attempt" --dir "$RUNNER_TEMP/sandbox-base-image"+ digest=$(jq -er 'select(.head_sha == env.SHA) | .digest | select(test("^sha256:[0-9a-f]{64}$"))' \+ "$RUNNER_TEMP/sandbox-base-image/sandbox-base-image.json")+ echo "image=ghcr.io/posthog/posthog-sandbox-base@$digest" >> "$GITHUB_OUTPUT"+- name: Smoke the agent on the Go ai-gatewayid: gateway-smokeif: steps.state.outputs.action == 'bump'timeout-minutes: 25uses: ./.github/actions/sandbox-agent-gateway-smokewith:- image: ghcr.io/posthog/posthog-sandbox-base:${{ steps.commit.outputs.commit-hash }}+ image: ${{ steps.image.outputs.image }}+ agent-version: ${{ steps.resolve.outputs.latest }}mint-key: ${{ secrets.AGENT_SMOKE_AI_GATEWAY_MINT_KEY }}registry-token: ${{ secrets.GITHUB_TOKEN }}diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.tsindex 38b4a8b81652..764bddd7b556 100644--- a/tools/workflow-plan/tests/workflows.test.ts+++ b/tools/workflow-plan/tests/workflows.test.ts@@ -490,6 +490,33 @@ const namedJobs = (file: string): Set<string> =>)describe('.github/workflows run plans', () => {+ it.each([+ ['new bump', workflowDispatch(), 'bump', 'success', 'pass', true, false],+ ['missing image', workflowDispatch(), 'bump', 'failure', 'pass', false, false],+ ['failed gateway', workflowDispatch(), 'bump', 'success', 'broken', false, false],+ ['nightly with open PR', schedule(), 'current', 'success', 'pass', false, true],+ ] as const)('sandbox agent release: %s', (name, github, action, imageOutcome, result, enqueue, nightly) => {+ const plan = planWorkflow(workflow('update-sandbox-agent-version.yml'), {+ name,+ github,+ steps: {+ 'update-sandbox-agent-version': {+ state: { outputs: { action } },+ smoke: { outputs: { conclusion: 'success' } },+ image: { outcome: imageOutcome },+ 'gateway-smoke': { outputs: { result } },+ 'Stop when the gateway smoke did not pass': { outcome: 'failure' },+ 'nightly-smoke': { outputs: { result: 'pass' } },+ },+ },+ })+ expect(plan.errors).toEqual([])+ const steps = plan.jobs['update-sandbox-agent-version'].steps+ expect(steps.find((step) => step.id === 'commit')?.runs).toBe(action === 'bump')+ expect(steps.find((step) => step.id === 'enqueue')?.runs).toBe(enqueue)+ expect(steps.find((step) => step.id === 'nightly-smoke')?.runs).toBe(nightly)+ })+it('Phrocs executes tests even when setup-go restores a warm build cache', () => {const testStep = workflow('ci-phrocs.yml').jobs.test.steps?.find((step) => step.name === 'Run tests')expect(testStep?.run).toMatch(/\bgo test\s+-count=1\b/)