- MCP
- blame on this site's /mcp
- CLI
- abso blame server/scale/scale.mjs --json
- JSON
- /christopher/abso-core/blame/server/scale/scale.mjs?format=json
448 linesspeed 100%Last change speed in version 152,
448 lines from 2 changes in 1 version.
speed152Scale harness for the open server, and its first ramp on abso-openCompare1#!/usr/bin/env node
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.
5//
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
8//
9// The token comes from ABSO_TOKEN, or from the file --token-file names. It is never printed. README.md says more.
11import { createHash, randomBytes } from "node:crypto";
12import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
13import { dirname, join, resolve } from "node:path";
14import { fileURLToPath } from "node:url";
16const HERE = dirname(fileURLToPath(import.meta.url));
17const HOT_LINES = 40;
18/** The ramp's stages: projects × agents per project. */
19export const RAMP = [
20 [1, 1],
21 [10, 5],
22 [50, 10],
23 [100, 10],
24 [200, 20],
25];
27function parseArgs(argv) {
28 const o = {
29 server: "",
30 projects: 10,
31 agents: 5,
32 rounds: 3,
33 overlap: 0.2,
34 prefix: "",
35 concurrency: 256,
36 maxSeconds: 240,
37 artifactsSample: 5,
38 artifactsWait: 180,
39 tokenFile: "",
40 ramp: false,
41 stopErrorRate: 0.02,
42 out: join(HERE, "results"),
43 };
44 for (let i = 0; i < argv.length; i++) {
45 const a = argv[i];
46 const next = () => {
47 const v = argv[++i];
48 if (v === undefined) throw new Error(`${a} needs a value`);
49 return v;
50 };
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}`);
66 }
67 return o;
68}
70/** The value at fraction q of sorted numbers (nearest rank), or null when there are none. */
71export 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))];
74}
76const 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. */
79function limiter(limit) {
80 let active = 0;
81 const queue = [];
82 const release = () => {
83 active--;
84 const next = queue.shift();
85 if (next) next();
86 };
87 return async (work) => {
88 if (active >= limit) await new Promise((ok) => queue.push(ok));
89 active++;
90 try {
91 return await work();
92 } finally {
93 release();
94 }
95 };
96}
98/** Latencies by operation, statuses, and the counts the summary reports. */
99class Stats {
100 ops = new Map();
101 statuses = new Map();
102 errors = new Map();
103 requests = 0;
104 pushes = 0;
105 held = 0;
106 settled = 0;
107 heldAfterRetry = 0;
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);
112 this.requests++;
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);
117 }
118 }
119 pushed(project) {
120 this.pushes++;
121 this.perProject.set(project, (this.perProject.get(project) ?? 0) + 1);
122 }
123 errorCount() {
124 let n = 0;
125 for (const v of this.errors.values()) n += v;
126 return n;
127 }
128 latency() {
129 const out = {};
130 for (const [op, list] of [...this.ops].sort()) {
131 const s = [...list].sort((a, b) => a - b);
132 out[op] = {
133 count: s.length,
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)),
138 };
139 }
140 return out;
141 }
142}
144class Client {
145 constructor(server, token, stats, limit) {
146 this.server = server;
147 this.token = token;
148 this.stats = stats;
149 this.limit = limit;
150 }
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";
156 try {
157 const res = await fetch(`${this.server}${path}`, {
158 method,
159 headers: {
160 authorization: `Bearer ${this.token}`,
161 "x-abso-client": "abso-scale/1",
162 ...(raw
163 ? { "content-type": "application/octet-stream" }
164 : body !== undefined
165 ? { "content-type": "application/json" }
166 : {}),
167 },
168 ...(raw ? { body: raw } : body !== undefined ? { body: JSON.stringify(body) } : {}),
169 signal: AbortSignal.timeout(120_000),
170 });
171 status = String(res.status);
172 const text = await res.text();
173 let parsed;
174 try {
175 parsed = JSON.parse(text);
176 } catch {
177 parsed = text;
178 }
179 return { status: res.status, body: parsed };
180 } catch (e) {
181 return { status: 0, body: { error: e instanceof Error ? e.message : String(e) } };
182 } finally {
183 this.stats.time(op, performance.now() - t0, status);
184 }
185 });
186 }
187}
189const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
190const 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. */
193async 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(
199 "POST",
200 `/p/${project}/init`,
201 { files: { "README.md": `# ${project}\n\nA scale run.\n`, "hot.txt": hotText() }, blobs: { "logo.bin": sha } },
202 "init",
203 );
204 return init.status === 200 ? { ok: true } : { ok: false, why: `init ${init.status}` };
205}
207/** One agent: join, say what it starts on, then rounds of edit, record and publish. A held push pulls and retries once. */
208async 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);
215 }
216 };
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`;
222 let mine = "";
223 for (let r = 1; r <= o.rounds && Date.now() < deadline; r++) {
224 const hot = Math.random() < o.overlap;
225 let files;
226 if (hot) {
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") };
235 } else {
236 mine += `${agent} round ${r}\n`;
237 files = { [own]: mine };
238 }
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) {
244 stats.held++;
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(
249 "POST",
250 `${base}/publish`,
251 { message: `${agent} round ${r}, settled`, asIs: true },
252 "publish",
253 );
254 if (pub.status === 200 && pub.body.ok === true) stats.settled++;
255 else if (pub.status === 200) stats.heldAfterRetry++;
256 }
257 if (pub.status === 200 && pub.body.ok === true) {
258 stats.pushed(project);
259 stats.lastPush.set(project, Date.now());
260 }
261 await client.call("POST", `${base}/news`, {}, "news");
262 }
263}
265/** For a sample of projects: how long after its last push until /out says Artifacts holds shared's newest version. */
266async 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) => {
271 for (;;) {
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 };
277 }
278 if (out.status === 200 && b.artifacts === "unbound")
279 return { project, version: b.version, seconds: null, error: "artifacts unbound" };
280 if (Date.now() > until)
281 return {
282 project,
283 version: b.version ?? null,
284 seconds: null,
285 error: b.error ? `not pushed: ${JSON.stringify(b.error).slice(0, 160)}` : "not pushed in time",
286 };
287 await sleep(3000);
288 }
289 }),
290 );
291 const done = results
292 .map((r) => r.seconds)
293 .filter((s) => s !== null)
294 .sort((a, b) => a - b);
295 return {
296 sampled: sample.length,
297 pushedOut: done.length,
298 p50Seconds: percentile(done, 0.5),
299 maxSeconds: done.at(-1) ?? null,
300 projects: results,
301 };
302}
304/** One stage: P projects × A agents × R rounds. */
305export 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;
316 await Promise.all(
317 live.flatMap((p) =>
318 Array.from({ length: o.agents }, (_, a) => runAgent(client, stats, p, `agent-${a + 1}`, o, deadline)),
319 ),
320 );
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);
324 return {
325 stage: name,
326 server: o.server,
327 at: new Date(t0).toISOString(),
328 projects: o.projects,
329 projectsMade: live.length,
330 agentsPerProject: o.agents,
331 agents: live.length * o.agents,
332 rounds: o.rounds,
333 overlap: o.overlap,
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),
343 },
344 held: stats.held,
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(),
354 artifacts: lag,
355 failedProjects: projects.filter((_, i) => !made[i].ok).map((p, i) => ({ project: p, why: made[i]?.why })),
356 };
357}
359export 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}) |`;
363}
365export 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 "|---|---|---|---|---|---|---|---|---|",
368];
370function 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");
375}
377function readToken(o) {
378 if (o.tokenFile)
379 return readFileSync(
380 o.tokenFile.replace(/^~(?=$|[\\/])/, process.env.USERPROFILE ?? process.env.HOME ?? "~"),
381 "utf8",
382 ).trim();
383 return (process.env.ABSO_TOKEN ?? "").trim();
384}
386async 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"));
390 return;
391 }
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]];
398 const rows = [];
399 const files = [];
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`);
406 files.push(file);
407 rows.push(r);
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) {
410 console.log(
411 `Stopped after stage ${name}: errors ${(r.errorRate * 100).toFixed(2)}%, projects made ${r.projectsMade} of ${r.projects}.`,
412 );
413 break;
414 }
415 }
416 if (rows.length > 1) {
417 const summary = {
418 prefix: o.prefix,
419 server: o.server,
420 rounds: o.rounds,
421 overlap: o.overlap,
422 stages: rows
423 .map((r) => ({
424 ...r,
425 latencyMs: { publish: r.latencyMs.publish, record: r.latencyMs.record, sync: r.latencyMs.sync },
426 }))
427 .map(({ artifacts, statuses, ...r }) => ({
428 ...r,
429 artifacts: {
430 sampled: artifacts.sampled,
431 pushedOut: artifacts.pushedOut,
432 p50Seconds: artifacts.p50Seconds,
433 maxSeconds: artifacts.maxSeconds,
434 },
435 })),
436 };
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`);
439 }
440 console.error(`results: ${files.join(", ")}`);
441}
443if (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));
446 process.exit(1);
447 });
448}