Skip to content

Commit 1afd2b3

Browse files
feat(server): record how each account's usage limits change, and every reset
A history service listens to the provider registry and appends changed readings to usage-limit-history.jsonl in the state directory. A drop in a window's usage is logged as a reset, with what was left unused and whether it came before the announced time. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3b67088 commit 1afd2b3

9 files changed

Lines changed: 475 additions & 1 deletion

File tree

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ export const RPC_REQUIRED_SCOPES = {
108108
[WS_METHODS.serverRetryResourceTelemetry]: AuthDiagnosticsReadScope,
109109
[WS_METHODS.serverGetUsageSummary]: AuthDiagnosticsReadScope,
110110
[WS_METHODS.serverRefreshUsageRates]: AuthDiagnosticsReadScope,
111+
[WS_METHODS.serverGetUsageLimitHistory]: AuthDiagnosticsReadScope,
111112
[WS_METHODS.serverSignalProcess]: AuthEnvironmentMaintainScope,
112113
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
113114
[WS_METHODS.serverReportHostPowerState]: AuthEnvironmentMaintainScope,

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ const RPC_AGGREGATES = {
7878
[WS_METHODS.serverRetryResourceTelemetry]: "server",
7979
[WS_METHODS.serverGetUsageSummary]: "server",
8080
[WS_METHODS.serverRefreshUsageRates]: "server",
81+
[WS_METHODS.serverGetUsageLimitHistory]: "server",
8182
[WS_METHODS.serverSignalProcess]: "server",
8283
[WS_METHODS.serverReportClientActivity]: "server",
8384
[WS_METHODS.serverReportHostPowerState]: "server",

‎apps/server/src/server.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.t
8484
import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegistry.ts";
8585
import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
8686
import * as ProviderUsageLimitsIngestion from "./provider/ProviderUsageLimitsIngestion.ts";
87+
import * as UsageLimitHistory from "./usage/UsageLimitHistory.ts";
8788
import * as UsageLimitSources from "./usage/UsageLimitSources.ts";
8889
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
8990
import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
@@ -592,7 +593,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
592593
// Both read a user-owned file out of the state directory and stream changes
593594
// to clients; neither depends on the other.
594595
Layer.provideMerge(
595-
Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer),
596+
Layer.mergeAll(
597+
Keybindings.layer,
598+
EnvironmentTheme.layer,
599+
UsageLimitSources.layer,
600+
UsageLimitHistory.layer,
601+
),
596602
),
597603
Layer.provideMerge(ProviderRegistry.layer),
598604
// The instance registry is the new routing keystone — text generation,
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/**
2+
* Keeps the history of every account's quota windows: how the allowance was
3+
* used over time, and what was left each time a window reset.
4+
*
5+
* It listens to the provider registry, so it records whatever the usage
6+
* probes already read and adds no probing of its own. The history is an
7+
* append-only file in the state directory, one JSON object per line.
8+
*
9+
* @module UsageLimitHistory
10+
*/
11+
import {
12+
UsageLimitHistoryPoint,
13+
UsageLimitReset,
14+
type ServerProvider,
15+
type UsageLimitHistory as UsageLimitHistoryResult,
16+
type UsageLimitHistoryInput,
17+
} from "@t3tools/contracts";
18+
import * as Clock from "effect/Clock";
19+
import * as Context from "effect/Context";
20+
import * as Effect from "effect/Effect";
21+
import * as FileSystem from "effect/FileSystem";
22+
import * as Layer from "effect/Layer";
23+
import * as Path from "effect/Path";
24+
import * as Schema from "effect/Schema";
25+
import * as Semaphore from "effect/Semaphore";
26+
import * as Stream from "effect/Stream";
27+
28+
import * as ServerConfig from "../config.ts";
29+
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
30+
import {
31+
recordUsageLimitReadings,
32+
usageLimitWindowKey,
33+
type UsageLimitReadingState,
34+
} from "./usageLimitReadings.ts";
35+
36+
export const USAGE_LIMIT_HISTORY_FILE_NAME = "usage-limit-history.jsonl";
37+
38+
/** Long enough to compare a few monthly windows; older lines are dropped at startup. */
39+
const RETENTION_MS = 120 * 24 * 60 * 60_000;
40+
41+
const HistoryLine = Schema.Union([
42+
Schema.Struct({ point: UsageLimitHistoryPoint }),
43+
Schema.Struct({ reset: UsageLimitReset }),
44+
]);
45+
type HistoryLine = typeof HistoryLine.Type;
46+
const decodeLine = Schema.decodeUnknownOption(Schema.fromJsonString(HistoryLine));
47+
const encodeLine = Schema.encodeSync(Schema.fromJsonString(HistoryLine));
48+
49+
export class UsageLimitHistory extends Context.Service<
50+
UsageLimitHistory,
51+
{
52+
/** Points and resets at or after `since`, oldest first. */
53+
readonly read: (input: UsageLimitHistoryInput) => Effect.Effect<UsageLimitHistoryResult>;
54+
}
55+
>()("t3/usage/UsageLimitHistory") {}
56+
57+
/** What a history file holds, with unreadable and expired lines left out. */
58+
export function parseUsageLimitHistory(
59+
contents: string,
60+
nowMs: number,
61+
): { readonly points: UsageLimitHistoryPoint[]; readonly resets: UsageLimitReset[] } {
62+
const points: UsageLimitHistoryPoint[] = [];
63+
const resets: UsageLimitReset[] = [];
64+
for (const raw of contents.split("\n")) {
65+
if (raw.trim() === "") continue;
66+
const line = decodeLine(raw);
67+
if (line._tag === "None") continue;
68+
const entry = line.value;
69+
const at = "point" in entry ? entry.point.at : entry.reset.at;
70+
if (nowMs - Date.parse(at) > RETENTION_MS) continue;
71+
if ("point" in entry) points.push(entry.point);
72+
else resets.push(entry.reset);
73+
}
74+
return { points, resets };
75+
}
76+
77+
function serialize(lines: ReadonlyArray<HistoryLine>): string {
78+
return lines.map((line) => `${encodeLine(line)}\n`).join("");
79+
}
80+
81+
export const make = Effect.gen(function* () {
82+
const fileSystem = yield* FileSystem.FileSystem;
83+
const path = yield* Path.Path;
84+
const config = yield* ServerConfig.ServerConfig;
85+
const registry = yield* ProviderRegistry.ProviderRegistry;
86+
const filePath = path.join(config.stateDir, USAGE_LIMIT_HISTORY_FILE_NAME);
87+
88+
const existing = yield* fileSystem.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
89+
const loaded = parseUsageLimitHistory(existing, yield* Clock.currentTimeMillis);
90+
const points = loaded.points;
91+
const resets = loaded.resets;
92+
let state: UsageLimitReadingState = new Map(
93+
points.map((point) => [usageLimitWindowKey(point), point]),
94+
);
95+
// Rewrite once at startup when lines expired or could not be read, so the
96+
// file never grows past the retention window.
97+
const kept = serialize([
98+
...points.map((point) => ({ point })),
99+
...resets.map((reset) => ({ reset })),
100+
]);
101+
if (existing !== "" && kept.length < existing.length) {
102+
yield* fileSystem.writeFileString(filePath, kept).pipe(Effect.ignore);
103+
}
104+
105+
const lock = yield* Semaphore.make(1);
106+
const record = (providers: ReadonlyArray<ServerProvider>) =>
107+
lock.withPermits(1)(
108+
Effect.gen(function* () {
109+
const delta = recordUsageLimitReadings(state, providers);
110+
if (delta.points.length === 0) return;
111+
state = delta.state;
112+
points.push(...delta.points);
113+
resets.push(...delta.resets);
114+
// History is a convenience; a full disk must not take usage limits down with it.
115+
yield* fileSystem
116+
.writeFileString(
117+
filePath,
118+
serialize([
119+
...delta.points.map((point) => ({ point })),
120+
...delta.resets.map((reset) => ({ reset })),
121+
]),
122+
{ flag: "a" },
123+
)
124+
.pipe(
125+
Effect.catch((cause) =>
126+
Effect.logWarning("Could not append to the usage limit history", cause),
127+
),
128+
);
129+
}),
130+
);
131+
132+
yield* Stream.runForEach(registry.streamChanges, record).pipe(Effect.forkScoped);
133+
yield* registry.getProviders.pipe(Effect.flatMap(record));
134+
135+
return UsageLimitHistory.of({
136+
read: (input) =>
137+
Effect.sync(() => {
138+
const sinceMs = Date.parse(input.since);
139+
return {
140+
points: points.filter((point) => Date.parse(point.at) >= sinceMs),
141+
resets: resets.filter((reset) => Date.parse(reset.at) >= sinceMs),
142+
};
143+
}),
144+
});
145+
});
146+
147+
export const layer = Layer.effect(UsageLimitHistory, make);
148+
149+
/** Empty history, for suites that only need the RPC surface to resolve. */
150+
export const layerTest = Layer.succeed(
151+
UsageLimitHistory,
152+
UsageLimitHistory.of({ read: () => Effect.succeed({ points: [], resets: [] }) }),
153+
);
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import { ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
3+
4+
import { recordUsageLimitReadings, type UsageLimitReadingState } from "./usageLimitReadings.ts";
5+
6+
type Reading = Pick<ServerProvider, "instanceId" | "usageLimits">;
7+
8+
function reading(
9+
at: string,
10+
weeklyUsed: number,
11+
weeklyResetsAt: string | undefined,
12+
instanceId = "codex",
13+
): Reading {
14+
return {
15+
instanceId: ProviderInstanceId.make(instanceId),
16+
usageLimits: {
17+
checkedAt: at,
18+
windows: [
19+
{
20+
id: "secondary",
21+
kind: "weekly",
22+
label: "Weekly",
23+
usedPercent: weeklyUsed,
24+
...(weeklyResetsAt === undefined ? {} : { resetsAt: weeklyResetsAt }),
25+
},
26+
],
27+
},
28+
};
29+
}
30+
31+
function replay(readings: ReadonlyArray<ReadonlyArray<Reading>>) {
32+
let state: UsageLimitReadingState = new Map();
33+
const points = [];
34+
const resets = [];
35+
for (const providers of readings) {
36+
const delta = recordUsageLimitReadings(state, providers);
37+
state = delta.state;
38+
points.push(...delta.points);
39+
resets.push(...delta.resets);
40+
}
41+
return { points, resets };
42+
}
43+
44+
const RESET = "2026-10-14T02:00:00.000Z";
45+
const NEXT_RESET = "2026-10-21T02:00:00.000Z";
46+
47+
describe("recordUsageLimitReadings", () => {
48+
it("records a point only when a window's reading changes", () => {
49+
const { points, resets } = replay([
50+
[reading("2026-10-10T10:00:00.000Z", 40, RESET)],
51+
[reading("2026-10-10T10:05:00.000Z", 40, RESET)],
52+
[reading("2026-10-10T10:10:00.000Z", 43, RESET)],
53+
]);
54+
expect(points.map((point) => [point.at, point.usedPercent])).toEqual([
55+
["2026-10-10T10:00:00.000Z", 40],
56+
["2026-10-10T10:10:00.000Z", 43],
57+
]);
58+
expect(resets).toEqual([]);
59+
});
60+
61+
it("does not record a reset time that only wanders by seconds", () => {
62+
const { points } = replay([
63+
[reading("2026-10-10T10:00:00.000Z", 40, "2026-10-14T02:00:00.100Z")],
64+
[reading("2026-10-10T10:05:00.000Z", 40, "2026-10-14T02:00:03.900Z")],
65+
]);
66+
expect(points).toHaveLength(1);
67+
});
68+
69+
it("logs an early reset with what was left unused", () => {
70+
const { resets } = replay([
71+
[reading("2026-10-11T08:00:00.000Z", 62, RESET)],
72+
[reading("2026-10-11T08:05:00.000Z", 0, NEXT_RESET)],
73+
]);
74+
expect(resets).toEqual([
75+
{
76+
at: "2026-10-11T08:05:00.000Z",
77+
instanceId: "codex",
78+
windowId: "secondary",
79+
kind: "weekly",
80+
label: "Weekly",
81+
usedPercentBefore: 62,
82+
unusedPercentBefore: 38,
83+
usedPercentAfter: 0,
84+
lastSeenBeforeAt: "2026-10-11T08:00:00.000Z",
85+
expectedAt: RESET,
86+
ahead: true,
87+
},
88+
]);
89+
});
90+
91+
it("treats a reset at its announced time, or without one, as on schedule", () => {
92+
const onTime = replay([
93+
[reading("2026-10-14T01:55:00.000Z", 97, RESET)],
94+
[reading("2026-10-14T02:03:00.000Z", 1, NEXT_RESET)],
95+
]);
96+
expect(onTime.resets.map((reset) => [reset.ahead, reset.unusedPercentBefore])).toEqual([
97+
[false, 3],
98+
]);
99+
const unknown = replay([
100+
[reading("2026-10-11T08:00:00.000Z", 50, undefined)],
101+
[reading("2026-10-11T09:00:00.000Z", 5, undefined)],
102+
]);
103+
expect(unknown.resets.map((reset) => reset.ahead)).toEqual([false]);
104+
});
105+
106+
it("ignores failed probes, stale reads, and jitter below one percent", () => {
107+
const failed: Reading = {
108+
instanceId: ProviderInstanceId.make("codex"),
109+
usageLimits: {
110+
checkedAt: "2026-10-10T10:20:00.000Z",
111+
windows: [],
112+
unavailable: { reason: "probeFailed" },
113+
},
114+
};
115+
const { points, resets } = replay([
116+
[reading("2026-10-10T10:00:00.000Z", 40, RESET)],
117+
[failed],
118+
[reading("2026-10-10T09:00:00.000Z", 10, RESET)],
119+
[reading("2026-10-10T10:30:00.000Z", 39.6, RESET)],
120+
]);
121+
expect(points.map((point) => point.usedPercent)).toEqual([40, 39.6]);
122+
expect(resets).toEqual([]);
123+
});
124+
125+
it("keeps accounts apart", () => {
126+
const { resets } = replay([
127+
[
128+
reading("2026-10-11T08:00:00.000Z", 80, RESET, "codex"),
129+
reading("2026-10-11T08:00:00.000Z", 5, RESET, "codex_personal"),
130+
],
131+
[
132+
reading("2026-10-11T08:05:00.000Z", 81, RESET, "codex"),
133+
reading("2026-10-11T08:05:00.000Z", 0, NEXT_RESET, "codex_personal"),
134+
],
135+
]);
136+
expect(resets.map((reset) => [reset.instanceId, reset.unusedPercentBefore])).toEqual([
137+
["codex_personal", 95],
138+
]);
139+
});
140+
});

0 commit comments

Comments
 (0)