Skip to content

Commit 9b089a2

Browse files
fix(config): keep the settings cache honest across batched same-key writes
CodeRabbit review comment 4452829726 (Data Integrity & Integration, Minor). The rollback added in 6536617 captured `previousValue` per call, but `Memento.update` batches: two writes to the same key issued before the scheduled flush share one pending promise, so a rejected batch rejects both callers and the second one rolls the key back to the first one's unflushed value - a value storage never held. Writes are now numbered per key and the newest value that actually persisted is remembered: only the newest write may touch the cache, and it restores what is persisted. `resetAllState` clears the bookkeeping along with the cache so it cannot remember values storage dropped. Tests: 4 new in `core/config/__tests__/ContextProxy.spec.ts` (42/42) - a batched rejection restores the startup value, a superseded write that fails late leaves the newer persisted value alone, an older failure cannot roll back a write that is still in flight, and the first write of a key read from storage at startup rolls back to it. Evidence: eight hand-written mutants are killed (drop the sequence guard, stop advancing the persisted value on success, stop tracking the sequence, seed the persisted value from the incoming value, never seed it, swallow the rejection, skip the cache write, restore undefined). Full unit suite: 58 failed / 12003 passed before and after this commit, the same 15 pre-existing Windows failures, no new ones (`core/webview/__tests__/ClineProvider .spec.ts` is 2 failed / 314 passed both with and without this change). `pnpm --dir src run check-types`: 114 pre-existing errors, none in a file this PR touches. ESLint exits 0 with `no-explicit-any` counts unchanged (1 and 5).
1 parent faa9c0b commit 9b089a2

2 files changed

Lines changed: 108 additions & 8 deletions

File tree

‎src/core/config/ContextProxy.ts‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ export class ContextProxy {
4343

4444
private stateCache: GlobalState
4545
private secretCache: SecretState
46+
// `Memento.update` batches: two writes to the same key issued before the scheduled
47+
// flush share one pending promise, so a rejected batch rejects both callers at once.
48+
// Each write is numbered per key and the newest value that actually persisted is
49+
// remembered, so only the newest write may roll the cache back, and it rolls back
50+
// to something that is really on disk.
51+
private readonly writeSequences = new Map<GlobalStateKey, number>()
52+
private readonly persistedValues = new Map<GlobalStateKey, GlobalState[GlobalStateKey]>()
4653
private _isInitialized = false
4754

4855
constructor(context: vscode.ExtensionContext) {
@@ -365,21 +372,35 @@ export class ContextProxy {
365372
return this.originalContext.globalState.update(key, value)
366373
}
367374

368-
const previousValue = this.stateCache[key]
369-
this.stateCache[key] = value
375+
const sequence = (this.writeSequences.get(key) ?? 0) + 1
376+
this.writeSequences.set(key, sequence)
377+
if (!this.persistedValues.has(key)) {
378+
this.persistedValues.set(key, this.stateCache[key])
379+
}
370380

371381
// The cache is globalState's in-memory mirror, so a value that never reached
372382
// disk must not stay in the mirror: readers would report a setting that the
373383
// next restart will not reproduce. Roll the key back to what is on disk and
374384
// let the rejection reach the caller. Memento.update is only specified as a
375-
// Thenable, so its result is normalized before a rejection handler is hung
376-
// off it.
385+
// Thenable, so its result is normalized before handlers are hung off it.
386+
this.stateCache[key] = value
377387
const update = Promise.resolve(this.originalContext.globalState.update(key, value))
378388

379-
return update.then(undefined, (error) => {
380-
this.stateCache[key] = previousValue
381-
throw error
382-
})
389+
return update.then(
390+
() => {
391+
this.persistedValues.set(key, value)
392+
},
393+
(error) => {
394+
// A batch also rejects writes that have since been superseded; only the
395+
// newest write for the key may touch the cache, and only back to a value
396+
// that persisted. The map spans every key, so its value is the union over
397+
// all keys - this write's key is the one being restored.
398+
if (this.writeSequences.get(key) === sequence) {
399+
this.stateCache[key] = this.persistedValues.get(key) as GlobalState[K]
400+
}
401+
throw error
402+
},
403+
)
383404
}
384405

385406
private getAllGlobalState(): GlobalState {
@@ -603,6 +624,10 @@ export class ContextProxy {
603624
// Clear in-memory caches
604625
this.stateCache = {}
605626
this.secretCache = {}
627+
// Nothing is persisted after a reset, so the write bookkeeping must not
628+
// remember values that storage no longer holds.
629+
this.writeSequences.clear()
630+
this.persistedValues.clear()
606631

607632
await Promise.all([
608633
...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)),

‎src/core/config/__tests__/ContextProxy.spec.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,20 @@ describe("ContextProxy", () => {
195195
expect(mockGlobalState.get).toHaveBeenCalledWith("taskHistory")
196196
})
197197

198+
it("restores the value read from storage at startup when the first write is rejected", async () => {
199+
// The usual shape in the field: storage already holds a value (read into the
200+
// cache at startup) and the session's first write of that key fails.
201+
mockGlobalState.get.mockImplementation((key: string) => (key === "apiProvider" ? "openrouter" : undefined))
202+
proxy = new ContextProxy(mockContext)
203+
await proxy.initialize()
204+
205+
mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed"))
206+
207+
await expect(proxy.updateGlobalState("apiProvider", "openai")).rejects.toThrow("globalState write failed")
208+
209+
expect(proxy.getGlobalState("apiProvider")).toBe("openrouter")
210+
})
211+
198212
it("keeps the value that is actually on disk when an update is rejected", async () => {
199213
await proxy.updateGlobalState("apiProvider", "deepseek")
200214
mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed"))
@@ -218,6 +232,67 @@ describe("ContextProxy", () => {
218232
expect(proxy.getValue("lastSettingsExportPath")).toBeUndefined()
219233
expect(mockGlobalState.update).toHaveBeenCalledWith("lastSettingsExportPath", "/usb/zoo-code-settings.json")
220234
})
235+
236+
it("restores the persisted value when same-key writes share a rejected batch", async () => {
237+
await proxy.updateGlobalState("apiProvider", "deepseek")
238+
239+
// Memento batches writes to one key: both calls receive the same pending
240+
// promise, so the second call captures the first call's unflushed value as its
241+
// "previous" one - rolling back to that would report a value that never existed
242+
// on disk.
243+
const sharedBatch = Promise.reject(new Error("globalState write failed"))
244+
mockGlobalState.update.mockReturnValue(sharedBatch)
245+
246+
const first = proxy.updateGlobalState("apiProvider", "openai")
247+
const second = proxy.updateGlobalState("apiProvider", "anthropic")
248+
249+
await expect(first).rejects.toThrow("globalState write failed")
250+
await expect(second).rejects.toThrow("globalState write failed")
251+
252+
// Only the newest write may touch the cache, and it rolls back to what is
253+
// actually persisted.
254+
expect(proxy.getGlobalState("apiProvider")).toBe("deepseek")
255+
})
256+
257+
it("keeps a newer persisted value when an older write for the same key rejects", async () => {
258+
let rejectFirst: (error: Error) => void = () => {}
259+
mockGlobalState.update.mockImplementationOnce(
260+
() => new Promise((_resolve, reject) => (rejectFirst = reject)),
261+
)
262+
const first = proxy.updateGlobalState("apiProvider", "openai")
263+
264+
mockGlobalState.update.mockResolvedValueOnce(undefined)
265+
await proxy.updateGlobalState("apiProvider", "anthropic")
266+
267+
rejectFirst(new Error("globalState write failed"))
268+
await expect(first).rejects.toThrow("globalState write failed")
269+
270+
// The late rejection belongs to a superseded write; the value that persisted
271+
// after it stays in the cache.
272+
expect(proxy.getGlobalState("apiProvider")).toBe("anthropic")
273+
})
274+
275+
it("does not roll back a pending write when an older one for the same key fails", async () => {
276+
let rejectFirst: (error: Error) => void = () => {}
277+
let resolveSecond: (value: undefined) => void = () => {}
278+
mockGlobalState.update.mockImplementationOnce(
279+
() => new Promise((_resolve, reject) => (rejectFirst = reject)),
280+
)
281+
const first = proxy.updateGlobalState("apiProvider", "openai")
282+
283+
mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (resolveSecond = resolve)))
284+
const second = proxy.updateGlobalState("apiProvider", "anthropic")
285+
286+
// The older write fails while the newer one is still in flight, so the only
287+
// value it could roll back to is one storage never held.
288+
rejectFirst(new Error("globalState write failed"))
289+
await expect(first).rejects.toThrow("globalState write failed")
290+
291+
resolveSecond(undefined)
292+
await second
293+
294+
expect(proxy.getGlobalState("apiProvider")).toBe("anthropic")
295+
})
221296
})
222297

223298
describe("getSecret", () => {

0 commit comments

Comments
 (0)