Skip to content

Commit ec8850b

Browse files
fix(config): settle same-key writes against the state they were issued against
CodeRabbit review comments 4454026019 (Functional Correctness, Minor) and 4454026031 (Data Integrity & Integration, Minor) against 35a8bf3. Both held. 1. A rejection now rolls the mirror back whenever the rejecting write is the newest one issued for the key, not only when it is the last write still running. When the newer of two same-key writes fails while the older one is still in flight, readers no longer report the rejected value for the duration of the older write. The landing repair from 35a8bf3 is unchanged: a landing may only write the mirror once nothing newer is in flight, so an older write that lands after a newer one failed still corrects it. 2. resetAllState now bumps a generation counter along with clearing the maps. A write issued before the reset that settles afterwards belongs to storage state that no longer exists: its success handler used to put the pre-reset value back into persistedValues (which initialize() does not clear), and a later rejected write would restore that value into stateCache. Settlements from a stale generation are ignored while the rejection is still reported to the caller. Tests (46/46 in ContextProxy.spec.ts): the out-of-order landing test now also asserts that the mirror reports the persisted value while the older write is in flight; a pre-reset write that lands after the reset leaves the key unset and does not seed a later rollback; a rejected pre-reset write does not roll back a write issued after the reset. Mutation sweep over the new lines: 14 of 15 hand-written mutants killed (success may land after a reset, failure may roll back across a reset, any rejection rolls the mirror back, landing never repairs the mirror, persisted value not advanced / never seeded / seeded from the incoming value, in-flight count never decremented, rejection leaves the write in flight, reset keeps the generation, rejection swallowed, no optimistic cache write). One survives and is disclosed rather than papered over: leaving writeSequences un-cleared on reset is not observable because the generation guard already ignores that write - it is redundant protection, and the sweep says so. Regressions: full unit suite 58 failed / 12007 passed (was 12005 before this commit), the same 15 pre-existing Windows failures. check-types: 114 pre-existing errors, none in a touched file. eslint --max-warnings=0 exits 0; eslint-suppressions.json untouched.
1 parent 35a8bf3 commit ec8850b

2 files changed

Lines changed: 94 additions & 20 deletions

File tree

‎src/core/config/ContextProxy.ts‎

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,17 @@ export class ContextProxy {
4545
private secretCache: SecretState
4646
// Writes to one key can settle out of order, and `Memento.update` batches: writes
4747
// issued before a scheduled flush share one pending promise, so a rejected batch
48-
// rejects every caller in that batch at once. Per key this tracks how many writes
49-
// are still in flight and the newest value that actually persisted. While a write
50-
// is in flight the cache optimistically holds the value that was asked for; once
51-
// nothing is in flight the cache must equal what storage holds - which is the last
52-
// write that landed, not necessarily the last one issued.
48+
// rejects every caller in that batch at once. Per key this tracks the number given
49+
// to each write, how many writes are still in flight, and the newest value that
50+
// actually persisted. While a write is in flight the cache optimistically holds the
51+
// value that was asked for; a settled write may only correct the mirror when it is
52+
// the newest one issued (a rejection) or the last one still running (a landing).
53+
// `resetAllState` bumps the generation so a write issued before it cannot repopulate
54+
// this bookkeeping when it settles afterwards.
55+
private readonly writeSequences = new Map<GlobalStateKey, number>()
5356
private readonly outstandingWrites = new Map<GlobalStateKey, number>()
5457
private readonly persistedValues = new Map<GlobalStateKey, GlobalState[GlobalStateKey]>()
58+
private stateGeneration = 0
5559
private _isInitialized = false
5660

5761
constructor(context: vscode.ExtensionContext) {
@@ -374,9 +378,12 @@ export class ContextProxy {
374378
return this.originalContext.globalState.update(key, value)
375379
}
376380

381+
const generation = this.stateGeneration
382+
const sequence = (this.writeSequences.get(key) ?? 0) + 1
383+
this.writeSequences.set(key, sequence)
377384
this.outstandingWrites.set(key, (this.outstandingWrites.get(key) ?? 0) + 1)
378385
if (!this.persistedValues.has(key)) {
379-
// First write of this key in the session: what the cache holds now came from
386+
// First write of this key in the generation: what the cache holds now came from
380387
// storage, so it is the value a rejection has to fall back to.
381388
this.persistedValues.set(key, this.stateCache[key])
382389
}
@@ -389,10 +396,10 @@ export class ContextProxy {
389396
this.stateCache[key] = value
390397
const update = Promise.resolve(this.originalContext.globalState.update(key, value))
391398

392-
// Whether this write is the last one still in flight for the key. Writes for the
393-
// same key settle independently, so only the last one standing may decide what
394-
// the cache holds; the others leave it to the newer write that is still running.
395-
const isLastWriteStanding = () => {
399+
// Retires this write and reports whether it was the last one still in flight for
400+
// the key. Writes for the same key settle independently, so a landing may only
401+
// decide what the mirror holds once nothing newer is still running.
402+
const retireWrite = () => {
396403
const remaining = (this.outstandingWrites.get(key) ?? 1) - 1
397404
if (remaining > 0) {
398405
this.outstandingWrites.set(key, remaining)
@@ -402,22 +409,37 @@ export class ContextProxy {
402409
return remaining === 0
403410
}
404411

412+
// Whether the state was reset while this write was in flight. Such a write
413+
// belongs to storage state that no longer exists: it must not put its value
414+
// back into the bookkeeping or the mirror.
415+
const belongsToCurrentState = () => generation === this.stateGeneration
416+
405417
return update.then(
406418
() => {
419+
if (!belongsToCurrentState()) {
420+
return
421+
}
422+
407423
this.persistedValues.set(key, value)
408424

409425
// Storage holds this value now. When a newer write for the same key has
410426
// already failed, this landing is what storage actually holds, so the
411427
// mirror has to follow it instead of keeping the failed write's value.
412-
if (isLastWriteStanding()) {
428+
if (retireWrite()) {
413429
this.stateCache[key] = value
414430
}
415431
},
416432
(error) => {
417-
// Fall back to the newest value that actually persisted. The map spans
418-
// every key, so its value is the union over all keys - this write's key is
419-
// the one being restored.
420-
if (isLastWriteStanding()) {
433+
retireWrite()
434+
435+
// The newest write for the key is the one storage would have ended up with,
436+
// so its rejection is rolled back to the newest value that actually
437+
// persisted, even while an older write for the same key is still running -
438+
// otherwise readers report a value that was rejected. An older rejection
439+
// leaves the mirror to the newer write that is still in flight.
440+
// The map spans every key, so its value is the union over all keys - this
441+
// write's key is the one being restored.
442+
if (belongsToCurrentState() && this.writeSequences.get(key) === sequence) {
421443
this.stateCache[key] = this.persistedValues.get(key) as GlobalState[K]
422444
}
423445
throw error
@@ -646,8 +668,11 @@ export class ContextProxy {
646668
// Clear in-memory caches
647669
this.stateCache = {}
648670
this.secretCache = {}
649-
// Nothing is persisted after a reset, so the write bookkeeping must not
650-
// remember values that storage no longer holds.
671+
// Nothing is persisted after a reset, so the write bookkeeping must not remember
672+
// values that storage no longer holds, and a write issued before the reset must
673+
// not repopulate it when it settles afterwards.
674+
this.stateGeneration++
675+
this.writeSequences.clear()
651676
this.outstandingWrites.clear()
652677
this.persistedValues.clear()
653678

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

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ describe("ContextProxy", () => {
299299
expect(proxy.getGlobalState("apiProvider")).toBe("anthropic")
300300
})
301301

302-
it("repairs the cache when an older write lands after a newer one failed", async () => {
302+
it("drops a rejected write from the cache and repairs it when an older one lands", async () => {
303303
await proxy.updateGlobalState("apiProvider", "deepseek")
304304

305305
let settleFirst: (value: undefined) => void = () => {}
@@ -312,10 +312,12 @@ describe("ContextProxy", () => {
312312
)
313313
const second = proxy.updateGlobalState("apiProvider", "anthropic")
314314

315-
// The newer write fails while the older one is still in flight, so for a moment
316-
// the cache holds only the failed write's value.
315+
// The newer write is the one storage would have ended up with, so its rejection
316+
// is rolled back to the newest value that persisted even while the older write
317+
// is still running.
317318
failSecond(new Error("globalState write failed"))
318319
await expect(second).rejects.toThrow("globalState write failed")
320+
expect(proxy.getGlobalState("apiProvider")).toBe("deepseek")
319321

320322
// The older write lands afterwards, so it is what storage holds and what the
321323
// cache has to report once nothing is in flight.
@@ -630,6 +632,53 @@ describe("ContextProxy", () => {
630632

631633
expect(proxy.getGlobalState("lastSettingsExportPath")).toBeUndefined()
632634
})
635+
636+
it("ignores a write issued before the reset when it lands afterwards", async () => {
637+
let settlePending: (value: undefined) => void = () => {}
638+
mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settlePending = resolve)))
639+
const pending = proxy.updateGlobalState("apiProvider", "openai")
640+
641+
await proxy.resetAllState()
642+
643+
settlePending(undefined)
644+
await pending
645+
646+
// The write belongs to storage state the reset discarded. Landing late must not
647+
// put its value back into the cache or into the rollback record.
648+
expect(proxy.getGlobalState("apiProvider")).toBeUndefined()
649+
650+
mockGlobalState.update.mockRejectedValueOnce(new Error("globalState write failed"))
651+
await expect(proxy.updateGlobalState("apiProvider", "anthropic")).rejects.toThrow(
652+
"globalState write failed",
653+
)
654+
655+
expect(proxy.getGlobalState("apiProvider")).toBeUndefined()
656+
})
657+
658+
it("keeps a rejected pre-reset write from rolling back a write issued after the reset", async () => {
659+
let failPending: (error: Error) => void = () => {}
660+
mockGlobalState.update.mockImplementationOnce(
661+
() => new Promise((_resolve, reject) => (failPending = reject)),
662+
)
663+
const preReset = proxy.updateGlobalState("apiProvider", "openai")
664+
665+
await proxy.resetAllState()
666+
667+
// A write issued after the reset reuses this key's first sequence number, so a
668+
// late rejection of the pre-reset write must not be mistaken for it.
669+
let settlePostReset: (value: undefined) => void = () => {}
670+
mockGlobalState.update.mockImplementationOnce(() => new Promise((resolve) => (settlePostReset = resolve)))
671+
const postReset = proxy.updateGlobalState("apiProvider", "anthropic")
672+
673+
failPending(new Error("globalState write failed"))
674+
await expect(preReset).rejects.toThrow("globalState write failed")
675+
676+
expect(proxy.getGlobalState("apiProvider")).toBe("anthropic")
677+
678+
settlePostReset(undefined)
679+
await postReset
680+
expect(proxy.getGlobalState("apiProvider")).toBe("anthropic")
681+
})
633682
})
634683

635684
describe("invalid apiProvider migration", () => {

0 commit comments

Comments
 (0)