From f028c71468903342acbfa134c022040bcfe7becb Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:21:52 +0100 Subject: [PATCH 1/7] fix(usage): compute the report in a worker and validate the window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The usage report — transcript sync and aggregates — now runs in a Bun worker instead of on the server's thread, so a cold `GET /api/usage` no longer stalls every other answer. Concurrent requests share one scan (`lib/single-flight.ts`); two waiting scans get `503 usage_busy`, a scan over ten minutes `504 usage_timeout`. `from` and `to` are validated as digit strings and answer `400` instead of silently producing an empty report, and error bodies never contain a file path. The worker opens its own `bun:sqlite` connection with a busy timeout, so it cannot block the server's connection. --- app/api/usage/route.ts | 87 ++++--- lib/single-flight.test.mjs | 119 ++++++++++ lib/single-flight.ts | 29 +++ lib/usage-db.ts | 7 +- lib/usage-nonblocking.test.mjs | 186 +++++++++++++++ lib/usage-report-worker.test.mjs | 387 +++++++++++++++++++++++++++++++ lib/usage-report-worker.ts | 263 +++++++++++++++++++++ lib/usage-route.test.mjs | 141 +++++++++++ lib/usage-service.test.mjs | 20 +- lib/usage-service.ts | 109 ++++++++- lib/usage-types.ts | 5 + lib/usage-worker.ts | 58 +++++ 12 files changed, 1375 insertions(+), 36 deletions(-) create mode 100644 lib/single-flight.test.mjs create mode 100644 lib/single-flight.ts create mode 100644 lib/usage-nonblocking.test.mjs create mode 100644 lib/usage-report-worker.test.mjs create mode 100644 lib/usage-report-worker.ts create mode 100644 lib/usage-route.test.mjs create mode 100644 lib/usage-worker.ts diff --git a/app/api/usage/route.ts b/app/api/usage/route.ts index 4e353ece4..4229093ea 100644 --- a/app/api/usage/route.ts +++ b/app/api/usage/route.ts @@ -1,42 +1,75 @@ -import { apiErrorResponse } from "@/lib/api-utils"; +import { isRecord } from "@/lib/type-guards"; import { getUsageReport } from "@/lib/usage-service"; import type { UsageGranularity, UsageTimeRange } from "@/lib/usage-types"; +/** The usage page never needs a wider window; a wider one would just make each + * distinct `from` a fresh full transcript scan. */ +const MAX_USAGE_WINDOW_MS = 400 * 24 * 60 * 60 * 1000; + +function invalidWindow(): Response { + return Response.json({ error: "Invalid usage window", code: "invalid_usage_window" }, { status: 400 }); +} + +/** Epoch milliseconds, digits only; undefined when absent, null when invalid. */ +function parseTimestamp(raw: string | null): number | undefined | null { + if (raw === null || raw === "") return undefined; + if (!/^\d{1,16}$/.test(raw)) return null; + const value = Number(raw); + return Number.isSafeInteger(value) ? value : null; +} + export async function GET(req: Request) { - try { - const url = new URL(req.url); - const rangeParam = url.searchParams.get("range"); - const granularityParam = url.searchParams.get("granularity"); - const projectParam = url.searchParams.get("project"); - const fromParam = url.searchParams.get("from"); - const toParam = url.searchParams.get("to"); - const refreshParam = url.searchParams.get("refresh"); - - const validRanges: UsageTimeRange[] = ["today", "7d", "30d", "90d", "month", "all"]; - const range: UsageTimeRange = validRanges.includes(rangeParam as UsageTimeRange) - ? (rangeParam as UsageTimeRange) - : "30d"; - - const validGranularities: UsageGranularity[] = ["daily", "monthly", "projects"]; - const granularity: UsageGranularity = validGranularities.includes(granularityParam as UsageGranularity) - ? (granularityParam as UsageGranularity) - : "daily"; - - const from = fromParam ? parseInt(fromParam, 10) : undefined; - const to = toParam ? parseInt(toParam, 10) : undefined; - const forceRefresh = refreshParam === "true" || refreshParam === "1"; + const url = new URL(req.url); + const rangeParam = url.searchParams.get("range"); + const granularityParam = url.searchParams.get("granularity"); + const projectParam = url.searchParams.get("project"); + const refreshParam = url.searchParams.get("refresh"); + const validRanges: UsageTimeRange[] = ["today", "7d", "30d", "90d", "month", "all"]; + const range: UsageTimeRange = validRanges.includes(rangeParam as UsageTimeRange) + ? (rangeParam as UsageTimeRange) + : "30d"; + + const validGranularities: UsageGranularity[] = ["daily", "monthly", "projects"]; + const granularity: UsageGranularity = validGranularities.includes(granularityParam as UsageGranularity) + ? (granularityParam as UsageGranularity) + : "daily"; + + const from = parseTimestamp(url.searchParams.get("from")); + const to = parseTimestamp(url.searchParams.get("to")); + if (from === null || to === null) return invalidWindow(); + const now = Date.now(); + // Every distinct from/to pair is its own cache key and its own full scan, so + // an unbounded/backwards/open window would let one client explore the + // transcript tree without limit. 400 days covers the UI's widest range. + if (from !== undefined && to !== undefined && (from > to || to - from > MAX_USAGE_WINDOW_MS)) return invalidWindow(); + if (from !== undefined && to === undefined && now - from > MAX_USAGE_WINDOW_MS) return invalidWindow(); + if (to !== undefined && from === undefined && now - to > MAX_USAGE_WINDOW_MS) return invalidWindow(); + + const forceRefresh = refreshParam === "true" || refreshParam === "1"; + + try { const report = await getUsageReport({ range, granularity, project: projectParam || undefined, - from: !isNaN(from as number) ? from : undefined, - to: !isNaN(to as number) ? to : undefined, + from, + to, forceRefresh, }); - return Response.json(report); } catch (error) { - return apiErrorResponse(error); + // Paths and database messages stay in the server log; the client gets a + // stable code it can act on. Match on the code, not `instanceof`: a + // re-evaluated module or a worker restart need not share class identity. + console.error("[api/usage]", error); + const code = isRecord(error) && typeof error.code === "string" ? error.code : undefined; + if (code === "usage_busy") { + return Response.json({ error: "Usage scan busy", code: "usage_busy" }, { status: 503 }); + } + if (code === "usage_timeout") { + return Response.json({ error: "Usage scan timed out", code: "usage_timeout" }, { status: 504 }); + } + return Response.json({ error: "Usage report failed", code: "usage_failed" }, { status: 500 }); } } diff --git a/lib/single-flight.test.mjs b/lib/single-flight.test.mjs new file mode 100644 index 000000000..b314c9a51 --- /dev/null +++ b/lib/single-flight.test.mjs @@ -0,0 +1,119 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const { runSingleFlight } = await import("./single-flight.ts"); + +const deferred = () => Promise.withResolvers(); + +test("concurrent callers for one key share a single run", async () => { + const flights = new Map(); + const gate = deferred(); + let runs = 0; + const run = () => { + runs++; + return gate.promise; + }; + + const first = runSingleFlight(flights, "k", run); + const second = runSingleFlight(flights, "k", run); + assert.equal(first.shared, false); + assert.equal(second.shared, true); + await Promise.resolve(); // the runner starts once the slot is recorded + assert.equal(runs, 1); + + gate.resolve("report"); + assert.equal(await first.promise, "report"); + assert.equal(await second.promise, "report"); + assert.equal(flights.size, 0, "the slot is released once the run settles"); +}); + +test("a settled run is not reused", async () => { + const flights = new Map(); + let runs = 0; + const run = async () => ++runs; + + assert.equal(await runSingleFlight(flights, "k", run).promise, 1); + assert.equal(await runSingleFlight(flights, "k", run).promise, 2); + assert.equal(runs, 2); +}); + +test("different keys run independently", async () => { + const flights = new Map(); + const a = deferred(); + const b = deferred(); + let runs = 0; + + const first = runSingleFlight(flights, "a", () => { + runs++; + return a.promise; + }); + const second = runSingleFlight(flights, "b", () => { + runs++; + return b.promise; + }); + assert.equal(first.shared, false); + assert.equal(second.shared, false); + await Promise.resolve(); // the runners start once their slots are recorded + assert.equal(runs, 2); + + a.resolve("a"); + b.resolve("b"); + assert.equal(await first.promise, "a"); + assert.equal(await second.promise, "b"); +}); + +test("a failed run releases the slot and the next call retries", async () => { + const flights = new Map(); + const failure = new Error("scan failed"); + const gate = deferred(); + let runs = 0; + + const first = runSingleFlight(flights, "k", () => { + runs++; + return gate.promise; + }); + gate.reject(failure); + await assert.rejects(first.promise, /scan failed/); + assert.equal(flights.size, 0); + + const retry = runSingleFlight(flights, "k", async () => { + runs++; + return "ok"; + }); + assert.equal(await retry.promise, "ok"); + assert.equal(runs, 2); +}); + +test("a runner that throws synchronously releases the slot instead of poisoning it", async () => { + const flights = new Map(); + const failure = new Error("sync failure"); + let runs = 0; + + const first = runSingleFlight(flights, "k", () => { + runs++; + throw failure; + }); + assert.equal(flights.size, 1, "the slot is held before the runner executes"); + assert.equal(first.shared, false); + await assert.rejects(first.promise, /sync failure/); + assert.equal(flights.size, 0, "the failed flight must not stay cached"); + + const retry = runSingleFlight(flights, "k", async () => { + runs++; + return "ok"; + }); + assert.equal(retry.shared, false, "the next caller starts a fresh run"); + assert.equal(await retry.promise, "ok"); + assert.equal(runs, 2); +}); + +test("a settling run deletes only its own entry", async () => { + const flights = new Map(); + const gate = deferred(); + const first = runSingleFlight(flights, "k", () => gate.promise); + const replacement = Promise.resolve("replacement"); + flights.set("k", replacement); + gate.resolve("first"); + assert.equal(await first.promise, "first"); + assert.equal(flights.get("k"), replacement, "a successor's slot survives the earlier run settling"); +}); diff --git a/lib/single-flight.ts b/lib/single-flight.ts new file mode 100644 index 000000000..539aa076b --- /dev/null +++ b/lib/single-flight.ts @@ -0,0 +1,29 @@ +/** + * Coalesce concurrent work for one key: callers that arrive while a run is in + * flight share its promise instead of starting a second run (the usage report + * scan is expensive and must not be started once per request). + * + * `shared` tells a caller whether it joined an existing run, which is what the + * usage route uses to decide between "computed for this request" and "served + * from cache while this refresh finishes". + */ +export function runSingleFlight( + flights: Map>, + key: string, + run: () => Promise, +): { promise: Promise; shared: boolean } { + const existing = flights.get(key); + if (existing) return { promise: existing, shared: true }; + + // The run starts in a microtask so the map holds the promise BEFORE any user + // code can throw: a synchronous throw must still release the slot instead of + // leaving a rejected promise that poisons every later caller. The finally + // deletes only its own entry, never a successor's. + const promise = Promise.resolve() + .then(run) + .finally(() => { + if (flights.get(key) === promise) flights.delete(key); + }); + flights.set(key, promise); + return { promise, shared: false }; +} diff --git a/lib/usage-db.ts b/lib/usage-db.ts index 1e7b045ec..38363c5af 100644 --- a/lib/usage-db.ts +++ b/lib/usage-db.ts @@ -769,6 +769,7 @@ export async function getUsageReportFromDb( const transcriptsInWindow = inWindowSyncedRow?.c ?? 0; const transcriptsOutsideWindow = Math.max(0, transcriptsScanned - transcriptsInWindow); const durationSeconds = Math.max(0.001, (Date.now() - startTime) / 1000); + const scannedAt = Date.now(); return { timeRange, @@ -784,7 +785,11 @@ export async function getUsageReportFromDb( transcriptsOutsideWindow, usageRecordsCount: totalRecords, durationSeconds: parseFloat(durationSeconds.toFixed(3)), - scannedAt: Date.now(), + scannedAt, }, + // Freshly computed; getUsageReport flips `stale` when it serves a cached + // report while a refresh runs. + stale: false, + scannedAt, }; } diff --git a/lib/usage-nonblocking.test.mjs b/lib/usage-nonblocking.test.mjs new file mode 100644 index 000000000..eab9c8177 --- /dev/null +++ b/lib/usage-nonblocking.test.mjs @@ -0,0 +1,186 @@ +import assert from "node:assert/strict"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { performance } from "node:perf_hooks"; +import test from "node:test"; +import { + getUsageReport, + invalidateUsageCache, + invalidateUsageReportCache, + USAGE_REPORT_REFRESH_MS, +} from "./usage-service.ts"; +import { closeUsageDatabase, getUsageDatabase } from "./usage-db.ts"; + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * Throwaway agent dir: getSessionsDir() resolves to /sessions, the usage + * database to /usage.db. + */ +async function withTempUsageDir(run) { + const dir = join(tmpdir(), `omp-test-usage-nonblocking-${Date.now()}-${Math.random().toString(36).slice(2)}`); + mkdirSync(join(dir, "sessions", "project"), { recursive: true }); + const previousAgentDir = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = dir; + invalidateUsageCache(); + invalidateUsageReportCache(); + try { + await run(dir); + } finally { + closeUsageDatabase(); + invalidateUsageCache(); + invalidateUsageReportCache(); + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + rmSync(dir, { recursive: true, force: true }); + } +} + +/** + * Write `files` transcripts of about `bytesPerFile` bytes. The bulk is ordinary + * conversation text, like a real transcript that grows through tool output and + * long user messages; only every 500th line is an assistant message with usage, + * so the scan does real read/parse work while the report stays small. + */ +function writeUsageFixtures(dir, files, bytesPerFile) { + const line = (index, withUsage) => JSON.stringify({ + type: "message", + id: `e${index}`, + parentId: null, + timestamp: new Date(Date.now() - 60_000 + index).toISOString(), + message: withUsage + ? { + role: "assistant", + provider: "anthropic", + model: "claude-opus-5-5", + usage: { input: 10, output: 5, cacheRead: 2, cacheWrite: 0, cost: { total: 0.001 } }, + } + : { role: "user", content: `message ${index} ${"x".repeat(240)}` }, + }); + const perFile = Math.max(1, Math.round(bytesPerFile / 340)); + for (let file = 0; file < files; file++) { + const header = JSON.stringify({ + type: "session", + id: `session-${file}`, + cwd: "/home/user/project", + timestamp: new Date(Date.now() - 120_000).toISOString(), + }); + const body = [header]; + for (let i = 0; i < perFile; i++) body.push(line(i, i % 500 === 0)); + writeFileSync(join(dir, "sessions", "project", `session-${file}.jsonl`), `${body.join("\n")}\n`, "utf8"); + } +} + +test("a large transcript scan leaves the event loop responsive", async () => { + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 6, 4 * 1024 * 1024); + // Opening and migrating a fresh usage.db is a one-time startup cost, not + // part of a scan; keep it out of the measured window. + getUsageDatabase(); + + let scanSettled = false; + let timerDuringScan = false; + let timerDelay = Infinity; + let maxGap = 0; + let ticks = 0; + let lastTick = performance.now(); + const startedAt = performance.now(); + + const scan = getUsageReport({ range: "30d", granularity: "daily" }).then((report) => { + scanSettled = true; + return report; + }); + + // Scheduled right after the scan starts: it must run while the scan is + // still reading, i.e. the scan never blocks this thread. + const scheduledAt = performance.now(); + setTimeout(() => { + timerDuringScan = !scanSettled; + timerDelay = performance.now() - scheduledAt; + }, 0); + const interval = setInterval(() => { + const now = performance.now(); + maxGap = Math.max(maxGap, now - lastTick); + lastTick = now; + ticks++; + }, 5); + + const report = await scan; + const elapsed = performance.now() - startedAt; + clearInterval(interval); + + assert.equal(report.stale, false); + assert.ok(report.scanInfo.usageRecordsCount > 0, "the fixture records were scanned"); + assert.ok(elapsed > 100, `fixture scan is long enough to matter (${elapsed.toFixed(0)} ms)`); + assert.ok(timerDuringScan, "a 0 ms timer fired before the scan finished"); + assert.ok(timerDelay < 100, `0 ms timer fired after ${timerDelay.toFixed(1)} ms`); + assert.ok(ticks > 0, "the interval ran during the scan"); + assert.ok(maxGap < 100, `max event-loop stall while scanning: ${maxGap.toFixed(1)} ms`); + }); +}); + +test("a served report is cached, then served stale while one background rescan runs", async () => { + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 1, 12 * 1024); + + const first = await getUsageReport({ range: "30d", granularity: "daily" }); + assert.equal(first.stale, false); + const firstCount = first.scanInfo.usageRecordsCount; + assert.ok(firstCount > 0); + + // Cached and fresh: served immediately without a rescan. + const cached = await getUsageReport({ range: "30d", granularity: "daily" }); + assert.equal(cached.stale, false); + assert.equal(cached.scannedAt, first.scannedAt); + + // After the refresh window, new transcript activity is not on the request + // path: the cached report answers, marked stale, and one refresh runs. + await sleep(USAGE_REPORT_REFRESH_MS + 100); + const fixture = join(dir, "sessions", "project", "session-0.jsonl"); + writeFileSync(fixture, `${JSON.stringify({ + type: "message", + id: "late", + parentId: null, + timestamp: new Date().toISOString(), + message: { role: "assistant", provider: "anthropic", model: "claude-opus-5-5", usage: { input: 9999, output: 0 } }, + })}\n`, { flag: "a" }); + + const stale = await getUsageReport({ range: "30d", granularity: "daily" }); + assert.equal(stale.stale, true, "the cached report is served while the rescan runs"); + assert.equal(stale.scannedAt, first.scannedAt); + assert.equal(stale.scanInfo.usageRecordsCount, firstCount, "the stale answer is the cached one"); + + // The background rescan lands and the next request reports it as current. + let refreshed; + const deadline = Date.now() + 15_000; + while (Date.now() < deadline) { + await sleep(50); + const report = await getUsageReport({ range: "30d", granularity: "daily" }); + if (!report.stale && report.scanInfo.usageRecordsCount > firstCount) { + refreshed = report; + break; + } + } + assert.ok(refreshed, "background rescan updated the cached report"); + assert.ok(refreshed.scannedAt > first.scannedAt); + }); +}); + +test("concurrent requests for one query share a single scan", async () => { + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 2, 16 * 1024); + const options = { range: "30d", granularity: "daily" }; + + const [a, b, c] = await Promise.all([ + getUsageReport(options), + getUsageReport(options), + getUsageReport(options), + ]); + + assert.equal(a, b, "joined requests resolve the same report object"); + assert.equal(b, c); + assert.equal(a.stale, false); + assert.ok(a.scanInfo.usageRecordsCount > 0); + }); +}); diff --git a/lib/usage-report-worker.test.mjs b/lib/usage-report-worker.test.mjs new file mode 100644 index 000000000..2c92b65de --- /dev/null +++ b/lib/usage-report-worker.test.mjs @@ -0,0 +1,387 @@ +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { runUsageReportInWorker, UsageWorkerError, UsageWorkerTimeoutError, UsageWorkerBusyError, getUsageWorkerPath } from "./usage-report-worker.ts"; +import { getUsageReportFromDb, getUsageDatabase, closeUsageDatabase } from "./usage-db.ts"; +import { invalidateUsageCache, invalidateUsageReportCache } from "./usage-service.ts"; + +/** + * Throwaway agent dir: the usage database and the session tree both live here, + * so a test never touches the real ~/.omp/agent. + */ +async function withTempAgentDir(run) { + const dir = join(tmpdir(), `omp-test-usage-worker-${Date.now()}-${Math.random().toString(36).slice(2)}`); + mkdirSync(join(dir, "sessions", "project"), { recursive: true }); + const previousAgentDir = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = dir; + invalidateUsageCache(); + invalidateUsageReportCache(); + try { + await run(dir); + } finally { + closeUsageDatabase(); + invalidateUsageCache(); + invalidateUsageReportCache(); + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + rmSync(dir, { recursive: true, force: true }); + } +} + +function writeJsonl(file, lines) { + writeFileSync(file, `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`, "utf8"); +} + +/** + * Two sessions, one with a foreground subagent (`task` summary plus its own + * transcript) and a summarised subagent without one, and a copy of the first + * session's entries in a later branch — the shapes the uncounted-usage pass + * has to decide, not just plain rows. + */ +function writeReportFixtures(dir) { + const project = join(dir, "sessions", "project"); + const artifacts = join(project, "session-a"); + mkdirSync(artifacts, { recursive: true }); + const started = Date.now() - 86_400_000; + const header = (id, cwd, timestamp) => ({ type: "session", id, cwd, timestamp: new Date(timestamp).toISOString() }); + const assistant = (id, timestamp, provider, model, usage) => ({ + type: "message", + id, + timestamp: new Date(timestamp).toISOString(), + message: { role: "assistant", provider, model, usage }, + }); + const taskResult = (id, timestamp, results) => ({ + type: "message", + id, + timestamp: new Date(timestamp).toISOString(), + message: { role: "toolResult", toolName: "task", details: { results } }, + }); + + writeJsonl(join(project, "session-a.jsonl"), [ + header("session-a", "/home/user/alpha", started), + assistant("e1", started + 1_000, "anthropic", "claude-opus-5-5", { input: 1_000, output: 100, cacheRead: 500 }), + assistant("e2", started + 2_000, "openai", "gpt-6", { input: 2_000, output: 200, reasoning: 50 }), + taskResult("e3", started + 3_000, [ + { id: "Sub1", resolvedModel: "anthropic/claude-sonnet-5", usage: { input: 500, output: 50 } }, + { id: "Gone1", resolvedModel: "anthropic/claude-haiku-5", usage: { input: 40, output: 4 } }, + ]), + ]); + // The foreground subagent's own transcript precedes the summary: counted + // there, the summary is skipped. + writeJsonl(join(artifacts, "Sub1.jsonl"), [ + header("sub-1", "/tmp/worktree", started + 2_500), + assistant("s1", started + 2_500, "anthropic", "claude-sonnet-5", { input: 500, output: 50 }), + ]); + // A branch copies the entries with their ids and timestamps; only the + // earliest-started session counts them. + writeJsonl(join(project, "session-b.jsonl"), [ + header("session-b", "/home/user/beta", started + 60_000), + assistant("e1", started + 1_000, "anthropic", "claude-opus-5-5", { input: 1_000, output: 100, cacheRead: 500 }), + assistant("e2", started + 2_000, "openai", "gpt-6", { input: 2_000, output: 200, reasoning: 50 }), + ]); +} + +/** The two reports may differ only in when they were computed. */ +function comparable(report) { + const copy = structuredClone(report); + delete copy.stale; + delete copy.scannedAt; + delete copy.scanInfo.durationSeconds; + delete copy.scanInfo.scannedAt; + return copy; +} + +test("the worker returns the same report as the in-process implementation", async () => { + await withTempAgentDir(async (dir) => { + writeReportFixtures(dir); + // Explicit bounds keep both runs on one window while they read the clock. + const options = { from: 0, to: Date.now() + 60_000, granularity: "daily" }; + + const fromWorker = await runUsageReportInWorker(options); + const inProcess = await getUsageReportFromDb(options); + + assert.ok(fromWorker.scanInfo.usageRecordsCount > 0, "the fixtures were scanned"); + assert.equal(fromWorker.stale, false); + assert.deepEqual(comparable(fromWorker), comparable(inProcess)); + }); +}); + +test("a report on a large database leaves the event loop responsive", async () => { + await withTempAgentDir(async (dir) => { + mkdirSync(join(dir, "sessions"), { recursive: true }); + const db = getUsageDatabase(); + // Rows inserted directly: the scan itself has nothing to read, so the + // measured work is the report pass over a big table — the correlated + // uncounted-usage statement plus the six aggregate queries. Half of the + // rows share an entry id with a copy, which is what makes that statement + // do real work. + const insert = db.prepare(` + INSERT INTO usage_records ( + file_path, session_id, session_cwd, timestamp, provider, model, + input_tokens, output_tokens, reasoning_tokens, cache_read_tokens, + cache_write_tokens, total_tokens, cost, cache_savings, cost_quality, + entry_id, subagent_file, session_started + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + const rows = 60_000; + const baseTimestamp = Date.now() - 30 * 86_400_000; + db.exec("BEGIN;"); + for (let i = 0; i < rows; i++) { + const copy = i % 2 === 1; + const index = Math.floor(i / 2); + insert.run( + copy ? join(dir, "sessions", "project", "copy.jsonl") : join(dir, "sessions", "project", "main.jsonl"), + copy ? "session-copy" : "session-main", + copy ? "/home/user/copy" : "/home/user/main", + baseTimestamp + index * 1_000, + i % 3 === 0 ? "openai" : "anthropic", + i % 5 === 0 ? "gpt-6" : "claude-opus-5-5", + 100, + 50, + 0, + 10, + 0, + 160, + 0.001, + 0.0002, + "model_priced", + `entry-${index}`, + null, + copy ? baseTimestamp + 60_000 : baseTimestamp, + ); + } + db.exec("COMMIT;"); + + let settled = false; + let maxGap = 0; + let ticks = 0; + let lastTick = performance.now(); + const startedAt = performance.now(); + const reportPromise = runUsageReportInWorker({ from: 0, to: Date.now(), granularity: "daily" }) + .finally(() => { settled = true; }); + const interval = setInterval(() => { + const now = performance.now(); + maxGap = Math.max(maxGap, now - lastTick); + lastTick = now; + ticks++; + }, 5); + + const report = await reportPromise; + const elapsed = performance.now() - startedAt; + clearInterval(interval); + + assert.ok(settled); + assert.ok(report.scanInfo.usageRecordsCount > 0); + // Half of the rows are copies of the other half. + assert.equal(report.scanInfo.usageRecordsCount, rows / 2); + assert.ok(elapsed > 100, `the report is long enough to matter (${elapsed.toFixed(0)} ms)`); + assert.ok(ticks > 0, "the interval ran during the report"); + assert.ok(maxGap < 100, `max event-loop stall while reporting: ${maxGap.toFixed(1)} ms`); + }); +}); + +test("a worker that cannot start fails with a clear error", async () => { + await withTempAgentDir(async () => { + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_USAGE_WORKER = join(tmpdir(), "omp-missing-usage-worker.ts"); + try { + await assert.rejects( + runUsageReportInWorker({}), + (error) => error instanceof UsageWorkerError && /usage report worker/i.test(error.message), + ); + } finally { + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + } + }); +}); + +/** Write a throwaway worker module and point OMP_WEB_USAGE_WORKER at it. */ +function withWorkerScript(source, run) { + const dir = mkdtempSync(join(tmpdir(), "omp-usage-worker-script-")); + const file = join(dir, "worker.mjs"); + writeFileSync(file, source, "utf8"); + const previous = process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_USAGE_WORKER = file; + return Promise.resolve(run(file)).finally(() => { + if (previous === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previous; + rmSync(dir, { recursive: true, force: true }); + }); +} + +test("a hung scan is terminated and reported as usage_timeout", { timeout: 10_000 }, async (t) => { + const previousTimeout = process.env.OMP_WEB_USAGE_TIMEOUT_MS; + process.env.OMP_WEB_USAGE_TIMEOUT_MS = "80"; + t.after(() => { + if (previousTimeout === undefined) delete process.env.OMP_WEB_USAGE_TIMEOUT_MS; + else process.env.OMP_WEB_USAGE_TIMEOUT_MS = previousTimeout; + }); + await withTempAgentDir(async () => { + await withWorkerScript("setInterval(() => {}, 1000);\n", async () => { + await assert.rejects( + runUsageReportInWorker({}), + (error) => error instanceof UsageWorkerTimeoutError && error.code === "usage_timeout", + ); + }); + }); +}); + +test("a third waiting scan is refused with usage_busy instead of joining an unbounded queue", { timeout: 10_000 }, async () => { + await withTempAgentDir(async () => { + await withWorkerScript( + "import { parentPort } from \"node:worker_threads\";\nsetTimeout(() => parentPort.postMessage({ ok: true, report: { scannedAt: 1 } }), 120);\n", + async () => { + const first = runUsageReportInWorker({ range: "7d" }); + const second = runUsageReportInWorker({ range: "30d" }); + const third = runUsageReportInWorker({ range: "90d" }); + await assert.rejects( + runUsageReportInWorker({ range: "month" }), + (error) => error instanceof UsageWorkerBusyError && error.code === "usage_busy", + ); + await Promise.all([first, second, third]); + }, + ); + }); +}); + +test("the worker path never comes from the process cwd", async (t) => { + const hostile = mkdtempSync(join(tmpdir(), "omp-usage-hostile-cwd-")); + mkdirSync(join(hostile, "lib"), { recursive: true }); + writeFileSync(join(hostile, "lib", "usage-worker.ts"), "throw new Error('hostile cwd worker');\n"); + const previousCwd = process.cwd(); + const previousPackage = process.env.OMP_WEB_PACKAGE_DIR; + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + delete process.env.OMP_WEB_PACKAGE_DIR; + delete process.env.OMP_WEB_USAGE_WORKER; + t.after(() => { + process.chdir(previousCwd); + if (previousPackage === undefined) delete process.env.OMP_WEB_PACKAGE_DIR; + else process.env.OMP_WEB_PACKAGE_DIR = previousPackage; + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + rmSync(hostile, { recursive: true, force: true }); + }); + process.chdir(hostile); + const resolved = getUsageWorkerPath(); + assert.notEqual(resolved, join(hostile, "lib", "usage-worker.ts"), "cwd must never choose the executed code"); + assert.ok(existsSync(resolved), `the module-relative worker exists (${resolved})`); +}); + +test("OMP_WEB_PACKAGE_DIR wins over the module-relative path", async (t) => { + const fakePackage = mkdtempSync(join(tmpdir(), "omp-usage-package-")); + mkdirSync(join(fakePackage, "lib"), { recursive: true }); + const worker = join(fakePackage, "lib", "usage-worker.ts"); + writeFileSync(worker, "// package worker\n"); + const previousPackage = process.env.OMP_WEB_PACKAGE_DIR; + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + delete process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_PACKAGE_DIR = fakePackage; + t.after(() => { + if (previousPackage === undefined) delete process.env.OMP_WEB_PACKAGE_DIR; + else process.env.OMP_WEB_PACKAGE_DIR = previousPackage; + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + rmSync(fakePackage, { recursive: true, force: true }); + }); + assert.equal(getUsageWorkerPath(), worker); +}); + +test("a package dir without the worker is skipped, never used as a directory guess", async (t) => { + const emptyPackage = mkdtempSync(join(tmpdir(), "omp-usage-empty-package-")); + const previousPackage = process.env.OMP_WEB_PACKAGE_DIR; + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + delete process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_PACKAGE_DIR = emptyPackage; + t.after(() => { + if (previousPackage === undefined) delete process.env.OMP_WEB_PACKAGE_DIR; + else process.env.OMP_WEB_PACKAGE_DIR = previousPackage; + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + rmSync(emptyPackage, { recursive: true, force: true }); + }); + const resolved = getUsageWorkerPath(); + assert.equal(resolved.startsWith(emptyPackage), false, "an incomplete package dir is not trusted"); + assert.ok(existsSync(resolved), `the module-relative path still finds the shipped worker (${resolved})`); +}); + +test("the worker never inherits the server's credentials", { timeout: 10_000 }, async () => { + // The worker executes a file path with the server's privileges. It needs the + // agent dir and OS plumbing, nothing else — above all not the password hash + // or the STT key (`lib/project-command-env.ts` states the same rule for + // child processes). + const secrets = { + OMP_WEB_PASSWORD_HASH: "hash", + OMP_WEB_STT_KEY: "stt", + OMP_WEB_TRUSTED_HEADER_SHA256: "trusted", + OMP_WEB_PASSWORD: "plain", + }; + const previous = Object.fromEntries(Object.keys(secrets).map((key) => [key, process.env[key]])); + Object.assign(process.env, secrets); + try { + await withTempAgentDir(async (dir) => { + await withWorkerScript( + "import { parentPort } from \"node:worker_threads\";\n" + + "parentPort.postMessage({ ok: true, report: { env: Object.keys(process.env), agentDir: process.env.PI_CODING_AGENT_DIR ?? null } });\n", + async () => { + const report = await runUsageReportInWorker({}); + const env = report.env; + for (const name of Object.keys(secrets)) assert.equal(env.includes(name), false, `${name} must not reach the worker`); + assert.equal(report.agentDir, dir, "the parent's resolved agent dir is pinned"); + assert.ok(env.includes("PATH"), "the OS plumbing a thread needs is kept"); + }, + ); + }); + } finally { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +}); + +test("a relative OMP_WEB_USAGE_WORKER is ignored, never resolved against the cwd", async (t) => { + const hostile = mkdtempSync(join(tmpdir(), "omp-usage-relative-worker-")); + writeFileSync(join(hostile, "worker.mjs"), "throw new Error('relative override ran');\n"); + const previousCwd = process.cwd(); + const previousPackage = process.env.OMP_WEB_PACKAGE_DIR; + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + delete process.env.OMP_WEB_PACKAGE_DIR; + process.env.OMP_WEB_USAGE_WORKER = "worker.mjs"; + t.after(() => { + process.chdir(previousCwd); + if (previousPackage === undefined) delete process.env.OMP_WEB_PACKAGE_DIR; + else process.env.OMP_WEB_PACKAGE_DIR = previousPackage; + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + rmSync(hostile, { recursive: true, force: true }); + }); + process.chdir(hostile); + const resolved = getUsageWorkerPath(); + assert.equal(resolved.startsWith(hostile), false, "a relative override must never pick the cwd's file"); + assert.ok(existsSync(resolved), `the module-relative worker is used (${resolved})`); +}); + +test("a missing worker rejects with a clear logged error instead of spawning", async () => { + const dir = mkdtempSync(join(tmpdir(), "omp-usage-missing-worker-")); + const missing = join(dir, "missing-worker.ts"); + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + const previousError = console.error; + const logged = []; + process.env.OMP_WEB_USAGE_WORKER = missing; + console.error = (...args) => logged.push(args.join(" ")); + try { + await assert.rejects( + runUsageReportInWorker({ range: "7d" }), + (error) => error instanceof UsageWorkerError && error.code === "usage_worker_failed" && error.message.includes(missing), + ); + } finally { + console.error = previousError; + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + rmSync(dir, { recursive: true, force: true }); + } + assert.ok(logged.some((line) => line.startsWith("[usage]") && line.includes(missing)), "the resolved path is logged"); +}); diff --git a/lib/usage-report-worker.ts b/lib/usage-report-worker.ts new file mode 100644 index 000000000..6ba892c3b --- /dev/null +++ b/lib/usage-report-worker.ts @@ -0,0 +1,263 @@ +import { existsSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { isAbsolute, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { getAgentDir } from "./omp/paths"; +import type { UsageQueryOptions, UsageReport } from "./usage-types"; + +/** + * Run one usage report in a Bun Worker. + * + * The report itself is synchronous `bun:sqlite` work (a write transaction over + * every changed transcript followed by several aggregate queries). Computing + * it on the server's thread blocked every other request — `/api/app-info` polls + * timed out behind a cold `GET /api/usage` — so the whole computation lives in + * {@link USAGE_WORKER_FILE} and the request path only awaits a message. + * + * There is deliberately no in-thread fallback: running the same statements on + * the event loop again is exactly the stall this module removes. A worker that + * cannot start, fails, or exits without answering rejects with + * {@link UsageWorkerError}, which the route reports as a 500. + */ + +/** The worker entry, shipped beside this module in the package's `lib/`. */ +const USAGE_WORKER_FILE = "usage-worker.ts"; + +/** + * Resolve the worker entry from the package layout — never from + * `process.cwd()`: a server started in an unrelated project directory would + * otherwise execute that project's `lib/usage-worker.ts` inside a worker with + * full server privileges. + * + * Both overrides are pinned to absolute paths inside the package directory: + * the worker runs with the server's provider credentials, so a relative value + * (resolved against whatever cwd the launcher had) or a directory another + * process can write is not an acceptable code source. `OMP_WEB_PACKAGE_DIR` + * is set by the launcher; the module-relative path is the normal case, since + * the server runs from source and therefore from this package's `lib/`. + */ +export function getUsageWorkerPath(): string { + const packageDir = process.env.OMP_WEB_PACKAGE_DIR; + if (packageDir) { + const fromPackage = join(packageDir, "lib", USAGE_WORKER_FILE); + if (existsSync(fromPackage)) return fromPackage; + } + const override = process.env.OMP_WEB_USAGE_WORKER; + if (override) { + // An absolute path only: a relative value would be resolved against + // whatever cwd the launcher happened to have, which is exactly the + // "another project's file runs with our env" case this function exists to + // rule out. + if (isAbsolute(override)) return resolve(override); + console.warn(`[usage] ignoring relative OMP_WEB_USAGE_WORKER=${override}`); + } + return fileURLToPath(new URL(`./${USAGE_WORKER_FILE}`, import.meta.url)); +} + +const DEFAULT_USAGE_WORKER_TIMEOUT_MS = 10 * 60_000; + +/** A scan that has not answered by then is killed; the route answers 504. */ +export function getUsageWorkerTimeoutMs(): number { + const raw = Number(process.env.OMP_WEB_USAGE_TIMEOUT_MS); + return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_USAGE_WORKER_TIMEOUT_MS; +} + +/** More than this many scans waiting behind the active one gets a 503. */ +export const MAX_QUEUED_USAGE_SCANS = 2; + +export class UsageWorkerError extends Error { + readonly code = "usage_worker_failed"; + constructor(message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "UsageWorkerError"; + } +} + +/** Another scan holds the lock and the queue is full; the route answers 503. */ +export class UsageWorkerBusyError extends Error { + readonly code = "usage_busy"; + constructor(message = "A usage scan is already running") { + super(message); + this.name = "UsageWorkerBusyError"; + } +} + +/** The scan exceeded its deadline and its worker was terminated; the route answers 504. */ +export class UsageWorkerTimeoutError extends Error { + readonly code = "usage_timeout"; + constructor(message = "The usage report timed out") { + super(message); + this.name = "UsageWorkerTimeoutError"; + } +} + +interface UsageWorkerQueueState { + /** Resolves when the active scan (and everything before it) settled. */ + tail: Promise | undefined; + /** Scans accepted and not yet finished (one running plus the queue). */ + accepted: number; +} + +declare global { + var __ompUsageWorkerQueue: UsageWorkerQueueState | undefined; +} + +function workerQueue(): UsageWorkerQueueState { + const state = (globalThis.__ompUsageWorkerQueue ??= { tail: undefined, accepted: 0 }); + state.accepted = typeof state.accepted === "number" ? state.accepted : 0; + return state; +} + +/** + * One report at a time. The write transaction and the analytics queries race + * the same usage.db that another omp-web process (dev server, second install) + * may be syncing, so running two worker reports concurrently would only trade + * event-loop stalls for SQLITE_BUSY errors. + * + * The queue is bounded: one running scan plus {@link MAX_QUEUED_USAGE_SCANS} + * waiting ones, after which a new caller gets `usage_busy` instead of joining + * an unbounded backlog. + */ +function withUsageWorkerLock(run: () => Promise): Promise { + const queue = workerQueue(); + if (queue.accepted >= MAX_QUEUED_USAGE_SCANS + 1) { + return Promise.reject(new UsageWorkerBusyError()); + } + queue.accepted += 1; + const start = () => Promise.resolve().then(run).finally(() => { + queue.accepted = Math.max(0, queue.accepted - 1); + }); + const next = queue.tail ? queue.tail.then(start, start) : start(); + queue.tail = next.catch(() => undefined); + return next; +} + +/** + * The worker gets a minimal environment, not a copy of the server's. + * + * The worker runs `bun:sqlite` over the agent directory and needs exactly + * three things: where the agent dir is (pinned to the value the parent + * resolved, so the data read and the caller's cache key cannot drift apart), + * the home directory the path helpers fall back to, and the OS plumbing a + * child needs to start (`PATH`, `SystemRoot`, `TEMP`, …). Everything else — + * above all the server's own credentials (`OMP_WEB_PASSWORD_HASH`, + * `OMP_WEB_STT_KEY`, `OMP_WEB_TRUSTED_HEADER_*`) — must not reach a thread + * that executes a file path, however that path was chosen + * (`lib/project-command-env.ts` states the same rule for child processes). + */ +function workerEnvironment(agentDir: string): Record { + const env: Record = { + PI_CODING_AGENT_DIR: agentDir, + HOME: process.env.HOME ?? homedir(), + USERPROFILE: process.env.USERPROFILE ?? process.env.HOME ?? homedir(), + // Windows resolves DLLs and the SQLite temp files through these. + SystemRoot: process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "", + TEMP: process.env.TEMP ?? tmpdir(), + TMP: process.env.TMP ?? process.env.TEMP ?? tmpdir(), + PATH: process.env.PATH ?? "", + }; + // `PI_CONFIG_DIR` renames the config root the agent-dir helpers build from; + // without it a non-default install would read the wrong directory. + if (process.env.PI_CONFIG_DIR) env.PI_CONFIG_DIR = process.env.PI_CONFIG_DIR; + if (process.env.XDG_DATA_HOME) env.XDG_DATA_HOME = process.env.XDG_DATA_HOME; + for (const key of Object.keys(env)) if (env[key] === "") delete env[key]; + return env; +} + +/** Compute a usage report in a worker thread and resolve with its answer. */ +export function runUsageReportInWorker( + options: UsageQueryOptions = {}, + agentDir: string = getAgentDir(), +): Promise { + return withUsageWorkerLock(() => computeReportInWorker(options, agentDir)); +} + +function computeReportInWorker(options: UsageQueryOptions, agentDir: string): Promise { + const workerPath = getUsageWorkerPath(); + const { promise, resolve: resolveReport, reject } = Promise.withResolvers(); + if (!existsSync(workerPath)) { + const message = `Usage report worker missing at ${workerPath}; the package is incomplete or OMP_WEB_USAGE_WORKER/OMP_WEB_PACKAGE_DIR point elsewhere`; + console.error("[usage]", message); + reject(new UsageWorkerError(message)); + return promise; + } + let worker: Worker; + try { + worker = new Worker(pathToFileURL(workerPath), { + type: "module", + name: "omp-usage-report", + env: workerEnvironment(agentDir), + }); + } catch (error) { + reject(new UsageWorkerError( + `Could not start the usage report worker at ${workerPath}: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + )); + return promise; + } + + let settled = false; + let closed = false; + + // A scan that hangs keeps the one worker lock forever; kill it so the queue + // (and the route) recover instead of piling requests behind it. + const timeoutMs = getUsageWorkerTimeoutMs(); + const timeout = setTimeout(() => { + console.error(`[usage] report worker exceeded ${timeoutMs} ms; terminating`); + finish(() => reject(new UsageWorkerTimeoutError(`The usage report worker exceeded ${timeoutMs} ms`))); + }, timeoutMs); + timeout.unref?.(); + + // Wait for the thread to be gone before the caller continues: a test or a + // shutdown may delete the agent directory right after the answer, and on + // Windows the worker's open usage.db handle would make that fail. + function finish(settle: () => void) { + if (settled) return; + settled = true; + clearTimeout(timeout); + worker.onmessage = null; + worker.onerror = null; + if (closed) { + settle(); + return; + } + // terminate() is asynchronous; one event-loop turn is not a guarantee that + // the thread is gone. A closed thread always wins, but a kill that never + // reports close must not hang the request that the timeout already + // answered. + const forced = setTimeout(settle, 5_000); + forced.unref?.(); + worker.addEventListener("close", () => { + clearTimeout(forced); + settle(); + }, { once: true }); + worker.terminate(); + } + + // `close` also fires after `terminate()`; only an exit before an answer is a + // failure. + worker.addEventListener("close", (event) => { + closed = true; + const code = (event as CloseEvent).code; + finish(() => reject(new UsageWorkerError( + `The usage report worker exited (code ${code}) without returning a report`, + ))); + }); + + worker.onmessage = (event: MessageEvent) => { + const answer = event.data as { ok?: boolean; report?: UsageReport; error?: string } | null; + if (answer?.ok === true && answer.report) { + finish(() => resolveReport(answer.report as UsageReport)); + return; + } + const reason = typeof answer?.error === "string" && answer.error ? answer.error : "unknown error"; + finish(() => reject(new UsageWorkerError(`The usage report worker failed: ${reason}`))); + }; + worker.onerror = (event: ErrorEvent) => { + const reason = typeof event.message === "string" && event.message ? event.message : "unknown error"; + finish(() => reject(new UsageWorkerError(`The usage report worker failed: ${reason}`))); + }; + + worker.postMessage({ options }); + return promise; +} diff --git a/lib/usage-route.test.mjs b/lib/usage-route.test.mjs new file mode 100644 index 000000000..718fb7135 --- /dev/null +++ b/lib/usage-route.test.mjs @@ -0,0 +1,141 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import * as route from "../app/api/usage/route.ts"; +import { invalidateUsageReportCache } from "../lib/usage-service.ts"; + +const MAX_WINDOW_MS = 400 * 24 * 60 * 60 * 1000; + +function call(query) { + return route.GET(new Request(`http://localhost/api/usage${query ? `?${query}` : ""}`)); +} + +/** Point OMP_WEB_USAGE_WORKER at a throwaway module for one test. */ +async function withWorker(source, run) { + const dir = mkdtempSync(join(tmpdir(), "omp-usage-route-worker-")); + const file = join(dir, "worker.mjs"); + writeFileSync(file, source, "utf8"); + const previous = process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_USAGE_WORKER = file; + try { + return await run(file, dir); + } finally { + if (previous === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previous; + invalidateUsageReportCache(); + rmSync(dir, { recursive: true, force: true }); + } +} + +async function withTempAgentDir(run) { + const dir = mkdtempSync(join(tmpdir(), "omp-usage-route-")); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = dir; + invalidateUsageReportCache(); + try { + return await run(dir); + } finally { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + invalidateUsageReportCache(); + rmSync(dir, { recursive: true, force: true }); + } +} + +function okWorker(report) { + return `import { parentPort } from "node:worker_threads";\nparentPort.postMessage({ ok: true, report: ${JSON.stringify(report)} });\n`; +} + +test("usage rejects non-numeric, backwards and over-wide windows with a stable code", async () => { + const cases = [ + "from=abc", + "to=NaN", + "from=1.5", + "from=-1", + "from=100&to=50", + `from=0&to=${MAX_WINDOW_MS + 1000}`, + `from=${Date.now() - MAX_WINDOW_MS - 1000}`, + ]; + for (const query of cases) { + const response = await call(query); + assert.equal(response.status, 400, query); + const body = await response.json(); + assert.deepEqual(body, { error: "Invalid usage window", code: "invalid_usage_window" }, query); + } + + // A window exactly at the limit is accepted (and answered by a fake worker). + await withTempAgentDir(async () => { + await withWorker(okWorker({ scannedAt: Date.now(), summary: { inputTokens: 1 } }), async () => { + const response = await call(`from=1000&to=${1000 + MAX_WINDOW_MS}`); + assert.equal(response.status, 200); + }); + }); +}); + +test("a valid report is served as JSON", async () => { + await withTempAgentDir(async () => { + await withWorker(okWorker({ scannedAt: Date.now(), summary: { inputTokens: 42 } }), async () => { + const response = await call("range=7d"); + assert.equal(response.status, 200); + assert.match(response.headers.get("content-type") ?? "", /application\/json/); + const body = await response.json(); + assert.equal(body.summary.inputTokens, 42); + }); + }); +}); + +test("worker failures never leak paths or raw messages to the client", async () => { + await withTempAgentDir(async () => { + const missing = join(tmpdir(), "omp-missing-usage-worker-for-route.mjs"); + const previous = process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_USAGE_WORKER = missing; + try { + const response = await call("range=30d"); + assert.equal(response.status, 500); + const body = await response.json(); + assert.deepEqual(body, { error: "Usage report failed", code: "usage_failed" }); + assert.doesNotMatch(JSON.stringify(body), /omp-missing-usage-worker|[A-Za-z]:\\|\/Users\/|\/tmp\//); + } finally { + if (previous === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previous; + } + }); +}); + +test("a scan that exceeds the deadline answers 504 usage_timeout", { timeout: 10_000 }, async (t) => { + const previousTimeout = process.env.OMP_WEB_USAGE_TIMEOUT_MS; + process.env.OMP_WEB_USAGE_TIMEOUT_MS = "60"; + t.after(() => { + if (previousTimeout === undefined) delete process.env.OMP_WEB_USAGE_TIMEOUT_MS; + else process.env.OMP_WEB_USAGE_TIMEOUT_MS = previousTimeout; + }); + await withTempAgentDir(async () => { + await withWorker("setInterval(() => {}, 1000);\n", async () => { + const response = await call("range=90d"); + assert.equal(response.status, 504); + assert.deepEqual(await response.json(), { error: "Usage scan timed out", code: "usage_timeout" }); + }); + }); +}); + +test("a full queue answers 503 usage_busy instead of piling up more scans", { timeout: 15_000 }, async () => { + await withTempAgentDir(async () => { + await withWorker( + "import { parentPort } from \"node:worker_threads\";\nsetTimeout(() => parentPort.postMessage({ ok: true, report: { scannedAt: Date.now() } }), 150);\n", + async () => { + const responses = await Promise.all([ + call("range=7d"), + call("range=30d"), + call("range=90d"), + call("range=month"), + ]); + const statuses = responses.map((response) => response.status).sort(); + assert.deepEqual(statuses, [200, 200, 200, 503]); + const busy = responses.find((response) => response.status === 503); + assert.deepEqual(await busy.json(), { error: "Usage scan busy", code: "usage_busy" }); + }, + ); + }); +}); diff --git a/lib/usage-service.test.mjs b/lib/usage-service.test.mjs index c3a1b537e..63a2983b6 100644 --- a/lib/usage-service.test.mjs +++ b/lib/usage-service.test.mjs @@ -3,6 +3,7 @@ import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; +import { invalidateSessionFileListCache } from "./omp/session-files.ts"; async function loadSubject() { return import("./usage-service.ts"); @@ -32,7 +33,7 @@ async function withTempSessionDir(run) { test("parseSessionUsage extracts assistant message usage with rate resolution", async () => { const { parseSessionUsage } = await loadSubject(); - withTempSessionDir((dir) => { + await withTempSessionDir((dir) => { const sessionFile = join(dir, "session-1.jsonl"); const now = Date.now(); @@ -110,7 +111,7 @@ test("parseSessionUsage extracts assistant message usage with rate resolution", test("parseSessionUsage extracts subagent task usage results", async () => { const { parseSessionUsage } = await loadSubject(); - withTempSessionDir((dir) => { + await withTempSessionDir((dir) => { const sessionFile = join(dir, "session-task.jsonl"); const now = Date.now(); @@ -156,7 +157,7 @@ test("parseSessionUsage extracts subagent task usage results", async () => { test("getUsageReport generates complete aggregated report across sessions", async () => { const { getUsageReport } = await loadSubject(); - withTempSessionDir(async (dir) => { + await withTempSessionDir(async (dir) => { const sessionsDir = join(dir, "sessions", "test-project"); mkdirSync(sessionsDir, { recursive: true }); @@ -357,7 +358,14 @@ test("getUsageReport counts history copied by /tan, /fork and branches once, and // the history once, and the subagent once, from the transcript the fork kept. rmSync(original); rmSync(originalArtifacts, { recursive: true, force: true }); - const afterDelete = await getUsageReport({ range: "30d" }); + // `refresh=true` is rate-limited to one scan per 60 s (lib/usage-service.ts + // USAGE_FORCE_REFRESH_COOLDOWN_MS); a test cannot wait that long, so drop + // the report and file-list caches the same way a later refresh would. + const { invalidateUsageCache, invalidateUsageReportCache } = await loadSubject(); + invalidateUsageCache(); + invalidateSessionFileListCache(); + invalidateUsageReportCache(); + const afterDelete = await getUsageReport({ range: "30d", forceRefresh: true }); assert.equal(afterDelete.summary.inputTokens, 1000 + 2000 + 300 + 70); assert.equal(afterDelete.projectBreakdown[0].sessionsCount, 2); }); @@ -426,7 +434,7 @@ test("time range bounds compute valid intervals", async () => { test("getUsageReport respects explicit from=0 timestamp without falling back to 30d", async () => { const { getUsageReport } = await loadSubject(); - withTempSessionDir(async (dir) => { + await withTempSessionDir(async (dir) => { const sessionsDir = join(dir, "sessions", "test-project"); mkdirSync(sessionsDir, { recursive: true }); @@ -462,7 +470,7 @@ test("getUsageReport respects explicit from=0 timestamp without falling back to test("usage cache evicts oldest entries when exceeding MAX_USAGE_CACHE_ENTRIES", async () => { const { parseSessionUsage, MAX_USAGE_CACHE_ENTRIES } = await loadSubject(); - withTempSessionDir((dir) => { + await withTempSessionDir((dir) => { // Create 10 dummy session files for (let i = 0; i < 10; i++) { const f = join(dir, `s-${i}.jsonl`); diff --git a/lib/usage-service.ts b/lib/usage-service.ts index b4fd1e0c1..731897864 100644 --- a/lib/usage-service.ts +++ b/lib/usage-service.ts @@ -1,5 +1,6 @@ import { statSync } from "fs"; import { basename, join } from "path"; +import { getAgentDir } from "./omp/paths"; import { readModelsConfig } from "./omp/models-config"; import { forEachFileLineSync, invalidateSessionFileListCache, readSessionHeaderSync } from "./omp/session-files"; import { SUBAGENT_ID_RE } from "./subagent-types"; @@ -9,7 +10,8 @@ import { calculateUsageCost, resolveModelRates, } from "./usage-rates"; -import { getUsageReportFromDb } from "./usage-db"; +import { runSingleFlight } from "./single-flight"; +import { runUsageReportInWorker } from "./usage-report-worker"; import type { UsageQueryOptions, UsageRecord, @@ -417,11 +419,114 @@ export function parseSessionUsage( /** * Generate full usage report over all sessions according to query options. * Backed by the persistent local SQLite usage database. + * + * The scan reads every new/changed transcript, so it must never run on the + * request path more than necessary: the last report for a query is served + * immediately (`stale: true`) while one background rescan runs, and concurrent + * requests for the same query share that rescan. A report younger than + * {@link USAGE_REPORT_REFRESH_MS} is served as current without any rescan. + * The scan itself runs in a worker (see usage-report-worker.ts): its + * synchronous SQLite work must never block this server's event loop. */ export async function getUsageReport(options: UsageQueryOptions = {}): Promise { + const agentDir = getAgentDir(); + const key = usageReportKey(options, agentDir); + if (options.forceRefresh) { + const flights = getUsageReportFlights(); + // A refresh request while this query is already scanning joins that scan + // instead of starting a second full pass (and discarding every cached + // report other callers hold). + const inFlight = flights.get(key); + if (inFlight) return inFlight; + const cached = getUsageReportCache().get(key); + if (cached && Date.now() - cached.scannedAt < USAGE_FORCE_REFRESH_COOLDOWN_MS) { + return { ...cached.report, stale: false, scannedAt: cached.scannedAt }; + } invalidateUsageCache(); invalidateSessionFileListCache(); + getUsageReportCache().clear(); + return runSingleFlight(flights, key, () => refreshUsageReport(key, options, agentDir)).promise; + } + + const cached = getUsageReportCache().get(key); + if (cached) { + const age = Date.now() - cached.scannedAt; + if (age < USAGE_REPORT_REFRESH_MS) { + return { ...cached.report, stale: false, scannedAt: cached.scannedAt }; + } + // Serve the cached report now; rescans are coalesced per query. + runSingleFlight(getUsageReportFlights(), key, () => refreshUsageReport(key, options, agentDir)).promise.catch(() => { + // A failed background rescan keeps the cached report; the next request retries. + }); + return { ...cached.report, stale: true, scannedAt: cached.scannedAt }; } - return getUsageReportFromDb(options); + + const { promise } = runSingleFlight(getUsageReportFlights(), key, () => refreshUsageReport(key, options, agentDir)); + return promise; +} + +/** Minimum age before a served report starts a background rescan. */ +export const USAGE_REPORT_REFRESH_MS = 5_000; + +/** A `refresh=true` this soon after a completed scan is answered from that scan. */ +export const USAGE_FORCE_REFRESH_COOLDOWN_MS = 60_000; + +/** Number of query reports kept; the usage page asks for one or two at a time. */ +const MAX_CACHED_USAGE_REPORTS = 24; + +interface CachedUsageReport { + report: UsageReport; + scannedAt: number; +} + +declare global { + var __ompUsageReportCache: Map | undefined; + var __ompUsageReportFlights: Map> | undefined; +} + +function getUsageReportCache(): Map { + if (!globalThis.__ompUsageReportCache) globalThis.__ompUsageReportCache = new Map(); + return globalThis.__ompUsageReportCache; +} + +function getUsageReportFlights(): Map> { + if (!globalThis.__ompUsageReportFlights) globalThis.__ompUsageReportFlights = new Map(); + return globalThis.__ompUsageReportFlights; +} + +/** Query identity: two requests share a report only for the same window, + * granularity and filters — and the same agent dir (the DB it was read from). */ +function usageReportKey(options: UsageQueryOptions, agentDir: string): string { + return [ + agentDir, + options.range ?? "", + options.granularity ?? "", + options.project ?? "", + options.from ?? "", + options.to ?? "", + ].join("|"); +} + +async function refreshUsageReport( + key: string, + options: UsageQueryOptions, + agentDir: string, +): Promise { + const report = await runUsageReportInWorker(options, agentDir); + const cached: CachedUsageReport = { report, scannedAt: report.scannedAt }; + const cache = getUsageReportCache(); + cache.delete(key); + cache.set(key, cached); + while (cache.size > MAX_CACHED_USAGE_REPORTS) { + const oldest = cache.keys().next().value; + if (oldest === undefined) break; + cache.delete(oldest); + } + return { ...report, stale: false }; +} + +/** Drop every cached report (new scan rules, tests). */ +export function invalidateUsageReportCache(): void { + globalThis.__ompUsageReportCache?.clear(); } diff --git a/lib/usage-types.ts b/lib/usage-types.ts index 33c292f50..cac31e8ee 100644 --- a/lib/usage-types.ts +++ b/lib/usage-types.ts @@ -136,6 +136,11 @@ export interface UsageReport { dayBreakdown: DayUsageSummary[]; projectBreakdown: ProjectUsageSummary[]; scanInfo: UsageReportScanInfo; + /** True when this is the last cached report served while a rescan runs in + * the background; false for a report computed for this request. */ + stale: boolean; + /** Epoch ms at which the served report was computed. */ + scannedAt: number; } export interface UsageQueryOptions { diff --git a/lib/usage-worker.ts b/lib/usage-worker.ts new file mode 100644 index 000000000..1abc8757d --- /dev/null +++ b/lib/usage-worker.ts @@ -0,0 +1,58 @@ +// Computes one usage report — transcript sync, the uncounted-usage pass and the +// analytics queries — in a Bun Worker. lib/usage-db.ts drives `bun:sqlite` +// synchronously (a transaction over every changed transcript, then several +// aggregate queries); on the server's event loop a cold scan stopped every +// other answer for tens of seconds. The parent (lib/usage-report-worker.ts) +// spawns this file, and the request path only awaits its message. +// +// The definition of the report stays in lib/usage-db.ts: the worker and the +// server share one implementation and cannot drift apart. +import { parentPort } from "node:worker_threads"; +import { closeUsageDatabase, getUsageReportFromDb } from "./usage-db"; +import { asNumber, asString, isRecord } from "./type-guards"; +import type { UsageGranularity, UsageQueryOptions, UsageTimeRange } from "./usage-types"; + +const port = parentPort; +if (!port) { + throw new Error("lib/usage-worker.ts must run as a worker thread"); +} + +const TIME_RANGES: UsageTimeRange[] = ["today", "7d", "30d", "90d", "month", "all"]; +const GRANULARITIES: UsageGranularity[] = ["daily", "monthly", "projects"]; + +/** The query the parent sent; anything outside the typed shape is ignored. */ +function readOptions(value: unknown): UsageQueryOptions { + if (!isRecord(value)) return {}; + const range = asString(value.range); + const granularity = asString(value.granularity); + const project = asString(value.project); + return { + range: TIME_RANGES.includes(range as UsageTimeRange) ? (range as UsageTimeRange) : undefined, + granularity: GRANULARITIES.includes(granularity as UsageGranularity) + ? (granularity as UsageGranularity) + : undefined, + project: project || undefined, + from: asNumber(value.from), + to: asNumber(value.to), + forceRefresh: value.forceRefresh === true, + }; +} + +port.once("message", (message: unknown) => { + const options = readOptions(isRecord(message) ? message.options : undefined); + getUsageReportFromDb(options) + .then((report) => { + // Close before answering: on Windows the open usage.db handle would keep + // the agent directory locked after the parent already has its answer. + closeUsageDatabase(); + port.postMessage({ ok: true, report }); + }) + .catch((error: unknown) => { + closeUsageDatabase(); + port.postMessage({ + ok: false, + error: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + }); +}); From 4162cab46ae153bc93f47608335febbd6966e3c7 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:24:19 +0100 Subject: [PATCH 2/7] fix(usage): ship the report worker in the binary and honour explicit refreshes A compiled binary's modules live in Bun's embedded filesystem, where existsSync fails and `new Worker` cannot start anything, so a release had no usable worker and /api/usage answered 500. scripts/build-binary.ts now bundles lib/usage-worker.ts to lib/usage-worker.mjs beside the executable and the resolver reads it, with the embedded prefix detected explicitly; a checkout keeps running the TypeScript source. The smoke test exercises /api/usage through the built install, so the release layout is covered. An explicit refresh was answered from the cache for 60 s after a scan, and an arbitrarily old report could be served stale while a rescan ran. A refresh now always rescans (joining a scan already in flight), and a report older than five minutes is never served stale: that request waits for the scan. The Usage page re-asks while the server answers stale, so it stops showing the previous visit's numbers, and a request-id guard keeps a slow older answer from overwriting a newer report. GET /api/usage now rejects explicit windows wider than 400 days; documented in CHANGELOG.md as an API change. --- CHANGELOG.md | 6 ++ components/UsageConfig.stale.test.mjs | 147 ++++++++++++++++++++++++++ components/UsageConfig.tsx | 35 +++++- lib/usage-nonblocking.test.mjs | 126 +++++++++++++++++++++- lib/usage-report-worker.test.mjs | 92 +++++++++++++++- lib/usage-report-worker.ts | 70 +++++++++--- lib/usage-service.test.mjs | 10 +- lib/usage-service.ts | 27 +++-- scripts/build-binary.ts | 15 +++ scripts/smoke.ts | 16 +++ 10 files changed, 506 insertions(+), 38 deletions(-) create mode 100644 components/UsageConfig.stale.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e9ad55..0412157ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ## [Unreleased] +### Fixes & Improvements + +- **The Usage page stays responsive while it rescans, and Refresh always rescans.** The usage report is now computed in a worker thread, so a cold scan of every transcript no longer stops the server from answering other requests. An explicit **Refresh** always rescans instead of reusing a recent report, a refresh that arrives during a running scan joins it rather than starting a second one, and a report older than five minutes is never served from the cache while a rescan runs. The page also asks again when the server answers with a cached report, so it stops showing the previous visit's numbers as soon as the new scan lands; a failed re-ask keeps the cached numbers on screen, shows the error and retries with the same bounded backoff instead of stopping for good. A refresh that fails leaves the last successful report in place as a fallback. The single-file releases now ship the worker as `lib/usage-worker.mjs` beside the binary, where a compiled binary can start it, and its own build's dependencies are covered by the shipped third-party licenses. +- **`GET /api/usage` rejects incomplete and over-wide windows.** A window must now name both ends or neither: a lone `from` or `to` used to be accepted, ignored by the report (which applies a window only when both are present) and keyed separately, so it answered the plain 30-day report under its own cache key and paid for a full transcript scan every time. An explicit `from`/`to` pair that spans more than 400 days, is backwards, or is not a whole non-negative number now answers 400 `invalid_usage_window` instead of running a full transcript scan per distinct window. Every distinct `from`/`to` pair is its own cache key and its own scan, so an unbounded window let one client explore the transcript tree without limit; 400 days covers the page's widest range. Callers that passed `from=0` to mean "everything" must switch to `range=all` or send a window inside the limit. +- **A failed or killed refresh no longer empties the usage database.** An explicit refresh used to delete every stored row before the re-sync transaction opened, so a scan that hit the worker's deadline or failed midway left an empty database behind — and the next request then cached a zero-usage report as current. The delete now happens inside the same transaction as the re-sync: a refresh that does not commit rolls back and the previous numbers stay. + ## [v0.7.4] - 2026-11-20 ### Fixed diff --git a/components/UsageConfig.stale.test.mjs b/components/UsageConfig.stale.test.mjs new file mode 100644 index 000000000..df5c6fcc6 --- /dev/null +++ b/components/UsageConfig.stale.test.mjs @@ -0,0 +1,147 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach } from "node:test"; +const { act, cleanup, fireEvent, render, screen } = await import("@testing-library/react/pure.js"); +const { createElement } = await import("react"); + +const { UsageConfig, STALE_POLL_MS } = await import("./UsageConfig.tsx"); + +const originalFetch = globalThis.fetch; + +afterEach(() => { + cleanup(); + globalThis.fetch = originalFetch; +}); + +/** + * One report shaped like the API's. `records` is what the footer prints, so a + * test can tell two answers apart without depending on the chart's layout. + */ +function report(records, stale) { + return { + timeRange: "30d", + granularity: "daily", + summary: { + totalCost: 1, + totalTokens: 1000, + inputTokens: 1000, + outputTokens: 0, + reasoningTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + cacheSavings: 0, + activeDays: 1, + tokensPerActiveDay: 1000, + cachePercentage: 0, + costQuality: { providerReported: 100, modelPriced: 0, unpriced: 0 }, + }, + providers: [], + timeSeries: [], + modelBreakdown: [], + dayBreakdown: [], + projectBreakdown: [], + scanInfo: { transcriptsScanned: 1, transcriptsOutsideWindow: 0, usageRecordsCount: records, durationSeconds: 0.1, scannedAt: Date.now() }, + stale, + scannedAt: Date.now(), + }; +} + +/** The footer's "Scanned … · N usage records · …" line, which names the served report. */ +function recordsShown() { + // Testing Library matches every ancestor too; the innermost one is the footer. + const footer = screen.getAllByText(/^Scanned .* usage records/).reduce((a, b) => (a.textContent.length <= b.textContent.length ? a : b)); + return Number(/· (\d+) usage records ·/.exec(footer.textContent ?? "")?.[1]); +} + +/** Answers with `answers` in order, repeating the last one; records each URL. */ +function serve(answers) { + const requested = []; + globalThis.fetch = async (url) => { + requested.push(String(url)); + const answer = answers[Math.min(requested.length - 1, answers.length - 1)]; + return { ok: true, json: async () => answer }; + }; + return requested; +} + +test("a stale report is re-fetched until the background scan lands, so the page never keeps old numbers", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const requested = serve([ + report(11, true), // the server served its cache while it rescans + report(22, false), // the rescan landed + ]); + + render(createElement(UsageConfig)); + await act(async () => {}); + assert.equal(requested.length, 1, "the first load asks once"); + assert.equal(recordsShown(), 11, "the cached numbers show while the rescan runs"); + + await act(async () => t.mock.timers.tick(STALE_POLL_MS)); + await act(async () => {}); + assert.equal(requested.length, 2, "the stale answer triggers a second request"); + assert.equal(recordsShown(), 22, "the page shows the rescanned numbers"); + + // The fresh answer ends the polling: no third request without a new reason. + await act(async () => t.mock.timers.tick(STALE_POLL_MS * 10)); + await act(async () => {}); + assert.equal(requested.length, 2, "a fresh report stops the re-fetch loop"); +}); + +test("a fresh report is not re-fetched", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const requested = serve([report(11, false)]); + + render(createElement(UsageConfig)); + await act(async () => {}); + await act(async () => t.mock.timers.tick(STALE_POLL_MS * 10)); + await act(async () => {}); + assert.equal(requested.length, 1); + assert.equal(recordsShown(), 11); +}); + +test("the refresh button asks for a rescan instead of reusing the cached report", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const requested = serve([report(11, false), report(33, false)]); + + render(createElement(UsageConfig)); + await act(async () => {}); + assert.equal(requested.length, 1); + + const refresh = screen.getByRole("button", { name: "Refresh usage data" }); + await act(async () => refresh.click()); + await act(async () => {}); + + assert.equal(requested.length, 2); + assert.match(requested[1], /refresh=true/); + assert.equal(recordsShown(), 33, "the refreshed numbers replace the old ones"); +}); + +test("a slow earlier answer cannot overwrite a newer report", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const requested = []; + let releaseSlow; + const slow = new Promise((resolve) => { releaseSlow = resolve; }); + globalThis.fetch = async (url) => { + requested.push(String(url)); + // The second request (the refresh) is the slow one. + if (requested.length === 2) return { ok: true, json: () => slow }; + return { ok: true, json: async () => report(requested.length === 1 ? 11 : 44, false) }; + }; + + render(createElement(UsageConfig)); + await act(async () => {}); + assert.equal(recordsShown(), 11); + + const refresh = screen.getByRole("button", { name: "Refresh usage data" }); + await act(async () => refresh.click()); + await act(async () => {}); + // The slow refresh is still pending; a different query answers meanwhile. + await act(async () => fireEvent.change(screen.getByLabelText("Time range"), { target: { value: "7d" } })); + await act(async () => {}); + assert.equal(recordsShown(), 44, "the newer query's report is on screen"); + + // The refresh answers last with numbers for the old query; they must not win. + await act(async () => releaseSlow(report(99, false))); + await act(async () => {}); + assert.equal(recordsShown(), 44, "the newer report stays on screen"); +}); diff --git a/components/UsageConfig.tsx b/components/UsageConfig.tsx index c0c35d340..87f24f79e 100644 --- a/components/UsageConfig.tsx +++ b/components/UsageConfig.tsx @@ -35,6 +35,11 @@ function formatCurrency(amount: number): string { return `$${amount.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } +/** First wait before re-asking for a report the server served as `stale`. */ +export const STALE_POLL_MS = 1_000; +/** Longest wait between those re-asks while one background rescan runs. */ +export const STALE_POLL_MAX_MS = 15_000; + export function UsageConfig() { const { t } = useI18n(); @@ -52,9 +57,14 @@ export function UsageConfig() { const [hoverIndex, setHoverIndex] = useState(null); const [hoverPos, setHoverPos] = useState<{ x: number; y: number } | null>(null); const chartSvgRef = useRef(null); + // Bumped by every fetch so a slow answer cannot overwrite a newer one. + const requestIdRef = useRef(0); + // Consecutive stale answers, which set the wait before asking again. + const stalePollsRef = useRef(0); const fetchUsage = useCallback( async (isRefresh = false, signal?: AbortSignal) => { + const requestId = ++requestIdRef.current; if (isRefresh) setRefreshing(true); else setLoading(true); setError(null); @@ -71,15 +81,19 @@ export function UsageConfig() { throw new Error(`Failed to fetch usage: ${res.statusText}`); } const data: UsageReport = await res.json(); + if (requestId !== requestIdRef.current) return; setReport(data); } catch (err) { if (err instanceof DOMException && err.name === "AbortError") { return; } + if (requestId !== requestIdRef.current) return; setError(err instanceof Error ? err.message : String(err)); } finally { - setLoading(false); - setRefreshing(false); + if (requestId === requestIdRef.current) { + setLoading(false); + setRefreshing(false); + } } }, [timeRange, granularity], @@ -93,6 +107,23 @@ export function UsageConfig() { }; }, [fetchUsage]); + // `stale` means the server answered from its cache while it rescans in the + // background. Ask again until that scan lands, backing off so a long scan + // does not turn into a tight poll loop; the server stops serving stale + // answers once the report is older than its bound and waits for the scan. + useEffect(() => { + if (!report?.stale) { + stalePollsRef.current = 0; + return; + } + const delay = Math.min(STALE_POLL_MS * 2 ** stalePollsRef.current, STALE_POLL_MAX_MS); + const timer = setTimeout(() => { + stalePollsRef.current += 1; + void fetchUsage(false); + }, delay); + return () => clearTimeout(timer); + }, [report, fetchUsage]); + // Date range subtitle calculation const dateRangeSubtitle = useMemo(() => { if (!report || !report.timeSeries || report.timeSeries.length === 0) { diff --git a/lib/usage-nonblocking.test.mjs b/lib/usage-nonblocking.test.mjs index eab9c8177..01b028a8a 100644 --- a/lib/usage-nonblocking.test.mjs +++ b/lib/usage-nonblocking.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { performance } from "node:perf_hooks"; @@ -9,6 +9,7 @@ import { invalidateUsageCache, invalidateUsageReportCache, USAGE_REPORT_REFRESH_MS, + USAGE_STALE_MAX_AGE_MS, } from "./usage-service.ts"; import { closeUsageDatabase, getUsageDatabase } from "./usage-db.ts"; @@ -184,3 +185,126 @@ test("concurrent requests for one query share a single scan", async () => { assert.ok(a.scanInfo.usageRecordsCount > 0); }); }); + +test("an explicit refresh rescans at once instead of answering from the cache", async () => { + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 1, 12 * 1024); + const options = { range: "30d", granularity: "daily" }; + + const first = await getUsageReport(options); + assert.equal(first.stale, false); + const firstCount = first.scanInfo.usageRecordsCount; + + // A usage record lands right after the scan that reported it. + writeFileSync(join(dir, "sessions", "project", "session-0.jsonl"), `${JSON.stringify({ + type: "message", + id: "late", + parentId: null, + timestamp: new Date().toISOString(), + message: { role: "assistant", provider: "anthropic", model: "claude-opus-5-5", usage: { input: 9999, output: 0 } }, + })}\n`, { flag: "a" }); + + // No wait: the refresh must not be swallowed by a cooldown, and it must + // not answer with the report the previous scan produced. + const refreshed = await getUsageReport({ ...options, forceRefresh: true }); + assert.equal(refreshed.stale, false); + assert.ok(refreshed.scannedAt >= first.scannedAt); + assert.ok( + refreshed.scanInfo.usageRecordsCount > firstCount, + `the refresh rescanned (${refreshed.scanInfo.usageRecordsCount} records, was ${firstCount})`, + ); + assert.equal(refreshed.summary.inputTokens, first.summary.inputTokens + 9999); + }); +}); + +test("a refresh joins the scan already running for its query instead of starting a second one", async () => { + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 2, 16 * 1024); + const options = { range: "30d", granularity: "daily" }; + const starts = join(dir, "worker-starts.txt"); + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + // A real scan, slowed down enough that the refresh arrives while it runs, + // and counted: a second scan would leave a second line here. + process.env.OMP_WEB_USAGE_WORKER = join(dir, "slow-worker.mjs"); + writeFileSync(process.env.OMP_WEB_USAGE_WORKER, ` +import { appendFileSync } from "node:fs"; +import { parentPort } from "node:worker_threads"; +appendFileSync(${JSON.stringify(starts)}, "start\\n"); +setTimeout(() => parentPort.postMessage({ ok: true, report: { scannedAt: Date.now(), stale: false, summary: { inputTokens: 5 } } }), 200); +`, "utf8"); + try { + const [plain, refresh] = await Promise.all([ + getUsageReport(options), + getUsageReport({ ...options, forceRefresh: true }), + ]); + assert.equal(plain, refresh, "the refresh shares the running scan's report"); + assert.equal(refresh.summary.inputTokens, 5); + assert.equal(readFileSync(starts, "utf8").trim(), "start", "exactly one scan ran"); + } finally { + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + } + }); +}); + +test("a report older than the stale bound is not served stale, the request waits for the rescan", async (t) => { + const realNow = Date.now(); + t.mock.timers.enable({ apis: ["Date"], now: realNow }); + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 1, 12 * 1024); + const options = { range: "30d", granularity: "daily" }; + + const first = await getUsageReport(options); + const firstCount = first.scanInfo.usageRecordsCount; + + writeFileSync(join(dir, "sessions", "project", "session-0.jsonl"), `${JSON.stringify({ + type: "message", + id: "late", + parentId: null, + timestamp: new Date().toISOString(), + message: { role: "assistant", provider: "anthropic", model: "claude-opus-5-5", usage: { input: 4242, output: 0 } }, + })}\n`, { flag: "a" }); + + // Past USAGE_STALE_MAX_AGE_MS the cached report is no longer an acceptable + // answer: the caller gets the rescan's result, never the old numbers. + t.mock.timers.setTime(realNow + USAGE_STALE_MAX_AGE_MS + 1_000); + const report = await getUsageReport(options); + assert.equal(report.stale, false, "an over-age report is never served as a stale answer"); + assert.equal(report.summary.inputTokens, first.summary.inputTokens + 4242); + assert.ok(report.scanInfo.usageRecordsCount > firstCount); + }); +}); + +test("a stale answer is served only inside the stale bound, and the rescan then replaces it", async () => { + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 1, 12 * 1024); + const options = { range: "30d", granularity: "daily" }; + + const first = await getUsageReport(options); + const firstCount = first.scanInfo.usageRecordsCount; + await sleep(USAGE_REPORT_REFRESH_MS + 100); + + writeFileSync(join(dir, "sessions", "project", "session-0.jsonl"), `${JSON.stringify({ + type: "message", + id: "late", + parentId: null, + timestamp: new Date().toISOString(), + message: { role: "assistant", provider: "anthropic", model: "claude-opus-5-5", usage: { input: 777, output: 0 } }, + })}\n`, { flag: "a" }); + + const stale = await getUsageReport(options); + assert.equal(stale.stale, true); + assert.equal(stale.scannedAt, first.scannedAt); + + // What the Usage UI does with a stale answer: ask again until the scan lands. + const deadline = Date.now() + 15_000; + let current = stale; + while (current.stale && Date.now() < deadline) { + await sleep(50); + current = await getUsageReport(options); + } + assert.equal(current.stale, false, "the background rescan lands within the deadline"); + assert.equal(current.summary.inputTokens, first.summary.inputTokens + 777); + assert.ok(current.scanInfo.usageRecordsCount > firstCount); + }); +}); diff --git a/lib/usage-report-worker.test.mjs b/lib/usage-report-worker.test.mjs index 2c92b65de..f40d8649a 100644 --- a/lib/usage-report-worker.test.mjs +++ b/lib/usage-report-worker.test.mjs @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node: import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { runUsageReportInWorker, UsageWorkerError, UsageWorkerTimeoutError, UsageWorkerBusyError, getUsageWorkerPath } from "./usage-report-worker.ts"; +import { runUsageReportInWorker, UsageWorkerError, UsageWorkerTimeoutError, UsageWorkerBusyError, getUsageWorkerPath, resolveUsageWorkerPath } from "./usage-report-worker.ts"; import { getUsageReportFromDb, getUsageDatabase, closeUsageDatabase } from "./usage-db.ts"; import { invalidateUsageCache, invalidateUsageReportCache } from "./usage-service.ts"; @@ -385,3 +385,93 @@ test("a missing worker rejects with a clear logged error instead of spawning", a } assert.ok(logged.some((line) => line.startsWith("[usage]") && line.includes(missing)), "the resolved path is logged"); }); + +test("a release layout resolves the bundled worker beside the executable", async (t) => { + const release = mkdtempSync(join(tmpdir(), "omp-usage-release-")); + mkdirSync(join(release, "lib"), { recursive: true }); + // What scripts/build-binary.ts writes: one bundled file, no TypeScript. + const bundled = join(release, "lib", "usage-worker.mjs"); + writeFileSync(bundled, "// bundled worker\n"); + const previousPackage = process.env.OMP_WEB_PACKAGE_DIR; + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + delete process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_PACKAGE_DIR = release; + t.after(() => { + if (previousPackage === undefined) delete process.env.OMP_WEB_PACKAGE_DIR; + else process.env.OMP_WEB_PACKAGE_DIR = previousPackage; + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + rmSync(release, { recursive: true, force: true }); + }); + // The binary sets OMP_WEB_PACKAGE_DIR to its own directory, so this is the + // path a release actually takes; the bundle wins over any .ts. + assert.equal(getUsageWorkerPath(), bundled); + writeFileSync(join(release, "lib", "usage-worker.ts"), "// source\n"); + assert.equal(getUsageWorkerPath(), bundled, "the release bundle is preferred over source"); +}); + +test("a checkout without a bundle runs the TypeScript worker", async (t) => { + const checkout = mkdtempSync(join(tmpdir(), "omp-usage-checkout-")); + mkdirSync(join(checkout, "lib"), { recursive: true }); + const source = join(checkout, "lib", "usage-worker.ts"); + writeFileSync(source, "// source worker\n"); + const previousPackage = process.env.OMP_WEB_PACKAGE_DIR; + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + delete process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_PACKAGE_DIR = checkout; + t.after(() => { + if (previousPackage === undefined) delete process.env.OMP_WEB_PACKAGE_DIR; + else process.env.OMP_WEB_PACKAGE_DIR = previousPackage; + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + rmSync(checkout, { recursive: true, force: true }); + }); + assert.equal(getUsageWorkerPath(), source); +}); + +test("a compiled binary reads the worker from its own directory, never from the embedded filesystem", (t) => { + // The layout scripts/build-binary.ts produces: ompweb.exe and lib/usage-worker.mjs. + const release = mkdtempSync(join(tmpdir(), "omp-usage-compiled-")); + mkdirSync(join(release, "lib"), { recursive: true }); + const bundled = join(release, "lib", "usage-worker.mjs"); + writeFileSync(bundled, "// bundled worker\n"); + t.after(() => rmSync(release, { recursive: true, force: true })); + + // Bun mounts the binary's modules under a virtual prefix; nothing there can + // be started as a worker. + for (const moduleDir of ["B:\\~BUN\\root\\", "/$bunfs/root/"]) { + assert.equal( + resolveUsageWorkerPath({ moduleDir, execDir: release }), + bundled, + `${moduleDir} must fall back to the executable's own directory`, + ); + } + // Without the bundle the resolver names the path the error message reports, + // instead of handing the virtual path to `new Worker`. + const empty = mkdtempSync(join(tmpdir(), "omp-usage-compiled-empty-")); + t.after(() => rmSync(empty, { recursive: true, force: true })); + const resolved = resolveUsageWorkerPath({ moduleDir: "B:\\~BUN\\root\\", execDir: empty }); + assert.equal(resolved, join(empty, "lib", "usage-worker.mjs")); + assert.equal(existsSync(resolved), false); +}); + +test("a release package dir wins, and a relative override is refused, in the resolver itself", (t) => { + const release = mkdtempSync(join(tmpdir(), "omp-usage-resolver-")); + mkdirSync(join(release, "lib"), { recursive: true }); + const bundled = join(release, "lib", "usage-worker.mjs"); + writeFileSync(bundled, "// bundled worker\n"); + t.after(() => rmSync(release, { recursive: true, force: true })); + + // The binary sets OMP_WEB_PACKAGE_DIR to its own directory; that is the path + // a release takes, and the bundle wins over a stray .ts beside it. + assert.equal(resolveUsageWorkerPath({ packageDir: release, moduleDir: "B:\\~BUN\\root\\", execDir: release }), bundled); + writeFileSync(join(release, "lib", "usage-worker.ts"), "// source\n"); + assert.equal(resolveUsageWorkerPath({ packageDir: release, moduleDir: "B:\\~BUN\\root\\", execDir: release }), bundled); + + // A relative override never resolves against a cwd: the embedded module dir + // is still not a code source, so the executable's directory answers. + assert.equal( + resolveUsageWorkerPath({ override: "worker.mjs", moduleDir: "B:\\~BUN\\root\\", execDir: release }), + bundled, + ); +}); diff --git a/lib/usage-report-worker.ts b/lib/usage-report-worker.ts index 6ba892c3b..de1760ee1 100644 --- a/lib/usage-report-worker.ts +++ b/lib/usage-report-worker.ts @@ -1,6 +1,6 @@ import { existsSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; -import { isAbsolute, join, resolve } from "node:path"; +import { dirname, isAbsolute, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { getAgentDir } from "./omp/paths"; import type { UsageQueryOptions, UsageReport } from "./usage-types"; @@ -12,7 +12,7 @@ import type { UsageQueryOptions, UsageReport } from "./usage-types"; * every changed transcript followed by several aggregate queries). Computing * it on the server's thread blocked every other request — `/api/app-info` polls * timed out behind a cold `GET /api/usage` — so the whole computation lives in - * {@link USAGE_WORKER_FILE} and the request path only awaits a message. + * `lib/usage-worker.ts` and the request path only awaits a message. * * There is deliberately no in-thread fallback: running the same statements on * the event loop again is exactly the stall this module removes. A worker that @@ -20,8 +20,19 @@ import type { UsageQueryOptions, UsageReport } from "./usage-types"; * {@link UsageWorkerError}, which the route reports as a 500. */ -/** The worker entry, shipped beside this module in the package's `lib/`. */ -const USAGE_WORKER_FILE = "usage-worker.ts"; +/** The worker entry as it ships in a release: a single bundled file. */ +const USAGE_WORKER_BUNDLE = "usage-worker.mjs"; +/** The worker entry in a checkout: TypeScript, run by Bun directly. */ +const USAGE_WORKER_SOURCE = "usage-worker.ts"; + +/** The worker under `/lib/`, preferring the bundle a release ships. */ +function packagedWorker(dir: string): string | undefined { + for (const name of [USAGE_WORKER_BUNDLE, USAGE_WORKER_SOURCE]) { + const candidate = join(dir, "lib", name); + if (existsSync(candidate)) return candidate; + } + return undefined; +} /** * Resolve the worker entry from the package layout — never from @@ -33,25 +44,54 @@ const USAGE_WORKER_FILE = "usage-worker.ts"; * the worker runs with the server's provider credentials, so a relative value * (resolved against whatever cwd the launcher had) or a directory another * process can write is not an acceptable code source. `OMP_WEB_PACKAGE_DIR` - * is set by the launcher; the module-relative path is the normal case, since - * the server runs from source and therefore from this package's `lib/`. + * is set by the launcher and by the compiled binary (to its own directory); + * the module-relative path is the normal case for a source run, since the + * server then lives in this package's `lib/`. + * + * A compiled binary's own modules sit in Bun's embedded filesystem + * (`B:\~BUN\root\` on Windows, `/$bunfs/root/` elsewhere), where `existsSync` + * fails and `new Worker` cannot resolve anything, so that case reads the + * bundle the release ships beside the executable (`lib/usage-worker.mjs`, + * scripts/build-binary.ts). `execPath` is the running program, which is the + * binary itself there. */ export function getUsageWorkerPath(): string { - const packageDir = process.env.OMP_WEB_PACKAGE_DIR; - if (packageDir) { - const fromPackage = join(packageDir, "lib", USAGE_WORKER_FILE); - if (existsSync(fromPackage)) return fromPackage; + return resolveUsageWorkerPath({ + packageDir: process.env.OMP_WEB_PACKAGE_DIR, + override: process.env.OMP_WEB_USAGE_WORKER, + moduleDir: fileURLToPath(new URL(".", import.meta.url)), + execDir: dirname(process.execPath), + }); +} + +/** + * The decision {@link getUsageWorkerPath} makes, with every input passed in so + * a test can exercise the release layout without building a binary. + */ +export function resolveUsageWorkerPath(input: { + packageDir?: string; + override?: string; + moduleDir: string; + execDir: string; +}): string { + if (input.packageDir) { + const fromPackage = packagedWorker(input.packageDir); + if (fromPackage) return fromPackage; } - const override = process.env.OMP_WEB_USAGE_WORKER; - if (override) { + if (input.override) { // An absolute path only: a relative value would be resolved against // whatever cwd the launcher happened to have, which is exactly the // "another project's file runs with our env" case this function exists to // rule out. - if (isAbsolute(override)) return resolve(override); - console.warn(`[usage] ignoring relative OMP_WEB_USAGE_WORKER=${override}`); + if (isAbsolute(input.override)) return resolve(input.override); + console.warn(`[usage] ignoring relative OMP_WEB_USAGE_WORKER=${input.override}`); + } + if (/(^|[\\/])(~BUN|\$bunfs)([\\/]|$)/i.test(input.moduleDir)) { + // OMP_WEB_PACKAGE_DIR pointed somewhere incomplete; the executable's own + // directory is still a real directory on disk. + return packagedWorker(input.execDir) ?? join(input.execDir, "lib", USAGE_WORKER_BUNDLE); } - return fileURLToPath(new URL(`./${USAGE_WORKER_FILE}`, import.meta.url)); + return packagedWorker(input.moduleDir) ?? join(input.moduleDir, USAGE_WORKER_SOURCE); } const DEFAULT_USAGE_WORKER_TIMEOUT_MS = 10 * 60_000; diff --git a/lib/usage-service.test.mjs b/lib/usage-service.test.mjs index 63a2983b6..8016dc050 100644 --- a/lib/usage-service.test.mjs +++ b/lib/usage-service.test.mjs @@ -3,7 +3,6 @@ import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { invalidateSessionFileListCache } from "./omp/session-files.ts"; async function loadSubject() { return import("./usage-service.ts"); @@ -358,13 +357,8 @@ test("getUsageReport counts history copied by /tan, /fork and branches once, and // the history once, and the subagent once, from the transcript the fork kept. rmSync(original); rmSync(originalArtifacts, { recursive: true, force: true }); - // `refresh=true` is rate-limited to one scan per 60 s (lib/usage-service.ts - // USAGE_FORCE_REFRESH_COOLDOWN_MS); a test cannot wait that long, so drop - // the report and file-list caches the same way a later refresh would. - const { invalidateUsageCache, invalidateUsageReportCache } = await loadSubject(); - invalidateUsageCache(); - invalidateSessionFileListCache(); - invalidateUsageReportCache(); + // An explicit refresh rescans immediately, however recent the last scan + // was; nothing here waits out a cooldown or clears a cache by hand. const afterDelete = await getUsageReport({ range: "30d", forceRefresh: true }); assert.equal(afterDelete.summary.inputTokens, 1000 + 2000 + 300 + 70); assert.equal(afterDelete.projectBreakdown[0].sessionsCount, 2); diff --git a/lib/usage-service.ts b/lib/usage-service.ts index 731897864..cab1f7e5f 100644 --- a/lib/usage-service.ts +++ b/lib/usage-service.ts @@ -424,7 +424,10 @@ export function parseSessionUsage( * request path more than necessary: the last report for a query is served * immediately (`stale: true`) while one background rescan runs, and concurrent * requests for the same query share that rescan. A report younger than - * {@link USAGE_REPORT_REFRESH_MS} is served as current without any rescan. + * {@link USAGE_REPORT_REFRESH_MS} is served as current without any rescan, and + * one older than {@link USAGE_STALE_MAX_AGE_MS} is never served stale: that + * request waits for the scan instead, so no caller is handed an arbitrarily + * old report. * The scan itself runs in a worker (see usage-report-worker.ts): its * synchronous SQLite work must never block this server's event loop. */ @@ -435,17 +438,17 @@ export async function getUsageReport(options: UsageQueryOptions = {}): Promise refreshUsageReport(key, options, agentDir)).promise; } @@ -456,7 +459,9 @@ export async function getUsageReport(options: UsageQueryOptions = {}): Promise refreshUsageReport(key, options, agentDir)).promise.catch(() => { + const { promise } = runSingleFlight(getUsageReportFlights(), key, () => refreshUsageReport(key, options, agentDir)); + if (age >= USAGE_STALE_MAX_AGE_MS) return promise; + promise.catch(() => { // A failed background rescan keeps the cached report; the next request retries. }); return { ...cached.report, stale: true, scannedAt: cached.scannedAt }; @@ -469,8 +474,8 @@ export async function getUsageReport(options: UsageQueryOptions = {}): Promise { + const response = await fetch(`${base}/api/usage?range=30d&granularity=daily&refresh=true`); + const body = await response.text(); + assert(response.status === 200, `status ${response.status}: ${body.slice(0, 400)}`); + const report = JSON.parse(body) as { summary?: { inputTokens?: number }; scanInfo?: { transcriptsScanned?: number }; stale?: boolean }; + assert(report.summary && typeof report.summary.inputTokens === "number", `no summary in ${body.slice(0, 400)}`); + assert(report.scanInfo && typeof report.scanInfo.transcriptsScanned === "number", `no scanInfo in ${body.slice(0, 400)}`); + // The fixture session above has no assistant usage, so the scan reports the transcript it read and no tokens. + assert(report.scanInfo.transcriptsScanned >= 1, `scanned ${report.scanInfo.transcriptsScanned} transcripts`); + assert.equal(report.summary.inputTokens, 0); + assert.equal(report.stale, false, "a forced refresh is computed, never served stale"); + }); + if (binary) { await step("the owned binary release supports GUI-coordinated updates", async () => { const update = await (await fetch(`${base}/api/app-update`)).json() as { installMethod?: string; selfUpdateSupported?: boolean; updateCommand?: string }; From 917aeb3f3a5ed06b330fb56dc98290cf46fca1b6 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:40:25 +0100 Subject: [PATCH 3/7] fix(usage): keep polling after a failed stale re-ask and retain the last report A failed poll left `report` unchanged, so the stale-poll effect never ran again and the page kept the old numbers forever with no error shown. Bump a counter on failure so the effect re-arms with the existing bounded backoff, and show the error above the report while stale numbers are on screen. A failed forced refresh also deleted the cached report before scanning; keep it so a later request still has the last good answer as a fallback, and include the usage worker's own metafile in the shipped license collection. --- components/UsageConfig.stale.test.mjs | 43 +++++++++++++++++++++++++++ components/UsageConfig.tsx | 34 ++++++++++++++++++++- lib/usage-nonblocking.test.mjs | 33 ++++++++++++++++++++ lib/usage-service.ts | 5 +++- scripts/build-binary.ts | 12 +++++++- 5 files changed, 124 insertions(+), 3 deletions(-) diff --git a/components/UsageConfig.stale.test.mjs b/components/UsageConfig.stale.test.mjs index df5c6fcc6..7a03dcf12 100644 --- a/components/UsageConfig.stale.test.mjs +++ b/components/UsageConfig.stale.test.mjs @@ -145,3 +145,46 @@ test("a slow earlier answer cannot overwrite a newer report", async (t) => { await act(async () => {}); assert.equal(recordsShown(), 44, "the newer report stays on screen"); }); + +test("a failed stale poll reschedules with the bounded backoff and shows the error until a fresh report lands", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + // The maintainer's sequence: stale report, 503 on the first poll, then a + // recovered fresh report. The 503 must neither stop the polling nor hide. + const requested = []; + globalThis.fetch = async (url) => { + requested.push(String(url)); + if (requested.length === 1) return { ok: true, json: async () => report(11, true) }; + if (requested.length === 2) return { ok: false, status: 503, statusText: "Service Unavailable", json: async () => ({}) }; + return { ok: true, json: async () => report(22, false) }; + }; + + render(createElement(UsageConfig)); + await act(async () => {}); + assert.equal(requested.length, 1); + assert.equal(recordsShown(), 11, "the stale report shows while the rescan runs"); + + await act(async () => t.mock.timers.tick(STALE_POLL_MS)); + await act(async () => {}); + assert.equal(requested.length, 2, "the stale answer schedules the first poll"); + assert.equal(recordsShown(), 11, "the stale report stays on screen after a failed poll"); + assert.ok( + screen.getByRole("alert").textContent?.includes("Service Unavailable"), + "the failure is visible while the stale report is shown", + ); + + // The next attempt uses the existing bounded backoff (2x), not a tight loop. + await act(async () => t.mock.timers.tick(STALE_POLL_MS)); + await act(async () => {}); + assert.equal(requested.length, 2, "no request before the doubled backoff elapsed"); + + await act(async () => t.mock.timers.tick(STALE_POLL_MS)); + await act(async () => {}); + assert.equal(requested.length, 3, "the failed poll rescheduled the next attempt"); + assert.equal(recordsShown(), 22, "the recovered fresh report replaces the stale numbers"); + assert.equal(screen.queryByRole("alert"), null, "the error clears once a report arrives"); + + // A fresh report ends the loop again. + await act(async () => t.mock.timers.tick(STALE_POLL_MS * 10)); + await act(async () => {}); + assert.equal(requested.length, 3, "a fresh report stops the re-fetch loop"); +}); diff --git a/components/UsageConfig.tsx b/components/UsageConfig.tsx index 87f24f79e..356d6b49f 100644 --- a/components/UsageConfig.tsx +++ b/components/UsageConfig.tsx @@ -61,6 +61,9 @@ export function UsageConfig() { const requestIdRef = useRef(0); // Consecutive stale answers, which set the wait before asking again. const stalePollsRef = useRef(0); + // Bumped by a failed poll so the stale-poll effect re-arms: a failure leaves + // `report` unchanged, and without this the effect would never run again. + const [failedPolls, setFailedPolls] = useState(0); const fetchUsage = useCallback( async (isRefresh = false, signal?: AbortSignal) => { @@ -89,6 +92,9 @@ export function UsageConfig() { } if (requestId !== requestIdRef.current) return; setError(err instanceof Error ? err.message : String(err)); + // A failed poll must not end the stale-report recovery: bumping this + // re-arms the poll effect even though `report` did not change. + setFailedPolls((count) => count + 1); } finally { if (requestId === requestIdRef.current) { setLoading(false); @@ -111,6 +117,9 @@ export function UsageConfig() { // background. Ask again until that scan lands, backing off so a long scan // does not turn into a tight poll loop; the server stops serving stale // answers once the report is older than its bound and waits for the scan. + // A failed poll keeps the stale report on screen and schedules the next + // attempt: `report` does not change on failure, so the effect would not run + // again and polling would stop for good. useEffect(() => { if (!report?.stale) { stalePollsRef.current = 0; @@ -122,7 +131,7 @@ export function UsageConfig() { void fetchUsage(false); }, delay); return () => clearTimeout(timer); - }, [report, fetchUsage]); + }, [report, fetchUsage, failedPolls]); // Date range subtitle calculation const dateRangeSubtitle = useMemo(() => { @@ -461,6 +470,29 @@ export function UsageConfig() { + {/* A failed poll must stay visible: the numbers below are the last report + that arrived, which may predate the failure. */} + {error && report && ( +
+ + {t("usageConfig.error")} + {error} +
+ )} + {/* 2. Top Row: Raw Token Cost & Chart */}
firstCount); }); }); + +test("a failed forced refresh keeps the last cached report as a fallback", async () => { + await withTempUsageDir(async (dir) => { + writeUsageFixtures(dir, 1, 12 * 1024); + const options = { range: "30d", granularity: "daily" }; + + const first = await getUsageReport(options); + assert.equal(first.stale, false); + + // The rescan fails (a missing worker module fails the scan itself). + const previousWorker = process.env.OMP_WEB_USAGE_WORKER; + process.env.OMP_WEB_USAGE_WORKER = join(dir, "missing-worker.mjs"); + try { + await assert.rejects(getUsageReport({ ...options, forceRefresh: true })); + } finally { + if (previousWorker === undefined) delete process.env.OMP_WEB_USAGE_WORKER; + else process.env.OMP_WEB_USAGE_WORKER = previousWorker; + } + + // The failure must not have thrown the last good report away: a later + // request still answers from it instead of failing again. (It is still + // inside USAGE_REPORT_REFRESH_MS, so it is served as current.) + const afterFailure = await getUsageReport(options); + assert.equal(afterFailure.scannedAt, first.scannedAt, "the last successful report is still the fallback"); + assert.equal(afterFailure.summary.inputTokens, first.summary.inputTokens); + assert.equal(afterFailure.stale, false, "a young cached report is still served as current"); + + // And a successful refresh still replaces it. + const refreshed = await getUsageReport({ ...options, forceRefresh: true }); + assert.equal(refreshed.stale, false); + assert.ok(refreshed.scannedAt >= first.scannedAt); + }); +}); diff --git a/lib/usage-service.ts b/lib/usage-service.ts index cab1f7e5f..661b795e1 100644 --- a/lib/usage-service.ts +++ b/lib/usage-service.ts @@ -448,7 +448,10 @@ export async function getUsageReport(options: UsageQueryOptions = {}): Promise refreshUsageReport(key, options, agentDir)).promise; } diff --git a/scripts/build-binary.ts b/scripts/build-binary.ts index 8fa2b5031..df826edb8 100644 --- a/scripts/build-binary.ts +++ b/scripts/build-binary.ts @@ -54,6 +54,9 @@ const usageWorker = await Bun.build({ target: "bun", format: "esm", minify: true, + // Its dependencies ship beside the binary as this bundle, so their licenses + // must come from this metafile too: the main bundle may not name them. + metafile: true, throw: false, }); for (const log of usageWorker.logs) console.log(log); @@ -76,7 +79,14 @@ for (const file of new Bun.Glob("app/fonts/*-{OFL.txt,LICENSE.*}").scanSync(root const katex = path.dirname(Bun.resolveSync("katex/package.json", root)); for (const file of ["package.json", "LICENSE", "dist/katex.min.css", "dist/fonts"]) copy(path.join(katex, file), `node_modules/katex/${file}`); const clientPackages = (JSON.parse(readFileSync(clientPackagesFile, "utf8")) as string[]).map((dir) => path.resolve(root, dir)); -writeLicenses(out, [...new Set([...bundledPackageDirs(result.metafile!, process.cwd()), ...clientPackages])].sort(), bunLicense); +// The server bundle, the client bundle and the usage worker's own bundle: the +// worker is a separate build shipped as a file, so a dependency only it uses +// would otherwise ship without its license. +writeLicenses(out, [...new Set([ + ...bundledPackageDirs(result.metafile!, process.cwd()), + ...bundledPackageDirs(usageWorker.metafile!, process.cwd()), + ...clientPackages, +])].sort(), bunLicense); // Bun.Archive writes every entry as 0644 (the binary would lose its execute bit) and makes no zip: the system tools do. // On Windows that is its own bsdtar, which makes zips: a GNU tar from Git Bash on PATH makes none. From fed43fa526decd6e50859b77f168ff55b53f3055 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:07:23 +0100 Subject: [PATCH 4/7] fix(usage): make a forced refresh atomic and reject lone window bounds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A forced refresh deleted every stored row before the re-sync transaction opened. A scan that hit the worker's ten-minute deadline, or failed between the delete and the commit, therefore left an empty database behind, and the next request cached that as a current zero-usage report. The delete now runs inside the same transaction as the re-sync: a refresh that does not commit rolls back and the previous rows survive. A lone `from` or `to` was accepted, keyed separately and then ignored — the report applies a window only when both ends are present — so `from=` answered the plain 30-day report under its own cache key and paid for a full transcript scan per distinct value. Both directions are rejected with 400 invalid_usage_window now, and the route test covers the lone `to` case that was missing. Also removes two pieces of dead API surface the review flagged: invalidateUsageReportCache had no production caller (the refresh path needs the last good report as a fallback, so it now calls the narrower per-file reset, and the test-only full reset is invalidateUsageCache), and runSingleFlight's `shared` flag was never read although its doc claimed the usage route used it. Documents OMP_WEB_USAGE_WORKER and OMP_WEB_USAGE_TIMEOUT_MS in the README table, and logs only the error message from the usage route instead of the error object with its stack and transcript paths. --- README.md | 2 ++ app/api/usage/route.ts | 12 +++++--- lib/single-flight.test.mjs | 31 +++++++++---------- lib/single-flight.ts | 10 ++---- lib/usage-db.test.mjs | 53 ++++++++++++++++++++++++++++++++ lib/usage-db.ts | 32 +++++++++++++------ lib/usage-nonblocking.test.mjs | 3 -- lib/usage-report-worker.test.mjs | 4 +-- lib/usage-route.test.mjs | 15 ++++++--- lib/usage-service.ts | 31 +++++++++++-------- 10 files changed, 134 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index ab17fb212..23161a56e 100644 --- a/README.md +++ b/README.md @@ -1049,6 +1049,8 @@ Stop it with `Stop-ScheduledTask ompweb-host`, then end the running host with | `OMP_WEB_STT_ENDPOINT` | OpenAI-compatible transcription endpoint URL. Leave unset to transcribe with `OMP_WEB_STT_MODEL` through omp's own credentials | _None_ | | `OMP_WEB_STT_KEY` | Optional API key for the STT endpoint | _None_ | | `OMP_WEB_STT_MODEL` | Model name for the STT endpoint. Without an endpoint: an omp speech-to-text model run with omp's logins, such as `openai-codex/codex-transcribe` (ChatGPT subscription; needs an omp version with that model) | _None (disabled without an endpoint)_ | +| `OMP_WEB_USAGE_WORKER` | Absolute path to the module that computes a usage report, overriding the one shipped with ompweb. Relative values are ignored with a warning: the worker runs with the server's provider credentials | _the packaged `lib/usage-worker.mjs`_ | +| `OMP_WEB_USAGE_TIMEOUT_MS` | How long a usage scan may run before it is killed and `GET /api/usage` answers `504 usage_timeout`. Raise it on a very large transcript tree | `600000` (10 minutes) | **`OMP_WEB_NAME` and installed apps.** An installed app (PWA) is usually named after the page it was installed from. If you later change `OMP_WEB_NAME`, or reach omp-web through a different address while `OMP_WEB_NAME` is `url`, `host` or `domain`, your operating system may rename the installed app as well. Leave `OMP_WEB_NAME` empty, or set a name that identifies this omp-web server whatever domain name or address is used to reach it. diff --git a/app/api/usage/route.ts b/app/api/usage/route.ts index 4229093ea..1a4c13271 100644 --- a/app/api/usage/route.ts +++ b/app/api/usage/route.ts @@ -38,13 +38,15 @@ export async function GET(req: Request) { const from = parseTimestamp(url.searchParams.get("from")); const to = parseTimestamp(url.searchParams.get("to")); if (from === null || to === null) return invalidWindow(); - const now = Date.now(); + // A lone bound is rejected rather than ignored: the report only applies an + // explicit window when BOTH ends are present, so `from=` used to + // answer the plain 30-day report under its own cache key — a wrong answer + // that also paid for a full transcript scan per distinct value. + if ((from === undefined) !== (to === undefined)) return invalidWindow(); // Every distinct from/to pair is its own cache key and its own full scan, so // an unbounded/backwards/open window would let one client explore the // transcript tree without limit. 400 days covers the UI's widest range. if (from !== undefined && to !== undefined && (from > to || to - from > MAX_USAGE_WINDOW_MS)) return invalidWindow(); - if (from !== undefined && to === undefined && now - from > MAX_USAGE_WINDOW_MS) return invalidWindow(); - if (to !== undefined && from === undefined && now - to > MAX_USAGE_WINDOW_MS) return invalidWindow(); const forceRefresh = refreshParam === "true" || refreshParam === "1"; @@ -62,7 +64,9 @@ export async function GET(req: Request) { // Paths and database messages stay in the server log; the client gets a // stable code it can act on. Match on the code, not `instanceof`: a // re-evaluated module or a worker restart need not share class identity. - console.error("[api/usage]", error); + // Log the message only: the error object carries a stack and often a + // transcript path, neither of which belongs in the log. + console.error("[api/usage]", error instanceof Error ? error.message : String(error)); const code = isRecord(error) && typeof error.code === "string" ? error.code : undefined; if (code === "usage_busy") { return Response.json({ error: "Usage scan busy", code: "usage_busy" }, { status: 503 }); diff --git a/lib/single-flight.test.mjs b/lib/single-flight.test.mjs index b314c9a51..242ba9cea 100644 --- a/lib/single-flight.test.mjs +++ b/lib/single-flight.test.mjs @@ -16,14 +16,13 @@ test("concurrent callers for one key share a single run", async () => { const first = runSingleFlight(flights, "k", run); const second = runSingleFlight(flights, "k", run); - assert.equal(first.shared, false); - assert.equal(second.shared, true); + assert.equal(first, second, "the second caller joins the first run"); await Promise.resolve(); // the runner starts once the slot is recorded assert.equal(runs, 1); gate.resolve("report"); - assert.equal(await first.promise, "report"); - assert.equal(await second.promise, "report"); + assert.equal(await first, "report"); + assert.equal(await second, "report"); assert.equal(flights.size, 0, "the slot is released once the run settles"); }); @@ -32,8 +31,8 @@ test("a settled run is not reused", async () => { let runs = 0; const run = async () => ++runs; - assert.equal(await runSingleFlight(flights, "k", run).promise, 1); - assert.equal(await runSingleFlight(flights, "k", run).promise, 2); + assert.equal(await runSingleFlight(flights, "k", run), 1); + assert.equal(await runSingleFlight(flights, "k", run), 2); assert.equal(runs, 2); }); @@ -51,15 +50,14 @@ test("different keys run independently", async () => { runs++; return b.promise; }); - assert.equal(first.shared, false); - assert.equal(second.shared, false); + assert.notEqual(first, second); await Promise.resolve(); // the runners start once their slots are recorded assert.equal(runs, 2); a.resolve("a"); b.resolve("b"); - assert.equal(await first.promise, "a"); - assert.equal(await second.promise, "b"); + assert.equal(await first, "a"); + assert.equal(await second, "b"); }); test("a failed run releases the slot and the next call retries", async () => { @@ -73,14 +71,14 @@ test("a failed run releases the slot and the next call retries", async () => { return gate.promise; }); gate.reject(failure); - await assert.rejects(first.promise, /scan failed/); + await assert.rejects(first, /scan failed/); assert.equal(flights.size, 0); const retry = runSingleFlight(flights, "k", async () => { runs++; return "ok"; }); - assert.equal(await retry.promise, "ok"); + assert.equal(await retry, "ok"); assert.equal(runs, 2); }); @@ -94,16 +92,15 @@ test("a runner that throws synchronously releases the slot instead of poisoning throw failure; }); assert.equal(flights.size, 1, "the slot is held before the runner executes"); - assert.equal(first.shared, false); - await assert.rejects(first.promise, /sync failure/); + await assert.rejects(first, /sync failure/); assert.equal(flights.size, 0, "the failed flight must not stay cached"); const retry = runSingleFlight(flights, "k", async () => { runs++; return "ok"; }); - assert.equal(retry.shared, false, "the next caller starts a fresh run"); - assert.equal(await retry.promise, "ok"); + assert.notEqual(retry, first, "the next caller starts a fresh run"); + assert.equal(await retry, "ok"); assert.equal(runs, 2); }); @@ -114,6 +111,6 @@ test("a settling run deletes only its own entry", async () => { const replacement = Promise.resolve("replacement"); flights.set("k", replacement); gate.resolve("first"); - assert.equal(await first.promise, "first"); + assert.equal(await first, "first"); assert.equal(flights.get("k"), replacement, "a successor's slot survives the earlier run settling"); }); diff --git a/lib/single-flight.ts b/lib/single-flight.ts index 539aa076b..7040c5ac2 100644 --- a/lib/single-flight.ts +++ b/lib/single-flight.ts @@ -2,18 +2,14 @@ * Coalesce concurrent work for one key: callers that arrive while a run is in * flight share its promise instead of starting a second run (the usage report * scan is expensive and must not be started once per request). - * - * `shared` tells a caller whether it joined an existing run, which is what the - * usage route uses to decide between "computed for this request" and "served - * from cache while this refresh finishes". */ export function runSingleFlight( flights: Map>, key: string, run: () => Promise, -): { promise: Promise; shared: boolean } { +): Promise { const existing = flights.get(key); - if (existing) return { promise: existing, shared: true }; + if (existing) return existing; // The run starts in a microtask so the map holds the promise BEFORE any user // code can throw: a synchronous throw must still release the slot instead of @@ -25,5 +21,5 @@ export function runSingleFlight( if (flights.get(key) === promise) flights.delete(key); }); flights.set(key, promise); - return { promise, shared: false }; + return promise; } diff --git a/lib/usage-db.test.mjs b/lib/usage-db.test.mjs index 5853de548..cac376712 100644 --- a/lib/usage-db.test.mjs +++ b/lib/usage-db.test.mjs @@ -343,3 +343,56 @@ test("files last synced by another omp-web build are re-parsed; files synced by assert.equal(syncSessionFilesToDb([file], { providers: {} }, db).filesUpdated, 0); }); }); + +test("a forced refresh drops and re-syncs inside one transaction", async () => { + const { syncSessionFilesToDb } = await loadSubject(); + + await withTempDbDir(async (dir, db) => { + const file = writeSession(dir, "a.jsonl", 100); + syncSessionFilesToDb([file], { providers: {} }, db); + assert.equal(inputTokens(db), 100); + + // A refresh re-reads the unchanged file: with the drop inside the same + // transaction, the row is deleted and re-inserted, never merely deleted. + const refreshed = syncSessionFilesToDb([file], { providers: {} }, db, true); + assert.equal(refreshed.filesUpdated, 1, "a forced refresh re-parses even unchanged files"); + assert.equal(inputTokens(db), 100); + assert.equal(db.prepare("SELECT COUNT(*) AS c FROM usage_records;").get().c, 1); + }); +}); + +test("a refresh killed before its commit leaves the previous rows intact", async () => { + const { syncSessionFilesToDb } = await loadSubject(); + + await withTempDbDir(async (dir, db) => { + const good = writeSession(dir, "good.jsonl", 100); + syncSessionFilesToDb([good], { providers: {} }, db); + assert.equal(inputTokens(db), 100); + + // Model the worker being killed right before it commits: the drop has run, + // the re-sync has run, and the COMMIT throws. Before the fix the DELETE ran + // in autocommit mode *outside* this transaction, so it survived the failure + // and the database stayed empty — which the next request cached as a valid + // zero-usage report. + const dying = new Proxy(db, { + get(target, property, receiver) { + if (property === "exec") { + return (sql) => { + if (/^COMMIT/i.test(sql.trim())) throw new Error("killed before commit"); + return target.exec(sql); + }; + } + const value = Reflect.get(target, property, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + + assert.throws(() => syncSessionFilesToDb([good], { providers: {} }, dying, true), /killed before commit/); + + // The refresh rolled back: the previous rows are still there and still + // counted, so the next request cannot cache a zero-usage report. + assert.equal(inputTokens(db), 100, "the failed refresh must not have emptied the database"); + assert.equal(db.prepare("SELECT COUNT(*) AS c FROM usage_records;").get().c, 1); + assert.equal(db.prepare("SELECT COUNT(*) AS c FROM synced_files;").get().c, 1); + }); +}); diff --git a/lib/usage-db.ts b/lib/usage-db.ts index 38363c5af..2ea9cc70c 100644 --- a/lib/usage-db.ts +++ b/lib/usage-db.ts @@ -189,11 +189,19 @@ export interface SyncStats { * sub-sessions — each bills its own model usage), into the usage database. * Artifact transcripts are attributed to the session they belong to. Only * files that are new, changed, or last synced by other parsing rules are parsed. + * + * `forceRefresh` drops every stored row first and re-syncs the whole corpus. + * The drop happens **inside this function's transaction**, not before it: a + * caller that deleted the rows outside could be killed (the worker's deadline) + * or fail midway and leave an empty database behind, which the next request + * would then cache as a valid zero-usage report. Here a failed or killed + * refresh rolls back and the previous rows survive untouched. */ export function syncSessionFilesToDb( sessionFiles: string[], customModelsConfig: ModelsFileConfig = readModelsConfig(), customDb?: Database, + forceRefresh = false, ): SyncStats { const db = customDb || getUsageDatabase(); const now = Date.now(); @@ -250,6 +258,16 @@ export function syncSessionFilesToDb( }; try { + // 1. A forced refresh starts from an empty database. This runs inside the + // transaction below (opened here, before the first DELETE), so a refresh + // that fails or is killed rolls back to the rows it started with instead + // of leaving the database empty for the next reader to cache. + if (forceRefresh) { + ensureTransaction(); + db.exec("DELETE FROM synced_files; DELETE FROM usage_records;"); + syncedMap.clear(); + } + // 2. Incremental sync for new / modified files for (const { filePath, sessionFile } of transcripts) { let stats; @@ -392,19 +410,15 @@ export async function getUsageReportFromDb( const projectFilter = options.project ? options.project.trim().toLowerCase() : undefined; const db = customDb || getUsageDatabase(); - if (options.forceRefresh) { - try { - db.exec("DELETE FROM synced_files; DELETE FROM usage_records;"); - } catch { - // Ignore - } - } // Sync latest sessions (and the helper transcripts in their artifacts - // directories) from disk before querying + // directories) from disk before querying. A forced refresh drops and + // re-syncs inside the sync's own transaction: deleting the rows here would + // leave an empty database behind if the scan were killed or failed, and the + // next request would cache that as a valid zero-usage report. const sessionsDir = getSessionsDir(); const sessionFiles = existsSync(sessionsDir) ? await listSessionFiles(sessionsDir) : []; - syncSessionFilesToDb(sessionFiles, readModelsConfig(), db); + syncSessionFilesToDb(sessionFiles, readModelsConfig(), db, options.forceRefresh === true); collectUncountedUsage(db); const hasExplicitBounds = typeof options.from === "number" && diff --git a/lib/usage-nonblocking.test.mjs b/lib/usage-nonblocking.test.mjs index e962b8891..ac4ad23d3 100644 --- a/lib/usage-nonblocking.test.mjs +++ b/lib/usage-nonblocking.test.mjs @@ -7,7 +7,6 @@ import test from "node:test"; import { getUsageReport, invalidateUsageCache, - invalidateUsageReportCache, USAGE_REPORT_REFRESH_MS, USAGE_STALE_MAX_AGE_MS, } from "./usage-service.ts"; @@ -25,13 +24,11 @@ async function withTempUsageDir(run) { const previousAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = dir; invalidateUsageCache(); - invalidateUsageReportCache(); try { await run(dir); } finally { closeUsageDatabase(); invalidateUsageCache(); - invalidateUsageReportCache(); if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousAgentDir; rmSync(dir, { recursive: true, force: true }); diff --git a/lib/usage-report-worker.test.mjs b/lib/usage-report-worker.test.mjs index f40d8649a..d2c7e984d 100644 --- a/lib/usage-report-worker.test.mjs +++ b/lib/usage-report-worker.test.mjs @@ -5,7 +5,7 @@ import { join } from "node:path"; import test from "node:test"; import { runUsageReportInWorker, UsageWorkerError, UsageWorkerTimeoutError, UsageWorkerBusyError, getUsageWorkerPath, resolveUsageWorkerPath } from "./usage-report-worker.ts"; import { getUsageReportFromDb, getUsageDatabase, closeUsageDatabase } from "./usage-db.ts"; -import { invalidateUsageCache, invalidateUsageReportCache } from "./usage-service.ts"; +import { invalidateUsageCache } from "./usage-service.ts"; /** * Throwaway agent dir: the usage database and the session tree both live here, @@ -17,13 +17,11 @@ async function withTempAgentDir(run) { const previousAgentDir = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = dir; invalidateUsageCache(); - invalidateUsageReportCache(); try { await run(dir); } finally { closeUsageDatabase(); invalidateUsageCache(); - invalidateUsageReportCache(); if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousAgentDir; rmSync(dir, { recursive: true, force: true }); diff --git a/lib/usage-route.test.mjs b/lib/usage-route.test.mjs index 718fb7135..b554e18ff 100644 --- a/lib/usage-route.test.mjs +++ b/lib/usage-route.test.mjs @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import * as route from "../app/api/usage/route.ts"; -import { invalidateUsageReportCache } from "../lib/usage-service.ts"; +import { invalidateUsageCache } from "../lib/usage-service.ts"; const MAX_WINDOW_MS = 400 * 24 * 60 * 60 * 1000; @@ -24,7 +24,7 @@ async function withWorker(source, run) { } finally { if (previous === undefined) delete process.env.OMP_WEB_USAGE_WORKER; else process.env.OMP_WEB_USAGE_WORKER = previous; - invalidateUsageReportCache(); + invalidateUsageCache(); rmSync(dir, { recursive: true, force: true }); } } @@ -33,13 +33,13 @@ async function withTempAgentDir(run) { const dir = mkdtempSync(join(tmpdir(), "omp-usage-route-")); const previous = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = dir; - invalidateUsageReportCache(); + invalidateUsageCache(); try { return await run(dir); } finally { if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previous; - invalidateUsageReportCache(); + invalidateUsageCache(); rmSync(dir, { recursive: true, force: true }); } } @@ -56,7 +56,14 @@ test("usage rejects non-numeric, backwards and over-wide windows with a stable c "from=-1", "from=100&to=50", `from=0&to=${MAX_WINDOW_MS + 1000}`, + // A lone bound used to be accepted, ignored by the report (which applies a + // window only when both ends are present) and keyed separately, so it + // answered the plain 30-day report under its own cache key and paid for a + // full transcript scan. Both directions are rejected now. `from=${Date.now() - MAX_WINDOW_MS - 1000}`, + `from=${Date.now() - 1000}`, + `to=${Date.now() - 1000}`, + `to=${Date.now() - MAX_WINDOW_MS - 1000}`, ]; for (const query of cases) { const response = await call(query); diff --git a/lib/usage-service.ts b/lib/usage-service.ts index 661b795e1..81cb01e75 100644 --- a/lib/usage-service.ts +++ b/lib/usage-service.ts @@ -79,12 +79,22 @@ function setUsageCacheEntry(filePath: string, entry: SessionUsageCacheEntry): vo } } -/** Clear in-memory usage cache (useful on session mutation or manual refresh). */ -export function invalidateUsageCache(): void { +/** Clear the per-file parse cache: a rescan must re-read the transcripts. */ +function invalidateSessionUsageCache(): void { globalThis.__ompUsageCache?.clear(); usageCacheApproxBytes = 0; } +/** + * Clear everything cached about usage: the per-file parses and every computed + * report. The reset for tests, and for any caller that knows the database was + * rebuilt underneath it. + */ +export function invalidateUsageCache(): void { + invalidateSessionUsageCache(); + globalThis.__ompUsageReportCache?.clear(); +} + /** * Format a Date object to "YYYY-MM-DD" in local time. */ @@ -443,8 +453,10 @@ export async function getUsageReport(options: UsageQueryOptions = {}): Promise refreshUsageReport(key, options, agentDir)).promise; + return runSingleFlight(flights, key, () => refreshUsageReport(key, options, agentDir)); } const cached = getUsageReportCache().get(key); @@ -462,7 +474,7 @@ export async function getUsageReport(options: UsageQueryOptions = {}): Promise refreshUsageReport(key, options, agentDir)); + const promise = runSingleFlight(getUsageReportFlights(), key, () => refreshUsageReport(key, options, agentDir)); if (age >= USAGE_STALE_MAX_AGE_MS) return promise; promise.catch(() => { // A failed background rescan keeps the cached report; the next request retries. @@ -470,7 +482,7 @@ export async function getUsageReport(options: UsageQueryOptions = {}): Promise refreshUsageReport(key, options, agentDir)); + const promise = runSingleFlight(getUsageReportFlights(), key, () => refreshUsageReport(key, options, agentDir)); return promise; } @@ -533,8 +545,3 @@ async function refreshUsageReport( } return { ...report, stale: false }; } - -/** Drop every cached report (new scan rules, tests). */ -export function invalidateUsageReportCache(): void { - globalThis.__ompUsageReportCache?.clear(); -} From 93569322d1f28a6d171826ed67e6bfea137fa1c4 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:50:16 +0100 Subject: [PATCH 5/7] fix(usage): let OMP_WEB_USAGE_WORKER override the packaged worker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README row this branch adds advertised the variable as "overriding the one shipped with ompweb", but the resolver returned the packaged worker before it ever read the override — and both launch paths set OMP_WEB_PACKAGE_DIR, so the override was dead in exactly the layouts a release user runs: the npm launcher answered /lib/usage-worker.ts, the compiled binary answered /lib/usage-worker.mjs, and only a bare source run without a package dir ever reached the variable. The override now wins in every layout. It is still an absolute path only: a relative value would resolve against whatever cwd the launcher happened to have, which is the "another project's file runs with our env" case the resolver exists to rule out, so it stays ignored with a warning and the packaged worker answers as if it were unset. The new test pins all three layouts (release bundle, checkout TypeScript worker, binary's own directory) plus a missing override and the relative case; mutation: moving the packageDir branch back above the override fails "the override must beat the packaged bundle". The README row now states the precedence and names the default worker per layout instead of claiming a bundle that a checkout does not have. --- README.md | 2 +- lib/usage-report-worker.test.mjs | 52 ++++++++++++++++++++++++++++++++ lib/usage-report-worker.ts | 13 +++++--- 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 23161a56e..031110d0f 100644 --- a/README.md +++ b/README.md @@ -1049,7 +1049,7 @@ Stop it with `Stop-ScheduledTask ompweb-host`, then end the running host with | `OMP_WEB_STT_ENDPOINT` | OpenAI-compatible transcription endpoint URL. Leave unset to transcribe with `OMP_WEB_STT_MODEL` through omp's own credentials | _None_ | | `OMP_WEB_STT_KEY` | Optional API key for the STT endpoint | _None_ | | `OMP_WEB_STT_MODEL` | Model name for the STT endpoint. Without an endpoint: an omp speech-to-text model run with omp's logins, such as `openai-codex/codex-transcribe` (ChatGPT subscription; needs an omp version with that model) | _None (disabled without an endpoint)_ | -| `OMP_WEB_USAGE_WORKER` | Absolute path to the module that computes a usage report, overriding the one shipped with ompweb. Relative values are ignored with a warning: the worker runs with the server's provider credentials | _the packaged `lib/usage-worker.mjs`_ | +| `OMP_WEB_USAGE_WORKER` | Absolute path to the module that computes a usage report. It wins over the worker shipped with ompweb in every layout, including a release or compiled binary. Relative values are ignored with a warning: the worker runs with the server's provider credentials | _the worker shipped in `lib/`_ (`usage-worker.mjs` in a release, `usage-worker.ts` in a checkout) | | `OMP_WEB_USAGE_TIMEOUT_MS` | How long a usage scan may run before it is killed and `GET /api/usage` answers `504 usage_timeout`. Raise it on a very large transcript tree | `600000` (10 minutes) | **`OMP_WEB_NAME` and installed apps.** An installed app (PWA) is usually named after the page it was installed from. If you later change `OMP_WEB_NAME`, or reach omp-web through a different address while `OMP_WEB_NAME` is `url`, `host` or `domain`, your operating system may rename the installed app as well. Leave `OMP_WEB_NAME` empty, or set a name that identifies this omp-web server whatever domain name or address is used to reach it. diff --git a/lib/usage-report-worker.test.mjs b/lib/usage-report-worker.test.mjs index d2c7e984d..e02695a7c 100644 --- a/lib/usage-report-worker.test.mjs +++ b/lib/usage-report-worker.test.mjs @@ -473,3 +473,55 @@ test("a release package dir wins, and a relative override is refused, in the res bundled, ); }); + +test("an absolute OMP_WEB_USAGE_WORKER wins over the packaged worker in every layout", (t) => { + // The two layouts a packaged server really runs in: a release directory with + // the bundled worker, and a checkout with the TypeScript one. + const release = mkdtempSync(join(tmpdir(), "omp-usage-override-release-")); + mkdirSync(join(release, "lib"), { recursive: true }); + const bundled = join(release, "lib", "usage-worker.mjs"); + writeFileSync(bundled, "// bundled worker\n"); + const checkout = mkdtempSync(join(tmpdir(), "omp-usage-override-checkout-")); + mkdirSync(join(checkout, "lib"), { recursive: true }); + const source = join(checkout, "lib", "usage-worker.ts"); + writeFileSync(source, "// source worker\n"); + const custom = join(release, "custom-worker.mjs"); + writeFileSync(custom, "// custom worker\n"); + t.after(() => { + rmSync(release, { recursive: true, force: true }); + rmSync(checkout, { recursive: true, force: true }); + }); + + // The compiled binary sets OMP_WEB_PACKAGE_DIR to a directory holding the + // bundle; the npm launcher sets it to the checkout with the TypeScript + // worker. The override is documented as the escape hatch for both, and a + // packaged worker that won there made the variable dead exactly where a + // release user reaches for it. + assert.equal( + resolveUsageWorkerPath({ packageDir: release, override: custom, moduleDir: release, execDir: release }), + custom, + "the override must beat the packaged bundle", + ); + assert.equal( + resolveUsageWorkerPath({ packageDir: checkout, override: custom, moduleDir: checkout, execDir: checkout }), + custom, + "the override must beat the packaged TypeScript worker", + ); + assert.equal( + resolveUsageWorkerPath({ packageDir: release, override: custom, moduleDir: "B:\\~BUN\\root\\", execDir: release }), + custom, + "the override must beat the binary's own bundle", + ); + + // An override that does not exist is still the answer: the resolver reports + // the path the worker error names instead of silently falling back. + const missing = join(release, "not-there.mjs"); + assert.equal(resolveUsageWorkerPath({ packageDir: release, override: missing, moduleDir: release, execDir: release }), missing); + + // A relative value is not an override at all: it is ignored, and the + // packaged worker answers as if the variable were unset. + assert.equal( + resolveUsageWorkerPath({ packageDir: release, override: "custom-worker.mjs", moduleDir: release, execDir: release }), + bundled, + ); +}); diff --git a/lib/usage-report-worker.ts b/lib/usage-report-worker.ts index de1760ee1..20c92b03f 100644 --- a/lib/usage-report-worker.ts +++ b/lib/usage-report-worker.ts @@ -67,6 +67,11 @@ export function getUsageWorkerPath(): string { /** * The decision {@link getUsageWorkerPath} makes, with every input passed in so * a test can exercise the release layout without building a binary. + * + * `OMP_WEB_USAGE_WORKER` wins over the packaged worker, in every layout: it is + * the documented escape hatch for running a different report module, and a + * packaged worker that silently overrode it made the variable dead exactly + * where a release user would reach for it. */ export function resolveUsageWorkerPath(input: { packageDir?: string; @@ -74,10 +79,6 @@ export function resolveUsageWorkerPath(input: { moduleDir: string; execDir: string; }): string { - if (input.packageDir) { - const fromPackage = packagedWorker(input.packageDir); - if (fromPackage) return fromPackage; - } if (input.override) { // An absolute path only: a relative value would be resolved against // whatever cwd the launcher happened to have, which is exactly the @@ -86,6 +87,10 @@ export function resolveUsageWorkerPath(input: { if (isAbsolute(input.override)) return resolve(input.override); console.warn(`[usage] ignoring relative OMP_WEB_USAGE_WORKER=${input.override}`); } + if (input.packageDir) { + const fromPackage = packagedWorker(input.packageDir); + if (fromPackage) return fromPackage; + } if (/(^|[\\/])(~BUN|\$bunfs)([\\/]|$)/i.test(input.moduleDir)) { // OMP_WEB_PACKAGE_DIR pointed somewhere incomplete; the executable's own // directory is still a real directory on disk. From 9c8392fdce3268a779a2d6fffb857b98788eec1b Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:18:14 +0100 Subject: [PATCH 6/7] docs(usage): describe the worker override rule the resolver enforces --- lib/usage-report-worker.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/lib/usage-report-worker.ts b/lib/usage-report-worker.ts index 20c92b03f..59af9ca6f 100644 --- a/lib/usage-report-worker.ts +++ b/lib/usage-report-worker.ts @@ -40,13 +40,14 @@ function packagedWorker(dir: string): string | undefined { * otherwise execute that project's `lib/usage-worker.ts` inside a worker with * full server privileges. * - * Both overrides are pinned to absolute paths inside the package directory: - * the worker runs with the server's provider credentials, so a relative value - * (resolved against whatever cwd the launcher had) or a directory another - * process can write is not an acceptable code source. `OMP_WEB_PACKAGE_DIR` - * is set by the launcher and by the compiled binary (to its own directory); - * the module-relative path is the normal case for a source run, since the - * server then lives in this package's `lib/`. + * Both overrides are honoured only as absolute paths: the worker runs with the + * server's provider credentials, so a relative value (resolved against + * whatever cwd the launcher had) is ignored with a warning. An absolute + * `OMP_WEB_USAGE_WORKER` is the operator's explicit choice and wins over the + * packaged worker. `OMP_WEB_PACKAGE_DIR` is set by the launcher and by the + * compiled binary (to its own directory); the module-relative path is the + * normal case for a source run, since the server then lives in this + * package's `lib/`. * * A compiled binary's own modules sit in Bun's embedded filesystem * (`B:\~BUN\root\` on Windows, `/$bunfs/root/` elsewhere), where `existsSync` From bbed69c30952b076a03df8570af00aa0d169fdb9 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:03:49 +0100 Subject: [PATCH 7/7] test(usage): drive the range picker through the themed select main replaced UsageConfig's native