Skip to content

Commit da940ae

Browse files
committed
fix(server): keep Antigravity quotas isolated and refresh health promptly
1 parent 156dc63 commit da940ae

8 files changed

Lines changed: 309 additions & 79 deletions

‎apps/server/src/provider/Drivers/AntigravityDriver.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,12 +392,14 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
392392
}).pipe(
393393
Effect.provideService(FileSystem.FileSystem, fileSystem),
394394
Effect.provideService(Crypto.Crypto, crypto),
395-
Effect.map((read) => read.pipe(Effect.provideService(HttpClient.HttpClient, httpClient))),
396395
);
397396
const provider = yield* makeAntigravityProvider(settings, {
398397
stampIdentity: classifyModels,
399398
probe,
400-
usageLimits,
399+
usageLimits: usageLimits.read.pipe(
400+
Effect.provideService(HttpClient.HttpClient, httpClient),
401+
),
402+
usageLimitsCredentialFingerprint: usageLimits.credentialFingerprint,
401403
auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
402404
supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
403405
Effect.provideService(FileSystem.FileSystem, fileSystem),

‎apps/server/src/provider/Layers/AntigravityProvider.test.ts‎

Lines changed: 132 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (
121121
readonly enabled?: boolean;
122122
readonly safe?: boolean;
123123
readonly usageLimits?: Effect.Effect<ServerProviderUsageLimits>;
124+
readonly usageLimitsCredentialFingerprint?: Effect.Effect<string | undefined>;
124125
} = {},
125126
) {
126127
const initialProbe = yield* Deferred.make<EffectAcpSchema.InitializeResponse, ProbeError>();
@@ -143,6 +144,9 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (
143144
Effect.flatten,
144145
),
145146
...(options.usageLimits ? { usageLimits: options.usageLimits } : {}),
147+
...(options.usageLimitsCredentialFingerprint
148+
? { usageLimitsCredentialFingerprint: options.usageLimitsCredentialFingerprint }
149+
: {}),
146150
},
147151
);
148152
const initialUpdate = yield* Stream.toPull(
@@ -677,6 +681,41 @@ const unsupportedLimits = {
677681
} satisfies ServerProviderUsageLimits;
678682

679683
describe("Antigravity quota lifecycle", () => {
684+
it.effect("health refreshes finish while a serialized quota read is pending", () =>
685+
Effect.scoped(
686+
Effect.gen(function* () {
687+
const release = yield* Deferred.make<ServerProviderUsageLimits>();
688+
const requested = yield* Deferred.make<void>();
689+
const reads = yield* Ref.make(0);
690+
const harness = yield* makeHarness({
691+
usageLimits: Ref.update(reads, (count) => count + 1).pipe(
692+
Effect.andThen(Deferred.succeed(requested, undefined)),
693+
Effect.andThen(Deferred.await(release)),
694+
),
695+
});
696+
yield* harness.initialize;
697+
yield* Deferred.await(requested);
698+
const first = yield* harness.provider.snapshot.refresh;
699+
const second = yield* harness.provider.snapshot.refresh;
700+
expect(first.installed).toBe(true);
701+
expect(second.status).toBe("warning");
702+
expect(second.usageLimits).toBeUndefined();
703+
expect(yield* Ref.get(reads)).toBe(1);
704+
expect(yield* Ref.get(harness.probeCalls)).toBe(3);
705+
const published = yield* Stream.toPull(
706+
harness.provider.snapshot.streamChanges.pipe(
707+
Stream.filter((snapshot) => snapshot.usageLimits?.windows.length === 1),
708+
),
709+
);
710+
yield* Deferred.succeed(release, testLimits);
711+
const update = yield* published;
712+
expect(Array.from(update)[0]?.usageLimits).toEqual(testLimits);
713+
yield* TestClock.adjust("0 seconds");
714+
expect(yield* Ref.get(reads)).toBe(1);
715+
}),
716+
).pipe(Effect.provide(testLayer)),
717+
);
718+
680719
it.effect("publishes models immediately, then publishes quota after sign-in", () =>
681720
Effect.scoped(
682721
Effect.gen(function* () {
@@ -731,32 +770,118 @@ describe("Antigravity quota lifecycle", () => {
731770
expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
732771
yield* Ref.set(read, Effect.succeed(unsupportedLimits));
733772
yield* Deferred.succeed(release, testLimits);
734-
// The next refresh drains the serialized quota read before we assert.
735-
const snapshot = yield* harness.provider.snapshot.refresh;
773+
const published = yield* Stream.toPull(
774+
harness.provider.snapshot.streamChanges.pipe(
775+
Stream.filter(
776+
(snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported",
777+
),
778+
),
779+
);
780+
yield* harness.provider.snapshot.refresh;
781+
const snapshot = Array.from(yield* published)[0]!;
736782
expect(snapshot.auth.status).toBe("unauthenticated");
737783
expect(snapshot.usageLimits?.windows).toEqual([]);
738784
}),
739785
).pipe(Effect.provide(testLayer)),
740786
);
741787

788+
it.effect.each(["session", "health"] as const)(
789+
"clears another account's quota before a failing %s refresh",
790+
(trigger) =>
791+
Effect.scoped(
792+
Effect.gen(function* () {
793+
const accountA = { ...testLimits, credentialFingerprint: "account-a" };
794+
const identity = yield* Ref.make<string | undefined>("account-a");
795+
const read = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
796+
Effect.succeed(accountA),
797+
);
798+
const harness = yield* makeHarness({
799+
usageLimits: Ref.get(read).pipe(Effect.flatten),
800+
usageLimitsCredentialFingerprint: Ref.get(identity),
801+
});
802+
const initial = yield* Stream.toPull(
803+
harness.provider.snapshot.streamChanges.pipe(
804+
Stream.filter(
805+
(snapshot) => snapshot.usageLimits?.credentialFingerprint === "account-a",
806+
),
807+
),
808+
);
809+
yield* harness.initialize;
810+
yield* initial;
811+
yield* harness.provider.onSessionStarted(started);
812+
yield* TestClock.adjust("0 seconds");
813+
const release = yield* Deferred.make<ServerProviderUsageLimits>();
814+
const requested = yield* Deferred.make<void>();
815+
yield* Ref.set(
816+
read,
817+
Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(release))),
818+
);
819+
const cleared = yield* Stream.toPull(
820+
harness.provider.snapshot.streamChanges.pipe(
821+
Stream.filter((snapshot) => snapshot.usageLimits === undefined),
822+
),
823+
);
824+
const clearUpdate = yield* cleared.pipe(Effect.forkChild);
825+
yield* TestClock.adjust("0 seconds");
826+
yield* Ref.set(identity, "account-b");
827+
if (trigger === "session") yield* harness.provider.onSessionStarted(started);
828+
else yield* harness.provider.snapshot.refresh;
829+
yield* Deferred.await(requested);
830+
yield* Fiber.join(clearUpdate);
831+
expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
832+
const failed = {
833+
checkedAt: testLimits.checkedAt,
834+
windows: [],
835+
credentialFingerprint: "account-b",
836+
unavailable: { reason: "probeFailed" },
837+
} satisfies ServerProviderUsageLimits;
838+
const published = yield* Stream.toPull(
839+
harness.provider.snapshot.streamChanges.pipe(
840+
Stream.filter(
841+
(snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed",
842+
),
843+
),
844+
);
845+
yield* Deferred.succeed(release, failed);
846+
expect(Array.from(yield* published)[0]?.usageLimits).toEqual(failed);
847+
}),
848+
).pipe(Effect.provide(testLayer)),
849+
);
850+
742851
it.effect("retains the last successful quota when a later read fails", () =>
743852
Effect.scoped(
744853
Effect.gen(function* () {
745854
const read = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
746-
Effect.succeed(testLimits),
855+
Effect.succeed({ ...testLimits, credentialFingerprint: "account-a" }),
856+
);
857+
const harness = yield* makeHarness({
858+
usageLimits: Ref.get(read).pipe(Effect.flatten),
859+
usageLimitsCredentialFingerprint: Effect.succeed("account-a"),
860+
});
861+
const published = yield* Stream.toPull(
862+
harness.provider.snapshot.streamChanges.pipe(
863+
Stream.filter((snapshot) => snapshot.usageLimits?.windows.length === 1),
864+
),
747865
);
748-
const harness = yield* makeHarness({ usageLimits: Ref.get(read).pipe(Effect.flatten) });
749866
yield* harness.initialize;
867+
yield* published;
868+
const failed = yield* Deferred.make<void>();
750869
yield* Ref.set(
751870
read,
752871
Effect.succeed({
753872
checkedAt: "2026-10-03T00:01:00.000Z",
873+
credentialFingerprint: "account-a",
754874
windows: [],
755875
unavailable: { reason: "probeFailed" },
756-
}),
876+
} satisfies ServerProviderUsageLimits).pipe(
877+
Effect.tap(() => Deferred.succeed(failed, undefined)),
878+
),
757879
);
758-
const snapshot = yield* harness.provider.snapshot.refresh;
759-
expect(snapshot.usageLimits).toEqual(testLimits);
880+
yield* TestClock.adjust("30 seconds");
881+
yield* harness.provider.snapshot.refresh;
882+
yield* Deferred.await(failed);
883+
const snapshot = yield* harness.provider.snapshot.getSnapshot;
884+
expect(snapshot.usageLimits).toEqual({ ...testLimits, credentialFingerprint: "account-a" });
760885
}),
761886
).pipe(Effect.provide(testLayer)),
762887
);

‎apps/server/src/provider/Layers/AntigravityProvider.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ interface AntigravityProviderOptions {
129129
>;
130130
readonly supportsTextGeneration: Effect.Effect<boolean>;
131131
readonly usageLimits?: Effect.Effect<ServerProviderUsageLimits>;
132+
readonly usageLimitsCredentialFingerprint?: Effect.Effect<string | undefined>;
132133
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
133134
/** Auth type and label published once a session authenticates. */
134135
readonly auth?: { readonly type: string; readonly label: string };
@@ -178,6 +179,28 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
178179
Effect.flatMap((state) => options.stampIdentity(state.draft)),
179180
);
180181

182+
/** Clear the previous account's limits without waiting for the quota backend. */
183+
const clearChangedAccountLimits = Effect.fn("AntigravityProvider.clearChangedAccountLimits")(
184+
function* (revision: number) {
185+
if (!options.usageLimitsCredentialFingerprint) return;
186+
const fingerprint = yield* options.usageLimitsCredentialFingerprint;
187+
const cleared = yield* SubscriptionRef.modify(metadata, (state) => {
188+
const limits = state.draft.usageLimits;
189+
if (
190+
state.authRevision !== revision ||
191+
!limits ||
192+
(limits.credentialFingerprint === undefined && limits.windows.length === 0) ||
193+
(fingerprint !== undefined && limits.credentialFingerprint === fingerprint)
194+
) {
195+
return [false, state] as const;
196+
}
197+
return [true, { ...state, draft: { ...state.draft, usageLimits: undefined } }] as const;
198+
});
199+
if (cleared) yield* Ref.set(lastUsageAttempt, undefined);
200+
},
201+
);
202+
203+
/** Read quotas in the background, serialized and throttled for the current account revision. */
181204
const refreshUsageLimits = Effect.fn("AntigravityProvider.refreshUsageLimits")(function* (
182205
revision: number,
183206
force = false,
@@ -186,6 +209,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
186209
if (!read) return;
187210
yield* usageSemaphore.withPermits(1)(
188211
Effect.gen(function* () {
212+
yield* clearChangedAccountLimits(revision);
189213
const state = yield* SubscriptionRef.get(metadata);
190214
if (state.authRevision !== revision || !state.draft.enabled || !state.draft.installed)
191215
return;
@@ -194,6 +218,14 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
194218
if (!force && last !== undefined && now - last < 30_000) return;
195219
yield* Ref.set(lastUsageAttempt, now);
196220
const limits = yield* read;
221+
if (
222+
options.usageLimitsCredentialFingerprint &&
223+
limits.credentialFingerprint !== undefined &&
224+
(yield* options.usageLimitsCredentialFingerprint) !== limits.credentialFingerprint
225+
) {
226+
yield* clearChangedAccountLimits(revision);
227+
return;
228+
}
197229
yield* SubscriptionRef.update(metadata, (current) =>
198230
current.authRevision !== revision
199231
? current
@@ -274,7 +306,9 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
274306
},
275307
} satisfies AntigravityProviderState;
276308
});
277-
if (initialized !== undefined) yield* refreshUsageLimits(next.authRevision, true);
309+
if (initialized !== undefined) {
310+
yield* refreshUsageLimits(next.authRevision).pipe(Effect.forkIn(scope));
311+
}
278312
return yield* getSnapshot;
279313
});
280314

@@ -307,6 +341,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
307341
started: AcpSessionRuntimeStartResult,
308342
cwd?: string,
309343
) {
344+
yield* clearChangedAccountLimits((yield* SubscriptionRef.get(metadata)).authRevision);
310345
const before = yield* SubscriptionRef.get(metadata);
311346
const supportsTextGeneration = yield* options.supportsTextGeneration;
312347
const updatedAt = DateTime.formatIso(yield* DateTime.now);

‎apps/server/src/provider/Layers/antigravityUsageLimits.test.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,12 @@ const makeFixture = Effect.fn("antigravityUsageFixture")(function* (input: {
4747
const directory = yield* fs.makeTempDirectoryScoped();
4848
const tokenPath = path.join(directory, "acp_token.json");
4949
if (input.contents !== undefined) yield* fs.writeFileString(tokenPath, input.contents);
50-
const read = yield* makeAntigravityUsageLimits({
50+
const reader = yield* makeAntigravityUsageLimits({
5151
enabled: input.enabled ?? true,
5252
authMethod: input.authMethod ?? "oauth-personal",
5353
tokenPath,
5454
});
55-
return { fs, tokenPath, read };
55+
return { fs, tokenPath, ...reader };
5656
});
5757

5858
describe("Antigravity subscription limits", () => {
@@ -126,6 +126,7 @@ describe("Antigravity subscription limits", () => {
126126
);
127127
expect(refreshes).toBe(1);
128128
expect(quotas).toBe(2);
129+
expect(yield* fixture.credentialFingerprint).toBe(first.credentialFingerprint);
129130
expect(first.credentialFingerprint).toMatch(/^[a-f0-9]{64}$/);
130131
expect(second.credentialFingerprint).toBe(first.credentialFingerprint);
131132
expect(yield* fixture.fs.readFileString(fixture.tokenPath)).toBe(contents);
@@ -138,6 +139,25 @@ describe("Antigravity subscription limits", () => {
138139
),
139140
);
140141

142+
it.effect(
143+
"reads account identity locally and detects replaced, missing, or invalid credentials",
144+
() =>
145+
Effect.gen(function* () {
146+
const fixture = yield* makeFixture({ contents: encodeJson(credentials) });
147+
const first = yield* fixture.credentialFingerprint;
148+
expect(first).toMatch(/^[a-f0-9]{64}$/);
149+
yield* fixture.fs.writeFileString(
150+
fixture.tokenPath,
151+
encodeJson({ ...credentials, refresh_token: "account-b" }),
152+
);
153+
expect(yield* fixture.credentialFingerprint).not.toBe(first);
154+
yield* fixture.fs.writeFileString(fixture.tokenPath, "invalid json");
155+
expect(yield* fixture.credentialFingerprint).toBeUndefined();
156+
yield* fixture.fs.remove(fixture.tokenPath);
157+
expect(yield* fixture.credentialFingerprint).toBeUndefined();
158+
}).pipe(Effect.provide(NodeServices.layer)),
159+
);
160+
141161
it.effect("retries an expired stored access token once", () =>
142162
Effect.gen(function* () {
143163
const fixture = yield* makeFixture({
@@ -183,13 +203,16 @@ describe("Antigravity subscription limits", () => {
183203

184204
it.effect.each([403, 500] as const)("reports a failed probe for HTTP %s", (status) =>
185205
Effect.gen(function* () {
186-
const fixture = yield* makeFixture({ contents: encodeJson({ access_token: "token" }) });
206+
const fixture = yield* makeFixture({
207+
contents: encodeJson({ ...credentials, access_token: "token" }),
208+
});
187209
const client = HttpClient.make((request) =>
188210
Effect.succeed(
189211
HttpClientResponse.fromWeb(request, new Response("private error", { status })),
190212
),
191213
);
192214
const limits = yield* fixture.read.pipe(Effect.provideService(HttpClient.HttpClient, client));
215+
expect(limits.credentialFingerprint).toBe(yield* fixture.credentialFingerprint);
193216
expect(limits.unavailable).toEqual({
194217
reason: "probeFailed",
195218
message: "Antigravity could not read usage limits.",

0 commit comments

Comments
 (0)