Skip to content

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

fix: 限制超限用量账本查询的内存占用

Zhehui Bi727c4fa4398a
diff --git a/server/usage-ledger.test.ts b/server/usage-ledger.test.ts
index 2151d4bc19..5e4572d2b9 100644
--- a/server/usage-ledger.test.ts
+++ b/server/usage-ledger.test.ts
@@ -1,4 +1,5 @@
-import { existsSync, mkdtempSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+import { appendFileSync, existsSync, mkdirSync, 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, vi } from "vitest";
@@ -143,6 +144,24 @@ describe("usage ledger files", () => {
}
});
+ 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.ts
index 7a154c5803..6eec636da2 100644
--- a/server/usage-ledger.ts
+++ b/server/usage-ledger.ts
@@ -202,47 +202,54 @@ function freezeRows(rows: DatedRow[]): void {
}
}
-function readMonth(path: string): DatedRow[] {
+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);
- return cached.rows;
+ 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 [];
+ return;
}
- const rows: DatedRow[] = [];
+ 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;
try {
- const row: unknown = JSON.parse(line);
- if (!isUsageRow(row)) continue;
- const at = Date.parse(row.at);
- if (Number.isFinite(at)) rows.push({ at, row });
+ row = JSON.parse(line);
} catch {
+ continue;
}
- }
- 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;
- }
+ 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 });
}
}
- return rows;
+ 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>[] {
@@ -250,9 +257,7 @@ export function readUsage(dataDir: string, range: { from: Date; to: Date }): Rea
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);
- }
+ readMonth(join(dataDir, DIR, `${key}.jsonl`), from, to, rows);
}
return rows;
}