Skip to content

Commit fe72cfb

Browse files
authored
Count daily AI credits per reusable workflow call (#80036)
1 parent 444ac7e commit fe72cfb

14 files changed

Lines changed: 210 additions & 116 deletions

‎.github/workflows/agy-conformance-reusable.lock.yml‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.github/workflows/smoke-copilot-dynamic-workflow.lock.yml‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.github/workflows/smoke-workflow-call-with-inputs.lock.yml‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.github/workflows/smoke-workflow-call.lock.yml‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.github/workflows/windows.lock.yml‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎actions/setup/js/check_daily_aic_workflow_guardrail.cjs‎

Lines changed: 58 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ const { parsePositiveCompactNumber } = require("./numeric_limits.cjs");
1313
const { getErrorMessage } = require("./error_helpers.cjs");
1414
const { createRateLimitAwareGithub } = require("./github_rate_limit_logger.cjs");
1515
const { scanDailyAIC } = require("./daily_aic_scan.cjs");
16-
const { DAILY_AIC_QUOTA_BLOCKED_ENV, API_READ_OPERATIONS, createAPIBudget, retryNotBefore, safeResponseHeaders, isQuotaError, getAPIReadFailure } = require("./daily_aic_api_budget.cjs");
16+
const { DAILY_AIC_QUOTA_BLOCKED_ENV, API_READ_OPERATIONS, createAPIBudget, retryNotBefore, safeResponseHeaders, isQuotaError, getAPIReadFailure, getErrorStatus } = require("./daily_aic_api_budget.cjs");
1717
const { GITHUB_API_QUOTA_EXHAUSTED, getGitHubAPIQuotaExhaustion, formatGitHubAPIQuotaDetails, writeGitHubAPIQuotaSummary } = require("./github_api_quota.cjs");
1818
const { getGitHubAPIDiagnostic } = require("./github_api_diagnostics.cjs");
19-
const { loadBillableJobs, allBillableJobsNotStarted, allBillableJobsSkipped, sumCoveredComponents } = require("./daily_aic_component_coverage.cjs");
19+
const { loadBillableJobs, allBillableJobsNotStarted, allBillableJobsSkipped, invocationUsageArtifactName, sumCoveredComponents } = require("./daily_aic_component_coverage.cjs");
2020
const { readLedgerEntries, readLedgerCoverageStart, WINDOW_MS } = require("./daily_aic_repo_memory_ledger.cjs");
2121

2222
const PRIMARY_GUARDRAIL_ARTIFACT_NAMES = ["usage"];
@@ -241,7 +241,7 @@ function inspectLegacyAgentLog(logText) {
241241
};
242242
}
243243

244-
async function inspectLegacyAgentArtifact(artifactClient, artifacts, downloadRoot, token, owner, repo, run, components) {
244+
async function inspectLegacyAgentArtifact(artifactClient, artifacts, downloadRoot, token, owner, repo, run, components, usageArtifactName) {
245245
const job = components.get("agent");
246246
const noEvidence = { artifactInspected: false, preHarnessFailure: false, sampleReplay: false };
247247
if (!job) return noEvidence;
@@ -255,7 +255,7 @@ async function inspectLegacyAgentArtifact(artifactClient, artifacts, downloadRoo
255255
}
256256
}
257257

258-
const artifact = artifacts.find(item => item?.name === "agent");
258+
const artifact = artifacts.find(item => item?.name === usageArtifactName.slice(0, -"usage".length) + "agent");
259259
const createdAt = artifact?.createdAt?.getTime();
260260
const startedAt = Date.parse(job.started_at);
261261
const completedAt = Date.parse(job.completed_at);
@@ -301,26 +301,30 @@ async function inspectLegacyAgentArtifact(artifactClient, artifacts, downloadRoo
301301
* @returns {Promise<number>}
302302
*/
303303
async function getRunAIC(artifactClient, runId, token, owner, repo, run, inspection) {
304-
const { components, priorJobs } = run ? await loadBillableJobs(inspection, owner, repo, run) : { components: null, priorJobs: null };
305-
if (components && allBillableJobsNotStarted(components)) {
304+
const invocations = run ? await loadBillableJobs(inspection, owner, repo, run) : null;
305+
const executed = invocations?.filter(({ components }) => !allBillableJobsNotStarted(components));
306+
if (invocations && executed?.length === 0) {
306307
inspection.accountingReason = "confirmed_zero";
307-
for (const [component, job] of components) {
308-
core.info(
309-
`[daily-workflow-aic] Computed component AIC: ${JSON.stringify({
310-
runId,
311-
component,
312-
jobId: job.id,
313-
runAttempt: job.run_attempt,
314-
conclusion: job.conclusion,
315-
aic: 0,
316-
reason: job.conclusion === "skipped" ? "job_skipped" : "runner_not_assigned",
317-
})}`
318-
);
308+
for (const { components, label } of invocations) {
309+
for (const [component, job] of components) {
310+
core.info(
311+
`[daily-workflow-aic] Computed component AIC: ${JSON.stringify({
312+
runId,
313+
component,
314+
invocation: label,
315+
jobId: job.id,
316+
runAttempt: job.run_attempt,
317+
conclusion: job.conclusion,
318+
aic: 0,
319+
reason: job.conclusion === "skipped" ? "job_skipped" : "runner_not_assigned",
320+
})}`
321+
);
322+
}
319323
}
320324
logDailyGuardrail("Computed run AIC", {
321325
runId,
322326
aic: 0,
323-
reason: components.size === 0 ? "no_billable_jobs" : allBillableJobsSkipped(components) ? "all_billable_jobs_skipped" : "all_billable_jobs_not_started",
327+
reason: invocations.length === 0 ? "no_billable_jobs" : invocations.every(({ components }) => allBillableJobsSkipped(components)) ? "all_billable_jobs_skipped" : "all_billable_jobs_not_started",
324328
});
325329
return 0;
326330
}
@@ -346,7 +350,36 @@ async function getRunAIC(artifactClient, runId, token, owner, repo, run, inspect
346350
artifacts: artifactSummaries,
347351
});
348352

349-
const artifact = artifacts.find(item => item?.name && matchesGuardrailArtifactName(item.name));
353+
if (!invocations) {
354+
const artifact = artifacts.find(item => item?.name && matchesGuardrailArtifactName(item.name));
355+
return readUsageArtifactAIC(artifactClient, artifact, artifacts, runId, token, owner, repo, null, null, artifactSummaries);
356+
}
357+
358+
let total = 0;
359+
const usedArtifacts = new Set();
360+
// An old hash-based artifact has no invocation identity. Only use that
361+
// format with a single recognized invocation, never to fill a missing call.
362+
const legacyArtifact = invocations.length === 1 ? artifacts.find(item => item?.name && !/^call-[1-9]\d*-usage$/.test(item.name) && matchesGuardrailArtifactName(item.name)) : null;
363+
for (const invocation of executed || []) {
364+
try {
365+
const name = invocationUsageArtifactName(invocation);
366+
const artifact = (name && artifacts.find(item => item?.name === name)) || (invocation.prefix ? legacyArtifact : artifacts.find(item => item?.name === "usage") || legacyArtifact);
367+
if (artifact?.id && usedArtifacts.has(artifact.id)) throw new Error(`Usage artifact ${artifact.id} is already assigned to another call`);
368+
total += await readUsageArtifactAIC(artifactClient, artifact, artifacts, runId, token, owner, repo, run, invocation, artifactSummaries);
369+
if (artifact?.id) usedArtifacts.add(artifact.id);
370+
} catch (error) {
371+
if (getErrorStatus(error) || isQuotaError(error) || getAPIReadFailure(error) || safeResponseHeaders(error?.response?.headers)["retry-after"] != null) {
372+
logDailyGuardrail("Invocation accounting unresolved", { runId, invocation: invocation.label, error: getErrorMessage(error) });
373+
throw error;
374+
}
375+
throw new Error(`Daily AIC unresolved for ${invocation.label}: ${getErrorMessage(error)}`, { cause: error });
376+
}
377+
}
378+
if (!Number.isFinite(total)) throw new Error("Daily AIC invocation total is not finite");
379+
return total;
380+
}
381+
382+
async function readUsageArtifactAIC(artifactClient, artifact, artifacts, runId, token, owner, repo, run, invocation, artifactSummaries) {
350383
if (!artifact) {
351384
if (run) {
352385
throw new Error(`No usage artifact proves AIC for completed run ${runId}; check artifact upload and retention`);
@@ -394,9 +427,6 @@ async function getRunAIC(artifactClient, runId, token, owner, repo, run, inspect
394427
});
395428

396429
const usageJSONLFiles = findJSONLFiles(download.downloadPath || downloadRoot);
397-
if (run && !components && usageJSONLFiles.length === 0) {
398-
throw new Error(`Usage artifact contains no accounting records for run ${runId}`);
399-
}
400430
logDailyGuardrail("Downloaded guardrail artifact", {
401431
runId,
402432
artifactId: artifact.id,
@@ -405,13 +435,15 @@ async function getRunAIC(artifactClient, runId, token, owner, repo, run, inspect
405435
usageJSONLFiles,
406436
});
407437
const artifactRoot = download.downloadPath || downloadRoot;
408-
const legacyAgentEvidence = components ? await inspectLegacyAgentArtifact(artifactClient, artifacts, artifactRoot, token, owner, repo, run, components) : null;
409-
const aic = components ? sumCoveredComponents(artifactRoot, components, artifact.createdAt.getTime(), artifacts, artifact.name, run.run_attempt, run.id, legacyAgentEvidence, priorJobs) : sumAICFromUsageJSONLFiles(usageJSONLFiles);
438+
const legacyAgentEvidence = invocation ? await inspectLegacyAgentArtifact(artifactClient, artifacts, artifactRoot, token, owner, repo, run, invocation.components, artifact.name) : null;
439+
const aic = invocation
440+
? sumCoveredComponents(artifactRoot, invocation.components, artifact.createdAt.getTime(), artifacts, artifact.name, run.run_attempt, run.id, legacyAgentEvidence, invocation.priorJobs)
441+
: sumAICFromUsageJSONLFiles(usageJSONLFiles);
410442
logDailyGuardrail("Computed run AIC from artifact", {
411443
runId,
412444
artifactId: artifact.id,
413445
aic,
414-
reason: components ? "covered_components" : "usage_files",
446+
reason: invocation ? "covered_components" : "usage_files",
415447
});
416448
return aic;
417449
} catch (error) {

‎actions/setup/js/daily_aic_component_coverage.cjs‎

Lines changed: 61 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -18,26 +18,30 @@ const COMPONENT_FILES = {
1818
// Generated jobs display as "Agent", "Detection" and "Evaluations".
1919
const COMPONENT_DISPLAY_NAMES = { evaluations: "evals" };
2020

21-
function componentKey(job, jobNames) {
21+
function callerPrefix(name) {
22+
const separator = typeof name === "string" ? name.lastIndexOf(" / ") : -1;
23+
return separator === -1 ? "" : name.slice(0, separator + 3);
24+
}
25+
26+
function componentIdentity(job, jobNames) {
2227
for (const candidate of [job.job_id, job.name]) {
2328
if (typeof candidate !== "string") continue;
24-
const separator = candidate.lastIndexOf(" / ");
25-
if (separator !== -1) {
29+
const candidatePrefix = callerPrefix(candidate);
30+
const prefix = candidatePrefix || callerPrefix(job.name);
31+
if (prefix) {
2632
// Caller names are arbitrary. Require the compiler's sibling jobs rather
2733
// than treating every reusable workflow with an "agent" job as gh-aw.
28-
const prefix = candidate.slice(0, separator + 3);
2934
if (!jobNames.has(`${prefix}activation`) || !jobNames.has(`${prefix}conclusion`)) continue;
3035
}
31-
const lower = (candidate.split(" / ").pop() ?? "").toLowerCase();
36+
const lower = candidate.slice(candidatePrefix.length).toLowerCase();
3237
const key = COMPONENT_DISPLAY_NAMES[lower] ?? lower;
33-
if (Object.hasOwn(COMPONENT_FILES, key)) return key;
38+
if (Object.hasOwn(COMPONENT_FILES, key)) return { prefix, key };
3439
}
35-
return "";
40+
return null;
3641
}
3742

3843
async function loadBillableJobs({ github, budget }, owner, repo, run) {
39-
const components = new Map();
40-
const jobsByComponent = new Map();
44+
const invocations = new Map();
4145
const allJobs = [];
4246
let complete = false;
4347
for (let page = 1; page <= 10; page++) {
@@ -65,43 +69,69 @@ async function loadBillableJobs({ github, budget }, owner, repo, run) {
6569
if (!complete) throw new Error("Cannot prove complete billable-component coverage");
6670
const jobNames = new Set(allJobs.flatMap(job => [job.job_id, job.name]));
6771
for (const job of allJobs) {
68-
const name = componentKey(job, jobNames);
69-
if (!name) continue;
72+
const identity = componentIdentity(job, jobNames);
73+
if (!identity) continue;
74+
const { prefix, key } = identity;
7075
if (!Number.isSafeInteger(job.run_attempt) || job.run_attempt < 1 || job.run_attempt > run.run_attempt || job.status !== "completed" || !job.conclusion) {
71-
throw new Error("Incomplete daily AIC component attempt metadata");
72-
}
73-
if (!jobsByComponent.has(name)) jobsByComponent.set(name, []);
74-
jobsByComponent.get(name).push(job);
75-
const prior = components.get(name);
76-
const notStarted = job.conclusion === "skipped" || provesJobExecutionNotStarted(job);
77-
const priorNotStarted = prior && (prior.conclusion === "skipped" || provesJobExecutionNotStarted(prior));
78-
if (!prior || (priorNotStarted && !notStarted) || (notStarted === priorNotStarted && job.run_attempt > prior.run_attempt)) {
79-
components.set(name, job);
76+
throw new Error(`Incomplete daily AIC component attempt metadata for ${prefix}${key}`);
8077
}
78+
if (!invocations.has(prefix)) invocations.set(prefix, new Map());
79+
const group = invocations.get(prefix);
80+
if (!group.has(key)) group.set(key, []);
81+
group.get(key).push(job);
8182
}
82-
// A complete empty job list proves the run ended before any billable job existed.
83-
if (components.size > 0 && !components.has("agent")) throw new Error("Cannot prove complete billable-component coverage");
83+
return [...invocations].map(([prefix, jobsByComponent]) => {
84+
const label = prefix ? prefix.slice(0, -3) : "top-level workflow";
85+
const activationJobs = allJobs.filter(job => job.name === `${prefix}activation` || (job.job_id === `${prefix}activation` && (!callerPrefix(job.name) || callerPrefix(job.name) === prefix)));
86+
return { prefix, label, activationJobs, ...selectInvocationJobs(jobsByComponent, label) };
87+
});
88+
}
89+
90+
function selectInvocationJobs(jobsByComponent, label) {
91+
const components = new Map();
8492
const priorJobs = new Map();
85-
for (const [name, selected] of components) {
86-
const selectedAttemptJobs = jobsByComponent.get(name).filter(job => job.run_attempt === selected.run_attempt);
93+
for (const [name, jobs] of jobsByComponent) {
94+
for (const job of jobs) {
95+
const prior = components.get(name);
96+
const notStarted = jobNotStarted(job);
97+
const priorNotStarted = prior && jobNotStarted(prior);
98+
if (!prior || (priorNotStarted && !notStarted) || (notStarted === priorNotStarted && job.run_attempt > prior.run_attempt)) {
99+
components.set(name, job);
100+
}
101+
}
102+
const selected = components.get(name);
103+
const selectedAttemptJobs = jobs.filter(job => job.run_attempt === selected.run_attempt);
87104
if (new Set(selectedAttemptJobs.map(job => job.id)).size > 1) {
88-
throw new Error("Ambiguous daily AIC component jobs");
105+
throw new Error(`Ambiguous daily AIC component jobs for ${label} (${name}, attempt ${selected.run_attempt})`);
89106
}
90107
if (selected.conclusion === "cancelled") {
91108
priorJobs.set(
92109
name,
93-
jobsByComponent
94-
.get(name)
95-
.filter(job => job.conclusion !== "skipped" && job.run_attempt < selected.run_attempt)
96-
.sort((a, b) => b.run_attempt - a.run_attempt)
110+
jobs.filter(job => job.conclusion !== "skipped" && job.run_attempt < selected.run_attempt).sort((a, b) => b.run_attempt - a.run_attempt)
97111
);
98112
}
99113
}
114+
if (!components.has("agent")) throw new Error(`Cannot prove complete billable-component coverage for ${label}`);
100115
return { components, priorJobs };
101116
}
102117

118+
function jobNotStarted(job) {
119+
return job.conclusion === "skipped" || provesJobExecutionNotStarted(job);
120+
}
121+
103122
function allBillableJobsNotStarted(components) {
104-
return [...components.values()].every(job => job.conclusion === "skipped" || provesJobExecutionNotStarted(job));
123+
return [...components.values()].every(jobNotStarted);
124+
}
125+
126+
function invocationUsageArtifactName({ activationJobs, components, label }) {
127+
const attempt = [...components.values()].reduce((max, job) => (jobNotStarted(job) ? max : Math.max(max, job.run_attempt)), 0);
128+
// A failed-only rerun may reuse the previous activation and its prefix.
129+
const eligible = activationJobs.filter(job => Number.isSafeInteger(job.run_attempt) && job.run_attempt >= 1 && job.run_attempt <= attempt && job.conclusion === "success");
130+
const latest = eligible.reduce((max, job) => Math.max(max, job.run_attempt), 0);
131+
const checkIds = new Set(eligible.filter(job => job.run_attempt === latest).map(job => /\/check-runs\/([1-9]\d*)$/.exec(job.check_run_url ?? "")?.[1]));
132+
if (checkIds.size > 1) throw new Error(`Ambiguous daily AIC activation jobs for ${label} (attempt ${latest})`);
133+
const [checkId] = checkIds;
134+
return checkId ? `call-${checkId}-usage` : null;
105135
}
106136

107137
function allBillableJobsSkipped(components) {
@@ -335,4 +365,4 @@ function sumCoveredComponents(directory, components, artifactCreatedAt, artifact
335365
return total;
336366
}
337367

338-
module.exports = { loadBillableJobs, allBillableJobsNotStarted, allBillableJobsSkipped, sumCoveredComponents };
368+
module.exports = { loadBillableJobs, allBillableJobsNotStarted, allBillableJobsSkipped, invocationUsageArtifactName, sumCoveredComponents };

0 commit comments

Comments
 (0)