Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Serve spend reports from saved daily totals (#1641)

Joshua Franceed0c894d719c
diff --git a/plugins/admin/test/spend-lit.test.ts b/plugins/admin/test/spend-lit.test.ts
index c8e4e94bc..9b2494f96 100644
--- a/plugins/admin/test/spend-lit.test.ts
+++ b/plugins/admin/test/spend-lit.test.ts
@@ -101,6 +101,12 @@ function render(data: any) {
return { f, calls, view, peopleRows };
}
+test("spend view: shows the saved report freshness", () => {
+ const { f } = render({ ...DATA, asOf: Date.UTC(2026, 8, 25, 12) });
+ assert.match(f.root.textContent!, /Totals as of.*Updated every minute/);
+ f.window.close();
+});
+
test("spend view: KPI stats, stacked chart and range tabs describe the whole org", () => {
const { f, calls } = render(DATA);
assert.deepEqual(JSON.parse(JSON.stringify(calls.shell.stats)), [
diff --git a/plugins/admin/ui/spend.ts b/plugins/admin/ui/spend.ts
index a559b590b..d6b46f741 100644
--- a/plugins/admin/ui/spend.ts
+++ b/plugins/admin/ui/spend.ts
@@ -140,7 +140,13 @@ export class SpendView {
const series = this.data.series || [];
const org = this.data.org || {};
this.paint(
- html`${card(
+ html`${
+ this.data.asOf == null
+ ? null
+ : html`<p class="subline">
+ Totals as of ${new Date(this.data.asOf).toLocaleString()}. Updated every minute.
+ </p>`
+ }${card(
"Spend over time",
series.length
? `${this.data.window?.from ?? ""} to ${this.data.window?.to ?? ""} (UTC, ${this.data.window?.bucket ?? "day"} buckets) · ${s.plural(org.calls || 0, "model call")}`
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index 908f6adbb..3182668ed 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -136,7 +136,7 @@ export function createMessagingMethods(
const identityMembers = async (): Promise<DirectoryMember[]> => {
const [externals, participants] = await Promise.all([
deps.identity.listExternalMembers(),
- deps.sessions?.listParticipants() ?? [],
+ deps.sessions?.distinctParticipants() ?? [],
]);
const candidates: DirectoryMember[] = [
...(deps.emailAuthMembers ?? []),
@@ -144,8 +144,8 @@ export function createMessagingMethods(
.filter((member) => externalMemberActive(member))
.map((member) => ({ principalId: member.email, displayName: member.email, type: "internal" as const })),
...participants
- .filter((w) => deps.identity.classify(w.principalId).type === "internal")
- .map((w) => ({ principalId: w.principalId, displayName: w.principalId, type: "internal" as const })),
+ .filter((principalId) => deps.identity.classify(principalId).type === "internal")
+ .map((principalId) => ({ principalId, displayName: principalId, type: "internal" as const })),
];
const byKey = new Map<string, DirectoryMember>();
for (const member of candidates) {
diff --git a/src/api/routes/admin/spend.ts b/src/api/routes/admin/spend.ts
index 0e8fba5b8..01d26a44f 100644
--- a/src/api/routes/admin/spend.ts
+++ b/src/api/routes/admin/spend.ts
@@ -363,14 +363,17 @@ export async function spend(ctx: ApiCtx): Promise<void> {
if (from === null) return bad("from must be a YYYY-MM-DD date (UTC) or epoch milliseconds");
if (to <= from) return bad("to must be later than from");
- const rows = (await deps.sessions?.spendRollup({ from, to })) ?? [];
+ const { rows, asOf } = deps.sessions?.spendReport
+ ? await deps.sessions.spendReport({ from, to })
+ : { rows: (await deps.sessions?.spendRollup({ from, to })) ?? [], asOf: undefined };
const labels = await discoverScopes(
app,
deps,
rows.map((r) => r.scopeId),
);
const report = summarizeSpend(rows, { from, to, bucket, label: (id) => labels.get(id) ?? "" });
- if (format === "json") return sendJson(res, 200, { scopeId: scope, ...report });
+ if (format === "json")
+ return sendJson(res, 200, { scopeId: scope, ...report, ...(asOf === undefined ? {} : { asOf }) });
const body = spendCsv(report, breakdown);
res.writeHead(200, {
diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.ts
index 93c7e9b53..102362416 100644
--- a/src/sessions/postgres-session-store.ts
+++ b/src/sessions/postgres-session-store.ts
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { createPgPool, type PgPool, type PoolClient, withPgTransaction } from "../persistence/pg-pool.ts";
import { jsonbSafeStringify } from "../util/text.ts";
+import { reportFailure } from "../util/errors.ts";
import type { Session, SessionEntry, SessionType, ScopeId } from "../types.ts";
import type {
NewSessionPin,
@@ -242,6 +243,56 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
ELSE NULL END
FROM (SELECT safe_json(replace(${col}, '\\u0000', '')) AS j) _)`;
+ const spendSql = `WITH RECURSIVE ancestry AS (
+ SELECT s.id AS session_id, s.parent_session_id, ${originExpr("s")} AS origin, ARRAY[s.id] AS path
+ FROM sessions s
+ WHERE s.parent_session_id IS NOT NULL AND ${originExpr("s")} = 'conversation'
+ AND EXISTS (SELECT 1 FROM session_llm_requests r
+ WHERE r.session_id = s.id AND r.created_at >= $1 AND r.created_at < $2
+ AND r.usage_json IS NOT NULL)
+ UNION ALL
+ SELECT a.session_id, p.parent_session_id, ${originExpr("p")}, a.path || p.id
+ FROM ancestry a JOIN sessions p ON p.id = a.parent_session_id
+ WHERE a.origin = 'conversation' AND NOT p.id = ANY(a.path) AND cardinality(a.path) < 64
+ ), origins AS (
+ SELECT DISTINCT ON (session_id) session_id, origin
+ FROM ancestry ORDER BY session_id, cardinality(path) DESC
+ ), rollup AS MATERIALIZED (
+ SELECT (r.created_at / 86400000)::bigint AS day, s.scope_id,
+ COALESCE(o.origin, ${originExpr("s")}) AS origin, r.model,
+ COUNT(*) AS calls,
+ COALESCE(SUM(cost_usd), 0)::text AS cost_usd,
+ COALESCE(SUM(input), 0) AS input,
+ COALESCE(SUM(output), 0) AS output,
+ COALESCE(SUM(cache_read), 0) AS cache_read,
+ COALESCE(SUM(cache_write), 0) AS cache_write
+ FROM (SELECT created_at, session_id, model,
+ (spend_usage_json(usage_json) ->> 'costUsd')::double precision AS cost_usd,
+ (spend_usage_json(usage_json) ->> 'input')::bigint AS input,
+ (spend_usage_json(usage_json) ->> 'output')::bigint AS output,
+ (spend_usage_json(usage_json) ->> 'cacheRead')::bigint AS cache_read,
+ (spend_usage_json(usage_json) ->> 'cacheWrite')::bigint AS cache_write
+ FROM session_llm_requests
+ WHERE created_at >= $1 AND created_at < $2 AND usage_json IS NOT NULL
+ AND ${SPEND_INDEXABLE}
+ UNION ALL
+ SELECT created_at, session_id, model,
+ (usage_json::jsonb ->> 'costUsd')::double precision AS cost_usd,
+ (usage_json::jsonb ->> 'input')::bigint AS input,
+ (usage_json::jsonb ->> 'output')::bigint AS output,
+ (usage_json::jsonb ->> 'cacheRead')::bigint AS cache_read,
+ (usage_json::jsonb ->> 'cacheWrite')::bigint AS cache_write
+ FROM session_llm_requests
+ WHERE created_at >= $1 AND created_at < $2 AND usage_json IS NOT NULL
+ AND NOT ${SPEND_INDEXABLE}
+ AND EXISTS (SELECT 1 FROM sessions WHERE id = session_llm_requests.session_id)
+ OFFSET 0) r
+ JOIN sessions s ON s.id = r.session_id
+ LEFT JOIN origins o ON o.session_id = s.id
+ GROUP BY day, s.scope_id, COALESCE(o.origin, ${originExpr("s")}), r.model
+ )
+ SELECT * FROM rollup ORDER BY day, scope_id, origin, model`;
+
const recountRecentSessions = `UPDATE sessions s
SET messages = c.messages, turns = c.turns, last_activity = c.last_activity
FROM (SELECT r.id,
@@ -651,6 +702,53 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
WHERE usage_json IS NOT NULL AND NOT ${SPEND_INDEXABLE}`,
],
},
+ {
+ id: "sessions/store/0022-spend-days",
+ statements: [
+ `SET LOCAL lock_timeout = '3s'`,
+ `CREATE TABLE session_spend_days(day BIGINT PRIMARY KEY, rows JSONB NOT NULL, updated_at BIGINT NOT NULL)`,
+ `CREATE TABLE session_spend_dirty(
+ day BIGINT, session_id TEXT, writer xid8 NOT NULL DEFAULT pg_current_xact_id(),
+ UNIQUE(day, writer), CHECK (num_nonnulls(day, session_id) = 1)
+ )`,
+ `CREATE OR REPLACE FUNCTION invalidate_request_spend() RETURNS trigger LANGUAGE plpgsql AS $invalidate_request_spend$
+ BEGIN
+ INSERT INTO session_spend_dirty(day)
+ SELECT DISTINCT floor(at::numeric / 86400000)::bigint
+ FROM (VALUES
+ (CASE WHEN TG_OP <> 'INSERT' AND OLD.usage_json IS NOT NULL THEN OLD.created_at END),
+ (CASE WHEN TG_OP <> 'DELETE' AND NEW.usage_json IS NOT NULL THEN NEW.created_at END)
+ ) changed(at) WHERE at IS NOT NULL
+ ON CONFLICT DO NOTHING;
+ RETURN NULL;
+ END $invalidate_request_spend$`,
+ `CREATE TRIGGER session_llm_requests_spend_dirty
+ AFTER INSERT OR UPDATE OF created_at, session_id, model, usage_json OR DELETE ON session_llm_requests
+ FOR EACH ROW EXECUTE FUNCTION invalidate_request_spend()`,
+ `CREATE OR REPLACE FUNCTION invalidate_session_spend() RETURNS trigger LANGUAGE plpgsql AS $invalidate_session_spend$
+ BEGIN
+ IF TG_OP = 'UPDATE' AND ROW(OLD.id, OLD.scope_id, OLD.origin, OLD.thread_ref, OLD.parent_session_id)
+ IS NOT DISTINCT FROM ROW(NEW.id, NEW.scope_id, NEW.origin, NEW.thread_ref, NEW.parent_session_id) THEN
+ RETURN NULL;
+ END IF;
+ INSERT INTO session_spend_dirty(session_id)
+ SELECT DISTINCT id FROM (VALUES (OLD.id), (NEW.id)) changed(id) WHERE id IS NOT NULL;
+ RETURN NULL;
+ END $invalidate_session_spend$`,
+ `CREATE TRIGGER sessions_spend_dirty
+ AFTER INSERT OR UPDATE OF id, scope_id, origin, thread_ref, parent_session_id OR DELETE ON sessions
+ FOR EACH ROW EXECUTE FUNCTION invalidate_session_spend()`,
+ ],
+ },
+ {
+ id: "sessions/store/0023-spend-days-backfill",
+ statements: [
+ `INSERT INTO session_spend_dirty(day)
+ SELECT DISTINCT floor(created_at::numeric / 86400000)::bigint
+ FROM session_llm_requests WHERE usage_json IS NOT NULL
+ ON CONFLICT DO NOTHING`,
+ ],
+ },
],
[
{
@@ -1687,59 +1785,77 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
},
async spendRollup(range): Promise<SpendRow[]> {
- const rows = await q(
- `WITH RECURSIVE ancestry AS (
- SELECT s.id AS session_id, s.parent_session_id, ${originExpr("s")} AS origin, ARRAY[s.id] AS path
- FROM sessions s
- WHERE s.parent_session_id IS NOT NULL AND ${originExpr("s")} = 'conversation'
- AND EXISTS (SELECT 1 FROM session_llm_requests r
- WHERE r.session_id = s.id AND r.created_at >= $1 AND r.created_at < $2
- AND r.usage_json IS NOT NULL)
- UNION ALL
- SELECT a.session_id, p.parent_session_id, ${originExpr("p")}, a.path || p.id
- FROM ancestry a JOIN sessions p ON p.id = a.parent_session_id
- WHERE a.origin = 'conversation' AND NOT p.id = ANY(a.path) AND cardinality(a.path) < 64
- ), origins AS (
- SELECT DISTINCT ON (session_id) session_id, origin
- FROM ancestry ORDER BY session_id, cardinality(path) DESC
- ), rollup AS MATERIALIZED (
- SELECT (r.created_at / 86400000)::bigint AS day, s.scope_id,
- COALESCE(o.origin, ${originExpr("s")}) AS origin, r.model,
- COUNT(*) AS calls,
- COALESCE(SUM(cost_usd), 0) AS cost_usd,
- COALESCE(SUM(input), 0) AS input,
- COALESCE(SUM(output), 0) AS output,
- COALESCE(SUM(cache_read), 0) AS cache_read,
- COALESCE(SUM(cache_write), 0) AS cache_write
- FROM (SELECT created_at, session_id, model,
- (spend_usage_json(usage_json) ->> 'costUsd')::double precision AS cost_usd,
- (spend_usage_json(usage_json) ->> 'input')::bigint AS input,
- (spend_usage_json(usage_json) ->> 'output')::bigint AS output,
- (spend_usage_json(usage_json) ->> 'cacheRead')::bigint AS cache_read,
- (spend_usage_json(usage_json) ->> 'cacheWrite')::bigint AS cache_write
- FROM session_llm_requests
- WHERE created_at >= $1 AND created_at < $2 AND usage_json IS NOT NULL
- AND ${SPEND_INDEXABLE}
- UNION ALL
- SELECT created_at, session_id, model,
- (usage_json::jsonb ->> 'costUsd')::double precision AS cost_usd,
- (usage_json::jsonb ->> 'input')::bigint AS input,
- (usage_json::jsonb ->> 'output')::bigint AS output,
- (usage_json::jsonb ->> 'cacheRead')::bigint AS cache_read,
- (usage_json::jsonb ->> 'cacheWrite')::bigint AS cache_write
- FROM session_llm_requests
- WHERE created_at >= $1 AND created_at < $2 AND usage_json IS NOT NULL
- AND NOT ${SPEND_INDEXABLE}
- AND EXISTS (SELECT 1 FROM sessions WHERE id = session_llm_requests.session_id)
- OFFSET 0) r
- JOIN sessions s ON s.id = r.session_id
- LEFT JOIN origins o ON o.session_id = s.id
- GROUP BY day, s.scope_id, COALESCE(o.origin, ${originExpr("s")}), r.model
- )
- SELECT * FROM rollup ORDER BY day, scope_id, origin, model`,
- [range.from, range.to],
+ return (await q(spendSql, [range.from, range.to])).map(rowToSpendRow);
+ },
+
+ async spendReport(range) {
+ const dayMs = 86_400_000;
+ if (range.from < 0 || range.from % dayMs || range.to % dayMs) {
+ return { rows: (await q(spendSql, [range.from, range.to])).map(rowToSpendRow) };
+ }
+ let asOf = now();
+ const days = await q(
+ `WITH pending AS (SELECT DISTINCT day FROM session_spend_dirty WHERE day >= $1 AND day < $2)
+ SELECT COALESCE(c.day, p.day) AS day, c.rows, c.updated_at,
+ p.day IS NOT NULL OR EXISTS (SELECT 1 FROM session_spend_dirty WHERE session_id IS NOT NULL) AS pending
+ FROM (SELECT * FROM session_spend_days WHERE day >= $1 AND day < $2) c
+ FULL JOIN pending p ON p.day = c.day ORDER BY day`,
+ [range.from / dayMs, range.to / dayMs],
);
- return rows.map(rowToSpendRow);
+ if (days.some((day) => day.rows === null)) {
+ return { rows: (await q(spendSql, [range.from, range.to])).map(rowToSpendRow) };
+ }
+ const rows: SpendRow[] = [];
+ for (const day of days) {
+ rows.push(...(day.rows as Record<string, unknown>[]).map(rowToSpendRow));
+ if (day.pending) asOf = Math.min(asOf, Number(day.updated_at));
+ }
+ return { rows, asOf };
+ },
+
+ async refreshSpendRollup() {
+ const started = Date.now();
+ await withPgTransaction(await pool(), async (client) => {
+ const changed = await client.query(
+ "DELETE FROM session_spend_dirty WHERE session_id IS NOT NULL RETURNING session_id",
+ );
+ if (!changed.rowCount) return;
+ await client.query(
+ `WITH RECURSIVE affected(id) AS (
+ SELECT unnest($1::text[])
+ UNION
+ SELECT s.id FROM sessions s JOIN affected a ON s.parent_session_id = a.id
+ )
+ INSERT INTO session_spend_dirty(day)
+ SELECT DISTINCT floor(r.created_at::numeric / 86400000)::bigint
+ FROM session_llm_requests r JOIN affected a ON a.id = r.session_id WHERE r.usage_json IS NOT NULL
+ ON CONFLICT DO NOTHING`,
+ [changed.rows.map((r) => r.session_id)],
+ );
+ });
+ const days = await q(
+ `SELECT d.day FROM (SELECT DISTINCT day FROM session_spend_dirty WHERE day IS NOT NULL) d
+ LEFT JOIN session_spend_days c ON c.day = d.day ORDER BY c.updated_at NULLS FIRST, d.day DESC`,
+ );
+ for (const { day } of days) {
+ try {
+ await withPgTransaction(await pool(), async (client) => {
+ const pending = await client.query("DELETE FROM session_spend_dirty WHERE day = $1 RETURNING day", [day]);
+ if (!pending.rowCount) return;
+ const updatedAt = now();
+ const rows = await client.query(spendSql, [Number(day) * 86_400_000, (Number(day) + 1) * 86_400_000]);
+ await client.query(
+ `INSERT INTO session_spend_days(day, rows, updated_at) VALUES ($1, $2, $3)
+ ON CONFLICT (day) DO UPDATE SET rows = EXCLUDED.rows, updated_at = EXCLUDED.updated_at`,
+ [day, jsonbSafeStringify(rows.rows), updatedAt],
+ );
+ });
+ } catch (error) {
+ reportFailure("spend: refresh daily totals", error);
+ continue;
+ }
+ if (Date.now() - started >= 5_000) break;
+ }
},
async listParticipants(): Promise<ParticipantWindow[]> {
diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.ts
index f2676a671..ec743fcbc 100644
--- a/src/sessions/session-store.ts
+++ b/src/sessions/session-store.ts
@@ -804,6 +804,10 @@ export interface SessionStore {
spendRollup(range: { from: number; to: number }): Promise<SpendRow[]>;
+ spendReport?(range: { from: number; to: number }): Promise<{ rows: SpendRow[]; asOf?: number }>;
+
+ refreshSpendRollup?(): Promise<void>;
+
listParticipants(): Promise<ParticipantWindow[]>;
distinctParticipants(): Promise<string[]>;
diff --git a/src/wiring.ts b/src/wiring.ts
index 7825a0ff3..708812da5 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -2545,6 +2545,12 @@ export function buildApp(
})
: null;
const MONITOR_RETENTION_SWEEP_MS = 24 * 60 * 60_000;
+ const spendSweeper = sessions.refreshSpendRollup
+ ? createSweeper(() => leaderLease.hold("spend:refresh", () => sessions.refreshSpendRollup!()), 60_000, {
+ label: "spend-refresh",
+ immediate: true,
+ })
+ : null;
const monitorRetentionSweeper = createSweeper(
() => leaderLease.hold("monitor:retention:sweep", () => monitors.deleteDefunct(Date.now())),
MONITOR_RETENTION_SWEEP_MS,
@@ -2619,6 +2625,7 @@ export function buildApp(
})
.catch(swallowAs("wiring: monitor resume failed", undefined));
monitorRetentionSweeper.start();
+ spendSweeper?.start();
if (config.skillSyncPollMs > 0) skillSyncEngine.start(config.skillSyncPollMs);
blobSweeper.start();
composioReturnSweeper.start();
@@ -2647,6 +2654,7 @@ export function buildApp(
reaper.stop(),
processReaper?.stop(),
monitorRetentionSweeper.stop(),
+ spendSweeper?.stop(),
skillSyncEngine.stop(),
idleSweeper?.stop(),
keepWarmSweeper.stop(),
diff --git a/test/admin-external-users.test.ts b/test/admin-external-users.test.ts
index b99de12f4..3045f2be0 100644
--- a/test/admin-external-users.test.ts
+++ b/test/admin-external-users.test.ts
@@ -537,6 +537,25 @@ test("expiry classifies an external as guest, and the signed broker check answer
}
});
+test("the directory resolves participants without loading their session windows", async (t) => {
+ const s = start();
+ t.after(s.close);
+ for (const thread of ["first", "second"]) {
+ const session = await s.built.sessions.getOrCreateByThread(thread, "dm", "personal:alice");
+ await s.built.sessions.addParticipant(session.id, "alice");
+ await s.built.sessions.addParticipant(session.id, "inactive");
+ }
+ await s.built.identity.deactivate("inactive");
+ t.mock.method(s.built.sessions, "listParticipants", () => {
+ throw new Error("Directory lookup must not load participant windows");
+ });
+ const alice = { principalId: "alice", displayName: "alice", type: "internal" };
+ assert.deepEqual(await s.built.app.directoryMembers(), [alice]);
+ assert.deepEqual(await s.built.app.directoryMember("alice"), alice);
+ assert.deepEqual(await s.built.app.resolveRecipient("alice"), { kind: "one", member: alice });
+ assert.equal(await s.built.app.directoryMember("inactive"), null);
+});
+
test("the directory resolves an active external member and not an expired one", async () => {
const s = start();
try {
diff --git a/test/admin-spend.test.ts b/test/admin-spend.test.ts
index 771a4a47d..93057e0bf 100644
--- a/test/admin-spend.test.ts
+++ b/test/admin-spend.test.ts
@@ -82,6 +82,28 @@ async function seedPricedFixture(sessions: SessionStore): Promise<void> {
const conserved = (report: any, column: string): number =>
[...report.people, ...report.scopes].reduce((sum: number, e: any) => sum + e[column], 0);
+test("spend: uses the saved report and exposes its freshness", async () => {
+ const store = createMemorySessionStore();
+ const asOf = Date.UTC(2026, 0, 1);
+ let reads = 0;
+ store.spendReport = async (range) => {
+ reads++;
+ return { rows: await store.spendRollup(range), asOf };
+ };
+ const s = start(store);
+ try {
+ await seedPricedFixture(store);
+ const body = await getJson(s.base, "/v1/admin/spend");
+ assert.equal(body.asOf, asOf);
+ assert.equal(body.org.costUsd, 6.75);
+ const csv = await get(s.base, "/v1/admin/spend?format=csv");
+ assert.equal(csv.status, 200);
+ assert.equal(reads, 2);
+ } finally {
+ await s.close();
+ }
+});
+
test("spend: live and cron dollars land on the owning person, shared scopes on their own rows", async () => {
const s = start();
try {
diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.ts
index 9a0f04fbf..c84ef7089 100644
--- a/test/postgres-store.test.ts
+++ b/test/postgres-store.test.ts
@@ -29,7 +29,7 @@ before(async () => {
const p = new pg.Pool({ connectionString: URL });
await p.query("DROP TABLE IF EXISTS qm_schema_migrations CASCADE");
await p.query(
- "DROP TABLE IF EXISTS sessions, session_entries, participants, session_leases, session_tape, session_llm_requests, session_pins, runs, tool_calls CASCADE",
+ "DROP TABLE IF EXISTS session_spend_days, session_spend_dirty, sessions, session_entries, participants, session_leases, session_tape, session_llm_requests, session_pins, runs, tool_calls CASCADE",
);
await p.end();
});
@@ -105,6 +105,210 @@ test("pg session store: spendRollup matches the memory rollup row for row", { sk
await assertSpendRollupParity((now) => createPostgresSessionStore(URL!, { now }), `pg-spend-${randomUUID()}`);
});
+test("pg saved spend refreshes changed days and preserves live attribution", { skip }, async () => {
+ const day = 86_400_000;
+ const base = Date.UTC(2024, 0, 1);
+ let at = base + 123;
+ const store = createPostgresSessionStore(URL!, { now: () => at });
+ const pg = (await import("pg")).default;
+ const raw = new pg.Pool({ connectionString: URL });
+ const scope = scopeId("personal", `saved-${randomUUID()}`);
+ const session = await store.getOrCreateByThread(scope, "dm", scope);
+ const range = { from: base, to: base + 2 * day };
+ const bill = () =>
+ store.recordLlmRequest(session.id, {
+ turnSeq: null,
+ step: 0,
+ model: "saved",
+ scopeLabel: scope,
+ usage: { input: 2, output: 3, cacheRead: 4, cacheWrite: 5, totalTokens: 14, costUsd: 0.25 },
+ });
+ const read = async () => (await store.spendReport!(range)).rows;
+ const check = async () => assert.deepEqual(await read(), await store.spendRollup(range));
+ try {
+ const first = await bill();
+ await check();
+ await store.refreshSpendRollup!();
+ await check();
+ at += 1_000;
+ await bill();
+ assert.equal((await read())[0]!.calls, 1);
+ assert.equal((await store.spendReport!(range)).asOf, base + 123);
+ await store.refreshSpendRollup!();
+ await check();
+ assert.equal((await read())[0]!.calls, 2);
+ const restarted = createPostgresSessionStore(URL!, { now: () => at });
+ assert.deepEqual((await restarted.spendReport!(range)).rows, await read());
+
+ await raw.query("UPDATE session_llm_requests SET created_at = $2, model = 'moved', usage_json = $3 WHERE id = $1", [
+ first.id,
+ base + day + 1,
+ JSON.stringify({ input: 1, costUsd: 2 }),
+ ]);
+ await store.refreshSpendRollup!();
+ await check();
+ assert.equal((await read()).length, 2);
+ const parent = await store.getOrCreateByThread(`cron:${randomUUID()}`, "dm", scope);
+ await store.setParentSession(session.id, parent.id);
+ await store.refreshSpendRollup!();
+ await check();
+ assert.ok((await read()).every((r) => r.origin === "cron"));
+ await raw.query("UPDATE sessions SET scope_id = $2 WHERE id = $1", [session.id, "personal:saved-moved"]);
+ await store.refreshSpendRollup!();
+ await check();
+ assert.ok((await read()).every((r) => r.scopeId === "personal:saved-moved"));
+ await store.deleteSession(parent.id);
+ await store.refreshSpendRollup!();
+ await check();
+ assert.ok((await read()).every((r) => r.origin === "conversation"));
+ const partial = { from: base + 124, to: base + day };
+ assert.deepEqual((await store.spendReport!(partial)).rows, await store.spendRollup(partial));
+ await store.deleteSession(session.id);
+ await store.refreshSpendRollup!();
+ assert.deepEqual(await read(), []);
+ assert.equal(
+ (await raw.query("SELECT jsonb_array_length(rows) AS n FROM session_spend_days WHERE day = $1", [base / day]))
+ .rows[0].n,
+ 0,
+ );
+ } finally {
+ await raw.end();
+ }
+});
+
+test("pg spend refresh keeps concurrent writes pending and failures preserve the last report", { skip }, async () => {
+ const base = Date.UTC(2025, 0, 1);
+ const range = { from: base, to: base + 86_400_000 };
+ const store = createPostgresSessionStore(URL!, { now: () => base + 123 });
+ const pg = (await import("pg")).default;
+ const raw = new pg.Pool({ connectionString: URL });
+ const scope = scopeId("personal", `race-${randomUUID()}`);
+ const session = await store.getOrCreateByThread(scope, "dm", scope);
+ const bill = () =>
+ store.recordLlmRequest(session.id, {
+ turnSeq: null,
+ step: 0,
+ model: "race",
+ scopeLabel: scope,
+ usage: { input: 1, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 1, costUsd: 1 },
+ });
+ const query = pg.Client.prototype.query;
+ const wallClock = Date.now;
+ let duringRollup: (() => Promise<unknown>) | undefined;
+ pg.Client.prototype.query = function (...args: any[]): any {
+ if (duringRollup && typeof args[0] === "string" && args[0].startsWith("WITH RECURSIVE ancestry")) {
+ const hook = duringRollup;
+ duringRollup = undefined;
+ return Promise.resolve(Reflect.apply(query, this, args)).then(async (result) => {
+ await hook();
+ return result;
+ });
+ }
+ return Reflect.apply(query, this, args);
+ };
+ try {
+ await bill();
+ await store.refreshSpendRollup!();
+ await bill();
+ duringRollup = bill;
+ await store.refreshSpendRollup!();
+ assert.equal((await store.spendReport!(range)).rows[0]!.calls, 2);
+ assert.equal((await store.spendRollup(range))[0]!.calls, 3);
+ assert.ok(
+ Number(
+ (await raw.query("SELECT count(*) AS n FROM session_spend_dirty WHERE day = $1", [base / 86_400_000])).rows[0]
+ .n,
+ ) > 0,
+ );
+ await store.refreshSpendRollup!();
+ assert.deepEqual((await store.spendReport!(range)).rows, await store.spendRollup(range));
+ const healthyId = randomUUID();
+ await raw.query(
+ "INSERT INTO session_llm_requests(id, session_id, step, model, scope_label, created_at, usage_json) VALUES ($1,$2,0,'healthy',$3,$4,$5)",
+ [healthyId, session.id, scope, base - 86_400_000, JSON.stringify({ costUsd: 1 })],
+ );
+ await store.refreshSpendRollup!();
+ await raw.query("UPDATE session_llm_requests SET usage_json = $2 WHERE id = $1", [
+ healthyId,
+ JSON.stringify({ costUsd: 2 }),
+ ]);
+ await bill();
+ duringRollup = async () => {
+ const elapsed = wallClock() + 5_001;
+ Date.now = () => elapsed;
+ throw new Error("injected slow spend refresh failure");
+ };
+ await store.refreshSpendRollup!();
+ Date.now = wallClock;
+ assert.equal((await store.spendReport!(range)).rows[0]!.calls, 3);
+ const healthy = await store.spendReport!({ from: base - 86_400_000, to: base });
+ assert.equal(healthy.rows[0]!.costUsd, 2);
+ await Promise.all([store.refreshSpendRollup!(), store.refreshSpendRollup!()]);
+ assert.equal((await store.spendReport!(range)).rows[0]!.calls, 4);
+ assert.equal(
+ Number(
+ (await raw.query("SELECT count(*) AS n FROM session_spend_dirty WHERE day = $1", [base / 86_400_000])).rows[0]
+ .n,
+ ),
+ 0,
+ );
+ } finally {
+ pg.Client.prototype.query = query;
+ Date.now = wallClock;
+ await raw.end();
+ }
+});
+
+test(
+ "pg saved spend resolves session changes after commit and preserves non-finite legacy costs",
+ { skip },
+ async () => {
+ const base = Date.UTC(2025, 2, 1);
+ let at = base + 123;
+ const range = { from: base, to: base + 86_400_000 };
+ const store = createPostgresSessionStore(URL!, { now: () => at });
+ const pg = (await import("pg")).default;
+ const raw = new pg.Pool({ connectionString: URL });
+ const editor = await raw.connect();
+ const scope = scopeId("personal", `commit-${randomUUID()}`);
+ const session = await store.getOrCreateByThread(scope, "dm", scope);
+ try {
+ await store.refreshSpendRollup!();
+ await editor.query("BEGIN");
+ await editor.query("UPDATE sessions SET origin = 'cron' WHERE id = $1", [session.id]);
+ await store.recordLlmRequest(session.id, {
+ turnSeq: null,
+ step: 0,
+ model: "commit",
+ scopeLabel: scope,
+ usage: { input: 1, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 1, costUsd: 1 },
+ });
+ await store.refreshSpendRollup!();
+ assert.equal((await store.spendReport!(range)).rows[0]!.origin, "conversation");
+ await editor.query("COMMIT");
+ at += 1_000;
+ assert.ok((await store.spendReport!(range)).asOf! < at);
+ await store.refreshSpendRollup!();
+ assert.deepEqual((await store.spendReport!(range)).rows, await store.spendRollup(range));
+ assert.equal((await store.spendReport!(range)).rows[0]!.origin, "cron");
+ for (const cost of ["NaN", "Infinity", "-Infinity"]) {
+ await raw.query(
+ "INSERT INTO session_llm_requests(id, session_id, step, model, scope_label, created_at, usage_json) VALUES ($1,$2,0,$3,$4,$5,$6)",
+ [randomUUID(), session.id, cost, scope, base, JSON.stringify({ costUsd: cost })],
+ );
+ }
+ await store.refreshSpendRollup!();
+ assert.deepEqual((await store.spendReport!(range)).rows, await store.spendRollup(range));
+ assert.ok(Number.isNaN((await store.spendReport!(range)).rows.find((r) => r.model === "NaN")!.costUsd));
+ } finally {
+ await editor.query("ROLLBACK");
+ editor.release();
+ await store.deleteSession(session.id);
+ await raw.end();
+ }
+ },
+);
+
test("pg spend indexes preserve legacy and unusual requests through migration and later writes", { skip }, async () => {
const at = Date.UTC(2022, 0, 1);
const store = createPostgresSessionStore(URL!, { now: () => at });