Skip to content

Commit 959adde

Browse files
kyle-sextonclaude
andauthored
feat(lane-transcripts): pull one workflow run's transcripts with pull --run (#17534)
No related issue: operator tooling for the lane-transcript sink. It pulls one workflow run on demand; #17261 is complete and closed, and this option only collected its evidence, so no issue remains for it to deliver. ## Summary The scheduled `pull` reads the whole 7-day backlog and stops at its 1,000-call gh budget, so two pulls on 2026-11-19 never reached run 44552939041. `pull --run RUN_ID` pulls just that one run. ## Fix - `--run` is accepted only with `pull` and must be a positive integer; anything else exits 2. - It lists `repos/<repo>/actions/runs/<id>/artifacts` (paged) and takes only the `lane-transcript-*` artifacts, each through the same code as a scheduled pull (`take()`/`store()`, factored out of `pullWithin`): same known, expired, fork and size checks, decrypt, telemetry and rows, and the same key-mismatch failure. - It writes no pull state and prunes nothing, so the scheduled pull's cursors, resume point and last success stay as they were. It exits 1 when an artifact was missed or the run's listing failed. README documents the command. ## Verification - `node --test --test-concurrency=4` on `pull-run.test.mjs`, `pull.test.mjs` and `pull-listing.test.mjs`: 72/72 pass (5 new). - Live `pull --run 44552939041`: 16 transcripts pulled with 18 gh calls, against the 1,000 a full pull spends without reaching the run. All 16 rows have `telemetry_outcome: stored` and `telemetry_joined_spans` > 0. - The scheduled job (provisioning `lane-transcript-pull/pull.sh`) runs only `pull` and `pull-outcomes` with no flags from an export of this directory; no export was removed or changed. ## Related - #17261 (closed): this option pulled the run whose stored telemetry rows met its completion check. This PR delivers no part of that issue. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01KeBVgaQE4QB75SPD3ky1jd Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 4433fa3 commit 959adde

4 files changed

Lines changed: 201 additions & 33 deletions

File tree

‎scripts/lane-transcripts/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ It runs four times a night on the laptop. Needs Node 22 or later, `gh` signed in
77

88
```bash
99
vault-exec --env LANE_TRANSCRIPT_PRIVATE_KEY=lane-transcript-private-key -- node scripts/lane-transcripts/pull.mjs pull
10+
vault-exec --env LANE_TRANSCRIPT_PRIVATE_KEY=lane-transcript-private-key -- node scripts/lane-transcripts/pull.mjs pull --run RUN_ID
1011
node scripts/lane-transcripts/pull.mjs status
1112
node scripts/lane-transcripts/pull.mjs query --lane pr-verify --model opus --outcome success --since 2026-11-01
1213
node scripts/lane-transcripts/pull.mjs prune
@@ -17,6 +18,7 @@ node scripts/lane-transcripts/pull.mjs backfill
1718
| Command | Does | Exit |
1819
|---|---|---|
1920
| `pull` | Copies every new `lane-transcript-*` artifact, then prunes | 0 done, including one that missed an artifact; 1 failed, and `ALERT:` on stderr when no pull succeeded in 5 days (a pull that missed an artifact and is that stale exits 1 too), or when a budget-stopped backlog is over 5 days old. A stale `pull-outcomes` prints its `ALERT:` here too but does not change this exit code, so a timer that chains the two still reaches it |
21+
| `pull --run RUN-ID` | Copies that one workflow run's `lane-transcript-*` artifacts, listed from the run itself, with the same checks and rows as `pull`; writes no pull state and prunes nothing, so the scheduled pull's cursors and resume point stay as they were | 0 done; 1 when an artifact was missed or the run's listing failed |
2022
| `status` | Prints the last successful pull, its age, and the store's size and counts as JSON | 1 and `ALERT:` when no pull succeeded in 5 days, or a budget-stopped backlog is over 5 days old; the same two checks apply to `pull-outcomes` once it has run |
2123
| `query` | Prints the metrics rows matching every filter given, as JSONL with the transcript's absolute path | 0 |
2224
| `prune` | Applies retention alone | 0 |

‎scripts/lane-transcripts/pull-fixtures.mjs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@ export function fakeDeps(artifacts, { now = NOW, runs = {}, failures = {}, workf
4747
const page = artifacts.filter((a) => a.name === m[1]).slice((Number(m[2]) - 1) * 100, Number(m[2]) * 100);
4848
return Buffer.from(JSON.stringify({ artifacts: page.map(({ zip, ...a }) => a) }));
4949
}
50+
m = /actions\/runs\/(\d+)\/artifacts\?per_page=100&page=(\d+)$/.exec(url);
51+
if (m) {
52+
const page = artifacts.filter((a) => String(a.workflow_run.id) === m[1]).slice((Number(m[2]) - 1) * 100, Number(m[2]) * 100);
53+
return Buffer.from(JSON.stringify({ artifacts: page.map(({ zip, ...a }) => a) }));
54+
}
5055
m = /actions\/workflows\/([^/]+)\/runs\?per_page=100$/.exec(url);
5156
if (m) return Buffer.from(JSON.stringify({ workflow_runs: workflowRuns[m[1]] ?? [] }));
5257
m = /actions\/artifacts\/(\d+)\/zip$/.exec(url);
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import assert from "node:assert/strict";
2+
import { readFileSync } from "node:fs";
3+
import { test } from "node:test";
4+
import { gzipSync } from "node:zlib";
5+
6+
import { generate } from "../../.github/actions/open-lane-output/keygen.mjs";
7+
import { parsePublicKey, sealRecord } from "../../.github/actions/seal-lane-output/seal.mjs";
8+
import { ENTRY, TELEMETRY_ENTRY, TELEMETRY_PAYLOAD } from "./pull.mjs";
9+
import { artifact, fakeDeps, iso, MARKER, NOW, run, sealed, seedState, sinkDir } from "./pull-fixtures.mjs";
10+
import { paths, readRows, traceIdOf } from "./store.mjs";
11+
process.env.GIT_CONFIG_GLOBAL ??= "/dev/null";
12+
process.env.GIT_CONFIG_NOSYSTEM = "1";
13+
14+
const telemetry = (publicLine, runId, jobId) => {
15+
const spans = [traceIdOf(runId, 1), "0".repeat(32)].map((traceId, i) => ({ traceId, spanId: `${i}`.padStart(16, "0"), name: MARKER }));
16+
return sealRecord(parsePublicKey(publicLine), TELEMETRY_PAYLOAD, gzipSync(Buffer.from(`${JSON.stringify({ resourceSpans: [{ scopeSpans: [{ spans }] }] })}\n`)), String(runId), jobId);
17+
};
18+
19+
function runArtifacts(publicLine) {
20+
const withTelemetry = (id, runId, jobId) => artifact(id, { runId, jobId, entries: { [ENTRY]: sealed(publicLine, { runId, jobId }), [TELEMETRY_ENTRY]: telemetry(publicLine, runId, jobId) } });
21+
return [
22+
withTelemetry(1, 77, "assess-units-a1"),
23+
withTelemetry(2, 77, "judge-a1"),
24+
{ ...artifact(3, { runId: 77, record: "x" }), name: "unit-findings-a1" },
25+
withTelemetry(4, 78, "assess-units-a1"),
26+
];
27+
}
28+
29+
const keyEnv = (privateText) => ({ LANE_TRANSCRIPT_PRIVATE_KEY: privateText });
30+
31+
test("pull --run stores only that run's transcripts and telemetry, listing only its artifacts, with the rows a pull writes", () => {
32+
const { publicLine, privateText } = generate();
33+
const artifacts = runArtifacts(publicLine);
34+
const sink = sinkDir();
35+
const deps = fakeDeps(artifacts);
36+
const result = run(["pull", "--run", "77", "--sink", sink], { env: keyEnv(privateText), deps });
37+
assert.equal(result.code, 0, result.err);
38+
for (const text of [result.out, result.err]) assert.ok(!text.includes(MARKER) && !text.includes(privateText));
39+
assert.match(result.out, /pulled 2 transcript\(s\) from run 77; skipped \{"pulled":2,"known":0,"fork":0,"expired":0,"unnamed":0,/);
40+
assert.match(result.out, /gh calls: 4 of 1000/);
41+
assert.ok(deps.calls.every((c) => !c.includes("actions/artifacts?") && !c.includes("/workflows/")), "no name listing and no workflow run listing");
42+
assert.ok(!deps.calls.some((c) => c.includes("artifacts/3/zip") || c.includes("artifacts/4/zip")), "another artifact of the run, and another run's, are not downloaded");
43+
const rows = readRows(sink);
44+
assert.deepEqual(rows.map((r) => [r.artifact_id, r.run_id, r.telemetry_outcome, r.telemetry_joined_spans]), [[1, 77, "stored", 1], [2, 77, "stored", 1]]);
45+
46+
const full = sinkDir();
47+
const fullDeps = fakeDeps(artifacts.filter((a) => a.workflow_run.id === 77 && a.id !== 3));
48+
assert.equal(run(["pull", "--sink", full], { env: keyEnv(privateText), deps: fullDeps }).code, 0);
49+
assert.deepEqual(rows, readRows(full).sort((a, b) => a.artifact_id - b.artifact_id));
50+
});
51+
52+
test("pull --run leaves the pull's state byte for byte, and a second run skips what it holds", () => {
53+
const { publicLine, privateText } = generate();
54+
const sink = sinkDir();
55+
seedState(sink, { last_success_at: iso(NOW - 3600_000), resume_cutoff_at: iso(NOW - 2 * 86400_000), resume_name: "lane-transcript-judge-a1-1", budget_exhausted: true, cursors: { "lane-transcript-judge-a1-1": iso(NOW - 7200_000) } });
56+
const before = readFileSync(paths(sink).state, "utf8");
57+
assert.equal(run(["pull", "--run", "77", "--sink", sink], { env: keyEnv(privateText), deps: fakeDeps(runArtifacts(publicLine)) }).code, 0);
58+
assert.equal(readFileSync(paths(sink).state, "utf8"), before);
59+
const deps = fakeDeps(runArtifacts(publicLine));
60+
const again = run(["pull", "--run", "77", "--sink", sink], { env: keyEnv(privateText), deps });
61+
assert.equal(again.code, 0, again.err);
62+
assert.match(again.out, /"pulled":0,"known":2/);
63+
assert.ok(!deps.calls.some((c) => c.includes("/zip")), "a held artifact is not downloaded again");
64+
assert.equal(readRows(sink).length, 2);
65+
});
66+
67+
test("pull --run skips a fork's artifact and fails when every transcript is sealed to another key", () => {
68+
const { publicLine, privateText } = generate();
69+
const fork = run(["pull", "--run", "42", "--sink", sinkDir()], { env: keyEnv(privateText), deps: fakeDeps([artifact(5, { record: sealed(publicLine), fork: true })]) });
70+
assert.equal(fork.code, 0, fork.err);
71+
assert.match(fork.out, /"pulled":0,"known":0,"fork":1/);
72+
const other = generate();
73+
const mismatch = run(["pull", "--run", "42", "--sink", sinkDir()], { env: keyEnv(privateText), deps: fakeDeps([artifact(6, { record: sealed(other.publicLine) })]) });
74+
assert.equal(mismatch.code, 1);
75+
assert.match(mismatch.err, /pull failed: key-mismatch: 1 transcript/);
76+
});
77+
78+
test("pull --run exits 1 on a missed artifact or a failed listing, naming the kind only and writing no state", () => {
79+
const { publicLine, privateText } = generate();
80+
const sink = sinkDir();
81+
const missed = run(["pull", "--run", "42", "--sink", sink], { env: keyEnv(privateText), deps: { ...fakeDeps([artifact(7, { record: sealed(publicLine) })], { failures: { "artifacts/7/zip": 5 } }), ghDelayMs: 0 } });
82+
assert.equal(missed.code, 1);
83+
assert.match(missed.out, /"fetch_failed":1/);
84+
const listing = run(["pull", "--run", "42", "--sink", sink], { env: keyEnv(privateText), deps: { ...fakeDeps([], { failures: { "artifacts?per_page=100&page=1": 10 } }), ghDelayMs: 0 } });
85+
assert.equal(listing.code, 1);
86+
assert.match(listing.err, /^pull failed: run-artifact-list: gh exited 1\n$/);
87+
assert.ok(!listing.err.includes(MARKER));
88+
assert.throws(() => readFileSync(paths(sink).state), { code: "ENOENT" });
89+
});
90+
91+
test("--run takes a run id, and only on pull", () => {
92+
for (const argv of [["pull", "--run", "abc"], ["pull", "--run", "0"], ["pull", "--run", "-1"], ["status", "--run", "77"], ["query", "--run", "77"], ["pull", "--run", "1", "--run", "2"]]) {
93+
assert.equal(run(argv, { deps: fakeDeps([]) }).code, 2, argv.join(" "));
94+
}
95+
});

‎scripts/lane-transcripts/pull.mjs‎

Lines changed: 99 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ const OUTCOME_FIRST_DAYS = 30;
169169

170170
const COMMANDS = ["pull", "pull-outcomes", "backfill", "status", "query", "prune"];
171171
const USAGE = `usage: pull.mjs <${COMMANDS.join("|")}> [--sink DIR] [--repo OWNER/REPO]
172+
pull: [--run RUN-ID] pulls only that workflow run's transcripts and leaves the pull's cursors as they are
172173
query filters: [--lane LANE[/JOB]] [--model TEXT] [--outcome OUTCOME] [--class FAILURE-CLASS] [--trace TRACE-ID] [--since YYYY-MM-DD] [--until YYYY-MM-DD]`;
173174

174175
export class UsageError extends Error {}
@@ -184,12 +185,13 @@ export function parseArgs(argv) {
184185
const [command, ...rest] = argv;
185186
if (!COMMANDS.includes(command)) throw new UsageError(USAGE);
186187
const flags = {};
187-
const names = new Set(["sink", "repo", "lane", "model", "outcome", "class", "trace", "since", "until"]);
188+
const names = new Set(["sink", "repo", "run", "lane", "model", "outcome", "class", "trace", "since", "until"]);
188189
for (let i = 0; i < rest.length; i += 2) {
189190
const name = /^--([a-z]+)$/.exec(rest[i])?.[1];
190191
if (!names.has(name) || rest[i + 1] === undefined || name in flags) throw new UsageError(USAGE);
191192
flags[name] = rest[i + 1];
192193
}
194+
if ("run" in flags && (command !== "pull" || !/^[1-9]\d*$/.test(flags.run))) throw new UsageError(USAGE);
193195
return { command, flags };
194196
}
195197

@@ -329,15 +331,11 @@ function pullWithin({ sink, repo, recipient, deps, log }) {
329331
const cursor = Date.parse(cursors[name] ?? "");
330332
return Math.max(floor, Number.isNaN(cursor) ? since : cursor - OVERLAP);
331333
};
332-
const known = new Set(readRows(sink).map((row) => row.artifact_id));
333-
const byTrace = outcomesByTrace(readOutcomes(sink));
334-
const tally = { pulled: 0, known: 0, fork: 0, expired: 0, unnamed: 0, too_large: 0, bad_zip: 0, sealed_mismatch: 0, fetch_failed: 0 };
335-
const failedKinds = new Set();
336-
const failedNames = new Set();
334+
const ctx = takeContext(sink, recipient, repo, deps, now);
335+
const { tally, failedKinds, failedNames } = ctx;
337336
let exhausted = false;
338337
const at = { name: state.resume_name ?? null };
339338
writeState(sink, { ...state, last_attempt_at: new Date(now).toISOString() });
340-
let runs = new Map();
341339
const dueWith = (attempts) => (name) => {
342340
const { attempt, workflows } = SOURCES.get(name);
343341
const listedAt = Date.parse(cursors[name] ?? "");
@@ -349,36 +347,13 @@ function pullWithin({ sink, repo, recipient, deps, log }) {
349347

350348
try {
351349
const recent = recentRuns(deps, repo);
352-
runs = recent.byId;
353-
for (const artifact of listed(deps, repo, { due: dueWith(recent.attempts), cutoffOf, at, onListed })) {
354-
const named = parseArtifactName(artifact.name);
355-
const wf = artifact.workflow_run ?? {};
356-
if (!named) tally.unnamed++;
357-
else if (known.has(artifact.id)) tally.known++;
358-
else if (artifact.expired) tally.expired++;
359-
// The public key is public: a fork's run could seal a record of its own.
360-
else if (!wf.id || wf.head_repository_id !== wf.repository_id) tally.fork++;
361-
else if (artifact.size_in_bytes > MAX_SEALED) tally.too_large++;
362-
else {
363-
try {
364-
const outcome = store({ sink, repo, recipient, deps, artifact, named, runs, byTrace, now });
365-
tally[outcome]++;
366-
if (outcome === "pulled") known.add(artifact.id);
367-
} catch (error) {
368-
if (!(error instanceof FetchFailed)) throw error;
369-
tally.fetch_failed++;
370-
failedKinds.add(error.message);
371-
failedNames.add(artifact.name);
372-
}
373-
}
374-
}
350+
ctx.runs = recent.byId;
351+
for (const artifact of listed(deps, repo, { due: dueWith(recent.attempts), cutoffOf, at, onListed })) take(ctx, artifact);
375352
} catch (error) {
376353
if (!(error instanceof BudgetSpent)) throw error;
377354
exhausted = true;
378355
}
379-
// Every candidate sealed to another key and none opened: the vault key does
380-
// not match the repository variable, which must alert, not pass.
381-
if (tally.sealed_mismatch > 0 && tally.pulled === 0 && tally.known === 0) throw new PullError(`key-mismatch: ${tally.sealed_mismatch} transcript(s) did not open for this key and none did`);
356+
failIfKeyMismatch(tally);
382357
const pruned = prune(sink, now);
383358
const finished = tally.fetch_failed > 0 ? { last_error: `fetch-failed: ${tally.fetch_failed} transcript(s) (${[...failedKinds].join(", ")})` } : { last_success_at: new Date(now).toISOString(), last_error: null, resume_cutoff_at: null };
384359
if (exhausted) finished.resume_cutoff_at = new Date(Math.min(...TRANSCRIPT_NAMES.map(cutoffOf))).toISOString();
@@ -387,6 +362,89 @@ function pullWithin({ sink, repo, recipient, deps, log }) {
387362
return tally;
388363
}
389364

365+
/** What taking an artifact reads and counts: the rows and outcomes held, the runs read, the tally. */
366+
function takeContext(sink, recipient, repo, deps, now) {
367+
return {
368+
sink,
369+
repo,
370+
recipient,
371+
deps,
372+
now,
373+
known: new Set(readRows(sink).map((row) => row.artifact_id)),
374+
byTrace: outcomesByTrace(readOutcomes(sink)),
375+
runs: new Map(),
376+
tally: { pulled: 0, known: 0, fork: 0, expired: 0, unnamed: 0, too_large: 0, bad_zip: 0, sealed_mismatch: 0, fetch_failed: 0 },
377+
failedKinds: new Set(),
378+
failedNames: new Set(),
379+
};
380+
}
381+
382+
/**
383+
* One listed artifact: skipped and counted, or stored. A fork's run is
384+
* skipped because the public key is public: it could seal a record of its own.
385+
*/
386+
function take(ctx, artifact) {
387+
const { tally, known } = ctx;
388+
const named = parseArtifactName(artifact.name);
389+
const wf = artifact.workflow_run ?? {};
390+
if (!named) tally.unnamed++;
391+
else if (known.has(artifact.id)) tally.known++;
392+
else if (artifact.expired) tally.expired++;
393+
else if (!wf.id || wf.head_repository_id !== wf.repository_id) tally.fork++;
394+
else if (artifact.size_in_bytes > MAX_SEALED) tally.too_large++;
395+
else {
396+
try {
397+
const outcome = store({ ...ctx, artifact, named });
398+
tally[outcome]++;
399+
if (outcome === "pulled") known.add(artifact.id);
400+
} catch (error) {
401+
if (!(error instanceof FetchFailed)) throw error;
402+
tally.fetch_failed++;
403+
ctx.failedKinds.add(error.message);
404+
ctx.failedNames.add(artifact.name);
405+
}
406+
}
407+
}
408+
409+
/**
410+
* Every candidate sealed to another key and none opened: the vault key does
411+
* not match the repository variable, which must alert, not pass.
412+
*/
413+
function failIfKeyMismatch(tally) {
414+
if (tally.sealed_mismatch > 0 && tally.pulled === 0 && tally.known === 0) throw new PullError(`key-mismatch: ${tally.sealed_mismatch} transcript(s) did not open for this key and none did`);
415+
}
416+
417+
/**
418+
* One workflow run's transcripts, listed from that run's own artifacts and
419+
* taken as a pull takes them. It writes no state and prunes nothing, so the
420+
* scheduled pull's cursors, resume point and last success stay as they were.
421+
*/
422+
export function pullRun({ sink, repo, recipient, deps, log, runId }) {
423+
const meter = { calls: 0, budget: deps.ghCallBudget ?? GH_CALL_BUDGET };
424+
try {
425+
return pullRunWithin({ sink, repo, recipient, deps: { ...deps, meter }, log, runId });
426+
} finally {
427+
log(`gh calls: ${meter.calls} of ${meter.budget}`);
428+
}
429+
}
430+
431+
function pullRunWithin({ sink, repo, recipient, deps, log, runId }) {
432+
for (const dir of [sink, paths(sink).transcripts, paths(sink).tmp]) ensureDir(dir);
433+
const ctx = takeContext(sink, recipient, repo, deps, deps.now());
434+
try {
435+
for (let page = 1; ; page++) {
436+
const { artifacts = [] } = json(ghRetried(deps, ["api", `repos/${repo}/actions/runs/${runId}/artifacts?per_page=${PER_PAGE}&page=${page}`], true));
437+
for (const artifact of artifacts) if (String(artifact.name).startsWith("lane-transcript-")) take(ctx, artifact);
438+
if (artifacts.length < PER_PAGE) break;
439+
}
440+
} catch (error) {
441+
throw error instanceof BudgetSpent ? new PullError(`budget-spent: stopped at the gh call budget of ${deps.meter.budget}`) : error;
442+
}
443+
failIfKeyMismatch(ctx.tally);
444+
log(`pulled ${ctx.tally.pulled} transcript(s) from run ${runId}; skipped ${JSON.stringify(ctx.tally)}`);
445+
return ctx.tally;
446+
}
447+
390448
function store({ sink, repo, recipient, deps, artifact, named, runs, byTrace, now }) {
391449
const runId = String(artifact.workflow_run.id);
392450
const records = sealedRecords(deps, sink, fetched("artifact-zip", () => ghRetried(deps, ["api", `repos/${repo}/actions/artifacts/${artifact.id}/zip`])));
@@ -768,6 +826,14 @@ export function main(argv = process.argv.slice(2), env = process.env, deps = und
768826
io.err(`${error instanceof OpenError ? error.message : "no-key"}; set LANE_TRANSCRIPT_PRIVATE_KEY through vault-exec\n`);
769827
return 1;
770828
}
829+
if (flags.run) {
830+
try {
831+
return pullRun({ sink, repo: flags.repo ?? REPO, recipient, deps: d, log: (s) => io.out(`${s}\n`), runId: flags.run }).fetch_failed > 0 ? 1 : 0;
832+
} catch (error) {
833+
io.err(`pull failed: ${failureKind(error, "run-artifact-list")}\n`);
834+
return 1;
835+
}
836+
}
771837
try {
772838
// A complete pull is fresh; one that missed an artifact or stopped at its
773839
// budget is stale once its kept window is.

0 commit comments

Comments
 (0)