GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(usage): refetch cached rates early for a model they do not list (… · pingdotgg/t3code@ed01784

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src/usage
    • UsageService.test.ts
    • UsageService.ts
    • usagePricing.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/usage/UsageService.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/usage/UsageService.test.ts
+50Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3771,6 +3771,56 @@ describe("UsageService", () => {
37713771
}),
37723772
);
37733773

3774+
it.effect("refetches cached rates early for a model they do not list", () =>
3775+
Effect.gen(function* () {
3776+
yield* TestClock.setTime(Date.parse("2026-08-02T00:00:00Z"));
3777+
const { transcript, settings, home } = yield* setup;
3778+
yield* Effect.promise(() =>
3779+
NodeFSP.writeFile(
3780+
transcript,
3781+
claudeLine(1, 5, "claude-new-model") + claudeLine(2, 5, "claude-unknown-model"),
3782+
),
3783+
);
3784+
const requests: string[] = [];
3785+
let ratesDocument: Record<string, unknown> = {
3786+
"claude-fable-5": { input_cost_per_token: 1e-5, output_cost_per_token: 5e-5 },
3787+
};
3788+
const serviceLayer = layerService({
3789+
prefix: "usage-service-unlisted-model-test",
3790+
home,
3791+
settings,
3792+
onRatesFetch: (request) => requests.push(request.url),
3793+
ratesResponse: () => Effect.succeed(Response.json(ratesDocument)),
3794+
});
3795+
const newModelCost = (summary: UsageSummary) =>
3796+
summary.buckets.find((bucket) => bucket.model === "claude-new-model")?.costUsd;
3797+
3798+
// Rates fetched for this scan are fresh: no second request for the models they lack.
3799+
const first = yield* (yield* UsageService.make.pipe(
3800+
Effect.provide(serviceLayer),
3801+
)).readSummary(WINDOW);
3802+
assert.strictEqual(newModelCost(first), 0);
3803+
assert.strictEqual(requests.length, 1);
3804+
3805+
// An hour later LiteLLM lists the new model; a restarted server starts from the cached table.
3806+
ratesDocument = {
3807+
...ratesDocument,
3808+
"claude-new-model": { input_cost_per_token: 2e-5, output_cost_per_token: 1e-4 },
3809+
};
3810+
yield* TestClock.adjust(Duration.hours(1));
3811+
const service = yield* UsageService.make.pipe(Effect.provide(serviceLayer));
3812+
const refreshed = yield* service.readSummary(WINDOW);
3813+
assert.strictEqual(refreshed.pricing.status, "fresh");
3814+
assert.closeTo(newModelCost(refreshed) ?? -1, 10 * 2e-5 + 5 * 1e-4, 1e-12);
3815+
assert.strictEqual(requests.length, 2);
3816+
3817+
// A model the fresh table still lacks does not refetch again before the TTL.
3818+
yield* TestClock.adjust(Duration.hours(1));
3819+
yield* service.readSummary(WINDOW);
3820+
assert.strictEqual(requests.length, 2);
3821+
}),
3822+
);
3823+
37743824
it.effect("does not orphan an in-flight scan when its first caller is interrupted", () =>
37753825
Effect.gen(function* () {
37763826
const { settings, home } = yield* setup;
Collapse file

‎apps/server/src/usage/UsageService.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/usage/UsageService.ts
+56-14Lines changed: 56 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,12 @@ import type {
4040
UsageRecord,
4141
} from "@t3tools/provider-core/server/usage";
4242
import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
43-
import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
43+
import {
44+
createOverrideRateTable,
45+
isUnlistedModel,
46+
parseRateTable,
47+
type RateTable,
48+
} from "./usagePricing.ts";
4449
import {
4550
DESKTOP_HOST_SCOPE_ENV,
4651
listTranscriptFiles,
@@ -312,6 +317,24 @@ export const make = Effect.gen(function* () {
312317

313318
const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
314319

320+
// Rates are kept for RATES_TTL_MS, so a model released after the table was fetched would stay unpriced
321+
// that long. A scan that meets a model the table does not list refetches early: once per model against
322+
// a fresh table, with loadRates keeping RATES_REFRESH_FLOOR_MS between attempts.
323+
const checkedUnlistedModels = new Set<string>();
324+
const refreshForUnlistedModels = Effect.fn("UsageService.refreshForUnlistedModels")(function* (
325+
models: ReadonlySet<string>,
326+
) {
327+
const unlisted = [...models].filter(
328+
(model) => !checkedUnlistedModels.has(model) && isUnlistedModel(rates, model),
329+
);
330+
if (unlisted.length === 0) return;
331+
yield* ensureRates(true);
332+
const now = yield* Clock.currentTimeMillis;
333+
// A failed fetch leaves the models unchecked, so a later scan tries again.
334+
if (ratesFetchedAtMs === null || now - ratesFetchedAtMs >= RATES_REFRESH_FLOOR_MS) return;
335+
for (const model of unlisted) checkedUnlistedModels.add(model);
336+
});
337+
315338
const refreshRates = ensureRates(true).pipe(
316339
Effect.map(pricing),
317340
Effect.withSpan("UsageService.refreshRates"),
@@ -881,19 +904,8 @@ export const make = Effect.gen(function* () {
881904
{ concurrency: 2 },
882905
);
883906

884-
const summaryPricing = pricing();
885-
const aggregator = new UsageAggregator({
886-
timeZone: input.timeZone,
887-
sinceDay: input.sinceDay,
888-
untilDay: input.untilDay,
889-
resolution: input.resolution ?? "day",
890-
...hourlyWindow,
891-
rates,
892-
priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
893-
modelAliases: resolveModelAliases(settings.usageModelAliases),
894-
...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
895-
});
896-
907+
const priceOverrides = createOverrideRateTable(settings.usagePriceOverrides);
908+
const modelAliases = resolveModelAliases(settings.usageModelAliases);
897909
const sources: UsageSource[] = [];
898910

899911
// Deleted transcripts' saved usage still aggregates and deduplicates normally.
@@ -959,6 +971,36 @@ export const make = Effect.gen(function* () {
959971
for (const filePath of ordered) fileCache.set(filePath, entries.get(filePath)!);
960972
cacheDirty = true;
961973
}
974+
975+
// The models priced below, as UsageAggregator resolves them: an alias replaces rateModel.
976+
const rateModels = new Set<string>();
977+
for (const files of filesByDir) {
978+
for (const file of files) {
979+
for (const record of file.records) {
980+
const alias = modelAliases.get(record.model);
981+
const model = alias ?? record.model;
982+
if (priceOverrides.has(model.trim())) continue;
983+
rateModels.add(alias === undefined ? (record.rateModel ?? model) : model);
984+
}
985+
}
986+
}
987+
// A saved answer prices with saved rates and the full scan after it refetches.
988+
if (!fromMemory) yield* refreshForUnlistedModels(rateModels);
989+
990+
const summaryPricing = pricing();
991+
992+
const aggregator = new UsageAggregator({
993+
timeZone: input.timeZone,
994+
sinceDay: input.sinceDay,
995+
untilDay: input.untilDay,
996+
resolution: input.resolution ?? "day",
997+
...hourlyWindow,
998+
rates,
999+
priceOverrides,
1000+
modelAliases,
1001+
...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
1002+
});
1003+
9621004
const windowEndMs =
9631005
hourlyWindow?.untilTimeMs ??
9641006
Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS;
Collapse file

‎apps/server/src/usage/usagePricing.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/usage/usagePricing.ts
+8Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,14 @@ export function lookupRate(table: RateTable, model: string): ModelRate | null {
310310
return rate;
311311
}
312312

313+
/** A priceable model the table has no rate for; a newer table may list it. */
314+
export function isUnlistedModel(table: RateTable, model: string): boolean {
315+
const bareName = bareModelName(stripVariantSuffix(normalizeRateKey(model)));
316+
return (
317+
bareName.length > 0 && !UNPRICEABLE_MODELS.has(bareName) && lookupRate(table, model) === null
318+
);
319+
}
320+
313321
function resolveRate(table: RateTable, model: string): ModelRate | null {
314322
const key = stripVariantSuffix(normalizeRateKey(model));
315323
const bareName = bareModelName(key);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.