Skip to content

Commit 233ccca

Browse files
fix(usage): weekly resets per subscription, without probe jitter or account switches
The reset log listed dozens of "resets" a day: two probes of one account round a point apart (90/91), and the default Claude instance switching accounts looked like a drop. A reset now needs a new window that began between the two readings (or an emptied window on an unchanged schedule), readings carry the signed-in account so each subscription keeps its own series, and resets are worked out from the recorded readings at startup, which also clears the false ones already logged. The Limits view groups by provider and email and lists only weekly resets, with the level before and when it was last read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c30f4ac commit 233ccca

8 files changed

Lines changed: 405 additions & 122 deletions

File tree

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

Lines changed: 21 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
*
55
* It listens to the provider registry, so it records whatever the usage
66
* 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.
7+
* append-only file of readings in the state directory, one JSON object per
8+
* line. Resets are worked out from the readings at startup, so a better rule
9+
* for telling a reset from noise also corrects the past.
810
*
911
* @module UsageLimitHistory
1012
*/
@@ -29,7 +31,7 @@ import * as ServerConfig from "../config.ts";
2931
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
3032
import {
3133
recordUsageLimitReadings,
32-
usageLimitWindowKey,
34+
replayUsageLimitPoints,
3335
type UsageLimitReadingState,
3436
} from "./usageLimitReadings.ts";
3537

@@ -38,11 +40,12 @@ export const USAGE_LIMIT_HISTORY_FILE_NAME = "usage-limit-history.jsonl";
3840
/** Long enough to compare a few monthly windows; older lines are dropped at startup. */
3941
const RETENTION_MS = 120 * 24 * 60 * 60_000;
4042

43+
// Files from before resets were worked out also hold reset lines. They are
44+
// read past and dropped at the next startup rewrite.
4145
const HistoryLine = Schema.Union([
4246
Schema.Struct({ point: UsageLimitHistoryPoint }),
4347
Schema.Struct({ reset: UsageLimitReset }),
4448
]);
45-
type HistoryLine = typeof HistoryLine.Type;
4649
const decodeLine = Schema.decodeUnknownOption(Schema.fromJsonString(HistoryLine));
4750
const encodeLine = Schema.encodeSync(Schema.fromJsonString(HistoryLine));
4851

@@ -54,28 +57,22 @@ export class UsageLimitHistory extends Context.Service<
5457
}
5558
>()("t3/usage/UsageLimitHistory") {}
5659

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[] } {
60+
/** The readings a history file holds, with unreadable and expired lines left out. */
61+
export function parseUsageLimitHistory(contents: string, nowMs: number): UsageLimitHistoryPoint[] {
6262
const points: UsageLimitHistoryPoint[] = [];
63-
const resets: UsageLimitReset[] = [];
6463
for (const raw of contents.split("\n")) {
6564
if (raw.trim() === "") continue;
6665
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);
66+
if (line._tag === "None" || !("point" in line.value)) continue;
67+
const point = line.value.point;
68+
if (nowMs - Date.parse(point.at) > RETENTION_MS) continue;
69+
points.push(point);
7370
}
74-
return { points, resets };
71+
return points;
7572
}
7673

77-
function serialize(lines: ReadonlyArray<HistoryLine>): string {
78-
return lines.map((line) => `${encodeLine(line)}\n`).join("");
74+
function serialize(points: ReadonlyArray<UsageLimitHistoryPoint>): string {
75+
return points.map((point) => `${encodeLine({ point })}\n`).join("");
7976
}
8077

8178
export const make = Effect.gen(function* () {
@@ -86,18 +83,13 @@ export const make = Effect.gen(function* () {
8683
const filePath = path.join(config.stateDir, USAGE_LIMIT_HISTORY_FILE_NAME);
8784

8885
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-
);
86+
const points = parseUsageLimitHistory(existing, yield* Clock.currentTimeMillis);
87+
const replayed = replayUsageLimitPoints(points);
88+
const resets: UsageLimitReset[] = [...replayed.resets];
89+
let state: UsageLimitReadingState = replayed.state;
9590
// Rewrite once at startup when lines expired or could not be read, so the
9691
// file never grows past the retention window.
97-
const kept = serialize([
98-
...points.map((point) => ({ point })),
99-
...resets.map((reset) => ({ reset })),
100-
]);
92+
const kept = serialize(points);
10193
if (existing !== "" && kept.length < existing.length) {
10294
yield* fileSystem.writeFileString(filePath, kept).pipe(Effect.ignore);
10395
}
@@ -113,14 +105,7 @@ export const make = Effect.gen(function* () {
113105
resets.push(...delta.resets);
114106
// History is a convenience; a full disk must not take usage limits down with it.
115107
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-
)
108+
.writeFileString(filePath, serialize(delta.points), { flag: "a" })
124109
.pipe(
125110
Effect.catch((cause) =>
126111
Effect.logWarning("Could not append to the usage limit history", cause),

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

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,19 @@ import { ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
33

44
import { recordUsageLimitReadings, type UsageLimitReadingState } from "./usageLimitReadings.ts";
55

6-
type Reading = Pick<ServerProvider, "instanceId" | "usageLimits">;
6+
type Reading = Pick<ServerProvider, "instanceId" | "usageLimits"> &
7+
Partial<Pick<ServerProvider, "auth">>;
78

89
function reading(
910
at: string,
1011
weeklyUsed: number,
1112
weeklyResetsAt: string | undefined,
1213
instanceId = "codex",
14+
email?: string,
1315
): Reading {
1416
return {
1517
instanceId: ProviderInstanceId.make(instanceId),
18+
...(email === undefined ? {} : { auth: { status: "authenticated" as const, email } }),
1619
usageLimits: {
1720
checkedAt: at,
1821
windows: [
@@ -43,6 +46,8 @@ function replay(readings: ReadonlyArray<ReadonlyArray<Reading>>) {
4346

4447
const RESET = "2026-10-14T02:00:00.000Z";
4548
const NEXT_RESET = "2026-10-21T02:00:00.000Z";
49+
/** A week from the early reset at 2026-10-11T08:05, when Codex starts the new window. */
50+
const EARLY_NEXT_RESET = "2026-10-18T08:04:00.000Z";
4651

4752
describe("recordUsageLimitReadings", () => {
4853
it("records a point only when a window's reading changes", () => {
@@ -69,7 +74,7 @@ describe("recordUsageLimitReadings", () => {
6974
it("logs an early reset with what was left unused", () => {
7075
const { resets } = replay([
7176
[reading("2026-10-11T08:00:00.000Z", 62, RESET)],
72-
[reading("2026-10-11T08:05:00.000Z", 0, NEXT_RESET)],
77+
[reading("2026-10-11T08:05:00.000Z", 0, EARLY_NEXT_RESET)],
7378
]);
7479
expect(resets).toEqual([
7580
{
@@ -130,11 +135,64 @@ describe("recordUsageLimitReadings", () => {
130135
],
131136
[
132137
reading("2026-10-11T08:05:00.000Z", 81, RESET, "codex"),
133-
reading("2026-10-11T08:05:00.000Z", 0, NEXT_RESET, "codex_personal"),
138+
reading("2026-10-11T08:05:00.000Z", 0, EARLY_NEXT_RESET, "codex_personal"),
134139
],
135140
]);
136141
expect(resets.map((reset) => [reset.instanceId, reset.unusedPercentBefore])).toEqual([
137142
["codex_personal", 95],
138143
]);
139144
});
145+
146+
it("counts an early reset that keeps the schedule once the window empties", () => {
147+
const { resets } = replay([
148+
[reading("2026-10-11T08:00:00.000Z", 40, RESET)],
149+
[reading("2026-10-11T08:05:00.000Z", 0, RESET)],
150+
]);
151+
expect(resets.map((reset) => [reset.ahead, reset.unusedPercentBefore])).toEqual([[true, 60]]);
152+
});
153+
154+
it("does not take two probes that round a point apart for resets", () => {
155+
const { resets } = replay([
156+
[reading("2026-10-12T14:38:00.000Z", 91, "2026-10-12T15:00:00.401Z")],
157+
[reading("2026-10-12T14:39:00.000Z", 90, "2026-10-12T15:00:00.000Z")],
158+
[reading("2026-10-12T14:40:00.000Z", 91, "2026-10-12T15:00:00.401Z")],
159+
[reading("2026-10-12T14:41:00.000Z", 90, "2026-10-12T15:00:00.000Z")],
160+
]);
161+
expect(resets).toEqual([]);
162+
});
163+
164+
it("keeps one series per account when an instance switches accounts", () => {
165+
const work = "2026-10-16T12:00:00.000Z";
166+
const { resets } = replay([
167+
[reading("2026-10-12T19:00:00.000Z", 22, work, "claude", "[email protected]")],
168+
[reading("2026-10-12T19:30:00.000Z", 6, NEXT_RESET, "claude", "[email protected]")],
169+
[reading("2026-10-12T20:00:00.000Z", 23, work, "claude", "[email protected]")],
170+
]);
171+
expect(resets).toEqual([]);
172+
});
173+
174+
it("does not take a switch between unnamed accounts for a reset", () => {
175+
const { resets } = replay([
176+
[reading("2026-10-12T19:00:00.000Z", 22, "2026-10-16T12:00:00.000Z")],
177+
[reading("2026-10-12T19:30:00.000Z", 2, "2026-10-19T15:00:00.000Z")],
178+
]);
179+
expect(resets).toEqual([]);
180+
});
181+
182+
it("names the subscription a reset belongs to", () => {
183+
const { resets } = replay([
184+
[reading("2026-10-11T08:00:00.000Z", 62, RESET, "claude", "[email protected]")],
185+
[reading("2026-10-11T08:05:00.000Z", 0, EARLY_NEXT_RESET, "claude", "[email protected]")],
186+
]);
187+
expect(resets.map((reset) => reset.account)).toEqual(["[email protected]"]);
188+
});
189+
190+
it("skips a reading of a window that had already ended", () => {
191+
const { points, resets } = replay([
192+
[reading("2026-10-14T02:03:00.000Z", 1, NEXT_RESET)],
193+
[reading("2026-10-14T02:20:00.000Z", 97, RESET)],
194+
]);
195+
expect(points.map((point) => point.usedPercent)).toEqual([1]);
196+
expect(resets).toEqual([]);
197+
});
140198
});

0 commit comments

Comments
 (0)