Skip to content

Commit ab70702

Browse files
fix(config): single-flight the reset so an overlapping caller cannot lower the guard early
resetAllState() had one guard and no owner. Two overlapping calls each ran their own delete pass, and the pass that finished first lowered the reset flag while the other was still inside its deletes, so a secret write that landed in that window was refused even though a reset was still erasing state - and, on the other side, a write that landed inside the still-running pass was erased by it. The finally added in the parent commit guarantees the flag falls when the pass it belongs to ends; it does not say which pass that is, and with two passes neither guarantee is worth much. Single-flight rather than the depth counter the reviewer proposed: a second caller joins the pass already running instead of starting one, so there is exactly one reset pass at a time and the flag cannot fall while a pass is in flight by construction rather than by arithmetic. A counter needs every entry to be matched by an exit on every path, including the throwing ones, and that is a claim about the code shape rather than about the state, which is the thing the row is about. resetAllState() drops the async keyword and returns the stored promise. That is not cosmetic: an async function hands every caller a fresh promise object, so a joined caller is indistinguishable from a second caller and the invariant cannot be observed, let alone asserted. Behaviourally the change is that a caller which arrives mid-reset now waits for a reset it did not start, and a caller that arrives after a pass settles starts a fresh one: the slot is cleared in the same finally that lowers the guard. Test: joins an in-flight reset instead of starting a second pass and keeps the guard raised until it ends. The erase double keeps a rejecter for every apiKey erase it hands back and settles them all at once, so the pass cannot hang on an erase nobody rejects; the test yields one macrotask before counting because the reset awaits its pending-write barrier before it reaches the delete pass, and apiKey is erased exactly once per pass - SECRET_STATE_KEYS in packages/types/src/global-settings.ts:361 lists it once and GLOBAL_SECRET_KEYS at :401 does not list it - so one erase is the measurement of one pass. Controls. Concurrency case first: with the parent commit's ContextProxy.ts in place it fails with Tests 1 failed | 317 passed (318) and the message is the defect - AssertionError: expected Promise{...} to be Promise{...} // Object.is equality - a second caller with a pass of its own. With single-flight: Test Files 10 passed (10), Tests 318 passed (318). Nothing existing had to move: core/config went 316 to 318 by the two cases added here and its parent, and core/webview is 34 files / 956 tests passed, identical to the same tree without these commits, so no ordering test disagreed with single-flight and none was bent. tsc -p . --noEmit exit 0, eslint --max-warnings=0 exit 0 on both files, and with --prune-suppressions the recorded counts for the two touched files stay 1 and 5, unchanged. Mutation posture: 44 added / 31 deleted lines in one executable file on a unit already measured over the 500 changed-executable-line cap against upstream main (539 for this PR head at scripts/stryker-diff.mjs), so this commit adds to an overrun that exists without it; the spec half is excluded by the /__tests__/ segment at scripts/stryker-diff.mjs:85. Review row answered: #2227 ContextProxy.ts:751 (root comment 4479544520), second half - overlapping resetAllState calls.
1 parent 32d9a10 commit ab70702

2 files changed

Lines changed: 87 additions & 31 deletions

File tree

‎src/core/config/ContextProxy.ts‎

Lines changed: 44 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,9 @@ export class ContextProxy {
410410
// A reset is in progress: the caches are meaningless mid-reset, and a secret write begun
411411
// inside it would commit after the delete pass and survive the erase.
412412
private resetting = false
413+
// The reset pass currently in flight, if any: single-flight so that two callers cannot each run a
414+
// delete pass and have whichever finishes first lower the guard under the other.
415+
private resetInFlight: Promise<void> | null = null
413416
/** How many writes of each secret were started. Unlike the owners, it is not cleared when a write is over. */
414417
private readonly secretWriteCount = new Map<string, number>()
415418

@@ -747,38 +750,48 @@ export class ContextProxy {
747750
* This clears all data from both the in-memory caches and the VSCode storage.
748751
* @returns A promise that resolves when all reset operations are complete
749752
*/
750-
public async resetAllState() {
751-
this.resetting = true
752-
try {
753-
// A secret write that is in flight at this moment has already committed nothing, but it will
754-
// commit as soon as it settles, and the deletes below cannot un-commit a write that lands
755-
// after them. Wait for the pending writes first, then end the claims, then delete, so the
756-
// cleared copy is the last one to land in storage and the cache stays empty afterwards.
757-
const inFlight = [...this.pendingSecretWrites.values()].flatMap((writes) =>
758-
[...writes].map((w) => w.settle),
759-
)
760-
await Promise.allSettled(inFlight)
761-
762-
// Clear in-memory caches
763-
this.stateCache = {}
764-
this.secretCache = {}
765-
// A reset also ends write ownership: a write that is still in flight reads the Memento back
766-
// into the cache it just lost, so clearing the caches is not enough to keep pre-reset state
767-
// out. Ownership is what the rejection handlers gate on.
768-
this.stateWriteOwner.clear()
769-
this.secretWriteOwner.clear()
770-
771-
await Promise.all([
772-
...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)),
773-
...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)),
774-
...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)),
775-
])
776-
777-
await this.initialize()
778-
this.resetting = false
779-
} finally {
780-
this.resetting = false
753+
public resetAllState(): Promise<void> {
754+
if (this.resetInFlight) {
755+
// A caller that arrives mid-reset joins the pass already running rather than starting a
756+
// second delete pass whose end could lower the guard while the first was still writing.
757+
return this.resetInFlight
781758
}
759+
this.resetting = true
760+
const pass = (async () => {
761+
try {
762+
// A secret write that is in flight at this moment has already committed nothing, but it will
763+
// commit as soon as it settles, and the deletes below cannot un-commit a write that lands
764+
// after them. Wait for the pending writes first, then end the claims, then delete, so the
765+
// cleared copy is the last one to land in storage and the cache stays empty afterwards.
766+
const inFlight = [...this.pendingSecretWrites.values()].flatMap((writes) =>
767+
[...writes].map((w) => w.settle),
768+
)
769+
await Promise.allSettled(inFlight)
770+
771+
// Clear in-memory caches
772+
this.stateCache = {}
773+
this.secretCache = {}
774+
// A reset also ends write ownership: a write that is still in flight reads the Memento back
775+
// into the cache it just lost, so clearing the caches is not enough to keep pre-reset state
776+
// out. Ownership is what the rejection handlers gate on.
777+
this.stateWriteOwner.clear()
778+
this.secretWriteOwner.clear()
779+
780+
await Promise.all([
781+
...GLOBAL_STATE_KEYS.map((key) => this.originalContext.globalState.update(key, undefined)),
782+
...SECRET_STATE_KEYS.map((key) => this.originalContext.secrets.delete(key)),
783+
...GLOBAL_SECRET_KEYS.map((key) => this.originalContext.secrets.delete(key)),
784+
])
785+
786+
await this.initialize()
787+
this.resetting = false
788+
} finally {
789+
this.resetting = false
790+
this.resetInFlight = null
791+
}
792+
})()
793+
this.resetInFlight = pass
794+
return pass
782795
}
783796

784797
private static _instance: ContextProxy | null = null

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,49 @@ describe("ContextProxy", () => {
232232
expect(await mockSecrets.get("apiKey")).toBe("written-after-failed-reset")
233233
expect(proxy.getSecret("apiKey")).toBe("written-after-failed-reset")
234234
})
235+
// Overlapping resets are the second half of the same defect: on its own the finally only
236+
// guarantees the flag falls when the pass it belongs to ends. Single-flight is the shape here
237+
// because it makes the invariant structural - a second caller joins the reset already running
238+
// rather than starting a second delete pass whose end could clear the flag while the first was
239+
// still writing.
240+
it("joins an in-flight reset instead of starting a second pass and keeps the guard raised until it ends", async () => {
241+
// Every apiKey erase handed back by the double, with its rejecter kept so the test can settle
242+
// them all at once: a held-open erase is what keeps the guard raised across the join check,
243+
// and the reset issues more than one erase per pass, so they must all be settled or the delete
244+
// pass never finishes.
245+
const erases: { reject: (error: Error) => void }[] = []
246+
mockSecrets.delete.mockImplementation((key: string) => {
247+
if (key === "apiKey") {
248+
return new Promise<void>((_, reject) => {
249+
erases.push({ reject })
250+
})
251+
}
252+
return Promise.resolve()
253+
})
254+
255+
const first = proxy.resetAllState()
256+
const second = proxy.resetAllState()
257+
258+
// One pass, not two racing delete passes: the second caller joins the reset already running.
259+
expect(second).toBe(first)
260+
// The reset yields once before it reaches its delete pass, so give it a macrotask to get there
261+
// rather than counting erases that have not been issued yet. Two passes would by now have issued
262+
// two apiKey erases, which is the defect this half of the row describes.
263+
await new Promise<void>((resolve) => {
264+
setTimeout(resolve, 10)
265+
})
266+
expect(erases.length).toBe(1)
267+
268+
erases.forEach((erase) => {
269+
erase.reject(new Error("keychain locked"))
270+
})
271+
await expect(first).rejects.toThrow("keychain locked")
272+
await expect(second).rejects.toThrow("keychain locked")
273+
274+
// The guard is down for both joiners, so the store accepts writes again.
275+
await expect(proxy.storeSecret("apiKey", "after-joined-reset")).resolves.toBeUndefined()
276+
expect(proxy.getSecret("apiKey")).toBe("after-joined-reset")
277+
})
235278

236279
it("adopts a secret write issued after a reset that waited for a pending write", async () => {
237280
const durable = new Map<string, string | undefined>()

0 commit comments

Comments
 (0)