fix(ci): respect GitHub quota resets during image publication (#22690)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Its image workflow builds immutable images and requires proof for
the exact source.
> - GitHub API quota failures can stop metadata generation and
verification reads.
> - Short retries before the quota reset consume requests without
restoring progress.
> - This pull request removes metadata API reads and makes quota retries
respect server timing and job budgets.
> - The benefit is fewer API requests and clear quota errors without
weakening release proof.

## Linked Issues or Issue Description

Refs #22677, which adds conditional requests for unchanged Actions
polls. This change retains that cache and extends quota recovery.

**What happened?**

[Docker run
45215585951](https://github.com/paperclipai/paperclip/actions/runs/45215585951)
failed in both Docker metadata steps with an installation API rate-limit
error. [Run
45210434846](https://github.com/paperclipai/paperclip/actions/runs/45210434846)
built both architectures but failed during source verification reads.
The reader retried quota-proven HTTP 403 responses after seconds and
then failed with a generic HTTP error. It ignored the primary reset time
and could shorten Retry-After below the server requirement.

**Expected behavior**

Metadata generation should need no GitHub API request. Quota recovery
should wait until GitHub permits another request, within the caller
deadline. Exhausted budgets should identify the quota failure and safe
response-header details. Permission failures must remain immediate.
Missing source, migrator, or attestation proof must still block
publication.

**Steps to reproduce**

1. Return HTTP 403 with zero remaining requests and a reset two minutes
away to the Actions reader.
2. Observe the old reader retry after seconds and exhaust its attempts
before the reset.
3. Return an hour-long Retry-After value. Observe the old reader retry
after its one-minute cap.

**Version**

Master after #22677.

**Deployment mode**

GitHub Actions image publication and release verification.

## What Changed

- Honor primary reset times and Retry-After seconds or dates. Use a
minute-long exponential fallback for secondary throttling without timing
headers.
- Bound the entire wait by a per-read budget and the caller deadline.
Keep permission-denied 403s immediate and preserve ETag caching and
transport retries.
- Emit a typed quota error with allowlisted token-source, resource,
limit, remaining, and reset diagnostics. Do not log tokens, response
bodies, or request URLs.
- Share the Docker observer's 40-minute deadline with its reader. Bound
final proof rechecks to five minutes. Add an explicit `github.token`
source hint beside workflow-issued token bindings.
- Generate Docker tags and OCI labels from checkout and workflow inputs.
Keep release-lane and immutable SHA tags. Feed metadata JSON explicitly
to manifest publication. Stop fetching the GitHub repository
description; keep local license and migration labels.
- Add regression tests and run them in the trusted PR and
source-verification workflows. Document retry budgets and metadata
inputs.

## Verification

- Final acceptance: [CI attempt
3](https://github.com/paperclipai/paperclip/actions/runs/45263398107/attempts/3)
succeeded on `302da8c`. All 68 reported checks are complete, with no
pending or failing checks. Greptile reviewed that exact commit at 5/5
and both review threads are resolved. The voice timeout recovered
without code changes; its earlier cause remains unconfirmed. Prior
failures and local reproduction limits remain below.

- [CI attempt
2](https://github.com/paperclipai/paperclip/actions/runs/45263398107/attempts/2)
recovered the interrupted checks. Its only remaining test failure is
server shard 2/12: `voice-session-store.integration.test.ts`, “retains
both spoken sides once on the public call task and preserves
quarantine,” exceeded 15 seconds on both Vitest attempts. The `ci /
verify` failure is its aggregate. The voice test file is byte-identical
to master and absent from this PR diff; its cause is not established as
an infrastructure fault. A focused local attempt could not start
PostgreSQL because the macOS binary lacks `libzstd.1.dylib`; no voice
test passed locally. Requesting one bounded retry of the affected shard
without code changes; all earlier failures remain recorded here.

- The automatic runner-loss retry helper for the current run failed on a
GitHub job-log download with HTTP 503 ([helper run
45265762243](https://github.com/paperclipai/paperclip/actions/runs/45265762243)).
Once the PR workflow completed, a manual failed-job retry was requested
successfully for unchanged head `302da8c`. Retry results remain pending;
no interrupted check is treated as passed.

- [CI run
45263398107](https://github.com/paperclipai/paperclip/actions/runs/45263398107)
on `302da8c` lost 25 jobs during verification. Inspected the logs for
these 25 jobs: all 25 contain an explicit runner shutdown signal
followed by cancellation, with no additional error records. This
includes Rust, browser, general-server, and serialized-server lanes.
These are interrupted checks and remain unverified until retried.
Greptile reviewed this exact commit at 5/5 with no new findings.

- Combined focused release/metadata and PR policy suite: **1,008 tests
passed**, zero failures. Command: `node --test
scripts/github-actions-rate-limit.test.mjs
scripts/docker-image-metadata.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 scripts/merge-group-image.test.mjs
scripts/__tests__/release-verify-workflow.test.mjs
.github/scripts/tests/*.test.mjs`.
- `pnpm exec vitest run
server/src/services/online-durable-data-migration.test.ts --project
@paperclipai/server`: **32 tests passed** after incorporating upstream
#22686. The final PR diff includes no migration test or runtime change.
- In `packages/paperclip-runner`, `pnpm exec vitest run
src/drivers/acpx/cursor-mode.test.ts
src/drivers/acpx/grok-native-session-options.test.ts --maxWorkers 1`:
**26 tests passed**. This local pass does not explain the earlier CI
timeouts.
- New tests first reproduced ignored primary reset timing, early
Retry-After retries, missing service-error waits, and older-checkout
failures. CLI tests confirm quota exhaustion produces a safe annotation,
no verified output, and no cancellation request. Workflow tests cover
neither, either, and both new test files being present.
- Initial policy CI failed two assertions that expected the old metadata
action and single-file proof test command. Updated them to check both
local metadata steps, the full-SHA tag, and all proof tests. Initial
Greptile findings about service Retry-After and older checkouts are
fixed and resolved.
- [CI attempt
1](https://github.com/paperclipai/paperclip/actions/runs/45259240827/attempts/1)
lost the Build runner and server shards 1, 7, and 12 within four
seconds. Logs explicitly record shutdown signals followed by
cancellation; Build reported no compiler error. Runner lane 2/3 hit
five-second Cursor and Grok test timeouts. E2E shard 2/8 failed document
visibility after outage/reload and the cached-task 404 assertion. Those
test failures are not assumed to be infrastructure faults. Their
aggregate checks also failed. They remain merge blockers until fresh CI
passes.
- Server shard 9 also found a deterministic, pre-existing
blocker-enumeration test failure. Reproduced it on unchanged base
`427d13c38c63`: the source scanner omitted helper-declared blockers.
Upstream #22686 fixes that test. Incorporated its version when updating
from master and removed the duplicate fix from the final diff. A
failed-job retry was accepted after attempt 1 finished; the updated
branch now needs fresh CI.
- Local setup: filtered frozen-lockfile installation changed no
lockfile. Initial server-test startup lacked built plugin SDK output;
`pnpm --filter @paperclipai/plugin-sdk ensure-build-deps` supplied it
before the passing run. Local tests used macOS and Node 25.6.1; CI
checks Linux and its configured Node version.
- `pnpm verify` initially could not start because the fresh worktree
lacked `cli/node_modules/tsx`. The underlying `node
scripts/local-verify.mjs` returned exit 2: workflow changes require
broad CI. No full local Vitest or Docker build was run. Required CI
supplies broad coverage.
- No credentials were changed and no live publication or deployment was
requested. CI retries do not authorize image publication or bypass
proof.

## Risks

- A reset outside the allowed wait still fails closed. Shared repository
quota pressure from other workflows can still delay publication.
- Attestation and source/migrator proof remain required. This change
does not add a privileged token or bypass a check.
- OCI labels now use checkout inputs. The remote repository description
is omitted; source, revision, version, creation time, license, and
schema labels remain available.
- Revert this PR to restore the previous reader and metadata action. No
database or runtime application changes are required.

## Model Used

OpenAI gpt-6.1-sol with xhigh reasoning, through Codex in T3 Code. Used
code editing, GitHub log and upstream action-source inspection, and
local test execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] This is a CI reliability fix; it does not change planned product
scope
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the bug template
- [x] I have not referenced internal or instance-local issues or links
- [x] My branch name describes the change
- [x] I have run focused tests locally and they pass; the broad
verification limitation is recorded
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented risks
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-23 14:39:14 -08:00
1 parent fe2db1c32b
commit bda1bf7b52
13 files changed
+412 -100

No files matched your search

+3 -3
View File
@@ -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;
}
}
+5 -4
View File
@@ -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 () => {
+48
View File
@@ -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`);
}
+92
View File
@@ -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 }); }
});
+124
View File
@@ -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 }); }
});
+60 -36
View File
@@ -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);
}
};
}
+27 -19
View File
@@ -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;
}
}