Skip to content

Commit 92a3f2b

Browse files
committed
fix(usage): discard stale balances when accounts change or clear
1 parent f9a550f commit 92a3f2b

4 files changed

Lines changed: 134 additions & 13 deletions

File tree

‎packages/provider-core/src/server/managedProvider.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,4 +643,50 @@ describe("makeManagedServerProvider", () => {
643643
}),
644644
).pipe(Effect.provide(layerAlwaysRunTest)),
645645
);
646+
it.effect("does not retain another account's credit balance after a failed usage probe", () =>
647+
Effect.scoped(
648+
Effect.gen(function* () {
649+
const auth = {
650+
status: "authenticated",
651+
type: "chatgpt",
652+
653+
} as const;
654+
const old = {
655+
...refreshedSnapshot,
656+
auth,
657+
usageLimits: {
658+
checkedAt: refreshedSnapshot.checkedAt,
659+
windows: [],
660+
credits: { hasCredits: true, unlimited: false, balance: "42" },
661+
},
662+
};
663+
const failed = {
664+
...old,
665+
auth: { ...auth, email: " [email protected] " },
666+
usageLimits: {
667+
checkedAt: refreshedSnapshot.checkedAt,
668+
windows: [],
669+
unavailable: { reason: "probeFailed" as const },
670+
},
671+
};
672+
const next = yield* Ref.make<ServerProvider>(failed);
673+
const provider = yield* makeManagedServerProvider<TestSettings>({
674+
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
675+
getSettings: Effect.succeed({ enabled: true }),
676+
streamSettings: Stream.empty,
677+
haveSettingsChanged: (previous, current) => previous.enabled !== current.enabled,
678+
initialSnapshot: () => Effect.succeed(old),
679+
checkProvider: Ref.get(next),
680+
refreshInterval: "1 hour",
681+
});
682+
yield* Stream.take(provider.streamChanges, 1).pipe(Stream.runDrain);
683+
assert.strictEqual((yield* provider.getSnapshot).usageLimits?.credits?.balance, "42");
684+
yield* Ref.set(next, { ...failed, auth: { ...auth, email: "[email protected]" } });
685+
const switched = yield* provider.refresh;
686+
assert.strictEqual(switched.auth.email, "[email protected]");
687+
assert.isUndefined(switched.usageLimits?.credits);
688+
assert.strictEqual(switched.usageLimits?.unavailable?.reason, "probeFailed");
689+
}),
690+
).pipe(Effect.provide(layerAlwaysRunTest)),
691+
);
646692
});

‎packages/provider-core/src/server/managedProvider.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,14 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
158158
const snapshot = withUsageLimits(
159159
probedSnapshot,
160160
resolveUsageLimitsAfterProbe({
161-
published: state.snapshot.usageLimits,
161+
// Failed reads may retain the last balance only for the same account.
162+
published:
163+
state.snapshot.auth.status === probedSnapshot.auth.status &&
164+
state.snapshot.auth.type === probedSnapshot.auth.type &&
165+
state.snapshot.auth.email?.trim().toLowerCase() ===
166+
probedSnapshot.auth.email?.trim().toLowerCase()
167+
? state.snapshot.usageLimits
168+
: undefined,
162169
probed: probedSnapshot.usageLimits,
163170
}),
164171
);

‎packages/shared/src/usageLimits.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,65 @@ describe("credit balances", () => {
186186
).toBe("20");
187187
expect(collectLimitAccounts(makePresentations(null))[0]?.limits.credits).toBeNull();
188188
});
189+
it.each(["native", "source"])(
190+
"honors a newer %s clear without windows and retains another environment's quota",
191+
(kind) => {
192+
const oldLimits = {
193+
checkedAt: "2026-09-03T10:00:00.000Z",
194+
windows: [window],
195+
credits: { hasCredits: true, unlimited: false, balance: "42" },
196+
};
197+
const cleared = { checkedAt: "2026-09-03T11:00:00.000Z", windows: [], credits: null };
198+
const auth = { status: "authenticated", email: "[email protected]" } as const;
199+
const newer = {
200+
entry: { target: { label: "Laptop" } },
201+
serverConfig: {
202+
providers: kind === "native" ? [provider({ auth, usageLimits: cleared })] : [],
203+
usageLimitSources:
204+
kind === "source"
205+
? [
206+
{
207+
id: UsageLimitSourceId.make("hub"),
208+
kind: "cliproxy" as const,
209+
label: "hub",
210+
checkedAt: cleared.checkedAt,
211+
accounts: [
212+
{
213+
id: "account",
214+
driver: ProviderDriverKind.make("codex"),
215+
email: auth.email,
216+
usageLimits: cleared,
217+
},
218+
],
219+
},
220+
]
221+
: [],
222+
},
223+
};
224+
const older = {
225+
entry: { target: { label: "Desktop" } },
226+
serverConfig: {
227+
providers: [provider({ auth, usageLimits: oldLimits })],
228+
usageLimitSources: [],
229+
},
230+
};
231+
const entries = [
232+
[EnvironmentId.make("desktop"), older],
233+
[EnvironmentId.make("laptop"), newer],
234+
] as const;
235+
for (const order of [entries, entries.toReversed()]) {
236+
const accounts = collectLimitAccounts(new Map(order));
237+
expect(accounts).toHaveLength(1);
238+
expect(accounts[0]?.limits.credits).toBeNull();
239+
expect(accounts[0]?.limits.windows).toEqual([window]);
240+
}
241+
expect(collectLimitAccounts(new Map([[EnvironmentId.make("laptop"), newer]]))).toEqual([]);
242+
older.serverConfig.providers = [
243+
provider({ auth, usageLimits: { ...oldLimits, windows: [] } }),
244+
];
245+
expect(collectLimitAccounts(new Map(entries))).toEqual([]);
246+
},
247+
);
189248
});
190249

191250
describe("providersWithLimits", () => {

‎packages/shared/src/usageLimits.ts‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,18 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
166166
const balanceSources = new Map<string, LimitAccount>();
167167
const hubRedeems = new Map<string, LimitAccount>();
168168
const merge = (key: string, next: LimitAccount) => {
169+
const previousBalance = balanceSources.get(key);
170+
if (
171+
!next.limits.unavailable &&
172+
next.limits.credits !== undefined &&
173+
(!previousBalance ||
174+
Date.parse(next.limits.checkedAt) > Date.parse(previousBalance.limits.checkedAt))
175+
) {
176+
balanceSources.set(key, next);
177+
}
178+
// A clear without windows still invalidates older balances from another environment.
179+
if (limitsNotice(next.limits) !== null) return;
180+
169181
// Redeeming through a hub also clears the routing cooldown that hub holds
170182
// for the account. Redeeming natively against the same subscription resets
171183
// it upstream but leaves the hub refusing to route to the account until
@@ -188,14 +200,6 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
188200
creditSources.set(key, next);
189201
}
190202
const previous = accounts.get(key);
191-
const previousBalance = balanceSources.get(key);
192-
if (
193-
next.limits.credits !== undefined &&
194-
(!previousBalance ||
195-
Date.parse(next.limits.checkedAt) > Date.parse(previousBalance.limits.checkedAt))
196-
) {
197-
balanceSources.set(key, next);
198-
}
199203
if (!previous) {
200204
accounts.set(key, next);
201205
return;
@@ -226,7 +230,6 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
226230
(creditSource ? creditSource.redeem : (winner.redeem ?? previous.redeem ?? next.redeem)),
227231
limits: {
228232
...winner.limits,
229-
credits: balanceSources.get(key)?.limits.credits,
230233
...(creditSource?.limits.resetCredits
231234
? { resetCredits: creditSource.limits.resetCredits }
232235
: { resetCredits: undefined }),
@@ -236,7 +239,7 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
236239
for (const [environmentId, presentation] of presentations) {
237240
const label = presentation.entry.target.label;
238241
for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {
239-
if (!provider.usageLimits || limitsNotice(provider.usageLimits) !== null) continue;
242+
if (!provider.usageLimits) continue;
240243
merge(
241244
accountKey(provider.driver, provider.auth.email, provider.usageLimits) ??
242245
`${environmentId}:${provider.instanceId}`,
@@ -265,7 +268,6 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
265268
? `${presentation.entry.target.label} · ${source.label}`
266269
: source.label;
267270
for (const account of source.accounts) {
268-
if (limitsNotice(account.usageLimits) !== null) continue;
269271
merge(
270272
accountKey(account.driver, account.email, account.usageLimits) ??
271273
`${source.id}:${account.id}`,
@@ -294,7 +296,14 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
294296
}
295297
}
296298
}
297-
return [...accounts.values()];
299+
return [...accounts.entries()]
300+
.map(([key, account]) => {
301+
const source = balanceSources.get(key);
302+
return source
303+
? { ...account, limits: { ...account.limits, credits: source.limits.credits } }
304+
: account;
305+
})
306+
.filter((account) => limitsNotice(account.limits) === null);
298307
}
299308

300309
/**

0 commit comments

Comments
 (0)