Skip to content

Commit e2e030e

Browse files
fix(auth): reset only the profile replaced by a successful login (#124014)
Summary: - Merged fix(auth): reset only the profile replaced by a successful login after ClawSweeper review. Automerge notes: - PR branch already contained follow-up commit before automerge: test(auth): use valid blocked source Validation: - ClawSweeper review passed for head 4b604a6. - Required merge gates passed before the squash merge. Prepared head SHA: 4b604a6 Review: #124014 (comment) Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Jesse Merhi <[email protected]> Approved-by: clawsweeper
1 parent 3405561 commit e2e030e

6 files changed

Lines changed: 230 additions & 231 deletions

File tree

‎src/agents/auth-profiles/profiles.ts‎

Lines changed: 10 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@ import {
2323
saveAuthProfileStore,
2424
updateAuthProfileStoreWithLock,
2525
} from "./store.js";
26-
import type { AuthProfileCredential, AuthProfileStore, ProfileUsageStats } from "./types.js";
26+
import type { AuthProfileCredential, AuthProfileStore } from "./types.js";
27+
import { resetAuthProfileFailureState } from "./usage-state.js";
2728
export {
2829
dedupeProfileIds,
2930
listProfilesForProvider,
3031
resolveSubscriptionAuthModeForProfiles,
3132
} from "./profile-list.js";
32-
export { upsertAuthProfileWithLock, upsertAuthProfileWithLockOrThrow } from "./upsert-with-lock.js";
33+
export {
34+
upsertAuthProfileAfterLoginWithLockOrThrow,
35+
upsertAuthProfileWithLock,
36+
upsertAuthProfileWithLockOrThrow,
37+
} from "./upsert-with-lock.js";
3338

3439
const authProfileProfilesLog = createSubsystemLogger("agent/embedded");
3540

@@ -71,37 +76,15 @@ function replaceProviderAuthState<T>(
7176
return Object.keys(next).length > 0 ? next : undefined;
7277
}
7378

74-
// Successful auth clears transient failure/cooldown/disable state while keeping
75-
// unrelated metadata and updating lastUsed for round-robin ordering.
76-
function resetSuccessfulUsageStats(
77-
existing: ProfileUsageStats | undefined,
78-
lastUsed: number,
79-
): ProfileUsageStats {
80-
return {
81-
...existing,
82-
errorCount: 0,
83-
blockedUntil: undefined,
84-
blockedReason: undefined,
85-
blockedSource: undefined,
86-
blockedModel: undefined,
87-
cooldownUntil: undefined,
88-
cooldownReason: undefined,
89-
cooldownClassification: undefined,
90-
cooldownModel: undefined,
91-
disabledUntil: undefined,
92-
disabledReason: undefined,
93-
failureCounts: undefined,
94-
lastUsed,
95-
};
96-
}
97-
9879
function updateSuccessfulUsageStatsEntry(
9980
store: AuthProfileStore,
10081
profileId: string,
10182
lastUsed: number,
10283
): void {
10384
store.usageStats = store.usageStats ?? {};
104-
store.usageStats[profileId] = resetSuccessfulUsageStats(store.usageStats[profileId], lastUsed);
85+
store.usageStats[profileId] = resetAuthProfileFailureState(store.usageStats[profileId] ?? {}, {
86+
lastUsed,
87+
});
10588
}
10689

10790
/** Sets or clears explicit auth profile order for a provider. */

‎src/agents/auth-profiles/upsert-with-lock.sqlite.test.ts‎

Lines changed: 133 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ import {
1717
} from "./sqlite.js";
1818
import { saveAuthProfileStore, updateAuthProfileStoreWithLock } from "./store.js";
1919
import type { ApiKeyCredential } from "./types.js";
20-
import { persistAuthProfileBatch, upsertAuthProfileWithLockOrThrow } from "./upsert-with-lock.js";
20+
import {
21+
persistAuthProfileBatch,
22+
upsertAuthProfileAfterLoginWithLockOrThrow,
23+
upsertAuthProfileWithLockOrThrow,
24+
} from "./upsert-with-lock.js";
2125

2226
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
2327

@@ -170,6 +174,134 @@ describe("auth profile batch persistence", () => {
170174
});
171175
});
172176

177+
it("replaces one completed login and resets only its existing failure state", async () => {
178+
await withAgentDir(async (agentDir) => {
179+
const targetId = "openai:target";
180+
const siblingId = "openai:sibling";
181+
const targetLastUsed = Date.now() - 10_000;
182+
const targetLastFailureAt = Date.now() - 5_000;
183+
const targetLastProbeAt = Date.now() - 2_000;
184+
const siblingBlockedUntil = Date.now() + 120_000;
185+
saveAuthProfileStore(
186+
{
187+
version: 1,
188+
profiles: {
189+
[targetId]: apiKey("sk-stale"),
190+
[siblingId]: apiKey("sk-sibling"),
191+
},
192+
order: { openai: [siblingId, targetId] },
193+
lastGood: { openai: siblingId },
194+
usageStats: {
195+
[targetId]: {
196+
errorCount: 4,
197+
failureCounts: { auth_permanent: 4 },
198+
blockedUntil: Date.now() + 60_000,
199+
blockedReason: "subscription_limit",
200+
blockedSource: "wham",
201+
blockedModel: "gpt-5.6",
202+
blockedScope: "model",
203+
cooldownUntil: Date.now() + 60_000,
204+
cooldownReason: "auth_permanent",
205+
cooldownModel: "gpt-5.6",
206+
disabledUntil: Date.now() + 60_000,
207+
disabledReason: "auth_permanent",
208+
lastUsed: targetLastUsed,
209+
lastFailureAt: targetLastFailureAt,
210+
lastProbeAt: targetLastProbeAt,
211+
},
212+
[siblingId]: {
213+
errorCount: 2,
214+
blockedUntil: siblingBlockedUntil,
215+
blockedReason: "subscription_limit",
216+
},
217+
},
218+
},
219+
agentDir,
220+
);
221+
222+
await upsertAuthProfileAfterLoginWithLockOrThrow({
223+
agentDir,
224+
profileId: targetId,
225+
credential: apiKey("sk-fresh"),
226+
});
227+
228+
expect(loadPersistedAuthProfileStore(agentDir)).toEqual({
229+
version: 1,
230+
profiles: {
231+
[targetId]: apiKey("sk-fresh"),
232+
[siblingId]: apiKey("sk-sibling"),
233+
},
234+
order: { openai: [siblingId, targetId] },
235+
lastGood: { openai: siblingId },
236+
usageStats: {
237+
[targetId]: {
238+
errorCount: 0,
239+
lastUsed: targetLastUsed,
240+
lastFailureAt: targetLastFailureAt,
241+
lastProbeAt: targetLastProbeAt,
242+
},
243+
[siblingId]: {
244+
errorCount: 2,
245+
blockedUntil: siblingBlockedUntil,
246+
blockedReason: "subscription_limit",
247+
},
248+
},
249+
});
250+
});
251+
});
252+
253+
it("rolls the completed-login credential and state back together on write failure", async () => {
254+
await withAgentDir(async (agentDir) => {
255+
const profileId = "openai:existing";
256+
const disabledUntil = Date.now() + 60_000;
257+
saveAuthProfileStore(
258+
{
259+
version: 1,
260+
profiles: { [profileId]: apiKey("sk-stale") },
261+
usageStats: {
262+
[profileId]: {
263+
errorCount: 3,
264+
disabledUntil,
265+
disabledReason: "auth_permanent",
266+
},
267+
},
268+
},
269+
agentDir,
270+
);
271+
const database = openOpenClawAgentDatabase({
272+
agentId: "work",
273+
path: resolveAuthProfileDatabasePath(agentDir),
274+
});
275+
database.db.exec(`
276+
CREATE TRIGGER reject_completed_login_state
277+
BEFORE UPDATE ON auth_profile_state
278+
BEGIN
279+
SELECT RAISE(ABORT, 'injected completed login state failure');
280+
END;
281+
`);
282+
283+
await expect(
284+
upsertAuthProfileAfterLoginWithLockOrThrow({
285+
agentDir,
286+
profileId,
287+
credential: apiKey("sk-fresh"),
288+
}),
289+
).rejects.toThrow("injected completed login state failure");
290+
291+
expect(loadPersistedAuthProfileStore(agentDir)).toEqual({
292+
version: 1,
293+
profiles: { [profileId]: apiKey("sk-stale") },
294+
usageStats: {
295+
[profileId]: {
296+
errorCount: 3,
297+
disabledUntil,
298+
disabledReason: "auth_permanent",
299+
},
300+
},
301+
});
302+
});
303+
});
304+
173305
it("reports the migration remediation instead of lock-contention retry advice", async () => {
174306
await withAgentDir(async (agentDir) => {
175307
// Credentials still living in the retired JSON store: the write can never

‎src/agents/auth-profiles/upsert-with-lock.ts‎

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ import {
1313
import { buildPersistedAuthProfileState } from "./state.js";
1414
import { saveAuthProfileStore, updateAuthProfileStoreWithLock } from "./store.js";
1515
import type { AuthProfileCredential, AuthProfileStore } from "./types.js";
16+
import { resetAuthProfileFailureState } from "./usage-state.js";
17+
18+
function throwAuthProfileUpdateError(): never {
19+
throw new Error(
20+
"Failed to update auth profile store; the auth store lock may be busy. Wait a moment and retry.",
21+
);
22+
}
1623

1724
type PersistAuthProfileBatchParams = {
1825
profiles: readonly {
@@ -157,13 +164,17 @@ export async function persistAuthProfileBatch(
157164
};
158165
}
159166

160-
/** Upserts an auth profile under the store lock, returning null on store write failure. */
161-
export async function upsertAuthProfileWithLock(params: {
167+
type AuthProfileUpsertParams = {
162168
profileId: string;
163169
credential: AuthProfileCredential;
164170
agentDir?: string;
165171
stateDir?: string;
166-
}): Promise<AuthProfileStore | null> {
172+
};
173+
174+
async function upsertAuthProfileWithLockCore(
175+
params: AuthProfileUpsertParams,
176+
resetFailureState: boolean,
177+
): Promise<AuthProfileStore | null> {
167178
const credential = normalizeAuthProfileCredential(params.credential);
168179
return await updateAuthProfileStoreWithLock({
169180
agentDir: params.agentDir,
@@ -175,19 +186,38 @@ export async function upsertAuthProfileWithLock(params: {
175186
},
176187
updater: (store) => {
177188
store.profiles[params.profileId] = credential;
189+
const existingStats = store.usageStats?.[params.profileId];
190+
if (resetFailureState && existingStats) {
191+
store.usageStats![params.profileId] = resetAuthProfileFailureState(existingStats);
192+
}
178193
return true;
179194
},
180195
});
181196
}
182197

198+
/** Upserts an auth profile under the store lock, returning null on store write failure. */
199+
export async function upsertAuthProfileWithLock(
200+
params: AuthProfileUpsertParams,
201+
): Promise<AuthProfileStore | null> {
202+
return await upsertAuthProfileWithLockCore(params, false);
203+
}
204+
183205
/** Upserts an auth profile under the store lock, failing when the store cannot be written. */
184206
export async function upsertAuthProfileWithLockOrThrow(
185207
params: Parameters<typeof upsertAuthProfileWithLock>[0],
186208
): Promise<void> {
187209
const updated = await upsertAuthProfileWithLock(params);
188210
if (!updated) {
189-
throw new Error(
190-
"Failed to update auth profile store; the auth store lock may be busy. Wait a moment and retry.",
191-
);
211+
throwAuthProfileUpdateError();
212+
}
213+
}
214+
215+
/** Replaces one completed-login credential and clears only its existing failure state. */
216+
export async function upsertAuthProfileAfterLoginWithLockOrThrow(
217+
params: AuthProfileUpsertParams,
218+
): Promise<void> {
219+
const updated = await upsertAuthProfileWithLockCore(params, true);
220+
if (!updated) {
221+
throwAuthProfileUpdateError();
192222
}
193223
}

‎src/agents/auth-profiles/usage-state.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,30 @@ import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
77
import { asDateTimestampMs } from "@openclaw/normalization-core/number-coercion";
88
import type { AuthProfileFailureReason, AuthProfileStore, ProfileUsageStats } from "./types.js";
99

10+
/** Clears failure windows while preserving unrelated usage history. */
11+
export function resetAuthProfileFailureState(
12+
existing: ProfileUsageStats,
13+
overrides?: Partial<ProfileUsageStats>,
14+
): ProfileUsageStats {
15+
return {
16+
...existing,
17+
errorCount: 0,
18+
blockedUntil: undefined,
19+
blockedReason: undefined,
20+
blockedSource: undefined,
21+
blockedModel: undefined,
22+
blockedScope: undefined,
23+
cooldownUntil: undefined,
24+
cooldownReason: undefined,
25+
cooldownClassification: undefined,
26+
cooldownModel: undefined,
27+
disabledUntil: undefined,
28+
disabledReason: undefined,
29+
failureCounts: undefined,
30+
...overrides,
31+
};
32+
}
33+
1034
/** Returns true for providers whose auth-profile cooldowns are provider-managed. */
1135
export function isAuthCooldownBypassedForProvider(provider: string | undefined): boolean {
1236
const normalized = normalizeProviderId(provider ?? "");

0 commit comments

Comments
 (0)