diff --git a/.github/scripts/tests/cloud-readiness.test.mjs b/.github/scripts/tests/cloud-readiness.test.mjs index 26c3acb435d..10007a7cba1 100644 --- a/.github/scripts/tests/cloud-readiness.test.mjs +++ b/.github/scripts/tests/cloud-readiness.test.mjs @@ -1,6 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { existsSync, readFileSync } from "node:fs"; +import { imageMetadata } from "../../../scripts/docker-image-metadata.mjs"; const workflow = readFileSync(new URL("../../workflows/cloud-readiness.yml", import.meta.url), "utf8"); @@ -51,7 +52,11 @@ test("Runner chaos evals still run but stay out of the publication gate", async test("standard image provenance and independent exact-source migrators remain available", () => { const docker = readFileSync(new URL("../../workflows/docker.yml", import.meta.url), "utf8"); assert.match(docker, /target: production/); - assert.match(docker, /type=raw,value=sha-\$\{\{ github.sha \}\}/); + assert.equal(docker.match(/run: node scripts\/docker-image-metadata.mjs/g)?.length, 2); + const sha = "a".repeat(40); + const metadata = imageMetadata({ repository: "paperclipai/paperclip", sha, ref: "refs/heads/master", event: "push", + lastMigration: "0000_fixture.sql", migrationCount: "1", created: "2000-01-01T00:00:00.000Z" }); + assert.ok(metadata.tags.includes(`ghcr.io/paperclipai/paperclip:sha-${sha}`)); assert.match(docker, /run: node scripts\/standard-image-contract.mjs --resolve "\$GITHUB_SHA"/); assert.match(docker, /subject-digest: \$\{\{ steps.standard.outputs.digest \}\}/); const migrator = readFileSync(new URL("../../workflows/cloud-migrator-artifacts.yml", import.meta.url), "utf8"); diff --git a/.github/scripts/tests/post-merge-runner-routing.test.mjs b/.github/scripts/tests/post-merge-runner-routing.test.mjs index 0e905635214..f61eecbec40 100644 --- a/.github/scripts/tests/post-merge-runner-routing.test.mjs +++ b/.github/scripts/tests/post-merge-runner-routing.test.mjs @@ -104,6 +104,6 @@ test("Cloud source proof keeps source-only gating on protected verification capa assert.match(body, /^ +SOURCE_SHA: \$\{\{ github.sha \}\}$/m); assert.equal(body.match(/^ needs: (.+)$/m)?.[1] ?? null, needs, `${name} prerequisites`); } - assert.match(bodies.get("source_verified"), /^ run: node --test scripts\/cloud-source-verification.test.mjs$/m); + assert.match(bodies.get("source_verified"), /^ run: node --test scripts\/cloud-source-verification.test.mjs scripts\/github-actions-rate-limit.test.mjs scripts\/docker-image-metadata.test.mjs$/m); assert.match(bodies.get("source_verified"), /echo "Cloud source verified v1: \$SOURCE_SHA"/); }); diff --git a/.github/workflows/cloud-readiness.yml b/.github/workflows/cloud-readiness.yml index 1e9e0a7dcc5..27e8fd9911d 100644 --- a/.github/workflows/cloud-readiness.yml +++ b/.github/workflows/cloud-readiness.yml @@ -86,7 +86,7 @@ jobs: with: node-version: 24 - name: Check the source verification consumer - run: node --test scripts/cloud-source-verification.test.mjs + run: node --test scripts/cloud-source-verification.test.mjs scripts/github-actions-rate-limit.test.mjs scripts/docker-image-metadata.test.mjs - name: Record source verification env: SOURCE_SHA: ${{ github.sha }} diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 2fa4d84e041..9d20e0ca8ef 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -148,6 +148,7 @@ jobs: id: watch env: GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN_SOURCE: github.token run: node scripts/watch-release-source.mjs reuse_canary_image: @@ -441,20 +442,10 @@ jobs: - name: Docker meta id: meta if: steps.promote.outputs.digest == '' - uses: docker/metadata-action@v6 - with: - images: ghcr.io/${{ github.repository }} - tags: | - type=raw,value=nightly,enable=${{ startsWith(github.ref, 'refs/tags/nightly/v') }} - type=raw,value=beta,enable=${{ startsWith(github.ref, 'refs/tags/beta/v') }} - type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }} - type=semver,pattern={{version}},enable=${{ startsWith(github.ref, 'refs/tags/v') }} - type=semver,pattern={{major}}.{{minor}},enable=${{ startsWith(github.ref, 'refs/tags/v') }} - type=sha - type=raw,value=sha-${{ github.sha }},enable=${{ github.repository == 'paperclipai/paperclip' && github.event_name == 'push' && github.ref == 'refs/heads/master' }} - labels: | - io.github.paperclipai.schema.last-migration=${{ steps.schema.outputs.last }} - io.github.paperclipai.schema.migration-count=${{ steps.schema.outputs.count }} + env: + LAST_MIGRATION: ${{ steps.schema.outputs.last }} + MIGRATION_COUNT: ${{ steps.schema.outputs.count }} + run: node scripts/docker-image-metadata.mjs - name: Build and push by digest id: build if: steps.promote.outputs.digest == '' @@ -567,6 +558,7 @@ jobs: - name: Require source proof and migrator admission before publication env: GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN_SOURCE: github.token run: node scripts/watch-release-source.mjs --require-proof # Names the per-architecture digests as one manifest list under the real @@ -606,8 +598,11 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 - # Repeated from the build job rather than passed between them: job - # outputs would have to survive a matrix, and this is two `ls` calls. + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 + with: + node-version: 24 + - name: Compute schema migration labels id: schema run: | @@ -624,25 +619,10 @@ jobs: # so parallel canary-tag builds can never race the channel backwards. - name: Docker meta id: meta - uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6 - with: - images: ghcr.io/${{ github.repository }} - tags: | - type=raw,value=nightly,enable=${{ startsWith(github.ref, 'refs/tags/nightly/v') }} - type=raw,value=beta,enable=${{ startsWith(github.ref, 'refs/tags/beta/v') }} - type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }} - type=semver,pattern={{version}},enable=${{ startsWith(github.ref, 'refs/tags/v') }} - type=semver,pattern={{major}}.{{minor}},enable=${{ startsWith(github.ref, 'refs/tags/v') }} - type=sha - type=raw,value=sha-${{ github.sha }},enable=${{ github.repository == 'paperclipai/paperclip' && github.event_name == 'push' && github.ref == 'refs/heads/master' }} - labels: | - io.github.paperclipai.schema.last-migration=${{ steps.schema.outputs.last }} - io.github.paperclipai.schema.migration-count=${{ steps.schema.outputs.count }} - - - name: Setup Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 - with: - node-version: 24 + env: + LAST_MIGRATION: ${{ steps.schema.outputs.last }} + MIGRATION_COUNT: ${{ steps.schema.outputs.count }} + run: node scripts/docker-image-metadata.mjs # Revalidate the latest attempt after runner assignment without waiting # here. A concurrent source retry must invalidate the earlier proof. @@ -650,10 +630,13 @@ jobs: if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.ref == 'refs/heads/master' env: GITHUB_TOKEN: ${{ github.token }} + GITHUB_TOKEN_SOURCE: github.token run: node scripts/watch-release-source.mjs --check-proof - name: Create manifest list and push working-directory: /tmp/digests + env: + DOCKER_METADATA_OUTPUT_JSON: ${{ steps.meta.outputs.json }} run: | set -euo pipefail docker buildx imagetools create \ diff --git a/.github/workflows/pr-trusted.yml b/.github/workflows/pr-trusted.yml index f749fd6af75..deb7d92060e 100644 --- a/.github/workflows/pr-trusted.yml +++ b/.github/workflows/pr-trusted.yml @@ -251,6 +251,9 @@ jobs: - name: Test release verify workflow wiring run: | tests=(./scripts/__tests__/release-verify-workflow.test.mjs ./scripts/__tests__/eval-schedule-monitor.test.mjs ./scripts/__tests__/prepare-runner-release-image.test.mjs ./scripts/cloud-source-verification.test.mjs ./scripts/cloud-readiness-runner-loss.test.mjs ./scripts/standard-image-contract.test.mjs ./scripts/reuse-canary-image.test.mjs) + for test in ./scripts/github-actions-rate-limit.test.mjs ./scripts/docker-image-metadata.test.mjs; do + if [[ -f "$test" ]]; then tests+=("$test"); fi + done if [[ -f ./scripts/verify-canary-provenance.test.mjs ]]; then tests+=(./scripts/verify-canary-provenance.test.mjs); fi node "$CI_NODE_TEST" "${tests[@]}" diff --git a/doc/cloud-build-readiness.md b/doc/cloud-build-readiness.md index df1a595bf56..82f397f0c0d 100644 --- a/doc/cloud-build-readiness.md +++ b/doc/cloud-build-readiness.md @@ -61,6 +61,30 @@ before that bot's PR merges. Verification must install and test that commit without waiting for another merge. The generated lockfile stays in the job's workspace; these checks do not commit it back to the repository. +## GitHub API quota recovery + +The Actions reader reuses ETags for unchanged polls. A primary quota response +waits until `x-ratelimit-reset`, with a one-second margin. `Retry-After` also sets +a minimum wait, including on transient service errors such as HTTP 503. +Without either value, a throttled request waits at least one +minute, then uses exponential backoff. A permission-denied 403 is not retried. + +A wait must fit the caller deadline and the per-read budget. The default reader +budget is 15 minutes. The Docker observer shares its 40-minute deadline with the +reader; its final proof recheck has a five-minute budget. If the reset falls +outside that budget, the step fails with `GitHub API rate limited` instead of +retrying early. The error can include the quota limit, remaining requests, +resource and reset time. It never includes the token or response body. Docker +sets `GITHUB_TOKEN_SOURCE=github.token` beside the automatic token binding; other +callers are described as a configured credential unless they supply that hint. + +Docker tags and OCI labels are generated from checkout and workflow inputs by +`scripts/docker-image-metadata.mjs`, without a repository API read. Stable, +beta, nightly and immutable SHA tag rules stay the same. Labels retain source, +revision, version, creation time, local license and migration metadata; the +GitHub repository description is no longer fetched. Source proof, migrator +proof and attestation checks remain required. + ## Consumer contract and retirement boundary Accept `Cloud source verified v1` only from the latest attempt of the canonical diff --git a/scripts/cloud-source-verification.mjs b/scripts/cloud-source-verification.mjs index db6f34019d8..297d26e90dd 100644 --- a/scripts/cloud-source-verification.mjs +++ b/scripts/cloud-source-verification.mjs @@ -1,6 +1,6 @@ import { appendFile } from "node:fs/promises"; import { pathToFileURL } from "node:url"; -import { createActionsReader } from "./github-actions-reader.mjs"; +import { createActionsReader, GitHubActionsRateLimitError } from "./github-actions-reader.mjs"; import { deferredProducer, requestDeferredProducer, sourceAdmissionJob, createReleaseRerunner } from "./cloud-release-admission.mjs"; import { createRunnerLossRetry } from "./cloud-readiness-runner-loss.mjs"; @@ -130,7 +130,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) // Long enough for a deferred full run plus two runner-loss retries. const timeoutMs = 90 * 60_000; const deadline = Date.now() + timeoutMs; - const api = createActionsReader({ token: process.env.GITHUB_TOKEN, deadlineAt: () => deadline }); + const api = createActionsReader({ token: process.env.GITHUB_TOKEN, tokenSource: process.env.GITHUB_TOKEN_SOURCE, deadlineAt: () => deadline, maxRetryAfterMs: timeoutMs }); const canonical = process.env.GITHUB_REPOSITORY === repository && process.env.GITHUB_REF === "refs/heads/master"; const rerun = canonical ? createReleaseRerunner(process.env.GITHUB_TOKEN) : undefined; const retryRunnerLoss = canonical ? createRunnerLossRetry({ token: process.env.GITHUB_TOKEN }) : undefined; @@ -139,7 +139,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) console.log(message); if (process.env.GITHUB_STEP_SUMMARY) await appendFile(process.env.GITHUB_STEP_SUMMARY, `${message}\n`); } catch (error) { - console.error(error.message); + console.error(error instanceof GitHubActionsRateLimitError ? `::error title=GitHub API rate limited::${error.message}` : error.message); process.exitCode = 1; } } diff --git a/scripts/cloud-source-verification.test.mjs b/scripts/cloud-source-verification.test.mjs index 612c9644832..c20d1f701cf 100644 --- a/scripts/cloud-source-verification.test.mjs +++ b/scripts/cloud-source-verification.test.mjs @@ -261,7 +261,7 @@ test("a transient gateway error is retried instead of failing the release", asyn }); test("every transient status is retried, and the backoff grows", async () => { - for (const status of [408, 425, 429, 500, 502, 503, 504]) { + for (const status of [408, 425, 500, 502, 503, 504]) { const { api, seen, waits } = reader({ responses: [{ status }, { status }, { status: 200, body: { ok: true } }] }); await api("/repos/x"); assert.equal(seen.length, 3, `status ${status} should be retried`); @@ -284,14 +284,15 @@ test("a rate-limited 403 is retried, and a forbidden 403 is not", async () => { } }); -test("Retry-After sets the wait, capped so one header cannot stall the poll", async () => { +test("Retry-After sets the wait and an excessive delay fails without retrying early", async () => { const { api, waits } = reader({ responses: [{ status: 429, headers: { "retry-after": "5" } }, { status: 200 }] }); await api("/repos/x"); assert.deepEqual(waits, [5_000]); const capped = reader({ responses: [{ status: 429, headers: { "retry-after": "86400" } }, { status: 200 }], maxRetryAfterMs: 60_000 }); - await capped.api("/repos/x"); - assert.deepEqual(capped.waits, [60_000]); + await assert.rejects(capped.api("/repos/x"), /GitHub API rate limited/); + assert.deepEqual(capped.waits, []); + assert.equal(capped.seen.length, 1); }); test("a body that fails while being read is retried", async () => { diff --git a/scripts/docker-image-metadata.mjs b/scripts/docker-image-metadata.mjs new file mode 100644 index 00000000000..545b8f76dd5 --- /dev/null +++ b/scripts/docker-image-metadata.mjs @@ -0,0 +1,48 @@ +import { appendFile, readFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { pathToFileURL } from "node:url"; + +export function imageMetadata({ repository, sha, ref, event, lastMigration, migrationCount, created = new Date().toISOString(), license = "" }) { + if (!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repository ?? "") || !/^[a-f0-9]{40}$/.test(sha ?? "") || + !/^[\w.-]+\.sql$/.test(lastMigration ?? "") || !/^\d+$/.test(migrationCount ?? "") || !Number.isFinite(Date.parse(created))) { + throw new Error("Invalid image metadata inputs."); + } + const image = `ghcr.io/${repository.toLowerCase()}`; + const versions = []; + if (ref?.startsWith("refs/tags/v")) { + const version = ref.slice("refs/tags/v".length); + const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(version); + if (match && match.slice(1, 4).every(value => Number.isSafeInteger(Number(value))) && + (!match[4] || match[4].slice(1).split(".").every(part => !/^0\d+$/.test(part)))) { + const normalized = `${match[1]}.${match[2]}.${match[3]}${match[4] ?? ""}`; + versions.push(normalized, match[4] ? normalized : `${match[1]}.${match[2]}`); + } + versions.push("latest"); + } + if (ref?.startsWith("refs/tags/nightly/v")) versions.push("nightly"); + if (ref?.startsWith("refs/tags/beta/v")) versions.push("beta"); + if (repository === "paperclipai/paperclip" && event === "push" && ref === "refs/heads/master") versions.push(`sha-${sha}`); + versions.push(`sha-${sha.slice(0, 7)}`); + const unique = [...new Set(versions)]; + const source = `https://github.com/${repository}`; + const labels = { + "org.opencontainers.image.created": created, + "org.opencontainers.image.source": source, + "org.opencontainers.image.url": source, + "org.opencontainers.image.revision": sha, + "org.opencontainers.image.title": repository.split("/")[1], + "org.opencontainers.image.version": unique[0], + "org.opencontainers.image.licenses": license, + "io.github.paperclipai.schema.last-migration": lastMigration, + "io.github.paperclipai.schema.migration-count": migrationCount, + }; + return { tags: unique.map(tag => `${image}:${tag}`), labels }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const metadata = imageMetadata({ repository: process.env.GITHUB_REPOSITORY, sha: process.env.GITHUB_SHA, ref: process.env.GITHUB_REF, + event: process.env.GITHUB_EVENT_NAME, lastMigration: process.env.LAST_MIGRATION, migrationCount: process.env.MIGRATION_COUNT, + license: (await readFile(new URL("../LICENSE", import.meta.url), "utf8")).startsWith("MIT License") ? "MIT" : "" }); + const delimiter = randomUUID(); + await appendFile(process.env.GITHUB_OUTPUT, `json=${JSON.stringify(metadata)}\nlabels<<${delimiter}\n${Object.entries(metadata.labels).map(([key, value]) => `${key}=${value}`).join("\n")}\n${delimiter}\n`); +} diff --git a/scripts/docker-image-metadata.test.mjs b/scripts/docker-image-metadata.test.mjs new file mode 100644 index 00000000000..ae48b2dedbb --- /dev/null +++ b/scripts/docker-image-metadata.test.mjs @@ -0,0 +1,92 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { imageMetadata } from "./docker-image-metadata.mjs"; + +const sha = "a".repeat(40); +const base = { repository: "paperclipai/paperclip", sha, ref: "refs/heads/master", event: "push", lastMigration: "0000_fixture.sql", migrationCount: "1", created: "2000-01-01T00:00:00.000Z" }; +const tags = options => imageMetadata({ ...base, ...options }).tags.map(tag => tag.split(":")[1]); + +test("master keeps immutable short/full SHA tags without moving a release channel", () => { + assert.deepEqual(tags({}), [`sha-${sha}`, `sha-${sha.slice(0, 7)}`]); + assert.deepEqual(tags({ event: "workflow_dispatch" }), [`sha-${sha.slice(0, 7)}`]); + assert.deepEqual(tags({ repository: "example/fork" }), [`sha-${sha.slice(0, 7)}`]); +}); + +test("release lanes keep their existing tags and stable semver aliases", () => { + for (const event of ["push", "workflow_dispatch"]) { + assert.deepEqual(tags({ ref: "refs/tags/v1.2.3", event }), ["1.2.3", "1.2", "latest", "sha-aaaaaaa"]); + assert.deepEqual(tags({ ref: "refs/tags/v1.2.3-rc.1+build", event }), ["1.2.3-rc.1", "latest", "sha-aaaaaaa"]); + assert.deepEqual(tags({ ref: "refs/tags/beta/v1.2.3-beta.1", event }), ["beta", "sha-aaaaaaa"]); + assert.deepEqual(tags({ ref: "refs/tags/nightly/v1.2.3", event }), ["nightly", "sha-aaaaaaa"]); + assert.deepEqual(tags({ ref: "refs/tags/canary/v1.2.3", event }), ["sha-aaaaaaa"]); + for (const version of ["01.2.3", "1.2.3-01", "1.2.3-a..b"]) { + assert.deepEqual(tags({ ref: `refs/tags/v${version}`, event }), ["latest", "sha-aaaaaaa"]); + } + } +}); + +test("OCI source, revision and migration labels come from the checkout inputs", () => { + const metadata = imageMetadata(base); + assert.equal(metadata.labels["org.opencontainers.image.source"], "https://github.com/paperclipai/paperclip"); + assert.equal(metadata.labels["org.opencontainers.image.revision"], sha); + assert.equal(metadata.labels["io.github.paperclipai.schema.last-migration"], base.lastMigration); + assert.equal(metadata.labels["io.github.paperclipai.schema.migration-count"], "1"); + for (const options of [{ sha: "main" }, { repository: "invalid\nrepo" }, { lastMigration: "x.sql\nINJECTED=1" }, { migrationCount: "1\nINJECTED=1" }]) { + assert.throws(() => imageMetadata({ ...base, ...options }), /Invalid image metadata/); + } +}); + +test("the CLI writes usable outputs without any GitHub credential", () => { + const dir = mkdtempSync(join(tmpdir(), "docker-metadata-")); + try { + const output = join(dir, "outputs"); + const env = { ...process.env, GITHUB_TOKEN: "", GH_TOKEN: "", GITHUB_OUTPUT: output, + GITHUB_REPOSITORY: base.repository, GITHUB_SHA: sha, GITHUB_REF: base.ref, GITHUB_EVENT_NAME: base.event, + LAST_MIGRATION: base.lastMigration, MIGRATION_COUNT: base.migrationCount }; + execFileSync(process.execPath, [new URL("./docker-image-metadata.mjs", import.meta.url).pathname], { env }); + const text = readFileSync(output, "utf8"); + const json = JSON.parse(text.split("\n")[0].slice(5)); + assert.deepEqual(json.tags, tags({}).map(tag => `ghcr.io/paperclipai/paperclip:${tag}`)); + assert.equal(json.labels["org.opencontainers.image.licenses"], "MIT"); + assert.match(text, /labels<<[^\n]+\norg.opencontainers.image.created=/); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test("both workflow metadata steps use local inputs and the manifest consumes their explicit JSON output", () => { + const workflow = readFileSync(new URL("../.github/workflows/docker.yml", import.meta.url), "utf8"); + assert.doesNotMatch(workflow, /docker\/metadata-action/); + assert.equal(workflow.match(/run: node scripts\/docker-image-metadata.mjs/g)?.length, 2); + assert.equal(workflow.match(/LAST_MIGRATION: \$\{\{ steps.schema.outputs.last \}\}/g)?.length, 2); + assert.match(workflow, /DOCKER_METADATA_OUTPUT_JSON: \$\{\{ steps.meta.outputs.json \}\}/); +}); + +test("trusted release checks tolerate older checkouts and run each new test when present", () => { + const workflow = readFileSync(new URL("../.github/workflows/pr-trusted.yml", import.meta.url), "utf8"); + const step = workflow.split(" - name: Test release verify workflow wiring\n")[1].split("\n - name:")[0]; + const script = step.split(" run: |\n")[1].replace(/^ {10}/gm, ""); + const baseline = ["./scripts/__tests__/release-verify-workflow.test.mjs", "./scripts/__tests__/eval-schedule-monitor.test.mjs", + "./scripts/__tests__/prepare-runner-release-image.test.mjs", "./scripts/cloud-source-verification.test.mjs", + "./scripts/cloud-readiness-runner-loss.test.mjs", "./scripts/standard-image-contract.test.mjs", "./scripts/reuse-canary-image.test.mjs"]; + const added = ["./scripts/github-actions-rate-limit.test.mjs", "./scripts/docker-image-metadata.test.mjs"]; + const dir = mkdtempSync(join(tmpdir(), "trusted-release-checks-")); + try { + mkdirSync(join(dir, "scripts/__tests__"), { recursive: true }); + for (const file of baseline) writeFileSync(join(dir, file), ""); + const output = join(dir, "selected.json"), capture = join(dir, "capture.mjs"); + writeFileSync(capture, `import { existsSync, writeFileSync } from "node:fs"; + const files = process.argv.slice(2); + if (files.some(file => !existsSync(file))) process.exit(1); + writeFileSync(process.env.CAPTURE_OUTPUT, JSON.stringify(files));`); + for (const present of [[], added.slice(0, 1), added.slice(1), added]) { + for (const file of added) rmSync(join(dir, file), { force: true }); + for (const file of present) writeFileSync(join(dir, file), ""); + execFileSync("bash", ["-euo", "pipefail", "-c", script], { cwd: dir, + env: { ...process.env, CI_NODE_TEST: capture, CAPTURE_OUTPUT: output } }); + assert.deepEqual(JSON.parse(readFileSync(output, "utf8")), [...baseline, ...present]); + } + } finally { rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/scripts/github-actions-rate-limit.test.mjs b/scripts/github-actions-rate-limit.test.mjs new file mode 100644 index 00000000000..e5f1f6c4f37 --- /dev/null +++ b/scripts/github-actions-rate-limit.test.mjs @@ -0,0 +1,124 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createActionsReader } from "./github-actions-reader.mjs"; + +function fixture(responses, options = {}) { + let clock = Date.UTC(2000, 0, 1); + const calls = [], waits = [], logs = []; + const api = createActionsReader({ + token: "fixture-secret", tokenSource: "github.token", now: () => clock, + sleep: async ms => { waits.push(ms); clock += ms; }, + log: message => logs.push(message), + fetchImpl: async () => { + calls.push(clock); + const next = responses.shift(); + assert.ok(next, "Unexpected extra API request"); + return new Response(JSON.stringify({ message: "fixture-private-body", ok: true }), next); + }, ...options, + }); + return { api, calls, waits, logs }; +} + +const reset = String(Date.UTC(2000, 0, 1) / 1000 + 120); + +test("primary throttling waits for the real reset and emits only safe quota diagnostics", async () => { + const f = fixture([{ status: 403, headers: { "x-ratelimit-remaining": "0", "x-ratelimit-limit": "1000", "x-ratelimit-reset": reset, + "x-ratelimit-resource": "core" } }, { status: 200 }]); + await f.api("/repos/example/repo/actions/runs"); + assert.deepEqual(f.waits, [121_000]); + assert.equal(f.calls[1] - f.calls[0], 121_000); + assert.match(f.logs[0], /credential: github.token.*resource: core.*limit: 1000.*remaining: 0.*reset: 2000-01-01T00:02:00.000Z/); + assert.doesNotMatch(f.logs.join(""), /fixture-secret|fixture-private-body|example\/repo/); +}); + +test("a reset or Retry-After outside the budget stops without an early retry", async () => { + for (const headers of [{ "x-ratelimit-remaining": "0", "x-ratelimit-reset": reset }, { "retry-after": "3600" }]) { + const f = fixture([{ status: 403, headers }], { maxRetryAfterMs: 60_000 }); + await assert.rejects(f.api("/repos/x"), /GitHub API rate limited/); + assert.equal(f.calls.length, 1); + assert.deepEqual(f.waits, []); + } +}); + +test("the caller deadline accounts for the entire server wait", async () => { + const f = fixture([{ status: 429, headers: { "retry-after": "120" } }], { deadlineAt: () => Date.UTC(2000, 0, 1) + 60_000 }); + await assert.rejects(f.api("/repos/x"), /GitHub API rate limited/); + assert.deepEqual(f.waits, []); + assert.equal(f.calls.length, 1); +}); + +test("secondary throttling without a reset backs off for at least a minute", async () => { + const f = fixture([{ status: 429 }, { status: 429 }, { status: 200 }]); + await f.api("/repos/x"); + assert.deepEqual(f.waits, [60_000, 120_000]); +}); + +test("Retry-After dates and a later primary reset are both respected", async () => { + const f = fixture([{ status: 429, headers: { "retry-after": "Sat, 01 Jan 2000 00:03:00 GMT", "x-ratelimit-remaining": "0", "x-ratelimit-reset": reset } }, { status: 200 }]); + await f.api("/repos/x"); + assert.deepEqual(f.waits, [180_000]); +}); + +test("quota errors stay explicit when attempts are exhausted and do not guess a token source", async () => { + const f = fixture([{ status: 429, headers: { "x-ratelimit-resource": "fixture-private-body", "x-ratelimit-limit": "unsafe-value" } }], + { attempts: 1, tokenSource: "fixture-secret" }); + await assert.rejects(f.api("/repos/x"), error => { + assert.equal(error.name, "GitHubActionsRateLimitError"); + assert.match(error.message, /HTTP 429; credential: configured credential/); + assert.doesNotMatch(error.message, /fixture-secret|fixture-private-body|unsafe-value|github.token/); + return true; + }); +}); + +test("an ordinary forbidden response is still an immediate permission failure", async () => { + const f = fixture([{ status: 403, headers: { "x-ratelimit-remaining": "999" } }]); + await assert.rejects(f.api("/repos/x"), /GitHub Actions read failed \(HTTP 403\)/); + assert.deepEqual(f.waits, []); +}); + +test("transient service failures honor Retry-After seconds and dates", async () => { + for (const retryAfter of ["30", "Sat, 01 Jan 2000 00:00:30 GMT"]) { + const f = fixture([{ status: 503, headers: { "retry-after": retryAfter } }, { status: 200 }]); + await f.api("/repos/x"); + assert.deepEqual(f.waits, [30_000]); + assert.equal(f.calls[1] - f.calls[0], 30_000); + } +}); + +test("transient Retry-After waits outside either budget fail without an early retry", async () => { + for (const options of [{ maxRetryAfterMs: 20_000 }, { deadlineAt: () => Date.UTC(2000, 0, 1) + 20_000 }]) { + const f = fixture([{ status: 503, headers: { "retry-after": "30" } }], options); + await assert.rejects(f.api("/repos/x"), /GitHub Actions read failed \(HTTP 503\)/); + assert.deepEqual(f.waits, []); + assert.equal(f.calls.length, 1); + } +}); + + +test("the release CLI reports safe quota evidence and cannot publish proof or cancel work", () => { + const dir = mkdtempSync(join(tmpdir(), "github-quota-cli-")); + try { + const mock = join(dir, "fetch.mjs"), output = join(dir, "outputs"); + writeFileSync(mock, `globalThis.fetch = async (_url, init) => { + if (init?.method && init.method !== "GET") throw new Error("Unexpected mutation"); + return new Response(JSON.stringify({ message: "fixture-private-body" }), { status: 403, + headers: { "x-ratelimit-remaining": "0", "x-ratelimit-limit": "1000", "x-ratelimit-reset": String(Math.floor(Date.now() / 1000) + 7200) } }); + };`); + for (const args of [[], ["--require-proof"], ["--check-proof"]]) { + writeFileSync(output, ""); + const result = spawnSync(process.execPath, ["--import", mock, new URL("./watch-release-source.mjs", import.meta.url).pathname, ...args], { + encoding: "utf8", timeout: 5000, env: { ...process.env, GITHUB_TOKEN: "fixture-secret", GITHUB_TOKEN_SOURCE: "github.token", + GITHUB_REPOSITORY: "paperclipai/paperclip", GITHUB_REF: "refs/heads/master", GITHUB_SHA: "a".repeat(40), + GITHUB_RUN_ID: "1", GITHUB_RUN_ATTEMPT: "1", GITHUB_OUTPUT: output }, + }); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /::error title=GitHub API rate limited::GitHub API rate limited.*credential: github.token.*limit: 1000.*remaining: 0.*reset:/); + assert.doesNotMatch(result.stderr + result.stdout, /fixture-secret|fixture-private-body|Unexpected mutation/); + assert.equal(readFileSync(output, "utf8"), ""); + } + } finally { rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/scripts/github-actions-reader.mjs b/scripts/github-actions-reader.mjs index a171fbc02b7..83a034bbcc9 100644 --- a/scripts/github-actions-reader.mjs +++ b/scripts/github-actions-reader.mjs @@ -1,45 +1,60 @@ -// Statuses that say "ask again", not "the answer is no". A release must not be -// blocked because GitHub returned a gateway error during a 60-minute poll. -const TRANSIENT_READ_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]); +const TRANSIENT_READ_STATUSES = new Set([408, 425, 500, 502, 503, 504]); +const rateResources = new Set(["core", "search", "code_search", "graphql", "integration_manifest", "actions_runner_registration"]); -// A rate-limited read also says "ask again", and GitHub reports both primary -// and secondary rate limits as 403. Only the headers separate that from a -// token that may not read Actions, which must still fail at once. function rateLimited(response) { - if (response.status !== 403) return false; - const header = (name) => response.headers?.get?.(name) ?? null; - return header("retry-after") !== null || header("x-ratelimit-remaining") === "0"; + return response.status === 429 || (response.status === 403 && + (response.headers?.get?.("retry-after") != null || response.headers?.get?.("x-ratelimit-remaining") === "0")); } -/** Milliseconds from a Retry-After header, when it carries a sane delay. */ -function retryAfterMs(response, capMs) { - const value = Number(response?.headers?.get?.("retry-after")); - if (!Number.isFinite(value) || value <= 0) return null; - return Math.min(value * 1_000, capMs); +function numericHeader(response, name) { + const value = response.headers?.get?.(name); + if (!/^\d+$/.test(value ?? "")) return undefined; + const number = Number(value); + return Number.isSafeInteger(number) ? number : undefined; +} + +function quota(response, tokenSource) { + const seconds = numericHeader(response, "x-ratelimit-reset"); + const reset = seconds !== undefined && seconds <= 8_640_000_000_000 ? seconds * 1000 : undefined; + const resource = response.headers?.get?.("x-ratelimit-resource"); + return { status: response.status, credential: tokenSource === "github.token" ? "github.token" : "configured credential", + ...(rateResources.has(resource) ? { resource } : {}), + limit: numericHeader(response, "x-ratelimit-limit"), remaining: numericHeader(response, "x-ratelimit-remaining"), reset }; +} + +export class GitHubActionsRateLimitError extends Error { + constructor(details) { + const fields = [`HTTP ${details.status}`, `credential: ${details.credential}`]; + for (const name of ["resource", "limit", "remaining"]) if (details[name] !== undefined) fields.push(`${name}: ${details[name]}`); + if (details.reset !== undefined) fields.push(`reset: ${new Date(details.reset).toISOString()}`); + super(`GitHub API rate limited (${fields.join("; ")}).`); + this.name = "GitHubActionsRateLimitError"; + } +} + +function retryAfterMs(response, now) { + const raw = response.headers?.get?.("retry-after"); + const parsed = raw == null || raw.trim() === "" ? NaN : /^\d+(?:\.\d+)?$/.test(raw) ? now + Number(raw) * 1000 : Date.parse(raw); + return Number.isFinite(parsed) && parsed > now ? parsed - now : undefined; +} + +function quotaWait(response, details, now, attempt) { + const retryAfter = retryAfterMs(response, now); + const resetWait = details.remaining === 0 && details.reset !== undefined && details.reset > now ? details.reset - now + 1000 : undefined; + return Math.max(retryAfter ?? 0, resetWait ?? 0) || 60_000 * 2 ** (attempt - 1); } -/** - * The GitHub Actions read used by the polling below, with transient transport - * failures retried: network errors, the statuses above, rate-limited 403s, and - * a body that fails while it is being read. Any other non-OK status throws on - * the first response, because waiting out a wrong token only delays the news. - * - * `deadlineAt` bounds retries by the caller's own polling deadline, so a read - * cannot extend the wait past the timeout it belongs to. - */ export function createActionsReader({ token, fetchImpl = fetch, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), attempts = 4, backoffMs = 1_000, log = console.log, - now = Date.now, deadlineAt = () => Infinity, maxRetryAfterMs = 60_000, + now = Date.now, deadlineAt = () => Infinity, maxRetryAfterMs = 15 * 60_000, tokenSource, } = {}) { const cached = new Map(); return async (path) => { + const deadline = Math.min(deadlineAt(), now() + maxRetryAfterMs); for (let attempt = 1; ; attempt += 1) { - // Retry only while both the attempt budget and the caller's deadline - // leave room for the wait this attempt would cost. const waitMs = backoffMs * attempt; - const retryable = attempt < attempts && now() + waitMs < deadlineAt(); - const pause = (response) => sleep(retryAfterMs(response, maxRetryAfterMs) ?? waitMs); + const retryable = delay => attempt < attempts && now() + delay < Math.min(deadline, deadlineAt()); let response; try { const etag = cached.get(path)?.etag; @@ -51,33 +66,42 @@ export function createActionsReader({ signal: AbortSignal.timeout(30_000), redirect: "error", }); } catch (cause) { - if (!retryable) throw new Error(`GitHub Actions read failed: ${cause.message}`); + if (!retryable(waitMs)) throw new Error(`GitHub Actions read failed: ${cause.message}`); log(`GitHub Actions read failed (${cause.message}); retrying (${attempt}/${attempts - 1}).`); - await pause(); + await sleep(waitMs); continue; } if (response.status === 304 && cached.has(path)) return structuredClone(cached.get(path).body); if (response.ok) { try { - // A 200 whose body is truncated or undecodable is a transport - // failure like any other, so it belongs inside the retry. const body = await response.json(); const etag = response.headers?.get?.("etag"); if (etag) cached.set(path, { etag, body: structuredClone(body) }); else cached.delete(path); return body; } catch (cause) { - if (!retryable) throw new Error(`GitHub Actions read failed: ${cause.message}`); + if (!retryable(waitMs)) throw new Error(`GitHub Actions read failed: ${cause.message}`); log(`GitHub Actions read body failed (${cause.message}); retrying (${attempt}/${attempts - 1}).`); - await pause(); + await sleep(waitMs); continue; } } - if (!retryable || !(TRANSIENT_READ_STATUSES.has(response.status) || rateLimited(response))) { + void response.body?.cancel().catch(() => {}); + if (rateLimited(response)) { + const details = quota(response, tokenSource); + const error = new GitHubActionsRateLimitError(details); + const delay = quotaWait(response, details, now(), attempt); + if (!retryable(delay)) throw error; + log(`${error.message} Waiting ${Math.ceil(delay / 1000)}s before retry ${attempt}/${attempts - 1}.`); + await sleep(delay); + continue; + } + const delay = Math.max(waitMs, retryAfterMs(response, now()) ?? 0); + if (!TRANSIENT_READ_STATUSES.has(response.status) || !retryable(delay)) { throw new Error(`GitHub Actions read failed (HTTP ${response.status}).`); } log(`GitHub Actions read failed (HTTP ${response.status}); retrying (${attempt}/${attempts - 1}).`); - await pause(response); + await sleep(delay); } }; } diff --git a/scripts/watch-release-source.mjs b/scripts/watch-release-source.mjs index 1dbdfe7b6ca..793dc9896cd 100644 --- a/scripts/watch-release-source.mjs +++ b/scripts/watch-release-source.mjs @@ -3,6 +3,7 @@ import { pathToFileURL } from "node:url"; import { createActionsReader, readSourceVerification, SourceVerificationFailed, SourceVerificationDeferred } from "./cloud-source-verification.mjs"; import { requestDeferredProducer, readMigratorPublication, sourceAdmissionJob, migratorAdmissionJob, createReleaseRerunner } from "./cloud-release-admission.mjs"; import { createRunnerLossRetry } from "./cloud-readiness-runner-loss.mjs"; +import { GitHubActionsRateLimitError } from "./github-actions-reader.mjs"; const repository = "paperclipai/paperclip"; @@ -92,23 +93,30 @@ export async function watchReleaseSource({ sha, runId, attempt, api, cancel, rer } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - const token = process.env.GITHUB_TOKEN; - if (!token || process.env.GITHUB_REPOSITORY !== repository || process.env.GITHUB_REF !== "refs/heads/master") throw new Error("Canonical master token required."); - const requireProof = process.argv.includes("--require-proof"); - const checkProof = process.argv.includes("--check-proof"); - const api = createActionsReader({ token }); - const proof = checkProof ? await readSourceVerification(process.env.GITHUB_SHA, api, { failFast: true }) : await watchReleaseSource({ requireProof, sha: process.env.GITHUB_SHA, runId: Number(process.env.GITHUB_RUN_ID), attempt: Number(process.env.GITHUB_RUN_ATTEMPT), - api, - rerun: createReleaseRerunner(token), - retryRunnerLoss: createRunnerLossRetry({ token }), - cancel: async path => { - const response = await fetch(`https://api.github.com${path}`, { method: "POST", redirect: "error", - headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(30_000) }); - if (!response.ok) throw new Error(`Could not cancel failed-source image work: HTTP ${response.status}.`); - }, - summary: text => process.env.GITHUB_STEP_SUMMARY ? appendFile(process.env.GITHUB_STEP_SUMMARY, text) : Promise.resolve(), - }); - if (checkProof && !proof) throw new Error("Exact-source proof changed before publication."); - if (checkProof && !await readMigratorPublication(process.env.GITHUB_SHA, api)) throw new Error("Exact-source migrator has not published."); - if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `verified=${Boolean(proof)}\n`); + try { + const token = process.env.GITHUB_TOKEN; + if (!token || process.env.GITHUB_REPOSITORY !== repository || process.env.GITHUB_REF !== "refs/heads/master") throw new Error("Canonical master token required."); + const requireProof = process.argv.includes("--require-proof"); + const checkProof = process.argv.includes("--check-proof"); + const timeoutMs = checkProof ? 5 * 60_000 : 40 * 60_000; + const deadline = Date.now() + timeoutMs; + const api = createActionsReader({ token, tokenSource: process.env.GITHUB_TOKEN_SOURCE, deadlineAt: () => deadline, maxRetryAfterMs: timeoutMs }); + const proof = checkProof ? await readSourceVerification(process.env.GITHUB_SHA, api, { failFast: true }) : await watchReleaseSource({ requireProof, timeoutMs, sha: process.env.GITHUB_SHA, runId: Number(process.env.GITHUB_RUN_ID), attempt: Number(process.env.GITHUB_RUN_ATTEMPT), + api, + rerun: createReleaseRerunner(token), + retryRunnerLoss: createRunnerLossRetry({ token }), + cancel: async path => { + const response = await fetch(`https://api.github.com${path}`, { method: "POST", redirect: "error", + headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(30_000) }); + if (!response.ok) throw new Error(`Could not cancel failed-source image work: HTTP ${response.status}.`); + }, + summary: text => process.env.GITHUB_STEP_SUMMARY ? appendFile(process.env.GITHUB_STEP_SUMMARY, text) : Promise.resolve(), + }); + if (checkProof && !proof) throw new Error("Exact-source proof changed before publication."); + if (checkProof && !await readMigratorPublication(process.env.GITHUB_SHA, api)) throw new Error("Exact-source migrator has not published."); + if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `verified=${Boolean(proof)}\n`); + } catch (error) { + console.error(error instanceof GitHubActionsRateLimitError ? `::error title=GitHub API rate limited::${error.message}` : error.message); + process.exitCode = 1; + } }