Skip to content

Commit af0f0ac

Browse files
t3dotggclaude
andcommitted
fix(usage): carry error causes, harden cache decode, scope sessions to window
UsageReadError gains an optional structured cause so the failure chain survives without stringified defect text leaking into the wire-serialized message. A corrupt scan-cache row now disqualifies its whole file entry, so the file cold re-parses instead of a partial warm hit silently dropping the corrupt rows' usage. Distinct session counts only include records that actually landed in the requested window. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 4633bce commit af0f0ac

6 files changed

Lines changed: 59 additions & 28 deletions

File tree

‎apps/server/src/usage/UsageService.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,10 @@ export const make = Effect.gen(function* () {
204204
(cause) =>
205205
new UsageReadError({
206206
reason: "scanFailed",
207-
detail: `Server settings could not be read: ${String(cause)}`,
207+
// Bounded description only; the chain travels in `cause` so defect
208+
// text never leaks into the wire-serialized message.
209+
detail: "Server settings could not be read.",
210+
cause,
208211
}),
209212
),
210213
);
@@ -347,8 +350,11 @@ export const make = Effect.gen(function* () {
347350
}
348351
scannedFiles += 1;
349352
for (const record of records) {
350-
aggregator.add(record);
351-
if (record.sessionId.length > 0) sessionIds.add(record.sessionId);
353+
// Only sessions that contributed in-window count: the mtime slack
354+
// admits boundary files whose records fall outside the range.
355+
if (aggregator.add(record) && record.sessionId.length > 0) {
356+
sessionIds.add(record.sessionId);
357+
}
352358
}
353359
}
354360

‎apps/server/src/usage/usageAggregation.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,19 @@ describe("UsageAggregator", () => {
107107
expect(result.buckets).toHaveLength(0);
108108
});
109109

110+
it("reports whether a record contributed", () => {
111+
const aggregator = new UsageAggregator({
112+
timeZone: "UTC",
113+
sinceDay: "2026-08-01",
114+
untilDay: "2026-08-31",
115+
rates,
116+
});
117+
118+
expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(true);
119+
expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(false);
120+
expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false);
121+
});
122+
110123
it("separates providers and models into their own buckets", () => {
111124
const result = aggregate([
112125
record(),
280 Bytes
Binary file not shown.

‎apps/server/src/usage/usageScanCache.test.ts‎

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,27 @@ describe("scan cache round trip", () => {
7676
const restored = decodeScanCache(JSON.parse(JSON.stringify(withJunk)));
7777
expect([...restored.keys()]).toEqual(["/good.jsonl"]);
7878
});
79+
80+
it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => {
81+
// Keeping the surviving rows under the original (size, mtime) would read
82+
// as a valid warm hit and the file would never be re-parsed.
83+
const encoded = encodeScanCache(
84+
cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]),
85+
);
86+
const rows = encoded.files["/a.jsonl"]!.r;
87+
const poisoned = {
88+
...encoded,
89+
files: {
90+
"/a.jsonl": {
91+
...encoded.files["/a.jsonl"]!,
92+
r: [rows[0]!, [...rows[1]!.slice(0, 3), "not-a-number", ...rows[1]!.slice(4)]],
93+
},
94+
},
95+
};
96+
97+
const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
98+
expect(restored.has("/a.jsonl")).toBe(false);
99+
});
79100
});
80101

81102
describe("pruneScanCache", () => {
@@ -156,25 +177,6 @@ describe("pruneScanCache with an unwalked root", () => {
156177
});
157178
});
158179

159-
describe("decodeScanCache numeric validation", () => {
160-
it("rejects rows whose token fields are not numbers", () => {
161-
const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
162-
const rows = encoded.files["/a.jsonl"]!.r;
163-
const poisoned = {
164-
...encoded,
165-
files: {
166-
"/a.jsonl": {
167-
...encoded.files["/a.jsonl"]!,
168-
r: [[...rows[0]!.slice(0, 3), "not-a-number", ...rows[0]!.slice(4)]],
169-
},
170-
},
171-
};
172-
173-
const restored = decodeScanCache(JSON.parse(JSON.stringify(poisoned)));
174-
expect(restored.get("/a.jsonl")?.records).toHaveLength(0);
175-
});
176-
});
177-
178180
describe("dedupeWithinFile", () => {
179181
it("keeps the first record per dedupe key", () => {
180182
const kept = dedupeWithinFile([

‎apps/server/src/usage/usageScanCache.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,15 @@ export function decodeScanCache(document: unknown): ScanCache {
132132

133133
const provider: UsageProviderKind = entry.p;
134134
const records: UsageRecord[] = [];
135+
// Any corrupt row disqualifies the whole entry. Keeping the survivors
136+
// under the original (size, mtime) would read as a valid warm hit and the
137+
// file would never be re-parsed, silently losing the dropped rows' usage.
138+
let corrupt = false;
135139
for (const row of entry.r) {
136-
if (!isRecordArray(row) || row.length < 10) continue;
140+
if (!isRecordArray(row) || row.length < 10) {
141+
corrupt = true;
142+
break;
143+
}
137144
const [
138145
timestampMs,
139146
modelIndex,
@@ -148,18 +155,18 @@ export function decodeScanCache(document: unknown): ScanCache {
148155
] = row as SerializedRecord;
149156

150157
const model = typeof modelIndex === "number" ? models[modelIndex] : undefined;
151-
if (typeof timestampMs !== "number" || !Number.isFinite(timestampMs)) continue;
152-
if (model === undefined) continue;
153-
// Token fields must be real numbers: a corrupt row must cost a cold
154-
// re-parse of its file, never flow into the aggregate as NaN or a string.
155158
if (
159+
typeof timestampMs !== "number" ||
160+
!Number.isFinite(timestampMs) ||
161+
model === undefined ||
156162
!Number.isFinite(uncached) ||
157163
!Number.isFinite(cached) ||
158164
!Number.isFinite(cacheCreation) ||
159165
!Number.isFinite(output) ||
160166
!Number.isFinite(reasoning)
161167
) {
162-
continue;
168+
corrupt = true;
169+
break;
163170
}
164171

165172
records.push({
@@ -179,6 +186,7 @@ export function decodeScanCache(document: unknown): ScanCache {
179186
});
180187
}
181188

189+
if (corrupt) continue;
182190
cache.set(path, { size: entry.s, mtimeMs: entry.m, provider, records });
183191
}
184192

‎packages/contracts/src/usage.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,9 @@ export type UsageSummary = typeof UsageSummary.Type;
184184

185185
export class UsageReadError extends Schema.TaggedErrorClass<UsageReadError>()("UsageReadError", {
186186
reason: Schema.Literals(["scanFailed", "invalidWindow"]),
187+
/** Stable, bounded description. The underlying failure travels in `cause`. */
187188
detail: TrimmedNonEmptyString,
189+
cause: Schema.optional(Schema.Defect()),
188190
}) {
189191
override get message(): string {
190192
return `Usage read failed (${this.reason}): ${this.detail}`;

0 commit comments

Comments
 (0)