import { test, describe } from "node:test"; import assert from "node:assert/strict"; import * as E from "../lib/engine.mjs"; import { parsePublicKey } from "../lib/sshkey.mjs"; import { memoryStore, transact } from "../lib/store.mjs"; import { A, B, KEY, RATE, T0, conserved, credits, funded, hash, running, sshKey } from "./helpers.mjs"; const SSH = { host: "10.0.0.1", port: 2222, user: "root" }; const s = (n) => T0 + n * 1000; const entries = (state, type, address = A) => state.ledger.filter((e) => e.address === address && e.type === type); describe("money", () => { test("a second is billed rounded up to the micro-dollar, an hour is exactly the rate", () => { assert.equal(E.dueMicro(RATE, 1), 200); assert.equal(E.dueMicro(RATE, 3600), RATE); assert.equal(E.dueMicro(590_040, 1), 164); // 163.9 rounds up assert.equal(E.dueMicro(590_040, 0), 0); assert.equal(E.dueMicro(1, 1), 1); }); test("the rate is the provider's price plus the margin, rounded up", () => { assert.equal(E.rateFor(0.44, 2000), 528_000); assert.equal(E.rateFor(0.44, 0), 440_000); assert.equal(E.rateFor(0.446849, 2000), 536_219); // 536218.8 rounds up assert.equal(E.rateFor(2.5, 1500), 2_875_000); }); }); describe("renting", () => { test("needs an SSH key, then credits for 10 minutes", () => { const state = E.emptyState(); assert.equal(E.rent(state, { address: A, gpu: "h100", rate: RATE, now: T0 }).error, "no-ssh-key"); assert.deepEqual(state, E.emptyState(), "a refusal writes nothing"); E.addSshKey(state, { address: A, name: "k", publicKey: KEY, now: T0 }); const poor = E.rent(state, { address: A, gpu: "h100", rate: RATE, now: T0 }); assert.equal(poor.error, "insufficient-credits"); assert.equal(poor.neededUsd, 0.12); // 600 s at 200 micro-dollars E.claim(state, { address: A, txHash: hash(1), micro: 119_999, now: T0 }); assert.equal(E.rent(state, { address: A, gpu: "h100", rate: RATE, now: T0 }).error, "insufficient-credits"); E.claim(state, { address: A, txHash: hash(2), micro: 1, now: T0 }); const ok = E.rent(state, { address: A, gpu: "h100", rate: RATE, now: T0 }); assert.equal(ok.ok, true); assert.equal(ok.instance.status, "requested"); assert.deepEqual(ok.publicKeys, [KEY.split(" ").slice(0, 2).join(" ")]); assert.equal(credits(state), 120_000, "booking charges nothing"); }); test("credits must cover 10 minutes of everything already live, not only of the new one", () => { const state = funded(0.3); // 300 000: two instances need 240 000, three need 360 000 assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).ok, true); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).ok, true); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).error, "insufficient-credits"); }); test("at most 3 live instances; an ended one frees a place", () => { const state = funded(100); const ids = [1, 2, 3].map(() => E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).instance.id); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).error, "limit"); E.end(state, { address: A, id: ids[0], now: T0 }); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).ok, true); }); test("uses the keys asked for, and refuses a key that is not on the account", () => { const state = funded(10); const second = E.addSshKey(state, { address: A, name: "desk", publicKey: sshKey(), now: T0 }).key; assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, sshKeyIds: [second.id], now: T0 }).publicKeys[0], second.publicKey); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).publicKeys.length, 2); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, sshKeyIds: ["k9999"], now: T0 }).error, "not-found"); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, sshKeyIds: [], now: T0 }).error, "invalid"); }); test("the rate is fixed at creation", () => { const state = funded(10); const inst = running(state); E.settle(state, s(3600)); assert.equal(inst.rate, RATE); assert.equal(inst.charged, RATE); }); }); describe("the meter", () => { test("billing starts when the machine is seen running with SSH open, not at the request", () => { const state = funded(10); const { instance } = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }); E.attach(state, { id: instance.id, providerId: "pod-1", now: s(2) }); E.observe(state, { id: instance.id, obs: { status: "starting", ssh: null }, now: s(60) }); E.settle(state, s(120)); assert.equal(instance.status, "starting"); assert.equal(credits(state), 10_000_000, "two minutes of starting cost nothing"); // Running without an SSH address is still not ready. E.observe(state, { id: instance.id, obs: { status: "running", ssh: null }, now: s(150) }); assert.equal(instance.status, "starting"); E.observe(state, { id: instance.id, obs: { status: "running", ssh: SSH }, now: s(180) }); assert.equal(instance.status, "running"); assert.equal(instance.startedAt, s(180)); E.settle(state, s(190)); assert.equal(instance.seconds, 10); assert.equal(credits(state), 10_000_000 - 2000); }); test("settling charges the seconds since the last settlement, and twice at the same moment charges once", () => { const state = funded(10); const inst = running(state); E.settle(state, s(30)); assert.equal(inst.charged, 6000); const snapshot = JSON.stringify(state); assert.deepEqual(E.settle(state, s(30)), { ended: [] }); assert.equal(JSON.stringify(state), snapshot); E.settle(state, s(30) + 999); // not a whole second more assert.equal(inst.charged, 6000); E.settle(state, s(29)); // a clock that went back assert.equal(inst.charged, 6000); E.settle(state, s(31)); assert.equal(inst.charged, 6200); assert.ok(conserved(state)); }); test("rounding over many settlements never drifts: the total is one rounding, not thousands", () => { const rate = 590_041; // 163.9 micro-dollars per second: every settlement lands between two micro-dollars const state = funded(1000); const inst = running(state, { rate }); let t = T0; let paid = 0; for (let i = 0; i < 5000; i++) { t += 1000 + ((i * 7919) % 4000); // 1 to 5 seconds, irregular, sometimes mid-second const before = credits(state); E.settle(state, t); const now = before - credits(state); assert.ok(now >= 0); paid += now; const seconds = Math.floor((t - T0) / 1000); assert.equal(inst.seconds, seconds); assert.equal(inst.charged, Math.ceil((rate * seconds) / 3600), "what is owed is the exact amount, rounded up once"); assert.ok(inst.charged * 3600 <= rate * seconds + 3600, "never more than elapsed x rate + 1 micro-dollar"); } assert.equal(paid, inst.charged); assert.equal(inst.unpaid, 0); assert.ok(conserved(state)); }); test("two accounts are metered apart", () => { const state = funded(10); E.claim(state, { address: B, txHash: hash(9), micro: 5_000_000, now: T0 }); E.addSshKey(state, { address: B, name: "k", publicKey: sshKey(), now: T0 }); running(state); running(state, { address: B, rate: 360_000 }); E.settle(state, s(100)); assert.equal(credits(state, A), 10_000_000 - 20_000); assert.equal(credits(state, B), 5_000_000 - 10_000); }); }); describe("running out", () => { test("an instance is ended when its account cannot cover the next 60 seconds", () => { const state = funded(0.2); // 200 000 micro-dollars: 1000 seconds at 200 per second const inst = running(state); assert.deepEqual(E.settle(state, s(939)).ended, []); // 12 200 left, the next minute is 12 000 assert.equal(inst.status, "running"); const { ended } = E.settle(state, s(941)); assert.equal(ended.length, 1); assert.equal(inst.status, "ended"); assert.equal(inst.reason, "out-of-credits"); assert.equal(inst.endedAt, s(941)); assert.equal(credits(state), 200_000 - 941 * 200); assert.ok(credits(state) >= 0); assert.equal(ended[0].micro, 941 * 200); assert.equal(ended[0].seconds, 941); // Its machine is now owed to the provider, and nothing more is charged. assert.deepEqual(E.pending(state).release, [{ id: inst.id, providerId: "pod-" + inst.id }]); E.settle(state, s(5000)); assert.equal(credits(state), 200_000 - 941 * 200); }); test("with several instances the newest go first, until the rest is covered", () => { const state = funded(1); const first = running(state); const second = running(state, { at: s(10) }); const third = running(state, { at: s(20) }); state.accounts[A].credits = 30_000; // covers two next minutes (24 000), not three (36 000) E.settle(state, s(20)); assert.deepEqual([first.status, second.status, third.status], ["running", "running", "ended"]); state.accounts[A].credits = 5_000; E.settle(state, s(20)); assert.deepEqual([first.status, second.status], ["ended", "ended"]); }); test("a late settlement never takes an account below zero; what could not be charged is recorded", () => { const state = funded(0.2); const inst = running(state); E.settle(state, s(3600)); // an hour late: 720 000 owed, 200 000 there assert.equal(credits(state), 0); assert.equal(inst.charged, 200_000); assert.equal(inst.unpaid, 520_000); assert.equal(inst.status, "ended"); assert.ok(conserved(state)); }); test("a machine that becomes ready for an account that can no longer pay a minute is not started", () => { const state = funded(1); const { instance } = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }); E.attach(state, { id: instance.id, providerId: "pod-1", now: T0 }); state.accounts[A].credits = 11_999; E.observe(state, { id: instance.id, obs: { status: "running", ssh: SSH }, now: s(30) }); assert.equal(instance.status, "failed"); assert.equal(instance.reason, "out-of-credits"); assert.equal(credits(state), 11_999); }); }); describe("a machine that never comes", () => { test("not ready within 10 minutes: given up, released, and it costs nothing", () => { const state = funded(10); const { instance } = E.rent(state, { address: A, gpu: "h100", rate: RATE, now: T0 }); E.attach(state, { id: instance.id, providerId: "pod-1", now: T0 }); E.observe(state, { id: instance.id, obs: { status: "starting", ssh: null }, now: s(599) }); assert.equal(instance.status, "starting"); E.observe(state, { id: instance.id, obs: { status: "starting", ssh: null }, now: s(600) }); assert.equal(instance.status, "failed"); assert.equal(instance.reason, "never-ready"); assert.equal(credits(state), 10_000_000); assert.equal(entries(state, "charge").length, 0); const [refund] = entries(state, "refund"); assert.equal(refund.micro, 0); assert.equal(refund.instanceId, instance.id); assert.deepEqual(E.pending(state).release, [{ id: instance.id, providerId: "pod-1" }]); E.settle(state, s(9999)); assert.equal(credits(state), 10_000_000); // A place is free again. assert.equal(Object.values(state.instances).filter((i) => i.status === "failed").length, 1); }); test("expire() gives up without the provider's word: a request never acknowledged, a start never finished", () => { const state = funded(10); const a = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).instance; // the provider never answered const b = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).instance; E.attach(state, { id: b.id, providerId: "pod-b", now: T0 }); assert.deepEqual(E.expire(state, s(179)).failed, []); assert.deepEqual(E.expire(state, s(180)).failed, [a.id]); assert.equal(a.reason, "provider-timeout"); assert.deepEqual(E.expire(state, s(600)).failed, [b.id]); assert.equal(b.reason, "never-ready"); assert.equal(credits(state), 10_000_000); }); test("a start the provider refused costs nothing and leaves no machine to release", () => { const state = funded(10); const { instance } = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }); E.failInstance(state, { id: instance.id, reason: "no-capacity", now: s(1) }); assert.equal(instance.status, "failed"); assert.equal(state.ledger.length, 1, "only the top-up"); assert.deepEqual(E.pending(state), { poll: [], release: [] }); }); }); describe("ending", () => { test("settles one last time and writes a receipt", () => { const state = funded(10); const inst = running(state, { gpu: "h100" }); E.settle(state, s(60)); const r = E.end(state, { address: A, id: inst.id, now: s(75) + 400 }); assert.equal(r.ok, true); assert.equal(r.already, false); assert.deepEqual( { ...r.receipt, id: null }, { id: null, t: s(75) + 400, address: A, type: "charge", micro: 15_000, instanceId: inst.id, gpu: "h100", seconds: 75, rate: RATE, startedAt: T0, endedAt: s(75) + 400, reason: "user" }, ); assert.equal(credits(state), 10_000_000 - 15_000); assert.equal(inst.status, "ended"); const view = E.viewEntry(r.receipt); assert.deepEqual( { usd: view.usd, deltaUsd: view.deltaUsd, secondsBilled: view.secondsBilled, ratePerHourUsd: view.ratePerHourUsd, startedAt: view.startedAt, endedAt: view.endedAt }, { usd: 0.015, deltaUsd: -0.015, secondsBilled: 75, ratePerHourUsd: 0.72, startedAt: new Date(T0).toISOString(), endedAt: new Date(s(75) + 400).toISOString() }, ); }); test("ending twice gives the same receipt and charges nothing more", () => { const state = funded(10); const inst = running(state); const first = E.end(state, { address: A, id: inst.id, now: s(100) }); const snapshot = JSON.stringify(state); const second = E.end(state, { address: A, id: inst.id, now: s(900) }); assert.equal(second.already, true); assert.deepEqual(second.receipt, first.receipt); assert.equal(JSON.stringify(state), snapshot); assert.equal(entries(state, "charge").length, 1); }); test("an end and a tick, in either order, cost the same", () => { const one = funded(10); const i1 = running(one); E.end(one, { address: A, id: i1.id, now: s(100) }); E.settle(one, s(100)); E.settle(one, s(160)); const two = funded(10); const i2 = running(two); E.settle(two, s(100)); E.end(two, { address: A, id: i2.id, now: s(100) }); E.settle(two, s(160)); assert.equal(credits(one), 10_000_000 - 20_000); assert.equal(credits(two), credits(one)); assert.equal(i1.charged, i2.charged); assert.equal(entries(one, "charge").length, 1); assert.equal(entries(two, "charge").length, 1); }); test("an end and a tick at the same instant on a shared store: one of them starts over, nothing is charged twice", async () => { const state = funded(10); const inst = running(state); const store = memoryStore(state); const results = await Promise.all([ transact(store, (st) => E.end(st, { address: A, id: inst.id, now: s(100) })), transact(store, (st) => E.settle(st, s(100))), transact(store, (st) => E.end(st, { address: A, id: inst.id, now: s(100) })), ]); assert.ok(store.conflicts >= 1, "they did collide"); const after = store.peek(); assert.equal(credits(after), 10_000_000 - 20_000); assert.equal(entries(after, "charge").length, 1); assert.equal(results[0].receipt.id, results[2].receipt.id); assert.ok(conserved(after)); }); test("ending before the machine is ready costs nothing and still gives a receipt", () => { const state = funded(10); const { instance } = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }); const r = E.end(state, { address: A, id: instance.id, now: s(5) }); assert.equal(r.receipt.micro, 0); assert.equal(r.receipt.seconds, 0); assert.equal(r.receipt.startedAt, null); // The provider's answer arrives after the end: the machine is recorded so that it gets released. const late = E.attach(state, { id: instance.id, providerId: "pod-late", now: s(6) }); assert.equal(late.live, false); assert.deepEqual(E.pending(state).release, [{ id: instance.id, providerId: "pod-late" }]); E.observe(state, { id: instance.id, obs: { status: "running", ssh: SSH }, now: s(30) }); assert.equal(instance.status, "ended", "a machine that shows up after the end does not start billing"); }); test("nobody ends someone else's instance", () => { const state = funded(10); const inst = running(state); assert.equal(E.end(state, { address: B, id: inst.id, now: s(10) }).error, "not-found"); assert.equal(E.end(state, { address: A, id: "i9999", now: s(10) }).error, "not-found"); assert.equal(inst.status, "running"); }); }); describe("a machine the provider lost", () => { test("billing stops at the last time the provider confirmed it, and what was charged past it comes back", () => { const state = funded(10); const inst = running(state); E.observe(state, { id: inst.id, obs: { status: "running", ssh: SSH }, now: s(60) }); // confirmed at 60 s E.settle(state, s(120)); // the renter looked at the meter at 120 s: charged to there assert.equal(credits(state), 10_000_000 - 24_000); E.observe(state, { id: inst.id, obs: { status: "gone", ssh: null }, now: s(130) }); assert.equal(inst.status, "ended"); assert.equal(inst.reason, "provider-lost"); assert.equal(inst.endedAt, s(60)); assert.equal(credits(state), 10_000_000 - 12_000, "60 seconds are paid, not 120"); const [refund] = entries(state, "refund"); assert.equal(refund.micro, 12_000); assert.equal(refund.seconds, 60); const view = E.viewInstance(inst); assert.equal(view.secondsBilled, 60); assert.equal(view.costUsd, 0.012); assert.ok(conserved(state)); // The ledger adds up to the balance. const sum = E.viewLedger(state, A).reduce((t, e) => t + Math.round(e.deltaUsd * 1e6), 0); assert.equal(sum, credits(state)); }); test("a running machine the provider stops confirming is closed after 5 minutes, at its last confirmation", () => { const state = funded(10); const inst = running(state); E.observe(state, { id: inst.id, obs: { status: "starting", ssh: null }, now: s(200) }); assert.equal(inst.status, "running"); E.observe(state, { id: inst.id, obs: { status: "starting", ssh: null }, now: s(300) }); assert.equal(inst.status, "ended"); assert.equal(inst.endedAt, T0); assert.equal(credits(state), 10_000_000); }); test("a machine lost while starting costs nothing", () => { const state = funded(10); const { instance } = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }); E.attach(state, { id: instance.id, providerId: "pod-1", now: T0 }); E.observe(state, { id: instance.id, obs: { status: "gone", ssh: null }, now: s(40) }); assert.equal(instance.status, "failed"); assert.equal(instance.reason, "provider-lost"); assert.equal(credits(state), 10_000_000); }); }); describe("SSH keys", () => { test("ed25519 and RSA of 2048 bits and more are taken; the comment is dropped", () => { const ed = parsePublicKey(sshKey("ed25519", 0, "me@laptop with spaces")); assert.equal(ed.ok, true); assert.equal(ed.type, "ssh-ed25519"); assert.match(ed.publicKey, /^ssh-ed25519 [A-Za-z0-9+/=]+$/); assert.match(ed.fingerprint, /^SHA256:[A-Za-z0-9+/]{43}$/); const rsa = parsePublicKey(sshKey("rsa", 2048)); assert.equal(rsa.ok, true); assert.equal(rsa.bits, 2048); }); test("everything else is refused", () => { const good = sshKey(); const body = good.split(" ")[1]; assert.match(parsePublicKey(sshKey("rsa", 1024)).reason, /at least 2048/); for (const bad of [ "", "hello", "ssh-dss " + body, "ecdsa-sha2-nistp256 " + body, "ssh-rsa " + body, // an ed25519 body under an RSA label "ssh-ed25519 " + body.slice(0, -8), "ssh-ed25519 not*base64", good + "\nssh-ed25519 " + body, // two keys in one entry "-----BEGIN OPENSSH PRIVATE KEY-----", 'command="rm -rf /" ' + good, // an authorized_keys option in front null, 42, ]) { assert.equal(parsePublicKey(bad).ok, false, String(bad).slice(0, 40)); } }); test("at most 10 per account, no duplicate, and a key can be removed", () => { const state = E.emptyState(); const first = E.addSshKey(state, { address: A, name: "one", publicKey: KEY, now: T0 }); assert.equal(first.ok, true); assert.equal(E.addSshKey(state, { address: A, name: "again", publicKey: KEY + " other comment", now: T0 }).error, "duplicate"); assert.equal(E.addSshKey(state, { address: A, name: "", publicKey: sshKey(), now: T0 }).error, "invalid"); assert.equal(E.addSshKey(state, { address: A, name: "bad", publicKey: "ssh-ed25519 AAAA", now: T0 }).error, "invalid"); for (let i = 0; i < 9; i++) assert.equal(E.addSshKey(state, { address: A, name: "k" + i, publicKey: sshKey(), now: T0 }).ok, true); assert.equal(E.addSshKey(state, { address: A, name: "eleven", publicKey: sshKey(), now: T0 }).error, "limit"); assert.equal(E.removeSshKey(state, { address: B, id: first.key.id }).error, "not-found"); assert.equal(E.removeSshKey(state, { address: A, id: first.key.id }).ok, true); assert.equal(state.accounts[A].sshKeys.length, 9); assert.equal(E.addSshKey(state, { address: A, name: "back", publicKey: KEY, now: T0 }).ok, true); }); }); describe("API keys", () => { const withKey = (usd, capUsd) => { const state = funded(usd); const key = E.addApiKey(state, { address: A, name: "agent", capMicro: Math.round(capUsd * 1e6), hash: "ab".repeat(32), prefix: "idk_abcdef", now: T0 }).key; return { state, key }; }; test("a key is found by the hash of its secret, and only by it", () => { const { state, key } = withKey(10, 1); assert.equal(E.resolveApiKey(state, "ab".repeat(32)).key.id, key.id); assert.equal(E.resolveApiKey(state, "ab".repeat(32)).address, A); assert.equal(E.resolveApiKey(state, "cd".repeat(32)), null); assert.equal(E.addApiKey(state, { address: B, name: "copy", capMicro: 1, hash: "ab".repeat(32), now: T0 }).error, "invalid"); assert.equal(E.addApiKey(state, { address: A, name: "zero", capMicro: 0, hash: "cd".repeat(32), now: T0 }).error, "invalid"); for (let i = 0; i < 9; i++) assert.equal(E.addApiKey(state, { address: A, name: "k" + i, capMicro: 1, hash: i.toString(16).padStart(64, "0"), now: T0 }).ok, true); assert.equal(E.addApiKey(state, { address: A, name: "eleven", capMicro: 1, hash: "ef".repeat(32), now: T0 }).error, "limit"); }); test("a key cannot start what its daily cap does not cover for 10 minutes", () => { const { state, key } = withKey(10, 0.1); // 100 000 a day; 10 minutes are 120 000 assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, keyId: key.id, now: T0 }).error, "key-cap"); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).ok, true, "the wallet itself is not capped"); }); test("an instance started by a key is ended when the cap cannot cover the next minute, and the cap is never passed", () => { const { state, key } = withKey(10, 0.2); // 200 000 a day const inst = running(state, { keyId: key.id }); E.settle(state, s(939)); assert.equal(inst.status, "running"); E.settle(state, s(941)); assert.equal(inst.status, "ended"); assert.equal(inst.reason, "key-cap"); assert.equal(key.spent, 941 * 200); assert.ok(key.spent <= key.cap); assert.equal(E.viewApiKey(key, s(941)).spentTodayUsd, 0.1882); // Even settled an hour late, the key pays no more than its cap. const late = withKey(10, 0.2); const li = running(late.state, { keyId: late.key.id }); E.settle(late.state, s(3600)); assert.equal(late.key.spent, 200_000); assert.equal(li.unpaid, 520_000); assert.equal(credits(late.state), 10_000_000 - 200_000); }); test("the cap counts per UTC day", () => { const { state, key } = withKey(10, 0.2); const evening = Date.UTC(2026, 10, 29, 23, 50, 0); const inst = running(state, { keyId: key.id, at: evening }); E.settle(state, evening + 500_000); // 23:58:20, 100 000 spent assert.equal(key.spent, 100_000); E.settle(state, evening + 700_000); // 00:01:40 the next day: the count starts again assert.equal(key.day, "2026-11-30"); assert.equal(key.spent, 40_000); assert.equal(inst.status, "running"); assert.equal(E.viewApiKey(key, evening + 700_000).spentTodayUsd, 0.04); }); test("stopping a key ends its instances and only its instances; a stopped key starts nothing", () => { const { state, key } = withKey(10, 5); const byKey = running(state, { keyId: key.id }); const byWallet = running(state); const r = E.stopApiKey(state, { address: A, id: key.id, now: s(50) }); assert.equal(r.ended.length, 1); assert.equal(r.ended[0].micro, 10_000); assert.equal(byKey.status, "ended"); assert.equal(byKey.reason, "key-stopped"); assert.equal(byWallet.status, "running"); assert.equal(key.stopped, true); assert.equal(E.rent(state, { address: A, gpu: "a", rate: RATE, keyId: key.id, now: s(60) }).error, "key-stopped"); assert.equal(E.stopApiKey(state, { address: B, id: key.id, now: s(60) }).error, "not-found"); }); test("deleting a key ends its instances and forgets its hash", () => { const { state, key } = withKey(10, 5); const inst = running(state, { keyId: key.id }); const r = E.deleteApiKey(state, { address: A, id: key.id, now: s(50) }); assert.equal(r.ended.length, 1); assert.equal(inst.status, "ended"); assert.equal(E.resolveApiKey(state, "ab".repeat(32)), null); assert.equal(state.accounts[A].apiKeys.length, 0); assert.equal(E.deleteApiKey(state, { address: A, id: key.id, now: s(60) }).error, "not-found"); }); }); describe("credits", () => { test("a transaction hash is credited once, ever, to anyone", () => { const state = E.emptyState(); const r = E.claim(state, { address: A, txHash: hash(7), micro: 2_500_000, block: 1234, now: T0 }); assert.equal(r.ok, true); assert.equal(r.credits, 2_500_000); assert.equal(E.claim(state, { address: A, txHash: hash(7), micro: 2_500_000, now: T0 }).error, "already-claimed"); assert.equal(E.claim(state, { address: B, txHash: hash(7), micro: 2_500_000, now: T0 }).error, "already-claimed"); assert.equal(credits(state), 2_500_000); assert.equal(state.accounts[B], undefined); for (const bad of [0, -5, 1.5, NaN]) assert.equal(E.claim(state, { address: A, txHash: hash(8), micro: bad, now: T0 }).error, "invalid"); assert.equal(E.claim(state, { address: A, txHash: "0x12", micro: 1, now: T0 }).error, "invalid"); assert.deepEqual(E.viewLedger(state, A).map((e) => [e.type, e.usd, e.txHash, e.block]), [["topup", 2.5, hash(7), 1234]]); // A top-up written before any other token was taken says nothing of its token: it was USDC, one for one. assert.deepEqual(E.viewLedger(state, A).map((e) => [e.token, e.amount]), [["USDC", "2.5"]]); }); test("the ledger records what was sent: the token, the amount, and for EQNVDA the two prices and the haircut", () => { const state = E.emptyState(); E.claim(state, { address: A, txHash: hash(1), micro: 10_000_000, now: T0, paid: { token: "USDC", amount: "10", priceUsd: 1 } }); const paid = { token: "EQNVDA", amount: "1.5", poolPriceUsd: 151.368838, markUsd: 151.305, priceUsd: 151.305, haircutBps: 100 }; const r = E.claim(state, { address: A, txHash: hash(2), micro: 224_687_925, block: 77, now: T0 + 1000, paid }); assert.equal(r.ok, true); assert.equal(credits(state), 234_687_925); const [equity, usdc] = E.viewLedger(state, A); assert.deepEqual( { type: equity.type, usd: equity.usd, deltaUsd: equity.deltaUsd, token: equity.token, amount: equity.amount, poolPriceUsd: equity.poolPriceUsd, markUsd: equity.markUsd, priceUsd: equity.priceUsd, haircutBps: equity.haircutBps, block: equity.block }, { type: "topup", usd: 224.687925, deltaUsd: 224.687925, token: "EQNVDA", amount: "1.5", poolPriceUsd: 151.368838, markUsd: 151.305, priceUsd: 151.305, haircutBps: 100, block: 77 }, ); assert.deepEqual([usdc.token, usdc.amount, usdc.priceUsd, "poolPriceUsd" in usdc], ["USDC", "10", 1, false]); // The same hash is refused whatever it is said to carry the second time. assert.equal(E.claim(state, { address: A, txHash: hash(2), micro: 1, now: T0, paid: { token: "USDC", amount: "0.000001" } }).error, "already-claimed"); for (const bad of [{ token: "eqnvda", amount: "1" }, { token: "EQNVDA", amount: "1e3" }, { token: "EQNVDA" }, { amount: "1" }, { token: "", amount: "1" }]) { assert.equal(E.claim(state, { address: A, txHash: hash(3), micro: 1, now: T0, paid: bad }).error, "invalid", JSON.stringify(bad)); } assert.equal(credits(state), 234_687_925); }); test("the ledger shows a running instance as an open charge, so it always adds up to the balance", () => { const state = funded(10); const inst = running(state); E.settle(state, s(100)); const rows = E.viewLedger(state, A); assert.deepEqual(rows.map((e) => [e.type, e.deltaUsd, !!e.open]), [["charge", -0.02, true], ["topup", 10, false]]); assert.equal(rows.reduce((t, e) => t + Math.round(e.deltaUsd * 1e6), 0), credits(state)); E.end(state, { address: A, id: inst.id, now: s(100) }); assert.deepEqual(E.viewLedger(state, A).map((e) => [e.type, e.deltaUsd, !!e.open]), [["charge", -0.02, false], ["topup", 10, false]]); assert.deepEqual(E.viewLedger(state, B), []); }); }); describe("the provider's side", () => { test("pending() lists what to ask and what to release; released() closes the loop", () => { const state = funded(10); const a = running(state); const b = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).instance; E.attach(state, { id: b.id, providerId: "pod-b", now: T0 }); assert.deepEqual(E.pending(state).poll.map((p) => p.id), [b.id]); assert.deepEqual(E.pending(state, { running: true }).poll.map((p) => p.id), [a.id, b.id]); assert.deepEqual(E.pending(state, { address: B, running: true }), { poll: [], release: [] }); assert.deepEqual(E.pending(state, { now: s(2), minGapMs: 4000 }).poll, [], "asked two seconds ago: not again yet"); E.end(state, { address: A, id: a.id, now: s(10) }); assert.deepEqual(E.pending(state).release.map((r) => r.providerId), ["pod-" + a.id]); E.released(state, { id: a.id, now: s(11) }); assert.deepEqual(E.pending(state).release, []); E.released(state, { id: b.id, now: s(11) }); assert.equal(b.releasedAt, null, "a live machine is not marked released"); }); test("reconcile() adopts a machine a crashed request left behind and names the ones nobody owns", () => { const state = funded(10); const live = running(state); const lost = E.rent(state, { address: A, gpu: "a", rate: RATE, now: T0 }).instance; // booked, id never recorded const pods = [ { providerId: "pod-" + live.id, name: "idle-" + live.id, createdAt: T0 }, { providerId: "pod-x", name: "idle-" + lost.id, createdAt: T0 }, { providerId: "pod-old", name: "idle-i9999", createdAt: T0 }, { providerId: "pod-new", name: "idle-i9998", createdAt: s(3000) }, { providerId: "pod-other", name: "someone-elses-training-run", createdAt: T0 }, ]; const r = E.reconcile(state, { pods, prefix: "idle", now: s(3600) }); assert.deepEqual(r.adopt, [{ id: lost.id, providerId: "pod-x" }]); assert.deepEqual(r.terminate, ["pod-old"], "old and unowned; the young one gets its 15 minutes, the foreign one is never touched"); }); test("ended instances are forgotten after a week, once released; their receipt stays", () => { const state = funded(10); const a = running(state); const b = running(state); E.end(state, { address: A, id: a.id, now: s(10) }); E.end(state, { address: A, id: b.id, now: s(10) }); E.released(state, { id: a.id, now: s(11) }); const week = 7 * 86_400_000; assert.equal(E.prune(state, s(10) + week - 1).pruned, 0); assert.equal(E.prune(state, s(10) + week).pruned, 1); assert.equal(state.instances[a.id], undefined); assert.ok(state.instances[b.id], "its machine is not confirmed released: it stays until it is"); assert.equal(entries(state, "charge").length, 2); }); }); describe("what the API shows", () => { test("an account that never did anything is empty, not an error", () => { assert.deepEqual(E.viewAccount(E.emptyState(), A, T0), { address: A, creditsUsd: 0, creditsMicro: 0, sshKeys: [], apiKeys: [], instances: [] }); }); test("an instance shows its SSH command only while it runs, and never the provider's id", () => { const state = funded(10); const inst = running(state); E.settle(state, s(90)); const v = E.viewInstance(inst); assert.equal(v.status, "running"); assert.equal(v.sshCommand, "ssh root@10.0.0.1 -p 2222"); assert.deepEqual(v.ssh, { host: "10.0.0.1", port: 2222, user: "root", command: "ssh root@10.0.0.1 -p 2222" }); assert.equal(v.secondsBilled, 90); assert.equal(v.costUsd, 0.018); assert.equal(v.ratePerHourUsd, 0.72); assert.equal("providerId" in v, false); E.end(state, { address: A, id: inst.id, now: s(90) }); assert.equal(E.viewInstance(inst).ssh, null); assert.equal(E.viewInstance(inst).status, "ended"); const account = E.viewAccount(state, A, s(90)); assert.equal(JSON.stringify(account).includes(KEY.split(" ")[1]), false, "the account view carries fingerprints, not key bodies"); }); });