@sandboxrouter/sdk 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/bench.d.ts +10 -0
- package/dist/bench.js +38 -7
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +44 -5
- package/dist/cli.js +19 -2
- package/dist/leaderboard.d.ts +33 -0
- package/dist/leaderboard.js +61 -1
- package/dist/results.js +18 -0
- package/dist/router.d.ts +5 -0
- package/dist/router.js +14 -6
- package/dist/task.d.ts +65 -0
- package/dist/task.js +118 -0
- package/dist/types.d.ts +7 -0
- package/dist/validate.d.ts +1 -1
- package/dist/validate.js +4 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -61,7 +61,7 @@ List price while running, 2 vCPU / 4 GB, cheapest first; waitlisted sign-ups fol
|
|
|
61
61
|
| [Upstash Box](https://sandboxrouter.ai/providers/upstash) | up to $0.200 | none | not run yet | [pricing](https://upstash.com/pricing/box) |
|
|
62
62
|
| [Cloudflare Sandbox](https://sandboxrouter.ai/providers/cloudflare) | up to $0.216 | $5/mo | passed (2026-11-13) | [pricing](https://developers.cloudflare.com/containers/platform/pricing/) |
|
|
63
63
|
| [Amazon Bedrock AgentCore Code Interpreter](https://sandboxrouter.ai/providers/agentcore) | up to $0.217 | none | passed (2026-11-13) | [pricing](https://aws.amazon.com/bedrock/agentcore/pricing/) |
|
|
64
|
-
| [Modal](https://sandboxrouter.ai/providers/modal) |
|
|
64
|
+
| [Modal](https://sandboxrouter.ai/providers/modal) | $0.238 | none | passed (2026-11-13) | [pricing](https://modal.com/pricing) |
|
|
65
65
|
| [AWS Lambda MicroVMs](https://sandboxrouter.ai/providers/lambda) | $0.252 | none | passed (2026-11-13) | [pricing](https://aws.amazon.com/lambda/pricing/) |
|
|
66
66
|
| [Deno Sandbox](https://sandboxrouter.ai/providers/deno) | up to $0.300 | $20/mo | not run yet | [pricing](https://deno.com/sandbox) |
|
|
67
67
|
| [Runloop](https://sandboxrouter.ai/providers/runloop) | $0.317 | none | not run yet | [pricing](https://www.runloop.ai/pricing) |
|
package/dist/bench.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Router } from "./router.js";
|
|
2
|
+
import { type TaskKind } from "./task.js";
|
|
2
3
|
import type { ProviderId, SandboxSpec } from "./types.js";
|
|
3
4
|
export interface BenchRow {
|
|
4
5
|
provider: ProviderId;
|
|
@@ -7,6 +8,11 @@ export interface BenchRow {
|
|
|
7
8
|
medianCreateMs?: number;
|
|
8
9
|
medianExecMs?: number;
|
|
9
10
|
hourlyUsd: number;
|
|
11
|
+
/** With `task`: median time of the standard task (src/task.ts), and of each of its phases. */
|
|
12
|
+
medianTaskMs?: number;
|
|
13
|
+
taskPhasesMs?: Record<string, number>;
|
|
14
|
+
/** With `task`: median CPU time the task used across all vCPUs, where the sandbox shows /proc/stat. */
|
|
15
|
+
medianTaskCpuMs?: number;
|
|
10
16
|
lastError?: string;
|
|
11
17
|
}
|
|
12
18
|
/**
|
|
@@ -21,6 +27,10 @@ export declare function bench(opts: {
|
|
|
21
27
|
runs?: number;
|
|
22
28
|
spec?: SandboxSpec;
|
|
23
29
|
benchFile?: string;
|
|
30
|
+
/** Also run a standard task (src/task.ts) in each sandbox, to price a fixed piece of work: true or "short", "long", "python", "download". */
|
|
31
|
+
task?: boolean | TaskKind;
|
|
32
|
+
/** Providers benched at once (default 1). Each provider's own runs stay one after another. */
|
|
33
|
+
parallel?: number;
|
|
24
34
|
onProgress?: (msg: string) => void;
|
|
25
35
|
}): Promise<BenchRow[]>;
|
|
26
36
|
export declare function benchMarkdown(rows: BenchRow[]): string;
|
package/dist/bench.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost } from "./catalog.js";
|
|
1
|
+
import { CATALOG, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fittingSpec, fixedSize, hourlyCost } from "./catalog.js";
|
|
2
2
|
import { loadBench, median, saveBench } from "./bench-store.js";
|
|
3
3
|
import { Router } from "./router.js";
|
|
4
|
+
import { runTask, taskMs, taskUsd, TASKS } from "./task.js";
|
|
4
5
|
/**
|
|
5
6
|
* Cold start = time from create() call to a usable sandbox. Exec = round trip of `echo ok`.
|
|
6
7
|
* Measured from wherever you run it, so network distance to each provider counts. Every provider is
|
|
@@ -12,14 +13,17 @@ export async function bench(opts) {
|
|
|
12
13
|
const runs = opts.runs ?? 3;
|
|
13
14
|
// The CLI passes unset flags as undefined: drop them so they don't wipe the defaults.
|
|
14
15
|
const given = Object.fromEntries(Object.entries(opts.spec ?? {}).filter(([, v]) => v !== undefined));
|
|
15
|
-
const
|
|
16
|
+
const kind = opts.task === true ? "short" : opts.task || undefined;
|
|
17
|
+
// The long task can take minutes on a slow provider: give the sandbox room to finish it.
|
|
18
|
+
const spec = { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB, timeoutMinutes: kind === "long" ? 20 : 5, ...given };
|
|
16
19
|
const ids = opts.providers ?? router.registered().filter((id) => router.isConfigured(id));
|
|
17
20
|
const log = opts.onProgress ?? (() => { });
|
|
18
21
|
const stored = loadBench(opts.benchFile);
|
|
19
22
|
const rows = [];
|
|
20
|
-
|
|
23
|
+
const one = async (id) => {
|
|
21
24
|
const createMs = [];
|
|
22
25
|
const execMs = [];
|
|
26
|
+
const tasks = [];
|
|
23
27
|
let failures = 0;
|
|
24
28
|
let lastError;
|
|
25
29
|
for (let i = 0; i < runs; i++) {
|
|
@@ -34,6 +38,15 @@ export async function bench(opts) {
|
|
|
34
38
|
if (r.exitCode !== 0 || r.stdout.trim() !== "ok")
|
|
35
39
|
throw new Error(`echo returned ${r.exitCode}: ${r.stdout}${r.stderr}`);
|
|
36
40
|
execMs.push(Math.round(performance.now() - t1));
|
|
41
|
+
if (kind) {
|
|
42
|
+
// A failed task doesn't fail the run: the start time still counts, the task just has no time.
|
|
43
|
+
try {
|
|
44
|
+
tasks.push(await runTask(box, kind));
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
lastError = `task: ${err.message.slice(0, 180)}`;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
37
50
|
}
|
|
38
51
|
catch (err) {
|
|
39
52
|
failures++;
|
|
@@ -51,12 +64,26 @@ export async function bench(opts) {
|
|
|
51
64
|
medianCreateMs: median(createMs),
|
|
52
65
|
medianExecMs: median(execMs),
|
|
53
66
|
hourlyUsd: hourlyCost(id, sized(id, spec)),
|
|
67
|
+
...(tasks.length ? taskSummary(tasks, kind) : {}),
|
|
54
68
|
lastError,
|
|
55
69
|
});
|
|
56
|
-
}
|
|
70
|
+
};
|
|
71
|
+
// A small pool: `parallel` providers at a time, each taking the next id when it finishes.
|
|
72
|
+
const queue = [...ids];
|
|
73
|
+
const lanes = Array.from({ length: Math.max(1, Math.min(opts.parallel ?? 1, ids.length)) }, async () => {
|
|
74
|
+
for (let id = queue.shift(); id; id = queue.shift())
|
|
75
|
+
await one(id);
|
|
76
|
+
});
|
|
77
|
+
await Promise.all(lanes);
|
|
57
78
|
saveBench(stored, opts.benchFile);
|
|
58
79
|
return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
|
|
59
80
|
}
|
|
81
|
+
/** Medians of the task runs that finished: the whole task, and each phase. */
|
|
82
|
+
function taskSummary(tasks, kind) {
|
|
83
|
+
const phases = Object.fromEntries(TASKS[kind].phases.map((p) => [p.id, median(tasks.map((t) => t.ms[p.id]))]));
|
|
84
|
+
const cpu = tasks.every((t) => t.cpuMs !== undefined) ? median(tasks.map((t) => t.cpuMs)) : undefined;
|
|
85
|
+
return { medianTaskMs: median(tasks.map((t) => taskMs(t.ms))), taskPhasesMs: phases, ...(cpu !== undefined ? { medianTaskCpuMs: cpu } : {}) };
|
|
86
|
+
}
|
|
60
87
|
/** The spec a provider is benched at: the asked size, or its fixed default size if its image has one. */
|
|
61
88
|
function sized(id, spec) {
|
|
62
89
|
return { ...spec, ...fixedSize(id, spec) };
|
|
@@ -64,10 +91,14 @@ function sized(id, spec) {
|
|
|
64
91
|
export function benchMarkdown(rows) {
|
|
65
92
|
const name = (id) => CATALOG.find((c) => c.id === id).name;
|
|
66
93
|
const ms = (n) => (n === undefined ? "n/a" : `${n} ms`);
|
|
94
|
+
const task = rows.some((r) => r.taskPhasesMs);
|
|
95
|
+
const cost = (r) => r.medianTaskMs !== undefined && r.medianCreateMs !== undefined
|
|
96
|
+
? `$${taskUsd(r.provider, fittingSpec(r.provider), r.medianCreateMs, r.medianTaskMs, r.medianTaskCpuMs).toFixed(6)}`
|
|
97
|
+
: "n/a";
|
|
67
98
|
const lines = [
|
|
68
|
-
|
|
69
|
-
"
|
|
70
|
-
...rows.map((r, i) => `| ${i + 1} | ${name(r.provider)} | ${ms(r.medianCreateMs)} | ${ms(r.medianExecMs)} | $${r.hourlyUsd.toFixed(3)} | ${r.runs - r.failures}/${r.runs} |`),
|
|
99
|
+
`| # | Provider | Cold start (median) | Exec round trip |${task ? " Task (median) | Task cost |" : ""} $/hr (list, size run) | Success |`,
|
|
100
|
+
`|---|---|---|---|${task ? "---|---|" : ""}---|---|`,
|
|
101
|
+
...rows.map((r, i) => `| ${i + 1} | ${name(r.provider)} | ${ms(r.medianCreateMs)} | ${ms(r.medianExecMs)} |${task ? ` ${ms(r.medianTaskMs)} | ${cost(r)} |` : ""} $${r.hourlyUsd.toFixed(3)} | ${r.runs - r.failures}/${r.runs} |`),
|
|
71
102
|
];
|
|
72
103
|
return lines.join("\n");
|
|
73
104
|
}
|
package/dist/catalog.d.ts
CHANGED
|
@@ -12,6 +12,16 @@ export interface ProviderInfo {
|
|
|
12
12
|
incrementSeconds?: number;
|
|
13
13
|
/** A fixed charge per sandbox created, USD, on top of running time. */
|
|
14
14
|
perSandboxUsd?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Active-CPU billing only: the share of the allocated CPU billed even when idle (Tensorlake bills at
|
|
17
|
+
* least 20%). Default 0.
|
|
18
|
+
*/
|
|
19
|
+
cpuFloor?: number;
|
|
20
|
+
/**
|
|
21
|
+
* What `minSeconds` applies to. "all" (default): the whole price. "memory": only the non-CPU part, as
|
|
22
|
+
* on Vercel, where provisioned memory has a one-minute minimum and active CPU has none.
|
|
23
|
+
*/
|
|
24
|
+
minimumCovers?: "all" | "memory";
|
|
15
25
|
note?: string;
|
|
16
26
|
source: string;
|
|
17
27
|
checked: string;
|
|
@@ -269,6 +279,7 @@ export declare function billingRules(id: ProviderId): {
|
|
|
269
279
|
minSeconds: number;
|
|
270
280
|
incrementSeconds: number;
|
|
271
281
|
perSandboxUsd: number;
|
|
282
|
+
minimumCovers: "all" | "memory";
|
|
272
283
|
};
|
|
273
284
|
/**
|
|
274
285
|
* What a provider bills for one sandbox that ran `seconds` at `hourlyUsd`: running time rounded up to
|
|
@@ -289,6 +300,15 @@ export declare function fittingSpec(id: ProviderId): {
|
|
|
289
300
|
vcpu: number;
|
|
290
301
|
memoryGb: number;
|
|
291
302
|
};
|
|
303
|
+
/**
|
|
304
|
+
* Estimated USD per hour for this spec on this provider (list price, while running). For providers that
|
|
305
|
+
* bill CPU only while it's busy ("active-cpu"), the CPU part is scaled by `spec.cpuUtilization` (default
|
|
306
|
+
* 1, every core busy, so the price is the most an hour costs), never below the provider's `cpuFloor`.
|
|
307
|
+
*/
|
|
292
308
|
export declare function hourlyCost(id: ProviderId, spec?: SandboxSpec): number;
|
|
309
|
+
/** The CPU part of the full-use hourly price for an "active-cpu" provider; 0 for providers that bill allocated capacity. */
|
|
310
|
+
export declare function cpuHourlyAtFull(id: ProviderId, spec?: SandboxSpec): number;
|
|
311
|
+
/** Share of an "active-cpu" provider's CPU that gets billed: `cpuUtilization` (default 1), at least its `cpuFloor`. */
|
|
312
|
+
export declare function billedCpuShare(id: ProviderId, spec?: SandboxSpec): number;
|
|
293
313
|
/** Why a provider can't take this spec, or null if it can. */
|
|
294
314
|
export declare function unfit(id: ProviderId, spec: SandboxSpec, require?: Capability[]): string | null;
|
package/dist/catalog.js
CHANGED
|
@@ -120,9 +120,10 @@ const ENTRIES = [
|
|
|
120
120
|
name: "Vercel Sandbox",
|
|
121
121
|
pricing: {
|
|
122
122
|
minSeconds: 60,
|
|
123
|
+
minimumCovers: "memory",
|
|
123
124
|
vcpuHour: 0.128,
|
|
124
125
|
gbHour: 0.0212,
|
|
125
|
-
note: "iad1; active CPU, provisioned RAM in minimum 1-minute increments (2 GB/vCPU); full
|
|
126
|
+
note: "iad1; active CPU (I/O wait free), provisioned RAM in minimum 1-minute increments (2 GB/vCPU); listed at full CPU, cpuUtilization lowers it; Hobby free within quotas, Pro $20/mo usage credit; creations $0.60/million and retained snapshots $0.08/GB-month extra",
|
|
126
127
|
source: "https://vercel.com/docs/vercel-sandbox/pricing",
|
|
127
128
|
checked: "2026-11-05",
|
|
128
129
|
},
|
|
@@ -189,7 +190,8 @@ const ENTRIES = [
|
|
|
189
190
|
pricing: {
|
|
190
191
|
vcpuHour: 0.07,
|
|
191
192
|
gbHour: 0.015,
|
|
192
|
-
|
|
193
|
+
cpuFloor: 0.2,
|
|
194
|
+
note: "bills active CPU (floor 20% of allocation); listed at full CPU, cpuUtilization lowers it; Pro plan is lower",
|
|
193
195
|
source: "https://www.tensorlake.ai/pricing",
|
|
194
196
|
checked: "2026-11-04",
|
|
195
197
|
},
|
|
@@ -610,7 +612,8 @@ const BILLING = {
|
|
|
610
612
|
lambda: { billing: "allocated" },
|
|
611
613
|
langsmith: { billing: "allocated" },
|
|
612
614
|
maritime: { billing: "allocated", plan: { usdMonth: 20, credited: true, note: "Starter plan; no free tier; 7-day trial needs a card", checked: P } },
|
|
613
|
-
|
|
615
|
+
// Modal bills the larger of the reservation and actual use, and the adapter reserves the size you ask for.
|
|
616
|
+
modal: { billing: "allocated" },
|
|
614
617
|
morph: { billing: "allocated" },
|
|
615
618
|
northflank: { billing: "allocated" },
|
|
616
619
|
novita: { billing: "allocated" },
|
|
@@ -672,7 +675,12 @@ export function cloudflareInstance(vcpu, memoryGb) {
|
|
|
672
675
|
/** How a provider turns running time into a bill: minimum, rounding and fixed per-sandbox charge. */
|
|
673
676
|
export function billingRules(id) {
|
|
674
677
|
const p = CATALOG.find((c) => c.id === id)?.pricing;
|
|
675
|
-
return {
|
|
678
|
+
return {
|
|
679
|
+
minSeconds: p?.minSeconds ?? 0,
|
|
680
|
+
incrementSeconds: p?.incrementSeconds ?? 1,
|
|
681
|
+
perSandboxUsd: p?.perSandboxUsd ?? 0,
|
|
682
|
+
minimumCovers: p?.minimumCovers ?? "all",
|
|
683
|
+
};
|
|
676
684
|
}
|
|
677
685
|
/**
|
|
678
686
|
* What a provider bills for one sandbox that ran `seconds` at `hourlyUsd`: running time rounded up to
|
|
@@ -701,7 +709,7 @@ export function fixedSize(id, spec = {}) {
|
|
|
701
709
|
export function fittingSpec(id) {
|
|
702
710
|
return fixedSize(id) ?? { vcpu: DEFAULT_VCPU, memoryGb: DEFAULT_MEMORY_GB };
|
|
703
711
|
}
|
|
704
|
-
|
|
712
|
+
function fullHourlyCost(id, spec = {}) {
|
|
705
713
|
const { pricing } = info(id);
|
|
706
714
|
// You get, and pay for, the default image's size whatever you asked for.
|
|
707
715
|
const fixed = fixedSize(id, spec);
|
|
@@ -769,6 +777,37 @@ export function hourlyCost(id, spec = {}) {
|
|
|
769
777
|
return Math.max(vcpu, Math.ceil(mem / 4)) * pricing.vcpuHour;
|
|
770
778
|
return vcpu * pricing.vcpuHour + mem * pricing.gbHour;
|
|
771
779
|
}
|
|
780
|
+
/**
|
|
781
|
+
* Estimated USD per hour for this spec on this provider (list price, while running). For providers that
|
|
782
|
+
* bill CPU only while it's busy ("active-cpu"), the CPU part is scaled by `spec.cpuUtilization` (default
|
|
783
|
+
* 1, every core busy, so the price is the most an hour costs), never below the provider's `cpuFloor`.
|
|
784
|
+
*/
|
|
785
|
+
export function hourlyCost(id, spec = {}) {
|
|
786
|
+
const cpu = cpuHourlyAtFull(id, spec);
|
|
787
|
+
return fullHourlyCost(id, spec) - cpu * (1 - billedCpuShare(id, spec));
|
|
788
|
+
}
|
|
789
|
+
/** The CPU part of the full-use hourly price for an "active-cpu" provider; 0 for providers that bill allocated capacity. */
|
|
790
|
+
export function cpuHourlyAtFull(id, spec = {}) {
|
|
791
|
+
const p = info(id);
|
|
792
|
+
if (p.billing !== "active-cpu")
|
|
793
|
+
return 0;
|
|
794
|
+
const fixed = fixedSize(id, spec);
|
|
795
|
+
if (fixed)
|
|
796
|
+
return fixed.vcpu * p.pricing.vcpuHour;
|
|
797
|
+
const vcpu = spec.vcpu ?? DEFAULT_VCPU;
|
|
798
|
+
const mem = spec.memoryGb ?? DEFAULT_MEMORY_GB;
|
|
799
|
+
if (id === "cloudflare")
|
|
800
|
+
return cloudflareInstance(vcpu, mem).vcpu * p.pricing.vcpuHour;
|
|
801
|
+
if (id === "upstash")
|
|
802
|
+
return fullHourlyCost(id, spec);
|
|
803
|
+
if (id === "deno")
|
|
804
|
+
return 2 * p.pricing.vcpuHour;
|
|
805
|
+
return vcpu * p.pricing.vcpuHour;
|
|
806
|
+
}
|
|
807
|
+
/** Share of an "active-cpu" provider's CPU that gets billed: `cpuUtilization` (default 1), at least its `cpuFloor`. */
|
|
808
|
+
export function billedCpuShare(id, spec = {}) {
|
|
809
|
+
return Math.min(1, Math.max(spec.cpuUtilization ?? 1, info(id).pricing.cpuFloor ?? 0));
|
|
810
|
+
}
|
|
772
811
|
/** Why a provider can't take this spec, or null if it can. */
|
|
773
812
|
export function unfit(id, spec, require = []) {
|
|
774
813
|
const p = info(id);
|
package/dist/cli.js
CHANGED
|
@@ -3,6 +3,7 @@ import { parseArgs } from "node:util";
|
|
|
3
3
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { platform, arch } from "node:os";
|
|
5
5
|
import { bench, benchMarkdown } from "./bench.js";
|
|
6
|
+
import { TASKS } from "./task.js";
|
|
6
7
|
import { costMarkdown, costRun, settle } from "./cost.js";
|
|
7
8
|
import { checkProvider } from "./check.js";
|
|
8
9
|
import { gc, listOpen } from "./gc.js";
|
|
@@ -28,7 +29,11 @@ Usage:
|
|
|
28
29
|
sandboxrouter ls [--json] sandboxes this machine started that weren't killed
|
|
29
30
|
sandboxrouter gc [--all | --older-than MIN] [--dry-run]
|
|
30
31
|
kill leaked sandboxes: by default those past their lifetime
|
|
31
|
-
sandboxrouter bench [--runs 3] [--provider a,b] [--json] [--share [--label "where you ran it"] [--by GITHUB_USER]]
|
|
32
|
+
sandboxrouter bench [--runs 3] [--provider a,b] [--task [--long]] [--parallel N] [--json] [--share [--label "where you ran it"] [--by GITHUB_USER]]
|
|
33
|
+
--task also runs the same fixed job in each sandbox (hash 512 MB on 1 core,
|
|
34
|
+
then on 2, write 256 MB to disk) and prices it with each provider's billing rules;
|
|
35
|
+
--long runs that job 40 times in a row (minutes); --job python (a pure-Python script)
|
|
36
|
+
or --job download (53 MB over HTTPS) runs another job. --parallel benches N providers at once
|
|
32
37
|
sandboxrouter cost run [--provider a,b] [--minutes 10] [--vcpu 2 --memory 4] [--no-load] [--out FILE] [--by GITHUB_USER]
|
|
33
38
|
start one sandbox per provider for a fixed time with every core busy, record
|
|
34
39
|
the size it really got and the list-price prediction
|
|
@@ -42,6 +47,7 @@ Usage:
|
|
|
42
47
|
sandboxrouter serve [--port 8787] [--host 127.0.0.1] [--cors https://site.example,http://localhost:3000]
|
|
43
48
|
|
|
44
49
|
Spec flags: --vcpu N --memory GB --gpu T4 --timeout MIN --expect SEC (how long you'll use it; ranks by the real bill)
|
|
50
|
+
--cpu 0.1 (how busy the CPU is, 0-1; lowers providers that bill active CPU)
|
|
45
51
|
Route flags: --provider e2b[,modal,...] --strategy balanced|verified|cheapest|fastest (default balanced: cheapest real cost, speed breaks near-ties)
|
|
46
52
|
--max-price USD (per hour, for this run: skip providers that would cost more)
|
|
47
53
|
--no-fallback --fallback-any (also on setup errors like a bad key)
|
|
@@ -57,6 +63,7 @@ const { values, positionals } = parseArgs({
|
|
|
57
63
|
gpu: { type: "string" },
|
|
58
64
|
timeout: { type: "string" },
|
|
59
65
|
expect: { type: "string" },
|
|
66
|
+
cpu: { type: "string" },
|
|
60
67
|
provider: { type: "string" },
|
|
61
68
|
strategy: { type: "string" },
|
|
62
69
|
"max-price": { type: "string" },
|
|
@@ -66,6 +73,10 @@ const { values, positionals } = parseArgs({
|
|
|
66
73
|
require: { type: "string" },
|
|
67
74
|
keep: { type: "boolean" },
|
|
68
75
|
runs: { type: "string" },
|
|
76
|
+
task: { type: "boolean" },
|
|
77
|
+
long: { type: "boolean" },
|
|
78
|
+
job: { type: "string" },
|
|
79
|
+
parallel: { type: "string" },
|
|
69
80
|
json: { type: "boolean" },
|
|
70
81
|
port: { type: "string" },
|
|
71
82
|
host: { type: "string" },
|
|
@@ -101,6 +112,7 @@ const spec = {
|
|
|
101
112
|
gpu: values.gpu,
|
|
102
113
|
timeoutMinutes: num(values.timeout),
|
|
103
114
|
expectedSeconds: num(values.expect),
|
|
115
|
+
cpuUtilization: num(values.cpu),
|
|
104
116
|
};
|
|
105
117
|
const providers = list(values.provider);
|
|
106
118
|
const by = (() => {
|
|
@@ -313,10 +325,15 @@ async function main() {
|
|
|
313
325
|
return;
|
|
314
326
|
}
|
|
315
327
|
if (cmd === "bench") {
|
|
328
|
+
const job = (values.long ? "long" : values.job ?? "short");
|
|
329
|
+
if (!(job in TASKS))
|
|
330
|
+
return console.error(`--job must be one of: ${Object.keys(TASKS).join(", ")}`);
|
|
316
331
|
const rows = await bench({
|
|
317
332
|
router,
|
|
318
333
|
providers,
|
|
319
334
|
runs: num(values.runs) ?? 3,
|
|
335
|
+
task: values.task ? job : undefined,
|
|
336
|
+
parallel: num(values.parallel),
|
|
320
337
|
spec: { ...spec, timeoutMinutes: spec.timeoutMinutes ?? 5 },
|
|
321
338
|
onProgress: (m) => console.error(m),
|
|
322
339
|
});
|
|
@@ -330,7 +347,7 @@ async function main() {
|
|
|
330
347
|
console.error(`\n${r.provider} last error: ${r.lastError}`);
|
|
331
348
|
if (values.share) {
|
|
332
349
|
const version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
333
|
-
const report = makeReport(rows, { version, runs: rows[0].runs, spec: { ...spec, vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB }, label: values.label, by });
|
|
350
|
+
const report = makeReport(rows, { version, runs: rows[0].runs, spec: { ...spec, vcpu: spec.vcpu ?? DEFAULT_VCPU, memoryGb: spec.memoryGb ?? DEFAULT_MEMORY_GB }, label: values.label, by, task: values.task ? TASKS[job].version : undefined });
|
|
334
351
|
const left = rows.filter((r) => !benchmarksPublishable(r.provider)).map((r) => r.provider);
|
|
335
352
|
if (left.length)
|
|
336
353
|
console.log(`\nleft out of the shared report: ${left.join(", ")} (their terms don't allow publishing benchmarks)`);
|
package/dist/leaderboard.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type PhaseMs } from "./task.js";
|
|
1
2
|
import type { BenchRow } from "./bench.js";
|
|
2
3
|
import type { ProviderId, SandboxSpec } from "./types.js";
|
|
3
4
|
/**
|
|
@@ -15,6 +16,8 @@ export interface BenchReport {
|
|
|
15
16
|
by?: string;
|
|
16
17
|
runs: number;
|
|
17
18
|
spec: SandboxSpec;
|
|
19
|
+
/** Set when the run also timed the standard task (`bench --task`): which version of it (src/task.ts). */
|
|
20
|
+
task?: string;
|
|
18
21
|
node: string;
|
|
19
22
|
platform: string;
|
|
20
23
|
rows: BenchRow[];
|
|
@@ -25,6 +28,7 @@ export declare function makeReport(rows: BenchRow[], opts: {
|
|
|
25
28
|
spec: SandboxSpec;
|
|
26
29
|
label?: string;
|
|
27
30
|
by?: string;
|
|
31
|
+
task?: string;
|
|
28
32
|
}): BenchReport;
|
|
29
33
|
export declare function loadReports(dir: string): BenchReport[];
|
|
30
34
|
export interface LeaderRow {
|
|
@@ -49,5 +53,34 @@ export interface LeaderRow {
|
|
|
49
53
|
* an old run can't outvote a newer one and one heavy submitter can't skew a provider.
|
|
50
54
|
*/
|
|
51
55
|
export declare function aggregate(reports: BenchReport[]): LeaderRow[];
|
|
56
|
+
export interface TaskRow {
|
|
57
|
+
provider: ProviderId;
|
|
58
|
+
name: string;
|
|
59
|
+
/** The size it ran at: 2 vCPU / 4 GB, or the provider's fixed default size. */
|
|
60
|
+
size: {
|
|
61
|
+
vcpu: number;
|
|
62
|
+
memoryGb: number;
|
|
63
|
+
};
|
|
64
|
+
createMs: number;
|
|
65
|
+
taskMs: number;
|
|
66
|
+
phasesMs: PhaseMs;
|
|
67
|
+
/** USD per hour at that size: list price, corrected by measured bills (`BILLED_VS_LIST`). */
|
|
68
|
+
hourlyUsd: number;
|
|
69
|
+
/** What one task is billed: start plus task, with the minimum charge, billing step and per-sandbox fee; active-CPU providers by the CPU time it used. */
|
|
70
|
+
taskUsd: number;
|
|
71
|
+
/** CPU time the task used across all vCPUs (median), where the sandbox shows /proc/stat. */
|
|
72
|
+
cpuMs?: number;
|
|
73
|
+
/** True when the provider bills CPU only while busy, so `taskUsd` counts `cpuMs` rather than every core. */
|
|
74
|
+
activeCpu: boolean;
|
|
75
|
+
minimumSeconds: number;
|
|
76
|
+
perSandboxUsd: number;
|
|
77
|
+
measuredAt: string;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Cost of the standard task (src/task.ts) per provider, from reports made with `bench --task` at
|
|
81
|
+
* `version` (the short task's by default; TASKS.long.version for `--long`): each provider's latest run
|
|
82
|
+
* from each location, then the median across locations (as `aggregate` does). Cheapest task first.
|
|
83
|
+
*/
|
|
84
|
+
export declare function taskTable(reports: BenchReport[], version?: string): TaskRow[];
|
|
52
85
|
/** One self-contained HTML page: a sorted table with an inline bar per measure, each on its own scale. */
|
|
53
86
|
export declare function renderLeaderboard(reports: BenchReport[]): string;
|
package/dist/leaderboard.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { readdirSync, readFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
import { benchmarksPublishable, CATALOG, fittingSpec, hourlyCost } from "./catalog.js";
|
|
3
|
+
import { benchmarksPublishable, billingRules, CATALOG, cpuHourlyAtFull, fittingSpec, hourlyCost } from "./catalog.js";
|
|
4
|
+
import { BILLED_VS_LIST } from "./billing.js";
|
|
5
|
+
import { TASK_VERSION, taskByVersion, taskUsd } from "./task.js";
|
|
4
6
|
import { median } from "./bench-store.js";
|
|
5
7
|
export function makeReport(rows, opts) {
|
|
6
8
|
return {
|
|
@@ -12,6 +14,7 @@ export function makeReport(rows, opts) {
|
|
|
12
14
|
runs: opts.runs,
|
|
13
15
|
// Only the shape matters for comparison; never ship env or metadata.
|
|
14
16
|
spec: { vcpu: opts.spec.vcpu, memoryGb: opts.spec.memoryGb },
|
|
17
|
+
...(opts.task ? { task: opts.task } : {}),
|
|
15
18
|
node: process.version,
|
|
16
19
|
platform: `${process.platform}-${process.arch}`,
|
|
17
20
|
// Providers whose terms forbid publishing benchmarks stay out of anything meant to be shared.
|
|
@@ -77,6 +80,63 @@ export function aggregate(reports) {
|
|
|
77
80
|
});
|
|
78
81
|
return rows.sort((a, b) => (a.medianCreateMs ?? Infinity) - (b.medianCreateMs ?? Infinity));
|
|
79
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Cost of the standard task (src/task.ts) per provider, from reports made with `bench --task` at
|
|
85
|
+
* `version` (the short task's by default; TASKS.long.version for `--long`): each provider's latest run
|
|
86
|
+
* from each location, then the median across locations (as `aggregate` does). Cheapest task first.
|
|
87
|
+
*/
|
|
88
|
+
export function taskTable(reports, version = TASK_VERSION) {
|
|
89
|
+
const def = taskByVersion(version);
|
|
90
|
+
if (!def)
|
|
91
|
+
return [];
|
|
92
|
+
const latest = new Map();
|
|
93
|
+
for (const rep of reports) {
|
|
94
|
+
if (rep.task !== version)
|
|
95
|
+
continue;
|
|
96
|
+
for (const r of rep.rows) {
|
|
97
|
+
if (!KNOWN.has(r.provider) || !r.taskPhasesMs || r.medianTaskMs === undefined || r.medianCreateMs === undefined)
|
|
98
|
+
continue;
|
|
99
|
+
const key = `${r.provider}\u0000${rep.label ?? ""}`;
|
|
100
|
+
const seen = latest.get(key);
|
|
101
|
+
if (!seen || rep.date > seen.date)
|
|
102
|
+
latest.set(key, { row: r, date: rep.date });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const by = new Map();
|
|
106
|
+
for (const x of latest.values())
|
|
107
|
+
by.set(x.row.provider, [...(by.get(x.row.provider) ?? []), x]);
|
|
108
|
+
const rows = [...by.entries()].map(([id, xs]) => {
|
|
109
|
+
const rs = xs.map((x) => x.row);
|
|
110
|
+
const createMs = median(rs.map((r) => r.medianCreateMs));
|
|
111
|
+
const taskMillis = median(rs.map((r) => r.medianTaskMs));
|
|
112
|
+
const phasesMs = Object.fromEntries(def.phases.map((p) => [p.id, median(rs.map((r) => r.taskPhasesMs[p.id]))]));
|
|
113
|
+
const size = fittingSpec(id);
|
|
114
|
+
const ratio = BILLED_VS_LIST[id]?.ratio ?? 1;
|
|
115
|
+
const hourlyUsd = hourlyCost(id, size) * ratio;
|
|
116
|
+
const rules = billingRules(id);
|
|
117
|
+
const cpus = rs.map((r) => r.medianTaskCpuMs).filter((n) => typeof n === "number");
|
|
118
|
+
// A container can show the whole host's /proc/stat (Daytona does): a reading beyond what the sandbox's
|
|
119
|
+
// own vCPUs could do in that time isn't the sandbox's, so it's dropped and the task is priced at full CPU.
|
|
120
|
+
const read = cpus.length === rs.length ? median(cpus) : undefined;
|
|
121
|
+
const cpuMs = read !== undefined && read <= size.vcpu * taskMillis * 1.1 ? read : undefined;
|
|
122
|
+
return {
|
|
123
|
+
provider: id,
|
|
124
|
+
name: CATALOG.find((c) => c.id === id).name,
|
|
125
|
+
size,
|
|
126
|
+
createMs,
|
|
127
|
+
taskMs: taskMillis,
|
|
128
|
+
phasesMs,
|
|
129
|
+
hourlyUsd,
|
|
130
|
+
taskUsd: taskUsd(id, size, createMs, taskMillis, cpuMs, ratio),
|
|
131
|
+
...(cpuMs !== undefined ? { cpuMs } : {}),
|
|
132
|
+
activeCpu: cpuHourlyAtFull(id, size) > 0,
|
|
133
|
+
minimumSeconds: rules.minSeconds,
|
|
134
|
+
perSandboxUsd: rules.perSandboxUsd,
|
|
135
|
+
measuredAt: xs.map((x) => x.date).sort().at(-1),
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
return rows.sort((a, b) => a.taskUsd - b.taskUsd || a.provider.localeCompare(b.provider));
|
|
139
|
+
}
|
|
80
140
|
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
81
141
|
function bar(value, max, text, tip) {
|
|
82
142
|
if (value === undefined)
|
package/dist/results.js
CHANGED
|
@@ -2,6 +2,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
|
2
2
|
import { join, relative } from "node:path";
|
|
3
3
|
import { benchmarksPublishable, CATALOG } from "./catalog.js";
|
|
4
4
|
import { CHECK_STEPS } from "./check.js";
|
|
5
|
+
import { taskByVersion } from "./task.js";
|
|
5
6
|
/** A GitHub handle, without the "@": what `--by` accepts and what reports store. */
|
|
6
7
|
export function contributor(by) {
|
|
7
8
|
if (by === undefined)
|
|
@@ -101,6 +102,8 @@ export function validateResult(j, now = Date.now()) {
|
|
|
101
102
|
add(checkBy(j.by));
|
|
102
103
|
if (!isNum(j.runs, 3, 1000))
|
|
103
104
|
out.push("runs must be at least 3");
|
|
105
|
+
if (j.task !== undefined && typeof j.task !== "string")
|
|
106
|
+
out.push("task must be the task version, e.g. \"v1\"");
|
|
104
107
|
if (!Array.isArray(j.rows) || !j.rows.length)
|
|
105
108
|
out.push("rows is empty");
|
|
106
109
|
for (const r of Array.isArray(j.rows) ? j.rows : []) {
|
|
@@ -117,6 +120,21 @@ export function validateResult(j, now = Date.now()) {
|
|
|
117
120
|
}
|
|
118
121
|
if (r?.failures < r?.runs && r?.medianCreateMs === undefined)
|
|
119
122
|
out.push(`${r?.provider}: successful runs but no medianCreateMs`);
|
|
123
|
+
if (r?.medianTaskMs !== undefined && !isNum(r.medianTaskMs, 1, MAX_MS))
|
|
124
|
+
out.push(`${r?.provider}: medianTaskMs must be between 1 ms and 15 min`);
|
|
125
|
+
if (r?.medianTaskCpuMs !== undefined && !isNum(r.medianTaskCpuMs, 0, 64 * MAX_MS))
|
|
126
|
+
out.push(`${r?.provider}: medianTaskCpuMs is out of range`);
|
|
127
|
+
if (r?.taskPhasesMs !== undefined) {
|
|
128
|
+
const ph = r.taskPhasesMs;
|
|
129
|
+
const def = taskByVersion(j.task);
|
|
130
|
+
if (j.task === undefined)
|
|
131
|
+
out.push(`${r?.provider}: has task times but the report doesn't say which task (task)`);
|
|
132
|
+
else if (!def)
|
|
133
|
+
out.push(`${r?.provider}: unknown task "${String(j.task)}"`);
|
|
134
|
+
else if (!ph || typeof ph !== "object" || def.phases.some((p) => !isNum(ph[p.id], 1, MAX_MS))) {
|
|
135
|
+
out.push(`${r?.provider}: taskPhasesMs needs ${def.phases.map((p) => p.id).join(", ")}, each between 1 ms and 15 min`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
120
138
|
if ("lastError" in (r ?? {}))
|
|
121
139
|
out.push(`${r?.provider}: lastError must not be shared (it can hold account details)`);
|
|
122
140
|
}
|
package/dist/router.d.ts
CHANGED
|
@@ -16,6 +16,11 @@ export interface Candidate {
|
|
|
16
16
|
estimatedHourlyUsd: number;
|
|
17
17
|
/** The provider's published list price for this size, USD/hour. */
|
|
18
18
|
listHourlyUsd: number;
|
|
19
|
+
/**
|
|
20
|
+
* For providers that bill CPU only while busy: the CPU part of `estimatedHourlyUsd`, at the spec's
|
|
21
|
+
* `cpuUtilization`. Ranking needs it where a minimum charge covers memory only (Vercel).
|
|
22
|
+
*/
|
|
23
|
+
cpuHourlyUsd?: number;
|
|
19
24
|
/** Billed / list-price ratio behind `estimatedHourlyUsd`, when measured (`BILLED_VS_LIST`). */
|
|
20
25
|
billedVsList?: number;
|
|
21
26
|
/**
|
package/dist/router.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { accessLabel, billedCpuShare, billingRules, CATALOG, cpuHourlyAtFull, DEFAULT_MEMORY_GB, DEFAULT_VCPU, fixedSize, hourlyCost, unfit } from "./catalog.js";
|
|
2
2
|
import { RoutedComputer, createComputer, planComputer, } from "./computers.js";
|
|
3
3
|
import { loadBench, median } from "./bench-store.js";
|
|
4
4
|
import { Ledger, defaultLedgerFile } from "./ledger.js";
|
|
@@ -163,6 +163,7 @@ export class Router {
|
|
|
163
163
|
provider: id,
|
|
164
164
|
estimatedHourlyUsd: round(list * (ratio ?? 1)),
|
|
165
165
|
listHourlyUsd: list,
|
|
166
|
+
...(cpuHourlyAtFull(id, spec) > 0 ? { cpuHourlyUsd: round(cpuHourlyAtFull(id, spec) * billedCpuShare(id, spec) * (ratio ?? 1)) } : {}),
|
|
166
167
|
...(ratio !== undefined ? { billedVsList: ratio } : {}),
|
|
167
168
|
size: sizeOf(id, spec),
|
|
168
169
|
medianCreateMs: speed ? (live && live.length >= LIVE_MIN_SAMPLES ? median(live) : median(bench[id]?.createMs)) : undefined,
|
|
@@ -283,15 +284,18 @@ export class Router {
|
|
|
283
284
|
const attempts = [];
|
|
284
285
|
const tries = route.fallback === false ? usable.slice(0, 1) : usable;
|
|
285
286
|
const deadline = Date.now() + (route.deadlineSeconds ?? DEFAULT_CREATE_DEADLINE_S) * 1000;
|
|
287
|
+
const outOfTime = () => new RouterError(`create ran out of time (deadlineSeconds) after trying ${attempts.map((a) => a.provider).join(", ")}: ${attempts.map((a) => `${a.provider}: ${a.error}`).join(" | ")}`, attempts, "timeout");
|
|
286
288
|
for (const [i, c] of tries.entries()) {
|
|
287
289
|
const left = deadline - Date.now();
|
|
288
|
-
if (left <= 0)
|
|
289
|
-
throw
|
|
290
|
-
}
|
|
290
|
+
if (left <= 0)
|
|
291
|
+
throw outOfTime();
|
|
291
292
|
const t0 = Date.now();
|
|
292
293
|
const pending = this.provider(c.provider).create(spec);
|
|
293
294
|
const { limitS, typicalMs } = this.waitFor(c.provider, route, i === tries.length - 1);
|
|
294
295
|
const waitS = Math.min(limitS, left / 1000);
|
|
296
|
+
// This try's wait is what's left of the deadline: if it times out, the deadline is spent. Decided here,
|
|
297
|
+
// not by reading the clock again, since a timer can fire a millisecond early and let one more try start.
|
|
298
|
+
const lastChance = left / 1000 <= limitS;
|
|
295
299
|
const price = { estimatedHourlyUsd: c.estimatedHourlyUsd, listHourlyUsd: c.listHourlyUsd, size: c.size };
|
|
296
300
|
let timedOut = false;
|
|
297
301
|
try {
|
|
@@ -313,6 +317,8 @@ export class Router {
|
|
|
313
317
|
pending.then((late) => this.discard(c.provider, late, price, spec.timeoutMinutes), () => { });
|
|
314
318
|
const status = errorStatus(err);
|
|
315
319
|
attempts.push({ provider: c.provider, ok: false, ms: Date.now() - t0, error: err.message, ...(status ? { status } : {}) });
|
|
320
|
+
if (timedOut && lastChance)
|
|
321
|
+
throw outOfTime();
|
|
316
322
|
const setup = err instanceof SetupError || (status !== undefined && SETUP_ERRORS.has(status));
|
|
317
323
|
// On the router's own accounts, a key, permission or install problem is ours: move on.
|
|
318
324
|
const account = err instanceof SetupError || status === 401 || status === 403;
|
|
@@ -516,10 +522,12 @@ export function runHours(spec) {
|
|
|
516
522
|
* per-sandbox charge is added, so short runs favor providers that bill by the second without a fee.
|
|
517
523
|
*/
|
|
518
524
|
export function rankUsd(c, hours) {
|
|
519
|
-
const { minSeconds, incrementSeconds } = billingRules(c.provider);
|
|
525
|
+
const { minSeconds, incrementSeconds, minimumCovers } = billingRules(c.provider);
|
|
520
526
|
const seconds = hours * 3600;
|
|
521
527
|
const billed = Math.max(minSeconds, Math.ceil(seconds / incrementSeconds - 1e-9) * incrementSeconds);
|
|
522
|
-
|
|
528
|
+
// Where the minimum covers memory only (Vercel), CPU is billed for the time actually used.
|
|
529
|
+
const cpu = minimumCovers === "memory" ? (c.cpuHourlyUsd ?? 0) : 0;
|
|
530
|
+
return ((c.estimatedHourlyUsd - cpu) * billed + cpu * seconds) / Math.max(seconds, 1) + (c.perSandboxUsd ?? 0) / Math.max(hours, 1 / 3600);
|
|
523
531
|
}
|
|
524
532
|
/** Seconds to wait for one provider's create before trying the next (RouteOptions.createTimeoutSeconds). */
|
|
525
533
|
export const DEFAULT_CREATE_TIMEOUT_S = 120;
|
package/dist/task.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ProviderId, ProviderSandbox } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The standard tasks for `bench --task`: the same fixed piece of work in every sandbox, so providers can be
|
|
4
|
+
* compared on what a job costs, not just on their hourly price. A slower CPU, disk or network makes the job
|
|
5
|
+
* take longer, and a longer job is billed more.
|
|
6
|
+
*
|
|
7
|
+
* Each phase is its own command, timed from here, minus the sandbox's own round trip for an empty command,
|
|
8
|
+
* so network distance to the provider mostly drops out.
|
|
9
|
+
*
|
|
10
|
+
* - "short": hash on one core, then two, then write to disk, once (seconds). Only POSIX shell and tools every
|
|
11
|
+
* Linux image has (coreutils or busybox), so no provider fails for lack of a package.
|
|
12
|
+
* - "long": the short job's phases 40 times in a row (minutes): sustained speed (CPUs that slow down after a
|
|
13
|
+
* burst) and prices once minimum charges stop mattering.
|
|
14
|
+
* - "python": a pure-Python script like a code-interpreter call. Needs python3 in the default image; a
|
|
15
|
+
* provider without it fails the task, which is itself worth knowing.
|
|
16
|
+
* - "download": fetch the 53 MB Node.js release from nodejs.org's CDN, with curl, else wget, else python3:
|
|
17
|
+
* what installing toolchains and packages depends on.
|
|
18
|
+
*
|
|
19
|
+
* Changing a phase changes what the numbers mean: bump that task's version, and older reports stop counting.
|
|
20
|
+
*/
|
|
21
|
+
export type TaskKind = "short" | "long" | "python" | "download";
|
|
22
|
+
export interface TaskPhaseDef {
|
|
23
|
+
id: string;
|
|
24
|
+
label: string;
|
|
25
|
+
cmd: string;
|
|
26
|
+
}
|
|
27
|
+
export declare const TASKS: Record<TaskKind, {
|
|
28
|
+
version: string;
|
|
29
|
+
repeat: number;
|
|
30
|
+
phases: TaskPhaseDef[];
|
|
31
|
+
}>;
|
|
32
|
+
/** The short task's version and phases, which is what plain `bench --task` records. */
|
|
33
|
+
export declare const TASK_VERSION: string;
|
|
34
|
+
export declare const TASK_PHASES: TaskPhaseDef[];
|
|
35
|
+
/** Milliseconds per phase, by phase id. */
|
|
36
|
+
export type PhaseMs = Record<string, number>;
|
|
37
|
+
/** The task a report's `task` version names, if it's one this release knows. */
|
|
38
|
+
export declare function taskByVersion(version: unknown): (typeof TASKS)[TaskKind] | undefined;
|
|
39
|
+
/** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
|
|
40
|
+
export declare function phaseCommand(cmd: string, repeat: number): string;
|
|
41
|
+
/** What one run of a task measured: milliseconds per phase, and the CPU time it used across all vCPUs, if the sandbox shows it. */
|
|
42
|
+
export interface TaskRun {
|
|
43
|
+
ms: PhaseMs;
|
|
44
|
+
cpuMs?: number;
|
|
45
|
+
}
|
|
46
|
+
/** Busy CPU milliseconds between two /proc/stat "cpu" lines: user, nice, system, irq and softirq (not idle, iowait or steal), at 100 ticks a second. */
|
|
47
|
+
export declare function busyMs(before: string, after: string): number | undefined;
|
|
48
|
+
/** Runs a standard task in `box`: milliseconds per phase (network round trip taken out) and CPU time used. Throws if a phase fails. */
|
|
49
|
+
export declare function runTask(box: Pick<ProviderSandbox, "exec">, kind?: TaskKind): Promise<TaskRun>;
|
|
50
|
+
/** The whole task's time: the phases added up. */
|
|
51
|
+
export declare const taskMs: (phases: PhaseMs) => number;
|
|
52
|
+
/**
|
|
53
|
+
* What one task would be billed, USD, on a sandbox of `size`. It's billed from create until the task is
|
|
54
|
+
* done: the start time plus the task, rounded up to the provider's minimum charge and billing increment,
|
|
55
|
+
* plus its per-sandbox charge.
|
|
56
|
+
*
|
|
57
|
+
* Providers that bill CPU only while busy are charged for the CPU time the task really used (`cpuMillis`,
|
|
58
|
+
* at least their CPU floor) plus their memory for the whole time; their minimum charge covers memory only
|
|
59
|
+
* where that's how they bill (Vercel). Without `cpuMillis` they're charged as if every core was busy.
|
|
60
|
+
* `billedVsList` scales the price by what the provider was measured to really bill.
|
|
61
|
+
*/
|
|
62
|
+
export declare function taskUsd(provider: ProviderId, size: {
|
|
63
|
+
vcpu: number;
|
|
64
|
+
memoryGb: number;
|
|
65
|
+
}, createMs: number, taskMillis: number, cpuMillis?: number, billedVsList?: number): number;
|
package/dist/task.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { billingRules, cpuHourlyAtFull, hourlyCost, info } from "./catalog.js";
|
|
2
|
+
const HASH_DISK = [
|
|
3
|
+
// One core: hash 512 MB of zeros.
|
|
4
|
+
{ id: "cpu", label: "1 core", cmd: "head -c 536870912 /dev/zero | sha256sum > /dev/null" },
|
|
5
|
+
// Two cores at once (bench asks for 2 vCPU), 256 MB each: shows whether the second vCPU is real.
|
|
6
|
+
{ id: "cores", label: "2 cores", cmd: "for i in 1 2; do (head -c 268435456 /dev/zero | sha256sum > /dev/null) & done; wait" },
|
|
7
|
+
// Write 256 MB and flush it to disk, then delete it.
|
|
8
|
+
{ id: "disk", label: "disk", cmd: "dd if=/dev/zero of=/tmp/sr-task bs=1048576 count=256 conv=fsync 2> /dev/null; rm -f /tmp/sr-task" },
|
|
9
|
+
];
|
|
10
|
+
// 200,000 small records through JSON, a regex and a sort: the kind of thing a code-interpreter call does.
|
|
11
|
+
const PYTHON = [
|
|
12
|
+
"import json, random, re",
|
|
13
|
+
"random.seed(1)",
|
|
14
|
+
"rows = [{'id': i, 'name': ''.join(random.choice('abcdefghij') for _ in range(16)), 'v': random.random()} for i in range(200000)]",
|
|
15
|
+
"back = json.loads(json.dumps(rows))",
|
|
16
|
+
"hits = sum(1 for r in back if re.search('abc', r['name']))",
|
|
17
|
+
"top = sorted(back, key=lambda r: (r['name'], r['v']))[:10]",
|
|
18
|
+
"print(hits, top[0]['id'])",
|
|
19
|
+
].join("\n");
|
|
20
|
+
// The Node.js 22.11.0 Linux release (53 MB), from nodejs.org's CDN: a real download, like installing a toolchain.
|
|
21
|
+
const DOWNLOAD_URL = "https://nodejs.org/dist/v22.11.0/node-v22.11.0-linux-x64.tar.gz";
|
|
22
|
+
const PY_FETCH = `import shutil, urllib.request; shutil.copyfileobj(urllib.request.urlopen('${DOWNLOAD_URL}'), open('/dev/null', 'wb'))`;
|
|
23
|
+
export const TASKS = {
|
|
24
|
+
short: { version: "v1", repeat: 1, phases: HASH_DISK },
|
|
25
|
+
long: { version: "v1-long", repeat: 40, phases: HASH_DISK },
|
|
26
|
+
python: { version: "python-v1", repeat: 1, phases: [{ id: "python", label: "Python", cmd: `python3 -c "${PYTHON}"` }] },
|
|
27
|
+
download: {
|
|
28
|
+
version: "download-v1",
|
|
29
|
+
repeat: 1,
|
|
30
|
+
phases: [
|
|
31
|
+
{
|
|
32
|
+
id: "download",
|
|
33
|
+
label: "53 MB download",
|
|
34
|
+
cmd: `if command -v curl > /dev/null; then curl -sSfL -o /dev/null '${DOWNLOAD_URL}'; ` +
|
|
35
|
+
`elif command -v wget > /dev/null; then wget -q -O /dev/null '${DOWNLOAD_URL}'; ` +
|
|
36
|
+
`else python3 -c "${PY_FETCH}"; fi`,
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
/** The short task's version and phases, which is what plain `bench --task` records. */
|
|
42
|
+
export const TASK_VERSION = TASKS.short.version;
|
|
43
|
+
export const TASK_PHASES = TASKS.short.phases;
|
|
44
|
+
/** The task a report's `task` version names, if it's one this release knows. */
|
|
45
|
+
export function taskByVersion(version) {
|
|
46
|
+
return Object.values(TASKS).find((t) => t.version === version);
|
|
47
|
+
}
|
|
48
|
+
/** A phase's command, run `repeat` times in a row in one shell (POSIX: no seq, no brace ranges). */
|
|
49
|
+
export function phaseCommand(cmd, repeat) {
|
|
50
|
+
return repeat <= 1 ? cmd : `n=0; while [ $n -lt ${repeat} ]; do ${cmd}; n=$((n+1)); done`;
|
|
51
|
+
}
|
|
52
|
+
// Wraps a phase to read /proc/stat's total CPU line before and after it, so the run also reports the CPU
|
|
53
|
+
// time it really used: what providers that bill active CPU charge for.
|
|
54
|
+
const MARK = "SRCPU";
|
|
55
|
+
const withCpu = (cmd) => `a=$(head -n 1 /proc/stat 2> /dev/null); ${cmd}; rc=$?; b=$(head -n 1 /proc/stat 2> /dev/null); echo "${MARK}|$a|$b"; exit $rc`;
|
|
56
|
+
/** Busy CPU milliseconds between two /proc/stat "cpu" lines: user, nice, system, irq and softirq (not idle, iowait or steal), at 100 ticks a second. */
|
|
57
|
+
export function busyMs(before, after) {
|
|
58
|
+
const ticks = (line) => {
|
|
59
|
+
const f = line.trim().split(/\s+/);
|
|
60
|
+
if (f[0] !== "cpu" || f.length < 8)
|
|
61
|
+
return undefined;
|
|
62
|
+
const n = f.slice(1).map(Number);
|
|
63
|
+
return n[0] + n[1] + n[2] + n[5] + n[6];
|
|
64
|
+
};
|
|
65
|
+
const a = ticks(before);
|
|
66
|
+
const b = ticks(after);
|
|
67
|
+
return a === undefined || b === undefined || !(b >= a) ? undefined : (b - a) * 10;
|
|
68
|
+
}
|
|
69
|
+
/** Runs a standard task in `box`: milliseconds per phase (network round trip taken out) and CPU time used. Throws if a phase fails. */
|
|
70
|
+
export async function runTask(box, kind = "short") {
|
|
71
|
+
const { repeat, phases } = TASKS[kind];
|
|
72
|
+
const rtt = [];
|
|
73
|
+
for (let i = 0; i < 3; i++) {
|
|
74
|
+
const t = performance.now();
|
|
75
|
+
await box.exec("true");
|
|
76
|
+
rtt.push(performance.now() - t);
|
|
77
|
+
}
|
|
78
|
+
const overhead = rtt.sort((a, b) => a - b)[1];
|
|
79
|
+
const out = {};
|
|
80
|
+
let cpuMs = 0;
|
|
81
|
+
for (const p of phases) {
|
|
82
|
+
const t = performance.now();
|
|
83
|
+
const r = await box.exec(withCpu(phaseCommand(p.cmd, repeat)), { timeoutSeconds: repeat > 1 ? 900 : 300 });
|
|
84
|
+
if (r.exitCode !== 0)
|
|
85
|
+
throw new Error(`task phase ${p.id} exited ${r.exitCode}: ${(r.stderr || r.stdout).slice(0, 120)}`);
|
|
86
|
+
out[p.id] = Math.max(1, Math.round(performance.now() - t - overhead));
|
|
87
|
+
const line = r.stdout.split("\n").find((l) => l.startsWith(`${MARK}|`));
|
|
88
|
+
const used = line ? busyMs(line.split("|")[1] ?? "", line.split("|")[2] ?? "") : undefined;
|
|
89
|
+
cpuMs = cpuMs === undefined || used === undefined ? undefined : cpuMs + used;
|
|
90
|
+
}
|
|
91
|
+
return { ms: out, ...(cpuMs !== undefined ? { cpuMs } : {}) };
|
|
92
|
+
}
|
|
93
|
+
/** The whole task's time: the phases added up. */
|
|
94
|
+
export const taskMs = (phases) => Object.values(phases).reduce((s, ms) => s + ms, 0);
|
|
95
|
+
/**
|
|
96
|
+
* What one task would be billed, USD, on a sandbox of `size`. It's billed from create until the task is
|
|
97
|
+
* done: the start time plus the task, rounded up to the provider's minimum charge and billing increment,
|
|
98
|
+
* plus its per-sandbox charge.
|
|
99
|
+
*
|
|
100
|
+
* Providers that bill CPU only while busy are charged for the CPU time the task really used (`cpuMillis`,
|
|
101
|
+
* at least their CPU floor) plus their memory for the whole time; their minimum charge covers memory only
|
|
102
|
+
* where that's how they bill (Vercel). Without `cpuMillis` they're charged as if every core was busy.
|
|
103
|
+
* `billedVsList` scales the price by what the provider was measured to really bill.
|
|
104
|
+
*/
|
|
105
|
+
export function taskUsd(provider, size, createMs, taskMillis, cpuMillis, billedVsList = 1) {
|
|
106
|
+
const { minSeconds, incrementSeconds, perSandboxUsd } = billingRules(provider);
|
|
107
|
+
const seconds = (createMs + taskMillis) / 1000;
|
|
108
|
+
const billed = Math.max(minSeconds, Math.ceil(seconds / incrementSeconds - 1e-9) * incrementSeconds);
|
|
109
|
+
const full = hourlyCost(provider, size);
|
|
110
|
+
const cpuFull = cpuHourlyAtFull(provider, size);
|
|
111
|
+
if (cpuFull === 0 || cpuMillis === undefined)
|
|
112
|
+
return (billedVsList * full * billed) / 3600 + perSandboxUsd;
|
|
113
|
+
const { vcpuHour, cpuFloor = 0 } = info(provider).pricing;
|
|
114
|
+
const vcpus = cpuFull / vcpuHour;
|
|
115
|
+
const cpuSeconds = Math.max(cpuMillis / 1000, cpuFloor * vcpus * seconds);
|
|
116
|
+
// Memory (and anything else that isn't CPU) is billed for the whole time, minimum included.
|
|
117
|
+
return (billedVsList * ((full - cpuFull) * billed + vcpuHour * cpuSeconds)) / 3600 + perSandboxUsd;
|
|
118
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -26,6 +26,13 @@ export interface SandboxSpec {
|
|
|
26
26
|
* cheaper per hour but charges a full minute.
|
|
27
27
|
*/
|
|
28
28
|
expectedSeconds?: number;
|
|
29
|
+
/**
|
|
30
|
+
* How busy the CPU will be, 0 to 1 (default 1). Only a pricing hint: providers that bill CPU only
|
|
31
|
+
* while it's busy (Vercel, Cloudflare, Tensorlake, AgentCore, Sail, Sprites, Deno, Upstash) are priced
|
|
32
|
+
* at this share of their CPU plus their full memory, never below a provider's CPU floor. An agent that
|
|
33
|
+
* mostly waits on model calls uses about 0.1; a build or test run is close to 1.
|
|
34
|
+
*/
|
|
35
|
+
cpuUtilization?: number;
|
|
29
36
|
/**
|
|
30
37
|
* Provider-specific image/template, keyed by provider, e.g.
|
|
31
38
|
* { maritime: "python", e2b: "code-interpreter-v1", modal: "python:3.13-slim" }.
|
package/dist/validate.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type RouteOptions, type SandboxSpec, type Strategy } from "./types.js";
|
|
2
2
|
/** Every key a SandboxSpec can have. Anything else in a request is a mistake (e.g. "memory" for "memoryGb"). */
|
|
3
|
-
export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "image", "metadata"];
|
|
3
|
+
export declare const SPEC_KEYS: readonly ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "cpuUtilization", "image", "metadata"];
|
|
4
4
|
/** Every key RouteOptions can have. */
|
|
5
5
|
export declare const ROUTE_KEYS: readonly ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds", "maxHourlyUsd"];
|
|
6
6
|
export declare const STRATEGIES: readonly Strategy[];
|
package/dist/validate.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CATALOG } from "./catalog.js";
|
|
2
2
|
import { RouterError } from "./types.js";
|
|
3
3
|
/** Every key a SandboxSpec can have. Anything else in a request is a mistake (e.g. "memory" for "memoryGb"). */
|
|
4
|
-
export const SPEC_KEYS = ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "image", "metadata"];
|
|
4
|
+
export const SPEC_KEYS = ["vcpu", "memoryGb", "gpu", "env", "timeoutMinutes", "expectedSeconds", "cpuUtilization", "image", "metadata"];
|
|
5
5
|
/** Every key RouteOptions can have. */
|
|
6
6
|
export const ROUTE_KEYS = ["provider", "strategy", "fallback", "require", "createTimeoutSeconds", "deadlineSeconds", "maxHourlyUsd"];
|
|
7
7
|
export const STRATEGIES = ["default", "balanced", "verified", "cheapest", "fastest"];
|
|
@@ -20,6 +20,9 @@ export function validate(spec = {}, route = {}) {
|
|
|
20
20
|
if (spec[k] !== undefined && !positive(spec[k]))
|
|
21
21
|
throw bad(`${k} must be a positive number, got ${show(spec[k])}`);
|
|
22
22
|
}
|
|
23
|
+
if (spec.cpuUtilization !== undefined && !(positive(spec.cpuUtilization) && spec.cpuUtilization <= 1)) {
|
|
24
|
+
throw bad(`cpuUtilization must be more than 0 and at most 1, got ${show(spec.cpuUtilization)}`);
|
|
25
|
+
}
|
|
23
26
|
if (spec.gpu !== undefined && (typeof spec.gpu !== "string" || !spec.gpu))
|
|
24
27
|
throw bad(`gpu must be a GPU type such as "T4", got ${JSON.stringify(spec.gpu)}`);
|
|
25
28
|
for (const k of ["env", "image", "metadata"]) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sandboxrouter/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "One API for every sandbox provider: route AI agents' code by price, speed or capability, with automatic fallback. Free and open source.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|