{"draft":null,"from":116,"to":318,"files":[{"path":"server/scale/scale.mjs","added":448,"removed":0,"diff":"--- /dev/null\n+++ b/server/scale/scale.mjs\n@@ -0,0 +1,448 @@\n+#!/usr/bin/env node\n+// A scale harness for abso's open server (server/). It talks HTTP directly, as the client does, so one machine can\n+// play thousands of agents across many projects. Each project is its own Durable Object and Artifacts repo, so total\n+// pushes a second should grow with the number of projects while each project's own latency stays flat.\n+//\n+//   node server/scale/scale.mjs --server <url> [--projects 10] [--agents 5] [--rounds 3] [--overlap 0.2]\n+//   node server/scale/scale.mjs --server <url> --ramp\n+//\n+// The token comes from ABSO_TOKEN, or from the file --token-file names. It is never printed. README.md says more.\n+\n+import { createHash, randomBytes } from \"node:crypto\";\n+import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\n+import { dirname, join, resolve } from \"node:path\";\n+import { fileURLToPath } from \"node:url\";\n+\n+const HERE = dirname(fileURLToPath(import.meta.url));\n+const HOT_LINES = 40;\n+/** The ramp's stages: projects × agents per project. */\n+export const RAMP = [\n+\t[1, 1],\n+\t[10, 5],\n+\t[50, 10],\n+\t[100, 10],\n+\t[200, 20],\n+];\n+\n+function parseArgs(argv) {\n+\tconst o = {\n+\t\tserver: \"\",\n+\t\tprojects: 10,\n+\t\tagents: 5,\n+\t\trounds: 3,\n+\t\toverlap: 0.2,\n+\t\tprefix: \"\",\n+\t\tconcurrency: 256,\n+\t\tmaxSeconds: 240,\n+\t\tartifactsSample: 5,\n+\t\tartifactsWait: 180,\n+\t\ttokenFile: \"\",\n+\t\tramp: false,\n+\t\tstopErrorRate: 0.02,\n+\t\tout: join(HERE, \"results\"),\n+\t};\n+\tfor (let i = 0; i < argv.length; i++) {\n+\t\tconst a = argv[i];\n+\t\tconst next = () => {\n+\t\t\tconst v = argv[++i];\n+\t\t\tif (v === undefined) throw new Error(`${a} needs a value`);\n+\t\t\treturn v;\n+\t\t};\n+\t\tif (a === \"--server\") o.server = next().replace(/\\/+$/, \"\");\n+\t\telse if (a === \"--projects\") o.projects = Number(next());\n+\t\telse if (a === \"--agents\") o.agents = Number(next());\n+\t\telse if (a === \"--rounds\") o.rounds = Number(next());\n+\t\telse if (a === \"--overlap\") o.overlap = Number(next());\n+\t\telse if (a === \"--prefix\") o.prefix = next();\n+\t\telse if (a === \"--concurrency\") o.concurrency = Number(next());\n+\t\telse if (a === \"--max-seconds\") o.maxSeconds = Number(next());\n+\t\telse if (a === \"--artifacts-sample\") o.artifactsSample = Number(next());\n+\t\telse if (a === \"--artifacts-wait\") o.artifactsWait = Number(next());\n+\t\telse if (a === \"--token-file\") o.tokenFile = next();\n+\t\telse if (a === \"--out\") o.out = next();\n+\t\telse if (a === \"--ramp\") o.ramp = true;\n+\t\telse if (a === \"--help\" || a === \"-h\") o.help = true;\n+\t\telse throw new Error(`unknown argument ${a}`);\n+\t}\n+\treturn o;\n+}\n+\n+/** The value at fraction q of sorted numbers (nearest rank), or null when there are none. */\n+export function percentile(sorted, q) {\n+\tif (sorted.length === 0) return null;\n+\treturn sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))];\n+}\n+\n+const round = (n, places = 1) => (n === null || n === undefined ? null : Math.round(n * 10 ** places) / 10 ** places);\n+\n+/** At most `limit` calls in flight at once. */\n+function limiter(limit) {\n+\tlet active = 0;\n+\tconst queue = [];\n+\tconst release = () => {\n+\t\tactive--;\n+\t\tconst next = queue.shift();\n+\t\tif (next) next();\n+\t};\n+\treturn async (work) => {\n+\t\tif (active >= limit) await new Promise((ok) => queue.push(ok));\n+\t\tactive++;\n+\t\ttry {\n+\t\t\treturn await work();\n+\t\t} finally {\n+\t\t\trelease();\n+\t\t}\n+\t};\n+}\n+\n+/** Latencies by operation, statuses, and the counts the summary reports. */\n+class Stats {\n+\tops = new Map();\n+\tstatuses = new Map();\n+\terrors = new Map();\n+\trequests = 0;\n+\tpushes = 0;\n+\theld = 0;\n+\tsettled = 0;\n+\theldAfterRetry = 0;\n+\tperProject = new Map();\n+\ttime(op, ms, status) {\n+\t\tif (!this.ops.has(op)) this.ops.set(op, []);\n+\t\tthis.ops.get(op).push(ms);\n+\t\tthis.requests++;\n+\t\tthis.statuses.set(status, (this.statuses.get(status) ?? 0) + 1);\n+\t\tif (status === \"network\" || Number(status) >= 400) {\n+\t\t\tconst key = `${op} ${status}`;\n+\t\t\tthis.errors.set(key, (this.errors.get(key) ?? 0) + 1);\n+\t\t}\n+\t}\n+\tpushed(project) {\n+\t\tthis.pushes++;\n+\t\tthis.perProject.set(project, (this.perProject.get(project) ?? 0) + 1);\n+\t}\n+\terrorCount() {\n+\t\tlet n = 0;\n+\t\tfor (const v of this.errors.values()) n += v;\n+\t\treturn n;\n+\t}\n+\tlatency() {\n+\t\tconst out = {};\n+\t\tfor (const [op, list] of [...this.ops].sort()) {\n+\t\t\tconst s = [...list].sort((a, b) => a - b);\n+\t\t\tout[op] = {\n+\t\t\t\tcount: s.length,\n+\t\t\t\tp50: round(percentile(s, 0.5)),\n+\t\t\t\tp95: round(percentile(s, 0.95)),\n+\t\t\t\tp99: round(percentile(s, 0.99)),\n+\t\t\t\tmax: round(s.at(-1)),\n+\t\t\t};\n+\t\t}\n+\t\treturn out;\n+\t}\n+}\n+\n+class Client {\n+\tconstructor(server, token, stats, limit) {\n+\t\tthis.server = server;\n+\t\tthis.token = token;\n+\t\tthis.stats = stats;\n+\t\tthis.limit = limit;\n+\t}\n+\t/** One request, timed. Answers {status, body}; a network failure is status \"network\". */\n+\tasync call(method, path, body, op, raw) {\n+\t\treturn this.limit(async () => {\n+\t\t\tconst t0 = performance.now();\n+\t\t\tlet status = \"network\";\n+\t\t\ttry {\n+\t\t\t\tconst res = await fetch(`${this.server}${path}`, {\n+\t\t\t\t\tmethod,\n+\t\t\t\t\theaders: {\n+\t\t\t\t\t\tauthorization: `Bearer ${this.token}`,\n+\t\t\t\t\t\t\"x-abso-client\": \"abso-scale/1\",\n+\t\t\t\t\t\t...(raw\n+\t\t\t\t\t\t\t? { \"content-type\": \"application/octet-stream\" }\n+\t\t\t\t\t\t\t: body !== undefined\n+\t\t\t\t\t\t\t\t? { \"content-type\": \"application/json\" }\n+\t\t\t\t\t\t\t\t: {}),\n+\t\t\t\t\t},\n+\t\t\t\t\t...(raw ? { body: raw } : body !== undefined ? { body: JSON.stringify(body) } : {}),\n+\t\t\t\t\tsignal: AbortSignal.timeout(120_000),\n+\t\t\t\t});\n+\t\t\t\tstatus = String(res.status);\n+\t\t\t\tconst text = await res.text();\n+\t\t\t\tlet parsed;\n+\t\t\t\ttry {\n+\t\t\t\t\tparsed = JSON.parse(text);\n+\t\t\t\t} catch {\n+\t\t\t\t\tparsed = text;\n+\t\t\t\t}\n+\t\t\t\treturn { status: res.status, body: parsed };\n+\t\t\t} catch (e) {\n+\t\t\t\treturn { status: 0, body: { error: e instanceof Error ? e.message : String(e) } };\n+\t\t\t} finally {\n+\t\t\t\tthis.stats.time(op, performance.now() - t0, status);\n+\t\t\t}\n+\t\t});\n+\t}\n+}\n+\n+const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));\n+const hotText = () => Array.from({ length: HOT_LINES }, (_, i) => `hot line ${i + 1}`).join(\"\\n\") + \"\\n\";\n+\n+/** Makes a project: one starting file per agent is left to the agents; init holds the hot file, a readme and a blob. */\n+async function initProject(client, project) {\n+\tconst bytes = randomBytes(256);\n+\tconst sha = createHash(\"sha256\").update(bytes).digest(\"hex\");\n+\tconst put = await client.call(\"PUT\", `/p/${project}/blobs/${sha}`, undefined, \"blob\", bytes);\n+\tif (put.status !== 200) return { ok: false, why: `blob ${put.status}` };\n+\tconst init = await client.call(\n+\t\t\"POST\",\n+\t\t`/p/${project}/init`,\n+\t\t{ files: { \"README.md\": `# ${project}\\n\\nA scale run.\\n`, \"hot.txt\": hotText() }, blobs: { \"logo.bin\": sha } },\n+\t\t\"init\",\n+\t);\n+\treturn init.status === 200 ? { ok: true } : { ok: false, why: `init ${init.status}` };\n+}\n+\n+/** One agent: join, say what it starts on, then rounds of edit, record and publish. A held push pulls and retries once. */\n+async function runAgent(client, stats, project, agent, o, deadline) {\n+\tconst base = `/p/${project}/a/${agent}`;\n+\tconst view = new Map();\n+\tconst take = (files) => {\n+\t\tfor (const [path, text] of Object.entries(files ?? {})) {\n+\t\t\tif (text === null) view.delete(path);\n+\t\t\telse view.set(path, text);\n+\t\t}\n+\t};\n+\tconst join = await client.call(\"POST\", `${base}/sync`, {}, \"sync\");\n+\tif (join.status !== 200) return;\n+\ttake(join.body.files);\n+\tawait client.call(\"POST\", `${base}/starting`, { text: `Scale run: ${agent} edits its own file` }, \"starting\");\n+\tconst own = `agents/${agent}.txt`;\n+\tlet mine = \"\";\n+\tfor (let r = 1; r <= o.rounds && Date.now() < deadline; r++) {\n+\t\tconst hot = Math.random() < o.overlap;\n+\t\tlet files;\n+\t\tif (hot) {\n+\t\t\t// Pull first, as an agent does before it touches a file others work on.\n+\t\t\tconst pulled = await client.call(\"POST\", `${base}/sync`, {}, \"sync\");\n+\t\t\tif (pulled.status !== 200) continue;\n+\t\t\ttake(pulled.body.files);\n+\t\t\tconst lines = (view.get(\"hot.txt\") ?? hotText()).split(\"\\n\");\n+\t\t\tconst at = Math.floor(Math.random() * Math.min(3, lines.length - 1));\n+\t\t\tlines[at] = `hot line ${at + 1}, as ${agent} wants it in round ${r}`;\n+\t\t\tfiles = { \"hot.txt\": lines.join(\"\\n\") };\n+\t\t} else {\n+\t\t\tmine += `${agent} round ${r}\\n`;\n+\t\t\tfiles = { [own]: mine };\n+\t\t}\n+\t\tconst rec = await client.call(\"POST\", `${base}/record`, { files }, \"record\");\n+\t\tif (rec.status !== 200) continue;\n+\t\tfor (const [p, t] of Object.entries(files)) view.set(p, t);\n+\t\tlet pub = await client.call(\"POST\", `${base}/publish`, { message: `${agent} round ${r}` }, \"publish\");\n+\t\tif (pub.status === 200 && pub.body.ok === false) {\n+\t\t\tstats.held++;\n+\t\t\t// Settle: pull (both sides' lines come back), then push with both sides kept, as abso push --as-is does.\n+\t\t\tconst pulled = await client.call(\"POST\", `${base}/sync`, {}, \"sync\");\n+\t\t\tif (pulled.status === 200) take(pulled.body.files);\n+\t\t\tpub = await client.call(\n+\t\t\t\t\"POST\",\n+\t\t\t\t`${base}/publish`,\n+\t\t\t\t{ message: `${agent} round ${r}, settled`, asIs: true },\n+\t\t\t\t\"publish\",\n+\t\t\t);\n+\t\t\tif (pub.status === 200 && pub.body.ok === true) stats.settled++;\n+\t\t\telse if (pub.status === 200) stats.heldAfterRetry++;\n+\t\t}\n+\t\tif (pub.status === 200 && pub.body.ok === true) {\n+\t\t\tstats.pushed(project);\n+\t\t\tstats.lastPush.set(project, Date.now());\n+\t\t}\n+\t\tawait client.call(\"POST\", `${base}/news`, {}, \"news\");\n+\t}\n+}\n+\n+/** For a sample of projects: how long after its last push until /out says Artifacts holds shared's newest version. */\n+async function artifactsLag(client, projects, stats, o) {\n+\tconst sample = projects.slice(0, o.artifactsSample);\n+\tconst until = Date.now() + o.artifactsWait * 1000;\n+\tconst results = await Promise.all(\n+\t\tsample.map(async (project) => {\n+\t\t\tfor (;;) {\n+\t\t\t\tconst out = await client.call(\"GET\", `/p/${project}/out`, undefined, \"out\");\n+\t\t\t\tconst b = out.body ?? {};\n+\t\t\t\tif (out.status === 200 && b.version !== null && b.pushed && b.pushed.version >= b.version) {\n+\t\t\t\t\tconst last = stats.lastPush.get(project) ?? stats.started;\n+\t\t\t\t\treturn { project, version: b.version, seconds: round((Date.now() - last) / 1000), error: null };\n+\t\t\t\t}\n+\t\t\t\tif (out.status === 200 && b.artifacts === \"unbound\")\n+\t\t\t\t\treturn { project, version: b.version, seconds: null, error: \"artifacts unbound\" };\n+\t\t\t\tif (Date.now() > until)\n+\t\t\t\t\treturn {\n+\t\t\t\t\t\tproject,\n+\t\t\t\t\t\tversion: b.version ?? null,\n+\t\t\t\t\t\tseconds: null,\n+\t\t\t\t\t\terror: b.error ? `not pushed: ${JSON.stringify(b.error).slice(0, 160)}` : \"not pushed in time\",\n+\t\t\t\t\t};\n+\t\t\t\tawait sleep(3000);\n+\t\t\t}\n+\t\t}),\n+\t);\n+\tconst done = results\n+\t\t.map((r) => r.seconds)\n+\t\t.filter((s) => s !== null)\n+\t\t.sort((a, b) => a - b);\n+\treturn {\n+\t\tsampled: sample.length,\n+\t\tpushedOut: done.length,\n+\t\tp50Seconds: percentile(done, 0.5),\n+\t\tmaxSeconds: done.at(-1) ?? null,\n+\t\tprojects: results,\n+\t};\n+}\n+\n+/** One stage: P projects × A agents × R rounds. */\n+export async function runStage(o, token, name) {\n+\tconst stats = new Stats();\n+\tstats.lastPush = new Map();\n+\tconst client = new Client(o.server, token, stats, limiter(o.concurrency));\n+\tconst projects = Array.from({ length: o.projects }, (_, i) => `${o.prefix}-${name}-p${i + 1}`.toLowerCase());\n+\tstats.started = Date.now();\n+\tconst made = await Promise.all(projects.map((p) => initProject(client, p)));\n+\tconst live = projects.filter((_, i) => made[i].ok);\n+\tconst initSeconds = (Date.now() - stats.started) / 1000;\n+\tconst t0 = Date.now();\n+\tconst deadline = t0 + o.maxSeconds * 1000;\n+\tawait Promise.all(\n+\t\tlive.flatMap((p) =>\n+\t\t\tArray.from({ length: o.agents }, (_, a) => runAgent(client, stats, p, `agent-${a + 1}`, o, deadline)),\n+\t\t),\n+\t);\n+\tconst seconds = (Date.now() - t0) / 1000;\n+\tconst lag = await artifactsLag(client, live, stats, o);\n+\tconst perProject = [...stats.perProject.values()].map((n) => n / seconds).sort((a, b) => a - b);\n+\treturn {\n+\t\tstage: name,\n+\t\tserver: o.server,\n+\t\tat: new Date(t0).toISOString(),\n+\t\tprojects: o.projects,\n+\t\tprojectsMade: live.length,\n+\t\tagentsPerProject: o.agents,\n+\t\tagents: live.length * o.agents,\n+\t\trounds: o.rounds,\n+\t\toverlap: o.overlap,\n+\t\tinitSeconds: round(initSeconds),\n+\t\tseconds: round(seconds),\n+\t\tcutShort: Date.now() > deadline,\n+\t\tpushes: stats.pushes,\n+\t\tpushesPerSecond: round(stats.pushes / seconds, 2),\n+\t\tpushesPerSecondPerProject: {\n+\t\t\tp50: round(percentile(perProject, 0.5), 3),\n+\t\t\tmin: round(perProject[0] ?? null, 3),\n+\t\t\tmax: round(perProject.at(-1) ?? null, 3),\n+\t\t},\n+\t\theld: stats.held,\n+\t\tsettledOnRetry: stats.settled,\n+\t\theldAfterRetry: stats.heldAfterRetry,\n+\t\trequests: stats.requests,\n+\t\trequestsPerSecond: round(stats.requests / seconds, 1),\n+\t\terrors: stats.errorCount(),\n+\t\terrorRate: round(stats.errorCount() / Math.max(1, stats.requests), 4),\n+\t\terrorsByStatus: Object.fromEntries(stats.errors),\n+\t\tstatuses: Object.fromEntries(stats.statuses),\n+\t\tlatencyMs: stats.latency(),\n+\t\tartifacts: lag,\n+\t\tfailedProjects: projects.filter((_, i) => !made[i].ok).map((p, i) => ({ project: p, why: made[i]?.why })),\n+\t};\n+}\n+\n+export function summaryRow(r) {\n+\tconst pub = r.latencyMs.publish ?? {};\n+\tconst lag = r.artifacts.p50Seconds === null ? \"n/a\" : `${r.artifacts.p50Seconds} s (max ${r.artifacts.maxSeconds} s)`;\n+\treturn `| ${r.projectsMade}×${r.agentsPerProject} | ${r.agents} | ${r.pushes} | ${r.pushesPerSecond} | ${pub.p50 ?? \"n/a\"} | ${pub.p95 ?? \"n/a\"} | ${r.held} (${r.heldAfterRetry} still held) | ${r.errors} (${(r.errorRate * 100).toFixed(2)}%) | ${lag} (${r.artifacts.pushedOut}/${r.artifacts.sampled}) |`;\n+}\n+\n+export const SUMMARY_HEAD = [\n+\t\"| Stage (projects×agents) | Agents | Pushes | Pushes/s | Push p50 ms | Push p95 ms | Held | Errors | Artifacts lag p50 (pushed/sampled) |\",\n+\t\"|---|---|---|---|---|---|---|---|---|\",\n+];\n+\n+function latencyTable(r) {\n+\tconst lines = [\"| Operation | Count | p50 ms | p95 ms | p99 ms | max ms |\", \"|---|---|---|---|---|---|\"];\n+\tfor (const [op, l] of Object.entries(r.latencyMs))\n+\t\tlines.push(`| ${op} | ${l.count} | ${l.p50} | ${l.p95} | ${l.p99} | ${l.max} |`);\n+\treturn lines.join(\"\\n\");\n+}\n+\n+function readToken(o) {\n+\tif (o.tokenFile)\n+\t\treturn readFileSync(\n+\t\t\to.tokenFile.replace(/^~(?=$|[\\\\/])/, process.env.USERPROFILE ?? process.env.HOME ?? \"~\"),\n+\t\t\t\"utf8\",\n+\t\t).trim();\n+\treturn (process.env.ABSO_TOKEN ?? \"\").trim();\n+}\n+\n+async function main() {\n+\tconst o = parseArgs(process.argv.slice(2));\n+\tif (o.help || !o.server) {\n+\t\tconsole.log(readFileSync(join(HERE, \"README.md\"), \"utf8\"));\n+\t\treturn;\n+\t}\n+\tconst token = readToken(o);\n+\tif (!token) throw new Error(\"no token: set ABSO_TOKEN or pass --token-file <file>\");\n+\tconst runId = Date.now().toString(36);\n+\to.prefix ||= `scale-${runId}`;\n+\tmkdirSync(o.out, { recursive: true });\n+\tconst stages = o.ramp ? RAMP : [[o.projects, o.agents]];\n+\tconst rows = [];\n+\tconst files = [];\n+\tfor (const [projects, agents] of stages) {\n+\t\tconst name = `${projects}x${agents}`;\n+\t\tconsole.error(`stage ${name}: ${projects} projects × ${agents} agents × ${o.rounds} rounds on ${o.server}`);\n+\t\tconst r = await runStage({ ...o, projects, agents }, token, name);\n+\t\tconst file = join(o.out, `${o.prefix}-${name}.json`);\n+\t\twriteFileSync(file, `${JSON.stringify(r, null, \"\\t\")}\\n`);\n+\t\tfiles.push(file);\n+\t\trows.push(r);\n+\t\tconsole.log(`\\n### Stage ${name}\\n\\n${SUMMARY_HEAD.join(\"\\n\")}\\n${summaryRow(r)}\\n\\n${latencyTable(r)}\\n`);\n+\t\tif (r.errorRate > o.stopErrorRate || r.projectsMade < r.projects) {\n+\t\t\tconsole.log(\n+\t\t\t\t`Stopped after stage ${name}: errors ${(r.errorRate * 100).toFixed(2)}%, projects made ${r.projectsMade} of ${r.projects}.`,\n+\t\t\t);\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tif (rows.length > 1) {\n+\t\tconst summary = {\n+\t\t\tprefix: o.prefix,\n+\t\t\tserver: o.server,\n+\t\t\trounds: o.rounds,\n+\t\t\toverlap: o.overlap,\n+\t\t\tstages: rows\n+\t\t\t\t.map((r) => ({\n+\t\t\t\t\t...r,\n+\t\t\t\t\tlatencyMs: { publish: r.latencyMs.publish, record: r.latencyMs.record, sync: r.latencyMs.sync },\n+\t\t\t\t}))\n+\t\t\t\t.map(({ artifacts, statuses, ...r }) => ({\n+\t\t\t\t\t...r,\n+\t\t\t\t\tartifacts: {\n+\t\t\t\t\t\tsampled: artifacts.sampled,\n+\t\t\t\t\t\tpushedOut: artifacts.pushedOut,\n+\t\t\t\t\t\tp50Seconds: artifacts.p50Seconds,\n+\t\t\t\t\t\tmaxSeconds: artifacts.maxSeconds,\n+\t\t\t\t\t},\n+\t\t\t\t})),\n+\t\t};\n+\t\twriteFileSync(join(o.out, `${o.prefix}-ramp.json`), `${JSON.stringify(summary, null, \"\\t\")}\\n`);\n+\t\tconsole.log(`\\n## Ramp ${o.prefix}\\n\\n${SUMMARY_HEAD.join(\"\\n\")}\\n${rows.map(summaryRow).join(\"\\n\")}\\n`);\n+\t}\n+\tconsole.error(`results: ${files.join(\", \")}`);\n+}\n+\n+if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {\n+\tmain().catch((e) => {\n+\t\tconsole.error(e instanceof Error ? e.message : String(e));\n+\t\tprocess.exit(1);\n+\t});\n+}"}],"unmatched":[]}