Files
PaperClipAI/scripts/cloud-release-admission.mjs
T
Devin FoleyandPaperclip 2a8a0b8e18 fix(ci): retry inconsistent release admission listings (#23572)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Core release workflows admit a source revision before running full
verification.
> - Admission discovers an active image or npm release for that exact
revision.
> - One inconsistent GitHub run listing currently fails admission before
tests start.
> - This pull request rereads count mismatches within a fixed retry
budget.
> - Complete listings and fresh canonical run identity remain required.

## Linked Issues or Issue Description

**What happened?**

[Cloud readiness run
47005873736](https://github.com/paperclipai/paperclip/actions/runs/47005873736)
failed candidate admission with `Incomplete release workflow listing.`
This happened before source tests ran. The [image
workflow](https://github.com/paperclipai/paperclip/actions/runs/47005873889)
then canceled itself because source verification failed. Image consumers
could not advance to that revision.

**Expected behavior**

Admission should allow a short, bounded recovery window for an
inconsistent workflow count. It must reject persistently incomplete or
untrusted evidence.

**Steps to reproduce**

Return a workflow listing whose `total_count` differs from the number of
returned runs. Then return a complete listing for the same query. The
original script fails on the first response. The new regression test
requires admission to wait for complete evidence and revalidate the
selected run.

**Paperclip version or commit**

The reported run used `b066a3ddd39123972d0e7f5f9935c83d41303297`. This
fix starts from `6e340a3f962c60e2723c780389db878ce7ff74c7`.

**Deployment mode**

Canonical GitHub Actions master-push release workflows.

Related changes: #18869 introduced release admission; #22677 added
conditional Actions reads; #22690 added quota-aware read retries. I
searched open and closed PRs and issues for admission and
workflow-listing failures. I found no duplicate fix.

## What Changed

- Allow up to three admission listing reads when valid, bounded counts
disagree with the returned run count. Wait one second, then two seconds.
- Include safe workflow and count details if the mismatch persists.
- Preserve strict listing validation and the fresh canonical run check.
Publication and deferred-producer readers retain their existing
single-read behavior.
- Cover recovery for both release consumers, exhausted retries,
overcounts, undercounts, and a run attempt changing before admission.

## Verification

- The new admission regressions fail against the original
implementation.
- `node --test scripts/cloud-source-verification.test.mjs
scripts/github-actions-rate-limit.test.mjs
scripts/docker-image-metadata.test.mjs
.github/scripts/tests/cloud-readiness.test.mjs` — 81 tests pass on the
changed revision.
- `node --check scripts/cloud-release-admission.mjs` and `git diff
--check` pass.
- `pnpm verify --explain` exits 2 as designed: the changed script is a
global CI input. Broad typecheck, test, build, Runner, and browser
checks must run in CI. This is not a full local-suite pass.
- Reviewed the diff and scanned added lines for credentials, personal
paths, and private URLs before pushing. No findings.
- Greptile reviewed `525694ddc75e7f4c4d1e6c2e00fbc9fd15deadd5` at 5/5.
No review threads or actionable comments remain. All underlying
typecheck, build, unit, Runner, serialized-server, and 16 browser shard
checks passed in [CI run
47008128119](https://github.com/paperclipai/paperclip/actions/runs/47008128119)
on `525694ddc75e7f4c4d1e6c2e00fbc9fd15deadd5`. The final [`ci / verify`
aggregate](https://github.com/paperclipai/paperclip/actions/runs/47008128119/job/143921126471)
also passed. All checks are settled with no failures. GitHub reports the
branch clean and mergeable against current master.

## Risks

Low risk. Admission can spend up to six extra seconds across its two
consumer queries. Malformed metadata, oversized listings, and exhausted
mismatches still fail closed. No source proof or publication gate is
relaxed. No database or deployment configuration changes are required.

The original GitHub response was not retained, so its exact invalid
field remains unknown. The regression tests inject count mismatches; a
later healthy master run establishes recovery, but does not prove the
cause of the earlier response.

## Model Used

OpenAI `gpt-6.1-sol` through Codex in T3 Code, with xhigh reasoning and
shell/tool access. The runtime does not report the context window size.
No subagents were used.

## 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] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [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>
2026-12-02 17:26:18 -08:00

154 lines
10 KiB
JavaScript

import { appendFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { pathToFileURL } from "node:url";
import { createActionsReader } from "./github-actions-reader.mjs";
const repository = "paperclipai/paperclip";
const repositoryId = 1170821064;
const workflows = new Set(["docker.yml", "release.yml", "cloud-readiness.yml", "cloud-migrator-artifacts.yml"]);
export const sourceAdmissionJob = "Cloud candidate admission v1";
export const migratorAdmissionJob = "Cloud image candidate admission v1";
function assertSha(sha) {
if (!/^[a-f0-9]{40}$/.test(sha ?? "")) throw new Error("Admission requires a full source SHA.");
}
function trusted(run, sha, workflow) {
return run.workflow_id === workflow.id && run.path === workflow.path && run.head_sha === sha &&
run.repository?.id === repositoryId && run.head_repository?.id === repositoryId &&
run.repository?.full_name === repository && run.head_repository?.full_name === repository &&
run.head_branch === "master" && run.event === "push" &&
Number.isSafeInteger(run.id) && run.id > 0 && Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0;
}
async function producer(file, sha, api, { status, listingAttempts = 1, sleep = delay } = {}) {
assertSha(sha);
if (!workflows.has(file)) throw new Error("Unknown release workflow.");
const workflow = await api(`/repos/${repository}/actions/workflows/${file}`);
if (workflow.path !== `.github/workflows/${file}` || !Number.isSafeInteger(workflow.id) || workflow.id < 1) throw new Error("Release workflow identity mismatch.");
for (let attempt = 1; ; attempt++) {
const list = await api(`/repos/${repository}/actions/workflows/${workflow.id}/runs?branch=master&event=push&head_sha=${sha}&per_page=100${status ? `&status=${status}` : ""}`);
if (!Array.isArray(list.workflow_runs) || !Number.isSafeInteger(list.total_count) || list.total_count < 0 ||
list.total_count > 100) throw new Error("Incomplete release workflow listing.");
if (list.workflow_runs.length !== list.total_count) {
if (attempt >= listingAttempts) throw new Error(`Incomplete release workflow listing for ${file} (${list.workflow_runs.length} returned, ${list.total_count} expected).`);
await sleep(1_000 * attempt);
continue;
}
const run = list.workflow_runs.filter(run => trusted(run, sha, workflow) && (!status || run.status === status)).sort((a, b) => b.id - a.id)[0];
return { workflow, run };
}
}
// A retry is an explicit request for this exact immutable source. Normal push
// work starts only for a candidate admitted by an image build or npm canary.
export async function releaseAdmitted(sha, { api, event = "push", attempt = 1, imageOnly = false, sleep }) {
assertSha(sha);
if (!Number.isSafeInteger(attempt) || attempt < 1) throw new Error("Invalid release attempt.");
if (!["push", "workflow_dispatch"].includes(event)) return false;
if (event === "workflow_dispatch" || (Number.isSafeInteger(attempt) && attempt > 1)) return true;
for (const file of imageOnly ? ["docker.yml"] : ["docker.yml", "release.yml"]) {
const { workflow, run } = await producer(file, sha, api, { status: "in_progress", listingAttempts: 3, sleep });
if (!run) continue;
const current = await api(`/repos/${repository}/actions/runs/${run.id}`);
if (current.id === run.id && trusted(current, sha, workflow) && current.run_attempt === run.run_attempt && current.status === "in_progress") return true;
}
return false;
}
export function deferredProducer(jobs, run, admissionJob) {
const admission = jobs.filter(job => job.name === admissionJob);
const remaining = jobs.filter(job => job.name !== admissionJob);
return run.status === "completed" && run.conclusion === "success" && admission.length === 1 && admission[0].status === "completed" && admission[0].conclusion === "success" && remaining.length > 0 &&
remaining.every(job => job.status === "completed" && job.conclusion === "skipped") &&
jobs.every(job => job.run_id === run.id && job.run_attempt === run.run_attempt && job.head_sha === run.head_sha);
}
async function producerJobs(run, api) {
const jobs = [];
let total;
for (let page = 1; page <= 10; page++) {
const batch = await api(`/repos/${repository}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100&page=${page}`);
if (!Array.isArray(batch.jobs) || !Number.isSafeInteger(batch.total_count) || batch.total_count < 0) throw new Error("Invalid release producer job list.");
if ((total !== undefined && total !== batch.total_count) ||
batch.jobs.length !== Math.min(100, Math.max(0, batch.total_count - (page - 1) * 100))) throw new Error("Incomplete release producer job list.");
total = batch.total_count;
jobs.push(...batch.jobs);
if (page * 100 >= total) return jobs;
}
throw new Error("Incomplete release producer job list.");
}
/** Admission is not publication. The final image gate requires the exact
* canonical migrator publisher, including a fresh read after its job evidence. */
export async function readMigratorPublication(sha, api) {
const { workflow, run } = await producer("cloud-migrator-artifacts.yml", sha, api);
if (!run) return false;
const current = await api(`/repos/${repository}/actions/runs/${run.id}`);
if (current.id !== run.id || !trusted(current, sha, workflow) || current.run_attempt !== run.run_attempt || current.status !== "completed") return false;
if (current.conclusion !== "success") throw new Error("Exact-source migrator publication failed; inspect its workflow before retrying.");
const jobs = await producerJobs(current, api);
if (!jobs.every(job => job.run_id === run.id && job.run_attempt === current.run_attempt && job.head_sha === sha)) return false;
const publish = jobs.filter(job => job.name === "publish");
if (publish.length !== 1 || publish[0].status !== "completed" || publish[0].conclusion !== "success") return false;
const confirmed = await api(`/repos/${repository}/actions/runs/${run.id}`);
return confirmed.id === run.id && trusted(confirmed, sha, workflow) && confirmed.run_attempt === current.run_attempt &&
confirmed.status === "completed" && confirmed.conclusion === "success";
}
// Only skipped admission is restartable here. A failed check or build never
// becomes an automatic retry, and every write revalidates canonical identity.
export async function requestDeferredProducer({ file, sha, admissionJob, api, rerun, requested = new Set() }) {
if (({ "cloud-readiness.yml": sourceAdmissionJob, "cloud-migrator-artifacts.yml": migratorAdmissionJob })[file] !== admissionJob) throw new Error("Unknown deferred producer contract.");
const { workflow, run } = await producer(file, sha, api);
if (!run) return "pending";
const key = `${run.id}/${run.run_attempt}`;
if (requested.has(key)) return "pending";
const jobs = await producerJobs(run, api);
if (run.status !== "completed") {
const current = jobs.filter(job => job.run_id === run.id && job.run_attempt === run.run_attempt && job.head_sha === sha);
// Admission itself succeeds for both outcomes. Only an actual build is
// evidence that its output admitted work; queued jobs may still be skipped.
return current.some(job => job.name !== admissionJob && Number.isSafeInteger(job.runner_id) && job.runner_id > 0 &&
["in_progress", "completed"].includes(job.status) && job.conclusion !== "skipped")
? "admitted" : "pending";
}
if (!deferredProducer(jobs, run, admissionJob)) return "finished";
const current = await api(`/repos/${repository}/actions/runs/${run.id}`);
if (current.id !== run.id || !trusted(current, sha, workflow) || current.run_attempt !== run.run_attempt || current.status !== "completed" || current.conclusion !== "success") return "pending";
try {
await rerun(`/repos/${repository}/actions/runs/${run.id}/rerun`);
} catch (error) {
// Docker and npm may select the same source at the same time. A rejected
// duplicate write is harmless only when a fresh read proves a retry began.
const latest = await api(`/repos/${repository}/actions/runs/${run.id}`);
if (latest.id !== run.id || !trusted(latest, sha, workflow)) throw error;
if (!(latest.run_attempt > run.run_attempt || (latest.run_attempt === run.run_attempt &&
["queued", "in_progress", "requested", "pending", "waiting"].includes(latest.status)))) {
// GitHub may reject a duplicate before its read API shows the retry.
// Leave it pending for the next poll; this is not proof of admission.
if ([409, 422].includes(error.status) && latest.run_attempt === run.run_attempt && latest.status === "completed" && latest.conclusion === "success") return "pending";
throw error;
}
}
requested.add(key);
return "pending";
}
export function createReleaseRerunner(token, fetchImpl = fetch) {
return async path => {
if (!/^\/repos\/paperclipai\/paperclip\/actions\/runs\/[1-9]\d*\/rerun$/.test(path)) throw new Error("Invalid release retry path.");
const response = await fetchImpl(`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 Object.assign(new Error(`Could not admit deferred release work: HTTP ${response.status}.`), { status: response.status });
};
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
if (process.env.GITHUB_REPOSITORY !== repository || process.env.GITHUB_REF !== "refs/heads/master" || !process.env.GITHUB_TOKEN) throw new Error("Canonical master admission context required.");
const admitted = await releaseAdmitted(process.env.GITHUB_SHA, { api: createActionsReader({ token: process.env.GITHUB_TOKEN }),
event: process.env.GITHUB_EVENT_NAME, attempt: Number(process.env.GITHUB_RUN_ATTEMPT), imageOnly: process.argv[2] === "image-only" });
console.log(admitted ? "Release candidate admitted." : "Full build deferred until a release consumer admits this source.");
if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `admitted=${admitted}\n`);
}