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
32 changes: 32 additions & 0 deletions docs/recipe-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,38 @@ Use `allowFailure: true` or `advisory: true` for evidence-only workflow steps.
Failed advisory steps are reported in `advisoryFailures` and do not make an
otherwise successful recipe return `success: false`.

### Parallel Browser Probes

Playground recipe `wordpress.browser-probe` commands share one lazily launched
Chromium browser, with a fresh context for each probe. Use the file references
in the step output or `browserEvidence` to find its captures under
`files/browser/probe-*/`; standalone probes still use `files/browser/`.

By default, steps run serially. Give consecutive independent browser probes in
one workflow phase (`before`, `steps`, or `after`) the same `parallelGroup` to
opt in to overlap:

```json
{
"runtime": { "workers": 2 },
"workflow": {
"steps": [
{ "command": "wordpress.browser-probe", "args": ["url=/site-a/"], "parallelGroup": "homepages" },
{ "command": "wordpress.browser-probe", "args": ["url=/site-b/"], "parallelGroup": "homepages" }
]
}
}
```

Group names use letters, numbers, underscores, and hyphens. Grouped probes
cannot use `continuation` or `pluginInput`. Only group probes that do not depend
on one another or compete over mutable WordPress state: browser contexts are
isolated, but the site is shared. Each wave runs at most `runtime.workers`
probes (one by default). Results are published in recipe order with each probe's
own timings, assertions, and artifacts. A required step failure stops the
recipe after the already-started wave settles; advisory failures are recorded
without stopping subsequent waves.

### Phased Plugin Inputs

A required workflow step may declare `pluginInput` to consume one named artifact
Expand Down
77 changes: 77 additions & 0 deletions packages/cli/src/commands/recipe-browser-probe-groups.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { cpus } from "node:os"
import type { RuntimeWorkerCount } from "@automattic/wp-codebox-core"
import type { RecipeWorkflowStepRef } from "../recipe-validation.js"
import { RecipeRunTimeoutError, bestEffortTimeout, watchRecipeOperation } from "./recipe-run-output.js"

/** Split consecutive probes in the same phase into bounded waves. */
export function* recipeWorkflowWaves(steps: RecipeWorkflowStepRef[], workers: RuntimeWorkerCount | undefined): Generator<RecipeWorkflowStepRef[]> {
const limit = workers === "auto" ? Math.max(1, cpus().length - 1) : workers ?? 1
for (let index = 0; index < steps.length;) {
const first = steps[index++]
const wave = [first]
if (first.step.parallelGroup) {
while (wave.length < limit && index < steps.length) {
const next = steps[index]
if (next.phase !== first.phase || next.step.parallelGroup !== first.step.parallelGroup) break
wave.push(next)
index++
}
}
yield wave
}
}

export function recipeWorkflowOperation({ phase, index, step }: RecipeWorkflowStepRef): string {
return `workflow.${phase}[${index}]:${step.command}`
}

export async function runRecipeProbeWave<T>(
wave: RecipeWorkflowStepRef[],
execute: (step: RecipeWorkflowStepRef, signal: AbortSignal) => Promise<T>,
run: (operation: string, work: () => Promise<void>) => Promise<void>,
record: (step: RecipeWorkflowStepRef, outcome: ProbeOutcome<T>) => Promise<void>,
): Promise<void> {
const controller = new AbortController()
const startedAtMs = Date.now()
const outcomes: Array<ProbeOutcome<T> | undefined> = []
let waveFailure: { error: unknown } | undefined
try {
await run(`workflow.${wave[0].phase}.parallel:${wave[0].step.parallelGroup}`, async () => {
await Promise.all(wave.map(async (step, index) => {
const stepController = new AbortController()
const signal = AbortSignal.any([controller.signal, stepController.signal])
const execution = Promise.resolve().then(() => execute(step, signal))
try {
const result = step.step.timeoutMs === undefined ? await execution : await watchRecipeOperation(recipeWorkflowOperation(step), execution, startedAtMs, step.step.timeoutMs)
outcomes[index] = { status: "completed", result }
} catch (error) {
outcomes[index] = { status: "failed", error, startedAtMs, finishedAtMs: Date.now() }
if (error instanceof RecipeRunTimeoutError) {
stepController.abort()
// Give an aborted probe a bounded window to close its context and flush evidence.
await bestEffortTimeout(execution.catch(() => undefined), 2_000)
}
}
}))
})
} catch (error) {
waveFailure = { error }
controller.abort()
}

// Publish in recipe order, even when a later probe completes or fails first.
const finishedAtMs = Date.now()
let firstRequiredFailure: { error: unknown } | undefined
for (const [index, step] of wave.entries()) {
const outcome = outcomes[index] ?? { status: "failed", error: waveFailure?.error, startedAtMs, finishedAtMs }
try {
await record(step, outcome)
} catch (error) {
firstRequiredFailure ??= { error }
}
}
if (waveFailure) throw waveFailure.error
if (firstRequiredFailure) throw firstRequiredFailure.error
}

type ProbeOutcome<T> = { status: "completed"; result: T } | { status: "failed"; error: unknown; startedAtMs: number; finishedAtMs: number }
1 change: 1 addition & 0 deletions packages/cli/src/commands/recipe-run-workflow-evidence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ export async function executeRecipeWorkflowStep(runtime: Runtime, workflowStep:
return phase(await executeWordPressRunWorkloadJsonRecipeCommand(runtime, step.args ?? [], recipeDirectory, sandboxWorkspace, undefined, undefined, inputMountPathMap, signal))
}
const spec = await recipeExecutionSpec(workflowStep.step, recipeDirectory, sandboxWorkspace, { inputMountPathMap })
signal?.throwIfAborted()
const execution = await runtime.execute({ ...spec, signal })
return {
...withRecipeExecutionPhase(execution, workflowStep.phase, workflowStep.index, step.command, recipeWorkflowArgsEvidence(spec.originalArgs, spec.resolvedArgs), step.metadata),
Expand Down
30 changes: 26 additions & 4 deletions packages/cli/src/commands/recipe-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { artifactManifestFilesByPath, parseBenchResults, writeBenchmarkArtifactE
import { createRecipeRunContext } from "./recipe-run-context.js"
import { collectRecipeDeclaredArtifacts, materializeTypedRecipeDeclaredArtifacts, recipeDeclaredArtifactFailure, recipeProbeFailure, recipeRuntimeEvidenceFiles } from "./recipe-declared-artifacts.js"
import { completedRecipeOutputFields, finalizeCompletedRecipeRun, finalizeRecipeValidationFailure, finalizeRecoveredRecipeFailure, runRecipeCleanup, RunResourceCleanupError, type RunResourceCleanupEvidence } from "./recipe-run-finalizer.js"
import { recipeWorkflowOperation, recipeWorkflowWaves, runRecipeProbeWave } from "./recipe-browser-probe-groups.js"
import { RecipeRunPhaseExecutor } from "./recipe-run-phase-executor.js"
import { RecipeArtifactsMountConflictError, recipeArtifactsMountConflict } from "./recipe-run-artifacts-mount-guard.js"
import { createRecipeInterruptionController, interruptedRecipeOutput, markRecipeArtifactsFinalized, recipeInterruptionSerializedError } from "./recipe-run-interruption.js"
Expand Down Expand Up @@ -375,8 +376,29 @@ export async function runRecipe(options: RecipeRunOptions, interruption?: Recipe
throw startupProbeFailure
}
await phaseTracker.run("run_workloads", phaseWorkflowData(workflowSteps), async () => {
for (const workflowStep of workflowSteps) {
const operation = `workflow.${workflowStep.phase}[${workflowStep.index}]:${workflowStep.step.command}`
for (const wave of recipeWorkflowWaves(workflowSteps, plan.runtime.workers)) {
interruption?.throwIfInterrupted()
if (wave[0].step.parallelGroup) {
await runRecipeProbeWave(wave,
(step, signal) => executeRecipeWorkflowStep(runtime!, step, recipeDirectory, sandboxWorkspace, configuredArtifactsDirectory, options, inputMountPathMap, undefined, signal),
awaitRecipe,
async (step, outcome) => {
const advisory = recipeWorkflowStepIsAdvisory(step.step)
if (outcome.status === "completed") {
executions.push({ ...outcome.result, ...(advisory ? { recipeAdvisory: true } : {}) })
return
}
const failure = recipeStepFailure(step, outcome.error, outcome.startedAtMs, outcome.finishedAtMs)
stepFailures.push(failure)
await artifactPointer.update({ command: recipeWorkflowOperation(step), commandStatus: "failed", failure: failure.error, phases: phaseTracker.list(), stepFailures })
if (!advisory) throw outcome.error
advisoryFailures.push(recipeAdvisoryFailure(step, outcome.error))
},
)
continue
}
const [workflowStep] = wave
const operation = recipeWorkflowOperation(workflowStep)
const stepStartedAtMs = Date.now()
let continuationProgress: RecipeContinuationProgress | undefined
try {
Expand Down Expand Up @@ -1557,8 +1579,8 @@ function packageDependencyVersion(manifest: Record<string, unknown>, name: strin
?? stringValue(recordValue(manifest.peerDependencies)?.[name])
}

function recipeStepMetadata(step: WorkspaceRecipe["workflow"]["steps"][number]): { command: string; args: string[]; continuation?: WorkspaceRecipe["workflow"]["steps"][number]["continuation"] } {
return stripUndefined({ command: step.command, args: step.args ?? [], continuation: step.continuation }) as { command: string; args: string[]; continuation?: WorkspaceRecipe["workflow"]["steps"][number]["continuation"] }
function recipeStepMetadata(step: WorkspaceRecipe["workflow"]["steps"][number]) {
return { command: step.command, args: step.args ?? [], ...(step.continuation ? { continuation: step.continuation } : {}), ...(step.parallelGroup ? { parallelGroup: step.parallelGroup } : {}) }
}

function effectiveRecipePreview(recipePreview: RuntimePreviewSpec | undefined, options: RecipeRunOptions): RuntimePreviewSpec {
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/recipe-dry-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ interface RecipeDryRunStep {
resolvedCommand: string
resolvedArgs: string[]
resolvedParsedArgs: Record<string, string | true>
parallelGroup?: string
continuation?: WorkspaceRecipe["workflow"]["steps"][number]["continuation"]
policy: {
status: "allowed" | "denied"
Expand Down Expand Up @@ -663,6 +664,7 @@ async function recipeDryRunStep(step: WorkspaceRecipe["workflow"]["steps"][numbe
resolvedCommand: resolved.command,
resolvedArgs: resolved.args,
resolvedParsedArgs: parseRecipeArgs(resolved.args),
...(step.parallelGroup ? { parallelGroup: step.parallelGroup } : {}),
...(step.continuation ? { continuation: step.continuation } : {}),
policy: {
status: allowed ? "allowed" : "denied",
Expand Down
9 changes: 9 additions & 0 deletions packages/cli/src/recipe-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,13 @@ export async function validateWorkspaceRecipeSemantics(recipe: WorkspaceRecipe,
}

await validateRecipeStepArgs(step, path, addIssue, recipeDirectory)
if (step.parallelGroup !== undefined && (
!["before", "steps", "after"].includes(phase)
|| normalizeRuntimeBackendKind(recipe.runtime?.backend) !== "wordpress-playground"
|| step.command !== "wordpress.browser-probe" || step.continuation || step.pluginInput
)) {
addIssue("invalid-parallel-group", `${path}.parallelGroup`, "Only Playground workflow browser probes without continuation or pluginInput can join a parallel group.")
}
if (step.pluginInput) {
const artifact = (recipe.artifacts?.typed ?? []).find((candidate) => candidate.name === step.pluginInput?.artifact)
if (!artifact) {
Expand Down Expand Up @@ -872,6 +879,7 @@ export async function validateWorkspaceRecipeSemantics(recipe: WorkspaceRecipe,
continue
}
await validateRecipeStepArgs(probe.step, path, addIssue, recipeDirectory)
if (probe.step.parallelGroup !== undefined) addIssue("invalid-parallel-group", `${path}.parallelGroup`, "Parallel groups are only available in the recipe workflow.")
}

for (const [index, name] of (recipe.inputs?.secretEnv ?? []).entries()) {
Expand Down Expand Up @@ -1540,6 +1548,7 @@ async function validateRecipePluginRuntime(pluginRuntime: WorkspaceRecipePluginR
continue
}
await validateRecipeStepArgs(step, path, addIssue, recipeDirectory)
if (step.parallelGroup !== undefined) addIssue("invalid-parallel-group", `${path}.parallelGroup`, "Parallel groups are only available in the recipe workflow.")
}

for (const [index, probe] of (pluginRuntime.healthProbes ?? []).entries()) {
Expand Down
1 change: 1 addition & 0 deletions packages/runtime-core/src/recipe-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1299,6 +1299,7 @@ export function createWorkspaceRecipeJsonSchema(options: WorkspaceRecipeJsonSche
items: { type: "string" },
},
timeoutMs: { type: "integer", minimum: 1 },
parallelGroup: { type: "string", pattern: "^[A-Za-z0-9_-]+$" },
resultPaths: {
type: "array",
maxItems: 16,
Expand Down
1 change: 1 addition & 0 deletions packages/runtime-core/src/runtime-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ export interface WorkspaceRecipeSourcePackage {
export interface WorkspaceRecipeStep {
command: string
args?: string[]
parallelGroup?: string
timeoutMs?: number
resultPaths?: WorkspaceRecipeResultPath[]
continuation?: WorkspaceRecipeStepContinuation
Expand Down
15 changes: 11 additions & 4 deletions packages/runtime-playground/src/browser-environment-matrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,17 @@ export async function createPlaywrightBrowserEnvironmentContext(browser: Browser
...(environment.permissions?.length || environment.geolocation?.permission === "granted" ? { permissions: [...new Set([...(environment.permissions ?? []).filter((permission) => permission !== "geolocation"), ...(environment.geolocation?.permission === "granted" ? ["geolocation"] : [])])] } : {}),
}
const context = await browser.newContext(contextOptions)
const page = await context.newPage()
const geolocationPermissionCleanup = environment.geolocation?.permission === "denied" ? await applyPlaywrightGeolocationPermission(page, "denied") : undefined
await applyPlaywrightPageEnvironment(page, environment, options)
return { context, page, close: async () => { await geolocationPermissionCleanup?.(); await context.close() } }
try {
const page = await context.newPage()
const geolocationPermissionCleanup = environment.geolocation?.permission === "denied" ? await applyPlaywrightGeolocationPermission(page, "denied") : undefined
await applyPlaywrightPageEnvironment(page, environment, options)
return { context, page, close: async () => {
try { await geolocationPermissionCleanup?.() } finally { await context.close() }
} }
} catch (error) {
await context.close().catch(() => undefined)
throw error
}
}

export async function observePlaywrightBrowserEnvironment(page: Page, requested: BrowserEnvironment, resolved: ResolvedBrowserEnvironment): Promise<NonNullable<BrowserArtifactSummary["environment"]>> {
Expand Down
Loading
Loading