Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageService.ts

1,195 lines46.2 KB

1import {
2 type ProviderInstanceConfig,
3 ProviderInstanceId,
4 USAGE_CONTRACT_VERSION,
5 type ServerSettings as ServerSettingsValue,
6 type UsageProviderKind,
7 type UsageSource,
8 type UsagePricing,
9 type UsageSummary,
10 type UsageSummaryInput,
11 UsageReadError,
12} from "@t3tools/contracts";
13import * as HostProcess from "@t3tools/shared/HostProcess";
14import * as Cause from "effect/Cause";
15import * as Clock from "effect/Clock";
16import * as Context from "effect/Context";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Exit from "effect/Exit";
21import * as Fiber from "effect/Fiber";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Path from "effect/Path";
26import * as Schema from "effect/Schema";
27import * as Semaphore from "effect/Semaphore";
28import { HttpClient, HttpClientResponse } from "effect/http";
29​
30import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
31import { formatMalformedUsageWarning } from "@t3tools/shared/usageFormat";
32import * as ServerConfig from "../config.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
35import type { ProviderDriver } from "@t3tools/provider-core/server/driver";
36import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
37import type {
38 ProviderUsageInstance,
39 TranscriptUsageFormat,
40 UsageRecord,
41} from "@t3tools/provider-core/server/usage";
42import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
43import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
44import {
45 DESKTOP_HOST_SCOPE_ENV,
46 listTranscriptFiles,
47 readDirectoryVolumeId,
48 readPhysicalSourceId,
49 readTranscriptRecords,
50} from "./usageTranscriptReader.ts";
51import {
52 decodeScanCache,
53 dedupeWithinFile,
54 LEGACY_SCAN_CACHE_FILE_NAMES,
55 makeScanCacheWriter,
56 pruneScanCache,
57 SCAN_CACHE_FILE_NAME,
58 type CachedFile,
59 type ScanCache,
60} from "./usageScanCache.ts";
61​
62const LITELLM_RATES_URL =
63 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
64const LITELLM_RATES_API_URL =
65 "https://api.github.com/repos/BerriAI/litellm/contents/model_prices_and_context_window.json?ref=main";
66​
67const RATES_TTL_MS = 24 * 60 * 60 * 1000;
68​
69const RATES_REFRESH_FLOOR_MS = 60 * 1000;
70​
71// mtime slack includes writes just before local midnight on the window's first day.
72const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
73const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
74​
75const CACHE_RETENTION_DAYS = 92;
76const STALE_TEMP_DIRECTORY_MS = 60 * 60 * 1000;
77​
78const TRANSCRIPT_READ_CONCURRENCY = 4;
79​
80const transcriptReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
81 driver.usage?.kind === "transcripts" ? [{ driver, reader: driver.usage }] : [],
82);
83​
84const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
85 driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [],
86);
87​
88const transcriptFormats = new Map(
89 transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const),
90);
91​
92interface TranscriptSource {
93 readonly provider: UsageProviderKind;
94 readonly format: TranscriptUsageFormat<unknown>;
95 readonly dir: string;
96 readonly volumeId: string;
97 readonly physicalSourceId?: string;
98 readonly fileName?: string;
100​
101const RatesCacheFile = Schema.Struct({
102 fetchedAtMs: Schema.Number,
103 document: Schema.Unknown,
104});
105const decodeRatesCache = Schema.decodeUnknownEffect(Schema.fromJsonString(RatesCacheFile));
106const encodeRatesCache = Schema.encodeEffect(Schema.fromJsonString(RatesCacheFile));
107​
108const ScanCacheJson = Schema.fromJsonString(Schema.Unknown);
109const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
110const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
111const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
112​
113function isLaterRead(a: CachedFile, b: CachedFile): boolean {
114 return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
116​
117const sharedSessionProviders: ReadonlySet<UsageProviderKind> = new Set(
118 transcriptReaders.flatMap(({ reader }) =>
119 reader.format.sharedSessionsAcrossFiles ? [reader.provider] : [],
120 ),
121);
122​
123// Only shared sessions need cross-file dedupe; per-file occurrence counts make other keys unique.
124function sharedSessions(
125 files: readonly { readonly records: readonly UsageRecord[] }[],
126): ReadonlySet<string> {
127 const firstFile = new Map<string, number>();
128 const shared = new Set<string>();
129 for (const [index, file] of files.entries()) {
130 let previous = "";
131 for (const { provider, sessionId } of file.records) {
132 if (!sharedSessionProviders.has(provider) || sessionId === previous || sessionId.length === 0)
133 continue;
134 previous = sessionId;
135 const first = firstFile.get(sessionId);
136 if (first === undefined) firstFile.set(sessionId, index);
137 else if (first !== index) shared.add(sessionId);
138 }
139 }
140 return shared;
142const decodeCachedSources = Schema.decodeUnknownOption(
143 Schema.Struct({
144 sources: Schema.Record(Schema.String, CachedSource),
145 coveredSince: Schema.optional(Schema.Record(Schema.String, Schema.Number)),
146 }),
147);
148​
149export class UsageService extends Context.Service<
150 UsageService,
151 {
152 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
153 readonly refreshRates: Effect.Effect<UsagePricing>;
154 }
155>()("t3/usage/UsageService") {}
156​
157export const make = Effect.gen(function* () {
158 const fileSystem = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const config = yield* ServerConfig.ServerConfig;
161 const settingsService = yield* ServerSettings.ServerSettingsService;
162 const httpClient = yield* HttpClient.HttpClient;
163 const hostEnvironment = yield* HostProcess.Environment;
164 const hostPlatform = yield* HostProcess.Platform;
165 const hostScope = hostEnvironment[DESKTOP_HOST_SCOPE_ENV]?.trim();
166 // A mount or a directory's on-disk name does not change under a running server.
167 // A miss is not cached: the directory may not exist yet.
168 const physicalSourceIds = new Map<string, Promise<string | undefined>>();
169 const physicalSourceId = (dir: string) =>
170 Effect.promise(() => {
171 const cached = physicalSourceIds.get(dir);
172 if (cached !== undefined) return cached;
173 const id = readPhysicalSourceId(dir, hostScope, hostPlatform);
174 physicalSourceIds.set(dir, id);
175 void id.then((resolved) => {
176 if (resolved === undefined && physicalSourceIds.get(dir) === id) {
177 physicalSourceIds.delete(dir);
178 }
179 });
180 return id;
181 });
182 const hostname = yield* HostProcess.Hostname;
183 const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
184​
185 const fileCache: ScanCache = new Map();
186 // Reads from concurrent windows can still hold the original record after it is corrected.
187 const resolvedRecords = new WeakMap<UsageRecord, UsageRecord>();
188 const correctedRecord = (record: UsageRecord) => resolvedRecords.get(record) ?? record;
189 const correctedBatch = (records: readonly UsageRecord[]) =>
190 records.some((record) => resolvedRecords.has(record)) ? records.map(correctedRecord) : records;
191 const sourceCache = new Map<string, typeof CachedSource.Type>();
192 // Earliest window start a complete scan read each transcript directory from.
193 const coveredSince = new Map<string, number>();
194 const coverageKey = (source: TranscriptSource) => `${source.provider}\0${source.dir}`;
195 let cacheDirty = false;
196 const cover = (source: TranscriptSource, windowStartMs: number) => {
197 if ((coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs) return;
198 coveredSince.set(coverageKey(source), windowStartMs);
199 cacheDirty = true;
200 };
201 const isWithinDirectory = (filePath: string, dir: string) => {
202 const relative = path.relative(dir, filePath);
203 return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
204 };
205​
206 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
207 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
208 const writeCacheFile = (filePath: string, contents: string | Iterable<string>) =>
209 writeFileStringAtomically({ filePath, contents }).pipe(
210 Effect.provideService(FileSystem.FileSystem, fileSystem),
211 Effect.provideService(Path.Path, path),
212 );
213 const hostIdPath = path.join(config.baseDir, "usage-host-id");
214 const explicitHostId = hostEnvironment["T3CODE_HOST_ID"]?.trim();
215 const hostId =
216 explicitHostId ||
217 (yield* fileSystem.readFileString(hostIdPath).pipe(
218 Effect.catchIf(
219 (error) => error.reason._tag === "NotFound",
220 () =>
221 Effect.scoped(
222 Effect.gen(function* () {
223 yield* fileSystem.makeDirectory(config.baseDir, { recursive: true });
224 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
225 directory: config.baseDir,
226 prefix: "usage-host-id.",
227 });
228 const tempFile = path.join(tempDirectory, "identity");
229 yield* fileSystem.writeFileString(tempFile, `${hostname}\n`);
230 // Publish complete contents without replacing another initializer's identity.
231 yield* fileSystem.link(tempFile, hostIdPath).pipe(
232 Effect.catchIf(
233 (error) => error.reason._tag === "AlreadyExists",
234 () => Effect.void,
235 ),
236 );
237 return yield* fileSystem.readFileString(hostIdPath);
238 }),
239 ),
240 ),
241 Effect.map((value) => value.trim() || hostname),
242 Effect.orElseSucceed(() => hostname),
243 ));
244 let rates: RateTable = new Map();
245 let ratesFetchedAtMs: number | null = null;
246 let ratesLastFailedAtMs: number | null = null;
247 let ratesStatus: UsagePricing["status"] = "unavailable";
248 const ratesLock = yield* Semaphore.make(1);
249​
250 const pricing = (): UsagePricing => ({
251 status: ratesStatus,
252 source: LITELLM_RATES_URL,
253 fetchedAt:
254 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
255 knownModels: rates.size,
256 });
257​
258 const fetchRates = (url: string, accept = "application/json") =>
259 httpClient.get(url, { headers: { accept } }).pipe(
260 Effect.flatMap(HttpClientResponse.filterStatusOk),
261 Effect.flatMap((response) => response.json),
262 Effect.map((document) => {
263 const parsed = parseRateTable(document);
264 return parsed.size > 0 ? { document, parsed } : null;
265 }),
266 Effect.timeout(10_000),
267 Effect.catchCause(() => Effect.succeed(null)),
268 );
269​
270 // Outside ratesLock, which a slow fetch holds: a provisional answer prices with these.
271 const loadSavedRates = yield* Effect.cached(
272 fileSystem.readFileString(ratesCachePath).pipe(
273 Effect.flatMap((raw) => decodeRatesCache(raw)),
274 Effect.map((saved) => {
275 const parsed = parseRateTable(saved.document);
276 if (parsed.size === 0) return;
277 rates = parsed;
278 ratesFetchedAtMs = saved.fetchedAtMs;
279 ratesStatus = "cached";
280 }),
281 Effect.ignoreCause,
282 ),
283 );
284​
285 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
286 const now = yield* Clock.currentTimeMillis;
287 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
288 yield* loadSavedRates;
289 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
290 if (ratesLastFailedAtMs !== null && now - ratesLastFailedAtMs < RATES_REFRESH_FLOOR_MS) return;
291​
292 let fetched = yield* fetchRates(LITELLM_RATES_URL);
293 if (fetched === null) {
294 fetched = yield* fetchRates(LITELLM_RATES_API_URL, "application/vnd.github.raw+json");
295 }
296 if (fetched === null) {
297 ratesLastFailedAtMs = yield* Clock.currentTimeMillis;
298 if (rates.size > 0) ratesStatus = "cached";
299 return;
300 }
301​
302 rates = fetched.parsed;
303 ratesFetchedAtMs = now;
304 ratesLastFailedAtMs = null;
305 ratesStatus = "fresh";
306​
307 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched.document }).pipe(
308 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
309 Effect.ignoreCause,
310 );
311 });
312​
313 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
314​
315 const refreshRates = ensureRates(true).pipe(
316 Effect.map(pricing),
317 Effect.withSpan("UsageService.refreshRates"),
318 );
319​
320 const readSettings = settingsService.getSettings.pipe(
321 Effect.catchCause(
322 (cause) =>
323 new UsageReadError({
324 reason: "scanFailed",
325 detail: "Server settings could not be read.",
326 cause: Cause.squash(cause),
327 }),
328 ),
329 );
330​
331 const usageInstances = Effect.fn("UsageService.usageInstances")(function* <Config>(
332 driver: ProviderDriver<Config, unknown, unknown>,
333 settings: ServerSettingsValue,
334 ) {
335 const entries: Array<
336 readonly [ProviderInstanceId, Pick<ProviderInstanceConfig, "config" | "environment">, boolean]
337 > = Object.entries(settings.providerInstances)
338 .filter(([, instance]) => instance.driver === driver.driverKind)
339 .map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const);
340 if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) {
341 entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]);
342 }
343 const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
344 return yield* Effect.forEach(
345 entries,
346 Effect.fnUntraced(function* ([instanceId, instance, configured]) {
347 const instanceConfig: ProviderUsageInstance<Config> = {
348 instanceId,
349 config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
350 environment: yield* mergeProviderInstanceEnvironment(
351 instance.environment,
352 hostEnvironment,
353 ),
354 configured,
355 };
356 return instanceConfig;
357 }),
358 );
359 });
360​
361 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
362 settings: ServerSettingsValue,
363 retentionCutoffMs: number,
364 awaitRefresh: boolean,
365 ) {
366 const dirs: Array<TranscriptSource> = [];
367 const pending: Array<ScannedDir> = [];
368 const seen = new Set<string>();
369 for (const { driver, reader } of transcriptReaders) {
370 const { provider, format } = reader;
371 const directories = yield* Effect.forEach(
372 yield* usageInstances(driver, settings),
373 (instance) => reader.directories(instance, { awaitRefresh }),
374 );
375 for (const { dir: directory, fileName, refreshing } of directories.flat()) {
376 if (refreshing) {
377 const key = `${provider}\0${directory}`;
378 if (seen.has(key)) continue;
379 seen.add(key);
380 pending.push({ provider, dir: directory, volumeId: "", files: [], refreshing });
381 continue;
382 }
383 const sourceKey = provider + "\0" + directory;
384 const previous = sourceCache.get(sourceKey);
385 const dir = yield* fileSystem
386 .realPath(directory)
387 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
388 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
389 const hasRetainedHistory = fileCache
390 .entries()
391 .some(
392 ([filePath, entry]) =>
393 entry.provider === provider &&
394 entry.mtimeMs >= retentionCutoffMs &&
395 (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) &&
396 isWithinDirectory(filePath, dir),
397 );
398 const volumeId =
399 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
400 ? previous.volumeId || currentVolumeId
401 : currentVolumeId;
402 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
403 sourceCache.set(sourceKey, { dir, volumeId });
404 cacheDirty = true;
405 }
406 const key = `${provider}\0${dir}`;
407 if (seen.has(key)) continue;
408 seen.add(key);
409 const sourceId = yield* physicalSourceId(dir);
410 dirs.push({
411 provider,
412 format,
413 dir,
414 volumeId,
415 ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
416 ...(fileName === undefined ? {} : { fileName }),
417 });
418 }
419 }
420 return { dirs, pending };
421 });
422​
423 // Share first loads so concurrent readers cannot scan against a still-empty cache.
424 const ensureScanCacheLoaded = yield* Effect.cached(
425 Effect.gen(function* () {
426 const readDocument = (filePath: string) =>
427 fileSystem.readFileString(filePath).pipe(
428 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
429 Effect.catchCause(() => Effect.succeed(null)),
430 );
431 let document = yield* readDocument(scanCachePath);
432 const current = document !== null;
433 for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
434 if (document !== null) break;
435 document = yield* readDocument(path.join(config.stateDir, fileName));
436 cacheDirty = document !== null;
437 }
438 if (document === null) return;
439 const decoded = decodeScanCache(document, transcriptFormats);
440 for (const [path, entry] of decoded) fileCache.set(path, entry);
441 const saved = (document as { readonly files?: unknown }).files;
442 const complete =
443 typeof saved === "object" && saved !== null && Object.keys(saved).length === decoded.size;
444 const sources = decodeCachedSources(document);
445 if (Option.isSome(sources)) {
446 for (const [key, source] of Object.entries(sources.value.sources))
447 sourceCache.set(key, source);
448 // Coverage describes the saved files, so it needs every one, in this version's format.
449 if (current && complete && fileCache.size > 0) {
450 for (const [key, since] of Object.entries(sources.value.coveredSince ?? {}))
451 coveredSince.set(key, since);
452 }
453 }
454 }),
455 );
456​
457 const writeScanCache = makeScanCacheWriter();
458 // Serialize writes so concurrently finished window scans cannot overwrite newer snapshots.
459 const persistLock = yield* Semaphore.make(1);
460​
461 // The saved cache supersedes older versions. Temp folders an aborted write left behind are
462 // removed once idle for an hour, so a write in progress from another server survives.
463 let supersededFilesRemoved = false;
464 const removeSupersededCacheFiles = Effect.gen(function* () {
465 for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
466 yield* fileSystem.remove(path.join(config.stateDir, fileName)).pipe(Effect.ignore);
467 }
468 const tempPrefixes = [SCAN_CACHE_FILE_NAME, ...LEGACY_SCAN_CACHE_FILE_NAMES].map(
469 (fileName) => `${fileName}.`,
470 );
471 const staleBeforeMs = (yield* Clock.currentTimeMillis) - STALE_TEMP_DIRECTORY_MS;
472 for (const name of yield* fileSystem.readDirectory(config.stateDir)) {
473 if (!tempPrefixes.some((prefix) => name.startsWith(prefix))) continue;
474 const tempPath = path.join(config.stateDir, name);
475 yield* fileSystem.stat(tempPath).pipe(
476 Effect.flatMap((info) => {
477 const mtimeMs = Option.getOrUndefined(info.mtime)?.getTime();
478 return info.type === "Directory" && mtimeMs !== undefined && mtimeMs <= staleBeforeMs
479 ? fileSystem.remove(tempPath, { recursive: true })
480 : Effect.void;
481 }),
482 Effect.ignore,
483 );
484 }
485 }).pipe(Effect.ignore);
486​
487 // Clear dirty before encoding to retain concurrent changes; restore it on failure for retry.
488 const persistCaches = Effect.gen(function* () {
489 if (cacheDirty) {
490 cacheDirty = false;
491 yield* Effect.sync(() =>
492 writeScanCache(fileCache, {
493 sources: Object.fromEntries(sourceCache),
494 coveredSince: Object.fromEntries(coveredSince),
495 }),
496 ).pipe(
497 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
498 Effect.andThen(
499 Effect.suspend(() => {
500 if (supersededFilesRemoved) return Effect.void;
501 supersededFilesRemoved = true;
502 return removeSupersededCacheFiles;
503 }),
504 ),
505 Effect.catchCause(() =>
506 Effect.sync(() => {
507 cacheDirty = true;
508 }),
509 ),
510 );
511 }
512 }).pipe(persistLock.withPermit, Effect.withSpan("UsageService.persistCaches"));
513​
514 const pendingPersists = new Set<Fiber.Fiber<void>>();
515 const schedulePersist = Effect.forkDetach(persistCaches).pipe(
516 Effect.map((fiber) => {
517 pendingPersists.add(fiber);
518 fiber.addObserver(() => pendingPersists.delete(fiber));
519 }),
520 );
521 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
522 Effect.asVoid,
523 );
524 yield* Effect.addFinalizer(() => awaitPersisted);
525​
526 /**
527 * Reads run concurrently, and the caller stores updates in walk order rather
528 * than completion order: saved records of deleted transcripts aggregate in
529 * cache order, where the first copy of a duplicate decides its bucket. Untraced: a scan
530 * reads thousands of files, so scanTranscriptDir records the counts instead.
531 */
532 const readFileRecords = Effect.fnUntraced(function* (
533 filePath: string,
534 size: number,
535 mtimeMs: number,
536 provider: UsageProviderKind,
537 format: TranscriptUsageFormat<unknown>,
538 ): Effect.fn.Return<{
539 readonly records: readonly UsageRecord[];
540 readonly malformedRecords: number;
541 readonly failed?: true;
542 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
543 }> {
544 const cached = fileCache.get(filePath);
545 // Provider is part of the identity: if both providers were ever pointed
546 // at one directory, a hit parsed by the other parser must not be reused.
547 if (
548 cached &&
549 cached.size === size &&
550 cached.mtimeMs === mtimeMs &&
551 cached.provider === provider
552 ) {
553 return {
554 records:
555 cached.tailRecords.length === 0
556 ? cached.records
557 : [...cached.records, ...cached.tailRecords],
558 malformedRecords: cached.malformedRecords,
559 };
560 }
561​
562 // Only a strictly grown file may resume. Same size with a new mtime, or
563 // a shrunken file, means rewritten content; re-parse it whole.
564 const resumeFrom =
565 cached !== undefined && cached.provider === provider && size > cached.size
566 ? cached.position
567 : undefined;
568​
569 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom));
570 // A read failure is not an empty transcript: caching it under this
571 // (size, mtime) would silently drop the file's usage until it changes.
572 if (parsed === null)
573 return {
574 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
575 malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0,
576 failed: true,
577 };
578​
579 const identity = (record: UsageRecord) =>
580 encodeUsageRecordKey([
581 record.provider,
582 record.sessionId,
583 record.timestampMs,
584 record.model,
585 record.rateModel,
586 record.totals,
587 record.reportedCostUsd,
588 record.dedupeKey,
589 ]);
590 if (!parsed.resumed && cached !== undefined && cached.provider === provider) {
591 // A whole-file re-parse re-emits saved requests unresolved. Keep their saved tier
592 // corrections, since the history that resolved them may no longer be available.
593 // Equal requests keep their own corrections by matching occurrences in order.
594 const saved = new Map<string, UsageRecord[]>();
595 for (const previous of [...cached.records, ...cached.tailRecords]) {
596 const corrected = correctedRecord(previous);
597 const key = identity(corrected);
598 const occurrences = saved.get(key);
599 if (occurrences === undefined) saved.set(key, [corrected]);
600 else occurrences.push(corrected);
601 }
602 for (const record of [...parsed.records, ...parsed.tailRecords]) {
603 const corrected = saved.get(identity(record))?.shift();
604 if (
605 record.unresolvedServiceTierTurnId !== undefined &&
606 corrected !== undefined &&
607 corrected.unresolvedServiceTierTurnId === undefined
608 ) {
609 resolvedRecords.set(record, corrected);
610 }
611 }
612 }
613 if (parsed.resumed && cached !== undefined && cached.tailRecords.length > 0) {
614 // Completing a tentative line reparses it. Reuse its saved correction only when the
615 // same usage is emitted again, without putting inferred tiers in the parser state.
616 const reparsed = [...parsed.records, ...parsed.tailRecords];
617 for (const [index, previous] of cached.tailRecords.entries()) {
618 const record = reparsed[index];
619 const corrected = correctedRecord(previous);
620 if (
621 record?.unresolvedServiceTierTurnId !== undefined &&
622 corrected.unresolvedServiceTierTurnId === undefined &&
623 identity(record) === identity(corrected)
624 ) {
625 resolvedRecords.set(record, corrected);
626 }
627 }
628 }
629 const base = parsed.resumed && cached !== undefined ? cached.records : [];
630 const records = dedupeWithinFile([...base, ...parsed.records]);
631 const tailRecords = parsed.tailRecords;
632​
633 return {
634 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
635 malformedRecords: parsed.malformedRecords,
636 update: {
637 entry: {
638 size,
639 mtimeMs,
640 provider,
641 records,
642 tailRecords,
643 malformedRecords: parsed.malformedRecords,
644 position: parsed.position,
645 },
646 replaces: cached,
647 },
648 };
649 });
650​
651 interface ScannedDir {
652 readonly provider: UsageProviderKind;
653 readonly dir: string;
654 readonly volumeId: string;
655 readonly physicalSourceId?: string;
656 readonly hostId?: string;
657 readonly status?: UsageSource["status"];
658 readonly message?: string;
659 readonly files:
660 | readonly {
661 readonly path: string;
662 readonly records: readonly UsageRecord[];
663 readonly malformedRecords: number;
664 }[]
665 | null;
666 /** Every transcript path the walk listed, in walk order, whatever its mtime. */
667 readonly walked?: readonly string[];
668 readonly refreshing?: true;
669 }
670​
671 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
672 source: TranscriptSource,
673 windowStartMs: number,
674 fromMemory: boolean,
675 ) {
676 const { provider, format, dir, volumeId, physicalSourceId, fileName } = source;
677 const identity = {
678 provider,
679 dir,
680 volumeId,
681 ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
682 };
683 const exists = yield* fileSystem
684 .exists(dir)
685 .pipe(Effect.catchCause(() => Effect.succeed(false)));
686 if (!exists) {
687 cover(source, windowStartMs);
688 return { ...identity, files: null } satisfies ScannedDir;
689 }
690 // scanSummary aggregates the saved files, as it does for a deleted directory.
691 if (fromMemory) return { ...identity, files: [] } satisfies ScannedDir;
692 const { files, walked, failedPaths } = yield* Effect.promise(() =>
693 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
694 );
695 const read = yield* Effect.forEach(
696 files,
697 (file) =>
698 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
699 Effect.map((result) => ({ path: file.path, ...result })),
700 ),
701 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
702 );
703 const parsedFiles = read.map(({ path, records, malformedRecords, update }) => {
704 if (update === undefined) return { path, records, malformedRecords };
705 // A scan of another window may have cached its own read of this file
706 // meanwhile. Then keep whichever read saw the later file, so a slower
707 // scan never replaces newer usage with older.
708 const current = fileCache.get(path);
709 if (
710 current === update.replaces ||
711 current === undefined ||
712 isLaterRead(update.entry, current)
713 ) {
714 fileCache.set(path, {
715 ...update.entry,
716 records: correctedBatch(update.entry.records),
717 tailRecords: correctedBatch(update.entry.tailRecords),
718 });
719 cacheDirty = true;
720 }
721 return { path, records, malformedRecords };
722 });
723 const livePaths = new Set(files.map((file) => file.path));
724 for (const file of read) {
725 if (file.failed || !file.path.endsWith(".jsonl.zst")) continue;
726 const originalPath = file.path.slice(0, -4);
727 // A successfully read archive replaces the original's saved records and diagnostics.
728 if (!livePaths.has(originalPath) && fileCache.delete(originalPath)) cacheDirty = true;
729 }
730 const unread = failedPaths + read.filter((file) => file.failed).length;
731 if (unread === 0) cover(source, windowStartMs);
732 yield* Effect.annotateCurrentSpan({
733 "usage.files": files.length,
734 "usage.files_parsed": read.filter((file) => file.update !== undefined).length,
735 });
736 return {
737 ...identity,
738 files: parsedFiles,
739 walked,
740 ...(unread > 0
741 ? {
742 status: "partial",
743 message: `${unread} transcript path(s) could not be read; usage may be incomplete.`,
744 }
745 : {}),
746 } satisfies ScannedDir;
747 });
748​
749 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
750 { dirs, pending }: Effect.Success<ReturnType<typeof resolveTranscriptDirs>>,
751 windowStartMs: number,
752 settings: ServerSettingsValue,
753 retentionCutoffMs: number,
754 awaitRefresh: boolean,
755 fromMemory: boolean,
756 ) {
757 const scans = Effect.forEach(
758 scanReaders,
759 ({ driver, reader }) =>
760 usageInstances(driver, settings).pipe(
761 Effect.flatMap((instances) =>
762 reader.scan({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }),
763 ),
764 Effect.flatMap((sources) =>
765 Effect.forEach(sources, ({ volumeId, ...source }) =>
766 Effect.map(
767 // A reader's own volumeId names a remote account, not a local directory.
768 volumeId === undefined
769 ? Effect.all([
770 Effect.promise(() => readDirectoryVolumeId(source.dir)),
771 physicalSourceId(source.dir),
772 ])
773 : Effect.succeed<[string, string | undefined]>([volumeId, undefined]),
774 ([resolved, sourceId]): ScannedDir => ({
775 ...source,
776 files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null,
777 provider: reader.provider,
778 volumeId: resolved,
779 ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
780 }),
781 ),
782 ),
783 ),
784 Effect.provideContext(readerContext),
785 ),
786 { concurrency: "unbounded" },
787 );
788​
789 // Scan independent sources together, directories sequentially to bound open files; keep order, since the first copy decides a duplicate's bucket.
790 const [transcripts, scanDirs] = yield* Effect.all(
791 [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs, fromMemory)), scans],
792 { concurrency: "unbounded" },
793 );
794 const scanned: readonly ScannedDir[] = [...transcripts, ...pending, ...scanDirs.flat()];
795 return scanned;
796 });
797​
798 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
799 input: UsageSummaryInput,
800 settings: ServerSettingsValue,
801 provisional: boolean,
802 ) {
803 if (input.sinceDay > input.untilDay) {
804 return yield* new UsageReadError({
805 reason: "invalidWindow",
806 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
807 });
808 }
809​
810 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
811 if (input.resolution === "hour") {
812 const sinceTime =
813 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
814 const untilTime =
815 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
816 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
817 return yield* new UsageReadError({
818 reason: "invalidWindow",
819 detail: "Hourly usage requires valid sinceTime and untilTime instants",
820 });
821 }
822 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
823 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
824 const durationMs = untilTimeMs - sinceTimeMs;
825 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
826 return yield* new UsageReadError({
827 reason: "invalidWindow",
828 detail: "Hourly usage window must be greater than zero and at most 24 hours",
829 });
830 }
831 hourlyWindow = { sinceTimeMs, untilTimeMs };
832 }
833​
834 const startedAtMs = yield* Clock.currentTimeMillis;
835 yield* ensureScanCacheLoaded;
836​
837 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
838 if (Option.isNone(windowStart)) {
839 return yield* new UsageReadError({
840 reason: "invalidWindow",
841 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
842 });
843 }
844 const windowStartMs =
845 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
846​
847 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
848​
849 const awaitRefresh = input.awaitRefresh === true;
850 const collect = Effect.gen(function* () {
851 const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe(
852 Effect.provideContext(readerContext),
853 );
854 // A window no complete scan has read would show partial totals, so every directory must cover it.
855 // Saved files are keyed by path, so two providers reading one directory keep only one parse.
856 const fromMemory =
857 provisional &&
858 resolved.dirs.length > 0 &&
859 new Set(resolved.dirs.map((source) => source.dir)).size === resolved.dirs.length &&
860 resolved.dirs.every(
861 (source) => (coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs,
862 );
863 const [, scanned] = yield* Effect.all(
864 [
865 fromMemory ? loadSavedRates : provisional ? ensureRates(false) : Effect.void,
866 collectDirs(
867 resolved,
868 windowStartMs,
869 settings,
870 retentionCutoffMs,
871 awaitRefresh,
872 fromMemory,
873 ),
874 ],
875 { concurrency: 2 },
876 );
877 return { scannedDirs: scanned, fromMemory };
878 });
879 const [{ scannedDirs, fromMemory }] = yield* Effect.all(
880 [collect, provisional ? Effect.void : ensureRates(false)],
881 { concurrency: 2 },
882 );
883​
884 const aggregator = new UsageAggregator({
885 timeZone: input.timeZone,
886 sinceDay: input.sinceDay,
887 untilDay: input.untilDay,
888 resolution: input.resolution ?? "day",
889 ...hourlyWindow,
890 rates,
891 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
892 modelAliases: resolveModelAliases(settings.usageModelAliases),
893 ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
894 });
895​
896 const sources: UsageSource[] = [];
897​
898 // Deleted transcripts' saved usage still aggregates and deduplicates normally.
899 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
900 // Saved paths are files below a scanned root, so their folder decides; folders repeat thousands of times.
901 const withinDir = (dir: string) => {
902 const foldersWithin = new Map<string, boolean>();
903 return (filePath: string) => {
904 const folder = path.dirname(filePath);
905 let within = foldersWithin.get(folder);
906 if (within === undefined) {
907 within = isWithinDirectory(folder, dir);
908 foldersWithin.set(folder, within);
909 }
910 return within;
911 };
912 };
913 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
914 const retainedFiles = [...(files ?? [])];
915 const livePaths = new Set(retainedFiles.map((file) => file.path));
916 const isRetained = withinDir(dir);
917 for (const [filePath, entry] of fileCache) {
918 if (
919 entry.provider !== provider ||
920 entry.mtimeMs < retainedSinceMs ||
921 livePaths.has(filePath) ||
922 !isRetained(filePath)
923 )
924 continue;
925 retainedFiles.push({
926 path: filePath,
927 records:
928 entry.tailRecords.length === 0
929 ? entry.records
930 : [...entry.records, ...entry.tailRecords],
931 malformedRecords: entry.malformedRecords,
932 });
933 }
934 return retainedFiles;
935 });
936 // Usage two transcripts share counts in the first one, so saved files take the order an exact
937 // scan reads them in: walked files in walk order, then the directory's deleted files.
938 for (const { provider, dir, walked } of fromMemory ? [] : scannedDirs) {
939 if (walked === undefined) continue;
940 const within = withinDir(dir);
941 const saved = [...fileCache.keys()];
942 const members = new Set(
943 saved.filter(
944 (filePath) => fileCache.get(filePath)!.provider === provider && within(filePath),
945 ),
946 );
947 if (members.size < 2) continue;
948 const listed = new Set(walked);
949 const target = [
950 ...walked.filter((filePath) => members.has(filePath)),
951 ...saved.filter((filePath) => members.has(filePath) && !listed.has(filePath)),
952 ];
953 let next = 0;
954 const ordered = saved.map((filePath) => (members.has(filePath) ? target[next++]! : filePath));
955 if (ordered.every((filePath, index) => filePath === saved[index])) continue;
956 const entries = new Map(fileCache);
957 fileCache.clear();
958 for (const filePath of ordered) fileCache.set(filePath, entries.get(filePath)!);
959 cacheDirty = true;
960 }
961 const windowEndMs =
962 hourlyWindow?.untilTimeMs ??
963 Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS;
964 let resolvedAny = false;
965 for (const { reader } of transcriptReaders) {
966 if (reader.resolveServiceTiers === undefined || fromMemory) continue;
967 const pending = new Set<UsageRecord>();
968 for (const [index, files] of filesByDir.entries()) {
969 if (scannedDirs[index]?.provider !== reader.provider) continue;
970 for (const file of files) {
971 for (const raw of file.records) {
972 const record = correctedRecord(raw);
973 if (
974 record.provider === reader.provider &&
975 record.unresolvedServiceTierTurnId !== undefined &&
976 record.timestampMs >= windowStartMs &&
977 record.timestampMs < windowEndMs
978 ) {
979 pending.add(record);
980 }
981 }
982 }
983 }
984 if (pending.size === 0) continue;
985 const resolved = yield* reader
986 .resolveServiceTiers([...pending])
987 .pipe(Effect.provideContext(readerContext));
988 for (const [record, speed] of resolved) {
989 const { unresolvedServiceTierTurnId: _turnId, ...rest } = record;
990 resolvedRecords.set(record, { ...rest, speed });
991 resolvedAny = true;
992 }
993 }
994 if (resolvedAny) {
995 for (const [filePath, entry] of fileCache) {
996 const records = correctedBatch(entry.records);
997 const tailRecords = correctedBatch(entry.tailRecords);
998 if (records === entry.records && tailRecords === entry.tailRecords) continue;
999 // Update the current entry by identity; a slow resolver cannot restore an older file.
1000 fileCache.set(filePath, { ...entry, records, tailRecords });
1001 cacheDirty = true;
1004 const crossFileSessions = sharedSessions(filesByDir.flat());
1005​
1006 for (const [
1007 index,
1009 provider,
1010 dir,
1011 volumeId,
1012 physicalSourceId,
1013 files,
1014 status,
1015 message,
1016 refreshing,
1017 hostId: sourceHostId,
1018 },
1019 ] of scannedDirs.entries()) {
1020 let scannedFiles = 0;
1021 let skippedFiles = 0;
1022 let malformedRecords = 0;
1023 // Distinct per directory. Buckets carry per-cell session counts, but a
1024 // session spans days and models, so clients total this figure instead.
1025 const sessionIds = new Set<string>();
1026 let counted = false;
1027​
1028 for (const file of filesByDir[index] ?? []) {
1029 malformedRecords += file.malformedRecords;
1030 if (file.records.length === 0) {
1031 skippedFiles += 1;
1032 continue;
1034 scannedFiles += 1;
1035 const eventOccurrences = new Map<string, number>();
1036 for (const rawRecord of file.records) {
1037 const record = correctedRecord(rawRecord);
1038 let usageRecord = record;
1039 if (
1040 sharedSessionProviders.has(record.provider) &&
1041 crossFileSessions.has(record.sessionId)
1042 ) {
1043 // Dedupe moved copies but retain repeated equal events within a file, including second-precision timestamps.
1044 const key = encodeUsageRecordKey([
1045 record.provider,
1046 record.sessionId,
1047 record.timestampMs,
1048 record.model,
1049 record.totals,
1050 ]);
1051 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
1052 eventOccurrences.set(key, occurrence);
1053 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
1055 if (aggregator.add(usageRecord, dir)) {
1056 counted = true;
1057 if (record.sessionId.length > 0) sessionIds.add(record.sessionId);
1061​
1062 const sourceMessage =
1063 message ?? (files === null ? "No transcript directory on this environment." : null);
1064 sources.push({
1065 fingerprint: {
1066 hostId: sourceHostId ?? hostId,
1067 provider,
1068 resolvedHomePath: dir,
1069 volumeId,
1070 ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
1071 },
1072 status:
1073 files === null && scannedFiles === 0
1074 ? "missing"
1075 : malformedRecords > 0
1076 ? status === undefined || status === "ok"
1077 ? "partial"
1078 : status
1079 : (status ?? "ok"),
1080 scannedFiles,
1081 skippedFiles,
1082 malformedRecords,
1083 distinctSessions: sessionIds.size,
1084 message:
1085 malformedRecords > 0
1086 ? [sourceMessage, formatMalformedUsageWarning(malformedRecords)]
1087 .filter(Boolean)
1088 .join(" ")
1089 : sourceMessage,
1090 // A saved answer misses what changed since its scan, so the client must ask again. An
1091 // empty source stays unmarked: it would only flash a loading row.
1092 ...(refreshing || (fromMemory && counted && transcriptFormats.has(provider))
1093 ? { refreshing: true }
1094 : {}),
1095 });
1097​
1098 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
1099 if (pruned > 0) {
1100 cacheDirty = true;
1101 // Pruned files are no longer saved, so nothing before the cutoff stays covered.
1102 for (const [key, since] of coveredSince) {
1103 if (since < retentionCutoffMs) coveredSince.set(key, retentionCutoffMs);
1106​
1107 const aggregated = aggregator.finish();
1108 const readAt = yield* DateTime.now;
1109 const finishedAtMs = yield* Clock.currentTimeMillis;
1110​
1111 const summary = {
1112 contractVersion: USAGE_CONTRACT_VERSION,
1113 readAt: DateTime.formatIso(readAt),
1114 timeZone: input.timeZone,
1115 sinceDay: input.sinceDay,
1116 untilDay: input.untilDay,
1117 buckets: aggregated.buckets,
1118 sources,
1119 pricing: pricing(),
1120 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
1121 ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
1122 } satisfies UsageSummary;
1123 return { summary, fromMemory };
1124 });
1125​
1126 const readWindow = Effect.fn("UsageService.readWindow")(function* (
1127 input: UsageSummaryInput,
1128 settings: ServerSettingsValue,
1129 provisional: boolean,
1130 ) {
1131 const { summary, fromMemory } = yield* scanSummary(input, settings, provisional);
1132 // With nothing marked refreshing the client would keep a saved answer as final.
1133 return fromMemory && !summary.sources.some((source) => source.refreshing === true)
1134 ? (yield* scanSummary(input, settings, false)).summary
1135 : summary;
1136 });
1137​
1138 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
1139​
1140 const scanKey = (
1141 input: UsageSummaryInput,
1142 settings: ServerSettingsValue,
1143 provisional: boolean,
1144 ): string =>
1145 JSON.stringify([
1146 input.timeZone,
1147 input.sinceDay,
1148 input.untilDay,
1149 input.resolution ?? "day",
1150 input.sinceTime ?? null,
1151 input.untilTime ?? null,
1152 settings,
1153 input.awaitRefresh === true,
1154 provisional,
1155 input.modelFilter ?? null,
1156 ]);
1157​
1158 const readSummary = Effect.fn("UsageService.readSummary")(function* (
1159 requested: UsageSummaryInput,
1160 ) {
1161 const { modelFilter: requestedFilter, ...unfiltered } = requested;
1162 const modelFilter = canonicalModelFilter(requestedFilter);
1163 const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter };
1164 const settings = yield* readSettings;
1165 const provisional = input.provisional === true && input.awaitRefresh !== true;
1166 const key = scanKey(input, settings, provisional);
1167 const deferred = yield* Effect.uninterruptible(
1168 Effect.gen(function* () {
1169 const existing = inflightScans.get(key);
1170 if (existing !== undefined) return existing;
1171​
1172 // Register and fork atomically so cancellation cannot leave a Deferred without a scan.
1173 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
1174 inflightScans.set(key, created);
1175 // Detach so caller departure cannot cancel shared scans; finished scans warm the cache.
1176 // Register writes before releasing waiters, but start writing after delivering their summary.
1177 yield* readWindow(input, settings, provisional).pipe(
1178 Effect.onExit((exit) =>
1179 Effect.sync(() => inflightScans.delete(key)).pipe(
1180 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
1181 Effect.andThen(Deferred.done(created, exit)),
1182 ),
1183 ),
1184 Effect.forkDetach,
1185 );
1186 return created;
1187 }),
1188 );
1189 return yield* Deferred.await(deferred);
1190 });
1191​
1192 return { readSummary, refreshRates, awaitPersisted } as const;
1193});
1194​
1195export const layer = Layer.effect(UsageService, make);