Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
bump: patch
---

### Changed

- pr-verify's `check-intent` hands its resolved pull request, spec and trusted PR text to
`check-intent-subscription` in one `reads` job output, written before the model runs, so a
handoff no longer repeats the resolver's and select-trusted-text's reads. The subscription job
still runs the trigger gate, whose head must match the carried one, and reads everything again
when the output is missing, malformed, too large, or from another run attempt.
105 changes: 103 additions & 2 deletions .github/scripts/pr-verify/resolve-pr.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
// changed since the head commit (relinkedSince), which sets how long its pass
// lasts (write-verdict.mjs retentionDays).

import { appendFileSync, writeFileSync } from "node:fs";
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
import process from "node:process";
import { fileURLToPath, pathToFileURL } from "node:url";

Expand Down Expand Up @@ -684,7 +684,106 @@ export function specFromBodyApps(text) {
return ids.every((id) => /^[1-9][0-9]*$/.test(id)) ? ids.map(Number) : [];
}

// check-intent's reads, handed to check-intent-subscription in one job output
// so a handoff does not repeat them: written by `carry` from the files and
// outputs of the base-side steps, before the model runs, as base64 JSON. A
// bundle over CARRY_MAX characters is not handed on, so the job output and the
// env var that takes it stay small; the subscription job then reads again.
export const CARRY_MAX = 96_000;
const HEAD_REF = /^[A-Za-z0-9._/-]+$/;
const ATTEMPT = /^[1-9][0-9]{0,4}$/;

export function packReads({ attempt, prNumber, headSha, baseSha, headRef, relinkSinceHead, linkedIssues, specText, context }) {
const packed = Buffer.from(
JSON.stringify({ v: 1, attempt, pr: prNumber, head_sha: headSha, base_sha: baseSha, head_ref: headRef, relink_since_head: relinkSinceHead, linked_issues: linkedIssues, spec_text: specText, context }),
).toString("base64");
return packed.length <= CARRY_MAX ? packed : "";
}

// The carried reads when they hold for this run attempt: a re-run of the
// subscription job alone is a new attempt that keeps check-intent's outputs,
// and what was judged may have changed since, so it reads again. Anything
// malformed is null, never a partial bundle.
export function takeReads(carried, attempt) {
if (String(carried ?? "").length > CARRY_MAX) {
return null;
}
let reads;
try {
reads = JSON.parse(Buffer.from(String(carried ?? ""), "base64").toString("utf8"));
} catch {
return null;
}
const valid =
reads?.v === 1 &&
ATTEMPT.test(String(attempt ?? "")) &&
reads.attempt === String(attempt) &&
Number.isSafeInteger(reads.pr) &&
reads.pr > 0 &&
SHA.test(reads.head_sha ?? "") &&
SHA.test(reads.base_sha ?? "") &&
HEAD_REF.test(reads.head_ref ?? "") &&
(reads.relink_since_head === "true" || reads.relink_since_head === "false") &&
Array.isArray(reads.linked_issues) &&
Array.isArray(reads.spec_text) &&
reads.context !== null &&
typeof reads.context === "object" &&
!Array.isArray(reads.context);
return valid
? { prNumber: reads.pr, headSha: reads.head_sha, baseSha: reads.base_sha, headRef: reads.head_ref, relinkSinceHead: reads.relink_since_head, linkedIssues: reads.linked_issues, specText: reads.spec_text, context: reads.context }
: null;
}

// `carry`: the reads output, from the resolver's outputs and the data files
// it and select-trusted-text wrote; empty when anything is missing.
export function carryMain(env = process.env) {
let packed = "";
try {
packed = packReads({
attempt: String(env.GITHUB_RUN_ATTEMPT ?? ""),
prNumber: Number(env.PR_NUMBER),
headSha: env.HEAD_SHA,
baseSha: env.BASE_SHA,
headRef: env.HEAD_REF,
relinkSinceHead: env.RELINK_SINCE_HEAD,
linkedIssues: JSON.parse(readFileSync(env.SPEC_FILE, "utf8")),
specText: JSON.parse(readFileSync(env.SPEC_TEXT_FILE, "utf8")),
context: JSON.parse(readFileSync(env.CONTEXT_FILE, "utf8")),
});
} catch {
packed = "";
}
// Checked as the taker will, so a bad bundle is never handed on.
if (packed !== "" && takeReads(packed, env.GITHUB_RUN_ATTEMPT) === null) {
packed = "";
}
appendFileSync(env.GITHUB_OUTPUT, `reads=${packed}\n`);
console.log(packed === "" ? "resolve-pr: no reads handed on; a handoff reads again" : `resolve-pr: handed on ${packed.length} characters of reads`);
}

export async function main(env = process.env, { github, fetchImpl } = {}) {
if (env.CARRIED) {
const taken = takeReads(env.CARRIED, env.GITHUB_RUN_ATTEMPT);
if (taken !== null && env.CONTEXT_FILE && env.SPEC_FILE && env.SPEC_TEXT_FILE && env.GITHUB_OUTPUT) {
writeFileSync(env.SPEC_FILE, `${JSON.stringify(taken.linkedIssues, null, 2)}\n`);
writeFileSync(env.SPEC_TEXT_FILE, `${JSON.stringify(taken.specText, null, 2)}\n`);
writeFileSync(env.CONTEXT_FILE, `${JSON.stringify(taken.context, null, 2)}\n`);
const lines = [
"proceed=true",
"reason=carried",
`pr-number=${taken.prNumber}`,
`head-sha=${taken.headSha}`,
`base-sha=${taken.baseSha}`,
`head-ref=${taken.headRef}`,
`relink-since-head=${taken.relinkSinceHead}`,
"carried=true",
Comment thread
kyle-sexton marked this conversation as resolved.
Resolved
];
Comment thread
kyle-sexton marked this conversation as resolved.
Resolved
appendFileSync(env.GITHUB_OUTPUT, `${lines.join("\n")}\n`);
console.log(`resolve-pr: proceed=true reason=carried pr=${taken.prNumber} head=${taken.headSha}`);
return;
}
console.log("resolve-pr: the key job's reads do not hold for this attempt; reading again");
}
for (const key of [
"GITHUB_TOKEN",
"GITHUB_REPOSITORY",
Expand Down Expand Up @@ -771,7 +870,9 @@ export async function main(env = process.env, { github, fetchImpl } = {}) {
console.log(`resolve-pr: proceed=${result.proceed} reason=${result.reason}${result.proceed ? ` pr=${result.prNumber} head=${result.headSha}` : ""}`);
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href && process.argv[2] === "carry") {
carryMain();
} else if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch((error) => {
console.log(`::error::pr-verify could not resolve the pull request: ${error.message}`);
process.exitCode = 1;
Expand Down
116 changes: 115 additions & 1 deletion .github/scripts/pr-verify/resolve-pr.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { test } from "node:test";

import { CONTRACT_STEP, DO_NOT_MERGE_LINE, HOLD_STEP, main, resolvePull } from "./resolve-pr.mjs";
import { CARRY_MAX, carryMain, CONTRACT_STEP, DO_NOT_MERGE_LINE, HOLD_STEP, main, packReads, resolvePull, takeReads } from "./resolve-pr.mjs";
import { artifactName } from "./write-verdict.mjs";
import { bodyVersion, loadRules, REFINE_MARKER, splitItemsLine } from "../intake-triage/admit.mjs";
import { holds, labelHolds } from "../pr-merge/merge-holds.mjs";
Expand Down Expand Up @@ -1511,3 +1511,117 @@ test("FAIL names first and a pass decided before the issue-named lookups give th
assert.equal(await reason(setup), expected, chosen.join("+") || "none");
}
});

// pr-verify.yml's check-intent hands its reads to check-intent-subscription
// (resolve-pr.mjs packReads, takeReads), so a handoff does not repeat them.
const CARRY = {
attempt: "1",
prNumber: 41,
headSha: HEAD,
baseSha: "b".repeat(40),
headRef: "feat/41-carry",
relinkSinceHead: "false",
linkedIssues: [{ number: 7 }],
specText: [{ number: 7, body: "spec" }],
context: { pr: { number: 41 }, items: [], dropped: {} },
};
// A client that fails the test on any read.
const noReads = () => async (method, apiPath) => assert.fail(`no read on the carried path: ${method} ${apiPath}`);

test("the carried reads round-trip for the same run attempt and nothing else", () => {
const packed = packReads(CARRY);
assert.ok(packed.length > 0 && packed.length <= CARRY_MAX);
const { attempt, ...rest } = CARRY;
assert.deepEqual(takeReads(packed, "1"), rest);
// relink-since-head survives as written, both ways.
assert.equal(takeReads(packReads({ ...CARRY, relinkSinceHead: "true" }), "1").relinkSinceHead, "true");
// A re-run of the subscription job alone is a new attempt: it reads again.
assert.equal(takeReads(packed, "2"), null);
assert.equal(takeReads(packed, ""), null);
for (const broken of [
{ headSha: "x" },
{ baseSha: "" },
{ headRef: "a b" },
{ prNumber: 0 },
{ linkedIssues: null },
{ specText: {} },
{ context: [] },
{ relinkSinceHead: "" },
{ relinkSinceHead: "yes" },
{ relinkSinceHead: undefined },
]) {
assert.equal(takeReads(packReads({ ...CARRY, ...broken }), "1"), null, JSON.stringify(broken));
}
assert.equal(takeReads("not base64 json", "1"), null);
assert.equal(takeReads("", "1"), null);
// Too large to hand on: empty, so the subscription job reads again.
assert.equal(packReads({ ...CARRY, context: { pad: "x".repeat(CARRY_MAX) } }), "");
// The taker caps size too, whoever wrote the bundle.
assert.equal(takeReads("A".repeat(CARRY_MAX + 1), "1"), null);
});

test("carry hands on the base-side files, and nothing when one is missing", (t) => {
t.mock.method(console, "log", () => {});
const dir = tempDir("pr-verify-");
const env = {
GITHUB_RUN_ATTEMPT: "1",
GITHUB_OUTPUT: path.join(dir, "out"),
PR_NUMBER: "41",
HEAD_SHA: CARRY.headSha,
BASE_SHA: CARRY.baseSha,
HEAD_REF: CARRY.headRef,
RELINK_SINCE_HEAD: CARRY.relinkSinceHead,
SPEC_FILE: path.join(dir, "spec.json"),
SPEC_TEXT_FILE: path.join(dir, "spec-text.json"),
CONTEXT_FILE: path.join(dir, "context.json"),
};
writeFileSync(env.SPEC_FILE, JSON.stringify(CARRY.linkedIssues));
writeFileSync(env.SPEC_TEXT_FILE, JSON.stringify(CARRY.specText));
carryMain(env);
assert.match(readFileSync(env.GITHUB_OUTPUT, "utf8"), /^reads=\n$/, "no context file");
writeFileSync(env.CONTEXT_FILE, JSON.stringify(CARRY.context));
writeFileSync(env.GITHUB_OUTPUT, "");
carryMain(env);
const reads = /^reads=(.+)$/m.exec(readFileSync(env.GITHUB_OUTPUT, "utf8"))[1];
assert.equal(takeReads(reads, "1").context.pr.number, 41);
// With no relink-since-head output, nothing is handed on.
writeFileSync(env.GITHUB_OUTPUT, "");
carryMain({ ...env, RELINK_SINCE_HEAD: "" });
assert.match(readFileSync(env.GITHUB_OUTPUT, "utf8"), /^reads=\n$/, "no relink-since-head");
});

test("main takes the carried reads with no API read, and reads again when they do not hold", async (t) => {
t.mock.method(console, "log", () => {});
const dir = tempDir("pr-verify-");
const actors = path.join(dir, "trusted-actors.json");
writeFileSync(actors, JSON.stringify({ version: 1, actors: [{ id: 100, login: "maintainer", kind: "human" }] }));
const env = {
GITHUB_TOKEN: "t",
GITHUB_REPOSITORY: REPO,
GITHUB_RUN_ATTEMPT: "1",
GITHUB_OUTPUT: path.join(dir, "out"),
UPSTREAM_RUN_ID: String(RUN),
SPEC_FILE: path.join(dir, "spec.json"),
SPEC_TEXT_FILE: path.join(dir, "spec-text.json"),
CONTEXT_FILE: path.join(dir, "context.json"),
TRUSTED_ACTORS_PATH: actors,
LANE_IDENTITY: LANE,
CARRIED: packReads(CARRY),
};
await main(env, { github: noReads() });
assert.equal(
readFileSync(env.GITHUB_OUTPUT, "utf8"),
`proceed=true\nreason=carried\npr-number=41\nhead-sha=${HEAD}\nbase-sha=${CARRY.baseSha}\nhead-ref=feat/41-carry\nrelink-since-head=false\ncarried=true\n`,
);
assert.deepEqual(JSON.parse(readFileSync(env.SPEC_FILE, "utf8")), CARRY.linkedIssues);
assert.deepEqual(JSON.parse(readFileSync(env.SPEC_TEXT_FILE, "utf8")), CARRY.specText);
assert.deepEqual(JSON.parse(readFileSync(env.CONTEXT_FILE, "utf8")), CARRY.context);
// Another attempt's reads, or none: the full resolver runs on its reads.
for (const carried of [packReads({ ...CARRY, attempt: "2" }), "garbage"]) {
writeFileSync(env.GITHUB_OUTPUT, "");
await main({ ...env, CARRIED: carried }, { github: fake() });
const out = readFileSync(env.GITHUB_OUTPUT, "utf8");
assert.match(out, /^proceed=true\nreason=ok\npr-number=41\n/, carried);
assert.doesNotMatch(out, /carried=true/);
}
});
56 changes: 49 additions & 7 deletions .github/scripts/pr-verify/workflow.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ const FALLBACK_READY = [
' echo "fallback-ready=false" >>"$GITHUB_OUTPUT"',
" fi",
].join("\n");
// check-intent's reads, which the subscription job's resolver takes through
// env only (resolve-pr.mjs takeReads).
const CARRIED = " CARRIED: ${{ needs.check-intent.outputs.reads }}";
const CARRY_ENV = [" CONTEXT_FILE: ${{ github.workspace }}/pr-verify-data/context.json", CARRIED];
const NOT_CARRIED = " && steps.pr.outputs.carried != 'true'";
const KEY_CLASS = "${{ steps.judge.outputs.lane-class == 'credit-stop' && 'rate-limit' || steps.judge.outputs.lane-class }}";
const KEY_REPORT_IF =
"(steps.judge.outcome == 'success' || steps.judge.outcome == 'failure') && (steps.judge.outputs.handoff != 'true' || steps.key-leg.outcome == 'failure')";
Expand Down Expand Up @@ -269,12 +274,13 @@ test("the subscription job runs only on a clean handoff or an empty key, on a fi
// No status function, so GitHub adds success(): a failed key job skips it.
assert.doesNotMatch(gate, /always\(\)|failure\(\)|cancelled\(\)|success\(\)/);
assert.match(job, /^ {4}runs-on: ubuntu-24\.04$/m);
// The key job's outputs reach only that if and the record's fallback
// reason, which they pick between three literals; never a run: script.
// The key job's outputs reach only that if, the resolver's env and the
// record's fallback reason, which they pick between three literals; never a
// run: script.
const steps = job.slice(job.indexOf("\n steps:\n"));
assert.deepEqual(
steps.split("\n").filter((line) => line.includes("needs.")),
[` fallback-reason: ${FALLBACK_REASON}`],
[CARRIED, ` fallback-reason: ${FALLBACK_REASON}`],
);
const key = jobText(KEY);
const outputs = /^ {4}outputs:\n((?: {6}.*\n)+)/m.exec(key)?.[1];
Expand All @@ -285,6 +291,7 @@ test("the subscription job runs only on a clean handoff or an empty key, on a fi
" handoff: ${{ steps.judge.outputs.handoff }}",
" credential-present: ${{ steps.credential.outputs.present }}",
" key-leg-clean: ${{ steps.key-leg.outputs.clean }}",
" reads: ${{ steps.carry.outputs.reads }}",
"",
].join("\n"),
);
Expand Down Expand Up @@ -394,9 +401,11 @@ test("the subscription job repeats the key job's steps but for the credential",
.join("\n");
const normalize = (blocks) =>
blocks
.filter((s) => s.name !== "Check the key leg" && s.name !== "Check the subscription leg")
.filter((s) => s.name !== "Check the key leg" && s.name !== "Check the subscription leg" && s.name !== "Hand the reads on")
.map((s) =>
lines(s.block)
.replace(`\n${CARRY_ENV.join("\n")}`, "")
.replace(`if: steps.agree.outcome == 'success'${NOT_CARRIED}`, "if: steps.agree.outcome == 'success'")
.replace(`\n${FALLBACK_PRESENT}`, "")
.replace(`\n${FALLBACK_READY}`, "")
.replace("\n fallback-ready: ${{ steps.credential.outputs.fallback-ready }}", "")
Expand All @@ -410,16 +419,49 @@ test("the subscription job repeats the key job's steps but for the credential",
.replace(/ && steps\.sub-leg\.outcome != 'success'$/m, ""),
);
assert.deepEqual(normalize(STEPS[SUB]), normalize(STEPS[KEY]));
// The fallback job's credential step reads the fallback token where the
// subscription job's reads the role's.
// The fallback job reads everything again, as the key job does; its
// credential step reads the fallback token where the subscription job's
// reads the role's.
const fallback = STEPS[FB].map((s) => ({
...s,
block: s.block
.replace(`PRESENT: \${{ secrets.${FALLBACK} != '' }}\n SECRET_NAME: ${FALLBACK}`, "PRESENT: ${{ secrets.PR_VERIFY_CLAUDE_CODE_OAUTH_TOKEN != '' }}\n SECRET_NAME: PR_VERIFY_CLAUDE_CODE_OAUTH_TOKEN")
.replace(`fallback-token: \${{ secrets.${FALLBACK} }}`, "subscription-token: ${{ secrets.PR_VERIFY_CLAUDE_CODE_OAUTH_TOKEN }}")
.replace(`\n fallback-reason: ${FB_REASON}`, `\n fallback-reason: ${FALLBACK_REASON}`),
}));
assert.deepEqual(normalize(fallback), normalize(STEPS[SUB]));
assert.deepEqual(normalize(fallback), normalize(STEPS[KEY]));
});

// check-intent hands its reads on only from steps that finish before the
// model runs, and the subscription job takes them only through env, then
// still runs the trigger gate, whose head the agree step compares.
test("the subscription job takes check-intent's pre-judge reads and still runs the trigger gate", () => {
const carry = step("Hand the reads on");
assert.ok(index("Hand the reads on") > index("Select the trusted PR text"), "after the trusted text");
assert.ok(index("Hand the reads on") > index("Assert the gate and the resolver agree"));
assert.ok(index("Hand the reads on") < index("Judge the pull request"), "before the model");
assert.match(carry, /^ {8}if: steps\.agree\.outcome == 'success'$/m);
assert.match(carry, /^ {8}continue-on-error: true$/m);
assert.match(carry, /^ {8}run: node \.base\/\.github\/scripts\/pr-verify\/resolve-pr\.mjs carry$/m);
for (const expression of carry.match(/\$\{\{[^}]*\}\}/g)) {
assert.match(expression, /^\$\{\{ (steps\.pr\.outputs\.[a-z-]+|github\.workspace) \}\}$/, expression);
}
// Every key job output comes from a step before the judge or from the
// launcher's and the key-leg check's own outputs.
const outputs = /^ {4}outputs:\n((?: {6}.*\n)+)/m.exec(jobText(KEY))[1];
assert.match(outputs, /^ {6}reads: \$\{\{ steps\.carry\.outputs\.reads \}\}$/m);
const resolve = step("Resolve the pull request", SUB);
for (const line of CARRY_ENV) assert.ok(resolve.split("\n").includes(line), line);
assert.doesNotMatch(/^ {8}run: \|\n((?: {10}.*\n?)+)/m.exec(resolve)[1], /\$\{\{/);
assert.equal(/^ {8}if: (.*)$/m.exec(step("Select the trusted PR text", SUB))[1], `steps.agree.outcome == 'success'${NOT_CARRIED}`);
for (const name of ["Check the trigger", "Assert the gate and the resolver agree", "Write the diff"]) {
assert.doesNotMatch(step(name, SUB), /carried/, name);
}
for (const job of [KEY, FB]) {
assert.doesNotMatch(jobText(job), /CARRIED|outputs\.carried/, job);
}
assert.equal(index("Hand the reads on", SUB), -1);
assert.equal(index("Hand the reads on", FB), -1);
});

test("the model reads only the data directory, with Read alone, and is told nothing is posted", () => {
Expand Down
Loading
Loading