From 72523310380dad23c996adcad9b43d033a1b5ab5 Mon Sep 17 00:00:00 2001 From: iceteaSA <171169159+iceteaSA@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:06:22 +0000 Subject: [PATCH] fix(vault): keep a newer quota reading when an older check finishes last The 3.1.11 guard covered only the local account store. On the vault path a manual quota check runs outside the poller lock, so a late older reading replaced the poller's newer one in the state file and on the live row. Refuse a dated reading older than the stored one, as the local store does; the check still reports the account as checked. --- .../shared/vault-quota-newer-reading.test.ts | 221 ++++++++++++++++++ .../shared/vault-request-credentials.test.ts | 2 +- .../shared/vault-request-credentials.ts | 72 ++++-- 3 files changed, 277 insertions(+), 18 deletions(-) create mode 100644 packages/opencode/src/plugin/shared/vault-quota-newer-reading.test.ts diff --git a/packages/opencode/src/plugin/shared/vault-quota-newer-reading.test.ts b/packages/opencode/src/plugin/shared/vault-quota-newer-reading.test.ts new file mode 100644 index 00000000..a3f10874 --- /dev/null +++ b/packages/opencode/src/plugin/shared/vault-quota-newer-reading.test.ts @@ -0,0 +1,221 @@ +/** + * A vault quota reading that ends late must not replace a newer one. A manual + * "Check quota now" runs outside the poller's lock, so the older of two + * readings can commit last. The local account store refuses an older dated + * reading under its write lock; the vault provider-state path keeps the same + * rule, both in the state file and on the live pool row. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { VaultStateAttribution } from '@cortexkit/antigravity-auth-core' +import { + commitVaultProviderState, + loadCommonAuthFs, + readVaultProviderState, +} from '@cortexkit/antigravity-auth-core' + +import { + checkVaultQuota, + createVaultAccountPool, + type VaultAccountPool, + type VaultAccountPoolOptions, + type VaultRequestSource, +} from './vault-request-credentials.ts' + +const OLDER = 1_000 +const NEWER = 2_000 +const NOW = 3_000 + +async function fixture() { + const fs = await loadCommonAuthFs() + const dir = await mkdtemp(join(tmpdir(), 'agy-vault-newer-reading-')) + const statePath = join(dir, 'state.json') + const by: VaultStateAttribution = { + routeId: 'vault:a', + credentialId: 'credential-a', + accountIdentity: 'account-a', + recordVersion: 1, + } + const route = () => ({ + routeId: by.routeId, + credentialId: by.credentialId, + accountIdentity: by.accountIdentity, + label: 'Work', + }) + const source: VaultRequestSource = { + refresh: async () => undefined, + routes: () => [route()], + admit: async () => ({ + ...by, + accessToken: 'fixture-access', + projectId: 'fixture-project', + expiresAtMs: null, + }), + reportServedStatus: async () => false, + } + const readState = () => readVaultProviderState(statePath) + const durable: NonNullable = { + stateFile: statePath, + readState, + source: { + attribution: () => by, + commitState: (attribution, update) => + commitVaultProviderState({ + claustrum: { + isDeclined: () => false, + async mutateVaultRoster(_path, change) { + const outcome = await change( + { + version: 1, + complete: true, + declined: [], + rows: [ + { + ...route(), + credentialType: 'oauth', + state: 'active', + enabled: true, + addedAt: 1, + }, + ], + }, + { assertOwned: async () => undefined }, + ) + return outcome.result + }, + }, + fs, + rosterPath: join(dir, 'roster.json'), + statePath, + attribution, + verify: async () => undefined, + update, + }), + }, + } + return { + by, + read: async () => (await readState()).accounts[by.accountIdentity], + close: () => rm(dir, { recursive: true, force: true }), + async open() { + const pool = createVaultAccountPool({ + source, + durable, + now: () => NOW, + }) + await pool.sync() + const [row] = pool.selector.rows + if (!row) throw new Error('missing vault row') + await pool.credentials.admit({ account: row, signal: undefined }) + return { pool, row } + }, + /** One quota check whose reading was observed at `observedAt`. */ + check( + pool: VaultAccountPool, + observedAt: number, + remainingFraction: number, + ) { + return checkVaultQuota({ + pool, + fetchReading: async () => ({ + quota: { + groups: { gemini: { remainingFraction, modelCount: 1 } }, + modelCount: 1, + }, + quotaAttribution: by, + observedAt, + }), + signal: new AbortController().signal, + now: () => NOW, + }) + }, + } +} + +describe('vault quota keeps the newer reading', () => { + let f: Awaited> + + beforeEach(async () => { + f = await fixture() + }) + + afterEach(async () => { + await f?.close() + }) + + it('keeps the newer stored reading when an older check commits last', async () => { + const poller = await f.open() + const manual = await f.open() + // The poller commits R2; the manual check took R1 earlier and ends last. + expect(await f.check(poller.pool, NEWER, 0.5)).toEqual({ + checked: 1, + notChecked: 0, + }) + expect(await f.check(poller.pool, OLDER, 0.9)).toEqual({ + checked: 1, + notChecked: 0, + }) + expect(await f.check(manual.pool, OLDER, 0.9)).toEqual({ + checked: 1, + notChecked: 0, + }) + + const stored = await f.read() + expect(stored?.quota?.cachedQuotaUpdatedAt).toBe(NEWER) + expect(stored?.quota?.cachedQuota?.gemini?.remainingFraction).toBe(0.5) + expect(poller.row.cachedQuotaUpdatedAt).toBe(NEWER) + expect(poller.row.cachedQuota?.gemini?.remainingFraction).toBe(0.5) + expect(manual.row.cachedQuotaUpdatedAt).not.toBe(OLDER) + + // Another pool still adopts the newer stored reading on sync. + await manual.pool.sync() + expect(manual.row.cachedQuotaUpdatedAt).toBe(NEWER) + expect(manual.row.cachedQuota?.gemini?.remainingFraction).toBe(0.5) + }) + + it('lets a newer reading replace an older one', async () => { + const { pool, row } = await f.open() + await f.check(pool, OLDER, 0.9) + expect((await f.read())?.quota?.cachedQuotaUpdatedAt).toBe(OLDER) + expect(row.cachedQuotaUpdatedAt).toBe(OLDER) + + expect(await f.check(pool, NEWER, 0.5)).toEqual({ + checked: 1, + notChecked: 0, + }) + const stored = await f.read() + expect(stored?.quota?.cachedQuotaUpdatedAt).toBe(NEWER) + expect(stored?.quota?.cachedQuota?.gemini?.remainingFraction).toBe(0.5) + expect(row.cachedQuotaUpdatedAt).toBe(NEWER) + expect(row.cachedQuota?.gemini?.remainingFraction).toBe(0.5) + }) + + it('keeps a newer reading on the live row when the file has none', async () => { + const { pool, row } = await f.open() + // The row holds a newer reading in memory only. + row.cachedQuota = { gemini: { remainingFraction: 0.5, modelCount: 1 } } + row.cachedQuotaUpdatedAt = NEWER + + expect(await f.check(pool, OLDER, 0.9)).toEqual({ + checked: 1, + notChecked: 0, + }) + expect(row.cachedQuotaUpdatedAt).toBe(NEWER) + expect(row.cachedQuota?.gemini?.remainingFraction).toBe(0.5) + }) + + it('accepts an undated reading over a dated one, as the local store does', async () => { + const { pool } = await f.open() + await f.check(pool, NEWER, 0.5) + const result = await pool.state?.recordQuota(f.by, { + schemaVersion: 1, + cachedQuota: { gemini: { remainingFraction: 0.9, modelCount: 1 } }, + }) + expect(result?.status).toBe('written') + const stored = await f.read() + expect(stored?.quota?.cachedQuota?.gemini?.remainingFraction).toBe(0.9) + }) +}) diff --git a/packages/opencode/src/plugin/shared/vault-request-credentials.test.ts b/packages/opencode/src/plugin/shared/vault-request-credentials.test.ts index 586eba7a..ae7f9ca5 100644 --- a/packages/opencode/src/plugin/shared/vault-request-credentials.test.ts +++ b/packages/opencode/src/plugin/shared/vault-request-credentials.test.ts @@ -782,7 +782,7 @@ describe('vault pools sharing one provider-state file', () => { a.pool.selector.markRateLimited(a.row, limitMs, 'gemini', model) await a.pool.flush() await f.checkQuota(p.pool, older, 0.9) - expect((await f.read())?.quota?.cachedQuotaUpdatedAt).toBe(older) + expect((await f.read())?.quota?.cachedQuotaUpdatedAt).toBe(newer) await a.pool.sync() expect(a.row.cachedQuotaUpdatedAt).toBe(newer) diff --git a/packages/opencode/src/plugin/shared/vault-request-credentials.ts b/packages/opencode/src/plugin/shared/vault-request-credentials.ts index 4d8d1112..bf3ca6ea 100644 --- a/packages/opencode/src/plugin/shared/vault-request-credentials.ts +++ b/packages/opencode/src/plugin/shared/vault-request-credentials.ts @@ -471,26 +471,51 @@ function legacyLimitKey( return JSON.stringify([by.accountIdentity, by.routeId, by.credentialId]) } +/** + * Tells if `incoming` is older than `stored`, by the same rule as the local + * account store: a reading without a date is never older and is not refused. + */ +function isOlderQuotaReading( + stored: Pick | undefined, + incoming: Pick, +): boolean { + const previousAt = stored?.cachedQuotaUpdatedAt + const observedAt = incoming.cachedQuotaUpdatedAt + return ( + typeof previousAt === 'number' && + typeof observedAt === 'number' && + observedAt < previousAt + ) +} + function quotaUpdate( quota: QuotaState, now: () => number, legacy: LegacyLimitStamps = {}, -): (current: VaultAccountState | undefined) => VaultAccountStateValue { - return (current) => ({ - ...(current?.metadata !== undefined - ? { - metadata: applyRateLimitReadingUpdate( - stampLoadedLegacyLimits(current.metadata, legacy), - rateLimitReadingUpdateOf(quota), - now(), - ), - } - : {}), - quota, - ...(current?.extensions !== undefined - ? { extensions: current.extensions } - : {}), - }) +): ( + current: VaultAccountState | undefined, +) => VaultAccountStateValue | undefined { + return (current) => { + // The update runs under the provider-state lock, so a check that ends + // late cannot replace a newer reading or its rate-limit decision. + // `undefined` makes the commit `unchanged`. + if (isOlderQuotaReading(current?.quota, quota)) return undefined + return { + ...(current?.metadata !== undefined + ? { + metadata: applyRateLimitReadingUpdate( + stampLoadedLegacyLimits(current.metadata, legacy), + rateLimitReadingUpdateOf(quota), + now(), + ), + } + : {}), + quota, + ...(current?.extensions !== undefined + ? { extensions: current.extensions } + : {}), + } + } } function stampLoadedLegacyLimits( @@ -1152,6 +1177,8 @@ export function vaultQuotaState(quota: QuotaSummary, at: number): QuotaState { * account or a newer record version) is not checked and is not shown, and * does not stop the other readings from being written. A written reading is * also put on the row that is still at that route, credential and account. + * A dated reading older than the stored one or the row's one is not written + * or put on the row; the row still counts as checked. * An aborted `signal` stops the check: the remaining rows are not fetched, * and readings already fetched are not written. */ @@ -1238,6 +1265,16 @@ export async function checkVaultQuota(input: { ) continue } + if ( + result.status === 'unchanged' && + isOlderQuotaReading(result.state?.quota, reading) + ) { + // The account already holds a newer reading, as the local store keeps + // one: the check is complete and the older reading is dropped. + checked += 1 + input.onOutcome?.('recorded') + continue + } if (result.status !== 'written') { input.onOutcome?.( result.status === 'uncertain' ? 'write-uncertain' : 'commit-unchanged', @@ -1250,7 +1287,8 @@ export async function checkVaultQuota(input: { const live = liveByRoute.get(attribution.routeId) if ( live?.route.credentialId === attribution.credentialId && - live.route.accountIdentity === attribution.accountIdentity + live.route.accountIdentity === attribution.accountIdentity && + !isOlderQuotaReading(live, reading) ) { const cached = cachedQuotaOf(reading) if (cached !== undefined) live.cachedQuota = cached