diff --git a/docs/recipe-contract.md b/docs/recipe-contract.md index 61596796..13a2c58a 100644 --- a/docs/recipe-contract.md +++ b/docs/recipe-contract.md @@ -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 diff --git a/packages/cli/src/commands/recipe-browser-probe-groups.ts b/packages/cli/src/commands/recipe-browser-probe-groups.ts new file mode 100644 index 00000000..9cbec59f --- /dev/null +++ b/packages/cli/src/commands/recipe-browser-probe-groups.ts @@ -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 { + 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( + wave: RecipeWorkflowStepRef[], + execute: (step: RecipeWorkflowStepRef, signal: AbortSignal) => Promise, + run: (operation: string, work: () => Promise) => Promise, + record: (step: RecipeWorkflowStepRef, outcome: ProbeOutcome) => Promise, +): Promise { + const controller = new AbortController() + const startedAtMs = Date.now() + const outcomes: Array | 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 = { status: "completed"; result: T } | { status: "failed"; error: unknown; startedAtMs: number; finishedAtMs: number } diff --git a/packages/cli/src/commands/recipe-run-workflow-evidence.ts b/packages/cli/src/commands/recipe-run-workflow-evidence.ts index aac931cc..c66a194f 100644 --- a/packages/cli/src/commands/recipe-run-workflow-evidence.ts +++ b/packages/cli/src/commands/recipe-run-workflow-evidence.ts @@ -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), diff --git a/packages/cli/src/commands/recipe-run.ts b/packages/cli/src/commands/recipe-run.ts index ae56fa64..ea430083 100644 --- a/packages/cli/src/commands/recipe-run.ts +++ b/packages/cli/src/commands/recipe-run.ts @@ -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" @@ -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 { @@ -1557,8 +1579,8 @@ function packageDependencyVersion(manifest: Record, 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 { diff --git a/packages/cli/src/recipe-dry-run.ts b/packages/cli/src/recipe-dry-run.ts index 3dc85834..434e06ad 100644 --- a/packages/cli/src/recipe-dry-run.ts +++ b/packages/cli/src/recipe-dry-run.ts @@ -272,6 +272,7 @@ interface RecipeDryRunStep { resolvedCommand: string resolvedArgs: string[] resolvedParsedArgs: Record + parallelGroup?: string continuation?: WorkspaceRecipe["workflow"]["steps"][number]["continuation"] policy: { status: "allowed" | "denied" @@ -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", diff --git a/packages/cli/src/recipe-validation.ts b/packages/cli/src/recipe-validation.ts index 4cf60fbb..c57060ba 100644 --- a/packages/cli/src/recipe-validation.ts +++ b/packages/cli/src/recipe-validation.ts @@ -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) { @@ -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()) { @@ -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()) { diff --git a/packages/runtime-core/src/recipe-schema.ts b/packages/runtime-core/src/recipe-schema.ts index a693d58a..65328c66 100644 --- a/packages/runtime-core/src/recipe-schema.ts +++ b/packages/runtime-core/src/recipe-schema.ts @@ -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, diff --git a/packages/runtime-core/src/runtime-contracts.ts b/packages/runtime-core/src/runtime-contracts.ts index a3bc1e67..b0d9f9a7 100644 --- a/packages/runtime-core/src/runtime-contracts.ts +++ b/packages/runtime-core/src/runtime-contracts.ts @@ -294,6 +294,7 @@ export interface WorkspaceRecipeSourcePackage { export interface WorkspaceRecipeStep { command: string args?: string[] + parallelGroup?: string timeoutMs?: number resultPaths?: WorkspaceRecipeResultPath[] continuation?: WorkspaceRecipeStepContinuation diff --git a/packages/runtime-playground/src/browser-environment-matrix.ts b/packages/runtime-playground/src/browser-environment-matrix.ts index 283b5de6..a9fef2c8 100644 --- a/packages/runtime-playground/src/browser-environment-matrix.ts +++ b/packages/runtime-playground/src/browser-environment-matrix.ts @@ -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> { diff --git a/packages/runtime-playground/src/browser-probe-runner.ts b/packages/runtime-playground/src/browser-probe-runner.ts index b1730efd..fa4190b6 100644 --- a/packages/runtime-playground/src/browser-probe-runner.ts +++ b/packages/runtime-playground/src/browser-probe-runner.ts @@ -42,7 +42,7 @@ export interface BrowserProbeRunPlan { export interface BrowserProbeDiagnosticProvider { id: string - setup(input: BrowserProbeDiagnosticSetupInput): Promise + setup(input: BrowserProbeDiagnosticSetupInput & { page: import("playwright").Page; cookieUrls: string[] }): Promise collect(input: BrowserProbeDiagnosticCollectInput): Promise } @@ -101,6 +101,8 @@ export async function runBrowserProbeCommand({ onProgress, diagnosticProviders, session, + acquireBrowser, + browserFilesDirectory = "files/browser", }: { abortSignal?: AbortSignal artifactRoot: string @@ -113,9 +115,11 @@ export async function runBrowserProbeCommand({ onProgress?: (event: BrowserCommandProgressEvent) => void diagnosticProviders?: BrowserProbeDiagnosticProvider[] session?: PlaywrightBrowserEnvironmentSession + acquireBrowser?: () => Promise + browserFilesDirectory?: string }): Promise<{ artifact: BrowserProbeArtifact; artifacts?: BrowserProbeArtifact[]; output: string }> { if (plan) { - return runSingleBrowserProbeCommand({ abortSignal, artifactRoot, command, plan, runtimeSpec, runPlaygroundCommand, server, spec, browserFilesDirectory: "files/browser", onProgress, diagnosticProviders, session }) + return runSingleBrowserProbeCommand({ abortSignal, artifactRoot, command, plan, runtimeSpec, runPlaygroundCommand, server, spec, browserFilesDirectory, onProgress, diagnosticProviders, session, acquireBrowser }) } const profileIds = browserProbeProfileIds(spec.args ?? []) @@ -131,13 +135,14 @@ export async function runBrowserProbeCommand({ runPlaygroundCommand, server, spec: { ...spec, args: browserProbeProfileArgs(spec.args ?? [], profile) }, - browserFilesDirectory: "files/browser", + browserFilesDirectory, + acquireBrowser, profileId: profile.id, onProgress, diagnosticProviders, }) } - return runSingleBrowserProbeCommand({ abortSignal, artifactRoot, command, runtimeSpec, runPlaygroundCommand, server, spec, browserFilesDirectory: "files/browser", onProgress, diagnosticProviders }) + return runSingleBrowserProbeCommand({ abortSignal, artifactRoot, command, runtimeSpec, runPlaygroundCommand, server, spec, browserFilesDirectory, onProgress, diagnosticProviders, acquireBrowser }) } const profiles = profileIds.map((profileId) => browserProbeProfile(profileId)) @@ -155,7 +160,8 @@ export async function runBrowserProbeCommand({ ...spec, args: browserProbeProfileArgs(spec.args ?? [], profile), }, - browserFilesDirectory: `files/browser/${profile.id}`, + browserFilesDirectory: `${browserFilesDirectory}/${profile.id}`, + acquireBrowser, profileId: profile.id, onProgress, diagnosticProviders, @@ -194,6 +200,7 @@ export async function runSingleBrowserProbeCommand({ onProgress, diagnosticProviders, session, + acquireBrowser, }: { abortSignal?: AbortSignal artifactRoot: string @@ -208,6 +215,7 @@ export async function runSingleBrowserProbeCommand({ onProgress?: (event: BrowserCommandProgressEvent) => void diagnosticProviders?: BrowserProbeDiagnosticProvider[] session?: PlaywrightBrowserEnvironmentSession + acquireBrowser?: () => Promise }): Promise<{ artifact: BrowserProbeArtifact; output: string }> { const args = spec.args ?? [] const runPlan = plan ?? await browserProbeRunPlanFromArgs(args, profileId, artifactRoot) @@ -276,7 +284,8 @@ export async function runSingleBrowserProbeCommand({ if (requestedContext.device && !deviceProfile) { throw new Error(`wordpress.browser-probe unknown Playwright device profile: ${requestedContext.device}`) } - const browser = session?.browser ?? await launchChromiumBrowser() + abortSignal?.throwIfAborted() + const browser = session?.browser ?? await (acquireBrowser ?? launchChromiumBrowser)() const browserMetadata = chromiumBrowserMetadata(browser) let finalUrl = targetUrl let windowLocationOrigin: string | undefined @@ -331,6 +340,7 @@ export async function runSingleBrowserProbeCommand({ environmentRuntime = await createPlaywrightBrowserEnvironmentContext(browser, resolved, { contextOptions: { ...topology.contextOptions(), ...(storageStateImport ? { storageState: storageStateImport.storageState } : {}), ...(capture.has("video") ? { recordVideo: { dir: videoSourceDirectory } } : {}) } }) } context = environmentRuntime.context + abortSignal?.throwIfAborted() if (context && browserPreviewNeedsContextRouting(networkPolicy) && !session) { await routeBrowserPreviewContextNetwork(context, networkPolicy, topology.origins.localProxyOrigin, routeTracker) } @@ -372,7 +382,7 @@ export async function runSingleBrowserProbeCommand({ const setupResult = await runBoundedBrowserDiagnostic({ command, phase: `diagnostics-setup:${provider.id}`, - operation: provider.setup({ command, runPlaygroundCommand, server }), + operation: provider.setup({ command, runPlaygroundCommand, server, page, cookieUrls: [...new Set([...topology.authCookieUrls([targetUrl]), new URL(preview.effectiveOrigin).origin + "/"])] }), timeoutMs: diagnosticsTimeoutMs, onError: (error) => errors.push(serializeBrowserError("probe-error", error)), }) @@ -522,7 +532,14 @@ export async function runSingleBrowserProbeCommand({ } catch (error) { errors.push(serializeBrowserError("probe-error", error)) } - const cleanupBrowser = session ? { close: async () => {} } : { close: async () => { await environmentRuntime?.close(); await browser.close() } } + const cleanupBrowser = { close: async () => { + if (session) return + try { + await environmentRuntime?.close() + } finally { + if (!acquireBrowser) await browser.close() + } + } } for (const routeError of await closeBrowserAndDrainPreviewRoutes(cleanupBrowser, routeTracker)) { const browserCloseFailed = routeError.message.includes("operation=browser-close") if (!pendingError && browserPreviewCleanupErrorIsFatal(routeError) && (browserCloseFailed || runPlan.routeHostDrain === "required")) { @@ -531,9 +548,9 @@ export async function runSingleBrowserProbeCommand({ } errors.push(serializeBrowserError("probe-error", routeError)) } + abortSignal?.removeEventListener("abort", abortHandler) if (videoHandle) { - // The recording is adopted from its staging directory rather than through - // video.saveAs(), which requires a browser connection that cleanup has closed. + // Read the finalized recording from staging, even if the browser is closed. try { const staged = (await readdir(videoSourceDirectory)).filter((entry) => entry.endsWith(".webm")).sort() if (staged.length === 0) throw new Error("wordpress.browser-probe capture=video produced no recording") @@ -655,7 +672,6 @@ export async function runSingleBrowserProbeCommand({ await artifactSession.writeJson("summary", "summary.json", result.summary) } - abortSignal?.removeEventListener("abort", abortHandler) if (pendingError) { if (!artifact) { throw pendingError diff --git a/packages/runtime-playground/src/browser-probe-support.ts b/packages/runtime-playground/src/browser-probe-support.ts index f0a3aa75..9f3f74eb 100644 --- a/packages/runtime-playground/src/browser-probe-support.ts +++ b/packages/runtime-playground/src/browser-probe-support.ts @@ -481,7 +481,9 @@ const BROWSER_WORDPRESS_DIAGNOSTICS_PLUGIN = phpBrowserWordPressDiagnosticsPlugi export async function installBrowserWordPressDiagnostics( runPlaygroundCommand: ((command: string, server: PlaygroundCliServer, options: { code: string } | { scriptPath: string }) => Promise) | undefined, server: PlaygroundCliServer, + probeId?: string, ): Promise { + const logPath = browserWordPressDiagnosticsLogPath(probeId) if (runPlaygroundCommand) { try { const response = await runPlaygroundCommand("wordpress.browser-diagnostics-setup", server, { @@ -490,8 +492,11 @@ $directory = '/wordpress/wp-content/mu-plugins'; if (!is_dir($directory)) { mkdir($directory, 0777, true); } -file_put_contents(${JSON.stringify(BROWSER_WORDPRESS_DIAGNOSTICS_MU_PLUGIN)}, base64_decode(${JSON.stringify(Buffer.from(BROWSER_WORDPRESS_DIAGNOSTICS_PLUGIN, "utf8").toString("base64"))})); -file_put_contents(${JSON.stringify(BROWSER_WORDPRESS_DIAGNOSTICS_LOG)}, ''); +$plugin = ${JSON.stringify(BROWSER_WORDPRESS_DIAGNOSTICS_MU_PLUGIN)}; +$temporary = tempnam($directory, 'wp-codebox-browser-'); +file_put_contents($temporary, base64_decode(${JSON.stringify(Buffer.from(BROWSER_WORDPRESS_DIAGNOSTICS_PLUGIN, "utf8").toString("base64"))})); +rename($temporary, $plugin); +file_put_contents(${JSON.stringify(logPath)}, ''); `, }) assertPlaygroundResponseOk("wordpress.browser-diagnostics-setup", response) @@ -507,7 +512,7 @@ file_put_contents(${JSON.stringify(BROWSER_WORDPRESS_DIAGNOSTICS_LOG)}, ''); try { await server.playground.writeFile(BROWSER_WORDPRESS_DIAGNOSTICS_MU_PLUGIN, BROWSER_WORDPRESS_DIAGNOSTICS_PLUGIN) - await server.playground.writeFile(BROWSER_WORDPRESS_DIAGNOSTICS_LOG, "") + await server.playground.writeFile(logPath, "") return true } catch { return false @@ -519,11 +524,13 @@ export async function browserWordPressDiagnosticsArtifact({ network, ready, server, + probeId, }: { artifactPath: string network: BrowserProbeNetworkRecord[] ready: boolean server: PlaygroundCliServer + probeId?: string }): Promise { const document5xxResponses = network .filter((record) => record.type === "response" && record.resourceType === "document" && typeof record.status === "number" && record.status >= 500 && record.status < 600) @@ -540,7 +547,7 @@ export async function browserWordPressDiagnosticsArtifact({ return undefined } - const diagnostics = ready ? await readBrowserWordPressDiagnostics(server) : [] + const diagnostics = ready ? await readBrowserWordPressDiagnostics(server, probeId) : [] const fatalErrors = diagnostics.filter((diagnostic) => diagnostic.classification === "php-fatal").length const classifications = [...new Set(diagnostics.map((diagnostic) => diagnostic.classification))].sort() const status: BrowserWordPressDiagnosticsSummary["status"] = !ready @@ -566,14 +573,18 @@ export async function browserWordPressDiagnosticsArtifact({ } } -export async function readBrowserWordPressDiagnostics(server: PlaygroundCliServer): Promise { +export function browserWordPressDiagnosticsLogPath(probeId?: string): string { + return probeId ? `/wordpress/wp-content/wp-codebox-browser-diagnostics-${probeId}.jsonl` : BROWSER_WORDPRESS_DIAGNOSTICS_LOG +} + +export async function readBrowserWordPressDiagnostics(server: PlaygroundCliServer, probeId?: string): Promise { if (!server.playground.readFileAsText) { return [] } let contents = "" try { - contents = await server.playground.readFileAsText(BROWSER_WORDPRESS_DIAGNOSTICS_LOG) + contents = await server.playground.readFileAsText(browserWordPressDiagnosticsLogPath(probeId)) } catch { return [] } diff --git a/packages/runtime-playground/src/browser-wordpress-diagnostic-provider.ts b/packages/runtime-playground/src/browser-wordpress-diagnostic-provider.ts index f2426914..bcd85677 100644 --- a/packages/runtime-playground/src/browser-wordpress-diagnostic-provider.ts +++ b/packages/runtime-playground/src/browser-wordpress-diagnostic-provider.ts @@ -1,16 +1,27 @@ -import { browserWordPressDiagnosticsArtifact, installBrowserWordPressDiagnostics } from "./browser-probe-support.js" +import { randomBytes } from "node:crypto" +import { browserWordPressDiagnosticsArtifact, browserWordPressDiagnosticsLogPath, installBrowserWordPressDiagnostics } from "./browser-probe-support.js" import type { BrowserProbeDiagnosticProvider } from "./browser-probe-runner.js" -export function browserWordPressDiagnosticProvider(): BrowserProbeDiagnosticProvider { +export function browserWordPressDiagnosticProvider(isolate = false): BrowserProbeDiagnosticProvider { return { id: "wordpress", - setup: ({ runPlaygroundCommand, server }) => installBrowserWordPressDiagnostics(runPlaygroundCommand, server), + async setup({ runPlaygroundCommand, server, page, cookieUrls }) { + if (!isolate) return installBrowserWordPressDiagnostics(runPlaygroundCommand, server) + // Scope the PHP log to this browser context, even for probes of the same URL. + const probeId = randomBytes(16).toString("hex") + await page.context().addCookies(cookieUrls.map((url) => ({ name: "wp_codebox_browser_probe", value: probeId, url, httpOnly: true }))) + return await installBrowserWordPressDiagnostics(runPlaygroundCommand, server, probeId) ? probeId : false + }, async collect({ artifactPath, network, server, setupResult }) { + const probeId = typeof setupResult === "string" ? setupResult : undefined const artifact = await browserWordPressDiagnosticsArtifact({ artifactPath, network, - ready: setupResult === true, + ready: setupResult === true || probeId !== undefined, server, + probeId, + }).finally(async () => { + if (probeId) await Promise.resolve().then(() => server.playground.unlink?.(browserWordPressDiagnosticsLogPath(probeId))).catch(() => undefined) }) if (!artifact) { return undefined diff --git a/packages/runtime-playground/src/php-snippets.ts b/packages/runtime-playground/src/php-snippets.ts index 674cbe9d..7919d823 100644 --- a/packages/runtime-playground/src/php-snippets.ts +++ b/packages/runtime-playground/src/php-snippets.ts @@ -108,7 +108,15 @@ if ( ! defined( 'WPINC' ) ) { } function wp_codebox_browser_diagnostics_write( array $record ): void { - file_put_contents( WP_CONTENT_DIR . '/wp-codebox-browser-diagnostics.jsonl', wp_json_encode( $record ) . "\n", FILE_APPEND | LOCK_EX ); + $probe_id = $_COOKIE['wp_codebox_browser_probe'] ?? ''; + $log = WP_CONTENT_DIR . '/wp-codebox-browser-diagnostics.jsonl'; + if ( is_string( $probe_id ) && preg_match( '/\\A[a-f0-9]{32}\\z/', $probe_id ) ) { + $log = WP_CONTENT_DIR . '/wp-codebox-browser-diagnostics-' . $probe_id . '.jsonl'; + if ( ! is_file( $log ) ) { + return; + } + } + file_put_contents( $log, wp_json_encode( $record ) . "\n", FILE_APPEND | LOCK_EX ); } function wp_codebox_browser_diagnostics_backtrace(): array { diff --git a/packages/runtime-playground/src/playground-command-errors.ts b/packages/runtime-playground/src/playground-command-errors.ts index 1d8c8485..3cdfc9db 100644 --- a/packages/runtime-playground/src/playground-command-errors.ts +++ b/packages/runtime-playground/src/playground-command-errors.ts @@ -3,8 +3,15 @@ import { errorMessage, parseJsonObject } from "@automattic/wp-codebox-core/inter export { errorMessage } -type PhpWasmUnhandledRejectionListener = (reason: unknown, promise: Promise) => void -const phpWasmRuntimeRejectionListeners = new Set() +const phpWasmRuntimeRejectionHandlers = new Set<(reason: Error) => void>() + +function onPhpWasmUnhandledRejection(reason: unknown): void { + if (isPhpWasmRuntimeRejection(reason)) { + for (const handle of phpWasmRuntimeRejectionHandlers) handle(reason) + } else if (!process.listeners("unhandledRejection").some((listener) => listener !== onPhpWasmUnhandledRejection)) { + queueMicrotask(() => { throw reason }) + } +} export interface PlaygroundRunResponse { bytes?: unknown @@ -76,26 +83,22 @@ export async function terminalizeOnPhpWasmRuntimeRejection(operation: () => P const runtimeRejection = new Promise((_resolve, reject) => { rejectRuntime = reject }) - const onUnhandledRejection: PhpWasmUnhandledRejectionListener = (reason) => { - if (isPhpWasmRuntimeRejection(reason)) { - rejectRuntime(new PhpWasmRuntimeRejectionError(reason)) - abort() - } else if (!process.listeners("unhandledRejection").some((listener) => !phpWasmRuntimeRejectionListeners.has(listener as PhpWasmUnhandledRejectionListener))) { - queueMicrotask(() => { throw reason }) - } + const handleRuntimeRejection = (reason: Error) => { + rejectRuntime(new PhpWasmRuntimeRejectionError(reason)) + abort() } - phpWasmRuntimeRejectionListeners.add(onUnhandledRejection) - process.on("unhandledRejection", onUnhandledRejection) + if (phpWasmRuntimeRejectionHandlers.size === 0) process.on("unhandledRejection", onPhpWasmUnhandledRejection) + phpWasmRuntimeRejectionHandlers.add(handleRuntimeRejection) try { return await Promise.race([Promise.resolve().then(operation), runtimeRejection]) } finally { - process.off("unhandledRejection", onUnhandledRejection) - phpWasmRuntimeRejectionListeners.delete(onUnhandledRejection) + phpWasmRuntimeRejectionHandlers.delete(handleRuntimeRejection) + if (phpWasmRuntimeRejectionHandlers.size === 0) process.off("unhandledRejection", onPhpWasmUnhandledRejection) } } -function isPhpWasmRuntimeRejection(reason: unknown): boolean { +function isPhpWasmRuntimeRejection(reason: unknown): reason is Error { if (!(reason instanceof Error) || reason.name !== "RuntimeError") { return false } diff --git a/packages/runtime-playground/src/playground-runtime.ts b/packages/runtime-playground/src/playground-runtime.ts index 7076e284..1c522e1f 100644 --- a/packages/runtime-playground/src/playground-runtime.ts +++ b/packages/runtime-playground/src/playground-runtime.ts @@ -10,6 +10,7 @@ import { browserArtifactFileManifest, browserReviewSummary as browserArtifactRev import { normalizeBrowserStorageStatePayload, wordpressFixtureUserStorageStatePhpCode, type WordPressFixtureUserSpec } from "./browser-auth-storage-state.js" import { adminFuzzInputFromArgs, adminFuzzPhpCode } from "./admin-fuzz-command-handlers.js" import { adminActionInputFromArgs, adminActionPhpCode } from "./admin-action-command-handlers.js" +import { launchChromiumBrowser } from "./browser-capture-session.js" import { browserWordPressDiagnosticProvider, isBrowserCommandArtifactError, runBrowserActionsCommand, runBrowserProbeCommand, runBrowserScenarioCommand, runEditorActionsCommand, runEditorCanvasProbeCommand, runEditorOpenCommand, runEditorValidateBlocksCommand, runHtmlCaptureCommand, runLayoutSweepCommand, runVisualCompareCommand, wordpressAdminAuthCookiePhpCode } from "./browser-command-runners.js" import type { PluginCheckArtifact, ThemeCheckArtifact } from "./check-artifacts.js" import { executePlaygroundCommand } from "./command-router.js" @@ -249,6 +250,8 @@ class PlaygroundRuntime implements Runtime { private readonly checkpoints = new Map() private readonly events: LifecycleEvent[] = [] private readonly browserProbes: BrowserArtifact[] = [] + private recipeProbeBrowser?: ReturnType + private recipeProbeCount = 0 private readonly pluginChecks: PluginCheckArtifact[] = [] private readonly themeChecks: ThemeCheckArtifact[] = [] private readonly artifactRoot: string @@ -712,8 +715,10 @@ class PlaygroundRuntime implements Runtime { controller.abort() } try { - const cliServer = await this.cliServerPromise - await cliServer?.[Symbol.asyncDispose]() + await Promise.all([ + this.recipeProbeBrowser?.then((browser) => browser.close(), () => undefined), + this.cliServerPromise?.then((server) => server[Symbol.asyncDispose]()), + ]) } finally { this.recordEvent("runtime.destroyed", { runtimeId: this.runtimeId }) } @@ -897,9 +902,18 @@ class PlaygroundRuntime implements Runtime { async runBrowserProbe(spec: ExecutionSpec): Promise { const server = await this.bootPlayground() + const recipeProbe = spec.command === "wordpress.browser-probe" && this.spec.metadata?.recipe !== undefined + const probeDirectory = recipeProbe ? `files/browser/probe-${++this.recipeProbeCount}` : undefined let result: Awaited> try { - result = await runBrowserProbeCommand({ abortSignal: this.executionSignals.getStore(), artifactRoot: this.artifactRoot, runtimeSpec: this.spec, runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options), server, spec, onProgress: (event) => this.recordEvent("runtime.browser-command-progress", { ...event, specCommand: spec.command }), diagnosticProviders: [browserWordPressDiagnosticProvider()] }) + result = await runBrowserProbeCommand({ + abortSignal: this.executionSignals.getStore(), artifactRoot: this.artifactRoot, runtimeSpec: this.spec, + runPlaygroundCommand: (command, targetServer, options) => this.runPlaygroundCommand(command, targetServer, options), + server, spec, browserFilesDirectory: probeDirectory, + acquireBrowser: recipeProbe ? () => this.acquireRecipeProbeBrowser() : undefined, + onProgress: (event) => this.recordEvent("runtime.browser-command-progress", { ...event, specCommand: spec.command, ...(probeDirectory ? { artifactDirectory: probeDirectory } : {}) }), + diagnosticProviders: [browserWordPressDiagnosticProvider(recipeProbe)], + }) } catch (error) { if (isBrowserCommandArtifactError(error)) { this.browserProbes.push(error.artifact) @@ -910,6 +924,18 @@ class PlaygroundRuntime implements Runtime { return result.output } + private acquireRecipeProbeBrowser(): ReturnType { + if (this.status === "destroyed") throw new Error("Cannot launch a browser for a destroyed runtime") + return this.recipeProbeBrowser ??= launchChromiumBrowser().then((browser) => { + browser.once("disconnected", () => { this.recipeProbeBrowser = undefined }) + this.recordEvent("runtime.recipe-probe-browser.launched") + return browser + }, (error) => { + this.recipeProbeBrowser = undefined + throw error + }) + } + async runHtmlCapture(spec: ExecutionSpec): Promise { const server = await this.bootPlayground() let result: Awaited> diff --git a/tests/recipe-browser-probe-groups.test.ts b/tests/recipe-browser-probe-groups.test.ts new file mode 100644 index 00000000..4f2f4b0a --- /dev/null +++ b/tests/recipe-browser-probe-groups.test.ts @@ -0,0 +1,66 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { setTimeout as delay } from "node:timers/promises" +import type { WorkspaceRecipe } from "@automattic/wp-codebox-core" +import { recipeWorkflowWaves, runRecipeProbeWave } from "../packages/cli/src/commands/recipe-browser-probe-groups.js" +import { recipeWorkflowSteps, validateWorkspaceRecipe } from "../packages/cli/src/recipe-validation.js" + +const probe = (parallelGroup?: string) => ({ command: "wordpress.browser-probe", args: ["url=/"], parallelGroup }) +const recipe: WorkspaceRecipe = { + schema: "wp-codebox/workspace-recipe/v1", + workflow: { before: [probe("home")], steps: [probe("home"), probe("home"), probe("home"), probe(), probe("home")], after: [probe("home")] }, +} + +test("groups respect workers, serial barriers, and workflow phases", () => { + const steps = recipeWorkflowSteps(recipe) + assert.deepEqual([...recipeWorkflowWaves(steps, 2)].map((wave) => wave.length), [1, 2, 1, 1, 1, 1]) + assert.deepEqual([...recipeWorkflowWaves(steps, undefined)].map((wave) => wave.length), steps.map(() => 1)) +}) + +test("only independent Playground workflow probes can opt in", async () => { + assert.deepEqual(await validateWorkspaceRecipe(recipe, "/tmp/recipe.json"), []) + const invalid = { ...recipe, workflow: { steps: [{ command: "wordpress.wp-cli", args: ["command=option get home"], parallelGroup: "home" }] } } + assert.ok((await validateWorkspaceRecipe(invalid, "/tmp/recipe.json")).some(({ code }) => code === "invalid-parallel-group")) +}) + +test("a wave overlaps, publishes outcomes in recipe order, and keeps the first required failure", async () => { + const wave = [...recipeWorkflowWaves(recipeWorkflowSteps(recipe), 2)][1] + const recorded: number[] = [] + const started: number[] = [] + const firstError = new Error("first probe failed") + const secondError = new Error("second probe failed") + let releaseFirst!: () => void + const firstGate = new Promise((resolve) => { releaseFirst = resolve }) + await assert.rejects(runRecipeProbeWave(wave, async ({ index }) => { + started.push(index) + if (index === 0) { + await firstGate + throw firstError + } + releaseFirst() + throw secondError + }, (_operation, work) => work(), async (step, outcome) => { + recorded.push(step.index) + assert.equal(outcome.status, "failed") + throw outcome.error + }), (error) => error === firstError) + assert.deepEqual(started, [0, 1]) + assert.deepEqual(recorded, [0, 1]) +}) + +test("a step timeout aborts only that probe", async () => { + const wave = [...recipeWorkflowWaves(recipeWorkflowSteps(recipe), 2)][1] + wave[0] = { ...wave[0], step: { ...wave[0].step, timeoutMs: 5 } } + let siblingSignal: AbortSignal | undefined + const outcomes: string[] = [] + await runRecipeProbeWave(wave, async ({ index }, signal) => { + if (index === 0) await delay(10_000, undefined, { signal }) + else siblingSignal = signal + return index + }, (_operation, work) => work(), async (_step, outcome) => { + outcomes.push(outcome.status) + if (outcome.status === "failed") assert.match(String(outcome.error), /workflow\.steps\[0\]:wordpress\.browser-probe/) + }) + assert.deepEqual(outcomes, ["failed", "completed"]) + assert.equal(siblingSignal?.aborted, false) +}) diff --git a/tests/recipe-browser-probe-reuse.browser.test.ts b/tests/recipe-browser-probe-reuse.browser.test.ts new file mode 100644 index 00000000..dadeceb7 --- /dev/null +++ b/tests/recipe-browser-probe-reuse.browser.test.ts @@ -0,0 +1,109 @@ +import assert from "node:assert/strict" +import { mkdtemp, readFile, rm } from "node:fs/promises" +import { createServer } from "node:http" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { test } from "node:test" +import { createRuntime } from "@automattic/wp-codebox-core" +import { executeRecipeWorkflowStep, recipeBrowserEvidence, recipeStepFailure } from "../packages/cli/src/commands/recipe-run-workflow-evidence.js" +import { runRecipeProbeWave } from "../packages/cli/src/commands/recipe-browser-probe-groups.js" +import { createPlaygroundRuntimeBackend } from "../packages/runtime-playground/src/index.js" + +test("recipe probes share Chromium, isolate contexts and captures, and keep failures per step", async () => { + const root = await mkdtemp(join(tmpdir(), "wp-codebox-recipe-probes-")) + let releaseGroupedRequests!: () => void + const bothGroupedRequests = new Promise((resolve) => { releaseGroupedRequests = resolve }) + let groupedRequests = 0 + const diagnostics = new Map() + const upstream = createServer(async (request, response) => { + if (!["/first", "/second", "/third"].includes(request.url ?? "")) { + response.writeHead(404).end() + return + } + const name = request.url!.slice(1) + if (name !== "first") { + if (++groupedRequests === 2) releaseGroupedRequests() + await bothGroupedRequests + } + if (name !== "first") { + const probeId = request.headers.cookie?.match(/wp_codebox_browser_probe=([a-f0-9]{32})/)?.[1] + if (probeId) diagnostics.set(`/wordpress/wp-content/wp-codebox-browser-diagnostics-${probeId}.jsonl`, JSON.stringify({ + schema: "wp-codebox/browser-wordpress-diagnostic-record/v1", classification: "php-fatal", message: `diagnostic for ${name}`, + })) + } + response.writeHead(name === "first" ? 200 : 500, { "content-type": "text/html", "set-cookie": `visited=${name}; Path=/` }) + const isolated = !request.headers.cookie?.includes("visited=") + response.end(`${name}

${name}

${isolated ? '

fresh

' : ""}`) + }) + await new Promise((resolve) => upstream.listen(0, "127.0.0.1", resolve)) + const address = upstream.address() + assert.ok(address && typeof address !== "string") + const runtime = await createRuntime({ + backend: "wordpress-playground", + artifactsDirectory: root, + environment: { kind: "wordpress", workers: 2, version: "mounted", phpVersion: "8.3", assets: { wordpressDirectory: root }, blueprint: { steps: [] } }, + policy: { network: "deny", filesystem: "sandbox", commands: ["wordpress.browser-probe"], secrets: "none", approvals: "never" }, + metadata: { recipe: {} }, + }, createPlaygroundRuntimeBackend({ cliModule: { async runCLI() { + return { + serverUrl: `http://127.0.0.1:${address.port}`, + playground: { + async run() { return { text: "", exitCode: 0 } }, + readFileAsText(path) { return diagnostics.get(path) ?? "" }, + unlink(path) { diagnostics.delete(path) }, + }, + async [Symbol.asyncDispose]() {}, + } + } } })) + + const steps = ["first", "second", "third"].map((name, index) => ({ + phase: "steps" as const, index, + step: { command: "wordpress.browser-probe", parallelGroup: index > 0 ? "home" : undefined, + args: [`url=/${name}`, "assert=exists:#fresh", `assert=text:h1 contains ${name === "third" ? "missing" : name}`, "timeout=10s"] }, + })) + try { + const executions = [await executeRecipeWorkflowStep(runtime, steps[0], root)] + const failures: Array<{ index: number; error: unknown }> = [] + await runRecipeProbeWave(steps.slice(1), (step, signal) => executeRecipeWorkflowStep(runtime, step, root, undefined, root, undefined, [], undefined, signal), (_operation, work) => work(), async (step, outcome) => { + if (outcome.status === "completed") executions.push(outcome.result) + else failures.push({ index: step.index, error: outcome.error }) + }) + assert.deepEqual(executions.map((execution) => execution.recipeStepIndex), [0, 1]) + assert.deepEqual(failures.map((failure) => failure.index), [2]) + assert.match(String(failures[0].error), /assertion failed/) + const failure = recipeStepFailure(steps[2], failures[0].error, Date.now()) + assert.match(JSON.stringify(failure.error), /files\/browser\/probe-\d+\/summary\.json/) + + const bundle = await runtime.collectArtifacts({ includeLogs: true, includeObservations: false }) + const events = (await readFile(bundle.eventsPath!, "utf8")).trim().split("\n").map((line) => JSON.parse(line)) + assert.equal(events.filter((event) => event.type === "runtime.recipe-probe-browser.launched").length, 1) + const probeStarts = events.filter((event) => event.type === "runtime.command.started") + const probeFinishes = events.filter((event) => event.type === "runtime.command.finished") + assert.equal(probeFinishes.length, 3) + assert.equal(groupedRequests, 2) + assert.ok(probeStarts[2].timestamp < probeFinishes[1].timestamp, "grouped command timings overlap") + + const evidence = await recipeBrowserEvidence(bundle, executions) + assert.deepEqual(evidence.map((item) => item.index), [0, 1]) + assert.equal(new Set(evidence.map((item) => item.summaryFile?.path)).size, 2) + for (const [index, name] of ["first", "second", "third"].entries()) { + const dir = join(bundle.directory, `files/browser/probe-${index + 1}`) + const summary = JSON.parse(await readFile(join(dir, "summary.json"), "utf8")) + assert.ok(summary.finalUrl.endsWith(`/${name}`)) + assert.match(await readFile(join(dir, "console.jsonl"), "utf8"), new RegExp(name)) + assert.match(await readFile(join(dir, "network.jsonl"), "utf8"), new RegExp(`/${name}`)) + assert.ok((await readFile(join(dir, "screenshot.png"))).length > 0) + assert.equal(summary.assertions.failed, name === "third" ? 1 : 0) + if (name !== "first") { + const log = JSON.parse(await readFile(join(dir, "wordpress-diagnostics.json"), "utf8")) + assert.deepEqual(log.diagnostics.map(({ message }: { message: string }) => message), [`diagnostic for ${name}`]) + } + } + assert.equal(diagnostics.size, 0) + } finally { + releaseGroupedRequests() + await runtime.destroy() + await new Promise((resolve) => upstream.close(() => resolve())) + await rm(root, { recursive: true, force: true }) + } +})