Skip to content

Commit f4df886

Browse files
committed
fix(infra): keep usage cache strict on read errors
1 parent fb5ea87 commit f4df886

3 files changed

Lines changed: 73 additions & 19 deletions

File tree

‎scripts/proof/session-cost-usage-readline-errors.mts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
// Real behavior proof: session-cost usage readline stream errors are swallowed
2-
// so callers get a truncated but stable result instead of an unhandled rejection.
1+
// Real behavior proof: session log readline errors are swallowed at the
2+
// diagnostic boundary so callers get a truncated but stable result.
33
//
44
// The proof creates a real transcript session directory where the session file
55
// is a directory instead of a file. `fs.createReadStream` on a directory emits
66
// an EISDIR error on the stream. With the fix, `loadSessionLogs` returns an
77
// empty array after the stream closes. Before the fix the unhandled stream error
8-
// rejected the `for await` loop in `readJsonlRecords`.
8+
// rejected `loadSessionLogs`.
99

1010
import fs from "node:fs/promises";
1111
import os from "node:os";
@@ -20,7 +20,7 @@ const sessionsDir = path.join(tmpDir, "agents", "main", "sessions");
2020
await fs.mkdir(sessionsDir, { recursive: true });
2121

2222
// Make the session file a directory. createReadStream on a directory emits
23-
// EISDIR, which exercises the stream error handler in readJsonlRecords.
23+
// EISDIR, which exercises the best-effort error handler in loadSessionLogs.
2424
const sessionFile = path.join(sessionsDir, "proof-session.jsonl");
2525
await fs.mkdir(sessionFile);
2626

@@ -40,7 +40,7 @@ try {
4040
} catch (err) {
4141
const message = err instanceof Error ? err.message : String(err);
4242
console.log(`\nFAIL: loadSessionLogs threw: ${message}`);
43-
console.log("The stream error should have been swallowed by readJsonlRecords.");
43+
console.log("The stream error should have been swallowed by loadSessionLogs.");
4444
process.exitCode = 1;
4545
} finally {
4646
await fs.rm(tmpDir, { recursive: true, force: true });

‎src/infra/session-cost-usage.stream-errors.test.ts‎

Lines changed: 56 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,25 @@
22
// crashing the caller's async iteration.
33
import nodeFs from "node:fs";
44
import fs from "node:fs/promises";
5-
import os from "node:os";
65
import path from "node:path";
76
import { afterEach, describe, expect, it, vi } from "vitest";
8-
import { loadSessionLogs } from "./session-cost-usage.js";
7+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
8+
import { withEnvAsync } from "../test-utils/env.js";
9+
import {
10+
loadCostUsageSummaryFromCache,
11+
loadSessionLogs,
12+
refreshCostUsageCache,
13+
} from "./session-cost-usage.js";
914

10-
describe("session cost usage stream errors", () => {
11-
let tempDir = "";
15+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
1216

13-
afterEach(async () => {
17+
describe("session cost usage stream errors", () => {
18+
afterEach(() => {
1419
vi.restoreAllMocks();
15-
if (tempDir) {
16-
await fs.rm(tempDir, { recursive: true, force: true });
17-
tempDir = "";
18-
}
1920
});
2021

2122
it("does not crash when the transcript stream emits an error mid-read", async () => {
22-
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-cost-stream-"));
23+
const tempDir = tempDirs.make("openclaw-session-cost-stream-");
2324
const sessionsDir = path.join(tempDir, "agents", "main", "sessions");
2425
await fs.mkdir(sessionsDir, { recursive: true });
2526
const sessionFile = path.join(sessionsDir, "sess-stream-error.jsonl");
@@ -50,4 +51,49 @@ describe("session cost usage stream errors", () => {
5051

5152
expect(logs).toEqual([]);
5253
});
54+
55+
it("does not persist a partial durable cache entry after a stream error", async () => {
56+
const tempDir = tempDirs.make("openclaw-session-cost-cache-stream-");
57+
const sessionsDir = path.join(tempDir, "agents", "main", "sessions");
58+
await fs.mkdir(sessionsDir, { recursive: true });
59+
const sessionFile = path.join(sessionsDir, "sess-cache-stream-error.jsonl");
60+
const usageEntry = (timestamp: string, input: number) =>
61+
JSON.stringify({
62+
type: "message",
63+
timestamp,
64+
message: {
65+
role: "assistant",
66+
usage: { input, output: 0, totalTokens: input, cost: { total: input / 1000 } },
67+
},
68+
});
69+
await fs.writeFile(sessionFile, `${usageEntry("2026-07-06T12:00:00.000Z", 10)}\n`, "utf-8");
70+
71+
await withEnvAsync({ OPENCLAW_STATE_DIR: tempDir }, async () => {
72+
await refreshCostUsageCache();
73+
const cachePath = path.join(sessionsDir, ".usage-cost-cache.json");
74+
const cacheBefore = await fs.readFile(cachePath, "utf-8");
75+
76+
await fs.appendFile(sessionFile, `${usageEntry("2026-07-06T12:01:00.000Z", 20)}\n`, "utf-8");
77+
const originalCreateReadStream = nodeFs.createReadStream;
78+
vi.spyOn(nodeFs, "createReadStream").mockImplementationOnce((...args: unknown[]) => {
79+
const stream = originalCreateReadStream.apply(nodeFs, args as never);
80+
process.nextTick(() => {
81+
stream.emit("error", new Error("stream read failed"));
82+
});
83+
return stream;
84+
});
85+
86+
await expect(refreshCostUsageCache()).rejects.toThrow("stream read failed");
87+
expect(await fs.readFile(cachePath, "utf-8")).toBe(cacheBefore);
88+
89+
const summary = await loadCostUsageSummaryFromCache({
90+
startMs: Date.UTC(2026, 6, 6),
91+
endMs: Date.UTC(2026, 6, 7),
92+
requestRefresh: false,
93+
});
94+
expect(summary.totals.totalTokens).toBe(10);
95+
expect(summary.cacheStatus?.status).toBe("partial");
96+
expect(summary.cacheStatus?.pendingFiles).toBe(1);
97+
});
98+
});
5399
});

‎src/infra/session-cost-usage.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1227,15 +1227,23 @@ async function* readJsonlRecords(
12271227
// Ignore malformed lines
12281228
}
12291229
}
1230-
} catch {
1231-
// Mid-stream read errors are swallowed so callers see a truncated but
1232-
// stable iterator, matching the behavior for missing/empty transcript files.
12331230
} finally {
12341231
rl.close();
12351232
fileStream.destroy();
12361233
}
12371234
}
12381235

1236+
async function* readJsonlRecordsBestEffort(
1237+
filePath: string,
1238+
): AsyncGenerator<Record<string, unknown>> {
1239+
try {
1240+
yield* readJsonlRecords(filePath);
1241+
} catch {
1242+
// Diagnostic readers return the records available before a stream failure.
1243+
// Durable cache scans use the strict reader so partial data is never marked fresh.
1244+
}
1245+
}
1246+
12391247
async function scanTranscriptFile(params: {
12401248
filePath: string;
12411249
config?: OpenClawConfig;
@@ -2654,7 +2662,7 @@ export async function loadSessionLogs(params: {
26542662
const retentionLimit = limit * 2;
26552663
const resolveCost = createUsageCostResolver(params.config);
26562664

2657-
for await (const parsed of readJsonlRecords(sessionFile)) {
2665+
for await (const parsed of readJsonlRecordsBestEffort(sessionFile)) {
26582666
try {
26592667
const message = parsed.message as Record<string, unknown> | undefined;
26602668
if (!message) {

0 commit comments

Comments
 (0)