@devries-cameron20 / t3code Mirror · read-only / commits / 64be361301
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

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

Julius Marminge committed Oct 19, 2026 at 21:05 UTC 64be3613011eaf38e9938b26fd9b6586f15c3438
7 files changed +210 -14
apps/server/src/usage/UsageService.test.ts
+47
@@ -19,6 +19,7 @@ import {
19 type UsageSummaryInput,
20 } from "@t3tools/contracts";
21 import * as Duration from "effect/Duration";
22 +import * as Clock from "effect/Clock";
23 import * as Deferred from "effect/Deferred";
24 import * as Effect from "effect/Effect";
25 import * as Exit from "effect/Exit";
@@ -42,6 +43,7 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts";
43 import * as ProviderHostLive from "../provider/ProviderHostLive.ts";
44 import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage";
45 import * as UsageService from "./UsageService.ts";
46 +import { encodeScanCache } from "./usageScanCache.ts";
47
48 const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
49 const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -1881,6 +1883,51 @@ describe("UsageService", () => {
1883 }).pipe(Effect.scoped),
1884 );
1885
1886 + it.live("keeps an absent directory missing when its cached files only contain diagnostics", () =>
1887 + Effect.gen(function* () {
1888 + const { transcript, settings, home } = yield* setup;
1889 + yield* Effect.promise(() =>
1890 + NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }),
1891 + );
1892 + yield* Effect.gen(function* () {
1893 + const { stateDir } = yield* ServerConfig.ServerConfig;
1894 + const mtimeMs = yield* Clock.currentTimeMillis;
1895 + const cache = encodeScanCache(
1896 + new Map([
1897 + [
1898 + transcript,
1899 + {
1900 + size: 0,
1901 + mtimeMs,
1902 + provider: "claude" as const,
1903 + records: [],
1904 + tailRecords: [],
1905 + malformedRecords: 2,
1906 + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
1907 + },
1908 + ],
1909 + ]),
1910 + );
1911 + yield* Effect.promise(async () => {
1912 + await NodeFSP.mkdir(stateDir, { recursive: true });
1913 + await NodeFSP.writeFile(
1914 + NodePath.join(stateDir, "usage-scan-cache-v5.json"),
1915 + encodeUnknownJsonString(cache),
1916 + );
1917 + });
1918 + const summary = yield* (yield* UsageService.make).readSummary(WINDOW);
1919 + const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
1920 + assert.strictEqual(source?.status, "missing");
1921 + assert.strictEqual(source?.scannedFiles, 0);
1922 + assert.strictEqual(source?.malformedRecords, 2);
1923 + }).pipe(
1924 + Effect.provide(
1925 + layerService({ prefix: "usage-service-missing-diagnostics", home, settings }),
1926 + ),
1927 + );
1928 + }).pipe(Effect.scoped),
1929 + );
1930 +
1931 it.live("reports saved usage of a removed directory only for windows it reaches", () =>
1932 Effect.gen(function* () {
1933 const { transcript, settings, home } = yield* setup;
apps/server/src/usage/UsageService.ts
+49 -10
@@ -353,7 +353,7 @@ export const make = Effect.gen(function* () {
353 ([filePath, entry]) =>
354 entry.provider === provider &&
355 entry.mtimeMs >= retentionCutoffMs &&
356 - entry.records.length + entry.tailRecords.length > 0 &&
356 + (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) &&
357 isWithinDirectory(filePath, dir),
358 );
359 const volumeId =
@@ -459,6 +459,7 @@ export const make = Effect.gen(function* () {
459 format: TranscriptUsageFormat<unknown>,
460 ): Effect.fn.Return<{
461 readonly records: readonly UsageRecord[];
462 + readonly malformedRecords: number;
463 readonly failed?: true;
464 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
465 }> {
@@ -476,6 +477,7 @@ export const make = Effect.gen(function* () {
477 cached.tailRecords.length === 0
478 ? cached.records
479 : [...cached.records, ...cached.tailRecords],
480 + malformedRecords: cached.malformedRecords,
481 };
482 }
483
@@ -492,6 +494,7 @@ export const make = Effect.gen(function* () {
494 if (parsed === null)
495 return {
496 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
497 + malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0,
498 failed: true,
499 };
500
@@ -502,8 +505,17 @@ export const make = Effect.gen(function* () {
505
506 return {
507 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
508 + malformedRecords: parsed.malformedRecords,
509 update: {
506 - entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
510 + entry: {
511 + size,
512 + mtimeMs,
513 + provider,
514 + records,
515 + tailRecords,
516 + malformedRecords: parsed.malformedRecords,
517 + position: parsed.position,
518 + },
519 replaces: cached,
520 },
521 };
@@ -518,7 +530,11 @@ export const make = Effect.gen(function* () {
530 readonly message?: string;
531 readonly action?: UsageSource["action"];
532 readonly files:
521 - | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
533 + | readonly {
534 + readonly path: string;
535 + readonly records: readonly UsageRecord[];
536 + readonly malformedRecords: number;
537 + }[]
538 | null;
539 readonly refreshing?: true;
540 }
@@ -543,8 +559,8 @@ export const make = Effect.gen(function* () {
559 ),
560 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
561 );
546 - const parsedFiles = read.map(({ path, records, update }) => {
547 - if (update === undefined) return { path, records };
562 + const parsedFiles = read.map(({ path, records, malformedRecords, update }) => {
563 + if (update === undefined) return { path, records, malformedRecords };
564 // A scan of another window may have cached its own read of this file
565 // meanwhile. Then keep whichever read saw the later file, so a slower
566 // scan never replaces newer usage with older.
@@ -557,7 +573,7 @@ export const make = Effect.gen(function* () {
573 fileCache.set(path, update.entry);
574 cacheDirty = true;
575 }
560 - return { path, records };
576 + return { path, records, malformedRecords };
577 });
578 const unread = failedPaths + read.filter((file) => file.failed).length;
579 return {
@@ -602,6 +618,7 @@ export const make = Effect.gen(function* () {
618 : Effect.succeed(volumeId),
619 (resolved): ScannedDir => ({
620 ...source,
621 + files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null,
622 provider: reader.provider,
623 volumeId: resolved,
624 }),
@@ -710,7 +727,11 @@ export const make = Effect.gen(function* () {
727 !isWithinDirectory(filePath, dir)
728 )
729 continue;
713 - retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
730 + retainedFiles.push({
731 + path: filePath,
732 + records: [...entry.records, ...entry.tailRecords],
733 + malformedRecords: entry.malformedRecords,
734 + });
735 }
736 return retainedFiles;
737 });
@@ -722,11 +743,13 @@ export const make = Effect.gen(function* () {
743 ] of scannedDirs.entries()) {
744 let scannedFiles = 0;
745 let skippedFiles = 0;
746 + let malformedRecords = 0;
747 // Distinct per directory. Buckets carry per-cell session counts, but a
748 // session spans days and models, so clients total this figure instead.
749 const sessionIds = new Set<string>();
750
751 for (const file of filesByDir[index] ?? []) {
752 + malformedRecords += file.malformedRecords;
753 if (file.records.length === 0) {
754 skippedFiles += 1;
755 continue;
@@ -758,15 +781,31 @@ export const make = Effect.gen(function* () {
781 }
782 }
783
784 + const sourceMessage =
785 + message ?? (files === null ? "No transcript directory on this environment." : null);
786 sources.push({
787 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
763 - status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
788 + status:
789 + files === null && scannedFiles === 0
790 + ? "missing"
791 + : malformedRecords > 0
792 + ? status === undefined || status === "ok"
793 + ? "partial"
794 + : status
795 + : (status ?? "ok"),
796 scannedFiles,
797 skippedFiles,
766 - malformedRecords: 0,
798 + malformedRecords,
799 distinctSessions: sessionIds.size,
800 message:
769 - message ?? (files === null ? "No transcript directory on this environment." : null),
801 + malformedRecords > 0
802 + ? [
803 + sourceMessage,
804 + `${malformedRecords} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`,
805 + ]
806 + .filter(Boolean)
807 + .join(" ")
808 + : sourceMessage,
809 ...(action ? { action } : {}),
810 ...(refreshing ? { refreshing } : {}),
811 });
apps/server/src/usage/usageScanCache.test.ts
+31
@@ -52,6 +52,7 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][])
52 provider: "claude",
53 records,
54 tailRecords: [],
55 + malformedRecords: 0,
56 position: position(),
57 });
58 }
@@ -86,6 +87,7 @@ describe("scan cache round trip", () => {
87 ]);
88 original.set("/grok.jsonl", {
89 size: 40,
90 + malformedRecords: 2,
91 mtimeMs: 300,
92 provider: "grok",
93 records: [
@@ -97,6 +99,7 @@ describe("scan cache round trip", () => {
99 });
100 original.set("/codex.jsonl", {
101 size: 80,
102 + malformedRecords: 3,
103 mtimeMs: 400,
104 provider: "codex",
105 records: [
@@ -135,9 +138,35 @@ describe("scan cache round trip", () => {
138 TEST_FORMAT_MAP,
139 );
140
141 + expect(restored.size).toBe(4);
142 expect(restored).toEqual(original);
143 });
144
145 + it("defaults missing v5 diagnostic counts to zero without losing cached records", () => {
146 + const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]);
147 + const encoded = encodeScanCache(original);
148 + const entry = encoded.files["/gone.jsonl"]!;
149 + const legacy = {
150 + ...encoded,
151 + version: 5,
152 + files: {
153 + "/gone.jsonl": {
154 + s: entry.s,
155 + m: entry.m,
156 + p: entry.p,
157 + r: entry.r,
158 + t: entry.t,
159 + o: entry.o,
160 + gl: entry.gl,
161 + gh: entry.gh,
162 + cs: entry.cs,
163 + },
164 + },
165 + };
166 +
167 + expect(decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP)).toEqual(original);
168 + });
169 +
170 it("drops an entry whose persisted parse state is corrupt", () => {
171 const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]]));
172 const poisoned = {
@@ -190,12 +219,14 @@ describe("scan cache round trip", () => {
219 ["/a.jsonl", 100, [record()]],
220 ["/b.jsonl", 200, [record({ sessionId: "session-b" })]],
221 ]);
222 + cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: 2 });
223 const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } };
224 expect(decodeScanCache(JSON.parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache);
225
226 cache.set("/b.jsonl", {
227 ...cache.get("/b.jsonl")!,
228 size: 30,
229 + malformedRecords: 4,
230 records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })],
231 });
232 const document = JSON.parse(write(cache, { sources }));
apps/server/src/usage/usageScanCache.ts
+7
@@ -33,6 +33,8 @@ export interface CachedFile {
33 * re-reads that segment and would otherwise double count it.
34 */
35 readonly tailRecords: readonly UsageRecord[];
36 + /** Whole-file count, including diagnostics from the tentative tail. */
37 + readonly malformedRecords: number;
38 readonly position: TranscriptParsePosition;
39 }
40
@@ -59,6 +61,7 @@ interface SerializedFile {
61 readonly p: UsageProviderKind;
62 readonly r: readonly SerializedRecord[];
63 readonly t: readonly SerializedRecord[];
64 + readonly mr: number;
65 readonly o: number;
66 readonly gl: number;
67 readonly gh: number;
@@ -115,6 +118,7 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile
118 p: entry.provider,
119 r: entry.records.map(serializeRecord),
120 t: entry.tailRecords.map(serializeRecord),
121 + mr: entry.malformedRecords,
122 o: entry.position.resumeOffset,
123 gl: entry.position.guardLength,
124 gh: entry.position.guardHash,
@@ -271,6 +275,8 @@ export function decodeScanCache(
275 const format = formats.get(entry.p);
276 if (format === undefined) continue;
277 if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue;
278 + const malformedRecords = entry.mr === undefined ? 0 : entry.mr;
279 + if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue;
280 // Position fields feed byte offsets and a Buffer allocation in the reader,
281 // so anything outside their real ranges must reject the entry: a bogus
282 // guard length would otherwise fail every parse of the file, silently
@@ -309,6 +315,7 @@ export function decodeScanCache(
315 provider,
316 records,
317 tailRecords,
318 + malformedRecords,
319 position: legacy
320 ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }
321 : {
apps/server/src/usage/usageTranscriptReader.test.ts
+68
@@ -6,6 +6,8 @@ import * as NodeOS from "node:os";
6 import * as NodePath from "node:path";
7
8 import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest";
9 +import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage";
10 +import * as Schema from "effect/Schema";
11
12 import { TEST_FORMATS } from "./usageTestFormats.ts";
13 import { readTranscriptRecords, transcriptLineGate } from "./usageTranscriptReader.ts";
@@ -70,6 +72,71 @@ function codexUsageLine(outputTokens: number, secondsOffset: number): string {
72 }
73
74 describe("readTranscriptRecords resume", () => {
75 + it.each([
76 + { mode: "buffered", streamingThresholdBytes: Infinity },
77 + { mode: "streaming", streamingThresholdBytes: 0 },
78 + ])("counts malformed tails once across $mode reads and resume", async (options) => {
79 + const format: TranscriptUsageFormat<{ errors: number }> = {
80 + ...TEST_FORMATS.claude,
81 + selectFields: { ...TEST_FORMATS.claude.selectFields, usage: true },
82 + state: {
83 + initial: () => ({ errors: 0 }),
84 + schema: Schema.Struct({ errors: Schema.Number }),
85 + },
86 + parseLine(line, state) {
87 + return this.parseProjected(JSON.parse(line), state);
88 + },
89 + parseProjected(value, state) {
90 + if (
91 + typeof value === "object" &&
92 + value !== null &&
93 + "usage" in value &&
94 + value.usage === "malformed"
95 + ) {
96 + state.errors += 1;
97 + return [];
98 + }
99 + return TEST_FORMATS.claude.parseProjected(value, undefined);
100 + },
101 + readMalformedRecords: (state: { errors: number }) => state.errors,
102 + };
103 + const path = NodePath.join(dir, "diagnostics.jsonl");
104 + const malformed = JSON.stringify({ usage: "malformed" });
105 + // Completed lines enter the projected parser only when they cross a stream chunk.
106 + const committed = `${JSON.stringify({ usage: "malformed", padding: "x".repeat(256 * 1024) })}\n${claudeLine(1, 5)}`;
107 + await NodeFSP.writeFile(path, committed + malformed);
108 +
109 + const first = await readTranscriptRecords(path, format, undefined, options);
110 + assert.isNotNull(first);
111 + assert.deepStrictEqual(
112 + first.records.map((record) => record.totals.outputTokens),
113 + [5],
114 + );
115 + assert.deepStrictEqual(first.tailRecords, []);
116 + assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed));
117 + assert.deepStrictEqual(first.position.state, { errors: 1 });
118 + assert.strictEqual(first.malformedRecords, 2);
119 +
120 + const savedPosition = JSON.parse(JSON.stringify(first.position));
121 + await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`);
122 + const resumed = await readTranscriptRecords(path, format, savedPosition, options);
123 + assert.isNotNull(resumed);
124 + assert.isTrue(resumed.resumed);
125 + assert.deepStrictEqual(
126 + resumed.records.map((record) => record.totals.outputTokens),
127 + [7],
128 + );
129 + assert.deepStrictEqual(resumed.position.state, { errors: 3 });
130 + assert.strictEqual(resumed.malformedRecords, 3);
131 +
132 + const full = await readTranscriptRecords(path, format, undefined, options);
133 + assert.isNotNull(full);
134 + assert.deepStrictEqual([...first.records, ...resumed.records], full.records);
135 + assert.deepStrictEqual(resumed.tailRecords, full.tailRecords);
136 + assert.deepStrictEqual(resumed.position, full.position);
137 + assert.strictEqual(resumed.malformedRecords, full.malformedRecords);
138 + });
139 +
140 it("parses only appended lines when resuming a grown file", async () => {
141 const path = NodePath.join(dir, "claude.jsonl");
142 await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7));
@@ -77,6 +144,7 @@ describe("readTranscriptRecords resume", () => {
144 assert.isNotNull(first);
145 assert.strictEqual(first.records.length, 2);
146 assert.isFalse(first.resumed);
147 + assert.strictEqual(first.malformedRecords, 0);
148
149 await NodeFSP.appendFile(path, claudeLine(3, 11));
150 const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position);
apps/server/src/usage/usageTranscriptReader.ts
+6 -4
@@ -45,6 +45,8 @@ export interface TranscriptParseResult {
45 * segment: the next scan re-reads it once the writer finishes the line.
46 */
47 readonly tailRecords: readonly UsageRecord[];
48 + /** Includes tentative tail diagnostics; position.state only includes committed lines. */
49 + readonly malformedRecords: number;
50 readonly position: TranscriptParsePosition;
51 readonly resumed: boolean;
52 }
@@ -306,10 +308,9 @@ export async function readTranscriptRecords<State>(
308 // `resumeOffset` and the next scan replays the tail from it.
309 const encodedState = encodeState === undefined ? null : encodeState(state);
310 const tailRecords: UsageRecord[] = [];
309 - finish(
310 - decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)),
311 - tailRecords,
312 - );
311 + const tailState =
312 + decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState));
313 + finish(tailState, tailRecords);
314
315 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
316 let guardHash = 0;
@@ -322,6 +323,7 @@ export async function readTranscriptRecords<State>(
323 return {
324 records,
325 tailRecords,
326 + malformedRecords: format.readMalformedRecords?.(tailState) ?? 0,
327 position: {
328 resumeOffset,
329 guardLength,
packages/provider-core/src/server/usage.ts
+2
@@ -62,6 +62,8 @@ export interface TranscriptUsageFormat<State> {
62 readonly usageMarkers: readonly [string, ...string[]];
63 parseLine(line: string, state: State): readonly UsageRecord[];
64 parseProjected(projected: unknown, state: State): readonly UsageRecord[];
65 + /** Cumulative malformed or inconsistent usage records, including skipped records. */
66 + readMalformedRecords?(state: State): number;
67 /**
68 * Present for formats whose records depend on earlier lines. The state at a
69 * resume point is persisted in the scan cache through `schema`, so a grown