Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 70 additions & 6 deletions apps/server/src/providers/vast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,40 @@ setsid nohup bash /root/vmbridge-idle.sh >/dev/null 2>&1 < /dev/null &`;
/** Hosts set an end date on each offer, when they may take the machine back. VM Bridge skips offers ending sooner. */
const leastDurationS = 14 * 86_400;

/**
* Machines whose rented container failed to start or never let VM Bridge in over SSH, by Vast.ai machine ID, with
* when to try them again. The cheapest offer is often the same broken machine, so without this every new VM would
* rent it first and lose minutes to it. Kept for this process only, across drivers, so changing a setting keeps it.
*/
const failedMachines = new Map<number, number>();
const failedMachineMs = 24 * 60 * 60_000;
const failedMachineLimit = 200;

/** Machines to leave out of the search now. */
export function skippedMachines(now = Date.now()) {
for (const [machine, until] of failedMachines) if (until <= now) failedMachines.delete(machine);
return [...failedMachines.keys()];
}

/** Leaves `machine` out of searches for a day. */
export function skipMachine(machine: number, now = Date.now()) {
failedMachines.delete(machine);
failedMachines.set(machine, now + failedMachineMs);
// The oldest go first: a Map keeps insertion order.
while (failedMachines.size > failedMachineLimit) failedMachines.delete(failedMachines.keys().next().value!);
}

/** The highest price per hour a setting allows, or undefined for none. Throws a readable error for a value that is not a price. */
export function maxPrice(value: string | undefined) {
const trimmed = value?.trim();
if (!trimmed) return undefined;
const text = trimmed.replace(/^\$/, "").trim();
const price = Number(text);
// Number("") is 0, so a lone "$" is refused here too.
if (!text || !Number.isFinite(price) || price <= 0) throw fail(`The Vast.ai max price per hour must be a number of dollars, such as 0.50, not "${value}".`, "invalid_argument");
return price;
}

interface Instance {
id: number;
label: string | null;
Expand All @@ -94,6 +128,7 @@ interface Instance {

interface Offer {
id: number;
machine_id?: number;
gpu_name: string;
dph_total: number;
}
Expand All @@ -102,6 +137,8 @@ export interface VastOptions {
apiKey: string;
/** A choice from the GPU field, or empty for the cheapest. */
gpu?: string;
/** The max price per hour field, in dollars. Empty: no limit. */
maxPrice?: string;
/** For tests. Default: the global `fetch`. */
fetch?: Fetch;
/** For tests. Default: SSH (vast-ssh.ts). */
Expand Down Expand Up @@ -130,6 +167,14 @@ export type VastProvider = Provider<Record<string, never>, "pause" | "size"> & {

const fail = (message: string, code: ErrorCode, sandboxId?: string) => new SandboxError(message, { code, provider: "vast", sandboxId });

/** Errors that show the rented machine itself is broken: its container stopped or never started, or SSH never let VM Bridge in. */
const machineFaults = new WeakSet<object>();
function machineFault(message: string, code: ErrorCode, sandboxId: string) {
const error = fail(message, code, sandboxId);
machineFaults.add(error);
return error;
}

/** ssh's own last line on a failed connection, as ": reason", with any IPv4 address left out. */
function sshReason(stderr: string) {
const line = stderr.trim().split("\n").at(-1)?.trim().replace(/\b\d{1,3}(?:\.\d{1,3}){3}\b/g, "the host");
Expand Down Expand Up @@ -296,7 +341,7 @@ export function vast(options: VastOptions): VastProvider {
const status = current.actual_status ?? "";
if (status !== "exited" && status !== "stopped") left = true;
if ((status === "exited" && left) || status === "offline") {
throw fail(`The Vast.ai machine ${status === "exited" ? "stopped its container" : "went offline"} while starting`, "unavailable", id);
throw machineFault(`The Vast.ai machine ${status === "exited" ? "stopped its container" : "went offline"} while starting`, "unavailable", id);
}
if (current.cur_state === "scheduling" || status === "scheduling") scheduling ??= Date.now();
if (scheduling !== undefined && Date.now() - scheduling > timing.schedulingMs) {
Expand All @@ -312,9 +357,9 @@ export function vast(options: VastOptions): VastProvider {
}
const sshGivenUp = running !== undefined && Date.now() - running > timing.sshMs;
if (sshError !== undefined && (sshGivenUp || Date.now() > deadline)) {
throw fail(`The Vast.ai machine runs but did not answer over SSH${sshError}`, "timeout", id);
throw machineFault(`The Vast.ai machine runs but did not answer over SSH${sshError}`, "timeout", id);
}
if (Date.now() > deadline) throw fail("The Vast.ai machine did not start in time", "timeout", id);
if (Date.now() > deadline) throw machineFault("The Vast.ai machine did not start in time", "timeout", id);
await sleep(timing.pollMs);
}
}
Expand All @@ -331,6 +376,8 @@ export function vast(options: VastOptions): VastProvider {

async function offers(size: VmSize) {
const { cores, ramMb, diskGb } = vastSizes[size];
const highest = maxPrice(options.maxPrice);
const skipped = skippedMachines();
const { offers: found } = await json<{ offers: Offer[] }>("POST", "/v0/bundles/", undefined, {
verified: { eq: true },
external: { eq: false },
Expand All @@ -340,18 +387,24 @@ export function vast(options: VastOptions): VastProvider {
// SSH straight to the host, which Vast.ai calls faster and more reliable than its proxy.
direct_port_count: { gte: 1 },
disk_space: { gte: diskGb },
inet_down: { gte: 200 },
// Each new VM downloads its image, Node, T3 and the agents, so a slow line makes it slow to start.
inet_down: { gte: 500 },
reliability2: { gte: 0.97 },
cpu_cores_effective: { gte: cores },
cpu_ram: { gte: ramMb },
duration: { gte: leastDurationS },
...(gpuNames.length ? { gpu_name: { in: gpuNames } } : {}),
...(highest !== undefined ? { dph_total: { lte: highest } } : {}),
...(skipped.length ? { machine_id: { notin: skipped } } : {}),
order: [["dph_total", "asc"]],
type: "on-demand",
allocated_storage: diskGb,
limit: 5,
});
if (!found.length) throw fail("Vast.ai has no machine for this size right now. Try another size or GPU, or try again later.", "quota");
if (!found.length) {
const price = highest !== undefined ? ` under $${highest} an hour` : "";
throw fail(`Vast.ai has no machine for this size${price} right now. Try another size or GPU${price ? ", a higher max price" : ""}, or try again later.`, "quota");
}
return found;
}

Expand Down Expand Up @@ -407,6 +460,9 @@ export function vast(options: VastOptions): VastProvider {
return info(ready, labels);
} catch (error) {
lastError = error;
// The machine itself would not start or let VM Bridge in: the next VM should not rent it again. Other failures,
// such as an API error or setup failing after SSH worked, say nothing about the machine.
if (offer.machine_id !== undefined && machineFaults.has(error as object)) skipMachine(offer.machine_id);
await destroy(id).catch(() => {});
}
}
Expand Down Expand Up @@ -573,6 +629,14 @@ export const vastProvider: ProviderDefinition = {
required: false,
options: Object.keys(gpuModels).map((value) => ({ value, label: value || "Cheapest available" })),
},
{
key: "maxPrice",
label: "Max price per hour",
kind: "text",
required: false,
placeholder: "0.50",
help: "In dollars, for the whole machine. VM Bridge rents nothing that costs more. Empty: no limit.",
},
],
features: {
// A stopped container keeps its disk. Memory and processes go, and T3 starts again on wake.
Expand All @@ -588,7 +652,7 @@ export const vastProvider: ProviderDefinition = {
defaultSize: "small",

open(config) {
const provider = vast({ apiKey: required(config, "apiKey", "Vast.ai API key"), gpu: config.values.gpu });
const provider = vast({ apiKey: required(config, "apiKey", "Vast.ai API key"), gpu: config.values.gpu, maxPrice: config.values.maxPrice });
return { ...sdkDriver({ id: "vast", provider, sleep: "pause" }), verify: provider.verify };
},
};
83 changes: 82 additions & 1 deletion apps/server/test/vast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { SandboxError } from "@opencoredev/sandbox-sdk";
import { parseLabel, sshTarget, vast } from "../src/providers/vast.ts";
import { maxPrice, parseLabel, skipMachine, skippedMachines, sshTarget, vast } from "../src/providers/vast.ts";
import type { RunOptions, RunResult, Transport } from "../src/providers/vast-ssh.ts";

interface Call {
Expand Down Expand Up @@ -222,6 +222,87 @@ describe("Vast.ai instances", () => {
});
});

describe("Vast.ai offer search", () => {
test("a machine that failed to start is left out of the next VM's search", async () => {
let rented = 0;
const searches: Record<string, unknown>[] = [];
const { fetch } = fakeApi((call) => {
if (call.path === "/v0/ssh/" && call.method === "GET") return { json: [{ id: 1, public_key: "ssh-ed25519 AAAAvmbridge vmbridge" }] };
if (call.path === "/v0/bundles/") {
searches.push(call.body as Record<string, unknown>);
return { json: { offers: [{ id: 201, machine_id: 9001, gpu_name: "GTX 1070", dph_total: 0.058 }, { id: 202, machine_id: 9002, gpu_name: "GTX 1660 S", dph_total: 0.067 }] } };
}
if (call.path.startsWith("/v0/asks/")) return { json: { success: true, new_contract: 7 + rented++ } };
// The first machine's container stops while starting; every later one runs.
if (call.path === "/v0/instances/7/" && call.method === "GET") return { json: { instances: instance("exited") } };
const id = Number(call.path.split("/")[3]);
if (call.method === "GET" && id > 7) return { json: { instances: { ...instance("running"), id } } };
return undefined;
});
const provider = vast({ apiKey: "vast_secret", fetch, transport: recordingTransport().transport, publicKey, timing });

await provider.create({ key: "vm-1", size: "small", labels: { vmbridge: "b1" } });
await provider.create({ key: "vm-2", size: "small", labels: { vmbridge: "b1" } });

expect((searches[1]!.machine_id as { notin: number[] }).notin).toContain(9001);
expect((searches[1]!.machine_id as { notin: number[] }).notin).not.toContain(9002);
});

test("a machine where setup fails after SSH worked is not left out of later searches", async () => {
let rented = 0;
const searches: Record<string, unknown>[] = [];
const { fetch } = fakeApi((call) => {
if (call.path === "/v0/ssh/" && call.method === "GET") return { json: [{ id: 1, public_key: "ssh-ed25519 AAAAvmbridge vmbridge" }] };
if (call.path === "/v0/bundles/") {
searches.push(call.body as Record<string, unknown>);
return { json: { offers: [{ id: 301, machine_id: 9101, gpu_name: "GTX 1070", dph_total: 0.058 }, { id: 302, machine_id: 9102, gpu_name: "GTX 1660 S", dph_total: 0.067 }] } };
}
if (call.path.startsWith("/v0/asks/")) return { json: { success: true, new_contract: 7 + rented++ } };
const id = Number(call.path.split("/")[3]);
if (call.method === "GET" && id >= 7) return { json: { instances: { ...instance("running"), id } } };
return undefined;
});
// SSH works everywhere, but setup on the first machine fails, as when a package mirror is down.
const transport: Transport = {
...recordingTransport().transport,
run: async (id, command) => ({ exitCode: id === "7" && command.includes("mkdir -p /workspace") ? 100 : 0, stdout: new Uint8Array(), stderr: "" }),
};
const provider = vast({ apiKey: "vast_secret", fetch, transport, publicKey, timing });

expect((await provider.create({ key: "vm-1", size: "small", labels: { vmbridge: "b1" } })).id).toBe("8");
await provider.create({ key: "vm-2", size: "small", labels: { vmbridge: "b1" } });

expect((searches[1]!.machine_id as { notin: number[] } | undefined)?.notin ?? []).not.toContain(9101);
});

test("a skipped machine is searched again after a day", () => {
skipMachine(424242, 0);
expect(skippedMachines(1_000)).toContain(424242);
expect(skippedMachines(24 * 60 * 60_000 + 1)).not.toContain(424242);
});

test("the max price setting caps the search, and asks for faster networks", async () => {
const { calls, fetch } = fakeApi((call) => (call.path === "/v0/bundles/" ? { json: { offers: [] } } : call.path === "/v0/ssh/" ? { json: [] } : undefined));
const provider = vast({ apiKey: "vast_secret", maxPrice: "$0.50", fetch, transport: recordingTransport().transport, publicKey, timing });

const error = (await provider.create({ key: "vm-1", size: "small", labels: { vmbridge: "b1" } }).catch((caught: unknown) => caught)) as SandboxError;

expect(calls.find((call) => call.path === "/v0/bundles/")!.body).toMatchObject({ dph_total: { lte: 0.5 }, inet_down: { gte: 500 } });
expect(error.code).toBe("quota");
expect(error.message).toContain("under $0.5 an hour");
});

test("a max price that is not a price is refused with a reason, and an empty one sets no limit", () => {
expect(maxPrice("")).toBeUndefined();
expect(maxPrice(" ")).toBeUndefined();
expect(maxPrice("$0.50")).toBe(0.5);
expect(() => maxPrice("$")).toThrow("must be a number of dollars");
expect(maxPrice(" 1.25 ")).toBe(1.25);
expect(() => maxPrice("cheap")).toThrow("must be a number of dollars");
expect(() => maxPrice("0")).toThrow("must be a number of dollars");
});
});

describe("Vast.ai commands and files", () => {
const dir = mkdtempSync(join(tmpdir(), "vast-test-"));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
Expand Down
Loading