Files
webstudio/apps/builder/e2e/flows/generated-app.ts
T
Oleg Isonen 9a86222afd perf: Cut Builder E2E shard startup and repeated work (#6705)
The five-worker A/B run (`3d464ec2`, run 43985693015) passed all 61 E2E
cases and every Main check. Full shard jobs took **197, 201, 218, 226,
and 233 seconds** with a warm Builder build cache. Browser phases were
**154, 147, 169, 184, and 186 seconds**, totaling about 18 seconds more
than the four-worker warm run (`6f87754c`, run 43983946199). Five
workers raised CPU scheduling pressure from 72–74% to 77–84%. Four
workers are restored; all five jobs still need to finish under 180
seconds.

The merged-main run (`dfa0fc97`, run 43981570428) passed all **61 E2E
tests** and every Main workflow check. Its cold build cache made each
shard wait about 35–41 seconds for the shared Builder artifact. Full job
times were **285, 246, 227, 202, and 228 seconds**; browser phases were
**196, 154, 138, 116, and 140 seconds**. CPU scheduling pressure was
68–71%, with no memory pressure. A same-SHA rerun hit the Builder build
cache on shard 1: the full job fell to 215 seconds and browser work took
155.9 seconds. Warm setup is cheaper, but shard 1 still misses 180
seconds. The other four jobs have not been rerun warm.

The warm-cache full run on commit `3c0a936d` passed all 60 browser cases
across five fixed shards with three workers. Full jobs took 184, 191,
124, 161, and 190 seconds. Shards 1, 2, and 5 remain 4–11 seconds over
the 180-second target.

Browser phases took 137.5, 140.3, 77.0, 117.4, and 134.0 seconds. Setup
and cleanup added 44–56 seconds. All caches hit, and source checkout
took about 1–2 seconds.

The latest warm-cache run on `8a8f04b4` passed all 60 cases, but browser
phases were 85.9, 129.8, 193.2, 169.9, and 138.4 seconds. Shard 3's
Email binding test alone took 96.8 seconds in this run, versus 50.5 and
59.2 seconds in two earlier runs. This shows the current fixed
assignment is still too uneven and timings vary by run. The third
assignment moved Data variables from shard 1 to 3, Style panel from
shard 2 to 4, and Animation runtime from shard 2 to 5. All 60 cases
passed, but browser phases were 93.7, 150.2, 156.7, 110.6, and 167.2
seconds. Shards 2, 3, and 5 remain above the target once setup is
included. Test times varied sharply from prior runs. Read-only
inspection found no safe material reduction in the 93-second redirect
test or 56-second Asset folder clone test; both use serial state changes
and persistence checks. A separate select-asset-folders test now uses a
direct page reload for its final persistence check, removing an
unnecessary canvas wait. Its focused full-run time changed from 19.9 to
18.8 seconds, but this small result is not a speedup for the slow Asset
folder clone test. The six-move assignment passed all 60 cases on run
43969666884, but browser phases were 166.8, 106.5, 151.5, 183.3, and
123.1 seconds. Only shards 2 and 5 finished under 180 seconds including
setup. The total measured test work was about 1,805 seconds across 15
workers, a 120-second ideal average before scheduling overhead. The
latest run on `b71669bf` passed all 60 cases, with browser phases of
88.4, 123.5, 138.8, 151.4, and 157.1 seconds. Setup added 43–65 seconds.
Only shard 1 finished under 180 seconds for the complete job. The
four-file rebalance reduced the worst complete-job time from about 238
to 209 seconds. Run `66163599` passed all 60 cases; full jobs took about
155, 212, 152, 168, and 173 seconds. Run `1853aef1` also passed all 60,
but jobs were about 180, 157, 203, 166, and 156 seconds; browser phases
were 129, 90, 136, 106, and 103 seconds. Setup and cleanup added 51, 67,
67, 60, and 53 seconds. Shards 1 and 3 missed the 180-second target. CPU
scheduling pressure was 48–62%, with no memory pressure.

Recent changes reduce repeated work and keep the same assertions:
- The variable test uses one saved pre-edit Preview snapshot while
Builder edits and reloads the project on a separate page.
- The two-generation Email test starts from a blank project because it
creates the routes and forms it checks. Both saved production
generations are still built and checked.
- Email delivery forms are authored inside the existing Preview process,
removing a separate Node process start.
- Two shard-3 form tests share one project and production Preview. Their
success/failure results, redirects, browser feedback, scroll behavior,
retry behavior, and saved project redirect checks remain.
- Marketplace settings save both fields in one cycle and keep checks for
each value before and after reload.
- Content-mode rich-text tests save both link edits together while
keeping stored href and link-removal checks.
- MCP form delivery uses a smaller fixture with the same email plan and
Builder permissions; it removes five unused inserts. Warm local timings
were nearly the same.
- The two longest shard-5 cases and the 64-second shard-3 Pages bridge
file moved to lower-load fixed shards. All 60 cases remain assigned
once.
- The shard-3 form-delivery file now sorts earlier so its Preview work
overlaps earlier cases. A local three-worker comparison reduced shard-3
Playwright time from 71.2 to 64.7 seconds.
- The shard-5 callbacks test uses a blank project with its existing
page. It keeps its production Preview and all assertions, removes eight
unrelated database operations, and measured 13.8% faster in focused
local comparisons.
- The shard action starts PostgreSQL and PostgREST image pulls while
pnpm installs dependencies. Both operations still occur; setup and
cleanup still add about 45 seconds.

The latest run (`43990503162`) passed all 61 browser cases, but GitHub
reported full shard jobs of **228/200/176/152/218 seconds**; shards 1,
2, and 5 missed the 180-second target. Hook-aware logs show per-file
work sums of **587/458/358/349/551 seconds**. These are work totals, not
CI wall times, and the two parallel suites on shard 1 made a simple
work-sum rebalance misleading. The current setup change starts and
readies the snapshot database/PostgREST while dependencies install, with
Prisma and Chromium work remaining after installation; its CI saving is
not measured yet.

Run `44008044890` passed all 61 browser cases and five setup tests on
the same fixed assignments after backend setup began overlapping
dependency installation. Browser phases were
**202.5/176.4/81.2/106.7/110.8 seconds**; the full jobs still missed the
180-second goal on the slower shards. Image pulls finished in
4/6/21/8/23 seconds, and only shards 3 and 5 waited after installation
(9 and 14 seconds). The nine-file tag assignment passed all 61 browser
cases and five setup tests in run `44008945736`. Complete shard jobs
took **174.4/125/223.7/161.6/166.2 seconds**; only shard 3 missed 180
seconds. Three more measured file retags move slow serial work from
shard 3 to shards 2 and 4. All twelve tag changes are exact file
renames, so test cases and assertions remain. The final full run on
commit `b9bc8b4` (run `44050045632`) passed all 61 browser tests and
five setup tests. Complete shard jobs, including setup and cleanup, took
**151/132/136/162/144 seconds**; all five finished under three minutes.
The Node/pnpm, Playwright browser, and Builder build caches hit, so no
E2E build artifact polling or download was needed. Each shard still
installs workspace dependencies, starts and readies its local database
services, prepares E2E, runs its assigned tests, and tears services
down. CPU scheduling pressure was 60–68%; memory pressure was 0%. All
workflow checks passed.

### Checklist

- [x] Keep five fixed shards and preserve every test while measuring
worker counts.
- [x] Add timings for generated Preview phases and preserve the logs in
CI.
- [x] Reduce repeated form, variable, and Preview setup without dropping
assertions.
- [x] Compare worker counts and restore three workers after the
two-worker trial increased total test time.
- [x] Manually rebalance fixed shard tags from measured test durations;
discovery confirms all 60 cases run once.
- [x] Review Builder documentation impact; the E2E README describes
fixed, manually measured shard tags.
- [x] Run all five shards on the latest assignment; all 60 browser cases
and all workflow checks passed.
- [x] Check whether slow source checkouts recur; this run's five fetches
took 1–2 seconds, and source caching remains unjustified.
- [x] Optimize shard-5 setup without removing its Preview or assertions.
- [x] Rebalance heavy tests onto lower-load fixed shards, based on
measured durations.
- [x] Overlap image pulls with the dependency install shared by the five
shards.
- [x] Run the full suite on these combined changes; all 60 cases and
workflow checks passed.
- [x] Re-run shard 5 with the Builder build cache warm; it passed in 173
seconds.
- [x] Rebalance measured files across the five shards and verify all 60
cases run once.
- [x] Run all five shards with the Builder build cache warm; four
finished under 180 seconds.
- [x] Move the 61-second data-variable Preview case from shard 1 to
shard 5; all 60 cases remain assigned once.
- [x] Run all five shards on the latest assignments; all 60 cases
passed, but shards 3 (183s) and 5 (212s) remain over 180 seconds.
- [x] Share one generated Preview between shard-5 callback and
legacy-route scenarios; local full-shard A/B improved by 6 seconds with
all assertions preserved.
- [x] Move the data-variable and Form inspector tests from shard 5 to
shard 4, Preview links from shard 5 to shard 1, and content-mode pages
from shard 3 to shard 1.
- [x] Run all five shards on the new assignments; all 60 cases passed,
but shard 4 took 235 seconds.
- [x] Move the 61-second data-variable and 46-second redirect tests from
shard 4 to shard 1, the 79-second Email binding test to shard 5, and the
21-second Slot keyboard test from shard 5 to shard 2.
- [x] Rebalance the four longest test files from the latest CI
measurements while keeping five fixed shards and all 60 cases.
- [x] Run all five shards on that assignment; all 60 browser cases and
workflow checks passed, but full jobs were approximately 144, 188, 247,
212, and 180 seconds. Shards 2–5 remained at or above the 180-second
goal.
- [x] Rebalance measured test files again and verify all 60 cases run
once; full workflow run 43965687329 passed all cases, but several shards
remained over 180 seconds.
- [x] Use four-run medians to rebalance Data variables, Style panel, and
Animation runtime while keeping five shards and three workers.
- [x] Run all five shards on the latest assignment; all 60 cases passed,
but browser phases were 93.7, 150.2, 156.7, 110.6, and 167.2 seconds.
- [x] Replace the unnecessary Builder canvas readiness wait with a
direct reload in the select-and-drag asset folder persistence test;
preserve the post-reload folder assertions. Focused full runs were 19.9s
and 18.8s, including setup; independent review found no coverage or
readiness issue.
- [x] Inspect the slow redirect and Asset folder clone tests; keep their
serial writes and persistence checks because no safe material reduction
was found.
- [x] Rebalance six files against recent and median timings; all 60
browser cases passed on run 43969666884, with full jobs approximately
212, 156, 208, 238, and 176 seconds. Shards 1, 3, and 4 remained over
180 seconds.
- [x] Rebalance Data variables, Content mode assets, Navigator, and Form
redirect files using the latest run. All 60 cases passed on run
43971617077; complete jobs were approximately 149, 191, 191, 209, and
202 seconds.
- [x] Move Navigator (shard 4→1), Form redirect matrix (5→1), and Editor
fragment (2→4). The 66163599 run passed all 60 cases; four full jobs
took 149–171 seconds and shard 2 took 208 seconds.
- [x] Move Share links from shard 2→3 and Author props from shard 2→1.
All 60 cases passed in run `1853aef1`, but shards 1 and 3 remained over
180 seconds.
- [x] Move Email binding from shard 1→2, Browser form preview from shard
3→1, and Share links from shard 3→5. All 60 cases passed, but the latest
run’s browser phases were 184, 145, 129, 89, and 182 seconds. Only shard
4’s full job was under 180 seconds.
- [x] Start DB/PostgREST image pulls before Node/pnpm cache restoration
and installation, preserving timeouts, error propagation, and cleanup.
The next run reported 5–17 seconds total pull time and zero wait after
install on all five shards; setup still varied and the 3-minute goal was
not met.
- [x] Compare three and four Playwright workers on the same five fixed
shards and assignments. Four workers lowered total browser-phase time by
about 13% and lowered the worst full job from 252s to 234s; all tests
passed. Keep four workers for the next balanced run.
- [x] Trial five Playwright workers on the same five fixed shards and 61
cases. Run 43985693015 passed every check with warm-cache full jobs of
197/201/218/226/233s; browser phases were 154/147/169/184/186s. Against
the four-worker run 43983946199 (198/180/224/230/246s full;
147/135/168/182/190s browser), aggregate browser work rose about 18s and
CPU pressure rose to 77–84%. Restore four workers; neither setting met
the 180s target.
- [x] Use run 43986730815's 61 case timings to rebalance whole test
files across the same five fixed shards with four workers. Discovery
found all 61 unique cases once; run 43988555497 passed all five shards
with full jobs of 158/162/224/220/177s. Shards 3 and 4 still miss 180s.
- [x] Overlap snapshot DB/PostgREST preparation with dependency
installation; preserve readiness, errors, and cleanup. Run 44008044890
passed all five shards; only two image pulls required waiting after
installation.
- [x] Add hook-aware timings and rebalance fixed shard tags using runs
43990503162 and 44008044890. All nine file changes are exact renames;
the 180-second whole-job target remains unverified on the new tags.
- [x] Rebalance the five fixed shards from all 61 current case timings
without weakening assertions; run `44050045632` passed all 61 browser
cases and five setup tests, with full jobs at 151/132/136/162/144
seconds and all checks green.
- [x] Validate seeded E2E pages, instances, props, and breakpoints with
existing schemas; preserve the historical Form identity marker and cover
its JSON round-trip. Builder typecheck, focused Vitest, lint,
formatting, and diff checks passed. Reviewed Builder docs; no
documentation changes are needed.
- [ ] Rebalance any shard still above three minutes using the latest
full-run timings while keeping five fixed shards and all tests.
2026-11-17 11:03:04 +01:00

374 lines
11 KiB
TypeScript

import { execFile, spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { bundleVersion } from "@webstudio-is/protocol";
import { getStyleDeclKey, type Page } from "@webstudio-is/sdk";
import type { ProjectSettings } from "@webstudio-is/project-build";
import { loadDevBuild } from "../db";
import { measure } from "../perf";
import { stopChildProcess } from "../process";
const execFileAsync = promisify(execFile);
const cliLocalPath = fileURLToPath(
new URL("../../../../packages/cli/local.js", import.meta.url)
);
type BuildRow = Awaited<ReturnType<typeof loadDevBuild>>;
export const getAvailablePort = async () => {
const server = createServer();
server.unref();
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => resolve());
});
const address = server.address();
if (address === null || typeof address === "string") {
await new Promise<void>((resolve) => server.close(() => resolve()));
throw new Error("Expected a numeric port for generated-app preview.");
}
await new Promise<void>((resolve) => server.close(() => resolve()));
return address.port;
};
export const waitForGeneratedPreview = async ({
process,
url,
output,
timeout = 120_000,
}: {
process: ChildProcess;
url: string;
output: () => string;
timeout?: number;
}) => {
// Preview also compiles the production app while other E2E workers are active.
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
if (process.exitCode !== null || process.signalCode !== null) {
throw new Error(
`Generated preview exited before it became ready at ${url}. Output:\n${output()}`
);
}
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(2_000),
});
if (response.ok) {
return await response.text();
}
} catch {
// The generated production server is still starting.
}
await new Promise<void>((resolve) => setTimeout(resolve, 250));
}
throw new Error(
`Generated preview did not become ready at ${url}. Output:\n${output()}`
);
};
const parseBuildField = <Value>(build: BuildRow, field: keyof BuildRow) =>
JSON.parse(String(build[field])) as Value;
const parseBuildEntriesById = <Value extends { id: string }>(
build: BuildRow,
field: keyof BuildRow
) => {
return parseBuildField<Value[]>(build, field).map((value) => [
value.id,
value,
]);
};
const parseBuildStyleEntries = (build: BuildRow) => {
return parseBuildField<Parameters<typeof getStyleDeclKey>[0][]>(
build,
"styles"
).map((style) => [getStyleDeclKey(style), style]);
};
const parseBuildStyleSourceSelectionEntries = (build: BuildRow) => {
return parseBuildField<Array<{ instanceId: string }>>(
build,
"styleSourceSelections"
).map((selection) => [selection.instanceId, selection]);
};
export const createLocalBundleFromDevBuild = (build: BuildRow) => {
const pages = parseBuildField<{
homePageId: string;
pages: Page[];
}>(build, "pages");
const homePage = pages.pages.find((page) => page.id === pages.homePageId);
if (homePage === undefined) {
throw new Error("Expected dev build to have a home page");
}
return {
bundleVersion,
origin: "https://assets.example",
projectDomain: "generated-e2e.example",
projectTitle: pages.pages[0]?.name ?? "Generated E2E",
page: homePage,
pages: pages.pages,
assets: [],
build: {
id: build.id,
projectId: build.projectId,
version: build.version,
createdAt: build.createdAt,
updatedAt: build.updatedAt,
pages,
breakpoints: parseBuildEntriesById(build, "breakpoints"),
styles: parseBuildStyleEntries(build),
styleSources: parseBuildEntriesById(build, "styleSources"),
styleSourceSelections: parseBuildStyleSourceSelectionEntries(build),
props: parseBuildEntriesById(build, "props"),
instances: parseBuildEntriesById(build, "instances"),
dataSources: parseBuildEntriesById(build, "dataSources"),
resources: parseBuildEntriesById(build, "resources"),
projectSettings: parseBuildField<ProjectSettings>(
build,
"projectSettings"
),
},
};
};
export const expectGeneratedAppBuild = async (
input: ({ projectId: string } | { build: BuildRow }) & {
expectedText?: string;
}
) => {
const { expectedText } = input;
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
try {
const build =
"build" in input
? input.build
: await loadDevBuild({ projectId: input.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build), undefined, 2)}\n`
);
await measure("generated app build", () =>
execFileAsync(
process.execPath,
[cliLocalPath, "build", "--assets", "false", "--template", "defaults"],
{
cwd: tempDir,
env: { ...process.env, PWD: tempDir },
maxBuffer: 1024 * 1024 * 10,
}
)
);
if (expectedText !== undefined) {
const generatedHome = await readFile(
join(tempDir, "app", "__generated__", "_index.tsx"),
"utf8"
);
if (generatedHome.includes(expectedText) === false) {
throw new Error(
`Expected generated home route to include "${expectedText}".`
);
}
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
};
export const startGeneratedPreview = async (
input: ({ projectId: string } | { build: BuildRow }) & {
evaluationReceiverPort?: string;
}
) => {
const { evaluationReceiverPort } = input;
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
let preview: ChildProcess | undefined;
const close = async () => {
try {
if (preview !== undefined) {
// The CLI starts npm and the generated server below it.
await stopChildProcess(preview, { killGroup: true });
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
};
try {
const build =
"build" in input
? input.build
: await loadDevBuild({ projectId: input.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build), undefined, 2)}\n`
);
const port = await getAvailablePort();
const output: string[] = [];
preview = spawn(
process.execPath,
[
cliLocalPath,
"preview",
"--assets",
"false",
"--template",
"defaults",
"--template",
"react-router",
"--host",
"127.0.0.1",
"--port",
String(port),
],
{
cwd: tempDir,
detached: process.platform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
PWD: tempDir,
...(evaluationReceiverPort === undefined
? {}
: {
WEBSTUDIO_FORM_EVALUATION_RECEIVER_PORT: evaluationReceiverPort,
}),
},
}
);
const appendOutput = (chunk: unknown) => {
output.push(String(chunk));
while (output.join("").length > 8_000) {
output.shift();
}
};
preview.stdout?.on("data", appendOutput);
preview.stderr?.on("data", appendOutput);
const url = `http://127.0.0.1:${port}/`;
const runningPreview = preview;
const html = await measure("generated app preview startup", () =>
waitForGeneratedPreview({
process: runningPreview,
url,
output: () => output.join(""),
})
);
return { url, html, close };
} catch (error) {
await close();
throw error;
}
};
export const withGeneratedPreview = async <Result>({
callback,
...input
}: Parameters<typeof startGeneratedPreview>[0] & {
callback: (preview: { url: string; html: string }) => Promise<Result>;
}) => {
const { url, html, close } = await startGeneratedPreview(input);
try {
return await measure("generated app preview callback", () =>
callback({ url, html })
);
} finally {
await close();
}
};
export const expectGeneratedAppToRender = async ({
projectId,
expectedText,
path = "/",
}: {
projectId: string;
expectedText: string;
path?: string;
}) => {
await withGeneratedPreview({
projectId,
callback: async ({ url, html }) => {
const response =
path === "/"
? undefined
: await fetch(new URL(path, url), { redirect: "manual" });
const routeHtml = response === undefined ? html : await response.text();
if (
(response !== undefined && response.ok === false) ||
routeHtml.includes(expectedText) === false
) {
throw new Error(
`Expected generated preview route ${JSON.stringify(path)} at ${url} to render ${JSON.stringify(expectedText)}.`
);
}
},
});
};
export const expectGeneratedRedirects = async ({
projectId,
expectedRedirects,
}: {
projectId: string;
expectedRedirects: Array<{ old: string; new: string; status?: string }>;
}) => {
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
try {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build), undefined, 2)}\n`
);
await execFileAsync(
process.execPath,
[cliLocalPath, "build", "--assets", "false", "--template", "defaults"],
{
cwd: tempDir,
env: { ...process.env, PWD: tempDir },
maxBuffer: 1024 * 1024 * 10,
}
);
const redirectsModule = await readFile(
join(tempDir, "app", "__generated__", "$resources.redirects.ts"),
"utf8"
);
const redirectsExport = redirectsModule.trim();
const prefix = "export const redirects = ";
const suffix = ";";
if (
redirectsExport.startsWith(prefix) === false ||
redirectsExport.endsWith(suffix) === false
) {
throw new Error(
`Expected generated redirects module to export redirects. Received ${redirectsModule}`
);
}
const redirectsJson = redirectsExport.slice(prefix.length, -suffix.length);
const redirects = JSON.parse(redirectsJson);
if (JSON.stringify(redirects) !== JSON.stringify(expectedRedirects)) {
throw new Error(
`Expected generated redirects ${JSON.stringify(
expectedRedirects
)}, received ${JSON.stringify(redirects)}.`
);
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
};