@open-qa/qa 0.1.0-alpha.4 → 0.1.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/THIRD_PARTY.md +5 -0
- package/drizzle/0017_provider_notifications.sql +13 -0
- package/drizzle/0018_classification_registry.sql +39 -0
- package/drizzle/0019_trial_audit.sql +44 -0
- package/drizzle/meta/0017_snapshot.json +2092 -0
- package/drizzle/meta/0018_snapshot.json +2102 -0
- package/drizzle/meta/0019_snapshot.json +2451 -0
- package/drizzle/meta/_journal.json +21 -0
- package/package.json +12 -7
- package/src/access-binding.d.ts +8 -0
- package/src/access-binding.js +26 -0
- package/src/adapters/classification-write.d.ts +87 -0
- package/src/adapters/classification-write.js +64 -0
- package/src/adapters/e2b-executor.js +4 -0
- package/src/adapters/file-run-store.d.ts +186 -41
- package/src/adapters/file-run-store.js +87 -19
- package/src/adapters/file-trial-audit.d.ts +280 -0
- package/src/adapters/file-trial-audit.js +105 -0
- package/src/adapters/pg-classification-store.d.ts +98 -20
- package/src/adapters/pg-classification-store.js +84 -44
- package/src/adapters/pg-run-store.d.ts +1 -0
- package/src/adapters/pg-run-store.js +70 -9
- package/src/adapters/run-metadata.d.ts +2 -0
- package/src/adapters/run-metadata.js +10 -0
- package/src/adapters/secret-manager-credential-resolver.d.ts +1 -1
- package/src/attempt-audit.d.ts +363 -0
- package/src/attempt-audit.js +253 -0
- package/src/audit-command.d.ts +13 -0
- package/src/audit-command.js +77 -0
- package/src/classification-command.d.ts +14 -9
- package/src/classification-command.js +119 -26
- package/src/classification-model.d.ts +10 -3
- package/src/classification-model.js +40 -24
- package/src/classification-notifier.d.ts +4 -3
- package/src/classification-notifier.js +26 -6
- package/src/classify-runs.d.ts +2 -1
- package/src/classify-runs.js +39 -3
- package/src/cli-program.js +53 -7
- package/src/commands.d.ts +1 -0
- package/src/commands.js +2 -0
- package/src/db/database.d.ts +7 -0
- package/src/db/database.js +15 -0
- package/src/db/event-chunks.d.ts +38 -29
- package/src/db/flow-status.d.ts +7 -3
- package/src/db/flow-status.js +240 -16
- package/src/db/queries.d.ts +24 -1
- package/src/db/queries.js +22 -0
- package/src/db/schema.d.ts +333 -4
- package/src/db/schema.js +83 -11
- package/src/db/trial-audit.d.ts +526 -0
- package/src/db/trial-audit.js +84 -0
- package/src/draft-api.d.ts +25 -421
- package/src/draft-api.js +10 -3
- package/src/engine.d.ts +47 -4
- package/src/engine.js +97 -8
- package/src/execution-snapshot.d.ts +1 -1
- package/src/execution-snapshot.js +22 -17
- package/src/export-command.d.ts +6 -0
- package/src/export-command.js +106 -0
- package/src/flow-check.js +1 -1
- package/src/flow-loader.d.ts +72 -6
- package/src/flow-loader.js +76 -12
- package/src/http-stage-client.d.ts +98 -1
- package/src/independent-model.js +53 -6
- package/src/judge-review-store.d.ts +13 -0
- package/src/judge-review-store.js +58 -0
- package/src/local-host-executor.d.ts +3 -1
- package/src/local-host-executor.js +2 -0
- package/src/quarantine-command.d.ts +5 -1
- package/src/quarantine-command.js +56 -13
- package/src/remote-command.js +2 -0
- package/src/report/browser.js +37 -37
- package/src/report/ctrf.d.ts +983 -0
- package/src/report/ctrf.js +306 -0
- package/src/report/generate.d.ts +1 -1
- package/src/report/generate.js +29 -6
- package/src/report/load.d.ts +738 -42
- package/src/report/load.js +78 -6
- package/src/result-notifier.js +1 -1
- package/src/result-trace.d.ts +62 -0
- package/src/result-trace.js +81 -0
- package/src/run-command.d.ts +2 -0
- package/src/run-command.js +285 -62
- package/src/run-setup-error.d.ts +1 -1
- package/src/run-setup-error.js +2 -2
- package/src/server/app.js +5 -4
- package/src/server/index.d.ts +2 -0
- package/src/server/index.js +11 -2
- package/src/server/repository.d.ts +166 -29
- package/src/server/repository.js +14 -2
- package/src/studio-review.js +1 -1
- package/src/system-config.d.ts +2 -2
- package/src/system-config.js +5 -4
- package/src/trial-audit.d.ts +630 -0
- package/src/trial-audit.js +272 -0
- package/src/visual-baseline.d.ts +4 -0
- package/src/visual-baseline.js +42 -0
- package/src/webhook-notification.d.ts +15 -0
- package/src/webhook-notification.js +61 -0
- package/src/worker/execution.d.ts +2 -1
- package/src/worker/execution.js +122 -3
- package/src/worker/index.d.ts +4 -0
- package/src/worker/index.js +10 -1
- package/src/worker/quarantine-notifications.js +2 -2
- package/src/worker/queue.d.ts +6 -2
- package/src/worker/queue.js +80 -19
- package/src/worker/result-notifications.d.ts +10 -2
- package/src/worker/result-notifications.js +120 -23
- package/src/worker/store.js +6 -3
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import {
|
|
3
|
+
jsonObjectSchema,
|
|
4
|
+
millisecondsSchema,
|
|
5
|
+
resultEvidenceSchema,
|
|
6
|
+
resultOutcome,
|
|
7
|
+
resultTraceSchema,
|
|
8
|
+
runUsageSchema,
|
|
9
|
+
usageSchema,
|
|
10
|
+
verdictSchema
|
|
11
|
+
} from "@open-qa/qa-engine/protocol";
|
|
12
|
+
import { publicId } from "./public-id.js";
|
|
13
|
+
import { attemptAuditSchema } from "./attempt-audit.js";
|
|
14
|
+
const trialGroupSchema = z.strictObject({
|
|
15
|
+
schemaVersion: z.literal(1),
|
|
16
|
+
groupId: z.string().min(1),
|
|
17
|
+
projectId: publicId,
|
|
18
|
+
batchId: publicId,
|
|
19
|
+
caseId: z.string().min(1),
|
|
20
|
+
flow: z.string().min(1),
|
|
21
|
+
caseRevision: z.string().regex(/^[a-f0-9]{64}$/),
|
|
22
|
+
target: z.string().min(1),
|
|
23
|
+
targetRevision: z.string().nullable(),
|
|
24
|
+
generation: z.number().int().nonnegative().nullable(),
|
|
25
|
+
planned: z.number().int().min(1).max(100),
|
|
26
|
+
startedAt: millisecondsSchema,
|
|
27
|
+
environment: jsonObjectSchema,
|
|
28
|
+
independent: z.boolean().optional(),
|
|
29
|
+
quarantinePolicy: z.strictObject({
|
|
30
|
+
expiresAfterHours: z.number().int().positive(),
|
|
31
|
+
evidenceMaxAgeHours: z.number().int().positive(),
|
|
32
|
+
minimumPassedTrials: z.number().int().positive(),
|
|
33
|
+
flakyStreak: z.number().int().positive()
|
|
34
|
+
}).optional()
|
|
35
|
+
}).refine(
|
|
36
|
+
({ groupId, batchId, caseId, projectId }) => groupId === `trial:${batchId}:${caseId}` && caseId.startsWith(`case:${projectId}:`)
|
|
37
|
+
);
|
|
38
|
+
const trialReceiptSchema = z.discriminatedUnion("kind", [
|
|
39
|
+
z.strictObject({ kind: z.literal("attempt-started"), trace: resultTraceSchema }),
|
|
40
|
+
z.strictObject({
|
|
41
|
+
kind: z.literal("attempt-finished"),
|
|
42
|
+
attemptId: publicId,
|
|
43
|
+
at: millisecondsSchema,
|
|
44
|
+
verdict: verdictSchema,
|
|
45
|
+
outcome: z.enum(["blocked", "skipped", "not-run", "expected-failure"]).optional(),
|
|
46
|
+
usage: runUsageSchema.optional(),
|
|
47
|
+
audit: attemptAuditSchema.optional(),
|
|
48
|
+
observation: jsonObjectSchema.optional(),
|
|
49
|
+
evidence: z.array(resultEvidenceSchema).optional()
|
|
50
|
+
}),
|
|
51
|
+
z.strictObject({
|
|
52
|
+
kind: z.literal("classifier-usage"),
|
|
53
|
+
attemptId: publicId,
|
|
54
|
+
usage: z.array(usageSchema).min(1)
|
|
55
|
+
}),
|
|
56
|
+
z.strictObject({
|
|
57
|
+
kind: z.literal("trial-finished"),
|
|
58
|
+
index: z.number().int().positive(),
|
|
59
|
+
attemptId: publicId,
|
|
60
|
+
quarantined: z.boolean()
|
|
61
|
+
}),
|
|
62
|
+
z.strictObject({
|
|
63
|
+
kind: z.literal("group-finished"),
|
|
64
|
+
at: millisecondsSchema
|
|
65
|
+
})
|
|
66
|
+
]);
|
|
67
|
+
function trialReceiptKey(group, receipt) {
|
|
68
|
+
switch (receipt.kind) {
|
|
69
|
+
case "attempt-started": {
|
|
70
|
+
const { trace } = receipt;
|
|
71
|
+
if (trace.trial?.groupId !== group.groupId || trace.trial.count !== group.planned || trace.trial.index > group.planned || trace.projectId !== group.projectId || trace.caseId !== group.caseId || trace.caseRevision !== group.caseRevision || trace.batchId !== group.batchId || trace.target !== group.target || trace.targetRevision !== group.targetRevision)
|
|
72
|
+
throw new Error("Trial identity mismatch");
|
|
73
|
+
return `start:${receipt.trace.attemptId}`;
|
|
74
|
+
}
|
|
75
|
+
case "attempt-finished":
|
|
76
|
+
return `finish:${receipt.attemptId}`;
|
|
77
|
+
case "classifier-usage":
|
|
78
|
+
return `classifier-usage:${receipt.attemptId}`;
|
|
79
|
+
case "trial-finished":
|
|
80
|
+
return `trial:${receipt.index}`;
|
|
81
|
+
case "group-finished":
|
|
82
|
+
return "close";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function conditionKey(value) {
|
|
86
|
+
return JSON.stringify(value, (_name, entry) => {
|
|
87
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return entry;
|
|
88
|
+
return Object.fromEntries(
|
|
89
|
+
Object.entries(entry).sort(([left], [right]) => left.localeCompare(right))
|
|
90
|
+
);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const included = /* @__PURE__ */ new Set([
|
|
94
|
+
"passed",
|
|
95
|
+
"failed",
|
|
96
|
+
"expected-failure",
|
|
97
|
+
"blocked",
|
|
98
|
+
"error",
|
|
99
|
+
"inconclusive"
|
|
100
|
+
]);
|
|
101
|
+
function rate(outcomes, comparable) {
|
|
102
|
+
const samples = outcomes.filter((outcome) => included.has(outcome));
|
|
103
|
+
const n = samples.length;
|
|
104
|
+
const passed = samples.filter((outcome) => outcome === "passed").length;
|
|
105
|
+
const fraction = n ? passed / n : null;
|
|
106
|
+
let interval = null;
|
|
107
|
+
if (fraction !== null && comparable) {
|
|
108
|
+
const z2 = 1.959963984540054;
|
|
109
|
+
const divisor = 1 + z2 ** 2 / n;
|
|
110
|
+
const center = (fraction + z2 ** 2 / (2 * n)) / divisor;
|
|
111
|
+
const halfWidth = z2 * Math.sqrt((fraction * (1 - fraction) + z2 ** 2 / (4 * n)) / n) / divisor;
|
|
112
|
+
interval = { lower: Math.max(0, center - halfWidth), upper: Math.min(1, center + halfWidth) };
|
|
113
|
+
}
|
|
114
|
+
return { passed, n, fraction, interval };
|
|
115
|
+
}
|
|
116
|
+
function summarizeTrial({ group, receipts }) {
|
|
117
|
+
const attempts = /* @__PURE__ */ new Map();
|
|
118
|
+
const results = /* @__PURE__ */ new Map();
|
|
119
|
+
const finals = /* @__PURE__ */ new Map();
|
|
120
|
+
const classifier = /* @__PURE__ */ new Map();
|
|
121
|
+
let finishedAt = null;
|
|
122
|
+
for (const receipt of receipts) {
|
|
123
|
+
trialReceiptKey(group, receipt);
|
|
124
|
+
switch (receipt.kind) {
|
|
125
|
+
case "attempt-started": {
|
|
126
|
+
const index = receipt.trace.trial.index;
|
|
127
|
+
if (!attempts.has(index)) attempts.set(index, []);
|
|
128
|
+
attempts.get(index).push(receipt.trace);
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
case "attempt-finished":
|
|
132
|
+
results.set(receipt.attemptId, receipt);
|
|
133
|
+
break;
|
|
134
|
+
case "classifier-usage":
|
|
135
|
+
classifier.set(receipt.attemptId, receipt);
|
|
136
|
+
break;
|
|
137
|
+
case "trial-finished":
|
|
138
|
+
finals.set(receipt.index, receipt);
|
|
139
|
+
break;
|
|
140
|
+
case "group-finished":
|
|
141
|
+
finishedAt = receipt.at;
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const counts = {
|
|
146
|
+
passed: 0,
|
|
147
|
+
failed: 0,
|
|
148
|
+
blocked: 0,
|
|
149
|
+
error: 0,
|
|
150
|
+
inconclusive: 0,
|
|
151
|
+
canceled: 0,
|
|
152
|
+
skipped: 0,
|
|
153
|
+
pending: 0,
|
|
154
|
+
notRun: 0
|
|
155
|
+
};
|
|
156
|
+
const fingerprints = /* @__PURE__ */ new Set();
|
|
157
|
+
const conditionKeys = /* @__PURE__ */ new Map();
|
|
158
|
+
const observe = (scope, field, value) => {
|
|
159
|
+
if (value === void 0 || value === null) return;
|
|
160
|
+
const slot = JSON.stringify([scope, field]);
|
|
161
|
+
const keys = conditionKeys.get(slot) ?? /* @__PURE__ */ new Set();
|
|
162
|
+
keys.add(conditionKey(value));
|
|
163
|
+
conditionKeys.set(slot, keys);
|
|
164
|
+
};
|
|
165
|
+
const observeRole = (slot, billing, model) => {
|
|
166
|
+
observe(slot, "billing", billing);
|
|
167
|
+
for (const [name, value] of Object.entries(model ?? {})) {
|
|
168
|
+
if (name === "parameters" || name === "deployment" || name === "billingVersion" || name === "seed" && value === "unknown")
|
|
169
|
+
continue;
|
|
170
|
+
observe(slot, name, value);
|
|
171
|
+
}
|
|
172
|
+
for (const [name, value] of Object.entries(model?.parameters ?? {}))
|
|
173
|
+
if (name !== "imageFallback") observe(slot, `parameter:${name}`, value);
|
|
174
|
+
};
|
|
175
|
+
const trials = Array.from({ length: group.planned }, (_, offset) => {
|
|
176
|
+
const index = offset + 1;
|
|
177
|
+
const history = (attempts.get(index) ?? []).sort((a, b) => a.attempt - b.attempt).map((trace) => {
|
|
178
|
+
fingerprints.add(
|
|
179
|
+
JSON.stringify([trace.environmentFingerprint, trace.parameterFingerprint])
|
|
180
|
+
);
|
|
181
|
+
const result = results.get(trace.attemptId);
|
|
182
|
+
for (const entry of result?.audit?.usage ?? [])
|
|
183
|
+
observeRole(
|
|
184
|
+
JSON.stringify([entry.role, entry.actor, entry.step]),
|
|
185
|
+
entry.billing,
|
|
186
|
+
entry.model
|
|
187
|
+
);
|
|
188
|
+
const classifierUsage = classifier.get(trace.attemptId)?.usage ?? [];
|
|
189
|
+
for (const entry of classifierUsage)
|
|
190
|
+
observeRole("classifier", entry.billingMode ?? null, entry.model);
|
|
191
|
+
for (const [name, value] of Object.entries(result?.observation ?? {}))
|
|
192
|
+
observe("execution", name, value);
|
|
193
|
+
const environment = result?.audit?.environment;
|
|
194
|
+
observe("stage", "imageTemplate", environment?.image.template);
|
|
195
|
+
observe("stage", "imageDigest", environment?.image.digest);
|
|
196
|
+
for (const { view, browser, device, viewport } of environment?.views ?? []) {
|
|
197
|
+
observe(view, "browser", browser);
|
|
198
|
+
observe(view, "device", device);
|
|
199
|
+
observe(view, "viewport", viewport);
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
trace,
|
|
203
|
+
result: result ?? null,
|
|
204
|
+
classifierUsage,
|
|
205
|
+
outcome: resultOutcome(result?.verdict, result?.outcome, trace.started)
|
|
206
|
+
};
|
|
207
|
+
});
|
|
208
|
+
const final = finals.get(index);
|
|
209
|
+
const last = history.at(-1);
|
|
210
|
+
const completeChain = history.every(
|
|
211
|
+
({ trace, result }, position) => result && (!finishedAt || result.at <= finishedAt) && result.at >= group.startedAt && trace.attempt === position + 1 && trace.executionId === history[0]?.trace.executionId && trace.retryOf === (history[position - 1]?.trace.attemptId ?? null)
|
|
212
|
+
);
|
|
213
|
+
const outcome = final && last && completeChain && last.trace.attemptId === final.attemptId ? last.outcome : history.length || final ? "unfinished" : "not-run";
|
|
214
|
+
const bucket = outcome === "expected-failure" ? "failed" : outcome === "not-run" ? "notRun" : outcome === "unfinished" ? "pending" : outcome;
|
|
215
|
+
if (Object.hasOwn(counts, bucket)) counts[bucket]++;
|
|
216
|
+
return {
|
|
217
|
+
index,
|
|
218
|
+
executionId: history[0]?.trace.executionId ?? null,
|
|
219
|
+
firstOutcome: history.find(({ trace }) => trace.attempt === 1)?.outcome ?? (history.length ? "unfinished" : "not-run"),
|
|
220
|
+
outcome,
|
|
221
|
+
quarantined: final?.quarantined ?? null,
|
|
222
|
+
attempts: history
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
const mixed = fingerprints.size > 1 || [...conditionKeys.values()].some((keys) => keys.size > 1);
|
|
226
|
+
const comparable = fingerprints.size === 1 && !mixed && group.independent !== false;
|
|
227
|
+
return {
|
|
228
|
+
group,
|
|
229
|
+
finishedAt,
|
|
230
|
+
counts,
|
|
231
|
+
completed: group.planned - counts.pending - counts.notRun,
|
|
232
|
+
confidence: {
|
|
233
|
+
method: "wilson",
|
|
234
|
+
level: 0.95,
|
|
235
|
+
comparable,
|
|
236
|
+
mixed,
|
|
237
|
+
assumptions: mixed ? "Recorded conditions differ across attempts." : group.independent === false ? "The group was declared dependent." : "Conditional on independent trials under the recorded conditions. Independence is unverified."
|
|
238
|
+
},
|
|
239
|
+
first: rate(
|
|
240
|
+
trials.map(({ firstOutcome }) => firstOutcome),
|
|
241
|
+
comparable
|
|
242
|
+
),
|
|
243
|
+
final: rate(
|
|
244
|
+
trials.map(({ outcome }) => outcome),
|
|
245
|
+
comparable
|
|
246
|
+
),
|
|
247
|
+
trials
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function printTrial(summary, output) {
|
|
251
|
+
output(
|
|
252
|
+
`Trial group ${summary.group.groupId} \xB7 ${summary.completed}/${summary.group.planned} completed \xB7 ${summary.counts.pending} pending \xB7 ${summary.counts.notRun} not run`
|
|
253
|
+
);
|
|
254
|
+
for (const [label, measure] of [
|
|
255
|
+
["First attempt", summary.first],
|
|
256
|
+
["Final", summary.final]
|
|
257
|
+
]) {
|
|
258
|
+
const percentage = measure.fraction === null ? "unavailable" : `${(100 * measure.fraction).toFixed(1)}%`;
|
|
259
|
+
const interval = measure.interval ? `${(100 * measure.interval.lower).toFixed(1)}\u2013${(100 * measure.interval.upper).toFixed(1)}%` : "unavailable";
|
|
260
|
+
output(
|
|
261
|
+
`${label} \xB7 ${measure.passed}/${measure.n} passed (${percentage}) \xB7 95% Wilson interval ${interval}`
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
output(summary.confidence.assumptions);
|
|
265
|
+
}
|
|
266
|
+
export {
|
|
267
|
+
printTrial,
|
|
268
|
+
summarizeTrial,
|
|
269
|
+
trialGroupSchema,
|
|
270
|
+
trialReceiptKey,
|
|
271
|
+
trialReceiptSchema
|
|
272
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type VisualBaselineKey, type VisualInput } from "@open-qa/qa-engine/protocol";
|
|
2
|
+
/** The reader is scoped to the selected consumer checkout's QA directory. */
|
|
3
|
+
export declare function readVisualBaseline(root: string, candidate: Pick<VisualInput, "key" | "attemptId">, signal: AbortSignal): Promise<VisualInput>;
|
|
4
|
+
export declare function visualBaselinePath(key: VisualBaselineKey): string;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { ArtifactReader, hasCode } from "@open-qa/qa-inspect/server";
|
|
3
|
+
import {
|
|
4
|
+
MAX_VISUAL_PNG_BYTES,
|
|
5
|
+
visualBaselineKeySchema,
|
|
6
|
+
visualBaselineManifestSchema
|
|
7
|
+
} from "@open-qa/qa-engine/protocol";
|
|
8
|
+
async function readVisualBaseline(root, candidate, signal) {
|
|
9
|
+
const key = visualBaselineKeySchema.parse(candidate.key);
|
|
10
|
+
const canonical = JSON.stringify(key);
|
|
11
|
+
const path = visualBaselinePath(key);
|
|
12
|
+
const reader = new ArtifactReader(root);
|
|
13
|
+
signal.throwIfAborted();
|
|
14
|
+
let raw;
|
|
15
|
+
try {
|
|
16
|
+
raw = await reader.read(`${path}.json`, 16384);
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (hasCode(error, "ENOENT")) return { ...candidate, key };
|
|
19
|
+
throw new Error("Visual baseline manifest could not be read", { cause: error });
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const manifest = visualBaselineManifestSchema.parse(JSON.parse(raw.toString("utf8")));
|
|
23
|
+
if (JSON.stringify(manifest.key) !== canonical) throw new Error("Baseline key mismatch");
|
|
24
|
+
const png = await reader.read(`${path}.png`, MAX_VISUAL_PNG_BYTES);
|
|
25
|
+
if (createHash("sha256").update(png).digest("hex") !== manifest.sha256)
|
|
26
|
+
throw new Error("Baseline digest mismatch");
|
|
27
|
+
signal.throwIfAborted();
|
|
28
|
+
return { ...candidate, key, baseline: { manifest, png: png.toString("base64") } };
|
|
29
|
+
} catch (error) {
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
throw new Error("Visual baseline PNG or manifest is invalid", { cause: error });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function visualBaselinePath(key) {
|
|
35
|
+
const parsed = visualBaselineKeySchema.parse(key);
|
|
36
|
+
const fingerprint = createHash("sha256").update(JSON.stringify(parsed)).digest("hex");
|
|
37
|
+
return `baselines/web/${parsed.check}/${fingerprint}`;
|
|
38
|
+
}
|
|
39
|
+
export {
|
|
40
|
+
readVisualBaseline,
|
|
41
|
+
visualBaselinePath
|
|
42
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type NotificationProvider } from "@open-qa/qa-engine";
|
|
2
|
+
/** Check the raw request body before parsing it, then deduplicate the signed event ID. */
|
|
3
|
+
export declare function verifyWebhookSignature(input: {
|
|
4
|
+
secret: string;
|
|
5
|
+
timestamp: string;
|
|
6
|
+
signature: string;
|
|
7
|
+
body: string | Uint8Array;
|
|
8
|
+
now?: number;
|
|
9
|
+
}): boolean;
|
|
10
|
+
export declare function createWebhookNotification(options: {
|
|
11
|
+
id?: string;
|
|
12
|
+
url: string;
|
|
13
|
+
secret: string;
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
}): NotificationProvider;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { providerIdSchema } from "@open-qa/qa-engine";
|
|
3
|
+
const timestampPattern = /^\d{1,12}$/;
|
|
4
|
+
const signaturePattern = /^v1=([a-f0-9]{64})$/;
|
|
5
|
+
const freshnessSeconds = 300;
|
|
6
|
+
function sign(secret, timestamp, body) {
|
|
7
|
+
return createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest();
|
|
8
|
+
}
|
|
9
|
+
function verifyWebhookSignature(input) {
|
|
10
|
+
const match = signaturePattern.exec(input.signature);
|
|
11
|
+
const now = input.now ?? Date.now();
|
|
12
|
+
if (!match || !timestampPattern.test(input.timestamp) || !Number.isFinite(now) || Math.abs(Math.floor(now / 1e3) - Number(input.timestamp)) > freshnessSeconds)
|
|
13
|
+
return false;
|
|
14
|
+
return timingSafeEqual(
|
|
15
|
+
sign(input.secret, input.timestamp, input.body),
|
|
16
|
+
Buffer.from(match[1], "hex")
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
function createWebhookNotification(options) {
|
|
20
|
+
const id = providerIdSchema.parse(options.id ?? "webhook");
|
|
21
|
+
let endpoint;
|
|
22
|
+
try {
|
|
23
|
+
endpoint = new URL(options.url);
|
|
24
|
+
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.hash)
|
|
25
|
+
throw new Error();
|
|
26
|
+
if (typeof options.secret !== "string" || Buffer.byteLength(options.secret) < 32)
|
|
27
|
+
throw new Error();
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error("Invalid QA webhook configuration");
|
|
30
|
+
}
|
|
31
|
+
const secret = options.secret;
|
|
32
|
+
const fetcher = options.fetch ?? fetch;
|
|
33
|
+
return {
|
|
34
|
+
id,
|
|
35
|
+
async deliver(event, signal) {
|
|
36
|
+
try {
|
|
37
|
+
const body = JSON.stringify(event);
|
|
38
|
+
const timestamp = String(Math.floor(Date.now() / 1e3));
|
|
39
|
+
const response = await fetcher(endpoint, {
|
|
40
|
+
method: "POST",
|
|
41
|
+
redirect: "error",
|
|
42
|
+
headers: {
|
|
43
|
+
"Content-Type": "application/json",
|
|
44
|
+
"X-Open-QA-Timestamp": timestamp,
|
|
45
|
+
"X-Open-QA-Signature": `v1=${sign(secret, timestamp, body).toString("hex")}`
|
|
46
|
+
},
|
|
47
|
+
body,
|
|
48
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(5e3)])
|
|
49
|
+
});
|
|
50
|
+
await response.body?.cancel();
|
|
51
|
+
if (!response.ok) throw new Error();
|
|
52
|
+
} catch {
|
|
53
|
+
throw new Error("QA webhook delivery failed");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export {
|
|
59
|
+
createWebhookNotification,
|
|
60
|
+
verifyWebhookSignature
|
|
61
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SecretRedactor, type CredentialResolver, type ExecutionPlan, type Executor } from "@open-qa/qa-engine";
|
|
1
|
+
import { SecretRedactor, type ProviderRegistry, type CredentialResolver, type ExecutionPlan, type Executor } from "@open-qa/qa-engine";
|
|
2
2
|
import { type EngineOptions } from "../engine.js";
|
|
3
3
|
import type { CloudRunIdentity } from "../adapters/secret-manager-credential-resolver.js";
|
|
4
4
|
import { type ResourceResolver } from "../adapters/db-lease-pool.js";
|
|
@@ -7,6 +7,7 @@ import type { ArtifactCatalog } from "../adapters/gcs/artifact-store.js";
|
|
|
7
7
|
import { type JobClaim, type JobOutcome, type PgJobQueue } from "./queue.js";
|
|
8
8
|
export interface WorkerExecution {
|
|
9
9
|
queue: PgJobQueue;
|
|
10
|
+
providers?: ProviderRegistry;
|
|
10
11
|
objects: EventObjects;
|
|
11
12
|
resolveResource: ResourceResolver;
|
|
12
13
|
credentials: (identity: CloudRunIdentity & {
|
package/src/worker/execution.js
CHANGED
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
-
SecretRedactor
|
|
2
|
+
SecretRedactor,
|
|
3
|
+
loadProviderRegistry
|
|
3
4
|
} from "@open-qa/qa-engine";
|
|
4
5
|
import { createEngine } from "../engine.js";
|
|
5
6
|
import { DbLeasePool } from "../adapters/db-lease-pool.js";
|
|
6
7
|
import { PgArtifactCatalog } from "../adapters/gcs/pg-catalog.js";
|
|
7
8
|
import { JobExecutionError } from "./execution-error.js";
|
|
8
9
|
import { PgClassificationStore } from "../adapters/pg-classification-store.js";
|
|
10
|
+
import { buildResultTrace, resultCaseId } from "../result-trace.js";
|
|
9
11
|
import { jobRunStore } from "./store.js";
|
|
12
|
+
import { captureExecutionSnapshot, sourceVersions } from "../execution-snapshot.js";
|
|
10
13
|
import { lockJob } from "./queue.js";
|
|
11
14
|
function createJobExecution(deps) {
|
|
15
|
+
let registry;
|
|
12
16
|
return async (job, signal) => {
|
|
13
17
|
const releases = /* @__PURE__ */ new Map();
|
|
14
18
|
const acquired = /* @__PURE__ */ new Set();
|
|
@@ -29,14 +33,80 @@ function createJobExecution(deps) {
|
|
|
29
33
|
const prepared = await deps.prepare(job, signal);
|
|
30
34
|
if (prepared.plan.key !== job.flow)
|
|
31
35
|
throw new Error("Worker flow does not match the submitted flow");
|
|
36
|
+
const target = job.target ?? job.request.target;
|
|
37
|
+
const { plan, options } = prepared;
|
|
38
|
+
const placement = options.placement ?? "local-host";
|
|
39
|
+
const resultInput = {
|
|
40
|
+
projectId: job.projectId,
|
|
41
|
+
flow: plan.key,
|
|
42
|
+
plan,
|
|
43
|
+
context: job.request.runContext,
|
|
44
|
+
attemptId: job.runId,
|
|
45
|
+
retryOf: job.retryOf ?? void 0,
|
|
46
|
+
batchId: job.batchId,
|
|
47
|
+
caseRevision: options.flowRevision,
|
|
48
|
+
target,
|
|
49
|
+
commit: job.request.commit,
|
|
50
|
+
parameters: {
|
|
51
|
+
runtime: job.request.runtime,
|
|
52
|
+
modelAccess: job.request.modelAccess,
|
|
53
|
+
placement,
|
|
54
|
+
agentAt: options.agentAt,
|
|
55
|
+
headed: options.stage?.headed,
|
|
56
|
+
level: options.level,
|
|
57
|
+
replay: options.replay === "off" ? "off" : "enabled"
|
|
58
|
+
},
|
|
59
|
+
environment: { suite: plan.acceptance?.revision, node: process.version }
|
|
60
|
+
};
|
|
61
|
+
if (plan.acceptance || plan.traceability?.caseId)
|
|
62
|
+
await deps.queue.recordPreparedTrace(
|
|
63
|
+
job,
|
|
64
|
+
buildResultTrace({ ...resultInput, started: false })
|
|
65
|
+
);
|
|
66
|
+
const providers = deps.providers ?? await (registry ??= loadProviderRegistry());
|
|
67
|
+
const page = options.stage?.page;
|
|
68
|
+
for (const reference of plan.providers ?? []) {
|
|
69
|
+
providers.module(reference);
|
|
70
|
+
providers.resolve(reference.kind, reference.id, target, placement);
|
|
71
|
+
if (reference.provider === "open-qa") continue;
|
|
72
|
+
if (reference.kind === "access") {
|
|
73
|
+
if (page?.accessHeaders?.origin !== new URL(options.target.url).origin)
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Worker access policy ${reference.id} requires headers bound to its target`
|
|
76
|
+
);
|
|
77
|
+
} else if (!page || page.target === "prod") {
|
|
78
|
+
throw new Error(
|
|
79
|
+
`Worker capability ${reference.id} requires a non-production page policy`
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
for (const view of Object.values(plan.views)) {
|
|
84
|
+
const reference = providers.resolve("surface", view.surface, target, placement);
|
|
85
|
+
if (reference.provider !== "open-qa" && !plan.providers?.some((item) => item.kind === "surface" && item.id === view.surface))
|
|
86
|
+
throw new Error(
|
|
87
|
+
`Worker plan is missing its surface provider reference for ${view.surface}`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
for (const lane of plan.lanes)
|
|
91
|
+
for (const tool of lane.spec.tools ?? []) {
|
|
92
|
+
const reference = providers.resolve("tool", tool, target, placement);
|
|
93
|
+
if (reference.provider !== "open-qa" && !plan.providers?.some((item) => item.kind === "tool" && item.id === tool))
|
|
94
|
+
throw new Error(`Worker plan is missing its tool provider reference for ${tool}`);
|
|
95
|
+
}
|
|
32
96
|
const revision = await prepared.verifyRevision();
|
|
33
97
|
if (!revision || job.commit && job.commit !== revision)
|
|
34
98
|
throw new Error("Worker target revision is unavailable or changed");
|
|
35
99
|
await deps.queue.recordRevision(job, revision);
|
|
100
|
+
const scope = deps.queue.classificationScope(job.projectId);
|
|
36
101
|
const notifier = prepared.options.notifier;
|
|
37
102
|
if (notifier)
|
|
38
103
|
deps.queue.deferClassificationNotification(job, async (runIds) => {
|
|
39
|
-
const classifications = new PgClassificationStore(
|
|
104
|
+
const classifications = new PgClassificationStore(
|
|
105
|
+
deps.queue.db,
|
|
106
|
+
job.projectId,
|
|
107
|
+
void 0,
|
|
108
|
+
scope
|
|
109
|
+
);
|
|
40
110
|
for (const runId of runIds) {
|
|
41
111
|
const classification = (await classifications.getClassification(runId))?.classification;
|
|
42
112
|
if (!classification) continue;
|
|
@@ -102,12 +172,49 @@ function createJobExecution(deps) {
|
|
|
102
172
|
return handle;
|
|
103
173
|
}
|
|
104
174
|
};
|
|
175
|
+
const flowRevision = options.flowRevision;
|
|
176
|
+
const executionSnapshot = flowRevision && /^[a-f0-9]{64}$/.test(flowRevision) && Object.values(plan.views).some(({ surface }) => surface === "web") ? captureExecutionSnapshot({
|
|
177
|
+
config: {
|
|
178
|
+
projectId: job.projectId,
|
|
179
|
+
heal: options.heal,
|
|
180
|
+
targets: {
|
|
181
|
+
[target]: {
|
|
182
|
+
url: options.target.url,
|
|
183
|
+
revision: /^[a-f0-9]{40,64}$/.test(revision ?? "") ? revision : void 0,
|
|
184
|
+
allow: page?.allowedHosts ?? [new URL(options.target.url).hostname],
|
|
185
|
+
access: page?.access ? "cloudflare" : "none"
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
definitions: {
|
|
190
|
+
flow: { source: plan.key, sha256: flowRevision },
|
|
191
|
+
suite: null,
|
|
192
|
+
config: null
|
|
193
|
+
},
|
|
194
|
+
plan,
|
|
195
|
+
targetName: target,
|
|
196
|
+
runtime: options.runtimeId ?? job.request.runtime,
|
|
197
|
+
modelAccess: options.modelAccess,
|
|
198
|
+
retries: 0,
|
|
199
|
+
placement,
|
|
200
|
+
agentAt: options.agentAt,
|
|
201
|
+
headed: options.stage?.headed,
|
|
202
|
+
level: options.level,
|
|
203
|
+
versions: await sourceVersions(options.root),
|
|
204
|
+
env: options.env ?? {},
|
|
205
|
+
publicEnv: options.consumerPublicEnv,
|
|
206
|
+
subscriptionToken: options.subscriptionToken
|
|
207
|
+
}) : void 0;
|
|
105
208
|
const store = jobRunStore(deps.queue, job, deps.objects);
|
|
106
209
|
const engine = createEngine({
|
|
107
210
|
...prepared.options,
|
|
108
211
|
allowConsumerHooks: prepared.options.allowConsumerHooks ?? false,
|
|
109
212
|
billing: job.trigger === "developer" && job.request.modelAccess === "personal" && job.request.runtime === "claude-code" ? "subscription" : "metered",
|
|
110
213
|
runId: job.runId,
|
|
214
|
+
visualBaseline: {
|
|
215
|
+
caseId: resultCaseId(job.projectId, plan.traceability?.caseId ?? plan.key),
|
|
216
|
+
environment: target
|
|
217
|
+
},
|
|
111
218
|
batchId: job.batchId,
|
|
112
219
|
principalId: job.createdBy,
|
|
113
220
|
executor,
|
|
@@ -117,7 +224,8 @@ function createJobExecution(deps) {
|
|
|
117
224
|
// Queue-managed retry completion owns quarantine transitions and notifications.
|
|
118
225
|
flowStatus: void 0,
|
|
119
226
|
notifier: void 0,
|
|
120
|
-
|
|
227
|
+
classificationScope: scope,
|
|
228
|
+
classifications: new PgClassificationStore(deps.queue.db, job.projectId, guard, scope),
|
|
121
229
|
targetRevision: prepared.verifyRevision,
|
|
122
230
|
runStore: {
|
|
123
231
|
...store,
|
|
@@ -125,6 +233,17 @@ function createJobExecution(deps) {
|
|
|
125
233
|
...input,
|
|
126
234
|
metadata: {
|
|
127
235
|
...input.metadata,
|
|
236
|
+
attempt: job.retryOf ? 2 : 1,
|
|
237
|
+
...executionSnapshot && { executionSnapshot },
|
|
238
|
+
...options.quarantine && { quarantinePolicy: options.quarantine },
|
|
239
|
+
resultTrace: buildResultTrace({
|
|
240
|
+
...resultInput,
|
|
241
|
+
targetRevision: revision,
|
|
242
|
+
environment: {
|
|
243
|
+
...resultInput.environment,
|
|
244
|
+
origin: new URL(options.target.url).origin
|
|
245
|
+
}
|
|
246
|
+
}),
|
|
128
247
|
...prepared.options.classificationOwners ? { flowOwner: prepared.options.classificationOwners.flowOwner } : {}
|
|
129
248
|
}
|
|
130
249
|
})
|
package/src/worker/index.d.ts
CHANGED
|
@@ -6,3 +6,7 @@ export { JobExecutionError } from "./execution-error.js";
|
|
|
6
6
|
export { PgResultNotifications, RESULT_DELIVERY_MAX_ATTEMPTS, RESULT_DELIVERY_INITIAL_BACKOFF_SECONDS, RESULT_DELIVERY_RETRY_WINDOW_SECONDS, type ResultNotificationOptions, } from "./result-notifications.js";
|
|
7
7
|
export { GitHubCommitStatusNotifier, GitHubPrCommentNotifier, DiscordResultNotifier, resultNotifiers, type ResultContext, type ResultTransports, } from "../result-notifier.js";
|
|
8
8
|
export { createGitHubResultTransport, createDiscordResultTransport, type ResultHttp, } from "../result-transports.js";
|
|
9
|
+
export { createWebhookNotification, verifyWebhookSignature } from "../webhook-notification.js";
|
|
10
|
+
export { actorPermissions } from "../system-config.js";
|
|
11
|
+
export { resolveAccessBinding } from "../access-binding.js";
|
|
12
|
+
export { LocalHostExecutor, type LocalHostExecutorOptions } from "../local-host-executor.js";
|
package/src/worker/index.js
CHANGED
|
@@ -19,22 +19,31 @@ import {
|
|
|
19
19
|
createGitHubResultTransport,
|
|
20
20
|
createDiscordResultTransport
|
|
21
21
|
} from "../result-transports.js";
|
|
22
|
+
import { createWebhookNotification, verifyWebhookSignature } from "../webhook-notification.js";
|
|
23
|
+
import { actorPermissions } from "../system-config.js";
|
|
24
|
+
import { resolveAccessBinding } from "../access-binding.js";
|
|
25
|
+
import { LocalHostExecutor } from "../local-host-executor.js";
|
|
22
26
|
export {
|
|
23
27
|
DiscordResultNotifier,
|
|
24
28
|
GitHubCommitStatusNotifier,
|
|
25
29
|
GitHubPrCommentNotifier,
|
|
26
30
|
JOB_LEASE_MS,
|
|
27
31
|
JobExecutionError,
|
|
32
|
+
LocalHostExecutor,
|
|
28
33
|
PgJobQueue,
|
|
29
34
|
PgResultNotifications,
|
|
30
35
|
RESULT_DELIVERY_INITIAL_BACKOFF_SECONDS,
|
|
31
36
|
RESULT_DELIVERY_MAX_ATTEMPTS,
|
|
32
37
|
RESULT_DELIVERY_RETRY_WINDOW_SECONDS,
|
|
38
|
+
actorPermissions,
|
|
33
39
|
createDiscordResultTransport,
|
|
34
40
|
createGitHubResultTransport,
|
|
35
41
|
createJobExecution,
|
|
42
|
+
createWebhookNotification,
|
|
36
43
|
createWorkerPruner,
|
|
37
44
|
installWorkerSignals,
|
|
45
|
+
resolveAccessBinding,
|
|
38
46
|
resultNotifiers,
|
|
39
|
-
startQaWorker
|
|
47
|
+
startQaWorker,
|
|
48
|
+
verifyWebhookSignature
|
|
40
49
|
};
|
|
@@ -35,8 +35,8 @@ async function drainQuarantineNotifications(db, options) {
|
|
|
35
35
|
{
|
|
36
36
|
content: `QA flow quarantined: ${label(row.flow, "flow")}
|
|
37
37
|
Owner: ${label(entry.owner ?? "unassigned", "owner")}
|
|
38
|
-
|
|
39
|
-
Use --repeat
|
|
38
|
+
Flaky execution threshold reached. Runs continue without blocking or result notifications. Run: ${run}
|
|
39
|
+
Use --repeat to check for automatic release.`,
|
|
40
40
|
allowedMentions: { parse: [] }
|
|
41
41
|
},
|
|
42
42
|
controller.signal
|
package/src/worker/queue.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { PoolClient } from "pg";
|
|
2
|
-
import { type
|
|
2
|
+
import { type ClassificationRegistry } from "@open-qa/qa-engine";
|
|
3
|
+
import { type SubmitBatch, type BatchDto, type ResultTrace, type Verdict } from "@open-qa/qa-engine/protocol";
|
|
3
4
|
import { QaDatabase } from "../db/database.js";
|
|
4
5
|
export declare const JOB_LEASE_MS = 120000;
|
|
5
6
|
export interface JobToken {
|
|
@@ -40,16 +41,19 @@ export declare function lockJob(client: PoolClient, job: JobToken): Promise<JobR
|
|
|
40
41
|
export declare class PgJobQueue {
|
|
41
42
|
readonly db: QaDatabase;
|
|
42
43
|
readonly projects: readonly string[];
|
|
44
|
+
private readonly classificationRegistry;
|
|
43
45
|
private readonly classificationNotifications;
|
|
44
46
|
private readonly completingNotifications;
|
|
45
47
|
deferClassificationNotification(job: JobToken, notify: (runIds: string[]) => Promise<void>): void;
|
|
46
48
|
private notifyCompletion;
|
|
47
49
|
private complete;
|
|
48
50
|
private pruneClassificationNotifications;
|
|
49
|
-
constructor(db: QaDatabase, projects: readonly string[]);
|
|
51
|
+
constructor(db: QaDatabase, projects: readonly string[], classificationRegistry?: ClassificationRegistry);
|
|
52
|
+
classificationScope(project: string): import("@open-qa/qa-engine").ProjectClassificationRegistry;
|
|
50
53
|
private scoped;
|
|
51
54
|
claim(owner: string, concurrency: number, signal?: AbortSignal): Promise<JobClaim | undefined>;
|
|
52
55
|
recordRevision(job: JobToken, revision: string): Promise<void>;
|
|
56
|
+
recordPreparedTrace(job: JobToken, trace: ResultTrace): Promise<void>;
|
|
53
57
|
start(job: JobToken): Promise<boolean>;
|
|
54
58
|
heartbeat(job: JobToken): Promise<{
|
|
55
59
|
cancelled: boolean;
|