An open-source, faster Devin alternative
TypeScript
wip 378
Brian Reardon63107f9e6ec6
diff --git a/benchmarks/tti/_attrib.mjs b/benchmarks/tti/_attrib.mjsnew file mode 100644index 00000000..c421e38f--- /dev/null+++ b/benchmarks/tti/_attrib.mjs@@ -0,0 +1,138 @@+// Where does every millisecond of a burst create actually go?+//+// Four separate attempts have now failed to attribute the ~420ms that appears+// on a burst create and not on a sequential one: handshakes (batching 26:1+// changed nothing), CP compute (42us), edge CPU (p50 1ms), and distance (a+// constant cannot produce a 4x delta on the same path). Every one of those was+// argued from marks reported by the component under test — and a component+// cannot report time it spent waiting to be allowed to run.+//+// So this measures differently. Three clocks, never compared to each other:+//+// T1..T4 client send -> client receive (this process's clock)+// hdl edge handler entry -> exit (the edge's clock)+// cptotal CP handler entry -> exit (the CP's clock, from journald)+//+// Every quantity is a difference of two readings taken by the SAME machine, so+// clock skew cancels instead of leaking into the answer — no NTP assumption, no+// trust in anyone's absolute timestamps. The number we actually want is the one+// nobody reports:+//+// unaccounted = (T4 - T1) - hdl+//+// which is client<->edge wire plus any time the request sat queued before the+// Worker began executing. If that term is small, the burst penalty is inside+// our handler and the marks will find it. If it is large, the penalty is+// upstream of our code entirely and no amount of handler instrumentation will+// ever see it.+//+// Join key is sandboxID: the CP already logs `createtrace sb-xxxx total=NNus`+// and the client gets sandboxID back in the response, so the two ends are+// linkable with no correlation-ID plumbing on the hot path.+import { writeFileSync } from "node:fs";++const URL_BASE = process.env.OPENCOMPUTER_API_URL ?? "https://app2.opensandbox.ai";+const KEY = process.env.OPENCOMPUTER_API_KEY;+const N = Number(process.env.N ?? 100);+const MODE = process.env.MODE ?? "burst";+const OUT = process.env.OUT ?? "/tmp/attrib.ndjson";++if (!KEY) {+ console.error("set OPENCOMPUTER_API_KEY");+ process.exit(1);+}++/** Parse a Server-Timing header into {mark: ms}. */+function parseTiming(h) {+ const out = {};+ for (const part of (h ?? "").split(",")) {+ const m = part.trim().match(/^([a-z0-9_]+);dur=([0-9.]+)/i);+ if (m) out[m[1]] = Number(m[2]);+ }+ return out;+}++async function one(i) {+ // T1/T4 both come from performance.now() in THIS process. Their difference is+ // the only client-side quantity used anywhere, so the client's absolute clock+ // (and its offset from every other machine) is irrelevant by construction.+ const t1 = performance.now();+ let rec = { i, t1, total: -1, status: 0, id: null, timing: {} };+ try {+ const r = await fetch(URL_BASE + "/api/sandboxes", {+ method: "POST",+ headers: { "x-api-key": KEY, "content-type": "application/json" },+ body: "{}",+ });+ const text = await r.text();+ rec.total = performance.now() - t1;+ rec.status = r.status;+ rec.timing = parseTiming(r.headers.get("server-timing"));+ rec.colo = (r.headers.get("cf-ray") ?? "").split("-")[1] ?? "?";+ try {+ rec.id = JSON.parse(text).sandboxID ?? null;+ } catch {+ rec.body = text.slice(0, 120);+ }+ } catch (e) {+ rec.total = performance.now() - t1;+ rec.status = -1;+ rec.body = String(e).slice(0, 120);+ }+ return rec;+}++const t0 = performance.now();+let recs;+if (MODE === "seq") {+ recs = [];+ for (let i = 0; i < N; i++) recs.push(await one(i));+} else {+ recs = await Promise.all(Array.from({ length: N }, (_, i) => one(i)));+}+const wall = performance.now() - t0;++const ok = recs.filter((r) => r.status === 201 && r.id);+const q = (a, p) => {+ const s = [...a].sort((x, y) => x - y);+ return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : -1;+};+const f = (n) => (n < 0 ? "-" : n.toFixed(0));+const stat = (name, v) =>+ `${name.padEnd(14)} n=${String(v.length).padStart(4)} p50 ${f(q(v, 0.5)).padStart(6)} p95 ${f(q(v, 0.95)).padStart(6)} max ${f(Math.max(...v, -1)).padStart(6)}`;++console.log(`\n=== attribution ${MODE} N=${N} — ${ok.length}/${N} ok, wall ${f(wall)}ms ===\n`);+console.log(" " + stat("total (T4-T1)", ok.map((r) => r.total)));+console.log(" " + stat("hdl (edge)", ok.map((r) => r.timing.hdl ?? -1).filter((x) => x >= 0)));+console.log(" " + stat("cell (edge)", ok.map((r) => r.timing.cell ?? -1).filter((x) => x >= 0)));++// THE number: what no component on the path reports about itself.+const unacc = ok.filter((r) => r.timing.hdl !== undefined).map((r) => r.total - r.timing.hdl);+console.log(" " + stat("UNACCOUNTED", unacc));+console.log(+ `\n unaccounted = (T4-T1) - hdl — client<->edge wire + time queued before the\n` ++ ` Worker started running. No mark inside the handler can see this.\n`,+);++const colos = {};+for (const r of ok) colos[r.colo] = (colos[r.colo] ?? 0) + 1;+console.log(" colos:", Object.entries(colos).map(([k, v]) => `${k}=${v}`).join(" "));++const bad = recs.filter((r) => r.status !== 201);+if (bad.length) {+ const kinds = {};+ for (const b of bad) kinds[`${b.status} ${(b.body ?? "").slice(0, 60)}`] = (kinds[`${b.status} ${(b.body ?? "").slice(0, 60)}`] ?? 0) + 1;+ console.log("\n NON-201:", Object.entries(kinds).map(([k, v]) => `${v}x ${k}`).join(" | "));+}++writeFileSync(OUT, recs.map((r) => JSON.stringify(r)).join("\n") + "\n");+console.log(`\nwrote ${recs.length} records -> ${OUT}`);+console.log(`join with the CP: grep createtrace for each sandboxID to add cptotal.`);++// Clean up: these are real sandboxes.+await Promise.all(+ ok.map((r) =>+ fetch(`${URL_BASE}/api/sandboxes/${r.id}`, { method: "DELETE", headers: { "x-api-key": KEY } }).catch(() => {}),+ ),+);+console.log(`destroyed ${ok.length}`);diff --git a/benchmarks/tti/_exec_probe.mjs b/benchmarks/tti/_exec_probe.mjsnew file mode 100644index 00000000..d7c78eb1--- /dev/null+++ b/benchmarks/tti/_exec_probe.mjs@@ -0,0 +1,69 @@+// Decompose exec's fixed ~107ms leg.+//+// exec is load-INVARIANT (min 123.2ms sequential vs 124.5ms at burst-100), so+// contention is already ruled out — this is a structural floor. There are only+// three places it can be, and this probe separates them by construction rather+// than by inference:+//+// 1. connection setup CP->box TCP+TLS, paid per exec if the keep-alive pool+// isn't holding the connection (MaxIdleConnsPerHost: 4,+// IdleConnTimeout 90s in internal/awsvmlite/lite.go).+// 2. wire CP (westus2) <-> box (us-east-1), one round trip.+// 3. guest the command actually running inside the box.+//+// THE DISCRIMINATOR: run the SAME command N times against the SAME box, back to+// back. Exec #1 pays for whatever setup is needed; execs #2..N reuse it. If #1+// is much slower than the rest, the floor is setup and it is FIXABLE. If they+// are all equal, the floor is wire+guest and no amount of pooling touches it.+//+// The CP already logs the other half of the split for us --+// `awsvmlite: exec <id> rt=<ms> cmd=<ms>` at lite.go:549 -- where rt is the+// CP->box round trip and cmd is what the guest spent. Client total minus rt is+// then the client->edge->CP leg. Pull those lines after this run and every+// millisecond has a home.+import { Sandbox } from "@opencomputer/sdk";++const REPEATS = Number(process.env.REPEATS ?? 10);+const BOXES = Number(process.env.BOXES ?? 3);+const CMD = process.env.CMD ?? "node -v";++const q = (a, p) => { const s = [...a].sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : 0; };+const f = (n) => n.toFixed(1);++const rows = [];+for (let b = 0; b < BOXES; b++) {+ const tc = performance.now();+ const sb = await Sandbox.create({});+ const createMs = performance.now() - tc;+ const seq = [];+ for (let i = 0; i < REPEATS; i++) {+ const t = performance.now();+ let err = null;+ try { await sb.exec.run(CMD); } catch (e) { err = String(e).slice(0, 60); }+ seq.push({ i, ms: performance.now() - t, err });+ }+ rows.push({ box: b, id: sb.sandboxId ?? sb.id ?? "?", createMs, seq });+ console.log(`box ${b} (${sb.sandboxId ?? sb.id}) create ${f(createMs)}ms execs: ${seq.map((s) => f(s.ms)).join(" ")}`);+ try { await sb.destroy(); } catch {}+}++console.log(`\n=== EXEC FLOOR: same box, ${REPEATS} back-to-back execs, ${BOXES} boxes ===`);+const byIdx = [];+for (let i = 0; i < REPEATS; i++) byIdx.push(rows.map((r) => r.seq[i]?.ms).filter((x) => x != null));+console.log("exec# p50 min (n)");+byIdx.forEach((v, i) => {+ if (!v.length) return;+ console.log(` ${String(i + 1).padStart(2)} ${f(q(v, 0.5)).padStart(7)}ms ${f(Math.min(...v)).padStart(8)}ms ${v.length}`);+});++const first = byIdx[0] ?? [];+const rest = byIdx.slice(1).flat();+if (first.length && rest.length) {+ const d = q(first, 0.5) - q(rest, 0.5);+ console.log(`\nfirst-exec premium: ${f(d)}ms (first p50 ${f(q(first, 0.5))} vs repeat p50 ${f(q(rest, 0.5))})`);+ console.log(d > 25+ ? " => setup-bound. The connection is NOT being reused across the first exec."+ : " => NOT setup. The floor is wire + guest; connection pooling cannot move it.");+}+const ids = rows.map((r) => r.id).join(" ");+console.log(`\nsandbox ids for journal join: ${ids}`);diff --git a/benchmarks/tti/_ledger.mjs b/benchmarks/tti/_ledger.mjsnew file mode 100644index 00000000..aae2a830--- /dev/null+++ b/benchmarks/tti/_ledger.mjs@@ -0,0 +1,173 @@+// A complete ledger for one create. Every millisecond gets a named home and the+// segments SUM TO TOTAL — there is no residual bucket, on purpose. We are+// hunting time; a bucket called "other" is where the answer goes to hide, and it+// has already hidden there twice.+//+// Four hypotheses have died against real measurements: TLS handshakes (batching+// 26 creates into one request moved `cell` 126->132ms), CP compute (42us),+// edge CPU (p50 1ms), and distance (constant; cannot explain 4x between+// sequential and burst on one path). What is left has to be somewhere in here.+//+// THE LEDGER (client clock unless noted):+//+// connect DNS + TCP + TLS. undici diagnostics. DIRECT+// req_wire client -> colo. derived from RTT. DERIVED+// colo_admit bytes at colo -> our handler starts running. DERIVED+// hdl handler entry -> return. edge clock. DIRECT+// auth/ctx/gatecell/capmint existing marks. DIRECT+// cell edge's fetch to the CP, round trip. DIRECT+// cp_total CP handler, CP clock, joined by sandboxID. DIRECT+// cp_wire cell - cp_total: edge<->CP network + CP admission. DIRECT+// hdl_other hdl minus its own marks. edge clock. DIRECT+// resp_wire handler returns -> client sees headers. DERIVED+// body_read headers -> body complete. DIRECT+//+// WHY THE DERIVED ONES ARE NOT GUESSES. Every DIRECT quantity is a difference of+// two readings taken by the SAME machine, so clock skew cancels and no NTP+// assumption enters anywhere. For the wire, TLS 1.3 completes in about two round+// trips, so a socket we actually open measures the path's RTT for us — we do not+// have to assume it. req_wire and resp_wire each take half. What remains after+// subtracting everything measured is colo_admit, and that is a real physical+// interval (bytes have arrived at Cloudflare; our code has not been given a CPU+// yet), not a write-off. It is also the only load-DEPENDENT term: wire and TLS+// do not care how many requests are in flight, contention does. That is what+// makes the sequential run the control — run both and colo_admit is the term+// that moves.+import diagnostics from "node:diagnostics_channel";+import { writeFileSync } from "node:fs";++const BASE = process.env.OPENCOMPUTER_API_URL ?? "https://app2.opensandbox.ai";+const KEY = process.env.OPENCOMPUTER_API_KEY;+const N = Number(process.env.N ?? 100);+const MODE = process.env.MODE ?? "burst";+const OUT = process.env.OUT ?? "/tmp/ledger.ndjson";+if (!KEY) { console.error("set OPENCOMPUTER_API_KEY"); process.exit(1); }++// ── connect timing, straight from undici ──────────────────────────────────+const connects = [];+const startedAt = new Map();+try {+ diagnostics.subscribe("undici:client:connectStart", (e) => startedAt.set(e, performance.now()));+ diagnostics.subscribe("undici:client:connected", (e) => {+ const t = startedAt.get(e);+ if (t !== undefined) { connects.push(performance.now() - t); startedAt.delete(e); }+ });+} catch { /* fall back to assuming reuse; reported as such */ }++function parseTiming(h) {+ const out = {};+ for (const p of (h ?? "").split(",")) {+ const m = p.trim().match(/^([a-z0-9_]+);dur=([0-9.]+)/i);+ if (m) out[m[1]] = Number(m[2]);+ }+ return out;+}++async function one(i) {+ const t0 = performance.now();+ const r = { i, status: 0, id: null, total: -1, headers: -1, body_read: -1, timing: {} };+ try {+ const resp = await fetch(BASE + "/api/sandboxes", {+ method: "POST",+ headers: { "x-api-key": KEY, "content-type": "application/json" },+ body: "{}",+ });+ // fetch resolves on HEADERS. Timing this separately from the body split the+ // return leg instead of lumping transit and read together.+ r.headers = performance.now() - t0;+ const text = await resp.text();+ r.total = performance.now() - t0;+ r.body_read = r.total - r.headers;+ r.status = resp.status;+ r.timing = parseTiming(resp.headers.get("server-timing"));+ r.colo = (resp.headers.get("cf-ray") ?? "").split("-")[1] ?? "?";+ try { r.id = JSON.parse(text).sandboxID ?? null; } catch { r.err = text.slice(0, 100); }+ } catch (e) {+ r.total = performance.now() - t0; r.status = -1; r.err = String(e).slice(0, 100);+ }+ return r;+}++const wall0 = performance.now();+let recs;+if (MODE === "seq") { recs = []; for (let i = 0; i < N; i++) recs.push(await one(i)); }+else recs = await Promise.all(Array.from({ length: N }, (_, i) => one(i)));+const wall = performance.now() - wall0;++const ok = recs.filter((r) => r.status === 201 && r.id);+const q = (a, p) => { const s = [...a].sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : 0; };+const f = (n) => n.toFixed(1);++// RTT, measured directly rather than inferred. A TCP connect to the same host+// and port is exactly one round trip (SYN -> SYN/ACK), so this is the cleanest+// possible reading of the wire and it does not depend on anyone's reporting.+// Sampled several times and taken at the median so a single scheduling hiccup+// cannot set the floor for the whole ledger.+//+// This matters because if RTT were left at zero, the wire would silently fall+// into colo_admit and we would "find" queueing that was really just the network.+async function measureRTT(host, port, samples = 7) {+ const { connect } = await import("node:net");+ const out = [];+ for (let i = 0; i < samples; i++) {+ const t = performance.now();+ await new Promise((res) => {+ const s = connect({ host, port }, () => { out.push(performance.now() - t); s.destroy(); res(); });+ s.on("error", () => { s.destroy(); res(); });+ s.setTimeout(3000, () => { s.destroy(); res(); });+ });+ }+ return out.length ? out.sort((a, b) => a - b)[Math.floor(out.length / 2)] : 0;+}+const rtt = await measureRTT(new URL(BASE).hostname, 443);+const connectP50 = connects.length ? q(connects, 0.5) : 0;++// Build the per-request ledger. colo_admit is defined as the remainder so the+// column sums to total EXACTLY — that identity is the point: nothing is dropped.+for (const r of ok) {+ const t = r.timing;+ r.seg = {+ connect: connects.length ? connectP50 : 0,+ req_wire: rtt / 2,+ resp_wire: rtt / 2,+ hdl: t.hdl ?? 0,+ body_read: r.body_read,+ };+ r.seg.colo_admit = r.total - (r.seg.connect + r.seg.req_wire + r.seg.resp_wire + r.seg.hdl + r.seg.body_read);+ r.hdl_marks = {+ auth: t.auth ?? 0, ctx: t.ctx ?? 0, gatecell: t.gatecell ?? 0,+ capmint: t.capmint ?? 0, cell: t.cell ?? 0, cellbody: t.cellbody ?? 0,+ };+ const named = Object.values(r.hdl_marks).reduce((a, b) => a + b, 0);+ r.hdl_marks.hdl_other = (t.hdl ?? 0) - named;+}++console.log(`\n=== LEDGER ${MODE} N=${N} — ${ok.length}/${N} ok, wall ${f(wall)}ms ===`);+console.log(`TCP RTT to origin (median of 7 direct connects): ${f(rtt)}ms [sockets opened this run: ${connects.length}, p50 handshake ${f(connectP50)}ms]\n`);++const SEGS = ["connect", "req_wire", "colo_admit", "hdl", "resp_wire", "body_read"];+console.log("SEGMENT p50 p95 share(p50)");+const totP50 = q(ok.map((r) => r.total), 0.5);+for (const s of SEGS) {+ const v = ok.map((r) => r.seg[s]);+ console.log(` ${s.padEnd(14)} ${f(q(v, 0.5)).padStart(7)}ms ${f(q(v, 0.95)).padStart(8)}ms ${((q(v, 0.5) / totP50) * 100).toFixed(0).padStart(3)}%`);+}+console.log(` ${"TOTAL".padEnd(14)} ${f(totP50).padStart(7)}ms ${f(q(ok.map((r) => r.total), 0.95)).padStart(8)}ms 100%`);+const sumP50 = SEGS.reduce((a, s) => a + q(ok.map((r) => r.seg[s]), 0.5), 0);+console.log(` (segments sum ${f(sumP50)}ms vs total ${f(totP50)}ms — per-request identity is exact)`);++console.log("\nINSIDE hdl (edge clock):");+for (const k of ["auth", "ctx", "gatecell", "capmint", "cell", "cellbody", "hdl_other"]) {+ const v = ok.map((r) => r.hdl_marks[k]);+ console.log(` ${k.padEnd(14)} ${f(q(v, 0.5)).padStart(7)}ms ${f(q(v, 0.95)).padStart(8)}ms`);+}++console.log("\ncolos:", Object.entries(ok.reduce((a, r) => ((a[r.colo] = (a[r.colo] ?? 0) + 1), a), {})).map(([k, v]) => `${k}=${v}`).join(" "));+const bad = recs.filter((r) => r.status !== 201);+if (bad.length) console.log(`NON-201: ${bad.length}`, [...new Set(bad.map((b) => `${b.status} ${(b.err ?? "").slice(0, 60)}`))].slice(0, 3));++writeFileSync(OUT, recs.map((r) => JSON.stringify(r)).join("\n") + "\n");+console.log(`\nwrote ${recs.length} -> ${OUT} (join cell vs cp_total by sandboxID from the CP journal)`);++await Promise.all(ok.map((r) => fetch(`${BASE}/api/sandboxes/${r.id}`, { method: "DELETE", headers: { "x-api-key": KEY } }).catch(() => {})));+console.log(`destroyed ${ok.length}`);diff --git a/benchmarks/tti/_ledger_sdk.mjs b/benchmarks/tti/_ledger_sdk.mjsnew file mode 100644index 00000000..12e09c17--- /dev/null+++ b/benchmarks/tti/_ledger_sdk.mjs@@ -0,0 +1,148 @@+// The same ledger, but driven by the REAL SDK — because the raw-fetch ledger+// answers "where does a create spend its time", and the question that actually+// matters is "where does the BENCHMARK's time go". Those differ: the SDK adds+// its own client, its own connection pool, and an exec leg the raw harness never+// touches.+//+// Method is identical to _ledger.mjs: every segment is a difference of two+// readings taken by the same machine, RTT is measured directly with a TCP+// connect, and the segments sum to the total. Nothing is written off.+//+// The one addition is scope. The raw ledger measured create only; the benchmark+// measures create + exec, so both legs get their own ledger here and the TTI is+// reported as the sum the leaderboard would see.+import diagnostics from "node:diagnostics_channel";+import { writeFileSync } from "node:fs";+import { Sandbox } from "@opencomputer/sdk";++const BASE = process.env.OPENCOMPUTER_API_URL ?? "https://app2.opensandbox.ai";+const N = Number(process.env.N ?? 100);+const MODE = process.env.MODE ?? "burst";+const CMD = process.env.CMD ?? "node -v";+const OUT = process.env.OUT ?? "/tmp/ledger_sdk.ndjson";++const connects = [];+const startedAt = new Map();+try {+ diagnostics.subscribe("undici:client:connectStart", (e) => startedAt.set(e, performance.now()));+ diagnostics.subscribe("undici:client:connected", (e) => {+ const t = startedAt.get(e);+ if (t !== undefined) { connects.push(performance.now() - t); startedAt.delete(e); }+ });+} catch { /* reported as zero sockets below */ }++function parseTiming(h) {+ const out = {};+ for (const p of (h ?? "").split(",")) {+ const m = p.trim().match(/^([a-z0-9_]+);dur=([0-9.]+)/i);+ if (m) out[m[1]] = Number(m[2]);+ }+ return out;+}++// Wrap fetch to capture per-request server-timing and the headers/body split.+// The SDK calls global fetch, so this sees exactly what the SDK sees — no+// parallel code path that might behave differently under load.+const calls = [];+const realFetch = globalThis.fetch;+globalThis.fetch = async function (input, init) {+ const url = typeof input === "string" ? input : (input?.url ?? String(input));+ const t0 = performance.now();+ const rec = { path: url.replace(/^https?:\/\/[^/]+/, "").split("?")[0], method: init?.method ?? "GET", start: t0, headers: -1, total: -1, timing: {}, status: 0 };+ calls.push(rec);+ const resp = await realFetch(input, init);+ rec.headers = performance.now() - t0;+ rec.status = resp.status;+ rec.timing = parseTiming(resp.headers.get("server-timing"));+ rec.colo = (resp.headers.get("cf-ray") ?? "").split("-")[1] ?? "?";+ // Read the body through a clone so the SDK still gets an unconsumed stream.+ const clone = resp.clone();+ void clone.text().then(() => { rec.total = performance.now() - t0; }).catch(() => {});+ return resp;+};++async function measureRTT(host, port, samples = 7) {+ const { connect } = await import("node:net");+ const out = [];+ for (let i = 0; i < samples; i++) {+ const t = performance.now();+ await new Promise((res) => {+ const s = connect({ host, port }, () => { out.push(performance.now() - t); s.destroy(); res(); });+ s.on("error", () => { s.destroy(); res(); });+ s.setTimeout(3000, () => { s.destroy(); res(); });+ });+ }+ return out.length ? out.sort((a, b) => a - b)[Math.floor(out.length / 2)] : 0;+}++const iters = [];+async function one(i) {+ const t = { i, create: -1, exec: -1, tti: -1, err: null };+ const s = performance.now();+ let sb;+ try {+ sb = await Sandbox.create({});+ t.create = performance.now() - s;+ const e = performance.now();+ await sb.exec.run(CMD);+ t.exec = performance.now() - e;+ t.tti = performance.now() - s;+ } catch (err) { t.err = String(err).slice(0, 90); }+ iters.push(t);+ try { if (sb) await sb.destroy(); } catch {}+}++// Let the SDK's import-time connection prewarm finish so it is not racing the+// measurement; those requests are dropped from the window below.+await new Promise((r) => setTimeout(r, 2000));+const rtt = await measureRTT(new URL(BASE).hostname, 443);+calls.length = 0;+connects.length = 0;++const wall0 = performance.now();+if (MODE === "seq") { for (let i = 0; i < N; i++) await one(i); }+else await Promise.all(Array.from({ length: N }, (_, i) => one(i)));+const wall = performance.now() - wall0;++const q = (a, p) => { const s = [...a].sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : 0; };+const f = (n) => n.toFixed(1);+const ok = iters.filter((x) => x.err === null);++console.log(`\n=== SDK LEDGER ${MODE} N=${N} — ${ok.length}/${N} ok, wall ${f(wall)}ms ===`);+console.log(`TCP RTT (median of 7 direct connects): ${f(rtt)}ms [sockets opened during run: ${connects.length}]\n`);+console.log("AS THE BENCHMARK SEES IT:");+console.log(` create p50 ${f(q(ok.map((x) => x.create), 0.5)).padStart(7)}ms p95 ${f(q(ok.map((x) => x.create), 0.95)).padStart(7)}ms`);+console.log(` exec p50 ${f(q(ok.map((x) => x.exec), 0.5)).padStart(7)}ms p95 ${f(q(ok.map((x) => x.exec), 0.95)).padStart(7)}ms`);+console.log(` TTI p50 ${f(q(ok.map((x) => x.tti), 0.5)).padStart(7)}ms p95 ${f(q(ok.map((x) => x.tti), 0.95)).padStart(7)}ms`);++// Per-endpoint ledger. colo_admit is the remainder, so each row closes exactly.+const groups = new Map();+for (const c of calls) {+ const k = `${c.method} ${c.path.replace(/\/sb-[a-z0-9]+/g, "/:id")}`;+ if (!groups.has(k)) groups.set(k, []);+ groups.get(k).push(c);+}+for (const [k, v] of [...groups.entries()].sort((a, b) => b[1].length - a[1].length)) {+ const done = v.filter((c) => c.headers >= 0);+ if (!done.length) continue;+ const seg = done.map((c) => {+ const hdl = c.timing.hdl ?? c.timing.origin ?? 0;+ return { total: c.headers, hdl, wire: rtt, colo_admit: c.headers - hdl - rtt };+ });+ console.log(`\n${k} n=${done.length}`);+ console.log(` total(headers) p50 ${f(q(seg.map((s) => s.total), 0.5)).padStart(7)}ms`);+ console.log(` wire p50 ${f(rtt).padStart(7)}ms`);+ console.log(` hdl (edge) p50 ${f(q(seg.map((s) => s.hdl), 0.5)).padStart(7)}ms`);+ console.log(` colo_admit p50 ${f(q(seg.map((s) => s.colo_admit), 0.5)).padStart(7)}ms <-- queued before our code ran`);+ const marks = [...new Set(done.flatMap((c) => Object.keys(c.timing)))].sort();+ const detail = marks.map((m) => `${m}=${f(q(done.map((c) => c.timing[m] ?? 0), 0.5))}`).join(" ");+ if (detail) console.log(` marks p50: ${detail}`);+}++const colos = calls.reduce((a, c) => (c.colo ? ((a[c.colo] = (a[c.colo] ?? 0) + 1), a) : a), {});+console.log("\ncolos:", Object.entries(colos).map(([k, v]) => `${k}=${v}`).join(" "));+const errs = iters.filter((x) => x.err);+if (errs.length) console.log("ERRORS:", [...new Set(errs.map((e) => e.err))].slice(0, 3));++writeFileSync(OUT, JSON.stringify({ rtt, iters, calls }, null, 0));+console.log(`\nwrote -> ${OUT}`);diff --git a/benchmarks/tti/_sweep.mjs b/benchmarks/tti/_sweep.mjsnew file mode 100644index 00000000..0f25d1d6--- /dev/null+++ b/benchmarks/tti/_sweep.mjs@@ -0,0 +1,166 @@+// Does colo_admit belong to Cloudflare, or is some of it our own client?+//+// colo_admit is a DERIVED term (total - hdl - rtt - body_read), so anything the+// client does between "we called fetch" and "the bytes left the NIC" lands in it+// silently. That is exactly the write-off we refuse to make, so it has to be+// excluded by measurement, not by argument. Two independent tests:+//+// TEST A -- does it scale with N? Client-side send queueing and Cloudflare+// admission both grow with concurrency, so this alone does not separate them --+// but the SHAPE does. Client queueing through a fixed connection pool is a+// step function in N/poolsize; colo admission is smoother. And if colo_admit+// were flat in N it would be neither, which would falsify the whole finding.+//+// TEST B -- the real discriminator. Run the same N with each request on its OWN+// undici Agent (its own connection pool, its own socket). If colo_admit is+// client-side pool contention it collapses; if it is Cloudflare it does not+// move. Sockets are counted with an explicit connect hook rather than the+// diagnostics channel, which silently reported `sockets opened: 0` last time and+// so proved nothing.+import { writeFileSync } from "node:fs";+import { Agent, buildConnector, fetch as uFetch } from "undici";++const BASE = process.env.OPENCOMPUTER_API_URL ?? "https://app2.opensandbox.ai";+const KEY = process.env.OPENCOMPUTER_API_KEY;+const LEVELS = (process.env.LEVELS ?? "10,25,50,100").split(",").map(Number);+const OUT = process.env.OUT ?? "/tmp/sweep.ndjson";+if (!KEY) { console.error("set OPENCOMPUTER_API_KEY"); process.exit(1); }++const q = (a, p) => { const s = [...a].sort((x, y) => x - y); return s.length ? s[Math.min(s.length - 1, Math.floor(p * s.length))] : 0; };+const f = (n) => n.toFixed(1);++function parseTiming(h) {+ const out = {};+ for (const p of (h ?? "").split(",")) {+ const m = p.trim().match(/^([a-z0-9_]+);dur=([0-9.]+)/i);+ if (m) out[m[1]] = Number(m[2]);+ }+ return out;+}++// Count sockets for real, by wrapping undici's own connector. Every new+// connection goes through here by construction, so unlike the diagnostics+// channel this cannot silently report zero and leave the wire unaccounted for.+let socketsOpened = 0;+let connectMs = [];+const baseConnector = buildConnector({});+const countingConnector = (opts, cb) => {+ const t = performance.now();+ return baseConnector(opts, (err, socket) => {+ if (!err) { socketsOpened++; connectMs.push(performance.now() - t); }+ cb(err, socket);+ });+};+const newAgent = (connections) => new Agent({ connections, connect: countingConnector });++async function measureRTT(host, port, samples = 7) {+ const { connect } = await import("node:net");+ const out = [];+ for (let i = 0; i < samples; i++) {+ const t = performance.now();+ await new Promise((res) => {+ const s = connect({ host, port }, () => { out.push(performance.now() - t); s.destroy(); res(); });+ s.on("error", () => { s.destroy(); res(); });+ s.setTimeout(3000, () => { s.destroy(); res(); });+ });+ }+ return out.length ? out.sort((a, b) => a - b)[Math.floor(out.length / 2)] : 0;+}++const rtt = await measureRTT(new URL(BASE).hostname, 443);+console.log(`TCP RTT (median of 7 direct connects): ${f(rtt)}ms\n`);++async function one(dispatcher) {+ const t0 = performance.now();+ const r = { status: 0, id: null, total: -1, headers: -1, timing: {} };+ try {+ const resp = await uFetch(BASE + "/api/sandboxes", {+ method: "POST",+ headers: { "x-api-key": KEY, "content-type": "application/json" },+ body: "{}",+ dispatcher,+ });+ r.headers = performance.now() - t0;+ const text = await resp.text();+ r.total = performance.now() - t0;+ r.body_read = r.total - r.headers;+ r.status = resp.status;+ r.timing = parseTiming(resp.headers.get("server-timing"));+ r.colo = (resp.headers.get("cf-ray") ?? "").split("-")[1] ?? "?";+ try { r.id = JSON.parse(text).sandboxID ?? null; } catch { r.err = text.slice(0, 80); }+ } catch (e) {+ r.total = performance.now() - t0; r.status = -1; r.err = String(e).slice(0, 80);+ }+ return r;+}++const all = [];+async function run(label, n, perRequestAgent) {+ socketsOpened = 0;+ connectMs = [];+ const shared = perRequestAgent ? null : newAgent(128);+ const agents = [];+ const mk = () => {+ if (!perRequestAgent) return shared;+ const a = newAgent(1);+ agents.push(a);+ return a;+ };+ const t0 = performance.now();+ const recs = await Promise.all(Array.from({ length: n }, () => one(mk())));+ const wall = performance.now() - t0;+ const ok = recs.filter((r) => r.status === 201 && r.id);+ for (const r of ok) {+ r.hdl = r.timing.hdl ?? 0;+ r.colo_admit = r.total - r.hdl - rtt - (r.body_read ?? 0);+ }+ const row = {+ label, n, perRequestAgent, ok: ok.length, wall,+ total: q(ok.map((r) => r.total), 0.5),+ hdl: q(ok.map((r) => r.hdl), 0.5),+ cell: q(ok.map((r) => r.timing.cell ?? 0), 0.5),+ colo_admit: q(ok.map((r) => r.colo_admit), 0.5),+ colo_admit_p95: q(ok.map((r) => r.colo_admit), 0.95),+ colo_admit_min: ok.length ? Math.min(...ok.map((r) => r.colo_admit)) : 0,+ sockets: socketsOpened,+ connect_p50: connectMs.length ? q(connectMs, 0.5) : 0,+ colos: [...new Set(ok.map((r) => r.colo))].join("/"),+ };+ all.push(row);+ console.log(`${label.padEnd(22)} n=${String(n).padStart(3)} ok=${String(row.ok).padStart(3)} total ${f(row.total).padStart(7)} hdl ${f(row.hdl).padStart(6)} cell ${f(row.cell).padStart(6)} colo_admit ${f(row.colo_admit).padStart(7)} (min ${f(row.colo_admit_min)} p95 ${f(row.colo_admit_p95)}) sockets=${row.sockets}@${f(row.connect_p50)}ms colo=${row.colos}`);+ const bad = recs.filter((r) => r.status !== 201);+ if (bad.length) console.log(` NON-201 ${bad.length}: ${[...new Set(bad.map((b) => `${b.status} ${(b.err ?? "").slice(0, 50)}`))].slice(0, 2).join(" | ")}`);+ // Give the boxes back before the next level so pool depth is not the variable.+ await Promise.all(ok.map((r) => uFetch(`${BASE}/api/sandboxes/${r.id}`, { method: "DELETE", headers: { "x-api-key": KEY } }).catch(() => {})));+ for (const a of agents) { try { await a.close(); } catch {} }+ if (shared) { try { await shared.close(); } catch {} }+ await new Promise((r) => setTimeout(r, Number(process.env.SETTLE_MS ?? 8000)));+ return row;+}++console.log("TEST A -- shared pool, concurrency swept:");+for (const n of LEVELS) await run(`shared N=${n}`, n, false);++console.log("\nTEST B -- one dedicated connection pool per request (client contention removed):");+for (const n of LEVELS) await run(`per-req N=${n}`, n, true);++console.log("\n=== VERDICT ===");+for (const n of LEVELS) {+ const a = all.find((r) => !r.perRequestAgent && r.n === n);+ const b = all.find((r) => r.perRequestAgent && r.n === n);+ if (!a || !b) continue;+ // A level where every create 503'd measured nothing. Printing its 0.0 beside+ // real rows would read as "admission was instant", which is the opposite of+ // the truth, so say VOID out loud instead.+ if (!a.ok || !b.ok) {+ console.log(`N=${String(n).padStart(3)} VOID — ${!a.ok ? "shared" : "per-request"} level had 0 successful creates (pool drained / capacity gate)`);+ continue;+ }+ const d = a.colo_admit - b.colo_admit;+ console.log(`N=${String(n).padStart(3)} shared colo_admit ${f(a.colo_admit).padStart(7)}ms per-request ${f(b.colo_admit).padStart(7)}ms delta ${f(d).padStart(7)}ms`);+}+console.log("\nIf per-request tracks shared, colo_admit is NOT client pool contention.");+console.log("If per-request collapses toward the sequential floor, it was ours all along.");++writeFileSync(OUT, all.map((r) => JSON.stringify(r)).join("\n") + "\n");+console.log(`\nwrote -> ${OUT}`);diff --git a/cloudflare-workers/api-edge/src/create_batch.test.ts b/cloudflare-workers/api-edge/src/create_batch.test.tsnew file mode 100644index 00000000..35575cee--- /dev/null+++ b/cloudflare-workers/api-edge/src/create_batch.test.ts@@ -0,0 +1,242 @@+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";+import { createViaCell, __resetCreateBatchState } from "./create_batch";++const BASE = "https://cp.example.com";+const TOKEN = "tok-a";+/** Captured before any test stubs setTimeout, so a stub can still schedule. */+const realSetTimeout = globalThis.setTimeout;++interface Sent {+ url: string;+ auth: string;+ body: string;+}++/**+ * Stands in for the control plane. `hold` lets a test keep creates in flight,+ * which is the only way to reach the batching path: a create with nothing else+ * outstanding is deliberately sent alone.+ */+function installFetch(opts: {+ hold?: Promise<void>;+ batchStatus?: number;+ batchBody?: (items: unknown[]) => unknown;+}): { sent: Sent[] } {+ const sent: Sent[] = [];+ vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {+ const body = String(init.body);+ sent.push({ url, auth: String((init.headers as Record<string, string>).authorization), body });+ if (url.endsWith("/create-batch")) {+ if (opts.hold) await opts.hold;+ const status = opts.batchStatus ?? 200;+ if (status !== 200) return new Response("nope", { status });+ const items = (JSON.parse(body) as { items: unknown[] }).items;+ const payload = opts.batchBody+ ? opts.batchBody(items)+ : { results: items.map((it) => ({ status: 201, body: { echo: it } })) };+ return new Response(JSON.stringify(payload), { status: 200 });+ }+ if (opts.hold) await opts.hold;+ // Tolerant of a non-JSON body: one test deliberately sends one.+ let echo: unknown = body;+ try {+ echo = JSON.parse(body || "{}");+ } catch {+ /* keep the raw text */+ }+ return new Response(JSON.stringify({ echo }), { status: 201 });+ });+ return { sent };+}++beforeEach(() => __resetCreateBatchState());+afterEach(() => vi.unstubAllGlobals());++describe("createViaCell", () => {+ // Sequential traffic is already fast and has nobody to batch with. If it ever+ // starts paying a coalescing window, this fix has made the common case worse.+ it("sends a lone create immediately and unbatched", async () => {+ const { sent } = installFetch({});+ const r = await createViaCell(BASE, TOKEN, '{"n":1}', true);+ expect(r.batched).toBe(false);+ expect(r.batchSize).toBe(1);+ expect(r.waitMs).toBe(0);+ expect(sent).toHaveLength(1);+ expect(sent[0].url).toBe(BASE + "/internal/sandboxes/create");+ });++ // The whole point: N concurrent creates cost ONE connection, not N.+ it("coalesces concurrent creates into a single request", async () => {+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { sent } = installFetch({ hold });++ const first = createViaCell(BASE, TOKEN, '{"n":0}', true);+ const rest = Array.from({ length: 20 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));+ await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));+ release();+ const results = await Promise.all([first, ...rest]);++ // One lone create (it arrived first, with nothing in flight) plus exactly one+ // batch carrying the other twenty.+ expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(1);+ expect(sent.filter((s) => s.url.endsWith("/sandboxes/create"))).toHaveLength(1);+ expect(results.filter((r) => r.batched)).toHaveLength(20);+ expect(results[1].batchSize).toBe(20);+ });++ // Results are positional. A shuffle hands caller A the sandbox caller B asked+ // for — silently, and with no error anywhere.+ it("returns each waiter its own result", async () => {+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { sent } = installFetch({ hold });++ const first = createViaCell(BASE, TOKEN, '{"n":0}', true);+ const rest = Array.from({ length: 10 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));+ await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));+ release();+ const results = await Promise.all([first, ...rest]);++ results.forEach((r, i) => {+ expect(JSON.parse(r.text).echo).toEqual({ n: i });+ });+ });++ // The CP verifies the cap-token ONCE and every item in the batch inherits+ // those claims. Two callers sharing a request would mean one org's create+ // authorized by another org's token.+ it("never batches creates carrying different cap-tokens", async () => {+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { sent } = installFetch({ hold });++ // n=0 arrives with nothing in flight and so goes out alone; the rest split+ // into one batch per token.+ const all = [+ createViaCell(BASE, "tok-a", '{"n":0}', true),+ createViaCell(BASE, "tok-a", '{"n":1}', true),+ createViaCell(BASE, "tok-a", '{"n":2}', true),+ createViaCell(BASE, "tok-b", '{"n":3}', true),+ createViaCell(BASE, "tok-b", '{"n":4}', true),+ ];+ await vi.waitFor(() => expect(sent.filter((s) => s.url.endsWith("/create-batch")).length).toBe(2));+ release();+ await Promise.all(all);++ for (const s of sent.filter((s) => s.url.endsWith("/create-batch"))) {+ const items = (JSON.parse(s.body) as { items: { n: number }[] }).items;+ const expected = s.auth === "Bearer tok-a" ? [1, 2] : [3, 4];+ expect(items.map((i) => i.n).sort()).toEqual(expected);+ }+ });++ // A failing envelope says nothing about the individual creates — none of them+ // ran. Every waiter must still get a real sandbox.+ it("falls back to single creates when the batch request fails", async () => {+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { sent } = installFetch({ hold, batchStatus: 500 });++ const first = createViaCell(BASE, TOKEN, '{"n":0}', true);+ const rest = Array.from({ length: 5 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));+ await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));+ release();+ const results = await Promise.all([first, ...rest]);++ expect(results.every((r) => r.status === 201)).toBe(true);+ results.forEach((r, i) => expect(JSON.parse(r.text).echo).toEqual({ n: i }));+ expect(sent.filter((s) => s.url.endsWith("/sandboxes/create"))).toHaveLength(6);+ });++ // A result count that does not match the item count means we cannot tell whose+ // sandbox is whose. Guessing is worse than redoing the work.+ it("discards a mismatched result set rather than guessing", async () => {+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { sent } = installFetch({ hold, batchBody: () => ({ results: [{ status: 201, body: {} }] }) });++ const first = createViaCell(BASE, TOKEN, '{"n":0}', true);+ const rest = Array.from({ length: 4 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));+ await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));+ release();+ const results = await Promise.all([first, ...rest]);++ results.forEach((r, i) => expect(JSON.parse(r.text).echo).toEqual({ n: i }));+ });++ // A control plane that predates the endpoint must not make every burst pay a+ // doomed batch on top of the fallback.+ it("stops batching after the endpoint 404s", async () => {+ let release!: () => void;+ let hold = new Promise<void>((r) => (release = r));+ const { sent } = installFetch({ hold, batchStatus: 404 });++ const burst = async (): Promise<void> => {+ const first = createViaCell(BASE, TOKEN, '{"n":0}', true);+ const rest = Array.from({ length: 3 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));+ await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));+ release();+ await Promise.all([first, ...rest]);+ };++ await burst();+ expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(1);++ hold = new Promise<void>((r) => (release = r));+ release();+ await burst();+ // Still one: the second burst never attempted the endpoint again.+ expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(1);+ });++ // The failure that took 18% of a burst-100 to HTTP 500 on dev: the request+ // owning a batch dies, so its timer never fires and its waiters are never+ // resolved. The Workers runtime then cancels every one of them as hung. No+ // waiter may depend on another request surviving — each must be able to+ // answer on its own.+ it("still answers every waiter when the batch never dispatches", async () => {+ const sent: string[] = [];+ vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {+ sent.push(url);+ return new Response(JSON.stringify({ echo: JSON.parse(String(init.body) || "{}") }), { status: 201 });+ });+ // Simulate the dead owner: the window timer is armed but never runs.+ vi.stubGlobal("setTimeout", ((fn: () => void, ms?: number) => {+ // Only the batch window is suppressed; each waiter's own deadline must+ // still fire, or this test would prove nothing.+ if (ms === 5) return 0 as unknown as ReturnType<typeof setTimeout>;+ return realSetTimeout(fn, ms);+ }) as typeof setTimeout);++ const first = createViaCell(BASE, TOKEN, '{"n":0}', true);+ const rest = Array.from({ length: 5 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));+ const results = await Promise.all([first, ...rest]);++ // Every waiter got a real create rather than hanging forever.+ expect(results).toHaveLength(6);+ results.forEach((r, i) => {+ expect(r.status).toBe(201);+ expect(JSON.parse(r.text).echo).toEqual({ n: i });+ });+ expect(sent.filter((u) => u.endsWith("/create-batch"))).toHaveLength(0);+ });++ // Item bodies are spliced into the envelope as raw JSON to stay byte-identical+ // to a single create. A body that is not a JSON object would corrupt every+ // other item in the batch, not just its own.+ it("sends an unparseable body on its own", async () => {+ let release!: () => void;+ const hold = new Promise<void>((r) => (release = r));+ const { sent } = installFetch({ hold });++ const first = createViaCell(BASE, TOKEN, '{"n":0}', true);+ const bad = createViaCell(BASE, TOKEN, "not json at all", true);+ await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));+ release();+ await Promise.all([first, bad]);++ expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(0);+ expect(sent.filter((s) => s.url.endsWith("/sandboxes/create"))).toHaveLength(2);+ });+});diff --git a/cloudflare-workers/api-edge/src/create_batch.ts b/cloudflare-workers/api-edge/src/create_batch.tsnew file mode 100644index 00000000..a838a0a6--- /dev/null+++ b/cloudflare-workers/api-edge/src/create_batch.ts@@ -0,0 +1,350 @@+// create_batch.ts — collapse a burst of concurrent creates into ONE request to+// the control plane.+//+// STATUS: BUILT, MEASURED, FALSIFIED. Gated behind the CREATE_BATCH env and+// DEFAULT OFF. Keep it that way unless something below changes.+//+// The hypothesis in "WHY" was tested on dev and did not survive. Coalescing+// worked exactly as designed — `cellbatch` p50 was 26 creates per request — and+// bought nothing: the `cell` mark was 132ms batched vs 126ms for a lone create.+// 26x fewer connections, no improvement, so the edge→cell hop is round-trip+// bound rather than connection bound. The burst cost turned out to be time spent+// queued BEFORE our handler is given a CPU, which no amount of batching touches.+//+// It is kept rather than deleted for two reasons: the CP endpoint is harmless+// and already deployed, and the "SURVIVING THE OWNER" section below documents a+// Workers constraint that cost us 18% of a burst to learn and that applies to+// any future cross-request coalescing.+//+// WHY (the original hypothesis — recorded because it was wrong, not because it+// was right). A burst of 100 creates costs ~115ms each in the create handler's `cell`+// mark while the CP answers every one of them in ~59us. Practically none of that+// hop is work: it is the connection. `cp-uswest2.opensandbox.ai` resolves to an+// Azure address that is NOT behind Cloudflare's proxy, so a Worker subrequest+// dials it directly and a concurrent burst opens a pile of fresh connections,+// each paying a TLS handshake to westus2. The same hop served serially is ~30ms+// — one warm connection, one round trip.+//+// The protocol knob that would fix this is not available to us: `fetch()` in a+// Worker exposes no way to force HTTP/2, and the zone-level "HTTP/2 to Origin"+// setting only applies to proxied hostnames, which this origin is not. So the+// only reliable way to stop paying ~100 handshakes is to stop making ~100+// requests. The CP side is POST /internal/sandboxes/create-batch.+//+// WHEN IT ENGAGES. A fixed coalescing window would tax every create, including+// the sequential ones that are already fast (~194ms end to end) and have nobody+// to batch with. So batching is gated on observed concurrency instead: a create+// that arrives when this isolate has none in flight is alone by definition and+// goes straight out, unchanged and undelayed. Only a create that arrives while+// another is already in flight joins a batch. Sequential traffic therefore never+// pays the window, and a burst self-clocks into it — the first create leaves+// immediately and its neighbours accumulate behind it.+//+// Coalescing is per-isolate on purpose. It needs no Durable Object, no shard+// map, and no cross-isolate coordination: an isolate can only batch requests it+// is already holding. If a burst spreads across several isolates each one+// batches its own share, which is a smaller win but never a wrong one.+//+// SURVIVING THE OWNER. Batching means one request's work answers several+// requests, and the Workers runtime is unforgiving about that: it cancels any+// request it decides "had hung and would never generate a response". A waiter+// whose result depends entirely on ANOTHER request's timer and fetch has no+// pending I/O of its own, so if that other request dies — cancelled client,+// abandoned connection, anything — its timer never fires, its waiters are never+// resolved, and the runtime kills every one of them. Measured on dev at+// burst-100: 18% of creates returned HTTP 500 (Cloudflare error 1101) that way,+// while burst-30 was clean, because one dead request takes its whole batch with+// it and bursts produce more of them.+//+// So no waiter may depend on another request surviving. Each one arms its own+// deadline in its own context and, if the batch has not answered by then, does+// its own single create. The batch becomes an optimisation that can fail+// silently instead of a shared point of failure.++import type { CreateCallResult } from "./create_batch_types";++// The window only ever delays a create that already has a peer in flight, so it+// trades a few ms of that create's latency for the whole burst's handshakes.+const BATCH_WINDOW_MS = 5;++// Mirrors maxBatchItems on the CP. Reaching it flushes early rather than+// truncating: no create is ever silently dropped from a batch.+const BATCH_MAX_ITEMS = 256;++// How long to stop trying after the CP rejects the endpoint itself (404/405 =+// a control plane that predates this). Without it every burst would pay a+// failed batch plus the full fallback, which is strictly worse than not+// batching at all.+const BATCH_DISABLE_MS = 60_000;++// How long a waiter will trust the batch before doing the work itself. Well+// clear of a healthy batch round trip (~30-130ms to the cell), so in normal+// operation this never fires; it exists so that a batch whose owning request+// died cannot hang anyone. The cost of it firing is one ordinary create.+const WAITER_DEADLINE_MS = 400;++interface Waiter {+ /** The exact bytes a single create would have sent. */+ body: string;+ resolve: (r: CreateCallResult) => void;+ reject: (e: unknown) => void;+ queuedAt: number;+ /**+ * Set once this waiter has an answer, from whichever path got there first.+ * The batch and the waiter's own deadline race, and both must be harmless+ * after the other has won.+ */+ settled: boolean;+}++interface OpenBatch {+ cellBase: string;+ capToken: string;+ waiters: Waiter[];+ timer: ReturnType<typeof setTimeout> | null;+}++const openBatches = new Map<string, OpenBatch>();++/** Creates this isolate is currently holding — the concurrency signal. */+let createsInFlight = 0;++/** Set when the CP tells us the batch endpoint does not exist. */+let batchDisabledUntil = 0;++/**+ * postCreate issues one ordinary single create, exactly as the handler did+ * before batching existed. Every fallback in this module lands here, so a+ * degraded batch path is never worse than no batch path.+ */+async function postCreate(cellBase: string, capToken: string, body: string): Promise<CreateCallResult> {+ const resp = await fetch(cellBase.replace(/\/$/, "") + "/internal/sandboxes/create", {+ method: "POST",+ headers: { authorization: "Bearer " + capToken, "content-type": "application/json" },+ body: body || "{}",+ });+ return { status: resp.status, text: await resp.text(), batched: false, batchSize: 1, waitMs: 0 };+}++/**+ * createViaCell is the entry point the create handler calls in place of its+ * direct fetch. It either sends immediately (nothing else in flight) or joins+ * the batch forming for this exact destination.+ */+export function createViaCell(+ cellBase: string,+ capToken: string,+ body: string,+ // Off unless the deployment turns it on. Measured on dev 2026-08-26 with a+ // settled 100/100 pool: coalescing worked (26 creates per request, p50) and+ // bought nothing — `cell` was 132ms batched vs 126ms for a lone create. That+ // says the edge->cell hop is not connection-bound after all; a batch of 26+ // just costs what the slowest of 26 pool claims costs. Kept behind a flag+ // rather than deleted so the A/B is one env change, not a redeploy.+ enabled: boolean,+): Promise<CreateCallResult> {+ createsInFlight++;+ const alone = createsInFlight === 1;+ const done = (): void => {+ createsInFlight--;+ };++ // Disabled, nothing else in flight, endpoint missing, or a body we could not+ // validate: take the untouched single-create path.+ if (!enabled || alone || Date.now() < batchDisabledUntil || !isJSONObject(body)) {+ return postCreate(cellBase, capToken, body).finally(done);+ }++ // The cap-token is the batch key, not just part of it. The CP verifies the+ // token ONCE for the batch and every item inherits those claims, so two+ // creates may only share a request if they would have presented byte-identical+ // credentials. Keying on the token makes that structural: a different org,+ // user, plan, runtime, or cell cannot land in the same batch.+ const key = cellBase + " " + capToken;++ let self: Waiter;+ const joined = new Promise<CreateCallResult>((resolve, reject) => {+ let batch = openBatches.get(key);+ if (!batch) {+ batch = { cellBase, capToken, waiters: [], timer: null };+ openBatches.set(key, batch);+ batch.timer = setTimeout(() => {+ void flush(key);+ }, BATCH_WINDOW_MS);+ }+ self = { body, resolve, reject, queuedAt: Date.now(), settled: false };+ batch.waiters.push(self);+ if (batch.waiters.length >= BATCH_MAX_ITEMS) void flush(key);+ });++ // The waiter's own timer, armed in the waiter's own request context. This is+ // what makes the batch non-fatal: whatever happens to the request that owns+ // the batch, this request still wakes up and still has work it can do.+ return withOwnDeadline(joined, () => {+ // Losing the race means the batch never answered — its owner is gone. Leave+ // the batch (if it has not dispatched, this also stops it creating a sandbox+ // nobody is waiting for) and do the create here, in this request's context.+ dropWaiter(key, self);+ console.error("create-batch: batch owner never answered, creating solo");+ return postCreate(cellBase, capToken, body);+ }).finally(done);+}++/**+ * withOwnDeadline resolves from `p` if it answers in time, otherwise from+ * `fallback` — with the timer living in the caller's own request context.+ */+async function withOwnDeadline(+ p: Promise<CreateCallResult>,+ fallback: () => Promise<CreateCallResult>,+): Promise<CreateCallResult> {+ const LATE = Symbol("late");+ let timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<typeof LATE>((resolve) => {+ timer = setTimeout(() => resolve(LATE), WAITER_DEADLINE_MS);+ });+ try {+ const winner = await Promise.race([p, deadline]);+ if (winner !== LATE) return winner;+ return await fallback();+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}++/**+ * dropWaiter removes a waiter from its batch if that batch has not dispatched+ * yet, so an abandoned waiter does not get a sandbox created for it that no one+ * will ever receive. A batch already on the wire cannot be recalled; that item's+ * result is simply discarded when it lands.+ */+function dropWaiter(key: string, w: Waiter): void {+ w.settled = true;+ const batch = openBatches.get(key);+ if (!batch) return;+ const i = batch.waiters.indexOf(w);+ if (i >= 0) batch.waiters.splice(i, 1);+ if (batch.waiters.length === 0) {+ if (batch.timer !== null) clearTimeout(batch.timer);+ openBatches.delete(key);+ }+}++/**+ * flush dispatches whatever has accumulated under `key`. It detaches the batch+ * from the map first, so creates arriving during the round trip start a fresh+ * one rather than joining a batch that is already on the wire.+ */+async function flush(key: string): Promise<void> {+ const batch = openBatches.get(key);+ if (!batch) return;+ openBatches.delete(key);+ if (batch.timer !== null) clearTimeout(batch.timer);++ const waiters = batch.waiters;+ // A batch of one is just a create wearing an envelope: send it as itself. This+ // is the common outcome when concurrency is low, and it keeps the near-idle+ // path free of any dependency on the batch endpoint.+ if (waiters.length === 1) {+ await settleIndividually(batch, waiters);+ return;+ }++ const started = Date.now();+ let results: unknown;+ try {+ const resp = await fetch(batch.cellBase.replace(/\/$/, "") + "/internal/sandboxes/create-batch", {+ method: "POST",+ headers: { authorization: "Bearer " + batch.capToken, "content-type": "application/json" },+ body: '{"items":[' + waiters.map((w) => w.body || "{}").join(",") + "]}",+ });+ if (resp.status === 404 || resp.status === 405) {+ // The control plane does not have the endpoint. Stop asking.+ batchDisabledUntil = Date.now() + BATCH_DISABLE_MS;+ console.log(`create-batch: endpoint absent on ${batch.cellBase} (${resp.status}), disabling for ${BATCH_DISABLE_MS}ms`);+ await settleIndividually(batch, waiters);+ return;+ }+ if (resp.status < 200 || resp.status >= 300) {+ // A failing envelope says nothing about the individual creates — none of+ // them ran. Retrying them singly is safe and is what would have happened+ // without batching.+ console.error(`create-batch: envelope status ${resp.status}, falling back to ${waiters.length} single creates`);+ await settleIndividually(batch, waiters);+ return;+ }+ results = ((await resp.json()) as { results?: unknown }).results;+ } catch (e) {+ console.error("create-batch: dispatch failed, falling back to single creates:", e);+ await settleIndividually(batch, waiters);+ return;+ }++ // Results are positional and the CP guarantees one per item. If that does not+ // hold we cannot tell whose sandbox is whose, and handing caller A the box+ // caller B asked for is far worse than being slow — so discard and redo.+ if (!Array.isArray(results) || results.length !== waiters.length) {+ console.error(`create-batch: got ${Array.isArray(results) ? results.length : "non-array"} results for ${waiters.length} items, falling back`);+ await settleIndividually(batch, waiters);+ return;+ }++ const elapsed = Date.now() - started;+ for (let i = 0; i < waiters.length; i++) {+ // Gave up while the batch was on the wire and is creating its own sandbox.+ // Its slot in the response is dead weight; dropping it is the only option,+ // since the create already happened at the cell.+ if (waiters[i].settled) continue;+ const r = results[i] as { status?: number; body?: unknown };+ waiters[i].settled = true;+ waiters[i].resolve({+ status: typeof r?.status === "number" ? r.status : 502,+ text: r?.body === undefined ? "{}" : JSON.stringify(r.body),+ batched: true,+ batchSize: waiters.length,+ waitMs: Date.now() - waiters[i].queuedAt - elapsed,+ });+ }+}++/** settleIndividually runs every waiter as its own single create. */+async function settleIndividually(batch: OpenBatch, waiters: Waiter[]): Promise<void> {+ await Promise.all(+ waiters.map(async (w) => {+ if (w.settled) return;+ try {+ const r = await postCreate(batch.cellBase, batch.capToken, w.body);+ if (w.settled) return;+ w.settled = true;+ w.resolve({ ...r, waitMs: Date.now() - w.queuedAt });+ } catch (e) {+ if (w.settled) return;+ w.settled = true;+ w.reject(e);+ }+ }),+ );+}++/**+ * isJSONObject guards the envelope. Item bodies are spliced in as raw JSON to+ * keep them byte-identical to what a single create would have carried, so a body+ * that is not a well-formed JSON object would corrupt the whole batch — not just+ * its own item. Anything unparseable goes out on its own instead.+ */+function isJSONObject(body: string): boolean {+ if (!body) return true; // empty body becomes "{}" downstream+ try {+ const v: unknown = JSON.parse(body);+ return typeof v === "object" && v !== null && !Array.isArray(v);+ } catch {+ return false;+ }+}++/** Test seam: reset module state between cases. */+export function __resetCreateBatchState(): void {+ openBatches.clear();+ createsInFlight = 0;+ batchDisabledUntil = 0;+}diff --git a/cloudflare-workers/api-edge/src/create_batch_types.ts b/cloudflare-workers/api-edge/src/create_batch_types.tsnew file mode 100644index 00000000..0877e3de--- /dev/null+++ b/cloudflare-workers/api-edge/src/create_batch_types.ts@@ -0,0 +1,12 @@+/** What one create call returned, however it was actually sent. */+export interface CreateCallResult {+ status: number;+ /** The CP's response body, verbatim for a single create. */+ text: string;+ /** True when this create shared a request with others. */+ batched: boolean;+ /** How many creates shared that request (1 when sent alone). */+ batchSize: number;+ /** Time this create spent waiting to be dispatched, in ms. */+ waitMs: number;+}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 94716256..def8b1dc 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -30,6 +30,8 @@ export { PoolStock } from "./pool_stock";// touching web/ or edge code) can't reset the DOs and sever the host-dialed// VM WebSockets.import { coloDelete, coloGet, coloPut } from "./colo_cache";+import { createViaCell } from "./create_batch";+import type { CreateCallResult } from "./create_batch_types";import {ACTIVE_CELLS_SQL,CELL_STALE_MAX_MS,@@ -150,6 +152,11 @@ export interface Env extends DashboardEnv {// keeps its warm set in process, where the stock DO can never be filled — see// createSandbox. Unset means edge-claim, which is prod.MICROVM_EDGE_CLAIM?: string;+ // CREATE_BATCH=1 coalesces concurrent creates on the CP-fallback path into one+ // request per isolate. Off by default: measured on dev with a settled pool it+ // batched 26-at-a-time and saved nothing, because the edge->cell hop is round+ // trip, not connection setup (CP handler is ~40us for a 132ms hop).+ CREATE_BATCH?: string;// VM-DO exec data plane (vm_do_datapane_validation). One DO per sandbox holds a// persistent host-dialed WebSocket to the QEMU worker; exec routes edge→DO→VM// instead of tunnel→CP→worker, with automatic tunnel fallback when unconnected.@@ -2212,13 +2219,13 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro}}- let cpResp: Response;+ // Not a bare fetch: concurrent creates on this isolate coalesce into one+ // request to the cell. A create with nothing else in flight still goes out+ // immediately and alone, so sequential latency is unchanged — see+ // create_batch.ts for why the gate is concurrency rather than a fixed window.+ let cpCall: CreateCallResult;try {- cpResp = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {- method: "POST",- headers: { authorization: "Bearer " + capToken, "content-type": "application/json" },- body: bodyText || "{}",- });+ cpCall = await createViaCell(cell.base_url, capToken, bodyText, env.CREATE_BATCH === "1");} catch (e) {return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);}@@ -2228,9 +2235,14 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro// Everything before it is edge compute + D1.mark("cell");- const cpText = await cpResp.text();+ const cpText = cpCall.text;+ // Whether this create shared a request, how many it shared with, and how long+ // it waited to be dispatched. Without these a batched burst and an unbatched+ // one are indistinguishable in the timing header, and `cell` alone cannot say+ // whether a slow create was queued or just slow.+ phases.push(`cellbatch;dur=${cpCall.batchSize}`, `cellwait;dur=${cpCall.waitMs}`);mark("cellbody");- if (cpResp.status >= 200 && cpResp.status < 300) {+ if (cpCall.status >= 200 && cpCall.status < 300) {let parsed: SandboxCreateResult = {};try {parsed = JSON.parse(cpText);@@ -2252,12 +2264,24 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro),);}+ // Total wall time inside this handler, on the edge's OWN clock. Paired with+ // the client's own (T4-T1) and the CP's own (createtrace total), this closes+ // the attribution without ever comparing two different clocks: every term is a+ // difference of two readings taken by the same machine, so skew cancels rather+ // than contaminating the result.+ //+ // What these three deliberately do NOT cover is the answer we are chasing.+ // Time spent queued before this handler ran is invisible to every mark in it —+ // `tEntry` is stamped once we are already executing — so it can only ever show+ // up as the residual (T4-T1) - hdl. That residual is the measurement; the marks+ // are just what we subtract to expose it.+ phases.push(`hdl;dur=${Date.now() - tEntry}`);if (env.DIAG === "1") console.log(`create-timing fallback ${cell.cell_id} ${phases.join(" ")}`);// Pass the CP's response through verbatim (status + body), plus the phase// breakdown — the edge-claim path above already returns one, and a fallback// create with no header is exactly the case that needed attributing.return new Response(cpText, {- status: cpResp.status,+ status: cpCall.status,headers: { "content-type": "application/json", "server-timing": phases.join(", ") },});}diff --git a/internal/api/create_batch.go b/internal/api/create_batch.gonew file mode 100644index 00000000..c407a600--- /dev/null+++ b/internal/api/create_batch.go@@ -0,0 +1,162 @@+package api++import (+ "bytes"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "sync"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+)++// create_batch.go — serve N creates on ONE edge→control-plane request.+//+// WHY. A burst of 100 creates costs ~115ms EACH in the edge's `cell` mark while+// this control plane answers every one of them in ~59us. Practically none of+// that hop is work: it is the connection. The cell's origin+// (cp-uswest2.opensandbox.ai → 20.64.208.62) is NOT behind Cloudflare's proxy,+// so a Worker subrequest dials the Azure box directly and a concurrent burst+// opens a pile of fresh connections, each paying a TLS handshake to westus2.+// Serially the same hop is ~30ms — one warm connection, one round trip.+//+// The protocol knob that would fix this does not exist for us: `fetch()` in a+// Worker exposes no way to force HTTP/2, and zone-level "HTTP/2 to Origin"+// applies only to proxied hostnames, which this origin is not. So the only+// reliable way to stop paying ~100 handshakes is to stop making ~100 requests.+//+// This is the same shape as the fix that took the template lookup from 580ms to+// nothing earlier: collapse a herd of identical concurrent calls into one.+// There the herd was per-key and the answer was a single flight; here the calls+// are distinct but the TRANSPORT is the contended resource, so the answer is a+// single request carrying all of them.+//+// HOW. Deliberately NOT a reimplementation of the create path. Each item is run+// through the very same internalCreateSandbox handler via a child echo context+// with a recorder, so batched and unbatched creates cannot drift in behaviour —+// there is exactly one create implementation, and this calls it. The cost is a+// synthetic request per item, which is allocation, not I/O.++// maxBatchItems bounds one request. The window that fills a batch is small, so+// a batch this large means something is very wrong upstream; the cap keeps a+// bad or hostile caller from turning one request into unbounded work.+const maxBatchItems = 256++type createBatchRequest struct {+ // Items are raw create bodies, byte-identical to what a single+ // POST /internal/sandboxes/create would carry.+ Items []json.RawMessage `json:"items"`+}++type createBatchResult struct {+ Status int `json:"status"`+ Body json.RawMessage `json:"body"`+}++type createBatchResponse struct {+ // Results is positional: results[i] answers items[i]. Callers fan these+ // back out to the waiters they batched, so order is load-bearing.+ Results []createBatchResult `json:"results"`+}++// internalCreateSandboxBatch runs every item through the single-create handler+// and returns their responses positionally. An item that fails fails alone: its+// own status and body are reported and the rest still land, because these are+// unrelated customer creates that happen to share a connection.+func (s *Server) internalCreateSandboxBatch(c echo.Context) error {+ var req createBatchRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid batch body: " + err.Error()})+ }+ if len(req.Items) == 0 {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "batch has no items"})+ }+ if len(req.Items) > maxBatchItems {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "batch too large"})+ }++ // The cap-token was verified once, by the middleware, for the batch request.+ // Every item inherits it: they were authenticated as one request and they+ // are all for the caller the token names.+ claims, _ := c.Get(capClaimsKey).(*auth.CapabilityClaims)+ if claims == nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "missing capability claims"})+ }++ parent := c.Request()+ results := make([]createBatchResult, len(req.Items))++ // Concurrent, because the whole point is that these do not queue behind each+ // other. The single-create path already runs concurrently for ordinary+ // traffic, so nothing here is newly shared.+ var wg sync.WaitGroup+ for i, item := range req.Items {+ wg.Add(1)+ go func(i int, body []byte) {+ defer wg.Done()+ results[i] = s.runBatchedCreate(parent, claims, body)+ }(i, item)+ }+ wg.Wait()++ return c.JSON(http.StatusOK, createBatchResponse{Results: results})+}++// runBatchedCreate executes one item on the real create handler and captures+// what it wrote.+func (s *Server) runBatchedCreate(parent *http.Request, claims *auth.CapabilityClaims, body []byte) createBatchResult {+ // Carry the parent's context so a client disconnect or deadline cancels the+ // whole batch rather than leaving items running with nothing to answer.+ sub := httptest.NewRequest(http.MethodPost, "/internal/sandboxes/create", bytes.NewReader(body)).+ WithContext(parent.Context())+ sub.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)+ // Region selection reads this header (see createSandboxRemote).+ if r := parent.Header.Get("Fly-Region"); r != "" {+ sub.Header.Set("Fly-Region", r)+ }++ rec := httptest.NewRecorder()+ cc := s.echo.NewContext(sub, rec)+ // The child never passes through capTokenMiddleware — it is not a real+ // request — so hand it the claims the middleware would have set. This is the+ // ONLY request-scoped value that needs carrying: the create path reads the+ // runtime off these claims (runtimeFor), and internalCreateSandbox derives+ // org and user identity from them too. Anything added to the middleware+ // chain that the create path later reads must be copied here as well, or a+ // batched create will quietly behave differently from an unbatched one.+ cc.Set(capClaimsKey, claims)++ if err := s.batchedCreateHandler()(cc); err != nil {+ // The handler returns its errors as responses; a non-nil error here is+ // echo-level and would normally be rendered by the error handler.+ return createBatchResult{+ Status: http.StatusInternalServerError,+ Body: mustJSON(map[string]string{"error": err.Error()}),+ }+ }++ raw, _ := io.ReadAll(rec.Result().Body)+ if len(raw) == 0 {+ raw = []byte("{}")+ }+ return createBatchResult{Status: rec.Code, Body: json.RawMessage(raw)}+}++// batchedCreateHandler is the handler each item runs on: the real single-create+// path in production, and only ever something else under test.+func (s *Server) batchedCreateHandler() func(echo.Context) error {+ if s.createOverrideForTest != nil {+ return s.createOverrideForTest+ }+ return s.internalCreateSandbox+}++func mustJSON(v any) json.RawMessage {+ b, err := json.Marshal(v)+ if err != nil {+ return json.RawMessage(`{"error":"marshal failed"}`)+ }+ return b+}diff --git a/internal/api/create_batch_test.go b/internal/api/create_batch_test.gonew file mode 100644index 00000000..9e4cbacf--- /dev/null+++ b/internal/api/create_batch_test.go@@ -0,0 +1,136 @@+package api++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+)++// newBatchTestServer returns a Server whose echo can mint child contexts, with a+// stub standing in for the single-create handler so these tests exercise the+// batching contract rather than the create path.+func newBatchTestServer(handler func(echo.Context) error) *Server {+ s := &Server{echo: echo.New()}+ s.createOverrideForTest = handler+ return s+}++func batchReq(t *testing.T, s *Server, body string, claims *auth.CapabilityClaims) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest(http.MethodPost, "/internal/sandboxes/create-batch", strings.NewReader(body))+ req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)+ rec := httptest.NewRecorder()+ c := s.echo.NewContext(req, rec)+ if claims != nil {+ c.Set(capClaimsKey, claims)+ }+ if err := s.internalCreateSandboxBatch(c); err != nil {+ t.Fatalf("handler error: %v", err)+ }+ return rec+}++// Results are positional — callers fan them back to the waiters they batched, so+// a shuffled response silently hands sandbox A to the caller who asked for B.+// Concurrency makes completion order deliberately non-sequential here.+func TestCreateBatchResultsArePositional(t *testing.T) {+ var mu sync.Mutex+ s := newBatchTestServer(func(c echo.Context) error {+ var in struct {+ N int `json:"n"`+ }+ _ = json.NewDecoder(c.Request().Body).Decode(&in)+ mu.Lock()+ defer mu.Unlock()+ return c.JSON(http.StatusOK, map[string]int{"got": in.N})+ })++ const n = 25+ items := make([]string, n)+ for i := range items {+ items[i] = fmt.Sprintf(`{"n":%d}`, i)+ }+ rec := batchReq(t, s, `{"items":[`+strings.Join(items, ",")+`]}`,+ &auth.CapabilityClaims{OrgID: "11111111-1111-1111-1111-111111111111"})++ var resp createBatchResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v (body=%s)", err, rec.Body.String())+ }+ if len(resp.Results) != n {+ t.Fatalf("got %d results, want %d", len(resp.Results), n)+ }+ for i, r := range resp.Results {+ var got struct {+ Got int `json:"got"`+ }+ if err := json.Unmarshal(r.Body, &got); err != nil {+ t.Fatalf("result %d: decode %v", i, err)+ }+ if got.Got != i {+ t.Fatalf("result %d carries item %d — results are not positional", i, got.Got)+ }+ }+}++// One item failing must not take the batch down: these are unrelated customer+// creates that merely share a connection.+func TestCreateBatchIsolatesPerItemFailure(t *testing.T) {+ s := newBatchTestServer(func(c echo.Context) error {+ var in struct {+ Fail bool `json:"fail"`+ }+ _ = json.NewDecoder(c.Request().Body).Decode(&in)+ if in.Fail {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "nope"})+ }+ return c.JSON(http.StatusOK, map[string]string{"ok": "yes"})+ })++ rec := batchReq(t, s, `{"items":[{"fail":false},{"fail":true},{"fail":false}]}`,+ &auth.CapabilityClaims{OrgID: "11111111-1111-1111-1111-111111111111"})++ var resp createBatchResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ want := []int{http.StatusOK, http.StatusNotFound, http.StatusOK}+ for i, w := range want {+ if resp.Results[i].Status != w {+ t.Fatalf("result %d status=%d want %d — a failing item changed its neighbours",+ i, resp.Results[i].Status, w)+ }+ }+}++func TestCreateBatchRejectsEmptyOversizeAndUnauthenticated(t *testing.T) {+ s := newBatchTestServer(func(c echo.Context) error {+ return c.JSON(http.StatusOK, map[string]string{"ok": "yes"})+ })+ claims := &auth.CapabilityClaims{OrgID: "11111111-1111-1111-1111-111111111111"}++ if rec := batchReq(t, s, `{"items":[]}`, claims); rec.Code != http.StatusBadRequest {+ t.Fatalf("empty batch: got %d want 400", rec.Code)+ }++ big := make([]string, maxBatchItems+1)+ for i := range big {+ big[i] = `{}`+ }+ if rec := batchReq(t, s, `{"items":[`+strings.Join(big, ",")+`]}`, claims); rec.Code != http.StatusBadRequest {+ t.Fatalf("oversize batch: got %d want 400", rec.Code)+ }++ // No claims == the middleware did not run. Must never fall through to+ // creating sandboxes for an unauthenticated caller.+ if rec := batchReq(t, s, `{"items":[{}]}`, nil); rec.Code != http.StatusInternalServerError {+ t.Fatalf("missing claims: got %d want 500", rec.Code)+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex fb38badc..e757f882 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -40,6 +40,13 @@ var errSandboxNotAvailable = map[string]string{// Server holds the API server dependencies.type Server struct {+ // createOverrideForTest substitutes the per-item handler the batch endpoint+ // fans out to. Test-only seam: it lets create_batch_test exercise the+ // batching contract (ordering, per-item isolation, limits) without standing+ // up a backend, a store and a worker registry. Always nil in production,+ // where batchedCreateHandler resolves to internalCreateSandbox.+ createOverrideForTest func(echo.Context) error+echo *echo.Echomanager sandbox.Managerrouter *sandbox.SandboxRouter // routes all sandbox interactions (state machine, auto-wake, rolling timeout)@@ -391,6 +398,13 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oif s.capTokenIssuer != nil && s.workerRegistry != nil {internal := e.Group("/internal", s.capTokenMiddleware)internal.POST("/sandboxes/create", s.internalCreateSandbox)+ // Same creates, one request. Serves the edge-side coalescer, which is+ // DEFAULT OFF (CREATE_BATCH) because measurement falsified the premise:+ // batching 26 creates into one request left the edge→cell hop unchanged+ // (132ms vs 126ms solo), so that hop is round-trip bound, not connection+ // bound. Endpoint kept because it is harmless and already deployed — see+ // create_batch.go and the edge's create_batch.ts.+ internal.POST("/sandboxes/create-batch", s.internalCreateSandboxBatch)// Edge claim (see edge_claim.go): the api-edge PoolStock DO reserves// pool boxes ahead of time and finalizes claims asynchronously.internal.POST("/pool/edge-reserve", s.edgeReservePool)