Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(benchmark): measure real browser message operations independently (#784)
Gustavo Yed70e07329484
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 426c5fefb..ce974e287 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -122,7 +122,7 @@ jobs:elif [[ "$EVENT_NAME" == "merge_group" ]]; thenargs+=(--base "$MERGE_BASE_SHA" --head "$EVENT_SHA")elif [[ "$EVENT_NAME" == "push" ]]; then- args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --force-full)+ args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --full-unless-benchmark-only)elseargs+=(--base "$EVENT_SHA" --head "$EVENT_SHA" --force-full)fidiff --git a/scripts/ci/changed-scopes.mjs b/scripts/ci/changed-scopes.mjsindex 81b9ec2bf..24ec49655 100644--- a/scripts/ci/changed-scopes.mjs+++ b/scripts/ci/changed-scopes.mjs@@ -293,9 +293,10 @@ function isKnownPath(path, manifest) {|| KNOWN_PREFIXES.some((prefix) => path.startsWith(prefix))}-function fullReason(paths, { forceFull, fallbackReason }) {+function fullReason(paths, { forceFull, fullUnlessBenchmarkOnly, benchmarkOnly, fallbackReason }) {if (fallbackReason) return "classifier_error"- if (forceFull) return "forced"+ if (forceFull || (fullUnlessBenchmarkOnly && !benchmarkOnly)) return "forced"+ if (benchmarkOnly) return nullif (paths.length === 0) return "empty_diff"const docsOnly = paths.every(isMarkdown)const blogOnly = paths.every(isBlogContent)@@ -353,8 +354,9 @@ function requiredCoverageFiles(changes, coverageRoots) {}))}-function planClass({ full, docsOnly, blogPathsOnly, authPathsOnly, direct }) {+function planClass({ full, benchmarkOnly, docsOnly, blogPathsOnly, authPathsOnly, direct }) {if (full) return "full"+ if (benchmarkOnly) return "benchmark"if (docsOnly) return "docs"if (blogPathsOnly) return "blog"if (authPathsOnly) return "auth"@@ -366,13 +368,15 @@ function planClass({ full, docsOnly, blogPathsOnly, authPathsOnly, direct }) {export function buildExecutionPlan(inputChanges, options = {}) {const manifest = validateScopeManifest(options.manifest || loadScopeManifest())const changes = normalizedChanges(inputChanges)- const paths = sorted(changes.flatMap(changePaths))+ const allPaths = sorted(changes.flatMap(changePaths))+ const paths = allPaths.filter((path) => !pathWithin(path, "src/benchmark"))+ const benchmarkOnly = allPaths.length > 0 && paths.length === 0const docsOnly = paths.length > 0 && paths.every(isMarkdown)const blogContentOnly = paths.length > 0 && paths.every(isBlogContent)const blogPathsOnly = paths.length > 0 && paths.every((path) => BLOG_ROOT.test(path))const authPathsOnly = paths.length > 0 && paths.every((path) => AUTH_ROOT.test(path))const unknown = paths.some((path) => !isKnownPath(path, manifest))- const reason = fullReason(paths, options) || (unknown ? "unknown_path" : null)+ const reason = fullReason(paths, { ...options, benchmarkOnly }) || (unknown ? "unknown_path" : null)const full = reason !== nullconst direct = sorted(paths.map((path) => findPackage(path, manifest)?.name).filter(Boolean))@@ -447,8 +451,8 @@ export function buildExecutionPlan(inputChanges, options = {}) {head_sha: options.headSha || "",diagnostic_only: options.diagnosticOnly === true,changes,- paths,- change_class: planClass({ full, docsOnly, blogPathsOnly, authPathsOnly, direct }),+ paths: allPaths,+ change_class: planClass({ full, benchmarkOnly, docsOnly, blogPathsOnly, authPathsOnly, direct }),full,full_reason: reason,docs_only: docsOnly && !full,@@ -582,6 +586,10 @@ function parseArgs(argv) {args.forceFull = truecontinue}+ if (arg === "--full-unless-benchmark-only") {+ args.fullUnlessBenchmarkOnly = true+ continue+ }if (arg === "--diagnostic-only") {args.diagnosticOnly = truecontinue@@ -621,6 +629,7 @@ export function runCli(argv) {baseSha: args.base || "",headSha: args.head || "",forceFull: args.forceFull,+ fullUnlessBenchmarkOnly: args.fullUnlessBenchmarkOnly,diagnosticOnly: args.diagnosticOnly,})} catch (error) {diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.tsindex 520fbe5bd..8b2030be9 100644--- a/scripts/ci/changed-scopes.test.ts+++ b/scripts/ci/changed-scopes.test.ts@@ -71,7 +71,7 @@ function cleanGitEnvironment() {return environment}-function gitDiffFixture() {+function gitDiffFixture(changedPath = "src/app/src/commands/inbox.ts") {const root = mkdtempSync(join(tmpdir(), "alook-ci-git-"))const runGit = (...args: string[]) => execFileSync("git", args, {cwd: root,@@ -90,8 +90,7 @@ function gitDiffFixture() {runGit("add", "README.md")commit("baseline")- const changedPath = "src/app/src/commands/inbox.ts"- mkdirSync(join(root, "src/app/src/commands"), { recursive: true })+ mkdirSync(join(root, changedPath.split("/").slice(0, -1).join("/")), { recursive: true })writeFileSync(join(root, changedPath), "export const fixture = true\n")runGit("add", changedPath)commit("change app")@@ -100,6 +99,47 @@ function gitDiffFixture() {}describe("canonical execution plan", () => {+ it("keeps benchmark-only changes out of product jobs while retaining diff evidence", () => {+ const changes = [+ { status: "A", path: "src/benchmark/package.json" },+ { status: "M", path: "src/benchmark/README.md" },+ { status: "D", path: "src/benchmark/src/old.mjs" },+ { status: "R100", old_path: "src/benchmark/src/a.mjs", path: "src/benchmark/src/b.mjs" },+ ]+ const result = buildExecutionPlan(changes)+ expect(result.change_class).toBe("benchmark")+ expect(result.full).toBe(false)+ expect(result.paths).toHaveLength(5)+ expect(result.changes).toHaveLength(4)+ expect(Object.values(result.jobs).every((run) => !run)).toBe(true)+ expect(result.packages.affected).toEqual([])+ expect(result.coverage.include_roots).toEqual([])+ expect(Object.entries(projectPlan(result)).filter(([name]) => name.startsWith("run_")).every(([, run]) => run === "false")).toBe(true)+ expect(validateExecutionPlan(result)).toEqual(result)+ })++ it("preserves existing product contracts when benchmark changes are mixed in", () => {+ for (const product of ["src/app/src/commands/inbox.ts", "src/daemon/src/index.ts", "src/web/src/app/page.tsx", "src/web/auth/index.ts", "src/web/blog/src/app/page.tsx", "src/web/blog/src/content/example.mdx", "src/shared/src/schema.ts"]) {+ const expected = plan([product])+ const mixed = plan([product, "src/benchmark/src/runner.mjs"])+ for (const field of ["change_class", "full", "packages", "suites", "jobs", "coverage", "ui", "auth_only", "blog_only"]) expect(mixed[field]).toEqual(expected[field])+ }+ for (const [old_path, path] of [["src/web/auth/index.ts", "src/benchmark/index.ts"], ["src/benchmark/index.ts", "src/web/auth/index.ts"]]) {+ const result = buildExecutionPlan([{ status: "R100", old_path, path }])+ expect(result.jobs).toEqual(plan(["src/web/auth/index.ts"]).jobs)+ expect(result.paths).toEqual(["src/benchmark/index.ts", "src/web/auth/index.ts"])+ }+ })++ it("keeps unknown, policy, empty and explicit full changes fail-closed", () => {+ for (const path of ["src/benchmark-other/new.mjs", "unknown/code.js", ".github/workflows/ci.yml"]) expect(plan([path, "src/benchmark/src/runner.mjs"]).full).toBe(true)+ expect(plan([]).full).toBe(true)+ expect(plan(["src/benchmark/src/runner.mjs"], { forceFull: true }).full).toBe(true)+ expect(plan(["src/benchmark/src/runner.mjs"], { fallbackReason: "diff failed" }).full).toBe(true)+ expect(plan(["src/benchmark/src/runner.mjs"], { fullUnlessBenchmarkOnly: true }).full).toBe(false)+ for (const paths of [[], ["README.md"], ["src/web/auth/index.ts", "src/benchmark/src/runner.mjs"]]) expect(plan(paths, { fullUnlessBenchmarkOnly: true }).full).toBe(true)+ })+it("routes Blog runtime through the complete Web contract and only UI spec 54", () => {const result = plan(["src/web/blog/src/app/page.tsx"])@@ -595,10 +635,12 @@ describe("compatibility and CLI fail-closed behavior", () => {for (const name of localEnvironment) delete process.env[name]process.env.GIT_DIR = join(fixture.root, ".git")process.env.GIT_WORK_TREE = fixture.root- runCli(["--base", "HEAD^", "--head", "HEAD", "--summary", summary])+ runCli(["--base", "HEAD^", "--head", "HEAD", "--full-unless-benchmark-only", "--summary", summary])const written = stdout.mock.calls.map(([value]) => String(value)).join("")const writtenPlan = JSON.parse(written)+ expect(writtenPlan.full).toBe(true)+ expect(writtenPlan.full_reason).toBe("forced")expect(writtenPlan.base_sha).toBe("HEAD^")expect(writtenPlan.head_sha).toBe("HEAD")expect(writtenPlan.changes).toEqual([{ status: "A", path: fixture.changedPath }])@@ -613,6 +655,25 @@ describe("compatibility and CLI fail-closed behavior", () => {}})+ it.each([+ ["src/benchmark/src/runner.mjs", false],+ ["src/web/auth/index.ts", true],+ ])("applies main-push policy through the actual CLI diff for %s", (path, full) => {+ const fixture = gitDiffFixture(String(path))+ const output = join(fixture.root, "projection")+ const planFile = join(fixture.root, "plan.json")+ try {+ execFileSync(process.execPath, ["scripts/ci/changed-scopes.mjs", "--base", "HEAD^", "--head", "HEAD", "--full-unless-benchmark-only", "--output", output, "--plan-file", planFile], {+ env: { ...cleanGitEnvironment(), GIT_DIR: join(fixture.root, ".git"), GIT_WORK_TREE: fixture.root },+ })+ const result = JSON.parse(readFileSync(planFile, "utf8"))+ expect(result.full).toBe(full)+ expect(result.changes).toEqual([{ status: "A", path }])+ } finally {+ rmSync(fixture.root, { recursive: true, force: true })+ }+ })+it("fails closed when the CLI SHA boundary is omitted", () => {const directory = mkdtempSync(join(tmpdir(), "alook-ci-scope-"))const output = join(directory, "output")diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.tsindex c8aa56eff..a8949d09a 100644--- a/scripts/ci/workflow-contract.test.ts+++ b/scripts/ci/workflow-contract.test.ts@@ -400,6 +400,7 @@ describe("CI workflow graph", () => {expect(scope).toContain('--expected-class "$EXPECTED_CLASS"')expect(scope).toContain('--diagnostic-only')expect(scope).toContain('args+=(--base "$EVENT_SHA" --head "$EVENT_SHA" --force-full)')+ expect(scope).toContain('args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --full-unless-benchmark-only)')expect(scope).not.toContain("ref: ${{ inputs.fixture_sha }}")})diff --git a/src/benchmark/.gitignore b/src/benchmark/.gitignorenew file mode 100644index 000000000..ce0766463--- /dev/null+++ b/src/benchmark/.gitignore@@ -0,0 +1,4 @@+artifacts/+.runtime/+*.local.json+node_modules/diff --git a/src/benchmark/README.md b/src/benchmark/README.mdnew file mode 100644index 000000000..34693bb6a--- /dev/null+++ b/src/benchmark/README.md@@ -0,0 +1,141 @@+# Independent browser benchmark++A manual tool for measuring real user operations against an already running application. It owns its Node/Playwright dependencies and imports no Alook product code. Copy this directory outside the repository to run it. Neither workspace tests nor CI invoke its scenarios.++The first journey uses a 100-member top-level text channel and two real user pages in one Chromium instance. The sender types and presses Enter; both pages must show the same message in the viewport. API-only measurements are available as supporting protocol calibration, not as the user-operation result.++## Install and run++```sh+cd src/benchmark+npm ci+npx playwright install chromium+cp example.config.json run.local.json+node src/cli.mjs run run.local.json+```++Record the exact product SHA and environment/build description in the config. The browser's WS endpoint comes from the real application's configuration; `wsUrl` is used only by protocol calibration. Disable the product's mock network when building the target. The target requires its ordinary migrations, local bindings and authentication configuration.++Supply a dedicated credential fixture, never commit or upload it:++```json+{+ "serverId": "dedicated-server-id",+ "channelId": "dedicated-channel-id",+ "accounts": [+ { "userId": "sender-id", "cookie": "AUTHENTICATION_COOKIES" },+ { "userId": "receiver-id", "cookie": "AUTHENTICATION_COOKIES" }+ ]+}+```++Use authenticated accounts with onboarding already handled. Export authentication cookies, not one-time signup markers that restart onboarding on every fresh context. The first account sends and the second receives. Membership APIs verify exactly `expectedMembers` visible members and access for both measured users; 100 members does not mean 100 online browser pages.++For fresh local fixtures, `accounts LOCAL_URL FIXTURE [COUNT]` calls the public signup API with `BENCHMARK_PASSWORD` from the environment. It saves credentials with mode 0600 and omits the one-time signup marker. `setup CONFIG` creates a server/channel and joins all accounts through public APIs. These preparations are outside timing and are not product performance measurements. Existing server/channel references are never overwritten; test data is not automatically deleted.++The browser driver navigates to the configured public route, waits for the actual page WS authentication and composer, and uses the visible scroll-to-present control until the page reaches the latest messages. It fills the composer before timing. It never calls product stores, mutation functions or internal UI helpers. Selectors, route templates and `submitAction: "enter" | "click"` can be supplied through `scenario`; defaults describe Alook's public DOM. Desktop Alook uses Enter by default.++## Add a case++`case` selects a factory in `src/cases/index.mjs`; the default is `channel-message-send`. Add one module and one registry entry. The common browser loop and report do not contain message selectors, WS event names, nonce decoding, participant-count assumptions or business success conditions. `http-counter-control` is a synthetic tool control, not additional Alook product coverage.++A factory receives the loaded config and returns this contract:++| Hook/field | Responsibility |+|---|---|+| `id`, `version`, `options`, `metrics` | Public case identity and configuration; each metric declares `label`, `unit`, `successOnly`. |+| `prepare({config})` | Validate case-specific settings; return sanitized public `fixture`, `participants: [{name,path,cookie?}]`, and `workloads: [{id,label,params}]`. Credentials belong only in participants, never the public fixture. |+| `setupPage({page,context,connection,participant,role,fixture,config})` | Prepare the visible page and install its observer before measurement. |+| `prepareSample({config,fixture,pages,workload,id})` | Prepare input outside timing; return private input passed to later hooks, not automatically written to artifacts. |+| `arm`, `perform`, `freeze` | Arm the probe, perform a real browser action and await the case's completion with bounded Playwright timeouts, then return frozen observations. Receive the same context plus `input`; perform/freeze also receive `operation`. |+| `finish({...context,input,snapshot,operation})` | Return `submit: {role,atMs,isTrusted,eventType}`, `metrics`, sanitized `diagnostics`, and `error` or null. `atMs` is the page's `performance.timeOrigin + performance.now()` from the actual event. Missing/nontrusted/out-of-window submit or nonfinite declared metrics makes the common runner reject success. |+| Optional `classifyRequest({request,role,fixture,operation,config})` | Return `direct`, `inject`, `observeDB`, sanitized `details`. Only selected requests receive delay. DB tagging also requires same origin and `observeDB: true` in config. |+| Optional `responseDetails({record,body,fixture,config})`, `frameDetails({payload,direction,role,fixture,config})` | Decode only public correlation metadata. A frame decoder may return `ready` for its own setup and `details` for artifacts. Omitted hooks make no WS/protocol assumptions. |++`pages` contains each public Playwright page/context plus calibrated clock, CDP session and generic connection state. The shared loop owns phase/workload/sample iteration, browser lifetime, network and CPU/heap capture, cutoff copies and persistence. The case owns completion and must bound its action waits with `config.timeoutMs`. Hook failure remains a failed operation or an incomplete run, never successful zero latency.++`fixtureFile` is optional and may contain any case-specific data. Account identity and member-count validation belong to the message preparation helper; `accounts`, `setup` and `calibrate` remain explicit message-fixture/protocol utilities. Message defaults (`payloadBytes`, `receivers`, `expectedMembers`, `historyLimit`, `scenario`) are ignored by the HTTP control. New case options can be read from config and must be recorded in the case's public `options` or workloads for comparison.++Reports aggregate declared metrics and arbitrary participant counts without loading the case. Case ID/version/options, metric names/units, workloads, participants and the tool digest (including nested case modules) form the comparison contract. Browser artifacts use **schema 2**; experimental schema-1 artifacts require their original tool version for rebuilding, and are not silently converted.++## Native, diagnostic and delay runs++The example is a native observation run: `observeDB: false`, one baseline phase with zero delay. HTTP/WS are observed passively; no routing is installed, so the tool does not disable HTTP cache. Both modes block service workers to ensure the page network is observable; this browser setting is recorded and is a limitation for service-worker-dependent journeys.++For D1 diagnostics, set `observeDB: true` and use the optional adapter below. For delay calibration, specify:++```json+"phases": [+ { "name": "baseline", "delayMs": 0 },+ { "name": "request-delay", "delayMs": 1000 }+]+```++Only the sender's message POST is delayed, before forwarding it to the server. WS and other requests are not delayed. Actual waits are recorded. The local optimistic row can appear during that wait. There is one delay mode; phase entries contain only a name and delayMs, with no request/response selector.++Any DB-header or delay run uses Playwright routing, which disables HTTP cache for the context. Reports explicitly identify `intercepted-cache-disabled` versus `passive-native-cache`; the comparator refuses to mix these modes. Compare observer-on/off or delayed/undelayed runs as calibration evidence, not as product version improvement. The target's normal entry and bundle contain no benchmark instrumentation; the optional wrapper is selected only by a dedicated runtime command.++## Recorded observations++- **Submit:** trusted real keydown/click received by the control. Preparation and filling are outside this timestamp.+- **Sender/receiver DOM visible:** the uniquely marked message intersects the viewport, is not hidden/transparent or clipped away, and the document is visible. An optimistic local row is distinguished from its canonical replacement. Real ID reconciliation is a diagnostic, not a visible delivery receipt.+- **Next animation frame:** separate callback after DOM visibility; it does not prove physical display paint. Each page uses `performance.timeOrigin + performance.now()` in the same browser instance. Node/HTTP timestamps additionally carry min-RTT clock calibration and its uncertainty.+- **Network:** HTTP request bodies, decoded response bodies, and WS application frames. Direct message requests are separated from other operations observed in the window. IDs/nonces link API, WS and DOM; raw bodies, tokens and message text are not logged. A shared WS frame is counted once in window bytes. No TLS, headers or physical wire size is claimed.+- **Resources:** CDP `threadTicks` task/script/layout duration deltas for each page's main thread, plus JS heap before/after. CPU sampling brackets probe arm through DOM freeze and includes driver/probe and concurrent work. This is not total browser/process CPU or server CPU.++The observation window starts just before the real action. It lasts at least `observationWindowMs` and can extend while waiting for the visible endpoints, bounded by action/visibility timeouts. DOM observations freeze at cutoff. HTTP records at cutoff remain immutable; later body completions are retained separately in raw requests and do not backfill window totals. Unfinished requests, failures, duplicates, WS disconnections and missing observations remain explicit. A quiet/fixed window does not prove all background work completed.++Warmups are retained but excluded from summaries. Success percentiles exclude failed attempts; failed attempts remain in the denominator and failed HTTP timing has its own field. Nearest-rank p50/p95 use available observations; small-sample tails are exploratory. Serial closed-loop operations include the observation window and configured pacing, so injected runs may have lower offered load.++## Optional generic Worker/D1 adapter++The runner itself works without this adapter and reports DB as unknown. Generate an independent entry around a target's normal Worker entry:++```sh+node src/benchmark/src/cli.mjs adapter src/web/custom-worker.ts src/benchmark/.runtime/worker.mjs+pnpm exec wrangler dev src/benchmark/.runtime/worker.mjs \+ --config src/web/wrangler.toml --config src/ws-do/wrangler.toml \+ --config src/queue-worker/wrangler.toml --local --port 3000 \+ --inspector-port 9237 --persist-to src/web/.wrangler/state \+ > /tmp/benchmark-worker.log 2>&1+```++Run this from the target repository after building its ordinary OpenNext artifact. These are example local target-launch commands, not imports required by this package or deployment instructions. Match the target's migration and runtime persistence paths. Regenerate the adapter after moving its absolute paths. If services share ingress 3000, configure the target's local WS URL/port accordingly.++Only requests carrying valid benchmark IDs activate the wrapper. It preserves fetch responses, D1 return values, session/bookmarks, atomic batches and tracked `waitUntil` tasks. Join captured records after the run:++```sh+node src/cli.mjs report artifacts/trace-run /tmp/benchmark-worker.log+```++D1 execution calls and submitted statements are different: batch is one call with N submitted statements, including failed batches without assuming all succeeded. `exec` retains its runtime-reported count separately; submitted SQL statement count remains unknown because that count is not a portable statement parser. Prepare/bind/session construction are not executions.++Rows read/written, SQL duration and internal attempts come only from actual metadata. `raw()`/`first()` supply no metadata: the adapter never issues extra queries or substitutes `all()`. Reports show known partial totals and coverage. Trigger/batch rollback behavior is calibrated against real local D1. Auth/schema introspection is real observed cost; it must not be mislabeled as message writes.++SQL UTF-8, bound-value JSON and result JSON logical bytes are separate. Binary data uses `{"binaryBase64":"..."}`; unsupported JSON values yield unknown sizes. No SQL, values or results are emitted. These counts do not measure D1 physical page I/O or transport bytes. The wrapper itself has measurement overhead.++Coverage is **web env.DB only**. WS DO server resources, queue consumers, other bindings, server CPU/RSS and physical I/O remain unknown. A web completion closes only that invocation's tracked tasks. Background calls starting or crossing the response remain identified. Completion records include the actual D1 execution count: fully closed requests with an explicit zero count report zero cost; missing execution logs or older completion records without that count cannot prove zero. Known missing D1 events invalidate complete metadata coverage and block cost comparison; observed partial values remain available. Duplicate logs are deduplicated; conflicting observations fail report generation. Share filtered `db.jsonl`, never raw target logs or fixture credentials.++## Compare and verify++```sh+node src/cli.mjs compare artifacts/base artifacts/head+```++Use the same fixture scale, browser, environment, tool source digest, scenario, viewport, observation mode, payloads, samples, warmup and pacing. Change `targetVersion` to the actual target commit. The comparator refuses incompatible contracts; it emits absolute values, deltas and percentages, with null percentage for zero baseline. Partial DB costs retain coverage; differing coverage prevents a conclusion about total cost. A/A runs are repeatability controls, not optimization evidence.++Each browser run creates metadata, `operations.jsonl`, first/last and prepared-page screenshots, JSON and Markdown summaries. Report rebuilding adds `db.jsonl`; comparison adds JSON/Markdown to the head directory. Every run requires an empty output directory. Inspect screenshots and IDs to verify that the measured page content matches the operation. Interrupted runs lack `finishedAt` and are incomplete.++Dedicated tool checks (not product test/CI integration):++```sh+npm run check+node test/browser-probe.control.mjs+node test/case-extension.control.mjs+```++The extension control starts its own local HTTP server and uses the normal CLI/config/registry with no accounts: two one-page A/A runs, exact report rebuilding, custom metrics and generic HTTP/CPU fields. It also verifies that missing, nontrusted and invalid-page submit records fail. It leaves inspectable artifacts and closes its browser/server.++The probe control verifies trusted input, replacement of an optimistic node before the next frame, frozen observations, and hidden/offscreen exclusion. `test/d1-control-worker.mjs` is a manual actual-D1 control target for trigger, batch rollback, raw columns and first() behavior. `calibrate CONFIG` retains the API/WS/history runner and 0/1000ms proxy for supporting protocol calibration; its `samples.jsonl` report is never the primary user journey.++References: [Playwright routing/cache](https://playwright.dev/docs/api/class-browsercontext#browser-context-route), [High Resolution Time](https://www.w3.org/TR/hr-time-3/), [D1 metadata](https://developers.cloudflare.com/d1/worker-api/return-object/).diff --git a/src/benchmark/example.config.json b/src/benchmark/example.config.jsonnew file mode 100644index 000000000..8a5de877a--- /dev/null+++ b/src/benchmark/example.config.json@@ -0,0 +1,29 @@+{+ "case": "channel-message-send",+ "baseUrl": "http://localhost:3000",+ "targetKind": "local",+ "targetVersion": "REPLACE_WITH_TARGET_GIT_SHA",+ "environment": "local Alook test stack; NEXT_PUBLIC_MOCK_NETWORK disabled",+ "fixtureFile": "fixture.local.json",+ "outDir": "artifacts/first-run",+ "expectedMembers": 100,+ "receivers": 1,+ "samples": 100,+ "warmup": 5,+ "concurrency": 1,+ "intervalMs": 400,+ "timeoutMs": 15000,+ "payloadBytes": [+ 64,+ 1024+ ],+ "historyLimit": 20,+ "observeDB": false,+ "observationWindowMs": 1800,+ "phases": [+ {+ "name": "baseline",+ "delayMs": 0+ }+ ]+}diff --git a/src/benchmark/package-lock.json b/src/benchmark/package-lock.jsonnew file mode 100644index 000000000..bf68383cb--- /dev/null+++ b/src/benchmark/package-lock.json@@ -0,0 +1,62 @@+{+ "name": "@alook/benchmark",+ "version": "0.1.37",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@alook/benchmark",+ "version": "0.1.37",+ "dependencies": {+ "playwright": "1.62.1"+ },+ "engines": {+ "node": ">=22.15"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/playwright": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",+ "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.62.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",+ "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ }+ }+}diff --git a/src/benchmark/package.json b/src/benchmark/package.jsonnew file mode 100644index 000000000..8da82f090--- /dev/null+++ b/src/benchmark/package.json@@ -0,0 +1,17 @@+{+ "name": "@alook/benchmark",+ "private": true,+ "type": "module",+ "engines": {+ "node": ">=22.15"+ },+ "scripts": {+ "benchmark": "node src/cli.mjs",+ "test": "node --test test/*.test.mjs",+ "check": "node --check src/cli.mjs && node --test test/*.test.mjs"+ },+ "version": "0.1.37",+ "dependencies": {+ "playwright": "1.62.1"+ }+}diff --git a/src/benchmark/src/adapter.mjs b/src/benchmark/src/adapter.mjsnew file mode 100644index 000000000..554a1e6b6--- /dev/null+++ b/src/benchmark/src/adapter.mjs@@ -0,0 +1,10 @@+import { writeFile, mkdir } from 'node:fs/promises'+import { resolve, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++export async function generateAdapter(entry, output) {+ const target = resolve(entry)+ const observer = fileURLToPath(new URL('./worker-observer.mjs', import.meta.url))+ await mkdir(dirname(resolve(output)), { recursive: true })+ await writeFile(output, `import worker from ${JSON.stringify(target)}\nimport { observeWorker } from ${JSON.stringify(observer)}\nexport * from ${JSON.stringify(target)}\nexport default observeWorker(worker)\n`)+}diff --git a/src/benchmark/src/browser-probe.mjs b/src/benchmark/src/browser-probe.mjsnew file mode 100644index 000000000..e9447b92f--- /dev/null+++ b/src/benchmark/src/browser-probe.mjs@@ -0,0 +1,73 @@+export function installBrowserProbe({ messageSelector, submitSelector, composerSelector, submitAction, idAttribute, optimisticPrefix }) {+ let active+ function now() { return performance.timeOrigin + performance.now() }+ function visible(element) {+ if (document.visibilityState !== 'visible' || !element.isConnected) return false+ const rect = element.getBoundingClientRect()+ let left = Math.max(0, rect.left), top = Math.max(0, rect.top)+ let right = Math.min(innerWidth, rect.right), bottom = Math.min(innerHeight, rect.bottom)+ for (let parent = element; parent; parent = parent.parentElement) {+ const style = getComputedStyle(parent)+ if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false+ if (parent !== element && /(auto|scroll|hidden|clip)/.test(style.overflow + style.overflowX + style.overflowY)) {+ const clip = parent.getBoundingClientRect()+ left = Math.max(left, clip.left); right = Math.min(right, clip.right)+ top = Math.max(top, clip.top); bottom = Math.min(bottom, clip.bottom)+ }+ }+ if (right - left < 1 || bottom - top < 1) return false+ const hit = document.elementFromPoint((left + right) / 2, (top + bottom) / 2)+ return hit !== null && (element.contains(hit) || hit.contains(element))+ }+ function scan() {+ if (!active) return+ for (const row of document.querySelectorAll(messageSelector)) {+ if (!row.textContent?.includes(active.text) || !visible(row)) continue+ const id = row.getAttribute(idAttribute)+ if (!id) continue+ const state = active+ if (state.visibleMs === null) {+ state.visibleMs = now()+ state.firstId = id++ }+ if (state.nextFrameMs === null) requestAnimationFrame(() => { if (active === state && visible(row)) state.nextFrameMs ??= now() })+ if (!id.startsWith(optimisticPrefix) && state.canonicalMs === null) {+ state.canonicalMs = now(); state.messageId = id+ }+ }+ }+ const observer = new MutationObserver(scan)+ observer.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true })+ addEventListener('scroll', scan, true)+ addEventListener('resize', scan)+ addEventListener('click', event => {+ if (active && event.target instanceof Element && event.target.closest(submitSelector)) { active.clickMs ??= now(); active.eventType = event.type; active.isTrusted = event.isTrusted }+ }, true)+ addEventListener('keydown', event => {+ if (active && submitAction === 'enter' && event.key === 'Enter' && !event.shiftKey && event.target instanceof Element && event.target.closest(composerSelector)) { active.clickMs ??= now(); active.eventType = event.type; active.isTrusted = event.isTrusted }+ }, true)+ window.__BENCHMARK_PROBE__ = {+ arm(text) { active = { text, visibilityState: document.visibilityState, timeOrigin: performance.timeOrigin, eventType: null, isTrusted: null, clickMs: null, visibleMs: null, nextFrameMs: null, canonicalMs: null, messageId: null, firstId: null } },+ snapshot() { if (!active) return null; const { text, ...result } = active; return result },+ freeze() { const result = this.snapshot(); active = undefined; return result },+ stop() { active = undefined },+ }+}++export async function syncPageClock(page, attempts = 7) {+ let best+ for (let i = 0; i < attempts; i++) {+ const before = performance.now()+ const browser = await page.evaluate(() => performance.timeOrigin + performance.now())+ const after = performance.now()+ const sample = { offsetMs: (before + after) / 2 - browser, uncertaintyMs: (after - before) / 2, roundTripMs: after - before }+ if (!best || sample.roundTripMs < best.roundTripMs) best = sample+ }+ return best+}++export function metricDelta(before, after, name, multiplier = 1) {+ const a = before[name], b = after[name]+ return Number.isFinite(a) && Number.isFinite(b) && b >= a ? (b - a) * multiplier : null+}diff --git a/src/benchmark/src/browser-report.mjs b/src/benchmark/src/browser-report.mjsnew file mode 100644index 000000000..763559a8f--- /dev/null+++ b/src/benchmark/src/browser-report.mjs@@ -0,0 +1,46 @@+import { distribution, dbMetrics, deduplicateTelemetry } from './report.mjs'++const sum = values => values.reduce((a, b) => a + b, 0)+const requests = sample => sample.requestsAtCutoff+const frames = sample => sample.framesAtCutoff++export function browserSummary(samples, metadata, telemetry = []) {+ if (metadata.schemaVersion !== 2 || !metadata.case?.metrics || !metadata.workloads || !metadata.participants) throw new Error('Unsupported browser artifact schema; rebuild with the tool version recorded by that run')+ const deduplicated = deduplicateTelemetry(telemetry)+ telemetry = deduplicated.events+ const measured = samples.filter(sample => !sample.warmup), groups = []+ for (const phase of metadata.config.phases) for (const workload of metadata.workloads) {+ const selected = measured.filter(sample => sample.phase === phase.name && sample.workloadId === workload.id)+ if (!selected.length) continue+ const good = selected.filter(sample => !sample.error)+ const db = direct => dbMetrics(selected.flatMap(sample => requests(sample).filter(record => record.direct === direct && record.observedDB).map(record => record.id)), telemetry)+ groups.push({ phase: phase.name, workloadId: workload.id, workloadLabel: workload.label, attempted: selected.length, failed: selected.length - good.length,+ caseMetrics: Object.fromEntries(Object.entries(metadata.case.metrics).map(([name, definition]) => [name, distribution((definition.successOnly === false ? selected : good).map(sample => sample.result.metrics[name]))])),+ directAckMs: distribution(selected.flatMap(sample => requests(sample).filter(record => record.direct && record.status >= 200 && record.status < 300 && !record.failure && record.finishedMs !== null && sample.submitNodeMs !== null).map(record => record.finishedMs - sample.submitNodeMs))),+ failedHttpMs: distribution(selected.flatMap(sample => requests(sample).filter(record => record.direct && (record.status >= 400 || record.failure) && record.finishedMs !== null && sample.submitNodeMs !== null).map(record => record.finishedMs - sample.submitNodeMs))),+ socketCloses: sum(selected.flatMap(sample => sample.socketCloses)), collectorErrors: sum(selected.map(sample => sample.collectorErrors.length)),+ unfinishedRequests: sum(selected.map(sample => sample.unfinishedRequestsAtCutoff)),+ directRequestBodyBytes: distribution(selected.map(sample => sum(requests(sample).filter(record => record.direct).map(record => record.requestBodyBytes)))),+ directResponseBodyBytes: distribution(selected.flatMap(sample => requests(sample).filter(record => record.direct).map(record => record.responseBodyBytes))),+ windowHttpResponseBodyBytes: distribution(selected.map(sample => sum(requests(sample).filter(record => record.finishedMs !== null && record.finishedMs <= sample.cutoffMs).map(record => record.responseBodyBytes ?? 0)))),+ windowWsApplicationBytes: distribution(selected.map(sample => sum(frames(sample).map(frame => frame.bytes)))),+ pageTaskCpuMs: metadata.participants.map(({ role }) => distribution(selected.map(sample => sample.resources[role].taskCpuMs))),+ pageJsHeapDeltaBytes: metadata.participants.map(({ role }) => distribution(selected.map(sample => {+ const resource = sample.resources[role]+ return Number.isFinite(resource.jsHeapBeforeBytes) && Number.isFinite(resource.jsHeapAfterBytes) ? resource.jsHeapAfterBytes - resource.jsHeapBeforeBytes : null+ }))),+ db: { directRequests: db(true), otherWindowRequests: db(false) }, smallSampleWarning: selected.length < 100 ? 'Fewer than 100 attempts; tail percentiles exploratory.' : null })+ }+ return { ...metadata, duplicateTelemetryRecords: deduplicated.duplicateTelemetryRecords, groups,+ db: dbMetrics(measured.flatMap(sample => requests(sample).filter(record => record.observedDB).map(record => record.id)), telemetry),+ limits: ['DOM visibility and animation-frame callbacks do not prove physical screen paint.', 'HTTP bodies are decoded application bytes; WS excludes protocol framing.', 'Window HTTP/WS and page main-thread CPU include concurrent work and observer overhead; window does not prove background completion.', 'DB covers only instrumented web env.DB. Other services, server CPU/RSS and physical I/O remain unknown.'] }+}++const format = distribution => [distribution.p50, distribution.p95].map(value => value?.toFixed(2) ?? 'unknown').join('/')+export function browserMarkdown(report) {+ const definitions = Object.entries(report.case.metrics)+ const rows = report.groups.map(group => `| ${group.phase}/${group.workloadLabel} | ${group.attempted}/${group.failed} | ${definitions.map(([name]) => format(group.caseMetrics[name])).join(' | ')} | ${format(group.directAckMs)} |`).join('\n')+ const resource = report.groups.map(group => `| ${group.phase}/${group.workloadLabel} | ${report.participants.map(({ role, name }) => `${name}: ${format(group.pageTaskCpuMs[role])}`).join('; ')} | ${format(group.directRequestBodyBytes)} | ${format(group.directResponseBodyBytes)} | ${format(group.windowHttpResponseBodyBytes)} | ${format(group.windowWsApplicationBytes)} | ${group.unfinishedRequests}/${group.collectorErrors}/${group.socketCloses} |`).join('\n')+ const db = report.groups.flatMap(group => Object.entries(group.db).map(([scope, value]) => `| ${group.phase}/${group.workloadLabel}/${scope} | ${value.executionCalls ?? 'unknown'} | ${value.submittedStatements ?? 'unknown'} | ${value.rowsRead.total ?? 'unknown'} (${value.rowsRead.coverage ?? 'unknown'}) | ${value.rowsWritten.total ?? 'unknown'} (${value.rowsWritten.coverage ?? 'unknown'}) | ${value.completedRequests}/${value.expectedRequests} |`)).join('\n')+ return `# Real browser operation benchmark\n\nCase ${report.case.id} v${report.case.version}; target ${report.config.targetVersion}; ${report.config.networkMode}. ${report.participants.length} real browser pages. Fixture: ${JSON.stringify(report.fixture)}.\n\nDistributions are p50/p95. Failed attempts stay in denominator; small-sample tails exploratory.\n\n| Phase/workload | Attempts/failed | ${definitions.map(([, definition]) => `${definition.label} (${definition.unit})`).join(' | ')} | Direct ACK ms |\n|---|---:|${definitions.map(() => '---:|').join('')}---:|\n${rows}\n\n| Phase/workload | Page main-thread CPU ms | Direct request B | Direct response B | Window HTTP response B | Window WS application B | Unclosed/collector errors/socket closes |\n|---|---|---:|---:|---:|---:|---:|\n${resource}\n\nD1 events known missing: ${report.db.missingD1Events ?? 'unknown (no complete execution counters)'}. Known loss blocks comparison.\n\nDB known totals, coverage fraction; unknown rows are not zero. Direct requests and other window requests are separate.\n\n| Scope | Calls | Submitted statements | Known rows read (coverage) | Known rows written (coverage) | Web request completion |\n|---|---:|---:|---:|---:|---:|\n${db}\n\n${report.limits.map(line => '- ' + line).join('\n')}\n\noperations.jsonl retains frozen cutoff observations, later HTTP completion, case-specific raw diagnostics, page clocks, trusted submit event, resource windows and injection waits.\n`+}diff --git a/src/benchmark/src/browser-runner.mjs b/src/benchmark/src/browser-runner.mjsnew file mode 100644index 000000000..ebd505263--- /dev/null+++ b/src/benchmark/src/browser-runner.mjs@@ -0,0 +1,164 @@+import { cpus, totalmem, release } from 'node:os'+import { chromium } from 'playwright'+import { mkdir, writeFile, appendFile, readFile, readdir } from 'node:fs/promises'+import { randomUUID, createHash } from 'node:crypto'+import { setTimeout as sleep } from 'node:timers/promises'+import { publicConfig } from './config.mjs'+import { syncPageClock, metricDelta } from './browser-probe.mjs'+import { browserSummary, browserMarkdown } from './browser-report.mjs'+import { resolveCase } from './cases/index.mjs'++async function metrics(session) {+ return Object.fromEntries((await session.send('Performance.getMetrics')).metrics.map(item => [item.name, item.value]))+}+function cookies(cookie, baseUrl) {+ if (!cookie) return []+ return cookie.split(';').map(part => {+ const index = part.indexOf('=')+ if (index < 1) throw new Error('Invalid participant cookie')+ return { name: part.slice(0, index).trim(), value: part.slice(index + 1).trim(), url: baseUrl }+ })+}+async function sourceDigest() {+ const digest = createHash('sha256')+ async function walk(directory, prefix = '') {+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {+ const name = prefix + entry.name+ if (entry.isDirectory()) await walk(new URL(entry.name + '/', directory), name + '/')+ else if (entry.name.endsWith('.mjs')) { digest.update(name); digest.update(await readFile(new URL(entry.name, directory))) }+ }+ }+ await walk(new URL('.', import.meta.url))+ digest.update(await readFile(new URL('../package-lock.json', import.meta.url)))+ return digest.digest('hex')+}++export async function runBrowserBenchmark(config, suppliedCase) {+ if (config.concurrency !== 1) throw new Error('Browser runner currently requires serial concurrency=1')+ const benchmarkCase = suppliedCase ?? resolveCase(config)+ for (const key of ['prepare', 'setupPage', 'prepareSample', 'arm', 'perform', 'freeze', 'finish']) if (typeof benchmarkCase[key] !== 'function') throw new Error(`Case requires ${key}`)+ if (!benchmarkCase.id || !Number.isInteger(benchmarkCase.version) || !benchmarkCase.metrics || !Object.keys(benchmarkCase.metrics).length) throw new Error('Case requires identity, version and metric definitions')+ for (const definition of Object.values(benchmarkCase.metrics)) if (!definition.label || !definition.unit || typeof definition.successOnly !== 'boolean') throw new Error('Metrics require label, unit and successOnly')+ const prepared = await benchmarkCase.prepare({ config })+ const { fixture, participants, workloads } = prepared+ if (!participants?.length || !workloads?.length || new Set(workloads.map(item => item.id)).size !== workloads.length) throw new Error('Case requires participants and distinct workloads')+ const intercepted = config.observeDB || config.phases.some(phase => phase.delayMs > 0)+ const windowMs = config.observationWindowMs ?? 1800+ await mkdir(config.outDir, { recursive: true })+ if ((await readdir(config.outDir)).length) throw new Error('Output directory must be empty; preserve each run separately')+ const browser = await chromium.launch({ headless: config.headless !== false, ...(config.executablePath ? { executablePath: config.executablePath } : {}), args: ['--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'] })+ const runId = randomUUID(), samples = [], pages = [], pendingCapture = new Set()+ let active = null, requestSequence = 0+ const metadata = { kind: 'browser-user-operation', schemaVersion: 2, runId, startedAt: new Date().toISOString(),+ case: { id: benchmarkCase.id, version: benchmarkCase.version, metrics: benchmarkCase.metrics, options: benchmarkCase.options ?? {} }, workloads,+ participants: participants.map((item, role) => ({ role, name: item.name })), fixture,+ config: { ...publicConfig(config), observationWindowMs: windowMs, viewport: config.viewport ?? { width: 1280, height: 900 }, headless: config.headless !== false, serviceWorkers: 'block', networkMode: intercepted ? 'intercepted-cache-disabled' : 'passive-native-cache' },+ runner: { toolDigest: await sourceDigest(), hardware: { cpuModel: cpus()[0]?.model ?? null, logicalCpus: cpus().length, totalMemoryBytes: totalmem(), osRelease: release() }, node: process.version, platform: process.platform, arch: process.arch, browser: browser.version() },+ coverage: 'Real browser pages; page main-thread CPU/JS heap including observer overhead; HTTP/WS application bytes; optional web env.DB only. Unobserved services, server CPU/RSS and physical I/O unknown.' }+ await writeFile(`${config.outDir}/metadata.json`, JSON.stringify(metadata, null, 2))+ await writeFile(`${config.outDir}/operations.jsonl`, '')+ try {+ for (let role = 0; role < participants.length; role++) {+ const participant = participants[role]+ const context = await browser.newContext({ viewport: metadata.config.viewport, serviceWorkers: 'block' })+ await context.addCookies(cookies(participant.cookie, config.baseUrl))+ const page = await context.newPage(), cdp = await context.newCDPSession(page)+ await cdp.send('Performance.enable', { timeDomain: 'threadTicks' })+ const connection = { ready: false, closes: 0 }, requests = new Map()+ page.on('request', request => {+ const operation = active, url = new URL(request.url())+ if (!operation || !['http:', 'https:'].includes(url.protocol)) return+ let classification = {}+ try { classification = benchmarkCase.classifyRequest?.({ request, role, fixture, operation, config }) ?? {} }+ catch { operation.collectorErrors.push('case-request-classification-failed') }+ const record = { id: `${operation.id}-r${requestSequence++}`, role, origin: url.origin, path: url.pathname, method: request.method(),+ observedDB: config.observeDB && url.origin === config.baseUrl && classification.observeDB !== false,+ direct: classification.direct === true, inject: classification.inject === true, details: classification.details ?? null,+ startMs: performance.now(), status: null, finishedMs: null, failure: null, requestBodyBytes: request.postDataBuffer()?.byteLength ?? 0, responseBodyBytes: null }+ operation.requests.push(record); requests.set(request, record)+ })+ if (intercepted) await context.route('**/*', async route => {+ const request = route.request(), record = requests.get(request), operation = active+ if (!record || !operation || (!record.observedDB && !record.inject)) return route.continue()+ const headers = { ...request.headers(), ...(record.observedDB ? { 'x-alook-benchmark-id': record.id } : {}) }+ if (record.inject && operation.phaseConfig.delayMs) {+ const at = performance.now(); await sleep(operation.phaseConfig.delayMs)+ operation.injections.push({ requestId: record.id, actualMs: performance.now() - at, configuredMs: operation.phaseConfig.delayMs })+ }+ await route.continue({ headers }).catch(() => { record.failure = 'interception-failed' })+ })+ page.on('requestfailed', request => { const record = requests.get(request); if (record) { record.failure = 'request-failed'; record.finishedMs = performance.now() } })+ page.on('response', response => {+ const record = requests.get(response.request())+ if (!record) return+ record.status = response.status()+ const capture = (async () => {+ try {+ const body = await response.body()+ record.finishedMs = performance.now(); record.responseBodyBytes = body.length+ try { record.responseDetails = benchmarkCase.responseDetails?.({ record, body, fixture, config }) ?? null }+ catch { record.failure = 'case-response-decode-failed' }+ } catch { record.failure = 'body-unavailable'; record.finishedMs = performance.now() }+ })()+ pendingCapture.add(capture); capture.finally(() => pendingCapture.delete(capture))+ })+ page.on('websocket', socket => {+ const receive = direction => ({ payload }) => {+ let decoded = {}+ try { decoded = benchmarkCase.frameDetails?.({ payload, direction, role, fixture, config }) ?? {} }+ catch { active?.collectorErrors.push('case-frame-decode-failed') }+ if (typeof decoded.ready === 'boolean') connection.ready = decoded.ready+ if (active) active.frames.push({ role, direction, atMs: performance.now(), bytes: typeof payload === 'string' ? Buffer.byteLength(payload) : payload.byteLength, details: decoded.details ?? null })+ }+ socket.on('framereceived', receive('receive')); socket.on('framesent', receive('send'))+ socket.on('close', () => { connection.ready = false; connection.closes++ })+ })+ await page.goto(new URL(participant.path, config.baseUrl).href, { waitUntil: 'domcontentloaded', timeout: 60000 })+ await benchmarkCase.setupPage({ page, context, connection, participant, role, fixture, config })+ pages.push({ page, context, cdp, connection, clock: await syncPageClock(page) })+ await page.screenshot({ path: `${config.outDir}/ready-${role}.png` })+ }+ metadata.clocks = pages.map(item => item.clock)+ for (const phase of config.phases) for (const workload of workloads) for (let index = 0; index < config.warmup + config.samples; index++) {+ const id = `${runId}-${samples.length}`, hook = { config, fixture, pages, workload, id }+ const input = await benchmarkCase.prepareSample(hook)+ const before = await Promise.all(pages.map(item => metrics(item.cdp))), closes = pages.map(item => item.connection.closes)+ await benchmarkCase.arm({ ...hook, input })+ const operation = { id, phase: phase.name, phaseConfig: phase, workloadId: workload.id, warmup: index < config.warmup, startedMs: performance.now(), requests: [], frames: [], injections: [], collectorErrors: [], error: null }+ active = operation+ try { await benchmarkCase.perform({ ...hook, input, operation }) } catch { operation.error = 'action-or-completion-timeout' }+ const left = operation.startedMs + windowMs - performance.now()+ if (left > 0) await sleep(left)+ let snapshot+ try { snapshot = await benchmarkCase.freeze({ ...hook, input, operation }) } catch { operation.error ??= 'case-freeze-failed' }+ operation.cutoffMs = performance.now(); active = null+ operation.requestsAtCutoff = structuredClone(operation.requests); operation.framesAtCutoff = structuredClone(operation.frames)+ try { operation.result = await benchmarkCase.finish({ ...hook, input, snapshot, operation }) } catch { operation.error ??= 'case-result-failed'; operation.result = { metrics: {} } }+ operation.error ??= operation.result.error ?? (operation.collectorErrors.length ? 'collector-error' : null)+ const submit = operation.result.submit+ const validSubmit = Number.isInteger(submit?.role) && !!pages[submit.role] && Number.isFinite(submit?.atMs) && submit.isTrusted === true+ operation.submitNodeMs = validSubmit ? submit.atMs + pages[submit.role].clock.offsetMs : null+ if (!validSubmit || operation.submitNodeMs < operation.startedMs - pages[submit.role].clock.roundTripMs || operation.submitNodeMs > operation.cutoffMs) operation.error ??= 'invalid-trusted-submit'+ for (const name of Object.keys(benchmarkCase.metrics)) if (!Number.isFinite(operation.result.metrics?.[name])) operation.error ??= 'missing-or-invalid-case-metric'+ const after = await Promise.all(pages.map(item => metrics(item.cdp)))+ operation.resources = after.map((values, role) => ({ role, observedWindow: 'before case arm through after freeze; includes driver/probe overhead',+ taskCpuMs: metricDelta(before[role], values, 'TaskDuration', 1000), scriptCpuMs: metricDelta(before[role], values, 'ScriptDuration', 1000), layoutCpuMs: metricDelta(before[role], values, 'LayoutDuration', 1000),+ jsHeapBeforeBytes: before[role].JSHeapUsedSize ?? null, jsHeapAfterBytes: values.JSHeapUsedSize ?? null }))+ operation.unfinishedRequestsAtCutoff = operation.requestsAtCutoff.filter(record => record.finishedMs === null).length+ operation.socketCloses = pages.map((item, role) => item.connection.closes - closes[role])+ if (samples.length === 0 || (phase === config.phases.at(-1) && workload === workloads.at(-1) && index === config.warmup + config.samples - 1)) {+ for (let role = 0; role < pages.length; role++) await pages[role].page.screenshot({ path: `${config.outDir}/sample-${samples.length}-page-${role}.png` })+ }+ samples.push(operation); await appendFile(`${config.outDir}/operations.jsonl`, JSON.stringify(operation) + '\n')+ if (config.intervalMs) await sleep(config.intervalMs)+ }+ metadata.finalClocks = await Promise.all(pages.map(item => syncPageClock(item.page)))+ await Promise.race([Promise.allSettled([...pendingCapture]), sleep(config.timeoutMs)])+ metadata.finishedAt = new Date().toISOString()+ await writeFile(`${config.outDir}/operations.jsonl`, samples.map(sample => JSON.stringify(sample)).join('\n') + '\n')+ await writeFile(`${config.outDir}/metadata.json`, JSON.stringify(metadata, null, 2))+ const report = browserSummary(samples, metadata)+ await writeFile(`${config.outDir}/summary.json`, JSON.stringify(report, null, 2)); await writeFile(`${config.outDir}/summary.md`, browserMarkdown(report))+ return report+ } finally { active = null; await browser.close() }+}diff --git a/src/benchmark/src/cases/http-counter-control.mjs b/src/benchmark/src/cases/http-counter-control.mjsnew file mode 100644index 000000000..f1c391cd3--- /dev/null+++ b/src/benchmark/src/cases/http-counter-control.mjs@@ -0,0 +1,32 @@+export function httpCounterControl(config) {+ return {+ id: 'http-counter-control', version: 1,+ metrics: { counterVisibleMs: { label: 'Counter DOM update', unit: 'ms', successOnly: true } },+ async prepare() { return { fixture: { kind: 'synthetic-tool-control' }, participants: [{ name: 'counter', path: '/' }], workloads: [{ id: 'increment', label: 'Increment by one', params: {} }] } },+ async setupPage({ page }) {+ await page.locator('#increment').waitFor({ state: 'visible', timeout: config.timeoutMs })+ await page.evaluate(() => {+ let active = null+ document.addEventListener('click', event => {+ if (active && event.target.closest('#increment')) active.submit = { role: 0, atMs: performance.timeOrigin + performance.now(), isTrusted: event.isTrusted, eventType: event.type }+ }, true)+ new MutationObserver(() => {+ if (active?.submit && document.querySelector('#count').textContent !== active.before && active.visibleAt === null) active.visibleAt = performance.timeOrigin + performance.now()+ }).observe(document.querySelector('#count'), { childList: true, subtree: true, characterData: true })+ window.__COUNTER_CONTROL__ = {+ arm() { active = { before: document.querySelector('#count').textContent, submit: null, visibleAt: null } },+ snapshot() { return active }, freeze() { const value = active; active = null; return value },+ }+ })+ },+ async prepareSample() { return {} },+ arm: ({ pages }) => pages[0].page.evaluate(() => window.__COUNTER_CONTROL__.arm()),+ async perform({ pages }) {+ await pages[0].page.locator('#increment').click({ timeout: config.timeoutMs })+ await pages[0].page.waitForFunction(() => window.__COUNTER_CONTROL__.snapshot()?.visibleAt !== null, undefined, { timeout: config.timeoutMs })+ },+ freeze: ({ pages }) => pages[0].page.evaluate(() => window.__COUNTER_CONTROL__.freeze()),+ finish({ snapshot }) { return { submit: snapshot.submit, metrics: { counterVisibleMs: snapshot.submit && snapshot.visibleAt !== null ? snapshot.visibleAt - snapshot.submit.atMs : null }, diagnostics: snapshot, error: snapshot.visibleAt === null ? 'counter-not-updated' : null } },+ classifyRequest({ request }) { const direct = new URL(request.url()).pathname === '/increment' && request.method() === 'POST'; return { direct, inject: direct, observeDB: false } },+ }+}diff --git a/src/benchmark/src/cases/index.mjs b/src/benchmark/src/cases/index.mjsnew file mode 100644index 000000000..67af6a1ce--- /dev/null+++ b/src/benchmark/src/cases/index.mjs@@ -0,0 +1,10 @@+import { messageSendCase } from './message-send.mjs'++import { httpCounterControl } from './http-counter-control.mjs'++const cases = { 'channel-message-send': messageSendCase, 'http-counter-control': httpCounterControl }+export function resolveCase(config) {+ const create = cases[config.case ?? 'channel-message-send']+ if (!create) throw new Error(`Unknown case: ${config.case}; available: ${Object.keys(cases).join(', ')}`)+ return create(config)+}diff --git a/src/benchmark/src/cases/message-send.mjs b/src/benchmark/src/cases/message-send.mjsnew file mode 100644index 000000000..07b0f6988--- /dev/null+++ b/src/benchmark/src/cases/message-send.mjs@@ -0,0 +1,94 @@+import { setTimeout as sleep } from 'node:timers/promises'+import { prepareFixture, messageEvents } from '../client.mjs'+import { installBrowserProbe } from '../browser-probe.mjs'++export const defaultScenario = {+ path: '/c/channels/{serverId}/{channelId}',+ composerSelector: '[data-testid="community-composer-input"] [contenteditable="true"]',+ submitAction: 'enter', scrollToPresentSelector: '[data-testid="community-scroll-to-present"]',+ submitSelector: '[data-testid="community-composer-send"]',+ messageSelector: '[data-msg-id]', idAttribute: 'data-msg-id', optimisticPrefix: 'temp_',+ sendPath: '/api/community/channels/{channelId}/messages',+}+const fillPath = (template, fixture) => template.replace(/\{(serverId|channelId)\}/g, (_, key) => encodeURIComponent(fixture[key]))++export function messageSendCase(config) {+ const scenario = { ...defaultScenario, ...config.scenario }+ return {+ id: 'channel-message-send', version: 1, options: scenario,+ metrics: {+ senderVisibleMs: { label: 'Sender DOM visible', unit: 'ms', successOnly: true },+ receiverVisibleMs: { label: 'Receiver DOM visible', unit: 'ms', successOnly: true },+ senderNextFrameMs: { label: 'Sender next frame', unit: 'ms', successOnly: true },+ receiverNextFrameMs: { label: 'Receiver next frame', unit: 'ms', successOnly: true },+ senderReconciledMs: { label: 'Sender reconciled (diagnostic)', unit: 'ms', successOnly: true },+ duplicateMessageFrames: { label: 'Duplicate receiver message frames', unit: 'count', successOnly: false },+ },+ async prepare() {+ if (config.receivers !== 1 || !Array.isArray(config.fixture.accounts) || config.fixture.accounts.length < 2) throw new Error('Message case requires two distinct users and receivers=1')+ if (scenario.submitAction && !['enter', 'click'].includes(scenario.submitAction)) throw new Error('Invalid submitAction')+ if (!Array.isArray(config.payloadBytes) || config.payloadBytes.some(size => size < 64)) throw new Error('Message case requires at least 64 content bytes')+ const fixture = await prepareFixture(config)+ return { fixture, participants: config.fixture.accounts.slice(0, 2).map((account, role) => ({ name: role === 0 ? 'sender' : 'receiver', cookie: account.cookie, path: fillPath(scenario.path, fixture) })),+ workloads: config.payloadBytes.map(payloadBytes => ({ id: `content-${payloadBytes}`, label: `${payloadBytes} content B`, params: { payloadBytes } })) }+ },+ classifyRequest({ request, role, fixture }) {+ const url = new URL(request.url())+ const direct = url.origin === config.baseUrl && role === 0 && request.method() === 'POST' && url.pathname === fillPath(scenario.sendPath, fixture)+ let clientNonce = null+ if (direct) { try { const body = request.postDataJSON(); clientNonce = body?.nonce ?? body?.clientNonce ?? null } catch {} }+ return { direct, inject: direct, observeDB: url.pathname.startsWith('/api/'), details: direct ? { clientNonce } : null }+ },+ responseDetails({ record, body }) { return record.direct ? { messageId: JSON.parse(body.toString('utf8'))?.message?.id ?? null } : null },+ frameDetails({ payload }) {+ let parsed+ try { parsed = JSON.parse(payload.toString()) } catch {}+ return { ready: parsed?.type === 'auth.ok' ? true : undefined, details: { type: parsed?.type ?? 'unparsed', messages: parsed ? messageEvents(parsed).map(event => ({ id: event.message.id, clientNonce: event.message.clientNonce ?? null })) : [] } }+ },+ async setupPage({ page, connection }) {+ await page.locator(scenario.composerSelector).waitFor({ state: 'visible', timeout: config.timeoutMs })+ const deadline = performance.now() + config.timeoutMs+ while (!connection.ready && performance.now() < deadline) await sleep(25)+ if (!connection.ready) throw new Error('Real page WS did not authenticate')+ await sleep(500)+ const scroll = page.locator(scenario.scrollToPresentSelector)+ while (await scroll.isVisible()) {+ if (performance.now() >= deadline) throw new Error('Could not prepare latest messages')+ await scroll.click(); await sleep(350)+ }+ if (await page.locator(scenario.composerSelector).count() !== 1) throw new Error('Expected one composer')+ await page.evaluate(installBrowserProbe, scenario)+ },+ async prepareSample({ pages, workload, id }) {+ const marker = `benchmark-${id.slice(0, 8)}-${id.split('-').at(-1)}-`+ const text = marker + 'x'.repeat(workload.params.payloadBytes - marker.length)+ await pages[0].page.locator(scenario.composerSelector).fill(text)+ return { text }+ },+ async arm({ pages, input }) { await Promise.all(pages.map(item => item.page.evaluate(text => window.__BENCHMARK_PROBE__.arm(text), input.text))) },+ async perform({ pages }) {+ if (pages.some(item => !item.connection.ready)) throw new Error('Page WS disconnected')+ if (scenario.submitAction === 'enter') await pages[0].page.locator(scenario.composerSelector).press('Enter', { timeout: config.timeoutMs })+ else await pages[0].page.locator(scenario.submitSelector).click({ timeout: config.timeoutMs })+ await Promise.all(pages.map(item => item.page.waitForFunction(() => {+ const sample = window.__BENCHMARK_PROBE__.snapshot()+ return sample && sample.visibleMs !== null && sample.nextFrameMs !== null && sample.messageId !== null+ }, undefined, { timeout: config.timeoutMs })))+ },+ freeze: ({ pages }) => Promise.all(pages.map(item => item.page.evaluate(() => window.__BENCHMARK_PROBE__.freeze()))),+ finish({ snapshot, operation, pages }) {+ const submit = { role: 0, atMs: snapshot[0]?.clickMs ?? null, eventType: snapshot[0]?.eventType, isTrusted: snapshot[0]?.isTrusted }+ const delta = value => Number.isFinite(value) && Number.isFinite(submit.atMs) ? value - submit.atMs : null+ const dom = snapshot.map((value, role) => ({ ...value, role, visibleMs: delta(value.visibleMs), nextFrameMs: delta(value.nextFrameMs), canonicalMs: delta(value.canonicalMs) }))+ const messageId = dom[0].messageId+ const sameCanonicalMessage = !!messageId && messageId === dom[1].messageId+ const sends = operation.requestsAtCutoff.filter(record => record.direct)+ const responseIds = sends.map(record => record.responseDetails?.messageId).filter(Boolean)+ const httpCanonicalMatch = responseIds.length > 0 ? responseIds.every(id => id === messageId) : null+ const receivedMessageFrames = operation.framesAtCutoff.filter(frame => frame.role === 1 && frame.details?.messages?.some(message => message.id === messageId)).length+ return { submit, metrics: { senderVisibleMs: dom[0].visibleMs, receiverVisibleMs: dom[1].visibleMs, senderNextFrameMs: dom[0].nextFrameMs, receiverNextFrameMs: dom[1].nextFrameMs, senderReconciledMs: dom[0].canonicalMs, duplicateMessageFrames: Math.max(0, receivedMessageFrames - 1) },+ diagnostics: { dom, clientNonce: sends[0]?.details?.clientNonce ?? null, sameCanonicalMessage, httpCanonicalMatch, receivedMessageFrames, wsDisconnected: pages.map(item => !item.connection.ready) },+ error: !sameCanonicalMessage ? 'canonical-message-mismatch' : httpCanonicalMatch === false ? 'http-message-mismatch' : null }+ },+ }+}diff --git a/src/benchmark/src/cli.mjs b/src/benchmark/src/cli.mjsnew file mode 100644index 000000000..eb6992f50--- /dev/null+++ b/src/benchmark/src/cli.mjs@@ -0,0 +1,85 @@+import { readFile, writeFile } from 'node:fs/promises'+import { loadConfig } from './config.mjs'+import { prepareFixture } from './client.mjs'+import { runBrowserBenchmark } from './browser-runner.mjs'+import { browserSummary, browserMarkdown } from './browser-report.mjs'+import { runBenchmark } from './runner.mjs'+import { summarize, markdown } from './report.mjs'+import { compareReports, comparisonMarkdown } from './compare.mjs'+import { generateAdapter } from './adapter.mjs'++async function main(args) {+ const [command, path, third] = args+ if (command === 'run' || command === 'calibrate') {+ const config = await loadConfig(path)+ const report = await (command === 'run' ? runBrowserBenchmark : runBenchmark)(config)+ console.log(JSON.stringify({ runId: report.runId, output: config.outDir, groups: report.groups.length, db: report.db.status }))+ } else if (command === 'compare') {+ const base = JSON.parse(await readFile(`${path}/summary.json`, 'utf8'))+ const head = JSON.parse(await readFile(`${third}/summary.json`, 'utf8'))+ const report = compareReports(base, head)+ await writeFile(`${third}/comparison.json`, JSON.stringify(report, null, 2))+ await writeFile(`${third}/comparison.md`, comparisonMarkdown(report))+ console.log(JSON.stringify({ output: `${third}/comparison.md`, sameVersionControl: report.sameVersionControl }))+ } else if (command === 'setup') {+ const config = await loadConfig(path)+ if (config.fixture.serverId || config.fixture.channelId) throw new Error('Fixture already references a server/channel; setup will not overwrite it')+ await prepareFixture(config, true)+ const { resolve, dirname } = await import('node:path')+ await writeFile(resolve(dirname(path), config.fixtureFile), JSON.stringify(config.fixture, null, 2), { mode: 0o600 })+ console.log(JSON.stringify({ serverId: config.fixture.serverId, channelId: config.fixture.channelId }))+ } else if (command === 'accounts') {+ const [baseUrl, output, countArg = '100'] = args.slice(1)+ const url = new URL(baseUrl)+ const count = Number(countArg)+ if (!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) throw new Error('Automatic dev account creation requires a local target')+ if (!Number.isInteger(count) || count < 2 || count > 1000 || !process.env.BENCHMARK_PASSWORD) throw new Error('Set BENCHMARK_PASSWORD and count 2..1000')+ const { randomUUID } = await import('node:crypto')+ const stamp = randomUUID().slice(0, 8)+ const accounts = []+ for (let i = 0; i < count; i++) {+ const response = await fetch(new URL('/api/auth/sign-up/email', url), {+ method: 'POST', headers: { 'Content-Type': 'application/json', Origin: url.origin },+ body: JSON.stringify({ name: `bench-${stamp}-${i}`, email: `bench-${stamp}-${i}@alook.test`, password: process.env.BENCHMARK_PASSWORD }),+ signal: AbortSignal.timeout(30000), redirect: 'error',+ })+ if (!response.ok) throw new Error(`Account creation ${i} failed (${response.status}); partial fixture retained`)+ const data = await response.json()+ const cookie = response.headers.getSetCookie().map(value => value.split(';')[0]).filter(value => !value.startsWith('is_new_signup=')).join('; ')+ if (!cookie || !data.user?.id) throw new Error('Sign-up did not return an authenticated fixture')+ accounts.push({ userId: data.user.id, cookie })+ await writeFile(output, JSON.stringify({ accounts }, null, 2), { mode: 0o600 })+ }+ console.log(JSON.stringify({ accounts: accounts.length, fixture: output }))+ } else if (command === 'adapter') {+ if (!path || !third) throw new Error('adapter requires target Worker entry and generated output path')+ await generateAdapter(path, third)+ console.log('Generated test-only Worker entry; run it with the target runtime/configuration.')+ } else if (command === 'report') {+ const metadata = JSON.parse(await readFile(`${path}/metadata.json`, 'utf8'))+ const isBrowser = metadata.kind === 'browser-user-operation'+ const samples = (await readFile(`${path}/${isBrowser ? 'operations' : 'samples'}.jsonl`, 'utf8')).trim().split('\n').filter(Boolean).map(line => JSON.parse(line))+ const telemetry = []+ const ownedIds = new Set(samples.flatMap(sample => isBrowser ? sample.requests.map(r => r.id) : [sample.requestId, sample.history?.requestId].filter(Boolean)))+ if (third) {+ for (const line of (await readFile(third, 'utf8')).split('\n')) {+ const start = line.indexOf('{')+ if (start < 0) continue+ try {+ const event = JSON.parse(line.slice(start))+ if (event.benchmark === 1 && ownedIds.has(event.requestId) && ['d1', 'request-start', 'response', 'request-complete'].includes(event.kind)) telemetry.push(event)+ } catch {}+ }+ }+ const report = (isBrowser ? browserSummary : summarize)(samples, metadata, telemetry)+ await writeFile(`${path}/db.jsonl`, telemetry.map(event => JSON.stringify(event)).join('\n') + '\n')+ await writeFile(`${path}/summary.json`, JSON.stringify(report, null, 2))+ await writeFile(`${path}/summary.md`, (isBrowser ? browserMarkdown : markdown)(report))+ console.log(JSON.stringify({ db: report.db.status, calls: report.db.executionCalls, completed: report.db.completedRequests, expected: report.db.expectedRequests }))+ } else {+ console.log('Usage: node src/cli.mjs run CONFIG | calibrate CONFIG | compare BASE_ARTIFACT_DIR HEAD_ARTIFACT_DIR | setup CONFIG | accounts LOCAL_URL FIXTURE_FILE [COUNT] | adapter TARGET_ENTRY OUTPUT | report ARTIFACT_DIR [WORKER_LOG_JSONL]')+ if (command && command !== 'help' && command !== '--help') process.exitCode = 1+ }+}++main(process.argv.slice(2)).then(() => { process.exit(process.exitCode ?? 0) }, error => { console.error(error.message); process.exit(1) })diff --git a/src/benchmark/src/client.mjs b/src/benchmark/src/client.mjsnew file mode 100644index 000000000..e81854fe5--- /dev/null+++ b/src/benchmark/src/client.mjs@@ -0,0 +1,109 @@+import { setTimeout as sleep } from 'node:timers/promises'+import { randomUUID } from 'node:crypto'++export async function api(baseUrl, account, path, { method = 'GET', body, timeoutMs = 15000, requestId } = {}) {+ const encoded = body === undefined ? undefined : JSON.stringify(body)+ const started = performance.now()+ const response = await fetch(new URL(path, baseUrl), {+ method, redirect: 'error', headers: { Cookie: account.cookie, Origin: new URL(baseUrl).origin,+ 'Content-Type': 'application/json', ...(requestId ? { 'x-alook-benchmark-id': requestId } : {}) },+ body: encoded, signal: AbortSignal.timeout(timeoutMs),+ })+ const bytes = Buffer.from(await response.arrayBuffer())+ const wallMs = performance.now() - started+ let data = null+ let parseError = false+ try { data = JSON.parse(bytes.toString('utf8')) } catch { parseError = true }+ return { status: response.status, ok: response.ok, data, parseError, wallMs,+ requestBodyBytes: encoded === undefined ? 0 : Buffer.byteLength(encoded), responseBodyBytes: bytes.byteLength }+}++async function checked(baseUrl, account, path, options) {+ const result = await api(baseUrl, account, path, options)+ if (!result.ok || result.parseError) throw new Error(`Fixture API failed: ${options?.method ?? 'GET'} ${path} (${result.status})`)+ return result.data+}++export async function prepareFixture(config, create = false) {+ const { fixture, baseUrl } = config+ if (!Array.isArray(fixture.accounts) || fixture.accounts.some(a => typeof a.cookie !== 'string' || !a.cookie || typeof a.userId !== 'string' || !a.userId)) throw new Error('Fixture requires accounts with cookie and userId')+ if (new Set(fixture.accounts.map(a => a.userId)).size !== fixture.accounts.length) throw new Error('Fixture accounts must be distinct')+ for (const [key, min, max] of [['receivers', 1, 1000], ['expectedMembers', 2, 10000], ['historyLimit', 1, 100]]) if (!Number.isInteger(config[key]) || config[key] < min || config[key] > max) throw new Error(`Invalid ${key}`)+ if (!Array.isArray(config.payloadBytes) || !config.payloadBytes.length || config.payloadBytes.some(n => !Number.isInteger(n) || n < 1 || n > 100000)) throw new Error('Invalid payloadBytes')+ if (fixture.accounts.length <= config.receivers) throw new Error('Fixture requires a sender plus configured receivers')+ const sender = fixture.accounts[0]+ if (create) {+ if (fixture.accounts.length !== config.expectedMembers) throw new Error('Creation requires exactly expectedMembers fixture accounts')+ const server = await checked(baseUrl, sender, '/api/community/servers', { method: 'POST', body: { name: `benchmark-${randomUUID().slice(0, 8)}` } })+ fixture.serverId = server.server.id+ const invite = await checked(baseUrl, sender, `/api/community/servers/${fixture.serverId}/invites`, { method: 'POST', body: {} })+ for (const account of fixture.accounts.slice(1)) {+ await checked(baseUrl, account, `/api/community/invites/${invite.invite.token}/join`, { method: 'POST' })+ await sleep(config.intervalMs)+ }+ const channel = await checked(baseUrl, sender, '/api/community/channels', { method: 'POST', body: { serverId: fixture.serverId, name: 'benchmark', type: 'text' } })+ fixture.channelId = channel.channel.id+ }+ if (!fixture.serverId || !fixture.channelId) throw new Error('Fixture needs serverId/channelId; run setup first')+ const channel = await checked(baseUrl, sender, `/api/community/channels/${fixture.channelId}`)+ if (channel.serverId !== fixture.serverId || channel.type !== 'text' || channel.parentChannelId || channel.categoryId) throw new Error('First version requires a top-level text channel in the configured server')+ const audience = await checked(baseUrl, sender, `/api/community/channels/${fixture.channelId}/members`)+ const visible = new Set(audience.members?.map(member => member.userId))+ const members = new Set()+ let cursor+ const seen = new Set()+ do {+ const path = `/api/community/servers/${fixture.serverId}/members?limit=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`+ const page = await checked(baseUrl, sender, path)+ if (!Array.isArray(page.members)) throw new Error('Invalid member page')+ for (const member of page.members) members.add(member.userId)+ cursor = page.hasMore ? page.cursor : undefined+ if (page.hasMore && (!cursor || seen.has(cursor))) throw new Error('Invalid member pagination')+ seen.add(cursor)+ } while (cursor)+ if (visible.size !== config.expectedMembers || [...visible].some(id => !members.has(id))) throw new Error('Channel audience does not match the expected server audience')+ if (members.size !== config.expectedMembers) throw new Error(`Observed ${members.size} server members; expected ${config.expectedMembers}`)+ for (const account of fixture.accounts.slice(0, config.receivers + 1)) {+ if (!members.has(account.userId)) throw new Error('A measured account is not a server member')+ await checked(baseUrl, account, `/api/community/channels/${fixture.channelId}/messages?limit=1`)+ }+ return { serverMembers: members.size, visibleMembers: visible.size, channelType: channel.type, measuredReceivers: config.receivers, channelId: fixture.channelId, serverId: fixture.serverId }+}++export function messageEvents(frame) {+ const events = frame.type === 'community:events.batch' ? frame.events : [frame]+ if (!Array.isArray(events)) return []+ return events.filter(event => event?.type === 'community:message.create' && typeof event.message?.id === 'string')+}++export async function connectReceiver(config, account, index, onMessage) {+ const auth = await checked(config.baseUrl, account, '/api/ws/token')+ if (auth.userId !== account.userId) throw new Error('WS fixture identity mismatch')+ const url = config.wsUrl ?? `${config.baseUrl.replace(/^http/, 'ws')}/api/ws/user`+ const endpoint = new URL(url)+ endpoint.searchParams.set('userId', auth.userId)+ const socket = new WebSocket(endpoint)+ let ready = false+ let closed = false+ let protocolErrors = 0+ const handshake = new Promise((resolve, reject) => {+ const timeout = setTimeout(() => { reject(new Error('WS auth timeout')); socket.close() }, config.timeoutMs)+ socket.addEventListener('open', () => socket.send(JSON.stringify({ type: 'auth', token: auth.token })))+ socket.addEventListener('message', event => {+ const at = performance.now()+ if (event.data === 'pong') return+ if (typeof event.data !== 'string') { protocolErrors++; return }+ let frame+ try { frame = JSON.parse(event.data) } catch { protocolErrors++; return }+ if (frame.type === 'auth.ok') { ready = true; clearTimeout(timeout); resolve(); return }+ if (!ready) return+ for (const message of messageEvents(frame)) onMessage({ receiver: index, messageId: message.message.id,+ channelId: message.channelId, clientNonce: message.message.clientNonce, at, frameBytes: Buffer.byteLength(event.data) })+ })+ socket.addEventListener('error', () => { if (!ready) { clearTimeout(timeout); reject(new Error('WS connection failed')) } })+ socket.addEventListener('close', () => { closed = true; clearTimeout(timeout); if (!ready) reject(new Error('WS closed before authentication')) })+ })+ try { await handshake } catch (error) { socket.close(); throw error }+ const heartbeat = setInterval(() => { if (socket.readyState === WebSocket.OPEN) socket.send('ping') }, 20000)+ return { state: () => ({ ready, closed, protocolErrors }), close: () => { clearInterval(heartbeat); socket.close() } }+}diff --git a/src/benchmark/src/compare.mjs b/src/benchmark/src/compare.mjsnew file mode 100644index 000000000..68b43da8c--- /dev/null+++ b/src/benchmark/src/compare.mjs@@ -0,0 +1,32 @@+const canonical = value => JSON.stringify(value, (_, item) => item && !Array.isArray(item) && typeof item === 'object' ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)++export function compareReports(base, head) {+ if (!base.finishedAt || !head.finishedAt) throw new Error('Incomplete runs cannot be compared')+ if ([base, head].some(report => report.db?.missingD1Events > 0)) throw new Error('Incomplete D1 logs: declared execution events are missing; cost comparison refused')+ const contract = report => ({ kind: report.kind, schemaVersion: report.schemaVersion, case: report.case, workloads: report.workloads, participants: report.participants, config: Object.fromEntries(Object.entries(report.config).filter(([key]) => !['targetVersion', 'baseUrl'].includes(key))), runner: report.runner, fixture: Object.fromEntries(Object.entries(report.fixture).filter(([key]) => !['serverId', 'channelId'].includes(key))) })+ if (base.kind !== 'browser-user-operation' || base.schemaVersion !== 2 || canonical(contract(base)) !== canonical(contract(head))) throw new Error('Incompatible measurement modes, workload, fixture or runner environment')+ const compare = (a, b) => ({ base: a, head: b, delta: Number.isFinite(a) && Number.isFinite(b) ? b - a : null, percent: Number.isFinite(a) && Number.isFinite(b) && a !== 0 ? 100 * (b - a) / a : null })+ const groups = head.groups.map(h => {+ const b = base.groups.find(g => g.phase === h.phase && g.workloadId === h.workloadId)+ if (!b) throw new Error('Incompatible scenario groups')+ const metrics = {}+ for (const key of ['directAckMs', 'directRequestBodyBytes', 'directResponseBodyBytes', 'windowHttpResponseBodyBytes', 'windowWsApplicationBytes']) {+ for (const percentile of ['p50', 'p95']) metrics[`${key}.${percentile}`] = compare(b[key][percentile], h[key][percentile])+ }+ for (const name of Object.keys(head.case.metrics)) for (const percentile of ['p50', 'p95']) metrics[`case.${name}.${percentile}`] = compare(b.caseMetrics[name][percentile], h.caseMetrics[name][percentile])+ for (const { role } of head.participants) metrics[`pageTaskCpuMs.${role}.p50`] = compare(b.pageTaskCpuMs[role].p50, h.pageTaskCpuMs[role].p50)+ for (const scope of ['directRequests', 'otherWindowRequests']) for (const key of ['executionCalls', 'submittedStatements']) metrics[`db.${scope}.${key}`] = compare(b.db[scope][key], h.db[scope][key])+ for (const scope of ['directRequests', 'otherWindowRequests']) for (const key of ['rowsRead', 'rowsWritten', 'sqlBytes', 'parameterJsonBytes', 'resultJsonBytes']) {+ const a = b.db[scope][key], z = h.db[scope][key]+ metrics[`db.${scope}.${key}.knownTotal`] = { ...compare(a.total, z.total), baseCoverage: a.coverage, headCoverage: z.coverage,+ attribution: a.coverage === z.coverage ? (a.coverage === 1 ? 'observed scope total' : 'known partial only') : 'coverage differs; cannot infer overall cost change' }+ metrics[`db.${scope}.${key}.coverage`] = compare(a.coverage, z.coverage)+ }+ return { phase: h.phase, workloadId: h.workloadId, workloadLabel: h.workloadLabel, attempted: compare(b.attempted, h.attempted), failed: compare(b.failed, h.failed), metrics }+ })+ return { baseVersion: base.config.targetVersion, headVersion: head.config.targetVersion, sameVersionControl: base.config.targetVersion === head.config.targetVersion, groups }+}++export function comparisonMarkdown(report) {+ return `# Browser benchmark comparison\n\n${report.baseVersion} → ${report.headVersion}${report.sameVersionControl ? '; same-version repeatability control, not feature improvement evidence' : ''}. Negative latency/byte deltas mean less observed cost. Unknown remains unknown.\n\n| Phase/workload | Metric | Base | Head | Delta | Change % | Coverage/interpretation |\n|---|---|---:|---:|---:|---:|---|\n${report.groups.flatMap(g => Object.entries({ attempted: g.attempted, failed: g.failed, ...g.metrics }).map(([key, values]) => `| ${g.phase}/${g.workloadLabel} | ${key} | ${['base', 'head', 'delta', 'percent'].map(k => values[k]?.toFixed(2) ?? 'unknown').join(' | ')} | ${values.attribution ? `${values.baseCoverage ?? 'unknown'} → ${values.headCoverage ?? 'unknown'}; ${values.attribution}` : ''} |`)).join('\n')}\n`+}diff --git a/src/benchmark/src/config.mjs b/src/benchmark/src/config.mjsnew file mode 100644index 000000000..3270841d2--- /dev/null+++ b/src/benchmark/src/config.mjs@@ -0,0 +1,35 @@+import { readFile } from 'node:fs/promises'+import { resolve, dirname } from 'node:path'++export async function loadConfig(path) {+ const source = JSON.parse(await readFile(path, 'utf8'))+ const config = {+ case: 'channel-message-send', observeDB: false, observationWindowMs: 1800, samples: 100, warmup: 5, concurrency: 1, timeoutMs: 15000, intervalMs: 400,+ payloadBytes: [64, 1024], receivers: 1, expectedMembers: 100, historyLimit: 20,+ phases: [{ name: 'baseline', delayMs: 0 }, { name: 'request-delay', delayMs: 1000 }],+ ...source,+ }+ const url = new URL(config.baseUrl)+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== '/') throw new Error('baseUrl must be a credential-free HTTP(S) origin')+ if (!['local', 'staging'].includes(config.targetKind)) throw new Error('targetKind must explicitly name local or staging')+ if (!config.targetVersion || !config.environment) throw new Error('Record targetVersion and environment')+ for (const [key, min, max] of [['samples', 1, 100000], ['warmup', 0, 10000], ['concurrency', 1, 100], ['timeoutMs', 100, 120000], ['intervalMs', 0, 60000], ['observationWindowMs', 100, 120000]]) {+ if (!Number.isInteger(config[key]) || config[key] < min || config[key] > max) throw new Error(`Invalid ${key}`)+ }+ if (!Array.isArray(config.phases) || !config.phases.length || new Set(config.phases.map(p => p.name)).size !== config.phases.length || config.phases.some(p => !/^[a-z0-9_-]+$/.test(p.name) || p.phase !== undefined || !Number.isInteger(p.delayMs) || p.delayMs < 0 || p.delayMs > 60000 || p.delayMs >= config.timeoutMs)) throw new Error('Invalid phases')+ if (config.headless !== undefined && typeof config.headless !== 'boolean') throw new Error('headless must be boolean')+ if (config.viewport && (!Number.isInteger(config.viewport.width) || !Number.isInteger(config.viewport.height) || config.viewport.width < 320 || config.viewport.height < 320)) throw new Error('Invalid viewport')+ if (typeof config.observeDB !== 'boolean') throw new Error('observeDB must be boolean')+ if (config.wsUrl) {+ const ws = new URL(config.wsUrl)+ if (!['ws:', 'wss:'].includes(ws.protocol) || ws.username || ws.password || ws.hash || ws.search) throw new Error('wsUrl must be a credential-free WS endpoint without query parameters')+ }+ config.fixture = config.fixtureFile ? JSON.parse(await readFile(resolve(dirname(path), config.fixtureFile), 'utf8')) : {}+ config.baseUrl = url.origin+ config.outDir = resolve(dirname(path), config.outDir ?? 'artifacts/latest')+ return config+}++export function publicConfig(config) {+ return Object.fromEntries(['case', 'observeDB', 'baseUrl', 'targetKind', 'targetVersion', 'environment', 'samples', 'warmup', 'concurrency', 'timeoutMs', 'intervalMs', 'payloadBytes', 'receivers', 'expectedMembers', 'historyLimit', 'phases'].map(key => [key, config[key]]))+}diff --git a/src/benchmark/src/d1-observer.mjs b/src/benchmark/src/d1-observer.mjsnew file mode 100644index 000000000..c7ed1f273--- /dev/null+++ b/src/benchmark/src/d1-observer.mjs@@ -0,0 +1,79 @@+function encodeBinary(bytes) {+ let binary = ''+ for (const byte of bytes) binary += String.fromCharCode(byte)+ return btoa(binary)+}++export function jsonBytes(value) {+ try { return new TextEncoder().encode(JSON.stringify(value, (_key, item) => item instanceof ArrayBuffer ? { binaryBase64: encodeBinary(new Uint8Array(item)) } : ArrayBuffer.isView(item) ? { binaryBase64: encodeBinary(new Uint8Array(item.buffer, item.byteOffset, item.byteLength)) } : item)).byteLength } catch { return null }+}++function numeric(value) {+ return typeof value === 'number' && Number.isFinite(value) ? value : null+}++export function observeD1(database, emit, clock = () => performance.now(), phase = () => false) {+ const originals = new WeakMap()+ let operation = 0+ function statement(target, sqlBytes, parameterBytes = 0) {+ const wrapped = new Proxy(target, {+ get(object, key) {+ if (key === 'bind') return (...values) => statement(object.bind(...values), sqlBytes, jsonBytes(values))+ if (['all', 'run', 'raw', 'first'].includes(key)) {+ return (...args) => execute(key, 1, sqlBytes, parameterBytes, () => object[key](...args))+ }+ const value = Reflect.get(object, key, object)+ return typeof value === 'function' ? value.bind(object) : value+ },+ })+ originals.set(wrapped, { target, sqlBytes, parameterBytes })+ return wrapped+ }+ async function execute(method, statements, sqlBytes, parameterBytes, run) {+ const id = ++operation+ const started = clock()+ const startedAfterResponse = phase()+ let result+ let ok = false+ try {+ result = await run()+ ok = true+ return result+ } finally {+ const elapsed = clock() - started+ const results = method === 'batch' ? (Array.isArray(result) ? result : []) : [result]+ const metadata = results.map(value => {+ const meta = ['all', 'run', 'batch'].includes(method) && value && !Array.isArray(value) ? value.meta : undefined+ return {+ sqlDurationMs: numeric(meta?.timings?.sql_duration_ms ?? meta?.duration),+ internalAttempts: numeric(meta?.total_attempts), rowsRead: numeric(meta?.rows_read), rowsWritten: numeric(meta?.rows_written),+ }+ })+ try {+ emit({ kind: 'd1', operation: id, method, statements, reportedExecCount: method === 'exec' && ok ? numeric(result?.count) : null, ok, startedMs: started, startedAfterResponse, completedAfterResponse: phase(),+ wallMs: elapsed, sqlBytes, parameterJsonBytes: parameterBytes,+ resultJsonBytes: result === undefined ? null : jsonBytes(result), metadata })+ } catch {}+ }+ }+ function binding(target) {+ return new Proxy(target, {+ get(object, key) {+ if (key === 'prepare') return sql => statement(object.prepare(sql), new TextEncoder().encode(sql).byteLength)+ if (key === 'withSession') return (...args) => binding(object.withSession(...args))+ if (key === 'batch') return statements => {+ const entries = statements.map(item => originals.get(item))+ if (entries.some(item => !item)) throw new Error('D1 batch contains a statement outside this observer')+ return execute('batch', statements.length,+ entries.reduce((sum, item) => sum + item.sqlBytes, 0),+ entries.some(item => item.parameterBytes === null) ? null : entries.reduce((sum, item) => sum + item.parameterBytes, 0),+ () => object.batch(entries.map(item => item.target)))+ }+ if (key === 'exec') return sql => execute('exec', null, new TextEncoder().encode(sql).byteLength, 0, () => object.exec(sql))+ const value = Reflect.get(object, key, object)+ return typeof value === 'function' ? value.bind(object) : value+ },+ })+ }+ return binding(database)+}diff --git a/src/benchmark/src/proxy.mjs b/src/benchmark/src/proxy.mjsnew file mode 100644index 000000000..bc4ffe0f6--- /dev/null+++ b/src/benchmark/src/proxy.mjs@@ -0,0 +1,37 @@+import http from 'node:http'+import https from 'node:https'+import { setTimeout as sleep } from 'node:timers/promises'++export async function startProxy({ upstream, delayMs = 0, port = 0, emit = () => {} }) {+ const target = new URL(upstream)+ if (!['http:', 'https:'].includes(target.protocol)) throw new Error('Proxy requires an HTTP(S) upstream')+ if (!Number.isInteger(delayMs) || delayMs < 0 || delayMs > 60000) throw new Error('Invalid delay configuration')+ const server = http.createServer(async (request, response) => {+ const selected = request.method === 'POST' && /^\/api\/community\/channels\/[^/]+\/messages(?:\?|$)/.test(request.url)+ const requestId = request.headers['x-alook-benchmark-id']+ const inject = async () => {+ const started = performance.now()+ await sleep(delayMs)+ emit({ kind: 'injection', requestId, configuredMs: delayMs, actualMs: performance.now() - started })+ }+ if (selected) await inject()+ if (response.destroyed) return+ const transport = target.protocol === 'https:' ? https : http+ const forwarded = transport.request(new URL(request.url, target), {+ method: request.method, headers: { ...request.headers, host: target.host, origin: target.origin },+ }, incoming => {+ if (response.destroyed) { incoming.destroy(); return }+ response.writeHead(incoming.statusCode, incoming.headers)+ incoming.pipe(response)+ incoming.on('error', () => response.destroy())+ })+ forwarded.on('error', () => {+ if (!response.headersSent) response.writeHead(502)+ response.end()+ })+ response.on('close', () => forwarded.destroy())+ request.pipe(forwarded)+ })+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve) })+ return { url: `http://127.0.0.1:${server.address().port}`, close: () => new Promise(resolve => { server.close(resolve); server.closeAllConnections() }) }+}diff --git a/src/benchmark/src/report.mjs b/src/benchmark/src/report.mjsnew file mode 100644index 000000000..034aedb92--- /dev/null+++ b/src/benchmark/src/report.mjs@@ -0,0 +1,110 @@+export function distribution(values) {+ const sorted = values.filter(Number.isFinite).sort((a, b) => a - b)+ const percentile = p => sorted.length ? sorted[Math.max(0, Math.ceil(p * sorted.length) - 1)] : null+ return { n: sorted.length, p50: percentile(.5), p95: percentile(.95), p99: percentile(.99), min: sorted[0] ?? null, max: sorted.at(-1) ?? null }+}++export function summarize(samples, metadata, telemetry = []) {+ const measured = samples.filter(s => !s.warmup)+ const groups = []+ for (const phase of metadata.config.phases) {+ for (const payloadBytes of metadata.config.payloadBytes) {+ const selected = measured.filter(s => s.phase === phase.name && s.payloadBytes === payloadBytes)+ if (!selected.length) continue+ const received = selected.flatMap(s => s.receivers)+ const elapsedMs = Math.max(...selected.map(s => s.finishedMs)) - Math.min(...selected.map(s => s.startedMs))+ groups.push({ phase: phase.name, payloadBytes, attempted: selected.length,+ acknowledged: selected.filter(s => s.messageId && s.status >= 200 && s.status < 300 && !s.parseError && !s.error).length,+ failed: selected.filter(s => s.error).length, expectedDeliveries: received.length,+ delivered: received.filter(r => r.receiveMs !== null).length,+ timedOut: received.filter(r => r.receiveMs === null && r.outcome !== 'unresolved').length,+ unresolved: received.filter(r => r.outcome === 'unresolved').length, late: received.reduce((sum, r) => sum + (r.late ?? 0), 0),+ duplicates: received.reduce((sum, r) => sum + r.duplicates, 0),+ sendAckMs: distribution(selected.filter(s => !s.error && s.messageId).map(s => s.ackMs)),+ failedHttpResponseMs: distribution(selected.filter(s => s.error).map(s => s.ackMs)), receiveMs: distribution(received.map(r => r.receiveMs)),+ historyMs: distribution(selected.filter(s => s.history?.ok).map(s => s.history.wallMs)),+ historyFailed: selected.filter(s => s.history && !s.history.ok).length,+ workflowThroughputPerSecond: selected.length / (elapsedMs / 1000), elapsedMs,+ requestBodyBytes: distribution(selected.map(s => s.requestBodyBytes)),+ responseBodyBytes: distribution(selected.map(s => s.responseBodyBytes)),+ wsApplicationBytes: distribution(received.map(r => r.frameBytes)),+ smallSampleWarning: selected.length < 1000 ? 'p99 is exploratory; fewer than 1000 attempts' : null })+ }+ }+ const { events, duplicateTelemetryRecords } = deduplicateTelemetry(telemetry)+ const requestIds = selected => selected.flatMap(s => [s.requestId, ...(s.history ? [s.history.requestId] : [])])+ const db = { ...dbMetrics(requestIds(measured), events), duplicateTelemetryRecords, groups: [] }+ for (const group of groups) {+ const selected = measured.filter(s => s.phase === group.phase && s.payloadBytes === group.payloadBytes)+ db.groups.push({ phase: group.phase, payloadBytes: group.payloadBytes,+ send: dbMetrics(selected.map(s => s.requestId), events),+ history: dbMetrics(selected.flatMap(s => s.history ? [s.history.requestId] : []), events) })+ }+ return { ...metadata, warning: 'DB coverage is incomplete. UI render and physical/network wire bytes are not measured.',+ percentileMethod: 'nearest rank over available observations; missing deliveries remain in failure counts', db, groups }+}++export function markdown(report) {+ const latency = report.groups.map(g => `| ${g.phase} | ${g.payloadBytes} | ${g.attempted} | ${g.failed} | ${format(g.sendAckMs)} | ${format(g.receiveMs)} | ${g.timedOut}/${g.unresolved} | ${g.historyMs.p95?.toFixed(2) ?? 'unknown'} |`).join('\n')+ const bytes = report.groups.map(g => `| ${g.phase} | ${g.payloadBytes} | ${format(g.requestBodyBytes)} | ${format(g.responseBodyBytes)} | ${format(g.wsApplicationBytes)} |`).join('\n')+ const cost = report.db.groups.flatMap(g => ['send', 'history'].map(kind => {+ const d = g[kind]+ return `| ${g.phase}/${g.payloadBytes}/${kind} | ${d.executionCalls ?? 'unknown'}/${d.submittedStatements ?? 'unknown'} | ${covered(d.rowsRead)} | ${covered(d.rowsWritten)} | ${d.sqlBytes.total ?? 'unknown'}/${d.parameterJsonBytes.total ?? 'unknown'}/${d.resultJsonBytes.total ?? 'unknown'} | ${d.completedRequests}/${d.expectedRequests} |`+ })).join('\n')+ return `# Message benchmark\n\n${report.warning}\n\nTarget: ${report.config.baseUrl}; version: ${report.config.targetVersion}. Observer requested: ${report.config.observeDB}.\nServer members: ${report.fixture.serverMembers}; visible channel members: ${report.fixture.visibleMembers}; connected receiving accounts: ${report.fixture.measuredReceivers}.\n\n| Phase | Content B | Attempts | Send failures | ACK p50/p95/p99 ms | WS p50/p95/p99 ms | Missing/unresolved WS | History p95 ms |\n|---|---:|---:|---:|---|---|---|---:|\n${latency}\n\nApplication payload bytes (p50/p95/p99):\n\n| Phase | Content B | HTTP request B | HTTP response B | WS application B |\n|---|---:|---|---|---|\n${bytes}\n\nDB observations (known row totals with metadata coverage; these are incomplete costs):\n\n| Phase/content B/API | Calls/submitted statements | Known rows read (coverage) | Known rows written (coverage) | Logical SQL/params/result B totals | Web completions |\n|---|---:|---|---|---|---|\n${cost}\n\nDB status: ${report.db.status}; completed observed web requests: ${report.db.completedRequests}/${report.db.expectedRequests}. ${report.db.coverage}.\n\nACK percentiles include successful sends only; failed HTTP response timings remain separate in JSON. HTTP bytes are decoded response/application request bodies. WS bytes exclude protocol framing. DB byte fields are logical JSON encodings, not physical I/O. Throughput is closed-loop workflow attempts per second, including WS wait, history reads and configured pacing; injected runs have a lower offered load. Warmups excluded. Each group below 1000 attempts has an exploratory p99. See summary.json and raw JSONL for per-receiver outcomes, duplicate/late frames, injection waits, exact configuration, and DB byte/duration distributions.\n`+}++function covered(metric) { return `${metric.total ?? 'unknown'} (${metric.coverage === null ? 'unknown' : (100 * metric.coverage).toFixed(1) + '%'})` }++function format(d) { return [d.p50, d.p95, d.p99].map(n => n?.toFixed(2) ?? 'unknown').join('/') }++export function dbMetrics(ids, events) {+ const expected = new Set(ids)+ const selected = events.filter(e => expected.has(e.requestId))+ const calls = selected.filter(e => e.kind === 'd1')+ const completions = selected.filter(e => e.kind === 'request-complete')+ const completed = new Set(completions.map(e => e.requestId))+ const missingD1Events = completions.length && completions.every(event => Number.isInteger(event.d1Calls)) ? completions.reduce((sum, event) => sum + Math.max(0, event.d1Calls - calls.filter(call => call.requestId === event.requestId).length), 0) : null+ const observedEmpty = expected.size > 0 && completed.size === expected.size && calls.length === 0 && completions.every(event => event.d1Calls === 0)+ const metadata = calls.flatMap(c => c.metadata)+ const statementCount = calls.some(c => c.statements === null) ? null : calls.reduce((sum, c) => sum + c.statements, 0)+ const metric = (values, expectedCount) => {+ const known = values.filter(Number.isFinite)+ return { total: known.length ? known.reduce((a, b) => a + b, 0) : observedEmpty ? 0 : null,+ distribution: distribution(known), observed: known.length, expected: missingD1Events > 0 ? null : expectedCount,+ coverage: missingD1Events > 0 ? null : expectedCount > 0 ? known.length / expectedCount : null }+ }+ const rowsRead = metric(metadata.map(m => m.rowsRead), statementCount)+ const rowsWritten = metric(metadata.map(m => m.rowsWritten), statementCount)+ const sqlDuration = metric(metadata.map(m => m.sqlDurationMs), statementCount)+ return {+ coverage: 'web env.DB invocation only; WS DO and queue consumers not observed; raw/first metadata unavailable',+ status: calls.length ? 'partial' : observedEmpty ? 'observed-empty' : 'unavailable', expectedRequests: expected.size, completedRequests: completed.size,+ missingD1Events,+ requestsWithoutCompletion: [...expected].filter(id => !completed.has(id)).length,+ executionCalls: calls.length || (observedEmpty ? 0 : null), submittedStatements: calls.length || observedEmpty ? statementCount : null,+ failedCalls: calls.length || observedEmpty ? calls.filter(c => !c.ok).length : null,+ failedBackgroundTasks: completions.reduce((sum, c) => sum + c.failedTasks, 0),+ callWallMs: distribution(calls.map(c => c.wallMs)),+ rowsRead, rowsWritten, sqlDuration, knownRowsRead: rowsRead.total, knownRowsWritten: rowsWritten.total, knownSqlDurationMs: sqlDuration.total,+ sqlBytes: metric(calls.map(c => c.sqlBytes), calls.length), parameterJsonBytes: metric(calls.map(c => c.parameterJsonBytes), calls.length),+ resultJsonBytes: metric(calls.map(c => c.resultJsonBytes), calls.length),+ internalAttempts: metric(metadata.map(m => m.internalAttempts), statementCount),+ backgroundCallsStarted: calls.filter(c => c.startedAfterResponse).length,+ callsCrossingResponse: calls.filter(c => !c.startedAfterResponse && c.completedAfterResponse).length,+ }+}++export function deduplicateTelemetry(telemetry) {+ const deduplicated = new Map()+ let duplicateTelemetryRecords = 0+ for (const event of telemetry.filter(e => e.benchmark === 1)) {+ const key = `${event.requestId}:${event.kind}:${event.operation ?? ''}`+ if (deduplicated.has(key)) {+ if (JSON.stringify(deduplicated.get(key)) !== JSON.stringify(event)) throw new Error('Conflicting telemetry record')+ duplicateTelemetryRecords+++ } else deduplicated.set(key, event)+ }+ const events = [...deduplicated.values()]+ return { events, duplicateTelemetryRecords }+}diff --git a/src/benchmark/src/runner.mjs b/src/benchmark/src/runner.mjsnew file mode 100644index 000000000..e5c403e1d--- /dev/null+++ b/src/benchmark/src/runner.mjs@@ -0,0 +1,125 @@+import { mkdir, writeFile, appendFile } from 'node:fs/promises'+import { randomUUID } from 'node:crypto'+import { setTimeout as sleep } from 'node:timers/promises'+import os from 'node:os'+import { api, prepareFixture, connectReceiver } from './client.mjs'+import { startProxy } from './proxy.mjs'+import { publicConfig } from './config.mjs'+import { summarize, markdown } from './report.mjs'++export async function runBenchmark(config) {+ const fixture = await prepareFixture(config)+ await mkdir(config.outDir, { recursive: true })+ const runId = randomUUID()+ const metadata = { runId, startedAt: new Date().toISOString(), config: publicConfig(config), fixture,+ runner: { node: process.version, platform: process.platform, arch: process.arch, cpus: os.cpus().length },+ adapterVersion: '1', workload: 'public-text send + authenticated WS receive + first-page history GET' }+ await writeFile(`${config.outDir}/metadata.json`, JSON.stringify(metadata, null, 2))+ await writeFile(`${config.outDir}/samples.jsonl`, '')+ await writeFile(`${config.outDir}/injections.jsonl`, '')+ const arrivals = new Map()+ const nonceIds = new Map()+ const sockets = []+ const samples = []+ const injections = []+ let proxy+ let index = 0+ try {+ for (let receiver = 0; receiver < config.receivers; receiver++) {+ sockets.push(await connectReceiver(config, config.fixture.accounts[receiver + 1], receiver, event => {+ if (event.channelId !== fixture.channelId) return+ if (event.clientNonce) nonceIds.set(event.clientNonce, event.messageId)+ const key = `${event.messageId}:${event.receiver}`+ const events = arrivals.get(key) ?? []+ events.push(event)+ arrivals.set(key, events)+ }))+ }+ for (const phase of config.phases) {+ proxy = await startProxy({ upstream: config.baseUrl, ...phase, emit: event => injections.push(event) })+ for (const payloadBytes of config.payloadBytes) {+ for (const warmup of [true, false]) {+ let remaining = warmup ? config.warmup : config.samples+ await Promise.all(Array.from({ length: config.concurrency }, async () => {+ while (remaining-- > 0) {+ const requestId = `${runId}-${index++}`+ const startedMs = performance.now()+ const sample = { requestId, phase: phase.name, payloadBytes, warmup, startedMs,+ status: null, ackMs: null, messageId: null, error: null, parseError: false,+ requestBodyBytes: Buffer.byteLength(JSON.stringify({ content: 'x'.repeat(payloadBytes), nonce: requestId })), responseBodyBytes: null }+ try {+ if (sockets.some(s => s.state().closed)) throw new Error('receiver-disconnected')+ const sent = await api(proxy.url, config.fixture.accounts[0], `/api/community/channels/${fixture.channelId}/messages`, {+ method: 'POST', body: { content: 'x'.repeat(payloadBytes), nonce: requestId }, timeoutMs: config.timeoutMs, requestId: config.observeDB ? requestId : undefined,+ })+ Object.assign(sample, { status: sent.status, ackMs: sent.wallMs, parseError: sent.parseError,+ requestBodyBytes: sent.requestBodyBytes, responseBodyBytes: sent.responseBodyBytes,+ messageId: typeof sent.data?.message?.id === 'string' ? sent.data.message.id : null })+ if (!sent.ok || !sample.messageId) sample.error = sent.parseError ? 'invalid-json' : 'send-failed'+ } catch (error) { sample.error = error.name === 'TimeoutError' ? 'send-timeout' : 'send-transport-or-receiver-error' }+ sample.correlation = sample.messageId ? 'http-message-id' : nonceIds.has(requestId) ? 'ws-client-nonce' : 'unresolved'+ sample.messageId ??= nonceIds.get(requestId) ?? null+ if (sample.messageId) {+ while (performance.now() - startedMs < config.timeoutMs) {+ if (sockets.every((_, receiver) => arrivals.has(`${sample.messageId}:${receiver}`))) break+ await sleep(10)+ }+ }+ const deadline = startedMs + config.timeoutMs+ sample.receivers = sockets.map((_, receiver) => {+ const events = arrivals.get(`${sample.messageId}:${receiver}`) ?? []+ const accepted = events.filter(e => e.at >= startedMs && e.at <= deadline)+ return { receiver, receiveMs: accepted.length ? accepted[0].at - startedMs : null,+ frameBytes: accepted[0]?.frameBytes ?? null, duplicates: Math.max(0, accepted.length - 1), late: events.filter(e => e.at > deadline).length }+ })+ if (sample.messageId) {+ const historyId = `${requestId}-h`+ try {+ const history = await api(proxy.url, config.fixture.accounts[1], `/api/community/channels/${fixture.channelId}/messages?limit=${config.historyLimit}`, { requestId: config.observeDB ? historyId : undefined, timeoutMs: config.timeoutMs })+ sample.history = { requestId: historyId, ok: history.ok && !history.parseError && Array.isArray(history.data?.messages),+ status: history.status, wallMs: history.wallMs, responseBodyBytes: history.responseBodyBytes,+ returnedMessages: Array.isArray(history.data?.messages) ? history.data.messages.length : null,+ containsSentMessage: history.data?.messages?.some(m => m.id === sample.messageId) ?? false, limit: config.historyLimit }+ } catch { sample.history = { requestId: historyId, ok: false, status: null, wallMs: null } }+ }+ sample.finishedMs = performance.now()+ sample.observationDeadlineMs = deadline+ samples.push(sample)+ await appendFile(`${config.outDir}/samples.jsonl`, `${JSON.stringify(sample)}\n`)+ if (config.intervalMs) await sleep(config.intervalMs)+ }+ }))+ }+ }+ await proxy.close()+ proxy = undefined+ }+ } finally {+ sockets.forEach(socket => socket.close())+ await proxy?.close()+ await writeFile(`${config.outDir}/injections.jsonl`, injections.map(e => JSON.stringify(e)).join('\n') + '\n')+ }+ const observationClosedMs = performance.now()+ for (const sample of samples) {+ sample.messageId ??= nonceIds.get(sample.requestId) ?? null+ if (sample.correlation === 'unresolved' && sample.messageId) sample.correlation = 'ws-client-nonce'+ sample.observationClosedMs = observationClosedMs+ sample.receivers = sockets.map((_, receiver) => {+ const events = arrivals.get(`${sample.messageId}:${receiver}`) ?? []+ const accepted = events.filter(e => e.at >= sample.startedMs && e.at <= sample.observationDeadlineMs)+ return { receiver, receiveMs: accepted.length ? accepted[0].at - sample.startedMs : null,+ frameBytes: accepted[0]?.frameBytes ?? null, duplicates: Math.max(0, accepted.length - 1),+ late: events.filter(e => e.at > sample.observationDeadlineMs).length,+ outcome: accepted.length ? 'delivered' : sample.messageId ? 'not-observed' : 'unresolved' }+ })+ }+ await writeFile(`${config.outDir}/samples.jsonl`, samples.map(s => JSON.stringify(s)).join('\n') + '\n')+ metadata.receiverStates = sockets.map(socket => socket.state())+ metadata.finishedAt = new Date().toISOString()+ metadata.observationClosedMs = observationClosedMs+ await writeFile(`${config.outDir}/metadata.json`, JSON.stringify(metadata, null, 2))+ const report = summarize(samples, metadata)+ await writeFile(`${config.outDir}/summary.json`, JSON.stringify(report, null, 2))+ await writeFile(`${config.outDir}/summary.md`, markdown(report))+ return report+}diff --git a/src/benchmark/src/worker-observer.mjs b/src/benchmark/src/worker-observer.mjsnew file mode 100644index 000000000..00bb4ef58--- /dev/null+++ b/src/benchmark/src/worker-observer.mjs@@ -0,0 +1,51 @@+import { observeD1 } from './d1-observer.mjs'++export function observeWorker(worker, emit = event => console.log(JSON.stringify(event))) {+ return {+ ...worker,+ async fetch(request, env, context) {+ const requestId = request.headers.get('x-alook-benchmark-id')+ if (!requestId || !/^[a-zA-Z0-9_-]{1,100}$/.test(requestId)) return worker.fetch(request, env, context)+ const started = performance.now()+ let responded = false+ let d1Calls = 0+ const tasks = []+ const write = event => {+ try { emit({ benchmark: 1, requestId, ...event }) } catch {}+ }+ const observedEnv = new Proxy(env, {+ get(target, key) { return key === 'DB' ? db : Reflect.get(target, key, target) },+ })+ const db = observeD1(env.DB, event => { d1Calls++; write({ ...event, startedMs: event.startedMs - started }) }, () => performance.now(), () => responded)+ const observedContext = new Proxy(context, {+ get(target, key) {+ if (key === 'waitUntil') return task => {+ const settled = Promise.resolve(task).then(() => true, () => false)+ tasks.push(settled)+ target.waitUntil(task)+ }+ const value = Reflect.get(target, key, target)+ return typeof value === 'function' ? value.bind(target) : value+ },+ })+ write({ kind: 'request-start' })+ try {+ const response = await worker.fetch(request, observedEnv, observedContext)+ write({ kind: 'response', status: response.status, wallMs: performance.now() - started })+ return response+ } finally {+ responded = true+ context.waitUntil((async () => {+ let consumed = 0+ let failedTasks = 0+ while (consumed < tasks.length) {+ const batch = tasks.slice(consumed)+ consumed += batch.length+ failedTasks += (await Promise.all(batch)).filter(ok => !ok).length+ }+ write({ kind: 'request-complete', backgroundTasks: consumed, failedTasks, d1Calls, wallMs: performance.now() - started })+ })())+ }+ },+ }+}diff --git a/src/benchmark/test/browser-probe.control.mjs b/src/benchmark/test/browser-probe.control.mjsnew file mode 100644index 000000000..9faeace51--- /dev/null+++ b/src/benchmark/test/browser-probe.control.mjs@@ -0,0 +1,30 @@+import assert from 'node:assert/strict'+import { chromium } from 'playwright'+import { installBrowserProbe } from '../src/browser-probe.mjs'+const browser = await chromium.launch()+try {+ const page = await browser.newPage()+ await page.setContent('<button id="send">Send</button><div id="rows"></div>')+ await page.evaluate(installBrowserProbe, { messageSelector: '[data-id]', submitSelector: '#send', idAttribute: 'data-id', optimisticPrefix: 'temp_' })+ await page.evaluate(() => window.__BENCHMARK_PROBE__.arm('unique'))+ await page.locator('#send').click()+ await page.evaluate(async () => {+ const rows = document.querySelector('#rows')+ rows.innerHTML = '<div data-id="temp_1">unique</div>'+ await Promise.resolve()+ rows.innerHTML = '<div data-id="canonical">unique</div>'+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))+ })+ const result = await page.evaluate(() => window.__BENCHMARK_PROBE__.freeze())+ assert.equal(result.messageId, 'canonical')+ assert.equal(result.isTrusted, true)+ assert.ok(result.nextFrameMs >= result.visibleMs)+ await page.evaluate(() => { document.querySelector('#rows').innerHTML = '<div data-id="later">unique</div>' })+ assert.equal(await page.evaluate(() => window.__BENCHMARK_PROBE__.snapshot()), null)+ await page.evaluate(() => {+ window.__BENCHMARK_PROBE__.arm('hidden')+ document.querySelector('#rows').innerHTML = '<div data-id="hidden" style="opacity:0">hidden</div><div data-id="offscreen" style="position:absolute;top:99999px">hidden</div>'+ })+ assert.equal((await page.evaluate(() => window.__BENCHMARK_PROBE__.snapshot())).visibleMs, null)+ console.log('Probe controls passed: trusted event, replacement before frame, freeze, hidden and offscreen rows')+} finally { await browser.close() }diff --git a/src/benchmark/test/browser-report.test.mjs b/src/benchmark/test/browser-report.test.mjsnew file mode 100644index 000000000..220eec04b--- /dev/null+++ b/src/benchmark/test/browser-report.test.mjs@@ -0,0 +1,53 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { browserSummary } from '../src/browser-report.mjs'+import { compareReports } from '../src/compare.mjs'++const metadata = { kind: 'browser-user-operation', schemaVersion: 2, finishedAt: '2026-09-13T00:00:00Z', case: { id: 'custom', version: 1, metrics: { customVisibleMs: { label: 'Custom visible', unit: 'ms', successOnly: true } } }, workloads: [{ id: 'custom-work', label: 'Custom work', params: { size: 64 } }], participants: [{ role: 0, name: 'page' }], config: { targetVersion: 'A', observeDB: false, phases: [{ name: 'baseline', delayMs: 0 }] }, fixture: {}, runner: { browser: 'control' } }+const sample = { id: 'operation', phase: 'baseline', workloadId: 'custom-work', submitNodeMs: 10, cutoffMs: 100, error: null, unfinishedRequestsAtCutoff: 1,+ result: { metrics: { customVisibleMs: 2 } }, socketCloses: [0], collectorErrors: [],+ requestsAtCutoff: [{ id: 'request', direct: true, observedDB: true, requestBodyBytes: 64, responseBodyBytes: null, status: 200, finishedMs: null }],+ requests: [{ id: 'request', direct: true, observedDB: true, requestBodyBytes: 64, responseBodyBytes: 400, status: 200, finishedMs: 150 }], framesAtCutoff: [],+ resources: [{ taskCpuMs: null, jsHeapBeforeBytes: null, jsHeapAfterBytes: null }] }++test('cutoff body remains unknown and unsuccessful attempts do not improve visible percentiles', () => {+ const report = browserSummary([sample, { ...sample, error: 'timeout', result: { metrics: { customVisibleMs: 1 } } }], metadata)+ assert.equal(report.groups[0].attempted, 2)+ assert.equal(report.groups[0].failed, 1)+ assert.equal(report.groups[0].caseMetrics.customVisibleMs.p50, 2)+ assert.equal(report.groups[0].directResponseBodyBytes.n, 0)+ assert.equal(report.groups[0].directAckMs.n, 0)+ assert.equal(report.groups[0].pageTaskCpuMs[0].p50, null)+})++test('browser telemetry deduplicates and rejects conflicting observations', () => {+ const event = { benchmark: 1, requestId: 'request', kind: 'd1', operation: 1, method: 'run', statements: 1, ok: true, metadata: [{ rowsRead: 1, rowsWritten: 1 }], sqlBytes: 20, parameterJsonBytes: 2, resultJsonBytes: 30 }+ const report = browserSummary([sample], metadata, [event, event])+ assert.equal(report.db.executionCalls, 1)+ assert.equal(report.duplicateTelemetryRecords, 1)+ assert.throws(() => browserSummary([sample], metadata, [event, { ...event, statements: 2 }]), /Conflicting/)+})++test('comparison accepts A/A, refuses observation/workload mismatch, and preserves unknown costs', () => {+ const a = browserSummary([sample], metadata)+ const b = structuredClone(a)+ assert.equal(compareReports(a, b).sameVersionControl, true)+ assert.equal(compareReports(a, b).groups[0].metrics['db.directRequests.rowsRead.knownTotal'].delta, null)+ b.db.missingD1Events = 1+ assert.throws(() => compareReports(a, b), /Incomplete D1 logs/)+ b.db.missingD1Events = null+ b.config.observeDB = true+ assert.throws(() => compareReports(a, b), /Incompatible/)+ b.config.observeDB = false+ b.workloads[0].params.size = 1024+ assert.throws(() => compareReports(a, b), /Incompatible/)+})++test('case identity, version and metric units form a comparison contract', () => {+ const a = browserSummary([sample], metadata)+ for (const change of [b => b.case.id = 'different', b => b.case.version++, b => b.case.metrics.customVisibleMs.unit = 'seconds']) {+ const b = structuredClone(a); change(b)+ assert.throws(() => compareReports(a, b), /Incompatible/)+ }+ assert.throws(() => browserSummary([sample], { ...metadata, schemaVersion: 1 }), /Unsupported/)+})diff --git a/src/benchmark/test/case-extension.control.mjs b/src/benchmark/test/case-extension.control.mjsnew file mode 100644index 000000000..2eb0b737d--- /dev/null+++ b/src/benchmark/test/case-extension.control.mjs@@ -0,0 +1,58 @@+import assert from 'node:assert/strict'+import { createServer } from 'node:http'+import { mkdtemp, writeFile, readFile, mkdir } from 'node:fs/promises'+import { resolve } from 'node:path'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { loadConfig } from '../src/config.mjs'+import { resolveCase } from '../src/cases/index.mjs'+import { runBrowserBenchmark } from '../src/browser-runner.mjs'+const exec = promisify(execFile)+const root = resolve(process.argv[2] ?? 'artifacts')+await mkdir(root, { recursive: true })+const out = await mkdtemp(`${root}/extension-control-`)+let count = 0+const server = createServer((req, res) => {+ if (req.method === 'POST' && req.url === '/increment') { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ count: ++count })); return }+ res.setHeader('Content-Type', 'text/html')+ res.end('<button id="increment">Increment</button><output id="count">0</output><script>document.querySelector("#increment").onclick=async()=>{const r=await fetch("/increment",{method:"POST"});document.querySelector("#count").textContent=(await r.json()).count}</script>')+})+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))+const config = { case: 'http-counter-control', baseUrl: `http://127.0.0.1:${server.address().port}`, targetKind: 'local', targetVersion: 'counter-control-v1', environment: 'single-page extension control', samples: 2, warmup: 0, intervalMs: 0, observationWindowMs: 300, phases: [{ name: 'baseline', delayMs: 0 }], timeoutMs: 3000 }+try {+ for (const name of ['a', 'b']) {+ const path = `${out}/${name}.json`+ await writeFile(path, JSON.stringify({ ...config, outDir: name }))+ await exec(process.execPath, ['src/cli.mjs', 'run', path])+ const summary = await readFile(`${out}/${name}/summary.json`, 'utf8')+ const report = JSON.parse(summary)+ assert.equal(report.participants.length, 1); assert.equal(report.groups[0].failed, 0)+ assert.equal(report.groups[0].caseMetrics.counterVisibleMs.n, 2)+ assert.equal(report.groups[0].windowWsApplicationBytes.p50, 0)+ assert.equal(report.groups[0].pageTaskCpuMs.length, 1)+ const raw = (await readFile(`${out}/${name}/operations.jsonl`, 'utf8')).trim().split('\n').map(JSON.parse)+ assert.ok(raw.every(sample => sample.result.submit.isTrusted && sample.requestsAtCutoff.some(r => r.direct && r.status === 200)))+ await exec(process.execPath, ['src/cli.mjs', 'report', `${out}/${name}`])+ assert.equal(await readFile(`${out}/${name}/summary.json`, 'utf8'), summary)+ }+ await exec(process.execPath, ['src/cli.mjs', 'compare', `${out}/a`, `${out}/b`])+ assert.equal(JSON.parse(await readFile(`${out}/b/comparison.json`, 'utf8')).sameVersionControl, true)+ const path = `${out}/invalid.json`+ await writeFile(path, JSON.stringify({ ...config, samples: 3, outDir: 'invalid' }))+ const invalidConfig = await loadConfig(path), invalid = resolveCase(invalidConfig), finish = invalid.finish+ let index = 0+ invalid.finish = args => {+ const result = finish(args)+ if (index === 0) result.submit = null+ else if (index === 1) result.submit.isTrusted = false+ else result.submit.role = 999+ index+++ return result+ }+ const rejected = await runBrowserBenchmark(invalidConfig, invalid)+ assert.equal(rejected.groups[0].failed, 3)+ assert.equal(rejected.groups[0].caseMetrics.counterVisibleMs.n, 0)+ const invalidRaw = (await readFile(`${out}/invalid/operations.jsonl`, 'utf8')).trim().split('\n').map(JSON.parse)+ assert.ok(invalidRaw.every(sample => sample.error === 'invalid-trusted-submit'))+ console.log(JSON.stringify({ pass: true, output: out, validSamples: 4, invalidSubmitsRejected: 3, reportRebuildExact: true, comparison: 'A/A' }))+} finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)) }diff --git a/src/benchmark/test/config.test.mjs b/src/benchmark/test/config.test.mjsnew file mode 100644index 000000000..cbe060f21--- /dev/null+++ b/src/benchmark/test/config.test.mjs@@ -0,0 +1,29 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { mkdtemp, writeFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { prepareFixture } from '../src/client.mjs'+import { loadConfig, publicConfig } from '../src/config.mjs'++test('config rejects ambiguous targets/identities and public output excludes fixture secrets', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'benchmark-config-'))+ const path = join(dir, 'config.json')+ const base = { baseUrl: 'http://localhost:3000', targetKind: 'local', targetVersion: 'sha', environment: 'test', fixtureFile: 'fixture.json' }+ const accounts = [{ cookie: 'secret-1', userId: 'one' }, { cookie: 'secret-2', userId: 'two' }]+ try {+ await writeFile(join(dir, 'fixture.json'), JSON.stringify({ accounts }))+ await writeFile(path, JSON.stringify(base))+ const config = await loadConfig(path)+ await assert.rejects(prepareFixture({ ...config, receivers: 2 }), /sender plus/ )+ await writeFile(path, JSON.stringify({ ...base, case: 'counter-control', fixtureFile: undefined }))+ assert.deepEqual((await loadConfig(path)).fixture, {})+ assert.equal(config.expectedMembers, 100)+ assert.equal(config.intervalMs, 400)+ assert.ok(!JSON.stringify(publicConfig(config)).includes('secret'))+ for (const override of [{ baseUrl: 'https://user:[email protected]' }, { wsUrl: 'ws://localhost/api/ws?token=secret' }, { phases: [{ name: 'obsolete', phase: 'response', delayMs: 1000 }] }, { samples: 0 }, { targetKind: 'production' }]) {+ await writeFile(path, JSON.stringify({ ...base, ...override }))+ await assert.rejects(loadConfig(path))+ }+ } finally { await rm(dir, { recursive: true, force: true }) }+})diff --git a/src/benchmark/test/d1-control-worker.mjs b/src/benchmark/test/d1-control-worker.mjsnew file mode 100644index 000000000..7a809cae2--- /dev/null+++ b/src/benchmark/test/d1-control-worker.mjs@@ -0,0 +1,19 @@+export default {+ async fetch(_request, env) {+ await env.DB.exec('CREATE TABLE IF NOT EXISTS measured(id INTEGER PRIMARY KEY, value BLOB); CREATE TABLE IF NOT EXISTS audit(id INTEGER PRIMARY KEY); CREATE TRIGGER IF NOT EXISTS measured_audit AFTER INSERT ON measured BEGIN INSERT INTO audit(id) VALUES (NEW.id); END; DELETE FROM measured; DELETE FROM audit;')+ const session = env.DB.withSession('first-primary')+ const batch = await session.batch([+ session.prepare('INSERT INTO measured(id,value) VALUES (?,?)').bind(1, new Uint8Array([0, 255]).buffer),+ session.prepare('INSERT INTO measured(id,value) VALUES (?,?)').bind(2, null),+ ])+ const raw = await session.prepare('SELECT id AS same, id+10 AS same FROM measured ORDER BY id').raw()+ const first = await session.prepare('SELECT COUNT(*) AS n FROM audit').first('n')+ let failed = false+ try {+ await session.batch([session.prepare('INSERT INTO measured(id) VALUES (?)').bind(3), session.prepare('INSERT INTO measured(id) VALUES (?)').bind(1)])+ } catch { failed = true }+ const afterFailure = await session.prepare('SELECT id FROM measured ORDER BY id').raw()+ const audit = await session.prepare('SELECT id FROM audit ORDER BY id').all()+ return Response.json({ raw, first, failed, afterFailure, audit: audit.results, batchMeta: batch.map(row => row.meta), bookmark: session.getBookmark(), success: failed && first === 2 && afterFailure.length === 2 && raw[0][1] === 11 })+ },+}diff --git a/src/benchmark/test/observer.test.mjs b/src/benchmark/test/observer.test.mjsnew file mode 100644index 000000000..917d0a3d6--- /dev/null+++ b/src/benchmark/test/observer.test.mjs@@ -0,0 +1,128 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { observeD1, jsonBytes } from '../src/d1-observer.mjs'+import { observeWorker } from '../src/worker-observer.mjs'++function fixture() {+ const calls = []+ const database = {+ prepare(sql) {+ return {+ bind(...args) { calls.push(['bind', args]); return this },+ async raw() { calls.push(['raw', sql]); return [['same', 'same', new Uint8Array([0, 255])]] },+ async first() { calls.push(['first']); return { meta: { rows_read: 999 }, value: 'literal user row' } },+ async run() { calls.push(['run']); return { success: true, results: [], meta: { duration: 2, rows_read: 4, rows_written: 3, total_attempts: 2 } } },+ }+ },+ withSession(value) { calls.push(['session', value]); return this },+ getBookmark() { return 'bookmark' },+ async batch(statements) { calls.push(['batch', statements.length]); return statements.map(() => ({ success: true, results: [], meta: { duration: 1, rows_read: 2, rows_written: 1 } })) },+ async exec() { return { count: 3, duration: 7 } },+ }+ return { database, calls }+}++test('prepare/bind/session are not executions; raw keeps duplicate columns and binary result', async () => {+ const { database, calls } = fixture()+ const events = []+ const db = observeD1(database, event => events.push(event))+ const session = db.withSession('first-primary')+ const stmt = session.prepare('SELECT ? AS same, ? AS same').bind('a', 'b')+ assert.equal(events.length, 0)+ assert.equal(session.getBookmark(), 'bookmark')+ assert.deepEqual(await stmt.raw(), [['same', 'same', new Uint8Array([0, 255])]])+ assert.equal(events.length, 1)+ assert.equal(events[0].statements, 1)+ assert.equal(events[0].metadata[0].rowsRead, null)+ assert.equal(calls.filter(c => c[0] === 'raw').length, 1)+ assert.equal(calls.some(c => c[0] === 'run'), false)+})++test('batch is one original call with N original bound statements; preserves meta', async () => {+ const { database, calls } = fixture()+ const events = []+ const db = observeD1(database, event => events.push(event))+ const result = await db.batch([db.prepare('INSERT x').bind(1), db.prepare('INSERT y').bind(null)])+ assert.equal(result.length, 2)+ assert.equal(events.length, 1)+ assert.equal(events[0].statements, 2)+ assert.equal(events[0].metadata.length, 2)+ assert.equal(calls.filter(c => c[0] === 'batch').length, 1)+ await db.prepare('SELECT x').first()+ assert.equal(events[1].metadata[0].rowsRead, null)+ await db.prepare('UPDATE x').run()+ assert.equal(events[2].metadata[0].internalAttempts, 2)+ await db.exec('multiple statements')+ assert.equal(events[3].statements, null)+ assert.equal(events[3].reportedExecCount, 3)+})++test('failure remains same error and reports one failed call, unknown meta', async () => {+ const error = new Error('constraint')+ const database = { batch: async () => { throw error }, prepare: () => ({}) }+ const events = []+ const db = observeD1(database, e => events.push(e))+ await assert.rejects(db.batch([db.prepare('INSERT')]), e => e === error)+ assert.equal(events.length, 1)+ assert.equal(events[0].ok, false)+ assert.deepEqual(events[0].metadata, [])+})++test('binary encodings are explicit; unicode bytes and unsupported values are honest', () => {+ assert.equal(jsonBytes('你'), 5)+ assert.equal(jsonBytes(new Uint8Array([0, 255])), Buffer.byteLength(JSON.stringify({ binaryBase64: 'AP8=' })))+ assert.equal(jsonBytes(new Uint8Array([0, 255]).buffer), jsonBytes(new Uint8Array([0, 255])))+ assert.equal(jsonBytes(1n), null)+})++test('worker keeps response independent of background tasks, isolates simultaneous requests', async () => {+ const events = []+ let release+ const barrier = new Promise(resolve => { release = resolve })+ const worker = observeWorker({ async fetch(_req, env, ctx) {+ await env.DB.prepare('one').run()+ ctx.waitUntil((async () => { await barrier; await env.DB.prepare('two').run() })())+ return new Response('ok')+ } }, e => events.push(e))+ const tasks = []+ const context = { waitUntil: task => tasks.push(task) }+ await Promise.all(['r1', 'r2'].map(requestId => worker.fetch(new Request('http://local/', { headers: { 'x-alook-benchmark-id': requestId } }), { DB: fixture().database }, context)))+ assert.equal(events.filter(e => e.kind === 'request-complete').length, 0)+ release()+ await Promise.all(tasks)+ for (const id of ['r1', 'r2']) {+ const records = events.filter(e => e.requestId === id)+ assert.equal(records.filter(e => e.kind === 'd1').length, 2)+ assert.deepEqual(records.filter(e => e.kind === 'd1').map(e => e.startedAfterResponse), [false, true])+ assert.equal(records.at(-1).kind, 'request-complete')+ assert.equal(records.at(-1).d1Calls, 2)+ }+})++test('a DB call spanning the response keeps both phase boundaries', async () => {+ const events = []+ let release+ let afterResponse = false+ const barrier = new Promise(resolve => { release = resolve })+ const db = observeD1({ prepare: () => ({ raw: () => barrier }) }, e => events.push(e), () => performance.now(), () => afterResponse)+ const call = db.prepare('SELECT').raw()+ afterResponse = true+ release([[1]])+ await call+ assert.equal(events[0].startedAfterResponse, false)+ assert.equal(events[0].completedAfterResponse, true)+})++test('unmarked requests pass original binding/context identity through untouched', async () => {+ const env = { DB: fixture().database }+ const ctx = { waitUntil() {} }+ let passed = false+ const worker = observeWorker({ fetch(_request, receivedEnv, receivedContext) {+ assert.equal(receivedEnv, env)+ assert.equal(receivedContext, ctx)+ passed = true+ return new Response('ok')+ } }, () => assert.fail('must not emit'))+ await worker.fetch(new Request('http://local'), env, ctx)+ assert.ok(passed)+})diff --git a/src/benchmark/test/proxy.test.mjs b/src/benchmark/test/proxy.test.mjsnew file mode 100644index 000000000..f83fbe8e5--- /dev/null+++ b/src/benchmark/test/proxy.test.mjs@@ -0,0 +1,29 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import http from 'node:http'+import { startProxy } from '../src/proxy.mjs'+import { api } from '../src/client.mjs'++test('1000ms request calibration and unselected GET bypass', async () => {+ let upstreamAt+ const server = http.createServer((request, response) => {+ upstreamAt = performance.now()+ response.setHeader('Content-Type', 'application/json')+ response.end(JSON.stringify({ text: '你好' }))+ })+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))+ const injections = []+ const proxy = await startProxy({ upstream: `http://127.0.0.1:${server.address().port}`, delayMs: 1000, emit: e => injections.push(e) })+ try {+ const start = performance.now()+ const result = await api(proxy.url, { cookie: 'test=fixture' }, '/api/community/channels/c/messages', { method: 'POST', body: { content: '你好' }, requestId: 'test' })+ assert.ok(result.wallMs >= 980)+ assert.equal(result.responseBodyBytes, Buffer.byteLength(JSON.stringify({ text: '你好' })))+ assert.ok(upstreamAt - start >= 980)+ assert.equal(injections.length, 1)+ assert.ok(injections[0].actualMs >= 980)+ const get = await api(proxy.url, { cookie: 'test=fixture' }, '/api/community/channels/c/messages')+ assert.ok(get.wallMs < 800)+ assert.equal(injections.length, 1)+ } finally { await proxy.close(); await new Promise(resolve => server.close(resolve)) }+})diff --git a/src/benchmark/test/report.test.mjs b/src/benchmark/test/report.test.mjsnew file mode 100644index 000000000..1a3593b4c--- /dev/null+++ b/src/benchmark/test/report.test.mjs@@ -0,0 +1,63 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { distribution, summarize } from '../src/report.mjs'++test('null observations are excluded from percentiles, not failures or denominators', () => {+ assert.deepEqual(distribution([null, 10, 20, NaN]), { n: 2, p50: 10, p95: 20, p99: 20, min: 10, max: 20 })+ const metadata = { config: { phases: [{ name: 'baseline' }], payloadBytes: [64] } }+ const report = summarize([{ requestId: 'r', phase: 'baseline', payloadBytes: 64, startedMs: 1, finishedMs: 1001, ackMs: null, error: 'timeout', receivers: [{ receiveMs: null, duplicates: 0, outcome: 'unresolved' }] }], metadata)+ assert.equal(report.groups[0].attempted, 1)+ assert.equal(report.groups[0].failed, 1)+ assert.equal(report.groups[0].unresolved, 1)+ assert.equal(report.groups[0].sendAckMs.p50, null)+ assert.equal(report.db.status, 'unavailable')+ assert.equal(report.db.executionCalls, null)+ assert.equal(report.db.knownRowsRead, null)+ assert.equal(report.db.requestsWithoutCompletion, 1)+})++test('DB phase/payload/API groups stay separate and duplicated telemetry is not double-counted', () => {+ const metadata = { config: { phases: [{ name: 'baseline' }, { name: 'delay' }], payloadBytes: [64] } }+ const samples = ['baseline', 'delay'].map((phase, i) => ({ requestId: `r${i}`, phase, payloadBytes: 64, startedMs: i * 1000, finishedMs: i * 1000 + 900, receivers: [], history: { requestId: `h${i}` } }))+ const event = { benchmark: 1, requestId: 'r0', kind: 'd1', operation: 1, method: 'raw', statements: 1, ok: true, wallMs: 3, sqlBytes: 12, parameterJsonBytes: 2, resultJsonBytes: 20, metadata: [{ rowsRead: null, rowsWritten: null, sqlDurationMs: null, internalAttempts: null }] }+ const report = summarize(samples, metadata, [event, event, { ...event, requestId: 'h1', metadata: [{ rowsRead: 3, rowsWritten: 0, sqlDurationMs: 1, internalAttempts: 1 }] }])+ assert.equal(report.db.duplicateTelemetryRecords, 1)+ assert.equal(report.db.executionCalls, 2)+ assert.equal(report.db.groups[0].send.executionCalls, 1)+ assert.equal(report.db.groups[0].history.executionCalls, null)+ assert.equal(report.db.groups[1].history.rowsRead.total, 3)+ assert.equal(report.db.rowsRead.coverage, .5)+ assert.equal(report.db.parameterJsonBytes.total, 4)+ assert.throws(() => summarize(samples, metadata, [event, { ...event, wallMs: 4 }]), /Conflicting telemetry/)+})++test('a fast 429 never improves successful ACK percentiles', () => {+ const metadata = { config: { phases: [{ name: 'baseline' }], payloadBytes: [64] } }+ const common = { phase: 'baseline', payloadBytes: 64, startedMs: 0, finishedMs: 1000, receivers: [] }+ const result = summarize([{ ...common, requestId: 'ok', messageId: 'm', ackMs: 100, error: null, status: 201 }, { ...common, requestId: 'limit', ackMs: 1, error: 'send-failed', status: 429 }], metadata)+ assert.equal(result.groups[0].sendAckMs.p50, 100)+ assert.equal(result.groups[0].failedHttpResponseMs.p50, 1)+ assert.equal(result.groups[0].failed, 1)+})+++test('completed observed requests with no D1 execution report real zero, missing logs remain unknown', async () => {+ const { dbMetrics } = await import('../src/report.mjs')+ const zero = dbMetrics(['empty'], [{ kind: 'request-complete', requestId: 'empty', failedTasks: 0, d1Calls: 0 }])+ assert.equal(zero.status, 'observed-empty')+ assert.equal(zero.executionCalls, 0)+ assert.equal(zero.submittedStatements, 0)+ assert.equal(zero.rowsRead.total, 0)+ assert.equal(zero.sqlBytes.total, 0)+ const missing = dbMetrics(['empty', 'missing'], [{ kind: 'request-complete', requestId: 'empty', failedTasks: 0, d1Calls: 0 }])+ assert.equal(missing.executionCalls, null)+ assert.equal(missing.rowsRead.total, null)+ const lost = dbMetrics(['empty'], [{ kind: 'request-complete', requestId: 'empty', d1Calls: 1 }])+ assert.equal(lost.executionCalls, null)+ assert.equal(lost.missingD1Events, 1)+ const partial = dbMetrics(['partial'], [{ kind: 'request-complete', requestId: 'partial', d1Calls: 2 }, { kind: 'd1', requestId: 'partial', statements: 1, metadata: [{ rowsRead: 3, rowsWritten: 1 }], sqlBytes: 20 }])+ assert.equal(partial.rowsRead.total, 3)+ assert.equal(partial.rowsRead.coverage, null)+ assert.equal(partial.sqlBytes.coverage, null)+ assert.equal(partial.missingD1Events, 1)+})diff --git a/src/benchmark/test/runner.test.mjs b/src/benchmark/test/runner.test.mjsnew file mode 100644index 000000000..1ec3783d8--- /dev/null+++ b/src/benchmark/test/runner.test.mjs@@ -0,0 +1,72 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import http from 'node:http'+import { createHash } from 'node:crypto'+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import os from 'node:os'+import { join } from 'node:path'+import { runBenchmark } from '../src/runner.mjs'++function frame(socket, object) {+ const data = Buffer.from(JSON.stringify(object))+ const header = data.length < 126 ? Buffer.from([0x81, data.length]) : Buffer.from([0x81, 126, data.length >> 8, data.length & 255])+ socket.write(Buffer.concat([header, data]))+}++test('real HTTP/WS control keeps pre-ACK delivery, nonce correlation, late duplicates and private data out of artifacts', async () => {+ const sockets = []+ const messages = []+ const server = http.createServer(async (request, response) => {+ response.setHeader('Content-Type', 'application/json')+ const url = new URL(request.url, 'http://local')+ let result+ if (url.pathname === '/api/ws/token') result = { userId: 'receiver', token: 'secret-token' }+ else if (url.pathname.endsWith('/servers/s/members')) result = { members: [{ userId: 'sender' }, { userId: 'receiver' }], hasMore: false }+ else if (url.pathname.endsWith('/channels/c/members')) result = { members: [{ userId: 'sender' }, { userId: 'receiver' }] }+ else if (url.pathname.endsWith('/channels/c')) result = { id: 'c', serverId: 's', type: 'text', parentChannelId: null, categoryId: null }+ else if (request.method === 'POST') {+ let body = ''+ for await (const part of request) body += part+ const sent = JSON.parse(body)+ const message = { id: `m${messages.length}`, clientNonce: sent.nonce, content: sent.content }+ messages.unshift(message)+ const batch = { type: 'community:events.batch', events: [{ type: 'community:message.create', channelId: 'c', message }] }+ for (const socket of sockets) frame(socket, batch)+ setTimeout(() => { for (const socket of sockets) if (!socket.destroyed) frame(socket, batch) }, 40)+ await new Promise(resolve => setTimeout(resolve, 100))+ result = { message }+ } else result = { messages }+ response.end(JSON.stringify(result))+ })+ server.on('upgrade', (request, socket) => {+ assert.equal(new URL(request.url, 'http://local').searchParams.get('userId'), 'receiver')+ const accept = createHash('sha1').update(request.headers['sec-websocket-key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64')+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`)+ socket.once('data', () => frame(socket, { type: 'auth.ok' }))+ sockets.push(socket)+ })+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))+ const outDir = await mkdtemp(join(os.tmpdir(), 'benchmark-control-'))+ const baseUrl = `http://127.0.0.1:${server.address().port}`+ try {+ const report = await runBenchmark({ baseUrl, wsUrl: baseUrl.replace('http', 'ws') + '/api/ws/user', targetKind: 'local', targetVersion: 'control', environment: 'controlled HTTP/WS', outDir,+ samples: 2, warmup: 0, concurrency: 1, timeoutMs: 2000, intervalMs: 60, receivers: 1, expectedMembers: 2, historyLimit: 20, observeDB: false,+ payloadBytes: [64], phases: [{ name: 'baseline', delayMs: 0 }],+ fixture: { serverId: 's', channelId: 'c', accounts: [{ userId: 'sender', cookie: 'session=secret-cookie' }, { userId: 'receiver', cookie: 'session=secret-cookie' }] } })+ const samples = (await readFile(`${outDir}/samples.jsonl`, 'utf8')).trim().split('\n').map(JSON.parse)+ assert.equal(samples.length, 2)+ assert.ok(samples.every(s => s.receivers[0].receiveMs < s.ackMs))+ assert.ok(samples.every(s => s.receivers[0].duplicates === 1))+ assert.ok(samples.every(s => s.history.containsSentMessage))+ assert.equal(report.groups[0].delivered, 2)+ assert.equal(report.groups[0].duplicates, 2)+ for (const file of ['samples.jsonl', 'summary.json', 'metadata.json', 'injections.jsonl']) {+ const text = await readFile(`${outDir}/${file}`, 'utf8')+ assert.ok(!text.includes('secret-cookie') && !text.includes('secret-token'))+ }+ } finally {+ sockets.forEach(socket => socket.destroy())+ await new Promise(resolve => server.close(resolve))+ await rm(outDir, { recursive: true, force: true })+ }+})