Skip to content
TypeScript

fix(usage): retain transcript diagnostics across scans (#21862)

Julius Marminge64be3613011e
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 667a71dd0c3..a4b0a8b30cf 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -19,6 +19,7 @@ import {
type UsageSummaryInput,
} from "@t3tools/contracts";
import * as Duration from "effect/Duration";
+import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -42,6 +43,7 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts";
import * as ProviderHostLive from "../provider/ProviderHostLive.ts";
import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage";
import * as UsageService from "./UsageService.ts";
+import { encodeScanCache } from "./usageScanCache.ts";
const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -1881,6 +1883,51 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
+ it.live("keeps an absent directory missing when its cached files only contain diagnostics", () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ yield* Effect.promise(() =>
+ NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }),
+ );
+ yield* Effect.gen(function* () {
+ const { stateDir } = yield* ServerConfig.ServerConfig;
+ const mtimeMs = yield* Clock.currentTimeMillis;
+ const cache = encodeScanCache(
+ new Map([
+ [
+ transcript,
+ {
+ size: 0,
+ mtimeMs,
+ provider: "claude" as const,
+ records: [],
+ tailRecords: [],
+ malformedRecords: 2,
+ position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
+ },
+ ],
+ ]),
+ );
+ yield* Effect.promise(async () => {
+ await NodeFSP.mkdir(stateDir, { recursive: true });
+ await NodeFSP.writeFile(
+ NodePath.join(stateDir, "usage-scan-cache-v5.json"),
+ encodeUnknownJsonString(cache),
+ );
+ });
+ const summary = yield* (yield* UsageService.make).readSummary(WINDOW);
+ const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
+ assert.strictEqual(source?.status, "missing");
+ assert.strictEqual(source?.scannedFiles, 0);
+ assert.strictEqual(source?.malformedRecords, 2);
+ }).pipe(
+ Effect.provide(
+ layerService({ prefix: "usage-service-missing-diagnostics", home, settings }),
+ ),
+ );
+ }).pipe(Effect.scoped),
+ );
+
it.live("reports saved usage of a removed directory only for windows it reaches", () =>
Effect.gen(function* () {
const { transcript, settings, home } = yield* setup;
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index c27321b5177..b17d5cb3064 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -353,7 +353,7 @@ export const make = Effect.gen(function* () {
([filePath, entry]) =>
entry.provider === provider &&
entry.mtimeMs >= retentionCutoffMs &&
- entry.records.length + entry.tailRecords.length > 0 &&
+ (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) &&
isWithinDirectory(filePath, dir),
);
const volumeId =
@@ -459,6 +459,7 @@ export const make = Effect.gen(function* () {
format: TranscriptUsageFormat<unknown>,
): Effect.fn.Return<{
readonly records: readonly UsageRecord[];
+ readonly malformedRecords: number;
readonly failed?: true;
readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
}> {
@@ -476,6 +477,7 @@ export const make = Effect.gen(function* () {
cached.tailRecords.length === 0
? cached.records
: [...cached.records, ...cached.tailRecords],
+ malformedRecords: cached.malformedRecords,
};
}
@@ -492,6 +494,7 @@ export const make = Effect.gen(function* () {
if (parsed === null)
return {
records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
+ malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0,
failed: true,
};
@@ -502,8 +505,17 @@ export const make = Effect.gen(function* () {
return {
records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
+ malformedRecords: parsed.malformedRecords,
update: {
- entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
+ entry: {
+ size,
+ mtimeMs,
+ provider,
+ records,
+ tailRecords,
+ malformedRecords: parsed.malformedRecords,
+ position: parsed.position,
+ },
replaces: cached,
},
};
@@ -518,7 +530,11 @@ export const make = Effect.gen(function* () {
readonly message?: string;
readonly action?: UsageSource["action"];
readonly files:
- | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
+ | readonly {
+ readonly path: string;
+ readonly records: readonly UsageRecord[];
+ readonly malformedRecords: number;
+ }[]
| null;
readonly refreshing?: true;
}
@@ -543,8 +559,8 @@ export const make = Effect.gen(function* () {
),
{ concurrency: TRANSCRIPT_READ_CONCURRENCY },
);
- const parsedFiles = read.map(({ path, records, update }) => {
- if (update === undefined) return { path, records };
+ const parsedFiles = read.map(({ path, records, malformedRecords, update }) => {
+ if (update === undefined) return { path, records, malformedRecords };
// A scan of another window may have cached its own read of this file
// meanwhile. Then keep whichever read saw the later file, so a slower
// scan never replaces newer usage with older.
@@ -557,7 +573,7 @@ export const make = Effect.gen(function* () {
fileCache.set(path, update.entry);
cacheDirty = true;
}
- return { path, records };
+ return { path, records, malformedRecords };
});
const unread = failedPaths + read.filter((file) => file.failed).length;
return {
@@ -602,6 +618,7 @@ export const make = Effect.gen(function* () {
: Effect.succeed(volumeId),
(resolved): ScannedDir => ({
...source,
+ files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null,
provider: reader.provider,
volumeId: resolved,
}),
@@ -710,7 +727,11 @@ export const make = Effect.gen(function* () {
!isWithinDirectory(filePath, dir)
)
continue;
- retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
+ retainedFiles.push({
+ path: filePath,
+ records: [...entry.records, ...entry.tailRecords],
+ malformedRecords: entry.malformedRecords,
+ });
}
return retainedFiles;
});
@@ -722,11 +743,13 @@ export const make = Effect.gen(function* () {
] of scannedDirs.entries()) {
let scannedFiles = 0;
let skippedFiles = 0;
+ let malformedRecords = 0;
// Distinct per directory. Buckets carry per-cell session counts, but a
// session spans days and models, so clients total this figure instead.
const sessionIds = new Set<string>();
for (const file of filesByDir[index] ?? []) {
+ malformedRecords += file.malformedRecords;
if (file.records.length === 0) {
skippedFiles += 1;
continue;
@@ -758,15 +781,31 @@ export const make = Effect.gen(function* () {
}
}
+ const sourceMessage =
+ message ?? (files === null ? "No transcript directory on this environment." : null);
sources.push({
fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
- status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
+ status:
+ files === null && scannedFiles === 0
+ ? "missing"
+ : malformedRecords > 0
+ ? status === undefined || status === "ok"
+ ? "partial"
+ : status
+ : (status ?? "ok"),
scannedFiles,
skippedFiles,
- malformedRecords: 0,
+ malformedRecords,
distinctSessions: sessionIds.size,
message:
- message ?? (files === null ? "No transcript directory on this environment." : null),
+ malformedRecords > 0
+ ? [
+ sourceMessage,
+ `${malformedRecords} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
+ ]
+ .filter(Boolean)
+ .join(" ")
+ : sourceMessage,
...(action ? { action } : {}),
...(refreshing ? { refreshing } : {}),
});
diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts
index f7edc7f86b4..e58293a02a6 100644
--- a/apps/server/src/usage/usageScanCache.test.ts
+++ b/apps/server/src/usage/usageScanCache.test.ts
@@ -52,6 +52,7 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][])
provider: "claude",
records,
tailRecords: [],
+ malformedRecords: 0,
position: position(),
});
}
@@ -86,6 +87,7 @@ describe("scan cache round trip", () => {
]);
original.set("/grok.jsonl", {
size: 40,
+ malformedRecords: 2,
mtimeMs: 300,
provider: "grok",
records: [
@@ -97,6 +99,7 @@ describe("scan cache round trip", () => {
});
original.set("/codex.jsonl", {
size: 80,
+ malformedRecords: 3,
mtimeMs: 400,
provider: "codex",
records: [
@@ -135,9 +138,35 @@ describe("scan cache round trip", () => {
TEST_FORMAT_MAP,
);
+ expect(restored.size).toBe(4);
expect(restored).toEqual(original);
});
+ it("defaults missing v5 diagnostic counts to zero without losing cached records", () => {
+ const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]);
+ const encoded = encodeScanCache(original);
+ const entry = encoded.files["/gone.jsonl"]!;
+ const legacy = {
+ ...encoded,
+ version: 5,
+ files: {
+ "/gone.jsonl": {
+ s: entry.s,
+ m: entry.m,
+ p: entry.p,
+ r: entry.r,
+ t: entry.t,
+ o: entry.o,
+ gl: entry.gl,
+ gh: entry.gh,
+ cs: entry.cs,
+ },
+ },
+ };
+
+ expect(decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP)).toEqual(original);
+ });
+
it("drops an entry whose persisted parse state is corrupt", () => {
const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
const poisoned = {
@@ -190,12 +219,14 @@ describe("scan cache round trip", () => {
["/a.jsonl", 100, [record()]],
["/b.jsonl", 200, [record({ sessionId: "session-b" })]],
]);
+ cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: 2 });
const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } };
expect(decodeScanCache(JSON.parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache);
cache.set("/b.jsonl", {
...cache.get("/b.jsonl")!,
size: 30,
+ malformedRecords: 4,
records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })],
});
const document = JSON.parse(write(cache, { sources }));
diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts
index 43b3a548a51..5d9df36a1d9 100644
--- a/apps/server/src/usage/usageScanCache.ts
+++ b/apps/server/src/usage/usageScanCache.ts
@@ -33,6 +33,8 @@ export interface CachedFile {
* re-reads that segment and would otherwise double count it.
*/
readonly tailRecords: readonly UsageRecord[];
+ /** Whole-file count, including diagnostics from the tentative tail. */
+ readonly malformedRecords: number;
readonly position: TranscriptParsePosition;
}
@@ -59,6 +61,7 @@ interface SerializedFile {
readonly p: UsageProviderKind;
readonly r: readonly SerializedRecord[];
readonly t: readonly SerializedRecord[];
+ readonly mr: number;
readonly o: number;
readonly gl: number;
readonly gh: number;
@@ -115,6 +118,7 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile
p: entry.provider,
r: entry.records.map(serializeRecord),
t: entry.tailRecords.map(serializeRecord),
+ mr: entry.malformedRecords,
o: entry.position.resumeOffset,
gl: entry.position.guardLength,
gh: entry.position.guardHash,
@@ -271,6 +275,8 @@ export function decodeScanCache(
const format = formats.get(entry.p);
if (format === undefined) continue;
if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
+ const malformedRecords = entry.mr === undefined ? 0 : entry.mr;
+ if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue;
// Position fields feed byte offsets and a Buffer allocation in the reader,
// so anything outside their real ranges must reject the entry: a bogus
// guard length would otherwise fail every parse of the file, silently
@@ -309,6 +315,7 @@ export function decodeScanCache(
provider,
records,
tailRecords,
+ malformedRecords,
position: legacy
? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
: {
diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts
index 3cd49d1cd1c..79014bfc222 100644
--- a/apps/server/src/usage/usageTranscriptReader.test.ts
+++ b/apps/server/src/usage/usageTranscriptReader.test.ts
@@ -6,6 +6,8 @@ import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";
+import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage";
+import * as Schema from "effect/Schema";
import { TEST_FORMATS } from "./usageTestFormats.ts";
import { readTranscriptRecords, transcriptLineGate } from "./usageTranscriptReader.ts";
@@ -70,6 +72,71 @@ function codexUsageLine(outputTokens: number, secondsOffset: number): string {
}
describe("readTranscriptRecords resume", () => {
+ it.each([
+ { mode: "buffered", streamingThresholdBytes: Infinity },
+ { mode: "streaming", streamingThresholdBytes: 0 },
+ ])("counts malformed tails once across $mode reads and resume", async (options) => {
+ const format: TranscriptUsageFormat<{ errors: number }> = {
+ ...TEST_FORMATS.claude,
+ selectFields: { ...TEST_FORMATS.claude.selectFields, usage: true },
+ state: {
+ initial: () => ({ errors: 0 }),
+ schema: Schema.Struct({ errors: Schema.Number }),
+ },
+ parseLine(line, state) {
+ return this.parseProjected(JSON.parse(line), state);
+ },
+ parseProjected(value, state) {
+ if (
+ typeof value === "object" &&
+ value !== null &&
+ "usage" in value &&
+ value.usage === "malformed"
+ ) {
+ state.errors += 1;
+ return [];
+ }
+ return TEST_FORMATS.claude.parseProjected(value, undefined);
+ },
+ readMalformedRecords: (state: { errors: number }) => state.errors,
+ };
+ const path = NodePath.join(dir, "diagnostics.jsonl");
+ const malformed = JSON.stringify({ usage: "malformed" });
+ // Completed lines enter the projected parser only when they cross a stream chunk.
+ const committed = `${JSON.stringify({ usage: "malformed", padding: "x".repeat(256 * 1024) })}\n${claudeLine(1, 5)}`;
+ await NodeFSP.writeFile(path, committed + malformed);
+
+ const first = await readTranscriptRecords(path, format, undefined, options);
+ assert.isNotNull(first);
+ assert.deepStrictEqual(
+ first.records.map((record) => record.totals.outputTokens),
+ [5],
+ );
+ assert.deepStrictEqual(first.tailRecords, []);
+ assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed));
+ assert.deepStrictEqual(first.position.state, { errors: 1 });
+ assert.strictEqual(first.malformedRecords, 2);
+
+ const savedPosition = JSON.parse(JSON.stringify(first.position));
+ await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`);
+ const resumed = await readTranscriptRecords(path, format, savedPosition, options);
+ assert.isNotNull(resumed);
+ assert.isTrue(resumed.resumed);
+ assert.deepStrictEqual(
+ resumed.records.map((record) => record.totals.outputTokens),
+ [7],
+ );
+ assert.deepStrictEqual(resumed.position.state, { errors: 3 });
+ assert.strictEqual(resumed.malformedRecords, 3);
+
+ const full = await readTranscriptRecords(path, format, undefined, options);
+ assert.isNotNull(full);
+ assert.deepStrictEqual([...first.records, ...resumed.records], full.records);
+ assert.deepStrictEqual(resumed.tailRecords, full.tailRecords);
+ assert.deepStrictEqual(resumed.position, full.position);
+ assert.strictEqual(resumed.malformedRecords, full.malformedRecords);
+ });
+
it("parses only appended lines when resuming a grown file", async () => {
const path = NodePath.join(dir, "claude.jsonl");
await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
@@ -77,6 +144,7 @@ describe("readTranscriptRecords resume", () => {
assert.isNotNull(first);
assert.strictEqual(first.records.length, 2);
assert.isFalse(first.resumed);
+ assert.strictEqual(first.malformedRecords, 0);
await NodeFSP.appendFile(path, claudeLine(3, 11));
const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts
index d3f19afd20a..1131b95bc7e 100644
--- a/apps/server/src/usage/usageTranscriptReader.ts
+++ b/apps/server/src/usage/usageTranscriptReader.ts
@@ -45,6 +45,8 @@ export interface TranscriptParseResult {
* segment: the next scan re-reads it once the writer finishes the line.
*/
readonly tailRecords: readonly UsageRecord[];
+ /** Includes tentative tail diagnostics; position.state only includes committed lines. */
+ readonly malformedRecords: number;
readonly position: TranscriptParsePosition;
readonly resumed: boolean;
}
@@ -306,10 +308,9 @@ export async function readTranscriptRecords<State>(
// `resumeOffset` and the next scan replays the tail from it.
const encodedState = encodeState === undefined ? null : encodeState(state);
const tailRecords: UsageRecord[] = [];
- finish(
- decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)),
- tailRecords,
- );
+ const tailState =
+ decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState));
+ finish(tailState, tailRecords);
const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
let guardHash = 0;
@@ -322,6 +323,7 @@ export async function readTranscriptRecords<State>(
return {
records,
tailRecords,
+ malformedRecords: format.readMalformedRecords?.(tailState) ?? 0,
position: {
resumeOffset,
guardLength,
diff --git a/packages/provider-core/src/server/usage.ts b/packages/provider-core/src/server/usage.ts
index 68cd6571307..89c627e5fa1 100644
--- a/packages/provider-core/src/server/usage.ts
+++ b/packages/provider-core/src/server/usage.ts
@@ -62,6 +62,8 @@ export interface TranscriptUsageFormat<State> {
readonly usageMarkers: readonly [string, ...string[]];
parseLine(line: string, state: State): readonly UsageRecord[];
parseProjected(projected: unknown, state: State): readonly UsageRecord[];
+ /** Cumulative malformed or inconsistent usage records, including skipped records. */
+ readMalformedRecords?(state: State): number;
/**
* Present for formats whose records depend on earlier lines. The state at a
* resume point is persisted in the scan cache through `schema`, so a grown