Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf: 复用稳定的月用量账本解析结果

Zhehui Bi9b5fe33446be
diff --git a/docs/verification/usage-ledger.md b/docs/verification/usage-ledger.md
index b99a922715..e592e622fd 100644
--- a/docs/verification/usage-ledger.md
+++ b/docs/verification/usage-ledger.md
@@ -121,6 +121,23 @@ directory never failing the turn, range parsing, every grouping, spreadsheet
formula neutralisation in the CSV, the localized person labels, and the admin
scope on both routes.
+## Read performance
+
+```sh
+node --experimental-strip-types scripts/bench-usage-ledger.ts
+```
+
+The benchmark seeds 40,000 synthetic rows in a disposable server and times the
+two Usage group requests together. It reports the first pair, the median of
+nine repeated pairs, server RSS on macOS/Linux, and the first pair after an
+append. Each response must account for every expected row.
+
+The server can reuse parsed rows for up to four settled month files within a
+32 MiB estimated cache budget (file bytes plus an allowance per parsed row).
+Files changed in the last two seconds bypass the cache. That keeps the next
+read fresh after appends or replacements, including during active turn traffic.
+The benchmark's repeated pairs measure a stable ledger.
+
## Gotchas
- Rows are appended when `turn.completed` folds, whether the turn succeeded
diff --git a/scripts/bench-usage-ledger.ts b/scripts/bench-usage-ledger.ts
new file mode 100644
index 0000000000..c153830890
--- /dev/null
+++ b/scripts/bench-usage-ledger.ts
@@ -0,0 +1,59 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { setTimeout } from "node:timers/promises";
+import { launchVerificationServer } from "./control-omb.ts";
+
+const count = Number(process.argv[2] ?? 40_000);
+assert(Number.isSafeInteger(count) && count > 0);
+const fixture = await launchVerificationServer();
+try {
+ const directory = join(fixture.info.dataDir, "usage");
+ await mkdir(directory, { recursive: true });
+ const rows = Array.from({ length: count }, (_, index) => JSON.stringify({
+ at: "2025-09-02T00:00:00.000Z",
+ botId: `fixture-${index % 10}`,
+ botName: `Synthetic bot ${index % 10}`,
+ threadId: "fixture-thread",
+ instanceId: "fixture-engine",
+ driverKind: "claudeAgent",
+ model: `synthetic-model-${index % 3}`,
+ input: 1000,
+ output: 100,
+ costUsd: 0.001,
+ trigger: { kind: "owner" },
+ })).join("\n") + "\n";
+ const file = join(directory, "2025-09.jsonl");
+ await writeFile(file, rows);
+ const groups = ["groupBy=bot&splitBy=model", "groupBy=model"];
+ async function readPair(turns: number) {
+ const started = performance.now();
+ await Promise.all(groups.map(async (group) => {
+ const response = await fetch(`${fixture.info.url}/api/usage?from=2025-09-01&to=2025-09-30&${group}`);
+ assert.equal(response.status, 200);
+ assert.equal((await response.json()).total.turns, turns);
+ }));
+ return performance.now() - started;
+ }
+ await fetch(`${fixture.info.url}/api/usage?from=2025-08-01&to=2025-08-31`).then((response) => response.text());
+ await setTimeout(2_100);
+ const firstPairMs = await readPair(count);
+ const samples = [];
+ for (let attempt = 0; attempt < 9; attempt++) samples.push(await readPair(count));
+ const stableRssKiB = rssKiB();
+ await writeFile(file, rows.slice(0, rows.indexOf("\n") + 1), { flag: "a" });
+ const afterAppendMs = await readPair(count + 1);
+ console.log(JSON.stringify({
+ count, bytes: Buffer.byteLength(rows), firstPairMs,
+ warmPairMedianMs: samples.sort((first, second) => first - second)[4],
+ afterAppendMs, stableRssKiB, afterAppendRssKiB: rssKiB(),
+ }, null, 2));
+
+ function rssKiB() {
+ if (process.platform === "win32") return null;
+ return Number(execFileSync("ps", ["-o", "rss=", "-p", String(fixture.info.pid)], { encoding: "utf8" }).trim());
+ }
+} finally {
+ await fixture.close();
+}
diff --git a/server/usage-ledger.test.ts b/server/usage-ledger.test.ts
index 7f0bd9a1ad..2151d4bc19 100644
--- a/server/usage-ledger.test.ts
+++ b/server/usage-ledger.test.ts
@@ -1,7 +1,7 @@
-import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { removeTempDir } from "./testing/cleanup.ts";
import {
appendUsage,
@@ -87,6 +87,62 @@ describe("usage ledger files", () => {
expect(readUsage(dataDir, { from: new Date("2026-09-04T00:00:00Z"), to: new Date("2026-09-30T23:59:59Z") })).toHaveLength(0);
});
+ it("reuses settled immutable rows but sees appends, rewrites, replacements and deletion", async () => {
+ const at = "2026-09-03T10:00:00.000Z";
+ const range = { from: new Date("2026-09-01"), to: new Date("2026-09-30") };
+ const file = usageFileFor(dataDir, new Date(at));
+ await appendUsage(dataDir, row({ at, botId: "b1" }));
+ const wallClock = Date.now.bind(Date);
+ const clock = vi.spyOn(Date, "now").mockImplementation(() => wallClock() + 3_000);
+ try {
+ const first = readUsage(dataDir, range)[0]!;
+ expect(readUsage(dataDir, range)[0]).toBe(first);
+ expect(Object.isFrozen(first.trigger)).toBe(true);
+
+ clock.mockImplementation(wallClock);
+ void appendUsage(dataDir, row({ at, botId: "b2" }));
+ await flushUsageLedger(dataDir);
+ expect(readUsage(dataDir, range).map((record) => record.botId)).toEqual(["b1", "b2"]);
+
+ clock.mockImplementation(() => wallClock() + 3_000);
+ expect(readUsage(dataDir, range)).toHaveLength(2);
+ clock.mockImplementation(wallClock);
+ writeFileSync(file, readFileSync(file, "utf8").replace('"b1"', '"b3"'));
+ expect(readUsage(dataDir, range).map((record) => record.botId)).toEqual(["b3", "b2"]);
+
+ clock.mockImplementation(() => wallClock() + 3_000);
+ expect(readUsage(dataDir, range)).toHaveLength(2);
+ writeFileSync(file + ".new", JSON.stringify(row({ at, botId: "b4" })));
+ renameSync(file + ".new", file);
+ expect(readUsage(dataDir, range).map((record) => record.botId)).toEqual(["b4"]);
+ unlinkSync(file);
+ expect(readUsage(dataDir, range)).toEqual([]);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
+ it("evicts the least recently read month when the snapshot cache fills", async () => {
+ const ranges = Array.from({ length: 5 }, (_, index) => {
+ const month = String(index + 1).padStart(2, "0");
+ return { from: new Date(`2026-${month}-01`), to: new Date(`2026-${month}-02`) };
+ });
+ for (const { from } of ranges) await appendUsage(dataDir, row({ at: from.toISOString() }));
+ const settled = Date.now() + 60_000;
+ const clock = vi.spyOn(Date, "now").mockReturnValue(settled);
+ try {
+ const firstFour = ranges.slice(0, 4).map((range) => readUsage(dataDir, range)[0]);
+ expect(readUsage(dataDir, ranges[0]!)[0]).toBe(firstFour[0]);
+ readUsage(dataDir, ranges[4]!);
+ expect(readUsage(dataDir, ranges[0]!)[0]).toBe(firstFour[0]);
+ const reread = readUsage(dataDir, ranges[1]!)[0];
+ expect(reread).toEqual(firstFour[1]);
+ expect(reread).not.toBe(firstFour[1]);
+ } finally {
+ clock.mockRestore();
+ }
+ });
+
it("keeps a full disk or a missing directory from failing the turn", async () => {
appendUsage(join(dataDir, "missing-file-as-dir"), row());
writeFileSync(join(dataDir, "blocked"), "not a directory");
diff --git a/server/usage-ledger.ts b/server/usage-ledger.ts
index 6d83b24d8b..7a154c5803 100644
--- a/server/usage-ledger.ts
+++ b/server/usage-ledger.ts
@@ -1,6 +1,6 @@
// Append-only usage rows under <data>/usage/ (0600): bookkeeping never fails the turn, and rows never carry message text.
import { personOf } from "./usage-attribution.ts";
-import { readFileSync } from "node:fs";
+import { readFileSync, statSync } from "node:fs";
import { appendFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import type { TraceParent, TraceStatus, TraceUsageStatus } from "../shared/usage-trace.ts";
@@ -172,31 +172,91 @@ export function monthsBetween(from: Date, to: Date): string[] {
return keys;
}
-export function readUsage(dataDir: string, range: { from: Date; to: Date }): UsageRow[] {
- const rows: UsageRow[] = [];
- const from = range.from.getTime();
- const to = range.to.getTime();
- for (const key of monthsBetween(range.from, range.to)) {
- let text: string;
+const MAX_CACHED_MONTHS = 4;
+const MAX_SNAPSHOT_WEIGHT = 32 * 1024 * 1024;
+type DatedRow = { at: number; row: Readonly<UsageRow> };
+const monthSnapshots = new Map<string, { stamp: string; weight: number; rows: DatedRow[] }>();
+
+function settledMonth(path: string) {
+ try {
+ const file = statSync(path, { bigint: true });
+ if (!file.isFile() || file.size > MAX_SNAPSHOT_WEIGHT) return null;
+ // Coarse file timestamps can miss rewrites within the same tick.
+ if (Date.now() - Math.max(Number(file.mtimeMs), Number(file.ctimeMs)) < 2_000) return null;
+ return { bytes: Number(file.size), stamp: `${file.dev}:${file.ino}:${file.size}:${file.mtimeNs}:${file.ctimeNs}` };
+ } catch {
+ return null;
+ }
+}
+
+function freezeRows(rows: DatedRow[]): void {
+ for (const { row } of rows) {
+ const pending: object[] = [row];
+ while (pending.length > 0) {
+ const value = pending.pop()!;
+ for (const child of Object.values(value)) {
+ if (child && typeof child === "object") pending.push(child);
+ }
+ Object.freeze(value);
+ }
+ }
+}
+
+function readMonth(path: string): DatedRow[] {
+ const before = settledMonth(path);
+ const cached = monthSnapshots.get(path);
+ monthSnapshots.delete(path);
+ if (cached && before?.stamp === cached.stamp) {
+ monthSnapshots.set(path, cached);
+ return cached.rows;
+ }
+
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch {
+ return [];
+ }
+ const rows: DatedRow[] = [];
+ for (const line of text.split("\n")) {
+ if (!line) continue;
try {
- text = readFileSync(join(dataDir, DIR, `${key}.jsonl`), "utf8");
+ const row: unknown = JSON.parse(line);
+ if (!isUsageRow(row)) continue;
+ const at = Date.parse(row.at);
+ if (Number.isFinite(at)) rows.push({ at, row });
} catch {
- continue;
}
- for (const line of text.split("\n")) {
- if (!line) continue;
- try {
- const value: unknown = JSON.parse(line);
- if (!isUsageRow(value)) continue;
- const at = Date.parse(value.at);
- if (at >= from && at <= to) rows.push(value);
- } catch {
+ }
+ if (before && settledMonth(path)?.stamp === before.stamp) {
+ const weight = before.bytes + rows.length * 256;
+ if (weight <= MAX_SNAPSHOT_WEIGHT) {
+ freezeRows(rows);
+ monthSnapshots.set(path, { stamp: before.stamp, weight, rows });
+ let total = 0;
+ for (const entry of monthSnapshots.values()) total += entry.weight;
+ for (const [oldest, entry] of monthSnapshots) {
+ if (monthSnapshots.size <= MAX_CACHED_MONTHS && total <= MAX_SNAPSHOT_WEIGHT) break;
+ monthSnapshots.delete(oldest);
+ total -= entry.weight;
}
}
}
return rows;
}
+export function readUsage(dataDir: string, range: { from: Date; to: Date }): Readonly<UsageRow>[] {
+ const rows: Readonly<UsageRow>[] = [];
+ const from = range.from.getTime();
+ const to = range.to.getTime();
+ for (const key of monthsBetween(range.from, range.to)) {
+ for (const { at, row } of readMonth(join(dataDir, DIR, `${key}.jsonl`))) {
+ if (at >= from && at <= to) rows.push(row);
+ }
+ }
+ return rows;
+}
+
export function parseUsageRange(from: string | null | undefined, to: string | null | undefined, now = new Date()): { from: Date; to: Date } | null {
const day = /^(\d{4})-(\d{2})-(\d{2})$/;
const parse = (value: string, endOfDay: boolean): Date | null => {