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