From ae37ed728b31f78c2a61a30188c7faa266760f4e Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Fri, 7 Aug 2026 07:22:18 -0700 Subject: [PATCH] fix(server): bound the usage cache and stop latching Codex fast pricing Adds an end-to-end usage endpoint test and a T3CODE_AGENT_LOG_HOME override so agent log reads can be isolated. Co-Authored-By: Claude Opus 5 (1M context) --- apps/server/src/server.test.ts | 45 +++++++++++++++++++ apps/server/src/usage/UsageService.ts | 28 +++++++++++- apps/server/src/usage/localAgentUsage.test.ts | 16 +++++++ apps/server/src/usage/localAgentUsage.ts | 4 +- 4 files changed, 91 insertions(+), 2 deletions(-) diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 4ddb01e09d..1f6b00abb1 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -3326,6 +3326,51 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.scoped, Effect.provide(NodeHttpServerTestWithWsDeflate)), ); + it.effect("serves a usage snapshot to an authenticated session", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const bearerToken = yield* getAuthenticatedBearerSessionToken(); + const usageUrl = yield* getHttpServerUrl("/api/usage/snapshot?sinceDate=2020-01-01"); + const response = yield* fetchEffect(usageUrl, { + headers: { authorization: `Bearer ${bearerToken}` }, + }); + assert.equal(response.status, 200); + + const body = yield* responseJsonEffect<{ + readonly environmentId: string; + readonly costUsd: number; + readonly models: ReadonlyArray; + readonly activity: { readonly turnsByHour: ReadonlyArray }; + readonly sources: ReadonlyArray<{ readonly provider: string }>; + }>(response); + + // Asserts the contract shape rather than values: this reads whatever + // agent logs the host actually has, which is empty on CI and populated on + // a developer machine. Both must produce a well-formed snapshot. + assert.isString(body.environmentId); + assert.isAtLeast(body.costUsd, 0); + assert.isArray(body.models); + assert.equal(body.activity.turnsByHour.length, 24); + // Both slots always report, so the client can tell "nothing used" from + // "provider not installed on this host". + assert.deepEqual(body.sources.map((source) => source.provider).toSorted(), [ + "claude", + "codex", + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects an unauthenticated usage snapshot request", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const usageUrl = yield* getHttpServerUrl("/api/usage/snapshot"); + const response = yield* fetchEffect(usageUrl); + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect("issues short-lived websocket tickets for authenticated bearer sessions", () => Effect.gen(function* () { yield* buildAppUnderTest(); diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 59415c7a46..34a3af5386 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -1,10 +1,12 @@ import type { EnvironmentUsageSnapshot } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; @@ -15,6 +17,8 @@ import { readLocalAgentUsage } from "./localAgentUsage.ts"; const CACHE_TTL_MILLIS = Duration.toMillis(Duration.seconds(60)); const DEFAULT_WINDOW_DAYS = 30; const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/; +/** Distinct windows a client realistically asks for; anything past this evicts oldest-first. */ +const MAX_CACHE_ENTRIES = 8; const emptyTokens = { inputTokens: 0, @@ -35,6 +39,10 @@ export class UsageService extends Context.Service< export const make = Effect.gen(function* () { const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + // Agent session logs live under the OS home, not the server's base directory, + // so isolating them needs an explicit override. Tests and sandboxed runs set + // this; in normal operation it is absent and the OS home is used. + const agentLogHome = yield* Config.string("T3CODE_AGENT_LOG_HOME").pipe(Config.option); // Captured once so the returned effects carry no outstanding requirements. const sql = yield* SqlClient.SqlClient; @@ -55,7 +63,12 @@ export const make = Effect.gen(function* () { const activity = yield* readActivitySummary(`${sinceDate}T00:00:00.000Z`).pipe( Effect.provideService(SqlClient.SqlClient, sql), ); - const local = yield* Effect.tryPromise(() => readLocalAgentUsage({ sinceDate })).pipe( + const local = yield* Effect.tryPromise(() => + readLocalAgentUsage({ + sinceDate, + ...(Option.isSome(agentLogHome) ? { homeDir: agentLogHome.value } : {}), + }), + ).pipe( Effect.catchCause((cause) => Effect.logWarning("Failed to read local agent usage logs", { cause }).pipe( Effect.as(undefined), @@ -98,12 +111,25 @@ export const make = Effect.gen(function* () { if (cached !== undefined && startedAt - cached.at < CACHE_TTL_MILLIS) { return cached.snapshot; } + // Callers choose the window, so evict expired entries before inserting; + // otherwise one entry accumulates per distinct date string and the map + // grows without bound. + for (const [key, entry] of cache) { + if (startedAt - entry.at >= CACHE_TTL_MILLIS) cache.delete(key); + } + const { snapshot, complete } = yield* build(resolved); // Only cache a complete read, and stamp it on completion so a slow // scan does not immediately expire. A failed scan reports zeros once // rather than pinning the page at $0 for the whole TTL. if (complete) { const finishedAt = yield* Clock.currentTimeMillis; + // Bounded even within one TTL window, so a burst of distinct dates + // cannot pin unbounded memory until the entries age out. + if (cache.size >= MAX_CACHE_ENTRIES) { + const oldest = cache.keys().next(); + if (!oldest.done) cache.delete(oldest.value); + } cache.set(resolved, { at: finishedAt, snapshot }); } return snapshot; diff --git a/apps/server/src/usage/localAgentUsage.test.ts b/apps/server/src/usage/localAgentUsage.test.ts index 42b6e95987..e2baf26891 100644 --- a/apps/server/src/usage/localAgentUsage.test.ts +++ b/apps/server/src/usage/localAgentUsage.test.ts @@ -221,6 +221,22 @@ describe("readLocalAgentUsage", () => { expect(result.costUsd).toBeCloseTo(pricing!.input, 6); }); + it("does not latch fast pricing onto standard turns later in the same session", async () => { + const result = await withFixture(async ({ codex }) => { + await write(NodePath.join(codex, "2099", "s.jsonl"), [ + { type: "turn_context", payload: { model: "gpt-5.6-sol", service_tier: "priority" } }, + codexTokenCount({ input: 1_000_000, cached: 0, output: 0 }), + // Back to standard: this turn must not inherit the premium multiplier. + { type: "turn_context", payload: { model: "gpt-5.6-sol", service_tier: "default" } }, + codexTokenCount({ input: 2_000_000, cached: 0, output: 0 }), + ]); + }); + + const pricing = lookupPricing("gpt-5.6-sol"); + // First 1M at the doubled rate, second 1M at the base rate. + expect(result.costUsd).toBeCloseTo(pricing!.input * 2 + pricing!.input, 6); + }); + it("resolves a dated model slug to its family but not an unrelated slug", () => { expect(lookupPricing("claude-haiku-4-5-20251001")).toEqual(lookupPricing("claude-haiku-4-5")); // `gpt-5000` starts with `gpt-5` but is a different model, not a variant. diff --git a/apps/server/src/usage/localAgentUsage.ts b/apps/server/src/usage/localAgentUsage.ts index 7adb610e4d..17efb621f5 100644 --- a/apps/server/src/usage/localAgentUsage.ts +++ b/apps/server/src/usage/localAgentUsage.ts @@ -357,8 +357,10 @@ async function scanCodex( if (typeof candidate === "string" && candidate.length > 0) model = candidate; const candidateCwd = payloadRecord?.["cwd"]; if (typeof candidateCwd === "string") cwd = candidateCwd; + // Recomputed per turn rather than latched: a session can mix tiers, and + // a premium turn must not price the standard turns that follow it. const tier = payloadRecord?.["service_tier"]; - if (typeof tier === "string") fast = tier === "fast" || tier === "priority"; + fast = tier === "fast" || tier === "priority"; } if (payloadRecord?.["type"] !== "token_count") continue;