Versions 145 to 318
new file, 448 lines
2+// A scale harness for abso's open server (server/). It talks HTTP directly, as the client does, so one machine can 3+// play thousands of agents across many projects. Each project is its own Durable Object and Artifacts repo, so total 4+// pushes a second should grow with the number of projects while each project's own latency stays flat. 6+// node server/scale/scale.mjs --server <url> [--projects 10] [--agents 5] [--rounds 3] [--overlap 0.2] 7+// node server/scale/scale.mjs --server <url> --ramp 9+// The token comes from ABSO_TOKEN, or from the file --token-file names. It is never printed. README.md says more. 11+import { createHash, randomBytes } from "node:crypto"; 12+import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; 13+import { dirname, join, resolve } from "node:path"; 14+import { fileURLToPath } from "node:url"; 16+const HERE = dirname(fileURLToPath(import.meta.url)); 18+/** The ramp's stages: projects × agents per project. */ 27+function parseArgs(argv) { 42+ out: join(HERE, "results"), 44+ for (let i = 0; i < argv.length; i++) { 48+ if (v === undefined) throw new Error(`${a} needs a value`); 51+ if (a === "--server") o.server = next().replace(/\/+$/, ""); 52+ else if (a === "--projects") o.projects = Number(next()); 53+ else if (a === "--agents") o.agents = Number(next()); 54+ else if (a === "--rounds") o.rounds = Number(next()); 55+ else if (a === "--overlap") o.overlap = Number(next()); 56+ else if (a === "--prefix") o.prefix = next(); 57+ else if (a === "--concurrency") o.concurrency = Number(next()); 58+ else if (a === "--max-seconds") o.maxSeconds = Number(next()); 59+ else if (a === "--artifacts-sample") o.artifactsSample = Number(next()); 60+ else if (a === "--artifacts-wait") o.artifactsWait = Number(next()); 61+ else if (a === "--token-file") o.tokenFile = next(); 62+ else if (a === "--out") o.out = next(); 63+ else if (a === "--ramp") o.ramp = true; 64+ else if (a === "--help" || a === "-h") o.help = true; 65+ else throw new Error(`unknown argument ${a}`); 70+/** The value at fraction q of sorted numbers (nearest rank), or null when there are none. */ 71+export function percentile(sorted, q) { 72+ if (sorted.length === 0) return null; 73+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))]; 76+const round = (n, places = 1) => (n === null || n === undefined ? null : Math.round(n * 10 ** places) / 10 ** places); 78+/** At most `limit` calls in flight at once. */ 79+function limiter(limit) { 82+ const release = () => { 84+ const next = queue.shift(); 87+ return async (work) => { 88+ if (active >= limit) await new Promise((ok) => queue.push(ok)); 98+/** Latencies by operation, statuses, and the counts the summary reports. */ 101+ statuses = new Map(); 108+ perProject = new Map(); 109+ time(op, ms, status) { 110+ if (!this.ops.has(op)) this.ops.set(op, []); 111+ this.ops.get(op).push(ms); 113+ this.statuses.set(status, (this.statuses.get(status) ?? 0) + 1); 114+ if (status === "network" || Number(status) >= 400) { 115+ const key = `${op} ${status}`; 116+ this.errors.set(key, (this.errors.get(key) ?? 0) + 1); 121+ this.perProject.set(project, (this.perProject.get(project) ?? 0) + 1); 125+ for (const v of this.errors.values()) n += v; 130+ for (const [op, list] of [...this.ops].sort()) { 131+ const s = [...list].sort((a, b) => a - b); 134+ p50: round(percentile(s, 0.5)), 135+ p95: round(percentile(s, 0.95)), 136+ p99: round(percentile(s, 0.99)), 137+ max: round(s.at(-1)), 145+ constructor(server, token, stats, limit) { 146+ this.server = server; 151+ /** One request, timed. Answers {status, body}; a network failure is status "network". */ 152+ async call(method, path, body, op, raw) { 153+ return this.limit(async () => { 154+ const t0 = performance.now(); 155+ let status = "network"; 157+ const res = await fetch(`${this.server}${path}`, { 160+ authorization: `Bearer ${this.token}`, 161+ "x-abso-client": "abso-scale/1", 163+ ? { "content-type": "application/octet-stream" } 164+ : body !== undefined 165+ ? { "content-type": "application/json" } 168+ ...(raw ? { body: raw } : body !== undefined ? { body: JSON.stringify(body) } : {}), 169+ signal: AbortSignal.timeout(120_000), 171+ status = String(res.status); 172+ const text = await res.text(); 175+ parsed = JSON.parse(text); 179+ return { status: res.status, body: parsed }; 181+ return { status: 0, body: { error: e instanceof Error ? e.message : String(e) } }; 183+ this.stats.time(op, performance.now() - t0, status); 189+const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms)); 190+const hotText = () => Array.from({ length: HOT_LINES }, (_, i) => `hot line ${i + 1}`).join("\n") + "\n"; 192+/** Makes a project: one starting file per agent is left to the agents; init holds the hot file, a readme and a blob. */ 193+async function initProject(client, project) { 194+ const bytes = randomBytes(256); 195+ const sha = createHash("sha256").update(bytes).digest("hex"); 196+ const put = await client.call("PUT", `/p/${project}/blobs/${sha}`, undefined, "blob", bytes); 197+ if (put.status !== 200) return { ok: false, why: `blob ${put.status}` }; 198+ const init = await client.call( 200+ `/p/${project}/init`, 201+ { files: { "README.md": `# ${project}\n\nA scale run.\n`, "hot.txt": hotText() }, blobs: { "logo.bin": sha } }, 204+ return init.status === 200 ? { ok: true } : { ok: false, why: `init ${init.status}` }; 207+/** One agent: join, say what it starts on, then rounds of edit, record and publish. A held push pulls and retries once. */ 208+async function runAgent(client, stats, project, agent, o, deadline) { 209+ const base = `/p/${project}/a/${agent}`; 210+ const view = new Map(); 211+ const take = (files) => { 212+ for (const [path, text] of Object.entries(files ?? {})) { 213+ if (text === null) view.delete(path); 214+ else view.set(path, text); 217+ const join = await client.call("POST", `${base}/sync`, {}, "sync"); 218+ if (join.status !== 200) return; 219+ take(join.body.files); 220+ await client.call("POST", `${base}/starting`, { text: `Scale run: ${agent} edits its own file` }, "starting"); 221+ const own = `agents/${agent}.txt`; 223+ for (let r = 1; r <= o.rounds && Date.now() < deadline; r++) { 224+ const hot = Math.random() < o.overlap; 227+ // Pull first, as an agent does before it touches a file others work on. 228+ const pulled = await client.call("POST", `${base}/sync`, {}, "sync"); 229+ if (pulled.status !== 200) continue; 230+ take(pulled.body.files); 231+ const lines = (view.get("hot.txt") ?? hotText()).split("\n"); 232+ const at = Math.floor(Math.random() * Math.min(3, lines.length - 1)); 233+ lines[at] = `hot line ${at + 1}, as ${agent} wants it in round ${r}`; 234+ files = { "hot.txt": lines.join("\n") }; 236+ mine += `${agent} round ${r}\n`; 237+ files = { [own]: mine }; 239+ const rec = await client.call("POST", `${base}/record`, { files }, "record"); 240+ if (rec.status !== 200) continue; 241+ for (const [p, t] of Object.entries(files)) view.set(p, t); 242+ let pub = await client.call("POST", `${base}/publish`, { message: `${agent} round ${r}` }, "publish"); 243+ if (pub.status === 200 && pub.body.ok === false) { 245+ // Settle: pull (both sides' lines come back), then push with both sides kept, as abso push --as-is does. 246+ const pulled = await client.call("POST", `${base}/sync`, {}, "sync"); 247+ if (pulled.status === 200) take(pulled.body.files); 248+ pub = await client.call( 251+ { message: `${agent} round ${r}, settled`, asIs: true }, 254+ if (pub.status === 200 && pub.body.ok === true) stats.settled++; 255+ else if (pub.status === 200) stats.heldAfterRetry++; 257+ if (pub.status === 200 && pub.body.ok === true) { 258+ stats.pushed(project); 259+ stats.lastPush.set(project, Date.now()); 261+ await client.call("POST", `${base}/news`, {}, "news"); 265+/** For a sample of projects: how long after its last push until /out says Artifacts holds shared's newest version. */ 266+async function artifactsLag(client, projects, stats, o) { 267+ const sample = projects.slice(0, o.artifactsSample); 268+ const until = Date.now() + o.artifactsWait * 1000; 269+ const results = await Promise.all( 270+ sample.map(async (project) => { 272+ const out = await client.call("GET", `/p/${project}/out`, undefined, "out"); 273+ const b = out.body ?? {}; 274+ if (out.status === 200 && b.version !== null && b.pushed && b.pushed.version >= b.version) { 275+ const last = stats.lastPush.get(project) ?? stats.started; 276+ return { project, version: b.version, seconds: round((Date.now() - last) / 1000), error: null }; 278+ if (out.status === 200 && b.artifacts === "unbound") 279+ return { project, version: b.version, seconds: null, error: "artifacts unbound" }; 280+ if (Date.now() > until) 283+ version: b.version ?? null, 285+ error: b.error ? `not pushed: ${JSON.stringify(b.error).slice(0, 160)}` : "not pushed in time", 291+ const done = results 292+ .map((r) => r.seconds) 293+ .filter((s) => s !== null) 294+ .sort((a, b) => a - b); 296+ sampled: sample.length, 297+ pushedOut: done.length, 298+ p50Seconds: percentile(done, 0.5), 299+ maxSeconds: done.at(-1) ?? null, 304+/** One stage: P projects × A agents × R rounds. */ 305+export async function runStage(o, token, name) { 306+ const stats = new Stats(); 307+ stats.lastPush = new Map(); 308+ const client = new Client(o.server, token, stats, limiter(o.concurrency)); 309+ const projects = Array.from({ length: o.projects }, (_, i) => `${o.prefix}-${name}-p${i + 1}`.toLowerCase()); 310+ stats.started = Date.now(); 311+ const made = await Promise.all(projects.map((p) => initProject(client, p))); 312+ const live = projects.filter((_, i) => made[i].ok); 313+ const initSeconds = (Date.now() - stats.started) / 1000; 314+ const t0 = Date.now(); 315+ const deadline = t0 + o.maxSeconds * 1000; 318+ Array.from({ length: o.agents }, (_, a) => runAgent(client, stats, p, `agent-${a + 1}`, o, deadline)), 321+ const seconds = (Date.now() - t0) / 1000; 322+ const lag = await artifactsLag(client, live, stats, o); 323+ const perProject = [...stats.perProject.values()].map((n) => n / seconds).sort((a, b) => a - b); 327+ at: new Date(t0).toISOString(), 328+ projects: o.projects, 329+ projectsMade: live.length, 330+ agentsPerProject: o.agents, 331+ agents: live.length * o.agents, 334+ initSeconds: round(initSeconds), 335+ seconds: round(seconds), 336+ cutShort: Date.now() > deadline, 337+ pushes: stats.pushes, 338+ pushesPerSecond: round(stats.pushes / seconds, 2), 339+ pushesPerSecondPerProject: { 340+ p50: round(percentile(perProject, 0.5), 3), 341+ min: round(perProject[0] ?? null, 3), 342+ max: round(perProject.at(-1) ?? null, 3), 345+ settledOnRetry: stats.settled, 346+ heldAfterRetry: stats.heldAfterRetry, 347+ requests: stats.requests, 348+ requestsPerSecond: round(stats.requests / seconds, 1), 349+ errors: stats.errorCount(), 350+ errorRate: round(stats.errorCount() / Math.max(1, stats.requests), 4), 351+ errorsByStatus: Object.fromEntries(stats.errors), 352+ statuses: Object.fromEntries(stats.statuses), 353+ latencyMs: stats.latency(), 355+ failedProjects: projects.filter((_, i) => !made[i].ok).map((p, i) => ({ project: p, why: made[i]?.why })), 359+export function summaryRow(r) { 360+ const pub = r.latencyMs.publish ?? {}; 361+ const lag = r.artifacts.p50Seconds === null ? "n/a" : `${r.artifacts.p50Seconds} s (max ${r.artifacts.maxSeconds} s)`; 362+ return `| ${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}) |`; 365+export const SUMMARY_HEAD = [ 366+ "| Stage (projects×agents) | Agents | Pushes | Pushes/s | Push p50 ms | Push p95 ms | Held | Errors | Artifacts lag p50 (pushed/sampled) |", 367+ "|---|---|---|---|---|---|---|---|---|", 370+function latencyTable(r) { 371+ const lines = ["| Operation | Count | p50 ms | p95 ms | p99 ms | max ms |", "|---|---|---|---|---|---|"]; 372+ for (const [op, l] of Object.entries(r.latencyMs)) 373+ lines.push(`| ${op} | ${l.count} | ${l.p50} | ${l.p95} | ${l.p99} | ${l.max} |`); 374+ return lines.join("\n"); 377+function readToken(o) { 379+ return readFileSync( 380+ o.tokenFile.replace(/^~(?=$|[\\/])/, process.env.USERPROFILE ?? process.env.HOME ?? "~"), 383+ return (process.env.ABSO_TOKEN ?? "").trim(); 386+async function main() { 387+ const o = parseArgs(process.argv.slice(2)); 388+ if (o.help || !o.server) { 389+ console.log(readFileSync(join(HERE, "README.md"), "utf8")); 392+ const token = readToken(o); 393+ if (!token) throw new Error("no token: set ABSO_TOKEN or pass --token-file <file>"); 394+ const runId = Date.now().toString(36); 395+ o.prefix ||= `scale-${runId}`; 396+ mkdirSync(o.out, { recursive: true }); 397+ const stages = o.ramp ? RAMP : [[o.projects, o.agents]]; 400+ for (const [projects, agents] of stages) { 401+ const name = `${projects}x${agents}`; 402+ console.error(`stage ${name}: ${projects} projects × ${agents} agents × ${o.rounds} rounds on ${o.server}`); 403+ const r = await runStage({ ...o, projects, agents }, token, name); 404+ const file = join(o.out, `${o.prefix}-${name}.json`); 405+ writeFileSync(file, `${JSON.stringify(r, null, "\t")}\n`); 408+ console.log(`\n### Stage ${name}\n\n${SUMMARY_HEAD.join("\n")}\n${summaryRow(r)}\n\n${latencyTable(r)}\n`); 409+ if (r.errorRate > o.stopErrorRate || r.projectsMade < r.projects) { 411+ `Stopped after stage ${name}: errors ${(r.errorRate * 100).toFixed(2)}%, projects made ${r.projectsMade} of ${r.projects}.`, 416+ if (rows.length > 1) { 425+ latencyMs: { publish: r.latencyMs.publish, record: r.latencyMs.record, sync: r.latencyMs.sync }, 427+ .map(({ artifacts, statuses, ...r }) => ({ 430+ sampled: artifacts.sampled, 431+ pushedOut: artifacts.pushedOut, 432+ p50Seconds: artifacts.p50Seconds, 433+ maxSeconds: artifacts.maxSeconds, 437+ writeFileSync(join(o.out, `${o.prefix}-ramp.json`), `${JSON.stringify(summary, null, "\t")}\n`); 438+ console.log(`\n## Ramp ${o.prefix}\n\n${SUMMARY_HEAD.join("\n")}\n${rows.map(summaryRow).join("\n")}\n`); 440+ console.error(`results: ${files.join(", ")}`); 443+if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) { 444+ main().catch((e) => { 445+ console.error(e instanceof Error ? e.message : String(e));