Skip to content

Commit 3c68951

Browse files
hastyyTrigger.dev RepoOps
authored andcommitted
feat(webapp,plugins): count deploy check decisions by reason
Mono-RevId: aae429f75a83d587cf823803188a9dbaf9ce8ccb
1 parent 9e84cbb commit 3c68951

4 files changed

Lines changed: 267 additions & 14 deletions

File tree

‎apps/webapp/app/v3/deploymentChecks.server.ts‎

Lines changed: 119 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ export const deploymentCheckJob = {
6666
export function deploymentCheckTelemetry(meter: Meter) {
6767
return {
6868
decisions: meter.createCounter("deployment_checks.decisions_total", {
69-
description: "Deployment check decisions by mode, selection and outcome",
69+
description: "Deployment check decisions by mode, selection, outcome and reason",
7070
}),
7171
duration: meter.createHistogram("deployment_checks.duration_ms", {
7272
description: "Deployment check duration",
@@ -380,6 +380,7 @@ export async function runDeploymentCheck(
380380
telemetry.noPlugin.add(1);
381381
return "no_plugin";
382382
}
383+
const reasons = pluginReasons(controller);
383384

384385
const deployment = await prisma.workerDeployment.findFirst({
385386
where: { id: deploymentId },
@@ -415,6 +416,7 @@ export async function runDeploymentCheck(
415416
selected_by: "decision_failed",
416417
outcome: "skipped",
417418
stage: "job",
419+
reason: "none",
418420
});
419421
logger.error("deploymentChecks.result", {
420422
deploymentId: deployment.id,
@@ -445,13 +447,23 @@ export async function runDeploymentCheck(
445447
outcome: DeploymentCheckJobOutcome,
446448
details: Record<string, unknown> = {}
447449
): DeploymentCheckJobOutcome => {
450+
// Only an answer that isn't a pass has a reason. The line carries the one it's counted under.
451+
const refused = outcome === "fail" || outcome === "unavailable";
452+
const counted = refused ? reasonLabel(details, reasons) : "none";
448453
telemetry.decisions.add(1, {
449454
mode: decision.plan,
450455
selected_by: decision.selectedBy,
451456
outcome,
452457
stage: "job",
458+
reason: counted,
453459
});
454-
const line = { ...log, outcome, attempt, ...details };
460+
const line = {
461+
...log,
462+
outcome,
463+
attempt,
464+
...details,
465+
...(refused && { countedReason: counted }),
466+
};
455467
// Log a deployment that was selected for a check but could not be checked.
456468
const selectedButSkipped = outcome === "skipped" && decision.plan !== "skip";
457469
if (outcome === "unavailable" || outcome === "fail" || selectedButSkipped)
@@ -575,18 +587,104 @@ export async function runDeploymentCheck(
575587
// pass waits for the lookup, tried again on a later attempt; on the last one the lookup's
576588
// answer stands, so the monitors for checks without an answer see it.
577589
if (result.outcome !== "pass") {
578-
return finish(result.outcome, { checkId: result.id, durationMs, ...lookupDetails });
590+
return finish(result.outcome, {
591+
checkId: result.id,
592+
durationMs,
593+
...answerReason(result),
594+
...lookupDetails,
595+
});
579596
}
580597
const checked = { checkId: result.id, checkOutcome: result.outcome };
581598
retryLater(tag, "image tag", checked);
582599
const [outcome, details] = imageNotRead(tag);
583600
return finish(outcome, { ...details, step: "tag", ...checked, durationMs });
584601
}
585-
return finish(result.outcome, { checkId: result.id, durationMs });
602+
return finish(result.outcome, { checkId: result.id, durationMs, ...answerReason(result) });
586603
}
587604

588605
type ImageNotRead = DeploymentCheckNotRead;
589606

607+
/**
608+
* The webapp's own reasons (a result line's `reason`), as `deployment_checks.decisions_total`
609+
* counts them. `error` there is the gate failing in the webapp: counted as `webapp_error`, apart
610+
* from any reason of the plugin's.
611+
*/
612+
const WEBAPP_REASONS: ReadonlyMap<string, string> = new Map([
613+
...[
614+
"image_not_read",
615+
"image_unreadable",
616+
"image_read_not_configured",
617+
"image_missing",
618+
"image_unknown",
619+
"no_image_reference",
620+
"not_a_single_image",
621+
"digest_mismatch",
622+
].map((reason) => [reason, reason] as const),
623+
["error", "webapp_error"],
624+
]);
625+
626+
/** The plugin's reasons counted by name: listed, short and lowercase, and only so many. */
627+
const PLUGIN_REASON = /^[a-z][a-z0-9_]{0,39}$/;
628+
const MAX_PLUGIN_REASONS = 32;
629+
630+
const pluginReasonsByController = new WeakMap<DeploymentChecksController, ReadonlySet<string>>();
631+
632+
/**
633+
* The plugin's own reasons the count may name: the ones its controller lists, never one of the
634+
* webapp's labels, `none` or `other`, read once per controller. Any other reason a plugin sends
635+
* counts as `other`, so the label stays bounded whatever it sends.
636+
*/
637+
function pluginReasons(controller: DeploymentChecksController): ReadonlySet<string> {
638+
const known = pluginReasonsByController.get(controller);
639+
if (known) return known;
640+
const taken = new Set([...WEBAPP_REASONS.values(), "none", "other"]);
641+
let listed: readonly unknown[] = [];
642+
try {
643+
if (Array.isArray(controller.reasons)) listed = controller.reasons;
644+
} catch {
645+
// A plugin's list can't stop a check: its reasons then count as `other`.
646+
}
647+
const reasons = new Set(
648+
listed
649+
.filter(
650+
(reason): reason is string =>
651+
typeof reason === "string" && PLUGIN_REASON.test(reason) && !taken.has(reason)
652+
)
653+
.slice(0, MAX_PLUGIN_REASONS)
654+
);
655+
pluginReasonsByController.set(controller, reasons);
656+
return reasons;
657+
}
658+
659+
/**
660+
* What `deployment_checks.decisions_total` counts a refused or unanswered decision under: the
661+
* webapp's own reason, else the plugin's (`checkReason`). One it doesn't know, or none at all,
662+
* counts as `other`. Every other decision counts as `none`.
663+
*/
664+
function reasonLabel(details: Record<string, unknown>, plugin: ReadonlySet<string>): string {
665+
const { reason, checkReason } = details;
666+
if (reason !== undefined) {
667+
return (typeof reason === "string" && WEBAPP_REASONS.get(reason)) || "other";
668+
}
669+
if (checkReason !== undefined) {
670+
return typeof checkReason === "string" && plugin.has(checkReason) ? checkReason : "other";
671+
}
672+
return "other";
673+
}
674+
675+
/**
676+
* The plugin's reason for an answer, for the result line and the count. It goes on the line as
677+
* `checkReason`, apart from the webapp's own `reason`; one that isn't short and lowercase as
678+
* `other`.
679+
*/
680+
function answerReason(answer: DeploymentCheckResult): { checkReason?: string } {
681+
if (answer.reason === undefined || answer.outcome === "pass" || answer.outcome === "flagged") {
682+
return {};
683+
}
684+
const valid = typeof answer.reason === "string" && PLUGIN_REASON.test(answer.reason);
685+
return { checkReason: valid ? answer.reason : "other" };
686+
}
687+
590688
const IMAGE_NOT_READ_REASONS: Record<ImageNotRead["kind"], string> = {
591689
retry: "image_not_read",
592690
unreadable: "image_unreadable",
@@ -734,6 +832,7 @@ export async function gateDeployment(
734832
return { kind: "proceed", checked: false };
735833
}
736834
const checks = controller;
835+
const reasons = pluginReasons(checks);
737836

738837
const log = {
739838
deploymentId: deployment.id,
@@ -769,6 +868,7 @@ export async function gateDeployment(
769868
selected_by: "decision_failed",
770869
outcome: "skipped",
771870
stage: "finalize",
871+
reason: "none",
772872
});
773873
logger.error("deploymentChecks.result", {
774874
...log,
@@ -788,6 +888,7 @@ export async function gateDeployment(
788888
selected_by: decision.selectedBy,
789889
outcome: "skipped",
790890
stage: "finalize",
891+
reason: "none",
791892
});
792893
logger.warn("deploymentChecks.result", {
793894
...log,
@@ -807,18 +908,24 @@ export async function gateDeployment(
807908
}
808909

809910
const gateLog = { ...log, mode: decision.plan, selectedBy: decision.selectedBy };
911+
// Counted under `counted`'s reason: the refusing image's, which may be a machine image's while
912+
// the line's top level is the deployment image's.
810913
const refuse = (
811914
outcome: "fail" | "unavailable",
812915
deployAgain: boolean,
813-
details: Record<string, unknown>
916+
details: Record<string, unknown>,
917+
counted: Record<string, unknown> = details
814918
): DeploymentGateResult => {
919+
const countedReason = reasonLabel(counted, reasons);
815920
telemetry.decisions.add(1, {
816921
mode: "gate",
817922
selected_by: decision.selectedBy,
818923
outcome,
819924
stage: "finalize",
925+
reason: countedReason,
820926
});
821-
logger.warn("deploymentChecks.result", { ...gateLog, outcome, ...details });
927+
// The line carries the reason it's counted under, so queries group refusals as the metric does.
928+
logger.warn("deploymentChecks.result", { ...gateLog, outcome, ...details, countedReason });
822929
return refusal(outcome === "unavailable" && deployAgain);
823930
};
824931

@@ -917,7 +1024,7 @@ export async function gateDeployment(
9171024
return {
9181025
outcome: answer.outcome,
9191026
deployAgain: answer.retryable,
920-
details: { checkId: answer.id, durationMs },
1027+
details: { checkId: answer.id, durationMs, ...answerReason(answer) },
9211028
};
9221029
};
9231030

@@ -991,8 +1098,9 @@ export async function gateDeployment(
9911098
const refusals = answers.filter(isRefusal);
9921099
if (refusals.length > 0) {
9931100
const worst = mostFinalRefusal(refusals);
994-
// The message depends on whether retrying may help.
995-
return refuse(worst.outcome, worst.deployAgain, details);
1101+
// The message depends on whether retrying may help. Counted under the refusing image's
1102+
// reason, which may be a machine image's.
1103+
return refuse(worst.outcome, worst.deployAgain, details, worst.details);
9961104
}
9971105

9981106
const outcome = answers.some((answer) => answer.outcome === "flagged") ? "flagged" : "pass";
@@ -1001,6 +1109,7 @@ export async function gateDeployment(
10011109
selected_by: decision.selectedBy,
10021110
outcome,
10031111
stage: "finalize",
1112+
reason: "none",
10041113
});
10051114
logger.info("deploymentChecks.result", { ...gateLog, outcome, ...details });
10061115
return {
@@ -1012,6 +1121,7 @@ export async function gateDeployment(
10121121
),
10131122
};
10141123
} catch (error) {
1124+
// Counted as `webapp_error`.
10151125
return refuse("unavailable", true, { reason: "error", error: errorMessage(error) });
10161126
}
10171127
}

‎apps/webapp/test/deploymentChecks.test.ts‎

Lines changed: 55 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ function testPlugin({
6666
const decisions: DeploymentCheckDecisionInput[] = [];
6767
const checks: DeploymentCheckInput[] = [];
6868
const controller: DeploymentChecksController = {
69+
// Plugin reasons the count may name; tests use made-up ones.
70+
reasons: ["test_blocked", "test_busy"],
6971
async decide(input) {
7072
decisions.push(input);
7173
return decision;
@@ -564,8 +566,8 @@ describe("deployment checks", () => {
564566
postgresTest("checks what the plugin chose, labelled with its mode", async ({ prisma }) => {
565567
// Catches: a gate or shadow deploy not checked, a skipped one checked, an image reference
566568
// the checker can't use sent, the plugin asked about the wrong org or deployment, an org id
567-
// in the metric attributes, or a flagged answer missing from the counter the deploy scan
568-
// alerts read.
569+
// in the metric attributes, a flagged answer missing from the counter the deploy scan alerts
570+
// read, or a plugin's reason counted as is (unbounded) or not at all.
569571
const metrics = createInMemoryMetrics();
570572
const telemetry = deploymentCheckTelemetry(metrics.meter);
571573
const run = async (
@@ -641,22 +643,70 @@ describe("deployment checks", () => {
641643
});
642644
expect(flagged.outcome).toBe("flagged");
643645

646+
// The plugin's reason labels the count when the plugin lists it; any other counts as other,
647+
// and a pass never has one.
648+
const blocked = await run(SHADOW, undefined, {
649+
outcome: "fail",
650+
id: "check_blocked",
651+
retryable: false,
652+
reason: "test_blocked",
653+
});
654+
expect(blocked.outcome).toBe("fail");
655+
const passWithReason = await run(SHADOW, undefined, {
656+
outcome: "pass",
657+
id: "check_pass",
658+
retryable: false,
659+
reason: "test_blocked",
660+
});
661+
expect(passWithReason.outcome).toBe("pass");
662+
const odd = await run(SHADOW, undefined, {
663+
outcome: "unavailable",
664+
id: "check_odd",
665+
retryable: false,
666+
reason: "proj_1234 said no",
667+
});
668+
expect(odd.outcome).toBe("unavailable");
669+
644670
// The reader also exports every 100 ms, and an earlier export holds partial totals. With
645671
// cumulative temporality the latest export holds every point.
646672
const points = ((await latestMetrics(metrics))?.scopeMetrics ?? [])
647673
.flatMap((scope) => scope.metrics)
648674
.find((metric) => metric.descriptor.name === "deployment_checks.decisions_total")?.dataPoints;
649675
expect(points?.map((point) => point.attributes)).toEqual(
650676
expect.arrayContaining([
651-
{ mode: "shadow", selected_by: "sampled", outcome: "pass", stage: "job" },
652-
{ mode: "gate", selected_by: "always", outcome: "pass", stage: "job" },
653-
{ mode: "shadow", selected_by: "sampled", outcome: "flagged", stage: "job" },
677+
{ mode: "shadow", selected_by: "sampled", outcome: "pass", stage: "job", reason: "none" },
678+
{ mode: "gate", selected_by: "always", outcome: "pass", stage: "job", reason: "none" },
679+
{
680+
mode: "shadow",
681+
selected_by: "sampled",
682+
outcome: "flagged",
683+
stage: "job",
684+
reason: "none",
685+
},
686+
{
687+
mode: "shadow",
688+
selected_by: "sampled",
689+
outcome: "fail",
690+
stage: "job",
691+
reason: "test_blocked",
692+
},
693+
{
694+
mode: "shadow",
695+
selected_by: "sampled",
696+
outcome: "unavailable",
697+
stage: "job",
698+
reason: "other",
699+
},
654700
])
655701
);
702+
expect(
703+
points?.filter((point) => point.attributes.outcome === "pass").map((p) => p.attributes.reason)
704+
).toEqual(["none", "none"]);
656705
for (const point of points ?? []) {
657706
expect(Object.keys(point.attributes).sort()).toEqual([
658707
"mode",
659708
"outcome",
709+
"reason",
660710
"selected_by",
661711
"stage",
662712
]);

0 commit comments

Comments
 (0)