Skip to content
TypeScript

fix(usage): price new models without waiting a day for the rate table (#9202)

Theo Browne2b745efe57cd
diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.ts
index cce91b65a6d..f5bdc0d0858 100644
--- a/apps/mobile/src/state/usage.ts
+++ b/apps/mobile/src/state/usage.ts
@@ -16,6 +16,7 @@ import {
type UsageSummary,
type UsageSummaryInput,
} from "@t3tools/contracts";
+import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
@@ -100,12 +101,21 @@ export function useUsage(input: UsageSummaryInput): UsageView {
// Refreshing only the derived atom would re-read the per-environment SWR
// queries within their stale window and change nothing. Refresh each
// environment's query so pull-to-refresh always rescans.
+ //
+ // Each environment refetches model pricing first, so a model released since
+ // its last daily fetch gets priced by the rescan. The rescan runs whether or
+ // not the refetch succeeds: an offline environment still recounts tokens.
const refresh = useCallback(() => {
const input = JSON.parse(windowKey) as UsageSummaryInput;
for (const environment of environments) {
- appAtomRegistry.refresh(
- serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
- );
+ const { environmentId } = environment;
+ const query = serverEnvironment.usageSummary({ environmentId, input });
+ void runAtomCommand(
+ appAtomRegistry,
+ serverEnvironment.refreshUsageRates,
+ { environmentId, input: {} },
+ { reportFailure: false },
+ ).finally(() => appAtomRegistry.refresh(query));
}
}, [environments, windowKey]);
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 6cc04c3775b..65f590d1a83 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -56,6 +56,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
[WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,
+ [WS_METHODS.serverRefreshUsageRates]: AuthOrchestrationReadScope,
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 8fc86ee3d46..63b74510e29 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -8,11 +8,13 @@ import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { UsageDay, type UsageSummaryInput } from "@t3tools/contracts";
+import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Scheduler from "effect/Scheduler";
+import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import * as ServerConfig from "../config.ts";
@@ -65,6 +67,8 @@ const serviceLayers = (input: {
readonly home: string;
readonly settings: Parameters<typeof ServerSettings.layerTest>[0];
readonly onRatesFetch?: () => void;
+ /** Defaults to an unparsable document so every scan retries the fetch. */
+ readonly ratesDocument?: unknown;
}) =>
ServerConfig.layerTest(process.cwd(), { prefix: input.prefix }).pipe(
Layer.provideMerge(NodeServices.layer),
@@ -77,7 +81,7 @@ const serviceLayers = (input: {
input.onRatesFetch?.();
// Unparsable rates: every scan retries the fetch, which makes the
// fetch count a boundary-level observation of how many scans ran.
- return HttpClientResponse.fromWeb(request, Response.json({}));
+ return HttpClientResponse.fromWeb(request, Response.json(input.ratesDocument ?? {}));
}),
),
),
@@ -142,6 +146,48 @@ describe("UsageService", () => {
}).pipe(Effect.scoped),
);
+ it.live("refetches a rate table inside its TTL only when the client asks", () =>
+ Effect.gen(function* () {
+ const { transcript, settings, home } = yield* setup;
+ yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
+
+ let ratesFetches = 0;
+ const service = yield* UsageService.make.pipe(
+ Effect.provide(
+ serviceLayers({
+ prefix: "usage-service-rates-refresh-test",
+ home,
+ settings,
+ ratesDocument: {
+ "claude-fable-5": { input_cost_per_token: 1e-5, output_cost_per_token: 5e-5 },
+ },
+ onRatesFetch: () => {
+ ratesFetches += 1;
+ },
+ }),
+ ),
+ );
+
+ const first = yield* service.readSummary(WINDOW);
+ assert.strictEqual(ratesFetches, 1);
+ assert.strictEqual(first.pricing.status, "fresh");
+
+ // Inside the daily TTL a plain rescan keeps the cached table.
+ yield* TestClock.adjust(Duration.minutes(2));
+ yield* service.readSummary(WINDOW);
+ assert.strictEqual(ratesFetches, 1);
+
+ // An explicit refresh fetches again so a newly listed model gets priced.
+ // A burst of refreshes shares that one fetch.
+ const [refreshed] = yield* Effect.all([service.refreshRates, service.refreshRates], {
+ concurrency: 2,
+ });
+ assert.strictEqual(ratesFetches, 2);
+ assert.strictEqual(refreshed.status, "fresh");
+ assert.strictEqual(refreshed.knownModels, 1);
+ }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
+ );
+
it.live("does not orphan an in-flight scan when its first caller is interrupted", () =>
Effect.gen(function* () {
const { settings, home } = yield* setup;
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index 16a7478d954..7c446ae14f9 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -18,6 +18,7 @@ import {
USAGE_CONTRACT_VERSION,
type UsageProviderKind,
type UsageSource,
+ type UsagePricing,
type UsageSummary,
type UsageSummaryInput,
UsageReadError,
@@ -34,6 +35,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ServerConfig } from "../config.ts";
@@ -63,6 +65,9 @@ const LITELLM_RATES_URL =
/** Rates move rarely; a day-old table keeps the page working offline. */
const RATES_TTL_MS = 24 * 60 * 60 * 1000;
+/** An explicit refresh ignores the TTL, but not a table fetched this recently. */
+const RATES_REFRESH_FLOOR_MS = 60 * 1000;
+
/**
* Files are filtered by mtime before opening. The slack covers a session whose
* last write lands just before local midnight on the window's first day.
@@ -94,9 +99,18 @@ export class UsageService extends Context.Service<
UsageService,
{
readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
+ /** Refetches the rate table ahead of its TTL. See `ensureRates`. */
+ readonly refreshRates: Effect.Effect<UsagePricing>;
}
>()("t3/usage/UsageService") {}
+const EMPTY_PRICING: UsagePricing = {
+ status: "unavailable",
+ source: LITELLM_RATES_URL,
+ fetchedAt: null,
+ knownModels: 0,
+};
+
/** Empty summary, for suites that only need the RPC surface to resolve. */
export const layerTest = Layer.succeed(
UsageService,
@@ -110,14 +124,10 @@ export const layerTest = Layer.succeed(
untilDay: input.untilDay,
buckets: [],
sources: [],
- pricing: {
- status: "unavailable",
- source: LITELLM_RATES_URL,
- fetchedAt: null,
- knownModels: 0,
- },
+ pricing: EMPTY_PRICING,
scanDurationMs: 0,
}),
+ refreshRates: Effect.succeed(EMPTY_PRICING),
}),
);
@@ -136,16 +146,29 @@ export const make = Effect.gen(function* () {
const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
let rates: RateTable = new Map();
let ratesFetchedAtMs: number | null = null;
- let ratesStatus: UsageSummary["pricing"]["status"] = "unavailable";
+ let ratesStatus: UsagePricing["status"] = "unavailable";
+ // One fetch at a time. A burst of refreshes from several clients waits on
+ // the first fetch and then sees a table young enough to skip its own.
+ const ratesLock = yield* Semaphore.make(1);
+
+ const pricing = (): UsagePricing => ({
+ status: ratesStatus,
+ source: LITELLM_RATES_URL,
+ fetchedAt:
+ ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
+ knownModels: rates.size,
+ });
/**
* Loads the LiteLLM rate table, preferring a fresh copy and falling back to
* the on-disk snapshot. With neither, every model reports as unpriced rather
- * than the page failing.
+ * than the page failing. `force` refetches inside the TTL so a model that
+ * LiteLLM added since the last fetch gets priced now.
*/
- const ensureRates = Effect.fn("UsageService.ensureRates")(function* () {
+ const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
const now = yield* Clock.currentTimeMillis;
- if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < RATES_TTL_MS) return;
+ const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
+ if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
if (ratesFetchedAtMs === null) {
const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
@@ -158,7 +181,7 @@ export const make = Effect.gen(function* () {
rates = parsed;
ratesFetchedAtMs = fromDisk.fetchedAtMs;
ratesStatus = "cached";
- if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return;
+ if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
}
}
}
@@ -189,6 +212,13 @@ export const make = Effect.gen(function* () {
);
});
+ const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
+
+ const refreshRates = ensureRates(true).pipe(
+ Effect.map(pricing),
+ Effect.withSpan("UsageService.refreshRates"),
+ );
+
/**
* Claude's config dir is the home itself when overridden, but a default
* install nests transcripts under `~/.claude/projects`. Probe both.
@@ -425,7 +455,7 @@ export const make = Effect.gen(function* () {
// Pricing only matters once records are aggregated, so the rate table
// loads while transcripts stream instead of gating them: a cold rates
// fetch on a slow network no longer delays the scan by its own timeout.
- const [, scannedDirs] = yield* Effect.all([ensureRates(), collectDirs(windowStartMs)], {
+ const [, scannedDirs] = yield* Effect.all([ensureRates(false), collectDirs(windowStartMs)], {
concurrency: 2,
});
@@ -511,15 +541,7 @@ export const make = Effect.gen(function* () {
untilDay: input.untilDay,
buckets: aggregated.buckets,
sources,
- pricing: {
- status: ratesStatus,
- source: LITELLM_RATES_URL,
- fetchedAt:
- ratesFetchedAtMs === null
- ? null
- : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
- knownModels: rates.size,
- },
+ pricing: pricing(),
scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
} satisfies UsageSummary;
});
@@ -570,7 +592,7 @@ export const make = Effect.gen(function* () {
return yield* Deferred.await(deferred);
});
- return { readSummary } as const;
+ return { readSummary, refreshRates } as const;
});
export const layer = Layer.effect(UsageService, make);
diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts
index 2ea27375b14..45113414f69 100644
--- a/apps/server/src/usage/usagePricing.test.ts
+++ b/apps/server/src/usage/usagePricing.test.ts
@@ -31,6 +31,15 @@ describe("usage pricing", () => {
}
});
+ it("prices a bracketed context-tier variant at the base model's rate", () => {
+ const table = parseRateTable({ "claude-fable-5-1": rate(1e-5, 2.5e-7) });
+
+ expect(lookupRate(table, "claude-fable-5-1[1m]")).toEqual(
+ lookupRate(table, "claude-fable-5-1"),
+ );
+ expect(lookupRate(table, "anthropic/Claude-Fable-5-1[1m]")).toBeNull();
+ });
+
it("adds a bare alias when every qualified entry has the same rate", () => {
const table = parseRateTable({
"provider-a/example-model": rate(1),
diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts
index 3d7f5fd2948..a7beecb1f55 100644
--- a/apps/server/src/usage/usagePricing.ts
+++ b/apps/server/src/usage/usagePricing.ts
@@ -119,6 +119,16 @@ function bareModelName(key: string): string {
return slash === -1 ? key : key.slice(slash + 1);
}
+/**
+ * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which
+ * Claude Code writes for the 1M context tier. The rate table only knows the
+ * base name, and we price at the base tier anyway.
+ */
+function stripVariantSuffix(key: string): string {
+ const bracket = key.indexOf("[");
+ return bracket === -1 ? key : key.slice(0, bracket);
+}
+
/**
* Models we never price, regardless of the table.
*
@@ -136,7 +146,7 @@ const UNPRICEABLE_MODELS = new Set([
]);
export function lookupRate(table: RateTable, model: string): ModelRate | null {
- const key = normalizeRateKey(model);
+ const key = stripVariantSuffix(normalizeRateKey(model));
const bareName = bareModelName(key);
if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
return table.get(key) ?? null;
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index d47ba60630e..839937cf2ea 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1899,6 +1899,10 @@ const makeWsRpcLayer = (
observeRpcEffect(WS_METHODS.serverGetUsageSummary, usage.readSummary(input), {
"rpc.aggregate": "server",
}),
+ [WS_METHODS.serverRefreshUsageRates]: (_input) =>
+ observeRpcEffect(WS_METHODS.serverRefreshUsageRates, usage.refreshRates, {
+ "rpc.aggregate": "server",
+ }),
[WS_METHODS.serverRetryResourceTelemetry]: (_input) =>
observeRpcEffect(WS_METHODS.serverRetryResourceTelemetry, resourceTelemetry.retry, {
"rpc.aggregate": "server",
diff --git a/apps/web/src/state/usage.ts b/apps/web/src/state/usage.ts
index ba78a61d8a8..359be7d7983 100644
--- a/apps/web/src/state/usage.ts
+++ b/apps/web/src/state/usage.ts
@@ -13,6 +13,7 @@ import {
type UsageSummary,
type UsageSummaryInput,
} from "@t3tools/contracts";
+import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
@@ -97,12 +98,21 @@ export function useUsage(input: UsageSummaryInput): UsageView {
// Refreshing only the derived atom would re-read the per-environment SWR
// queries within their stale window and change nothing. Refresh each
// environment's query so the button always rescans.
+ //
+ // Each environment refetches model pricing first, so a model released since
+ // its last daily fetch gets priced by the rescan. The rescan runs whether or
+ // not the refetch succeeds: an offline environment still recounts tokens.
const refresh = useCallback(() => {
const input = JSON.parse(windowKey) as UsageSummaryInput;
for (const environment of environments) {
- appAtomRegistry.refresh(
- serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
- );
+ const { environmentId } = environment;
+ const query = serverEnvironment.usageSummary({ environmentId, input });
+ void runAtomCommand(
+ appAtomRegistry,
+ serverEnvironment.refreshUsageRates,
+ { environmentId, input: {} },
+ { reportFailure: false },
+ ).finally(() => appAtomRegistry.refresh(query));
}
}, [environments, windowKey]);
diff --git a/docs/user/usage.md b/docs/user/usage.md
index ff38c730c1c..24e2d6a575c 100644
--- a/docs/user/usage.md
+++ b/docs/user/usage.md
@@ -10,4 +10,6 @@ completed-turn record will not appear.
Use **Past 24h** for an hourly chart covering the exact rolling 24-hour period. The **7 days**,
**30 days**, and **90 days** ranges use daily resolution. Cost and token toggles update both the
-headline and chart, and refreshing rescans every connected environment.
+headline and chart. Refreshing rescans every connected environment and refetches model pricing on
+each of them, so a newly released model that showed $0.00 gets a price without waiting for the daily
+pricing update.
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 448aa2f2acb..120432e8190 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -933,6 +933,14 @@ export function createServerEnvironmentAtoms<R, E>(
label: "environment-data:server:signal-process",
tag: WS_METHODS.serverSignalProcess,
}),
+ refreshUsageRates: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:refresh-usage-rates",
+ tag: WS_METHODS.serverRefreshUsageRates,
+ concurrency: {
+ mode: "singleFlight",
+ key: ({ environmentId }) => environmentId,
+ },
+ }),
retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:retry-resource-telemetry",
tag: WS_METHODS.serverRetryResourceTelemetry,
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index f333d6af94d..9b2953a6009 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -206,7 +206,7 @@ import {
ResourceTelemetryRetryResult,
ResourceTelemetrySnapshot,
} from "./resourceTelemetry.ts";
-import { UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
+import { UsagePricing, UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
import {
SourceControlCloneRepositoryInput,
@@ -315,6 +315,7 @@ export const WS_METHODS = {
serverReportHostPowerState: "server.reportHostPowerState",
serverGetBackgroundPolicy: "server.getBackgroundPolicy",
serverGetUsageSummary: "server.getUsageSummary",
+ serverRefreshUsageRates: "server.refreshUsageRates",
// Cloud environment methods
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
@@ -547,6 +548,16 @@ export const WsServerGetUsageSummaryRpc = Rpc.make(WS_METHODS.serverGetUsageSumm
error: Schema.Union([EnvironmentAuthorizationError, UsageReadError]),
});
+/**
+ * Refetches the model rate table ahead of its daily TTL, so a model released
+ * since the last fetch gets priced. The next usage summary uses the new table.
+ */
+export const WsServerRefreshUsageRatesRpc = Rpc.make(WS_METHODS.serverRefreshUsageRates, {
+ payload: Schema.Struct({}),
+ success: UsagePricing,
+ error: EnvironmentAuthorizationError,
+});
+
export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess, {
payload: ServerSignalProcessInput,
success: ServerSignalProcessResult,
@@ -1167,6 +1178,7 @@ export const WsRpcGroup = RpcGroup.make(
WsServerGetResourceTelemetryHistoryRpc,
WsServerRetryResourceTelemetryRpc,
WsServerGetUsageSummaryRpc,
+ WsServerRefreshUsageRatesRpc,
WsServerSignalProcessRpc,
WsServerReportClientActivityRpc,
WsServerReportHostPowerStateRpc,