cloud / internal-packages / cloud-ai / src / usage-by-mind.test.tsmain at aacbc74
import { MessageChannel } from "node:worker_threads";
import { DatabaseSync } from "node:sqlite";
import { newMessagePortRpcSession } from "capnweb";
import { expect, test } from "vitest";
import { type CloudAiDeps, IterateCloudApi } from "./ai-target.ts";
import type { IterateCloudClientApi } from "./connect.ts";
import {
CloudUsageLedger,
createInMemoryOpenAiUsageStore,
durableObjectUsageStore,
type OpenAiUsageStore,
} from "./ledger.ts";
const CLOUD_MIND = { id: "c".repeat(64), hostname: "iterate.iterate.com" };
const MIND_A = { mindId: "a".repeat(64), mindSlug: "iterate.acme.example" };
const MIND_B = { mindId: "b".repeat(64), mindSlug: "iterate.blifto.example" };
const WINDOW = { since: "2026-11-20T00:00:00.000Z", until: "2026-11-23T00:00:00.000Z" };
const at = (iso: string) => Date.parse(iso);
function clientOf(
caller: { mindId: string; mindSlug: string },
deps: Partial<CloudAiDeps> & { openAiUsageStore: OpenAiUsageStore },
) {
const { port1, port2 } = new MessageChannel();
newMessagePortRpcSession(
port1 as unknown as MessagePort,
new IterateCloudApi(
{ ...caller, expiresAtMs: Date.now() + 60_000 },
{ ai: {} as Ai, gatewayId: "iterate-cloud", ...deps },
),
);
const client = newMessagePortRpcSession<IterateCloudClientApi>(port2 as unknown as MessagePort);
return {
client,
[Symbol.dispose]() {
port1.close();
port2.close();
},
};
}
async function fill(store: OpenAiUsageStore) {
await store.recordUsage({
...MIND_A,
id: "a1",
createdAtMs: at("2026-11-20T10:00:00.000Z"),
kind: "transcription",
route: "POST /v1/audio/transcriptions",
model: "whisper-1",
costUsd: 0.006,
audioSeconds: 60,
});
await store.recordUsage({
...MIND_A,
id: "a2",
createdAtMs: at("2026-11-20T23:59:59.999Z"),
kind: "transcription",
route: "POST /v1/audio/transcriptions",
model: "whisper-1",
costUsd: 0.012,
audioSeconds: 120,
});
await store.recordUsage({
...MIND_A,
id: "a3",
createdAtMs: at("2026-11-21T00:00:00.000Z"),
kind: "voice",
route: "GET /v1/realtime",
model: "gpt-realtime",
costUsd: 0.5,
audioSeconds: 30,
tokensIn: 100,
tokensOut: 50,
});
// outside the window, on each side
await store.recordUsage({
...MIND_A,
id: "a4",
createdAtMs: at("2026-11-19T23:59:59.999Z"),
kind: "voice",
route: "GET /v1/realtime",
model: "gpt-realtime",
costUsd: 9,
});
await store.recordUsage({
...MIND_B,
id: "b1",
createdAtMs: at("2026-11-23T00:00:00.000Z"),
kind: "voice",
route: "GET /v1/realtime",
model: "gpt-realtime",
costUsd: 9,
});
// a live session of 30 seconds that was closed, and one that nobody closed
await store.openWebRtcSession({
...MIND_B,
sessionId: "closed",
model: "gpt-live-1",
startedAtMs: at("2026-11-21T08:00:00.000Z"),
});
await store.closeWebRtcSession({
sessionId: "closed",
mindId: MIND_B.mindId,
endedAtMs: at("2026-11-21T08:00:30.000Z"),
});
await store.openWebRtcSession({
...MIND_B,
sessionId: "open",
model: "gpt-live-1",
startedAtMs: at("2026-11-22T23:59:00.000Z"),
});
}
const EXPECTED_DAYS = [
{
day: "2026-11-20",
...MIND_A,
kind: "transcription",
model: "whisper-1",
requests: 2,
costUsd: 0.018,
audioSeconds: 180,
tokensIn: 0,
tokensOut: 0,
},
{
day: "2026-11-21",
...MIND_A,
kind: "voice",
model: "gpt-realtime",
requests: 1,
costUsd: 0.5,
audioSeconds: 30,
tokensIn: 100,
tokensOut: 50,
},
{
day: "2026-11-21",
...MIND_B,
kind: "voice",
model: "gpt-live-1",
requests: 1,
costUsd: 0.025,
audioSeconds: 30,
tokensIn: 0,
tokensOut: 0,
},
// the open session: an hour at most, on the day that it began
{
day: "2026-11-22",
...MIND_B,
kind: "voice",
model: "gpt-live-1",
requests: 1,
costUsd: 3,
audioSeconds: 3600,
tokensIn: 0,
tokensOut: 0,
},
];
test("the Cloud's own mind reads every mind's OpenAI-direct spend by UTC day", async () => {
const store = createInMemoryOpenAiUsageStore();
await fill(store);
using own = clientOf(
{ mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname },
{ openAiUsageStore: store, ownMind: CLOUD_MIND },
);
const report = await own.client.openAiUsageByMind(WINDOW);
expect(report.byDay).toEqual(EXPECTED_DAYS);
expect(report).toMatchObject({
since: WINDOW.since,
until: WINDOW.until,
totalRequests: 5,
totalCostUsd: 3.543,
totalAudioSeconds: 3840,
byMind: [
{ ...MIND_B, requests: 2, costUsd: 3.025, audioSeconds: 3630 },
{ ...MIND_A, requests: 3, costUsd: 0.518, audioSeconds: 210 },
],
});
});
test("any other mind is refused every mind's spend, and so is everyone when the Cloud names no own mind", async () => {
const store = createInMemoryOpenAiUsageStore();
await fill(store);
const refusal = "only iterate Cloud's own mind reads every mind's usage";
using customer = clientOf(MIND_A, { openAiUsageStore: store, ownMind: CLOUD_MIND });
await expect(customer.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal);
// the own mind's id from another hostname
using elsewhere = clientOf(
{ mindId: CLOUD_MIND.id, mindSlug: "iterate.other.example" },
{ openAiUsageStore: store, ownMind: CLOUD_MIND },
);
await expect(elsewhere.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal);
// a Worker with no MIND_ID: a hostname alone names nobody
using unnamed = clientOf(
{ mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname },
{ openAiUsageStore: store, ownMind: { hostname: CLOUD_MIND.hostname } },
);
await expect(unnamed.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal);
using bare = clientOf(
{ mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname },
{ openAiUsageStore: store },
);
await expect(bare.client.openAiUsageByMind(WINDOW)).rejects.toThrow(refusal);
using own = clientOf(
{ mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname },
{ openAiUsageStore: store, ownMind: CLOUD_MIND },
);
await expect(own.client.openAiUsageByMind({ ...WINDOW, minds: ["not-an-id"] })).rejects.toThrow(
"`minds` must be at most 200 mind ids",
);
await expect(
own.client.openAiUsageByMind({ since: "2026-10-01T00:00:00.000Z", until: WINDOW.until }),
).rejects.toThrow("at most 31 days");
});
/** The ledger's Durable Objects on Node's SQLite: each name is one object with a database of its
* own, as `idFromName` gives each mind a shard. `listed: false` builds a shard with no binding
* to the namespace, as a ledger that was written before the list of minds existed. */
function ledgerNamespace() {
const shards = new Map<string, CloudUsageLedger>();
const held: Promise<unknown>[] = [];
const unlisted = new Set<string>();
const namespace = {
idFromName: (name: string) => name,
get(name: string) {
let shard = shards.get(name);
if (!shard) {
const db = new DatabaseSync(":memory:");
const sql = {
exec(query: string, ...bindings: (string | number | null)[]) {
if (bindings.length === 0 && query.trim().split(";").filter((s) => s.trim()).length > 1) {
db.exec(query);
return [];
}
return db.prepare(query).all(...bindings);
},
};
const ctx = { storage: { sql }, waitUntil: (promise: Promise<unknown>) => held.push(promise) };
const Ledger = CloudUsageLedger as unknown as new (
ctx: unknown,
env: unknown,
) => CloudUsageLedger;
shard = new Ledger(ctx, unlisted.has(name) ? {} : { USAGE_LEDGER: namespace });
shards.set(name, shard);
}
const target = shard as unknown as Record<string, (...args: unknown[]) => unknown>;
// a stub's call answers a promise
return new Proxy(
{},
{ get: (_, method: string) => async (...args: unknown[]) => target[method]!(...args) },
);
},
};
return {
namespace: namespace as unknown as DurableObjectNamespace<CloudUsageLedger>,
names: () => [...shards.keys()].sort(),
unlisted,
settle: async () => {
while (held.length) await held.pop();
},
};
}
test("the Durable Object ledger lists its minds and answers every shard's days", async () => {
const ledger = ledgerNamespace();
const store = durableObjectUsageStore(ledger.namespace);
await fill(store);
await ledger.settle();
expect(ledger.names()).toEqual([MIND_A.mindId, MIND_B.mindId, "index:minds"]);
const nowMs = at("2026-11-25T00:00:00.000Z");
const window = { sinceMs: at(WINDOW.since), untilMs: at(WINDOW.until), nowMs };
expect(await store.queryUsageByDay(window)).toEqual(EXPECTED_DAYS);
// an open session costs what has run of it
const early = await store.queryUsageByDay({ ...window, nowMs: at("2026-11-22T23:59:30.000Z") });
expect(early.at(-1)).toMatchObject({ day: "2026-11-22", costUsd: 0.025, audioSeconds: 30 });
// a mind's own read is unchanged by the list
expect(await store.queryUsage({ ...MIND_A, ...window })).toMatchObject({
totalRequests: 3,
totalCostUsd: 0.518,
});
});
test("a ledger from before the list is read when its mind is named, and is listed from its mind's next use", async () => {
const ledger = ledgerNamespace();
const old = { mindId: "d".repeat(64), mindSlug: "iterate.old.example" };
ledger.unlisted.add(old.mindId);
const store = durableObjectUsageStore(ledger.namespace);
await store.recordUsage({
...old,
id: "d1",
createdAtMs: at("2026-11-20T10:00:00.000Z"),
kind: "transcription",
route: "POST /v1/audio/transcriptions",
model: "whisper-1",
costUsd: 0.006,
audioSeconds: 60,
});
await ledger.settle();
const window = { sinceMs: at(WINDOW.since), untilMs: at(WINDOW.until) };
expect(await store.queryUsageByDay(window)).toEqual([]);
expect(await store.queryUsageByDay({ ...window, mindIds: [old.mindId] })).toMatchObject([
{ day: "2026-11-20", ...old, requests: 1, costUsd: 0.006 },
]);
// the Cloud's own mind names it through the call
using own = clientOf(
{ mindId: CLOUD_MIND.id, mindSlug: CLOUD_MIND.hostname },
{ openAiUsageStore: store, ownMind: CLOUD_MIND },
);
expect(await own.client.openAiUsageByMind({ ...WINDOW, minds: [old.mindId] })).toMatchObject({
totalCostUsd: 0.006,
byMind: [{ ...old, requests: 1 }],
});
});
test("a shard tells the list of its mind on the mind's own read", async () => {
const ledger = ledgerNamespace();
const store = durableObjectUsageStore(ledger.namespace);
const window = { sinceMs: at(WINDOW.since), untilMs: at(WINDOW.until) };
await store.queryUsage({ ...MIND_A, ...window });
await store.queryUsage({ ...MIND_A, ...window });
await ledger.settle();
const index = ledger.namespace.get(ledger.namespace.idFromName("index:minds"));
expect(await index.listMinds()).toEqual([MIND_A]);
});