Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): do not share an in-flight model refresh across account identities

masashiono06116dbaeea2dec0
diff --git a/src/core/ai/openai-latest.ts b/src/core/ai/openai-latest.ts
index de2bead9d2..1f5abd4f08 100644
--- a/src/core/ai/openai-latest.ts
+++ b/src/core/ai/openai-latest.ts
@@ -236,6 +236,7 @@ export function latestOpenAITiers(tier?: ModelTier): OpenAITierPick | string | n
/* ── refresh (async, throttled, fail-open) ────────────────────────────────── */
let _refreshInFlight: Promise<void> | null = null;
+let _refreshInFlightFp = '';
let _warnedUnpriced: string | null = null;
// Failure backoff: a persistently-failing refresh (blackholed network,
// revoked key, unwritable config dir — nothing lands in the cache, so the
@@ -295,6 +296,7 @@ function stampAttempt(fp: string): void {
export function _resetOpenAILatestForTests(): void {
_refreshInFlight = null;
+ _refreshInFlightFp = '';
_warnedUnpriced = null;
_lastAttemptAt = 0;
_lastAttemptFp = '';
@@ -338,9 +340,14 @@ export async function refreshLatestOpenAIModels(opts: RefreshOpts = {}): Promise
const moduleAttempt = _lastAttemptFp === fp ? _lastAttemptAt : 0;
if (!opts.force && Date.now() - Math.max(moduleAttempt, persistedAttempt) < FAILURE_BACKOFF_MS) return;
- if (_refreshInFlight) return _refreshInFlight;
+ if (_refreshInFlight) {
+ if (_refreshInFlightFp === fp) return _refreshInFlight;
+ await _refreshInFlight;
+ return refreshLatestOpenAIModels(opts);
+ }
_lastAttemptAt = Date.now();
_lastAttemptFp = fp;
+ _refreshInFlightFp = fp;
_refreshInFlight = (async () => {
try {
const doFetch = opts.fetchImpl ?? fetch;
@@ -385,6 +392,7 @@ export async function refreshLatestOpenAIModels(opts: RefreshOpts = {}): Promise
stampAttempt(fp);
} finally {
_refreshInFlight = null;
+ _refreshInFlightFp = '';
}
})();
return _refreshInFlight;
diff --git a/test/openai-latest.serial.test.ts b/test/openai-latest.serial.test.ts
index 45cf29be60..698ec07d41 100644
--- a/test/openai-latest.serial.test.ts
+++ b/test/openai-latest.serial.test.ts
@@ -4,6 +4,7 @@
* GBRAIN_HOME + process env + module memo state.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
+import { createHash } from 'node:crypto';
import {
mkdtempSync,
rmSync,
@@ -189,6 +190,50 @@ describe('refresh + cache + resolution overlay', () => {
expect(calls).toBe(2);
});
+ test('concurrent refreshes for the same identity share one fetch', async () => {
+ let calls = 0;
+ let release!: (response: Response) => void;
+ const deferred = (async () => {
+ calls++;
+ return new Promise<Response>((resolve) => { release = resolve; });
+ }) as unknown as typeof fetch;
+ const first = refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'sk-same-account' }, fetchImpl: deferred, force: true,
+ });
+ const second = refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'sk-same-account' }, fetchImpl: deferred, force: true,
+ });
+ expect(calls).toBe(1);
+ release(new Response(JSON.stringify({ data: [{ id: 'gpt-5.6' }] }), { status: 200 }));
+ await Promise.all([first, second]);
+ expect(calls).toBe(1);
+ });
+
+ test('concurrent refresh for another identity runs after the pending refresh', async () => {
+ let releaseA!: (response: Response) => void;
+ const fetchA = (async () => new Promise<Response>((resolve) => { releaseA = resolve; })) as unknown as typeof fetch;
+ let callsB = 0;
+ const fetchB = (async () => {
+ callsB++;
+ return new Response(JSON.stringify({ data: [{ id: 'gpt-5.5' }] }), { status: 200 });
+ }) as unknown as typeof fetch;
+
+ const refreshA = refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'sk-account-a' }, fetchImpl: fetchA, force: true,
+ });
+ const refreshB = refreshLatestOpenAIModels({
+ env: { OPENAI_API_KEY: 'sk-account-b' }, fetchImpl: fetchB, force: true,
+ });
+ releaseA(new Response(JSON.stringify({ data: [{ id: 'gpt-5.6' }] }), { status: 200 }));
+ await Promise.all([refreshA, refreshB]);
+
+ expect(callsB).toBe(1);
+ const raw = JSON.parse(readFileSync(join(tmpHome, '.gbrain', 'model-cache.json'), 'utf8'));
+ const fingerprintB = createHash('sha256')
+ .update('https://api.openai.com/v1|sk-account-b').digest('hex').slice(0, 16);
+ expect(raw.openai.fingerprint).toBe(fingerprintB);
+ });
+
test('fail-open: keyless, disabled, HTTP error, and throwing fetch never write or throw', async () => {
const boom = (async () => { throw new Error('offline'); }) as unknown as typeof fetch;
await refreshLatestOpenAIModels({ env: {}, fetchImpl: boom, force: true }); // keyless → no-op