Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Leave out the usage-ledger month cache: main now has its own
milind-soniff6b38fbb013
diff --git a/docs/verification/usage-ledger.md b/docs/verification/usage-ledger.mdindex 5af9944d80..0a561c263d 100644--- a/docs/verification/usage-ledger.md+++ b/docs/verification/usage-ledger.md@@ -125,23 +125,6 @@ directory never failing the turn, range parsing, every grouping, spreadsheetformula neutralisation in the CSV, the localized person labels, and the adminscope 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 succeededdiff --git a/scripts/bench-usage-ledger.ts b/scripts/bench-usage-ledger.tsdeleted file mode 100644index c153830890..0000000000--- a/scripts/bench-usage-ledger.ts+++ /dev/null@@ -1,59 +0,0 @@-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.tsindex 5e4572d2b9..7f0bd9a1ad 100644--- a/server/usage-ledger.test.ts+++ b/server/usage-ledger.test.ts@@ -1,8 +1,7 @@-import { execFileSync } from "node:child_process";-import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it } from "vitest";import { removeTempDir } from "./testing/cleanup.ts";import {appendUsage,@@ -88,80 +87,6 @@ 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("reads a narrow date range from an oversized month under a constrained heap", () => {- const at = "2026-09-02T00:00:00Z";- const file = usageFileFor(dataDir, new Date(at));- mkdirSync(join(dataDir, "usage"));- const line = JSON.stringify(row({ at })) + "\n";- const batch = line.repeat(10_000);- for (let batchIndex = 0; batchIndex < 30; batchIndex++) appendFileSync(file, batch);- appendFileSync(file, JSON.stringify(row({ at: "2026-09-30T12:00:00Z", botId: "match" })));- const output = execFileSync(process.execPath, [- "--max-old-space-size=128", "--experimental-strip-types", "--input-type=module", "--eval",- `import { readUsage } from ${JSON.stringify(new URL("./usage-ledger.ts", import.meta.url).href)};- const rows = readUsage(process.argv[1], { from: new Date("2026-09-30"), to: new Date("2026-10-01") });- console.log(JSON.stringify(rows.map((row) => row.botId)));`,- dataDir,- ], { encoding: "utf8", timeout: 15_000 });- expect(JSON.parse(output)).toEqual(["match"]);- });-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.tsindex 3025a8e956..e1bfe89a6b 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, statSync } from "node:fs";+import { readFileSync } 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,93 +172,28 @@ export function monthsBetween(from: Date, to: Date): string[] {return keys;}-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, from: number, to: number, result: Readonly<UsageRow>[]): void {- const before = settledMonth(path);- const cached = monthSnapshots.get(path);- monthSnapshots.delete(path);- if (cached && before?.stamp === cached.stamp) {- monthSnapshots.set(path, cached);- for (const { at, row } of cached.rows) {- if (at >= from && at <= to) result.push(row);- }- return;- }-- let text: string;- try {- text = readFileSync(path, "utf8");- } catch {- return;- }- let snapshot: DatedRow[] | null = before && settledMonth(path)?.stamp === before.stamp ? [] : null;- let weight = before?.bytes ?? 0;- for (const line of text.split("\n")) {- if (!line) continue;- let row: unknown;+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;try {- row = JSON.parse(line);+ text = readFileSync(join(dataDir, DIR, `${key}.jsonl`), "utf8");} catch {continue;}- if (!isUsageRow(row)) continue;- const at = Date.parse(row.at);- if (!Number.isFinite(at)) continue;- if (at >= from && at <= to) result.push(row);- if (snapshot) {- weight += 256;- if (weight > MAX_SNAPSHOT_WEIGHT) snapshot = null;- else snapshot.push({ at, row });+ 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 (!snapshot || !before || settledMonth(path)?.stamp !== before.stamp) return;- freezeRows(snapshot);- monthSnapshots.set(path, { stamp: before.stamp, weight, rows: snapshot });- 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;- }-}--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)) {- readMonth(join(dataDir, DIR, `${key}.jsonl`), from, to, rows);- }return rows;}