From 01ab2855f03b9c7d8d8afd56f7adbf1a377a5c00 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 01:48:19 +0100 Subject: [PATCH 1/8] fix(webview): sweep the legacy taskHistory blob after a verified migration After the file-backed migration sets taskHistoryMigratedToFiles, the legacy globalState "taskHistory" array stayed forever, so VS Code kept weighing the whole extension state on every read and write and the large-state warning never cleared for migrated users (#1771). initializeTaskHistoryStore now runs a one-time sweep once the store is initialized. The delete happens only when the file-backed store holds every blob entry whose task directory exists, and only after the full array is backed up to legacy-task-history.backup.json in global storage and a read-back of that file matches the blob. Orphan entries (task directory gone) cannot be held by the store; the backup preserves them. Any failure keeps the blob and the next startup retries. The delete is the idempotent globalState update(key, undefined), so concurrent windows that run the same verified sweep are safe, and a window whose startup failed keeps serving the legacy fallback: getTaskHistoryItem now also reads the sweep backup when the blob is gone, so a failed provider does not report existing tasks as missing after a peer window swept. Downgrade: entries an older build appends to the blob after the marker is set have no per-task files, fail the verification gate, and keep the blob - unverified history is never deleted. A downgraded build still reads the blob directly; restoring the backup file for it stays manual, as the issue's downgrade question anticipated. SDD: new spec docs/architecture/tla/TaskHistoryMigration.tla (+MC, base + 4 variant cfgs). Base cfg passes in 650 states (TypeOK plus SweptWhenVerifiable, ClearRequiresVerification, ClearRequiresBackup, PeerClearedStaysCleared). NoSweep (the pre-fix behavior) fails SweptWhenVerifiable (218 states); NoVerify fails ClearRequiresVerification (392); NoBackup fails ClearRequiresBackup (97); StaleResurrect fails PeerClearedStaysCleared (515). Each variant run violates only its named invariant. Tests: core/webview/__tests__/ClineProvider.taskHistory.spec.ts gains a sweep suite (clear after a verified migration, keep on an unverified entry, keep on a backup failure, retry clears on the next startup, orphan backup, peer-cleared no-op, failed-init fallback reads the backup); the sweep cases fail on the pre-fix code exactly at the sweep assertions. core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts is the property test of the pure sweep decision (seeded 500-scenario loop plus deterministic edges). Sabotage-verified: removing the orphan exclusion, the verification gate, the backup-failure handling, or the empty-blob guard fails the matching test. UI/UX: no UI change; the webview already reads the file-backed store after migration. This corrects persisted state only. --- .../tla/TaskHistoryMigration.NoBackup.cfg | 7 + .../tla/TaskHistoryMigration.NoSweep.cfg | 7 + .../tla/TaskHistoryMigration.NoVerify.cfg | 7 + .../TaskHistoryMigration.StaleResurrect.cfg | 7 + .../architecture/tla/TaskHistoryMigration.cfg | 3 + .../architecture/tla/TaskHistoryMigration.tla | 191 ++++++++++ .../tla/TaskHistoryMigrationMC.tla | 8 + src/core/task-persistence/TaskHistoryStore.ts | 13 + .../__tests__/legacyTaskHistoryBlob.spec.ts | 80 ++++ .../task-persistence/legacyTaskHistoryBlob.ts | 35 ++ src/core/webview/ClineProvider.ts | 134 ++++++- .../ClineProvider.taskHistory.spec.ts | 346 +++++++++++++++++- 12 files changed, 821 insertions(+), 17 deletions(-) create mode 100644 docs/architecture/tla/TaskHistoryMigration.NoBackup.cfg create mode 100644 docs/architecture/tla/TaskHistoryMigration.NoSweep.cfg create mode 100644 docs/architecture/tla/TaskHistoryMigration.NoVerify.cfg create mode 100644 docs/architecture/tla/TaskHistoryMigration.StaleResurrect.cfg create mode 100644 docs/architecture/tla/TaskHistoryMigration.cfg create mode 100644 docs/architecture/tla/TaskHistoryMigration.tla create mode 100644 docs/architecture/tla/TaskHistoryMigrationMC.tla create mode 100644 src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts create mode 100644 src/core/task-persistence/legacyTaskHistoryBlob.ts diff --git a/docs/architecture/tla/TaskHistoryMigration.NoBackup.cfg b/docs/architecture/tla/TaskHistoryMigration.NoBackup.cfg new file mode 100644 index 00000000000..011da41a680 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoBackup.cfg @@ -0,0 +1,7 @@ +\* A sweep without the backup write clears the only copy of the blob. +\* expect-fail:ClearRequiresBackup +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + BackupEnabled <- NoBackupEnabled +INVARIANTS TypeOK ClearRequiresBackup diff --git a/docs/architecture/tla/TaskHistoryMigration.NoSweep.cfg b/docs/architecture/tla/TaskHistoryMigration.NoSweep.cfg new file mode 100644 index 00000000000..17a9931afac --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoSweep.cfg @@ -0,0 +1,7 @@ +\* The pre-fix behavior: no sweep runs, so the verified blob stays forever. +\* expect-fail:SweptWhenVerifiable +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + SweepEnabled <- NoSweepEnabled +INVARIANTS TypeOK SweptWhenVerifiable diff --git a/docs/architecture/tla/TaskHistoryMigration.NoVerify.cfg b/docs/architecture/tla/TaskHistoryMigration.NoVerify.cfg new file mode 100644 index 00000000000..fc2289ab426 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoVerify.cfg @@ -0,0 +1,7 @@ +\* A sweep without the store-verification guard deletes unverified history. +\* expect-fail:ClearRequiresVerification +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + VerifyEnabled <- NoVerifyEnabled +INVARIANTS TypeOK ClearRequiresVerification diff --git a/docs/architecture/tla/TaskHistoryMigration.StaleResurrect.cfg b/docs/architecture/tla/TaskHistoryMigration.StaleResurrect.cfg new file mode 100644 index 00000000000..0b04a350f79 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.StaleResurrect.cfg @@ -0,0 +1,7 @@ +\* A stale in-memory array written back after a peer clear fills the blob. +\* expect-fail:PeerClearedStaysCleared +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ResurrectEnabled <- StaleResurrectEnabled +INVARIANTS TypeOK PeerClearedStaysCleared diff --git a/docs/architecture/tla/TaskHistoryMigration.cfg b/docs/architecture/tla/TaskHistoryMigration.cfg new file mode 100644 index 00000000000..6911d1dc205 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS TypeOK SweptWhenVerifiable ClearRequiresVerification ClearRequiresBackup PeerClearedStaysCleared diff --git a/docs/architecture/tla/TaskHistoryMigration.tla b/docs/architecture/tla/TaskHistoryMigration.tla new file mode 100644 index 00000000000..9db0d62d6c0 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.tla @@ -0,0 +1,191 @@ +---- MODULE TaskHistoryMigration ---- +(***************************************************************************) +(* Source: ClineProvider.initializeTaskHistoryStore reads the legacy *) +(* globalState "taskHistory" array and sets the *) +(* taskHistoryMigratedToFiles marker after TaskHistoryStore migration. *) +(* Sink: globalState.update("taskHistory", undefined) after a verified *) +(* migration, and the uninitialized getTaskHistoryItem fallback read. *) +(* *) +(* Failure: the legacy taskHistory blob survives a startup that completed *) +(* a verified migration, so it weighs globalState down forever. *) +(* Invariant: SweptWhenVerifiable. *) +(* *) +(* Other failures this spec guards: *) +(* - A sweep clears the blob while a blob entry whose task directory *) +(* exists is not held by the file store. Unverified history must never *) +(* be deleted. Invariant: ClearRequiresVerification. *) +(* - A sweep clears the blob before a backup holds its full content. *) +(* Invariant: ClearRequiresBackup. *) +(* - A stale in-memory array is written back after a peer window cleared *) +(* the shared blob. Invariant: PeerClearedStaysCleared. *) +(* *) +(* Model: one startup performs initialization, migration and the sweep in *) +(* one step, as the code runs them in one async chain. A startup whose *) +(* migration fails keeps the marker unset and the blob. An orphan entry *) +(* has no task directory; migration cannot write it, and the backup *) +(* preserves it. Orphans do not block a sweep. DowngradeAppend models an *) +(* old build that re-writes the legacy list while the marker is set. Its *) +(* new entries are unverified, so the sweep keeps the blob. *) +(* *) +(* Constants: SweepEnabled, VerifyEnabled and BackupEnabled guard the *) +(* fix. ResurrectEnabled enables a stale write-back for the sabotage *) +(* check. MaxStartups bounds the retries. *) +(* *) +(* Replay: ClineProvider.taskHistory.spec.ts sweeps the blob after a *) +(* verified migration and keeps it on an unverified entry, on a backup *) +(* failure, and after a peer clear. The uninitialized fallback reads the *) +(* sweep backup. The sweep tests fail on the pre-fix code. *) +(* legacyTaskHistoryBlob.spec.ts is the property test of the pure *) +(* sweep decision. *) +(* *) +(* Result: fixed holds (650 states). NoSweep, the pre-fix behavior, fails *) +(* SweptWhenVerifiable (218 states). NoVerify fails *) +(* ClearRequiresVerification (392 states). NoBackup fails *) +(* ClearRequiresBackup (97 states). StaleResurrect fails *) +(* PeerClearedStaysCleared (515 states). Each variant run violates its *) +(* named invariant only. No further failure was found. *) +(* Cost: about 1 minute for all five configs on 4 cores. *) +(* Review ratchet: 0 covered, 0 added, 0 gap (first version). *) +(***************************************************************************) +EXTENDS Integers + +MaxStartups == 2 +SweepEnabled == TRUE +VerifyEnabled == TRUE +BackupEnabled == TRUE +ResurrectEnabled == FALSE + +Ids == {"t1", "t2"} + +VARIABLES blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts +vars == <> + +Held(ids, storeSet) == (ids \cap dirs) \subseteq storeSet + +Init == + /\ blob \in SUBSET Ids + /\ store \in SUBSET Ids + /\ dirs \in SUBSET Ids + /\ backup = {} + /\ marker = FALSE + /\ initialized = FALSE + /\ cleared = FALSE + /\ verifiedAtClear = FALSE + /\ peerCleared = FALSE + /\ attempts = 0 + +(* First startup: initialize the store, migrate entries whose task + directories exist, set the marker, then run the sweep decision. *) +A1 == + /\ attempts < MaxStartups + /\ ~initialized + /\ attempts' = attempts + 1 + /\ marker' = TRUE + /\ initialized' = TRUE + /\ store' = store \cup (blob \cap dirs) + /\ (IF SweepEnabled /\ blob # {} /\ (~VerifyEnabled \/ Held(blob, store')) + THEN /\ backup' = IF BackupEnabled THEN blob ELSE backup + /\ blob' = {} + /\ cleared' = TRUE + /\ verifiedAtClear' = Held(blob, store') + ELSE /\ backup' = backup + /\ blob' = blob + /\ cleared' = cleared + /\ verifiedAtClear' = verifiedAtClear) + /\ dirs' = dirs + /\ peerCleared' = peerCleared + +(* A startup whose migration fails. The marker stays unset, the blob + stays, and the next startup retries. *) +A1MigrationFails == + /\ attempts < MaxStartups + /\ ~initialized + /\ attempts' = attempts + 1 + /\ UNCHANGED <> + +(* A later startup with the marker already set. Migration is skipped, so + entries that appeared after the marker are verified against the store + as they are. This is the one-time sweep for already migrated users. *) +RetrySweep == + /\ attempts < MaxStartups + /\ initialized + /\ marker + /\ attempts' = attempts + 1 + /\ store' = store + /\ (IF SweepEnabled /\ blob # {} /\ (~VerifyEnabled \/ Held(blob, store)) + THEN /\ backup' = IF BackupEnabled THEN blob ELSE backup + /\ blob' = {} + /\ cleared' = TRUE + /\ verifiedAtClear' = Held(blob, store) + ELSE /\ backup' = backup + /\ blob' = blob + /\ cleared' = cleared + /\ verifiedAtClear' = verifiedAtClear) + /\ dirs' = dirs + /\ marker' = marker + /\ initialized' = initialized + /\ peerCleared' = peerCleared + +(* A peer window completed its own verified sweep between our startups. + It deletes the shared blob and writes the shared backup file. *) +PeerClear == + /\ marker + /\ blob # {} + /\ blob' = {} + /\ backup' = blob + /\ peerCleared' = TRUE + /\ UNCHANGED <> + +(* An old build re-writes the legacy list while the marker is set. Its + entries were never migrated, so they are not held by the store. *) +DowngradeAppend == + /\ marker + /\ ~peerCleared + /\ attempts < MaxStartups + /\ \E id \in Ids \ blob : + /\ blob' = blob \cup {id} + /\ UNCHANGED <> + +(* Sabotage only: a buggy variant writes a stale in-memory array back + after a peer cleared the shared blob. *) +Resurrect == + /\ ResurrectEnabled + /\ peerCleared + /\ blob' = Ids + /\ UNCHANGED <> + +Next == A1 \/ A1MigrationFails \/ RetrySweep \/ PeerClear \/ DowngradeAppend \/ Resurrect + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ blob \subseteq Ids + /\ store \subseteq Ids + /\ dirs \subseteq Ids + /\ backup \subseteq Ids + /\ marker \in BOOLEAN + /\ initialized \in BOOLEAN + /\ cleared \in BOOLEAN + /\ verifiedAtClear \in BOOLEAN + /\ peerCleared \in BOOLEAN + /\ attempts \leq MaxStartups + +(* No startup that finished a verified migration leaves the blob behind. + A blob that survives is unverified, so the sweep kept it on purpose. *) +SweptWhenVerifiable == + (initialized /\ attempts >= MaxStartups) => + (\/ blob = {} + \/ ~Held(blob, store)) + +(* A sweep only clears after every entry with a task directory is held + by the file store. *) +ClearRequiresVerification == cleared => verifiedAtClear + +(* A sweep only clears after a backup holds the full blob. *) +ClearRequiresBackup == cleared => backup # {} + +(* After a peer cleared the shared blob, no stale write-back fills it. *) +PeerClearedStaysCleared == ~( + peerCleared /\ blob # {}) + +==== diff --git a/docs/architecture/tla/TaskHistoryMigrationMC.tla b/docs/architecture/tla/TaskHistoryMigrationMC.tla new file mode 100644 index 00000000000..82fcec9997f --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigrationMC.tla @@ -0,0 +1,8 @@ +---- MODULE TaskHistoryMigrationMC ---- +\* Sabotage operator values for the variant configs. +EXTENDS TaskHistoryMigration +NoSweepEnabled == FALSE +NoVerifyEnabled == FALSE +NoBackupEnabled == FALSE +StaleResurrectEnabled == TRUE +==== diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts index e0bb54998c3..cab2f699778 100644 --- a/src/core/task-persistence/TaskHistoryStore.ts +++ b/src/core/task-persistence/TaskHistoryStore.ts @@ -1311,6 +1311,19 @@ export class TaskHistoryStore { // ────────────────────────────── Private: Path helpers ────────────────────────────── + /** + * Check whether a task directory exists without reading its files. + */ + async hasTaskDir(taskId: string): Promise { + try { + const tasksDir = await this.getTasksDir() + await fs.access(path.join(tasksDir, taskId)) + return true + } catch { + return false + } + } + /** * Get the tasks base directory path, resolving custom storage paths. */ diff --git a/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts new file mode 100644 index 00000000000..0a9e46d974c --- /dev/null +++ b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from "vitest" +import type { HistoryItem } from "@roo-code/types" +import { planLegacyBlobSweep } from "../legacyTaskHistoryBlob" + +// pnpm --filter zoo-code test core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts + +/** + * Deterministic LCG so a failure reproduces with the same scenario set. + */ +function makeRng(seed: number) { + let s = seed >>> 0 + return () => { + s = (s * 1664525 + 1013904223) >>> 0 + return s / 4294967296 + } +} + +const IDS = ["t1", "t2", "t3"] + +const makeEntries = (rng: () => number): HistoryItem[] => + IDS.filter(() => rng() < 0.5).map((id) => ({ number: 1, ts: 1, id, task: id }) as HistoryItem) + +const pickSet = (rng: () => number): Set => new Set(IDS.filter(() => rng() < 0.5)) + +describe("planLegacyBlobSweep", () => { + it("clears only when every non-orphan entry is held and a backup exists", () => { + const rng = makeRng(20261206) + for (let i = 0; i < 500; i++) { + const entries = makeEntries(rng) + const held = pickSet(rng) + const orphans = pickSet(rng) + const backupWritten = rng() < 0.5 + const decision = planLegacyBlobSweep(entries, held, orphans, backupWritten) + const nonOrphans = entries.map((entry) => entry.id!).filter((id) => !orphans.has(id)) + const allHeld = nonOrphans.every((id) => held.has(id)) + const scenario = JSON.stringify({ + entries: entries.map((e) => e.id), + nonOrphans, + held: [...held], + orphans: [...orphans], + backupWritten, + }) + if (decision.action === "clear") { + expect(backupWritten, scenario).toBe(true) + expect(allHeld, scenario).toBe(true) + } else if (!allHeld) { + expect(decision.reason, scenario).toBe("unverified-entries") + expect(decision.unverifiedIds.sort(), scenario).toStrictEqual( + nonOrphans.filter((id) => !held.has(id)).sort(), + ) + } else { + expect(decision.reason, scenario).toBe(backupWritten ? undefined : "backup-unwritten") + } + } + }) + + it("keeps with the unverified ids listed when a directory-backed entry is missing", () => { + const entries = [{ id: "t1" }, { id: "t2" }] as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(), true) + expect(decision).toStrictEqual({ action: "keep", reason: "unverified-entries", unverifiedIds: ["t2"] }) + }) + + it("keeps with backup-unwritten before the backup write even when everything is held", () => { + const entries = [{ id: "t1" }] as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(), false) + expect(decision).toStrictEqual({ action: "keep", reason: "backup-unwritten", unverifiedIds: [] }) + }) + + it("clears orphans too once they are backed up", () => { + const entries = [{ id: "t1" }, { id: "t2" }] as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(["t2"]), true) + expect(decision).toStrictEqual({ action: "clear" }) + }) + + it("ignores id-less entries like orphans", () => { + const entries = [{ id: "t1" }, { task: "no-id" }] as unknown as HistoryItem[] + const decision = planLegacyBlobSweep(entries, new Set(["t1"]), new Set(), true) + expect(decision).toStrictEqual({ action: "clear" }) + }) +}) diff --git a/src/core/task-persistence/legacyTaskHistoryBlob.ts b/src/core/task-persistence/legacyTaskHistoryBlob.ts new file mode 100644 index 00000000000..cfd5a3b1965 --- /dev/null +++ b/src/core/task-persistence/legacyTaskHistoryBlob.ts @@ -0,0 +1,35 @@ +import type { HistoryItem } from "@roo-code/types" + +export const LEGACY_TASK_HISTORY_BACKUP_FILE = "legacy-task-history.backup.json" + +export type LegacyBlobSweepDecision = + { action: "keep"; reason: "unverified-entries" | "backup-unwritten"; unverifiedIds: string[] } | { action: "clear" } + +/** + * Decide whether the legacy globalState taskHistory blob can be removed. + * + * The file-backed store must hold every entry whose task directory still + * exists, and a backup must hold the full array before the delete. Entries + * without an id were never migrated, so they count like orphans here. + */ +export function planLegacyBlobSweep( + entries: HistoryItem[], + storeHeldIds: ReadonlySet, + orphanIds: ReadonlySet, + backupWritten: boolean, +): LegacyBlobSweepDecision { + const unverifiedIds = entries + .map((item) => item?.id) + .filter((id): id is string => Boolean(id)) + .filter((id) => !orphanIds.has(id) && !storeHeldIds.has(id)) + + if (unverifiedIds.length > 0) { + return { action: "keep", reason: "unverified-entries", unverifiedIds } + } + + if (!backupWritten) { + return { action: "keep", reason: "backup-unwritten", unverifiedIds: [] } + } + + return { action: "clear" } +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 78ad36cd97c..81c825c0da2 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -153,8 +153,11 @@ import { interruptDelegatedChild, LifecycleTransitionError, } from "../task-persistence" +import { LEGACY_TASK_HISTORY_BACKUP_FILE, planLegacyBlobSweep } from "../task-persistence/legacyTaskHistoryBlob" import { readTaskMessages } from "../task-persistence/taskMessages" import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry" +import deepEqual from "fast-deep-equal" +import { safeWriteJson } from "../../utils/safeWriteJson" import { TaskTitleService } from "../task-title/TaskTitleService" import { getNonce } from "./getNonce" import { getUri } from "./getUri" @@ -330,8 +333,13 @@ export class ClineProvider private recentTasksCache?: string[] public readonly taskHistoryStore: TaskHistoryStore + private readonly taskTitleService: TaskTitleService private taskHistoryStoreInitialized = false + /** Storage root of the legacy blob sweep backup, resolved once. */ + private legacyBackupPath: string | undefined + /** Parsed legacy blob backup; undefined = not read yet, null = absent or unparsable. */ + private legacyBackupItems: HistoryItem[] | null | undefined public static readonly PENDING_OPERATION_TIMEOUT_MS = 30000 // 30 seconds private providerProfileMutationQueue = Promise.resolve() private historyTaskCreationQueue = Promise.resolve() @@ -648,6 +656,14 @@ export class ClineProvider type: "initialize", elapsedMs: Date.now() - startedAt, }) + try { + await this.sweepLegacyTaskHistoryBlob() + } catch (error) { + // Keep the legacy blob; the next startup retries the sweep. + this.log( + `[initializeTaskHistoryStore] Legacy blob sweep deferred: ${error instanceof Error ? error.message : String(error)}`, + ) + } } catch (error) { this.diagnosticsRecorder.record({ boundary: "task-history", @@ -659,6 +675,103 @@ export class ClineProvider } } + /** + * Remove the legacy globalState taskHistory blob after a verified migration. + * + * The delete runs only when the file-backed store holds every entry whose + * task directory exists and a backup file holds the full array. Orphan + * entries have no task directory; the backup preserves them. Any failure + * keeps the blob, and the next startup retries. A second window that + * already cleared the blob makes this a no-op. + */ + private async sweepLegacyTaskHistoryBlob(): Promise { + const legacyHistory = this.context.globalState.get("taskHistory") ?? [] + if (legacyHistory.length === 0) { + return + } + + const storeHeldIds = new Set() + const orphanIds = new Set() + for (const item of legacyHistory) { + if (!item?.id) { + // Migration skipped entries without an id; the backup preserves them. + continue + } + if (!(await this.taskHistoryStore.hasTaskDir(item.id))) { + orphanIds.add(item.id) + continue + } + if (this.taskHistoryStore.get(item.id)) { + storeHeldIds.add(item.id) + } + } + + const preflight = planLegacyBlobSweep(legacyHistory, storeHeldIds, orphanIds, false) + if (preflight.action === "keep" && preflight.reason === "unverified-entries") { + this.log( + `[initializeTaskHistoryStore] Keeping legacy taskHistory blob (unverified-entries: ${preflight.unverifiedIds.join(", ")})`, + ) + return + } + + const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) + await safeWriteJson(backupPath, legacyHistory) + + let backup: HistoryItem[] | null = null + try { + const raw = await fs.readFile(backupPath, "utf8") + const parsed: unknown = JSON.parse(raw) + backup = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null + } catch { + backup = null + } + if (!backup || !deepEqual(backup, legacyHistory)) { + this.log("[initializeTaskHistoryStore] Keeping legacy taskHistory blob: backup read-back did not match") + return + } + + const decision = planLegacyBlobSweep(legacyHistory, storeHeldIds, orphanIds, true) + if (decision.action !== "clear") { + this.log(`[initializeTaskHistoryStore] Keeping legacy taskHistory blob (${decision.reason})`) + return + } + + // VS Code defines update(key, undefined) as removal; the delete is + // idempotent across windows that run the same verified sweep. + await this.context.globalState.update("taskHistory", undefined) + this.log( + `[initializeTaskHistoryStore] Removed the legacy taskHistory blob; ${legacyHistory.length} entries are backed up in ${LEGACY_TASK_HISTORY_BACKUP_FILE}`, + ) + } + + /** + * Storage root for the legacy blob backup, resolved once per provider. + */ + private async getLegacyBackupBasePath(): Promise { + if (!this.legacyBackupPath) { + const { getStorageBasePath } = await import("../../utils/storage") + this.legacyBackupPath = await getStorageBasePath(this.contextProxy.globalStorageUri.fsPath) + } + return this.legacyBackupPath + } + + /** + * Read an item from the legacy blob sweep backup, parsed once. + */ + private async getLegacyBackupItem(id: string): Promise { + if (this.legacyBackupItems === undefined) { + try { + const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) + const raw = await fs.readFile(backupPath, "utf8") + const parsed: unknown = JSON.parse(raw) + this.legacyBackupItems = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null + } catch { + this.legacyBackupItems = null + } + } + return this.legacyBackupItems?.find((item) => item?.id === id) ?? undefined + } + /** * Override EventEmitter's on method to match TaskProviderLike interface */ @@ -2118,7 +2231,7 @@ export class ClineProvider try { // Update the task history with the new mode first. - const taskHistoryItem = this.getTaskHistoryItem(task.taskId) + const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) if (taskHistoryItem) { await this.updateTaskHistory({ ...taskHistoryItem, mode: newMode }) @@ -2500,7 +2613,7 @@ export class ClineProvider // been persisted into taskHistory (it will be captured on the next save). task.setTaskApiConfigName(apiConfigName) - const taskHistoryItem = this.getTaskHistoryItem(task.taskId) + const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) if (taskHistoryItem) { await this.updateTaskHistory({ ...taskHistoryItem, apiConfigName }) @@ -2767,7 +2880,7 @@ export class ClineProvider // Task history - private getTaskHistoryItem(id: string): HistoryItem | undefined { + private async getTaskHistoryItem(id: string): Promise { const historyItem = this.taskHistoryStore.get(id) // Once initialization and migration succeed, the file-backed store is authoritative. @@ -2776,7 +2889,14 @@ export class ClineProvider return historyItem } - return (this.getGlobalState("taskHistory") ?? []).find((item) => item.id === id) + const legacyItem = (this.getGlobalState("taskHistory") ?? []).find((item) => item.id === id) + if (legacyItem) { + return legacyItem + } + + // A peer window may have swept the blob while this provider's startup failed; + // the sweep backup keeps the fallback working in that window. + return this.getLegacyBackupItem(id) } async getTaskWithId(id: string): Promise<{ @@ -2786,7 +2906,7 @@ export class ClineProvider uiMessagesFilePath: string apiConversationHistory: Anthropic.MessageParam[] }> { - const historyItem = this.getTaskHistoryItem(id) + const historyItem = await this.getTaskHistoryItem(id) if (!historyItem) { throw new Error("Task not found") @@ -2820,11 +2940,11 @@ export class ClineProvider historyItem: HistoryItem aggregatedCosts: AggregatedCosts }> { - const historyItem = this.getTaskHistoryItem(taskId) + const historyItem = await this.getTaskHistoryItem(taskId) if (!historyItem) throw new Error("Task not found") const aggregatedCosts = await aggregateTaskCostsRecursive(taskId, async (id: string) => { - const item = this.getTaskHistoryItem(id) + const item = await this.getTaskHistoryItem(id) if (!item) throw new Error("Task not found") return item }) diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index e16badb3482..715844ea822 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -20,16 +20,22 @@ vi.mock("p-wait-for", () => ({ default: vi.fn().mockResolvedValue(undefined), })) -vi.mock("fs/promises", () => ({ - mkdir: vi.fn().mockResolvedValue(undefined), - writeFile: vi.fn().mockResolvedValue(undefined), - readFile: vi.fn().mockResolvedValue(""), - readdir: vi.fn().mockResolvedValue([]), - unlink: vi.fn().mockResolvedValue(undefined), - rmdir: vi.fn().mockResolvedValue(undefined), - access: vi.fn().mockResolvedValue(undefined), - rm: vi.fn().mockResolvedValue(undefined), -})) +vi.mock("fs/promises", () => { + // The same object backs the named exports and `default`, so default + // importers (`import fs from "fs/promises"`) hit the same mocked fns. + const mock = { + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + readdir: vi.fn().mockResolvedValue([]), + stat: vi.fn(), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + access: vi.fn().mockResolvedValue(undefined), + rm: vi.fn().mockResolvedValue(undefined), + } + return { ...mock, default: mock } +}) vi.mock("axios", () => ({ default: { @@ -1321,3 +1327,323 @@ describe("ClineProvider Task History Synchronization", () => { ) }) }) + +describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { + const STORAGE_ROOT = "/test/storage/path" + const TASKS_DIR = `${STORAGE_ROOT}/tasks` + const BACKUP_PATH = `${STORAGE_ROOT}/legacy-task-history.backup.json` + + const makeItem = (id: string, task: string): HistoryItem => ({ + number: 1, + ts: 1700000000000 + id.length, + tokensIn: 10, + tokensOut: 5, + totalCost: 0.01, + id, + task, + }) + + describe("sweep after a verified migration", () => { + let provider: ClineProvider + let context: vscode.ExtensionContext + let outputChannel: vscode.OutputChannel + let state: Record + const memFiles = new Map() + const memDirs = new Set() + + const errno = (code: string, p: string): NodeJS.ErrnoException => { + const err: NodeJS.ErrnoException = new Error(`${code}: ${p}`) + err.code = code + return err + } + + const toKey = (p: unknown): string => (typeof p === "string" ? p : String(p)) + + const wireFsMocks = async () => { + fsMockRef = await import("fs/promises") + const fsMock = fsMockRef + vi.mocked(fsMock.mkdir).mockReset().mockResolvedValue(undefined) + vi.mocked(fsMock.access) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + if (memDirs.has(key) || Array.from(memFiles.keys()).some((k) => k.startsWith(`${key}/`))) { + return undefined + } + throw errno("ENOENT", key) + }) + vi.mocked(fsMock.readFile) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + vi.mocked(fsMock.readdir) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + const names = new Set() + for (const k of memFiles.keys()) { + if (k.startsWith(`${key}/`)) { + const rest = k.slice(key.length + 1) + if (!rest.includes("/")) names.add(rest) + } + } + for (const d of memDirs) { + if (d.startsWith(`${key}/`)) { + const rest = d.slice(key.length + 1) + if (!rest.includes("/")) names.add(rest) + } + } + return Array.from(names) as never + }) + vi.mocked(fsMock.stat) + .mockReset() + .mockImplementation(async (p) => { + const key = toKey(p) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return { mtimeMs: content.length } as never + }) + const swj = (swjRef = await import("../../../utils/safeWriteJson")) + vi.mocked(swj.safeWriteJson) + .mockReset() + .mockImplementation(async (p, data) => { + memFiles.set(toKey(p), JSON.stringify(data, null, " ")) + return undefined as never + }) + } + + let fsMockRef: typeof import("fs/promises") + let swjRef: typeof import("../../../utils/safeWriteJson") + + const buildProvider = async (options: { + globalState: Record + dirs?: string[] + files?: Record + beforeFlush?: () => void + }): Promise => { + vi.clearAllMocks() + memFiles.clear() + memDirs.clear() + for (const d of options.dirs ?? []) { + memDirs.add(d) + } + for (const [k, v] of Object.entries(options.files ?? {})) { + memFiles.set(k, v) + } + state = { taskHistoryMigratedToFiles: false, ...options.globalState } + + const secrets: Record = {} + context = { + extensionPath: "/test/path", + extensionUri: { fsPath: "/test/path" } as vscode.Uri, + globalState: { + get: vi.fn().mockImplementation((key: string) => state[key]), + update: vi.fn().mockImplementation((key: string, value: unknown) => { + state[key] = value + return Promise.resolve() + }), + keys: vi.fn().mockImplementation(() => Object.keys(state)), + }, + secrets: { + get: vi.fn().mockImplementation((key: string) => secrets[key]), + store: vi + .fn() + .mockImplementation((key: string, value: string | undefined) => (secrets[key] = value)), + delete: vi.fn().mockImplementation((key: string) => void delete secrets[key]), + }, + workspaceState: { + get: vi.fn().mockReturnValue(undefined), + update: vi.fn().mockResolvedValue(undefined), + keys: vi.fn().mockReturnValue([]), + }, + subscriptions: [], + extension: { packageJSON: { version: "1.0.0" } }, + globalStorageUri: { fsPath: STORAGE_ROOT }, + } as unknown as vscode.ExtensionContext + + outputChannel = { + appendLine: vi.fn(), + clear: vi.fn(), + dispose: vi.fn(), + } as unknown as vscode.OutputChannel + + await wireFsMocks() + + provider = new ClineProvider( + context, + outputChannel, + "sidebar", + new ContextProxy(context), + new WebviewFocusTracker(), + ) + // Synchronous hook: it must land before the constructor's async + // init chain resumes in the flush below. + options.beforeFlush?.() + // Long enough for reconcile's ENOENT retry path to settle. + await new Promise((resolve) => setTimeout(resolve, 250)) + + ;(provider as unknown as Record)["customModesManager"] = { + updateCustomMode: vi.fn().mockResolvedValue(undefined), + getCustomModes: vi.fn().mockResolvedValue([]), + dispose: vi.fn(), + } + provider.getMcpHub = vi.fn().mockReturnValue({ + listTools: vi.fn().mockResolvedValue([]), + callTool: vi.fn().mockResolvedValue({ content: [] }), + listResources: vi.fn().mockResolvedValue({ contents: [] }), + readResource: vi.fn().mockResolvedValue({ contents: [] }), + getAllServers: vi.fn().mockReturnValue([]), + }) + return provider + } + + it("clears the legacy blob and writes a backup after a verified migration", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemB] }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " "), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, " "), + }, + }) + + // The migration log proves the marker flow ran before the sweep. + const initLog = vi + .mocked(outputChannel.appendLine) + .mock.calls.map((call) => String(call[0])) + .join(" | ") + expect(initLog).toContain("[initializeTaskHistoryStore] Migration complete") + expect(p["taskHistoryStoreInitialized"]).toBe(true) + // The blob must be gone from globalState, and the backup must hold + // the full array before the delete. + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup.map((item) => item.id).sort()).toStrictEqual(["task-a", "task-b"]) + }) + + it("keeps the blob when an entry with a task directory is not held by the store", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + await buildProvider({ + globalState: { taskHistory: [itemA, itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + }) + + // task-b has a task directory but no store entry: deleting the blob + // would destroy unverified history, so the sweep must keep it. + expect(provider["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA, itemB]) + expect(memFiles.has(BACKUP_PATH)).toBe(false) + }) + + it("keeps the blob when the backup write fails", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + beforeFlush: () => { + // Only the sweep's backup write fails; init-time repair writes go through. + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { + if (toKey(p) === BACKUP_PATH) { + throw new Error("disk full") + } + memFiles.set(toKey(p), JSON.stringify(data, null, " ")) + return undefined as never + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + }) + + it("clears the blob on a later startup after a failed sweep", async () => { + const itemA = makeItem("task-a", "A") + const seeds = { + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + } + const first = await buildProvider({ + ...seeds, + beforeFlush: () => { + // Only the sweep's backup write fails; init-time repair writes go through. + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { + if (toKey(p) === BACKUP_PATH) { + throw new Error("disk full") + } + memFiles.set(toKey(p), JSON.stringify(data, null, " ")) + return undefined as never + }) + }, + }) + const firstContext = context + const firstState = state + expect(first["taskHistoryStoreInitialized"]).toBe(true) + expect(firstContext.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + + const second = await buildProvider({ ...seeds, files: { ...seeds.files } }) + expect(second["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(firstState.taskHistory).toStrictEqual([itemA]) + }) + + it("sweeps the blob when only orphan entries lack task directories", async () => { + const itemA = makeItem("task-a", "A") + const itemOrphan = makeItem("task-orphan", "Orphan") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemOrphan], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, + }) + + // The orphan has no task directory, so the store can never hold it. + // The backup preserves it and the sweep proceeds. + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup.map((item) => item.id).sort()).toStrictEqual(["task-a", "task-orphan"]) + }) + + it("does nothing when a peer window already cleared the blob", async () => { + await buildProvider({ globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true } }) + + expect(provider["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(memFiles.has(BACKUP_PATH)).toBe(false) + }) + + it("failed-initialization fallback reads the sweep backup when the blob is gone", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, " ") }, + beforeFlush: () => { + // Every mkdir call fails, so TaskHistoryStore.initialize() throws. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + }, + }) + + // The store never initialized, so the provider still serves the legacy + // fallback; the blob was swept by a peer, and the backup takes over. + expect(p["taskHistoryStoreInitialized"]).toBe(false) + const item = await p["getTaskHistoryItem"]("task-a") + expect(item?.id).toBe("task-a") + }) + }) +}) From 2a2251eb8865cd0b1e50afaac966668d155c9335 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 02:08:04 +0100 Subject: [PATCH 2/8] test(webview): normalize path separators in the taskHistory sweep harness The in-memory fs keys use forward slashes while production path.join emits backslashes on Windows, so the Windows CI run missed every directory lookup and six sweep cases failed. toKey now normalizes separators before every map lookup. --- src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index 715844ea822..98270ac07be 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -1357,7 +1357,9 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { return err } - const toKey = (p: unknown): string => (typeof p === "string" ? p : String(p)) + // Normalize separators: production path.join emits backslashes on + // Windows, while the in-memory keys use forward slashes. + const toKey = (p: unknown): string => String(p).replace(/\\/g, "/") const wireFsMocks = async () => { fsMockRef = await import("fs/promises") From b43fc8aaf01482abc9455978382e28e80f1c59f6 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 03:23:59 +0100 Subject: [PATCH 3/8] fix(webview): keep the legacy blob when the sweep window or backup is unsafe CodeRabbit round 1 on PR 2873 (1 Major + 7 Minors), all verified against the code and fixed: - Major 4814458162: the sweep cleared globalState after awaits without re-reading it, so an entry a downgraded build appended mid-sweep was deleted outside the backup. The clear now compares the current blob with the array it read and keeps the blob on a mismatch; the next startup retries. - The sweep backup write merges the existing backup file (new pure mergeLegacyBackup): entries only an earlier sweep backed up (orphans) survive; a transient read error defers the sweep instead of risking an overwrite. TLC PeerOverwrite showed the old overwrite lost such an orphan (ClearRequiresBackup, 2178 states). - hasTaskDir returns false only on confirmed absence (ENOENT/ENOTDIR) and rethrows EACCES/EIO, so an unreadable directory no longer counts as an orphan; the sweep defers and keeps the blob. - getLegacyBackupItem caches null only for confirmed absence; transient read errors stay retryable, so the failed-init fallback recovers when storage recovers. SDD (docs/architecture/tla/AGENTS.md): TaskHistoryMigration restructured into interleavable sweep actions (SweepRead via A1/RetrySweep, Verify, BackupWrite, ReadBack, ClearBlob) with DowngradeAppend between any two, backup io-failure outcomes (backupOk), content-based ClearRequiresBackup (clearedSet), AppendedEntryNeverLost invariant for the mid-sweep append window, and peer merge modeling. Ratchet: 2 covered, 4 added, 2 gap. TLC (check.sh TaskHistoryMigration): base pass 3,449 states; NoSweep 218, NoVerify 2,258, NoBackup 1,181, StaleResurrect 476, NoCompareGuard 1,762, PeerOverwrite 2,178 - each fails exactly its named invariant. Tests: 4 new behavior tests were RED on the pre-fix code (guard, merge, access rethrow, retry); read-back mismatch, unreadable backup, and pending-write order cases are sabotage-verified. Gates: test:core 5,341, test:api 6,417, scoped vitest 73, tsc, eslint, prettier. Closes #1771 --- .../TaskHistoryMigration.NoCompareGuard.cfg | 8 + .../TaskHistoryMigration.PeerOverwrite.cfg | 8 + .../architecture/tla/TaskHistoryMigration.cfg | 2 +- .../architecture/tla/TaskHistoryMigration.tla | 214 +++++++++++----- .../tla/TaskHistoryMigrationMC.tla | 2 + src/core/task-persistence/TaskHistoryStore.ts | 13 +- .../__tests__/legacyTaskHistoryBlob.spec.ts | 27 +- .../task-persistence/legacyTaskHistoryBlob.ts | 12 + src/core/webview/ClineProvider.ts | 53 +++- .../ClineProvider.taskHistory.spec.ts | 235 +++++++++++++++++- 10 files changed, 499 insertions(+), 75 deletions(-) create mode 100644 docs/architecture/tla/TaskHistoryMigration.NoCompareGuard.cfg create mode 100644 docs/architecture/tla/TaskHistoryMigration.PeerOverwrite.cfg diff --git a/docs/architecture/tla/TaskHistoryMigration.NoCompareGuard.cfg b/docs/architecture/tla/TaskHistoryMigration.NoCompareGuard.cfg new file mode 100644 index 00000000000..d0ec6a76913 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.NoCompareGuard.cfg @@ -0,0 +1,8 @@ +\* The clear has no compare-before-clear guard: an entry a downgrade +\* appended while the sweep awaited is deleted unverified. +\* expect-fail:AppendedEntryNeverLost +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CompareGuardEnabled <- NoCompareGuardEnabled +INVARIANTS TypeOK AppendedEntryNeverLost diff --git a/docs/architecture/tla/TaskHistoryMigration.PeerOverwrite.cfg b/docs/architecture/tla/TaskHistoryMigration.PeerOverwrite.cfg new file mode 100644 index 00000000000..9c739dd09f5 --- /dev/null +++ b/docs/architecture/tla/TaskHistoryMigration.PeerOverwrite.cfg @@ -0,0 +1,8 @@ +\* A peer sweep overwrites the shared backup with only what it saw, so +\* an entry only an earlier sweep backed up is lost. +\* expect-fail:ClearRequiresBackup +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PeerMergeEnabled <- PeerOverwriteEnabled +INVARIANTS TypeOK ClearRequiresBackup diff --git a/docs/architecture/tla/TaskHistoryMigration.cfg b/docs/architecture/tla/TaskHistoryMigration.cfg index 6911d1dc205..2e915d8965f 100644 --- a/docs/architecture/tla/TaskHistoryMigration.cfg +++ b/docs/architecture/tla/TaskHistoryMigration.cfg @@ -1,3 +1,3 @@ SPECIFICATION Spec CHECK_DEADLOCK FALSE -INVARIANTS TypeOK SweptWhenVerifiable ClearRequiresVerification ClearRequiresBackup PeerClearedStaysCleared +INVARIANTS TypeOK SweptWhenVerifiable ClearRequiresVerification ClearRequiresBackup PeerClearedStaysCleared AppendedEntryNeverLost diff --git a/docs/architecture/tla/TaskHistoryMigration.tla b/docs/architecture/tla/TaskHistoryMigration.tla index 9db0d62d6c0..5b2cb7b4134 100644 --- a/docs/architecture/tla/TaskHistoryMigration.tla +++ b/docs/architecture/tla/TaskHistoryMigration.tla @@ -18,34 +18,56 @@ (* Invariant: ClearRequiresBackup. *) (* - A stale in-memory array is written back after a peer window cleared *) (* the shared blob. Invariant: PeerClearedStaysCleared. *) +(* - An entry appended by a downgrade while the sweep awaits is deleted *) +(* by the clear. The clear must compare the current blob with the array *) +(* it read and keep the blob when they differ. Invariant: *) +(* AppendedEntryNeverLost. (CR 2873 thread 4814458162, added.) *) (* *) -(* Model: one startup performs initialization, migration and the sweep in *) -(* one step, as the code runs them in one async chain. A startup whose *) -(* migration fails keeps the marker unset and the blob. An orphan entry *) -(* has no task directory; migration cannot write it, and the backup *) -(* preserves it. Orphans do not block a sweep. DowngradeAppend models an *) -(* old build that re-writes the legacy list while the marker is set. Its *) -(* new entries are unverified, so the sweep keeps the blob. *) +(* Model: a startup runs initialize and migration in one action. The *) +(* sweep is a chain of separate actions - SweepRead, VerifyEntries, *) +(* BackupWrite, ReadBackCheck, ClearBlob - because the code awaits *) +(* between them. DowngradeAppend and PeerClear interleave between any two *) +(* sweep actions. A sweep whose migration fails keeps the marker unset *) +(* and the blob. An orphan entry has no task directory; migration cannot *) +(* write it, and the backup preserves it. Orphans do not block a sweep. *) +(* DowngradeAppend models an old build that re-writes the legacy list *) +(* while the marker is set. Entries appended during a sweep window are *) +(* tracked in appendedAfterRead. BackupWrite merges the existing backup *) +(* content, so a peer sweep cannot erase entries an earlier sweep backed *) +(* up (an orphan can exist only there). PeerOverwrite models the old *) +(* overwrite and must fail ClearRequiresBackup. *) (* *) -(* Constants: SweepEnabled, VerifyEnabled and BackupEnabled guard the *) -(* fix. ResurrectEnabled enables a stale write-back for the sabotage *) -(* check. MaxStartups bounds the retries. *) +(* Constants: SweepEnabled, VerifyEnabled, BackupEnabled, *) +(* CompareGuardEnabled and PeerMergeEnabled guard the fix. *) +(* ResurrectEnabled enables a stale write-back for the sabotage check. *) +(* MaxStartups bounds the retries. BackupWrite and ReadBackCheck also *) +(* explore an io-failure outcome that keeps the blob. *) (* *) (* Replay: ClineProvider.taskHistory.spec.ts sweeps the blob after a *) (* verified migration and keeps it on an unverified entry, on a backup *) -(* failure, and after a peer clear. The uninitialized fallback reads the *) -(* sweep backup. The sweep tests fail on the pre-fix code. *) +(* failure, when the blob changed during the sweep, and after a peer *) +(* clear. The uninitialized fallback reads the sweep backup and retries a *) +(* transient read error. The sweep tests fail on the pre-fix code. *) (* legacyTaskHistoryBlob.spec.ts is the property test of the pure *) -(* sweep decision. *) +(* sweep decision and the backup merge. *) (* *) -(* Result: fixed holds (650 states). NoSweep, the pre-fix behavior, fails *) -(* SweptWhenVerifiable (218 states). NoVerify fails *) -(* ClearRequiresVerification (392 states). NoBackup fails *) -(* ClearRequiresBackup (97 states). StaleResurrect fails *) -(* PeerClearedStaysCleared (515 states). Each variant run violates its *) -(* named invariant only. No further failure was found. *) -(* Cost: about 1 minute for all five configs on 4 cores. *) -(* Review ratchet: 0 covered, 0 added, 0 gap (first version). *) +(* Result: fixed holds. NoSweep, the pre-fix behavior, fails *) +(* SweptWhenVerifiable. NoVerify fails ClearRequiresVerification. *) +(* NoBackup fails ClearRequiresBackup. StaleResurrect fails *) +(* PeerClearedStaysCleared. NoCompareGuard fails AppendedEntryNeverLost. *) +(* PeerOverwrite fails ClearRequiresBackup. Each variant run violates its *) +(* named invariant only. State counts are in the PR evidence. *) +(* Cost: about 1 minute for all seven configs on 4 cores. *) +(* Review ratchet (CR 2873 round 1): 2 covered, 4 added, 2 gap. *) +(* Added: 4814458162 (mid-sweep append guard), 4814458143 (sweep action *) +(* split), 4814458148 (backup io-failure outcomes), 4814458149 (backup *) +(* content check). Covered: 4814458152 (the verify keep semantics already *) +(* holds the blob on any unconfirmable entry; the access-error fix is a *) +(* code path change), 4814458157 (failure outcomes modeled; the matching *) +(* negative tests land in the same commit). Gap: 4814458155 (test-suite *) +(* setup, no modeled behavior), 4814458167 (fallback read retry is a *) +(* read-resilience path outside the sweep machine; the oracle rule keeps *) +(* it out of the model and a regression test pins it). *) (***************************************************************************) EXTENDS Integers @@ -53,12 +75,14 @@ MaxStartups == 2 SweepEnabled == TRUE VerifyEnabled == TRUE BackupEnabled == TRUE +CompareGuardEnabled == TRUE +PeerMergeEnabled == TRUE ResurrectEnabled == FALSE Ids == {"t1", "t2"} -VARIABLES blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts -vars == <> +VARIABLES blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts, sweepPhase, readSnapshot, clearedSet, appendedAfterRead, backupOk +vars == <> Held(ids, storeSet) == (ids \cap dirs) \subseteq storeSet @@ -73,9 +97,14 @@ Init == /\ verifiedAtClear = FALSE /\ peerCleared = FALSE /\ attempts = 0 + /\ sweepPhase = "none" + /\ readSnapshot = {} + /\ clearedSet = {} + /\ appendedAfterRead = {} + /\ backupOk = TRUE (* First startup: initialize the store, migrate entries whose task - directories exist, set the marker, then run the sweep decision. *) + directories exist, set the marker, then open the sweep with a read. *) A1 == /\ attempts < MaxStartups /\ ~initialized @@ -83,17 +112,12 @@ A1 == /\ marker' = TRUE /\ initialized' = TRUE /\ store' = store \cup (blob \cap dirs) - /\ (IF SweepEnabled /\ blob # {} /\ (~VerifyEnabled \/ Held(blob, store')) - THEN /\ backup' = IF BackupEnabled THEN blob ELSE backup - /\ blob' = {} - /\ cleared' = TRUE - /\ verifiedAtClear' = Held(blob, store') - ELSE /\ backup' = backup - /\ blob' = blob - /\ cleared' = cleared - /\ verifiedAtClear' = verifiedAtClear) - /\ dirs' = dirs - /\ peerCleared' = peerCleared + /\ (IF SweepEnabled /\ blob # {} + THEN /\ sweepPhase' = "read" + /\ readSnapshot' = blob + ELSE /\ sweepPhase' = "none" + /\ readSnapshot' = readSnapshot) + /\ UNCHANGED <> (* A startup whose migration fails. The marker stays unset, the blob stays, and the next startup retries. *) @@ -101,50 +125,100 @@ A1MigrationFails == /\ attempts < MaxStartups /\ ~initialized /\ attempts' = attempts + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> -(* A later startup with the marker already set. Migration is skipped, so - entries that appeared after the marker are verified against the store - as they are. This is the one-time sweep for already migrated users. *) +(* A later startup with the marker already set. Migration is skipped and + the sweep opens with a fresh read of the current blob, so entries an + earlier sweep kept become visible to verification. *) RetrySweep == /\ attempts < MaxStartups /\ initialized /\ marker /\ attempts' = attempts + 1 /\ store' = store - /\ (IF SweepEnabled /\ blob # {} /\ (~VerifyEnabled \/ Held(blob, store)) - THEN /\ backup' = IF BackupEnabled THEN blob ELSE backup - /\ blob' = {} + /\ (IF SweepEnabled /\ blob # {} + THEN /\ sweepPhase' = "read" + /\ readSnapshot' = blob + /\ appendedAfterRead' = {} + ELSE /\ sweepPhase' = "none" + /\ readSnapshot' = readSnapshot + /\ appendedAfterRead' = appendedAfterRead) + /\ UNCHANGED <> + +(* Sweep step 2: verify every read entry against the file store. An + unconfirmed entry stops the sweep and keeps the blob. *) +VerifyEntries == + /\ sweepPhase = "read" + /\ sweepPhase' = (IF ~VerifyEnabled \/ Held(readSnapshot, store) THEN "verified" ELSE "none") + /\ UNCHANGED <> + +(* Sweep step 3: write the backup. The write merges the existing backup + content, so entries only an earlier sweep backed up survive. The write + can fail; the blob stays and a later startup retries. *) +BackupWrite == + /\ sweepPhase = "verified" + /\ \E ok \in BOOLEAN : + (IF ok + THEN /\ backup' = (IF BackupEnabled THEN backup \cup readSnapshot ELSE backup) + /\ sweepPhase' = "backed" + /\ backupOk' = backupOk + ELSE /\ backup' = backup + /\ sweepPhase' = "none" + /\ backupOk' = FALSE) + /\ UNCHANGED <> + +(* Sweep step 4: read the backup back and compare its content. Without + the backup requirement the check passes by design; a failed read or a + content mismatch keeps the blob. *) +ReadBackCheck == + /\ sweepPhase = "backed" + /\ \E ok \in BOOLEAN : + (IF ~BackupEnabled \/ (ok /\ readSnapshot \subseteq backup) + THEN /\ sweepPhase' = "checked" + /\ backupOk' = TRUE + ELSE /\ sweepPhase' = "none" + /\ backupOk' = FALSE) + /\ UNCHANGED <> + +(* Sweep step 5: clear the blob. The clear compares the CURRENT blob + with the array the sweep read; an append during the awaits keeps the + blob for the next startup. *) +ClearBlob == + /\ sweepPhase = "checked" + /\ (IF ~CompareGuardEnabled \/ blob = readSnapshot + THEN /\ blob' = {} /\ cleared' = TRUE + /\ clearedSet' = blob /\ verifiedAtClear' = Held(blob, store) - ELSE /\ backup' = backup - /\ blob' = blob + ELSE /\ blob' = blob /\ cleared' = cleared + /\ clearedSet' = clearedSet /\ verifiedAtClear' = verifiedAtClear) - /\ dirs' = dirs - /\ marker' = marker - /\ initialized' = initialized - /\ peerCleared' = peerCleared + /\ sweepPhase' = "none" + /\ UNCHANGED <> -(* A peer window completed its own verified sweep between our startups. - It deletes the shared blob and writes the shared backup file. *) +(* A peer window completed its own verified sweep between our actions. + It deletes the shared blob and merges what it saw into the shared + backup file. *) PeerClear == /\ marker /\ blob # {} /\ blob' = {} - /\ backup' = blob + /\ backup' = (IF PeerMergeEnabled THEN backup \cup blob ELSE blob) /\ peerCleared' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> (* An old build re-writes the legacy list while the marker is set. Its - entries were never migrated, so they are not held by the store. *) + entries were never migrated, so they are not held by the store. An + append during a sweep window is tracked in appendedAfterRead. *) DowngradeAppend == /\ marker /\ ~peerCleared /\ attempts < MaxStartups /\ \E id \in Ids \ blob : /\ blob' = blob \cup {id} - /\ UNCHANGED <> + /\ appendedAfterRead' = (IF sweepPhase # "none" THEN appendedAfterRead \cup {id} ELSE appendedAfterRead) + /\ UNCHANGED <> (* Sabotage only: a buggy variant writes a stale in-memory array back after a peer cleared the shared blob. *) @@ -152,9 +226,11 @@ Resurrect == /\ ResurrectEnabled /\ peerCleared /\ blob' = Ids - /\ UNCHANGED <> + /\ UNCHANGED <> -Next == A1 \/ A1MigrationFails \/ RetrySweep \/ PeerClear \/ DowngradeAppend \/ Resurrect +Next == + A1 \/ A1MigrationFails \/ RetrySweep \/ VerifyEntries \/ BackupWrite + \/ ReadBackCheck \/ ClearBlob \/ PeerClear \/ DowngradeAppend \/ Resurrect Spec == Init /\ [][Next]_vars @@ -169,23 +245,37 @@ TypeOK == /\ verifiedAtClear \in BOOLEAN /\ peerCleared \in BOOLEAN /\ attempts \leq MaxStartups + /\ sweepPhase \in {"none", "read", "verified", "backed", "checked"} + /\ readSnapshot \subseteq Ids + /\ clearedSet \subseteq Ids + /\ appendedAfterRead \subseteq Ids + /\ backupOk \in BOOLEAN -(* No startup that finished a verified migration leaves the blob behind. - A blob that survives is unverified, so the sweep kept it on purpose. *) +(* No startup that finished a verified migration leaves the blob behind + without a reason. A blob that survives is unverified, or the sweep + kept it because the blob changed after the read, or the last backup + cycle failed. *) SweptWhenVerifiable == - (initialized /\ attempts >= MaxStartups) => + (initialized /\ attempts >= MaxStartups /\ backupOk /\ sweepPhase = "none") => (\/ blob = {} - \/ ~Held(blob, store)) + \/ ~Held(blob, store) + \/ (blob # readSnapshot /\ readSnapshot # {})) (* A sweep only clears after every entry with a task directory is held by the file store. *) ClearRequiresVerification == cleared => verifiedAtClear -(* A sweep only clears after a backup holds the full blob. *) -ClearRequiresBackup == cleared => backup # {} +(* A sweep only clears after the backup holds the full content it + removes. *) +ClearRequiresBackup == cleared => clearedSet \subseteq backup (* After a peer cleared the shared blob, no stale write-back fills it. *) PeerClearedStaysCleared == ~( peerCleared /\ blob # {}) +(* No entry appended while the sweep was awaiting is ever cleared. The + clear guard must compare the current blob with the read snapshot. *) +AppendedEntryNeverLost == + appendedAfterRead \cap clearedSet = {} + ==== diff --git a/docs/architecture/tla/TaskHistoryMigrationMC.tla b/docs/architecture/tla/TaskHistoryMigrationMC.tla index 82fcec9997f..6c46b658cf6 100644 --- a/docs/architecture/tla/TaskHistoryMigrationMC.tla +++ b/docs/architecture/tla/TaskHistoryMigrationMC.tla @@ -5,4 +5,6 @@ NoSweepEnabled == FALSE NoVerifyEnabled == FALSE NoBackupEnabled == FALSE StaleResurrectEnabled == TRUE +NoCompareGuardEnabled == FALSE +PeerOverwriteEnabled == FALSE ==== diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts index cab2f699778..8e7afcfdb41 100644 --- a/src/core/task-persistence/TaskHistoryStore.ts +++ b/src/core/task-persistence/TaskHistoryStore.ts @@ -1315,12 +1315,19 @@ export class TaskHistoryStore { * Check whether a task directory exists without reading its files. */ async hasTaskDir(taskId: string): Promise { + const tasksDir = await this.getTasksDir() try { - const tasksDir = await this.getTasksDir() await fs.access(path.join(tasksDir, taskId)) return true - } catch { - return false + } catch (error) { + // Absence makes the entry an orphan. Any other failure (e.g. + // EACCES, EIO) must not make the sweep treat an existing + // directory as gone, so the caller keeps the blob instead. + const code = getErrorCode(error) + if (code === "ENOENT" || code === "ENOTDIR") { + return false + } + throw error } } diff --git a/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts index 0a9e46d974c..93557a595fb 100644 --- a/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts +++ b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest" import type { HistoryItem } from "@roo-code/types" -import { planLegacyBlobSweep } from "../legacyTaskHistoryBlob" +import { mergeLegacyBackup, planLegacyBlobSweep } from "../legacyTaskHistoryBlob" // pnpm --filter zoo-code test core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts @@ -78,3 +78,28 @@ describe("planLegacyBlobSweep", () => { expect(decision).toStrictEqual({ action: "clear" }) }) }) + +describe("mergeLegacyBackup", () => { + it("keeps prior-only entries behind the current array", () => { + const current = [{ id: "t1" }, { id: "t2" }] as HistoryItem[] + const prior = [{ id: "t1" }, { id: "t9" }] as HistoryItem[] + expect(mergeLegacyBackup(current, prior)).toStrictEqual([{ id: "t1" }, { id: "t2" }, { id: "t9" }]) + }) + + it("lets the current array win on an id clash", () => { + const current = [{ id: "t1", task: "fresh" }] as HistoryItem[] + const prior = [{ id: "t1", task: "stale" }, { id: "t8" }] as HistoryItem[] + expect(mergeLegacyBackup(current, prior)).toStrictEqual([{ id: "t1", task: "fresh" }, { id: "t8" }]) + }) + + it("keeps id-less prior entries like any other backup content", () => { + const current = [{ id: "t1" }] as HistoryItem[] + const prior = [{ task: "no-id" }] as HistoryItem[] + expect(mergeLegacyBackup(current, prior)).toStrictEqual([{ id: "t1" }, { task: "no-id" }]) + }) + + it("returns the current array unchanged when the prior backup is empty", () => { + const current = [{ id: "t1" }] as HistoryItem[] + expect(mergeLegacyBackup(current, [])).toStrictEqual([{ id: "t1" }]) + }) +}) diff --git a/src/core/task-persistence/legacyTaskHistoryBlob.ts b/src/core/task-persistence/legacyTaskHistoryBlob.ts index cfd5a3b1965..c0c73a357e4 100644 --- a/src/core/task-persistence/legacyTaskHistoryBlob.ts +++ b/src/core/task-persistence/legacyTaskHistoryBlob.ts @@ -33,3 +33,15 @@ export function planLegacyBlobSweep( return { action: "clear" } } + +/** + * Merge the current legacy array with an earlier sweep's backup. + * + * Entries only the earlier backup holds (e.g. orphans with no task + * directory) must survive the write; current entries win on an id clash. + */ +export function mergeLegacyBackup(current: HistoryItem[], prior: HistoryItem[]): HistoryItem[] { + const currentIds = new Set(current.map((item) => item?.id).filter((id): id is string => Boolean(id))) + const keptPrior = prior.filter((item) => !item?.id || !currentIds.has(item.id)) + return [...current, ...keptPrior] +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 81c825c0da2..d73e1f4782a 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -153,7 +153,12 @@ import { interruptDelegatedChild, LifecycleTransitionError, } from "../task-persistence" -import { LEGACY_TASK_HISTORY_BACKUP_FILE, planLegacyBlobSweep } from "../task-persistence/legacyTaskHistoryBlob" +import { + LEGACY_TASK_HISTORY_BACKUP_FILE, + mergeLegacyBackup, + planLegacyBlobSweep, +} from "../task-persistence/legacyTaskHistoryBlob" +import { getErrorCode } from "../../utils/errorCode" import { readTaskMessages } from "../task-persistence/taskMessages" import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry" import deepEqual from "fast-deep-equal" @@ -715,7 +720,28 @@ export class ClineProvider } const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) - await safeWriteJson(backupPath, legacyHistory) + + // Merge with any existing backup: entries an earlier sweep backed + // up (e.g. orphans with no task directory) must survive this write. + let toPersist: HistoryItem[] + try { + const existingRaw = await fs.readFile(backupPath, "utf8") + const existingParsed: unknown = JSON.parse(existingRaw) + toPersist = mergeLegacyBackup( + legacyHistory, + Array.isArray(existingParsed) ? (existingParsed as HistoryItem[]) : [], + ) + } catch (error) { + if (getErrorCode(error) !== "ENOENT" && getErrorCode(error) !== "ENOTDIR") { + // A transient read or a corrupt file must not risk + // overwriting the only copy of earlier backup entries; the + // next startup retries the sweep. + throw error + } + toPersist = legacyHistory + } + + await safeWriteJson(backupPath, toPersist) let backup: HistoryItem[] | null = null try { @@ -725,7 +751,7 @@ export class ClineProvider } catch { backup = null } - if (!backup || !deepEqual(backup, legacyHistory)) { + if (!backup || !deepEqual(backup, toPersist)) { this.log("[initializeTaskHistoryStore] Keeping legacy taskHistory blob: backup read-back did not match") return } @@ -736,11 +762,20 @@ export class ClineProvider return } + // A downgrade can append entries while the awaits above run; the + // backup does not hold them, so the sweep keeps the blob for the + // next startup when the blob changed after the read. + const current = this.context.globalState.get("taskHistory") ?? [] + if (!deepEqual(current, legacyHistory)) { + this.log("[initializeTaskHistoryStore] Keeping legacy taskHistory blob: it changed during the sweep") + return + } + // VS Code defines update(key, undefined) as removal; the delete is // idempotent across windows that run the same verified sweep. await this.context.globalState.update("taskHistory", undefined) this.log( - `[initializeTaskHistoryStore] Removed the legacy taskHistory blob; ${legacyHistory.length} entries are backed up in ${LEGACY_TASK_HISTORY_BACKUP_FILE}`, + `[initializeTaskHistoryStore] Removed the legacy taskHistory blob; ${toPersist.length} entries are backed up in ${LEGACY_TASK_HISTORY_BACKUP_FILE}`, ) } @@ -765,8 +800,14 @@ export class ClineProvider const raw = await fs.readFile(backupPath, "utf8") const parsed: unknown = JSON.parse(raw) this.legacyBackupItems = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null - } catch { - this.legacyBackupItems = null + } catch (error) { + // A missing backup file is confirmed absence. Any other + // failure (e.g. EACCES, EIO) must stay retryable, so keep + // the unread state and let the next lookup read again. + const code = getErrorCode(error) + if (code === "ENOENT" || code === "ENOTDIR") { + this.legacyBackupItems = null + } } } return this.legacyBackupItems?.find((item) => item?.id === id) ?? undefined diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index 98270ac07be..67e037a4e3f 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -1432,6 +1432,11 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { beforeFlush?: () => void }): Promise => { vi.clearAllMocks() + // This suite must also pass when it runs without its sibling + // suite, whose beforeEach creates the telemetry singleton. + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } memFiles.clear() memDirs.clear() for (const d of options.dirs ?? []) { @@ -1531,7 +1536,7 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) expect(state.taskHistory).toBeUndefined() const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] - expect(backup.map((item) => item.id).sort()).toStrictEqual(["task-a", "task-b"]) + expect(backup).toStrictEqual([itemA, itemB]) }) it("keeps the blob when an entry with a task directory is not held by the store", async () => { @@ -1619,7 +1624,7 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { expect(p["taskHistoryStoreInitialized"]).toBe(true) expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] - expect(backup.map((item) => item.id).sort()).toStrictEqual(["task-a", "task-orphan"]) + expect(backup).toStrictEqual([itemA, itemOrphan]) }) it("does nothing when a peer window already cleared the blob", async () => { @@ -1647,5 +1652,231 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { const item = await p["getTaskHistoryItem"]("task-a") expect(item?.id).toBe("task-a") }) + + it("keeps the blob when it changes during the sweep", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + const itemC = makeItem("task-c", "C") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, "\t"), + }, + beforeFlush: () => { + // A downgraded build appends task-c while the sweep + // awaits the directory check for task-a, which runs + // after the sweep's read of the blob. + let appended = false + vi.mocked(fsMockRef.access).mockImplementation(async (p) => { + const key = toKey(p) + if (key === `${TASKS_DIR}/task-a` && !appended) { + appended = true + state.taskHistory = [...(state.taskHistory as HistoryItem[]), itemC] + } + if (memDirs.has(key) || Array.from(memFiles.keys()).some((k) => k.startsWith(`${key}/`))) { + return undefined as never + } + throw errno("ENOENT", key) + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + // The appended entry is not in the backup, so the sweep must + // keep the blob and let the next startup retry. Capture the + // first window's state before the second build replaces it. + const firstContext = context + const firstState = state + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(firstContext.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(firstState.taskHistory).toStrictEqual([itemA, itemB, itemC]) + expect(backup).toStrictEqual([itemA, itemB]) + + // The next startup reads all three entries and completes the + // sweep. + const second = await buildProvider({ + globalState: { taskHistory: [itemA, itemB, itemC], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`, `${TASKS_DIR}/task-c`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, "\t"), + [`${TASKS_DIR}/task-c/history_item.json`]: JSON.stringify(itemC, null, "\t"), + }, + }) + expect(second["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + }) + + it("merges the sweep backup with entries an earlier sweep backed up", async () => { + const itemA = makeItem("task-a", "A") + const itemOld = makeItem("task-old", "Old") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + // An earlier sweep backed up an orphan that has no task + // directory; the orphan exists only in the backup. + [BACKUP_PATH]: JSON.stringify([itemOld], null, "\t"), + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup).toStrictEqual([itemA, itemOld]) + }) + + it("keeps the blob when the backup read-back does not match", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + const p = await buildProvider({ + globalState: { taskHistory: [itemA, itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`, `${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, "\t"), + }, + beforeFlush: () => { + // The backup write succeeds but the stored content + // loses an entry, so the read-back cannot match. + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { + const content = toKey(p) === BACKUP_PATH ? [(data as HistoryItem[])[0]] : data + memFiles.set(toKey(p), JSON.stringify(content, null, "\t")) + return undefined as never + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA, itemB]) + }) + + it("keeps the blob when the backup read-back cannot be read", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + beforeFlush: () => { + vi.mocked(fsMockRef.readFile).mockImplementation(async (p) => { + if (toKey(p) === BACKUP_PATH) { + throw errno("EIO", toKey(p)) + } + const key = toKey(p) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + }) + + it("leaves the blob untouched while the backup write is pending", async () => { + const itemA = makeItem("task-a", "A") + let pendingSnapshot: HistoryItem[] | undefined + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + beforeFlush: () => { + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { + if (toKey(p) === BACKUP_PATH) { + // Observed while the write is still pending: the + // blob must still exist at this point. + pendingSnapshot = (state.taskHistory as HistoryItem[] | undefined)?.slice() + } + memFiles.set(toKey(p), JSON.stringify(data, null, "\t")) + return undefined as never + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(pendingSnapshot).toStrictEqual([itemA]) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toBeUndefined() + }) + + it("keeps the blob when a task directory access fails", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + beforeFlush: () => { + vi.mocked(fsMockRef.access).mockImplementation(async (p) => { + const key = toKey(p) + if (key === `${TASKS_DIR}/task-a`) { + throw errno("EIO", key) + } + if (memDirs.has(key) || Array.from(memFiles.keys()).some((k) => k.startsWith(`${key}/`))) { + return undefined as never + } + throw errno("ENOENT", key) + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + // An access failure is not evidence of absence: the sweep + // defers and keeps the blob. + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + expect(memFiles.has(BACKUP_PATH)).toBe(false) + const initLog = vi + .mocked(outputChannel.appendLine) + .mock.calls.map((call) => String(call[0])) + .join(" | ") + expect(initLog).toContain("Legacy blob sweep deferred") + }) + + it("retries a transient backup read error in the fallback", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + // Store init fails, so the provider keeps the legacy + // fallback path. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + // The first backup read hits a transient I/O error. + let backupReads = 0 + vi.mocked(fsMockRef.readFile).mockImplementation(async (p) => { + if (toKey(p) === BACKUP_PATH) { + backupReads += 1 + if (backupReads === 1) { + throw errno("EIO", toKey(p)) + } + } + const key = toKey(p) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(false) + const first = await p["getTaskHistoryItem"]("task-a") + expect(first).toBeUndefined() + // A transient read error must not be cached as absence: the + // next lookup reads the backup again. + const second = await p["getTaskHistoryItem"]("task-a") + expect(second?.id).toBe("task-a") + }) }) }) From 57fd66ebdc09a14166ce204974fe155c2e693377 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 04:15:18 +0100 Subject: [PATCH 4/8] fix(webview): lock the backup merge and bound the sweep's cache window CodeRabbit round 2 on PR 2873 (follow-ups on 5 of the 8 round-1 fixes), all verified against the code: - The backup read-merge-write now runs inside safeWriteJson's advisory lock via its merge callback, so a concurrent sweep cannot merge against the same old content (the delayed-sweep overwrite CR traced). The corrupt-file pre-check keeps deferring instead of overwriting a possibly recoverable file; a transient read error inside the locked merge still fails the write, which defers the sweep. - TaskHistoryMigration.tla: the globalState key is now two variables - `shared` (what every window writes) and `blob` (this window's cached view that get returns, per VS Code extHostMemento) - with SyncCache modeling the delayed change notification, DowngradeAppend writing shared only (and no longer gated on attempts, so it interleaves with the final retry too), and the compare-plus-delete-request as one synchronous action, as in the code. New escape documents that material arriving after the last startup drains is swept by the next one. Ratchet: 1 covered, 3 added, 2 gap. - Tests: the unreadable-backup case now fails only the post-write read-back (reaching the keep branch it claims to cover) and asserts the backup was written; the pending-write case parks the write on a deferred promise, asserts the blob is untouched before releasing, and the sweep completes after release. The harness's safeWriteJson mock now mirrors the merge contract. TLC (check.sh TaskHistoryMigration): base pass 12,050 states; NoSweep 242, NoVerify 5,061, NoBackup 2,183, StaleResurrect 566, NoCompareGuard 5,374, PeerOverwrite 5,372 - each fails exactly its named invariant. Gates: test:core 5,341, test:api 6,417, scoped vitest 73, tsc, eslint, prettier. Closes #1771 --- .../architecture/tla/TaskHistoryMigration.tla | 236 +++++++++++------- src/core/webview/ClineProvider.ts | 30 +-- .../ClineProvider.taskHistory.spec.ts | 73 ++++-- 3 files changed, 221 insertions(+), 118 deletions(-) diff --git a/docs/architecture/tla/TaskHistoryMigration.tla b/docs/architecture/tla/TaskHistoryMigration.tla index 5b2cb7b4134..c0f105f0ae8 100644 --- a/docs/architecture/tla/TaskHistoryMigration.tla +++ b/docs/architecture/tla/TaskHistoryMigration.tla @@ -18,37 +18,51 @@ (* Invariant: ClearRequiresBackup. *) (* - A stale in-memory array is written back after a peer window cleared *) (* the shared blob. Invariant: PeerClearedStaysCleared. *) -(* - An entry appended by a downgrade while the sweep awaits is deleted *) -(* by the clear. The clear must compare the current blob with the array *) -(* it read and keep the blob when they differ. Invariant: *) -(* AppendedEntryNeverLost. (CR 2873 thread 4814458162, added.) *) +(* - An entry that a downgrade appended and whose change notification has *) +(* reached this window's cache during the sweep is deleted. The clear *) +(* must compare the cached blob with the array the sweep read and keep *) +(* the blob when they differ. Invariant: AppendedEntryNeverLost. *) +(* (CR 2873 thread 4814458162, added.) *) (* *) (* Model: a startup runs initialize and migration in one action. The *) -(* sweep is a chain of separate actions - SweepRead, VerifyEntries, *) -(* BackupWrite, ReadBackCheck, ClearBlob - because the code awaits *) -(* between them. DowngradeAppend and PeerClear interleave between any two *) -(* sweep actions. A sweep whose migration fails keeps the marker unset *) -(* and the blob. An orphan entry has no task directory; migration cannot *) -(* write it, and the backup preserves it. Orphans do not block a sweep. *) -(* DowngradeAppend models an old build that re-writes the legacy list *) -(* while the marker is set. Entries appended during a sweep window are *) -(* tracked in appendedAfterRead. BackupWrite merges the existing backup *) -(* content, so a peer sweep cannot erase entries an earlier sweep backed *) -(* up (an orphan can exist only there). PeerOverwrite models the old *) -(* overwrite and must fail ClearRequiresBackup. *) +(* sweep is a chain of separate actions - SweepRead via A1 and *) +(* RetrySweep, VerifyEntries, BackupWrite, ReadBackCheck, CompareBlob, *) +(* ClearBlob - because the code awaits between them. The globalState *) +(* key is modeled as two variables: `shared` is the shared storage all *) +(* windows write, `blob` is this window's cached view that `get` *) +(* returns (VS Code extHostMemento). SyncCache models the change *) +(* notification that copies shared into the cache, with a delay. *) +(* DowngradeAppend writes shared only; until SyncCache runs, the sweep *) +(* cannot see the entry. PeerClear is a peer window's own verified *) +(* sweep: it deletes shared and merges what it saw into the shared *) +(* backup file. BackupWrite runs read-merge-write as one atomic step *) +(* (safeWriteJson merge callback under the advisory lock), so a peer *) +(* sweep cannot erase entries an earlier backup holds. BackupWrite and *) +(* ReadBackCheck also explore an io-failure outcome that keeps the blob. *) +(* *) +(* Residual race (documented, not fixable at this API level): an entry *) +(* appended to shared after the compare but before the delete request *) +(* reaches shared storage is removed without a backup. VS Code Memento *) +(* has no compare-and-delete primitive (extHostMemento.ts: update *) +(* schedules an unconditional write), so the guard can only cover entries *) +(* the cache has already seen. The compare and the delete request are *) +(* adjacent synchronous calls, which is the smallest window the API *) +(* allows. A later startup re-reads shared through a fresh cache and *) +(* sweeps any entry that arrives later. *) (* *) (* Constants: SweepEnabled, VerifyEnabled, BackupEnabled, *) (* CompareGuardEnabled and PeerMergeEnabled guard the fix. *) (* ResurrectEnabled enables a stale write-back for the sabotage check. *) -(* MaxStartups bounds the retries. BackupWrite and ReadBackCheck also *) -(* explore an io-failure outcome that keeps the blob. *) +(* MaxStartups bounds the retries. readHappened marks that a sweep read *) +(* ran, so the beyond-snapshot escape of SweptWhenVerifiable cannot hide *) +(* the pre-fix behavior. *) (* *) (* Replay: ClineProvider.taskHistory.spec.ts sweeps the blob after a *) (* verified migration and keeps it on an unverified entry, on a backup *) -(* failure, when the blob changed during the sweep, and after a peer *) -(* clear. The uninitialized fallback reads the sweep backup and retries a *) -(* transient read error. The sweep tests fail on the pre-fix code. *) -(* legacyTaskHistoryBlob.spec.ts is the property test of the pure *) +(* failure, when the cached blob changed during the sweep, and after a *) +(* peer clear. The uninitialized fallback reads the sweep backup and *) +(* retries a transient read error. The sweep tests fail on the pre-fix *) +(* code. legacyTaskHistoryBlob.spec.ts is the property test of the pure *) (* sweep decision and the backup merge. *) (* *) (* Result: fixed holds. NoSweep, the pre-fix behavior, fails *) @@ -57,17 +71,18 @@ (* PeerClearedStaysCleared. NoCompareGuard fails AppendedEntryNeverLost. *) (* PeerOverwrite fails ClearRequiresBackup. Each variant run violates its *) (* named invariant only. State counts are in the PR evidence. *) -(* Cost: about 1 minute for all seven configs on 4 cores. *) -(* Review ratchet (CR 2873 round 1): 2 covered, 4 added, 2 gap. *) -(* Added: 4814458162 (mid-sweep append guard), 4814458143 (sweep action *) -(* split), 4814458148 (backup io-failure outcomes), 4814458149 (backup *) -(* content check). Covered: 4814458152 (the verify keep semantics already *) -(* holds the blob on any unconfirmable entry; the access-error fix is a *) -(* code path change), 4814458157 (failure outcomes modeled; the matching *) -(* negative tests land in the same commit). Gap: 4814458155 (test-suite *) -(* setup, no modeled behavior), 4814458167 (fallback read retry is a *) -(* read-resilience path outside the sweep machine; the oracle rule keeps *) -(* it out of the model and a regression test pins it). *) +(* Cost: about 2 minutes for all seven configs on 4 cores. *) +(* Review ratchet (CR 2873 round 2): 1 covered, 3 added, 2 gap. *) +(* Added: 4814652338 (DowngradeAppend at MaxStartups; compare and delete *) +(* split into two actions), 4814651913 (cached view vs shared storage *) +(* with delayed notification), 4814653507 (backup read-merge-write under *) +(* the advisory lock, modeled atomic). Covered: 4814651541 (test-side *) +(* precision fixes; the behavior they pin is already modeled by the *) +(* ReadBackCheck failure outcome and the BackupWrite ordering). Gap: *) +(* the documented residual race above (no CAS primitive on Memento), *) +(* 4814458155 (test-suite setup, no modeled behavior), 4814458167 *) +(* (fallback read retry is a read-resilience path outside the sweep *) +(* machine; a regression test pins it). *) (***************************************************************************) EXTENDS Integers @@ -81,13 +96,14 @@ ResurrectEnabled == FALSE Ids == {"t1", "t2"} -VARIABLES blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts, sweepPhase, readSnapshot, clearedSet, appendedAfterRead, backupOk -vars == <> +VARIABLES shared, blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts, sweepPhase, readSnapshot, clearedSet, appendedAfterRead, backupOk, compareOk, readHappened, lateArrivals +vars == <> Held(ids, storeSet) == (ids \cap dirs) \subseteq storeSet Init == - /\ blob \in SUBSET Ids + /\ shared \in SUBSET Ids + /\ blob = shared /\ store \in SUBSET Ids /\ dirs \in SUBSET Ids /\ backup = {} @@ -102,9 +118,13 @@ Init == /\ clearedSet = {} /\ appendedAfterRead = {} /\ backupOk = TRUE + /\ compareOk = TRUE + /\ readHappened = FALSE + /\ lateArrivals = {} (* First startup: initialize the store, migrate entries whose task - directories exist, set the marker, then open the sweep with a read. *) + directories exist, set the marker, then open the sweep with a read + of the cached blob. *) A1 == /\ attempts < MaxStartups /\ ~initialized @@ -115,9 +135,11 @@ A1 == /\ (IF SweepEnabled /\ blob # {} THEN /\ sweepPhase' = "read" /\ readSnapshot' = blob + /\ readHappened' = TRUE ELSE /\ sweepPhase' = "none" - /\ readSnapshot' = readSnapshot) - /\ UNCHANGED <> + /\ readSnapshot' = readSnapshot + /\ readHappened' = readHappened) + /\ UNCHANGED <> (* A startup whose migration fails. The marker stays unset, the blob stays, and the next startup retries. *) @@ -125,36 +147,53 @@ A1MigrationFails == /\ attempts < MaxStartups /\ ~initialized /\ attempts' = attempts + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> (* A later startup with the marker already set. Migration is skipped and - the sweep opens with a fresh read of the current blob, so entries an - earlier sweep kept become visible to verification. *) + the sweep opens with a fresh read of the cached blob, so entries an + earlier sweep kept become visible to verification. A fresh cache in a + new window sees shared as it is. *) RetrySweep == /\ attempts < MaxStartups /\ initialized /\ marker /\ attempts' = attempts + 1 /\ store' = store - /\ (IF SweepEnabled /\ blob # {} + /\ blob' = shared + /\ (IF SweepEnabled /\ blob' # {} THEN /\ sweepPhase' = "read" - /\ readSnapshot' = blob + /\ readSnapshot' = blob' /\ appendedAfterRead' = {} + /\ clearedSet' = {} + /\ readHappened' = TRUE ELSE /\ sweepPhase' = "none" /\ readSnapshot' = readSnapshot - /\ appendedAfterRead' = appendedAfterRead) - /\ UNCHANGED <> + /\ appendedAfterRead' = appendedAfterRead + /\ clearedSet' = clearedSet + /\ readHappened' = readHappened) + /\ UNCHANGED <> + +(* The change notification catches this window's cache up with the + shared storage. It can run at any time, with any delay. *) +SyncCache == + /\ blob # shared + /\ blob' = shared + /\ appendedAfterRead' = (IF sweepPhase # "none" THEN appendedAfterRead \cup (shared \ blob) ELSE appendedAfterRead) + /\ UNCHANGED <> (* Sweep step 2: verify every read entry against the file store. An unconfirmed entry stops the sweep and keeps the blob. *) VerifyEntries == /\ sweepPhase = "read" /\ sweepPhase' = (IF ~VerifyEnabled \/ Held(readSnapshot, store) THEN "verified" ELSE "none") - /\ UNCHANGED <> + /\ UNCHANGED <> -(* Sweep step 3: write the backup. The write merges the existing backup - content, so entries only an earlier sweep backed up survive. The write - can fail; the blob stays and a later startup retries. *) +(* Sweep step 3: write the backup. The read-merge-write runs as one + atomic step under the advisory lock (safeWriteJson merge callback), + so a concurrent sweep cannot merge against the same old content. The + write merges the existing backup content, so entries only an earlier + backup holds survive. The write can fail; the blob stays and a later + startup retries. *) BackupWrite == /\ sweepPhase = "verified" /\ \E ok \in BOOLEAN : @@ -165,7 +204,7 @@ BackupWrite == ELSE /\ backup' = backup /\ sweepPhase' = "none" /\ backupOk' = FALSE) - /\ UNCHANGED <> + /\ UNCHANGED <> (* Sweep step 4: read the backup back and compare its content. Without the backup requirement the check passes by design; a failed read or a @@ -178,63 +217,73 @@ ReadBackCheck == /\ backupOk' = TRUE ELSE /\ sweepPhase' = "none" /\ backupOk' = FALSE) - /\ UNCHANGED <> + /\ UNCHANGED <> -(* Sweep step 5: clear the blob. The clear compares the CURRENT blob - with the array the sweep read; an append during the awaits keeps the - blob for the next startup. *) +(* Sweep step 5: compare the cached blob with the array the sweep read + and request the delete. The code runs both in one synchronous + sequence, so no action interleaves between them; the delete removes + the shared key while the compare sees only this window's cache, and + a shared-only append that the cache has not synced is the documented + residual race. *) ClearBlob == /\ sweepPhase = "checked" - /\ (IF ~CompareGuardEnabled \/ blob = readSnapshot - THEN /\ blob' = {} - /\ cleared' = TRUE - /\ clearedSet' = blob - /\ verifiedAtClear' = Held(blob, store) - ELSE /\ blob' = blob - /\ cleared' = cleared - /\ clearedSet' = clearedSet - /\ verifiedAtClear' = verifiedAtClear) + /\ LET ok == (~CompareGuardEnabled \/ blob = readSnapshot) + IN /\ compareOk' = ok + /\ (IF ok + THEN /\ shared' = {} + /\ blob' = {} + /\ cleared' = TRUE + /\ clearedSet' = blob + /\ verifiedAtClear' = Held(blob, store) + ELSE /\ shared' = shared + /\ blob' = blob + /\ cleared' = cleared + /\ clearedSet' = clearedSet + /\ verifiedAtClear' = verifiedAtClear) /\ sweepPhase' = "none" - /\ UNCHANGED <> + /\ UNCHANGED <> (* A peer window completed its own verified sweep between our actions. It deletes the shared blob and merges what it saw into the shared - backup file. *) + backup file. This window's cache stays stale until SyncCache. *) PeerClear == /\ marker - /\ blob # {} - /\ blob' = {} - /\ backup' = (IF PeerMergeEnabled THEN backup \cup blob ELSE blob) + /\ shared # {} + /\ shared' = {} + /\ backup' = (IF PeerMergeEnabled THEN backup \cup shared ELSE shared) /\ peerCleared' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> -(* An old build re-writes the legacy list while the marker is set. Its - entries were never migrated, so they are not held by the store. An - append during a sweep window is tracked in appendedAfterRead. *) +(* An old build re-writes the legacy list in shared storage while the + marker is set. Its entries were never migrated, so they are not held + by the store. This window's cache learns of it only via SyncCache; an + entry that arrives during a sweep window is tracked in + appendedAfterRead. *) DowngradeAppend == /\ marker /\ ~peerCleared - /\ attempts < MaxStartups - /\ \E id \in Ids \ blob : - /\ blob' = blob \cup {id} - /\ appendedAfterRead' = (IF sweepPhase # "none" THEN appendedAfterRead \cup {id} ELSE appendedAfterRead) - /\ UNCHANGED <> + /\ \E id \in Ids \ shared : + /\ shared' = shared \cup {id} + /\ lateArrivals' = lateArrivals \cup {id} + /\ UNCHANGED <> (* Sabotage only: a buggy variant writes a stale in-memory array back after a peer cleared the shared blob. *) Resurrect == /\ ResurrectEnabled /\ peerCleared + /\ shared' = Ids /\ blob' = Ids - /\ UNCHANGED <> + /\ UNCHANGED <> Next == - A1 \/ A1MigrationFails \/ RetrySweep \/ VerifyEntries \/ BackupWrite + A1 \/ A1MigrationFails \/ RetrySweep \/ SyncCache \/ VerifyEntries \/ BackupWrite \/ ReadBackCheck \/ ClearBlob \/ PeerClear \/ DowngradeAppend \/ Resurrect Spec == Init /\ [][Next]_vars TypeOK == + /\ shared \subseteq Ids /\ blob \subseteq Ids /\ store \subseteq Ids /\ dirs \subseteq Ids @@ -250,31 +299,38 @@ TypeOK == /\ clearedSet \subseteq Ids /\ appendedAfterRead \subseteq Ids /\ backupOk \in BOOLEAN + /\ compareOk \in BOOLEAN + /\ readHappened \in BOOLEAN + /\ lateArrivals \subseteq Ids (* No startup that finished a verified migration leaves the blob behind - without a reason. A blob that survives is unverified, or the sweep - kept it because the blob changed after the read, or the last backup - cycle failed. *) + without a reason, judged on the shared storage. A blob that survives + is unverified, or the sweep kept it because the cached blob changed + after the read, or the last backup cycle failed. *) SweptWhenVerifiable == (initialized /\ attempts >= MaxStartups /\ backupOk /\ sweepPhase = "none") => - (\/ blob = {} - \/ ~Held(blob, store) - \/ (blob # readSnapshot /\ readSnapshot # {})) + (\/ shared = {} + \/ ~Held(shared, store) + \/ (shared # readSnapshot /\ readHappened) + \/ shared \subseteq lateArrivals) (* A sweep only clears after every entry with a task directory is held by the file store. *) ClearRequiresVerification == cleared => verifiedAtClear (* A sweep only clears after the backup holds the full content it - removes. *) + removes from this window's view. *) ClearRequiresBackup == cleared => clearedSet \subseteq backup (* After a peer cleared the shared blob, no stale write-back fills it. *) PeerClearedStaysCleared == ~( - peerCleared /\ blob # {}) + peerCleared /\ shared # {}) -(* No entry appended while the sweep was awaiting is ever cleared. The - clear guard must compare the current blob with the read snapshot. *) +(* No entry whose change notification reached this window's cache during + the sweep is ever cleared. The compare guard must run before the + delete. An entry that is still only in shared storage at delete time + is the documented residual race; SyncCache brings it into the cache + of a later startup, which then sweeps it safely. *) AppendedEntryNeverLost == appendedAfterRead \cap clearedSet = {} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index d73e1f4782a..6c66fc33909 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -721,27 +721,29 @@ export class ClineProvider const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) - // Merge with any existing backup: entries an earlier sweep backed - // up (e.g. orphans with no task directory) must survive this write. - let toPersist: HistoryItem[] + // A corrupt backup may still hold recoverable raw text, and a + // transient read error must not risk losing it; the sweep defers + // instead of writing over it. The lock-protected merge inside + // safeWriteJson re-reads the file under the advisory lock, so a + // concurrent sweep cannot merge against the same old content. try { - const existingRaw = await fs.readFile(backupPath, "utf8") - const existingParsed: unknown = JSON.parse(existingRaw) - toPersist = mergeLegacyBackup( - legacyHistory, - Array.isArray(existingParsed) ? (existingParsed as HistoryItem[]) : [], - ) + JSON.parse(await fs.readFile(backupPath, "utf8")) } catch (error) { if (getErrorCode(error) !== "ENOENT" && getErrorCode(error) !== "ENOTDIR") { - // A transient read or a corrupt file must not risk - // overwriting the only copy of earlier backup entries; the - // next startup retries the sweep. throw error } - toPersist = legacyHistory } - await safeWriteJson(backupPath, toPersist) + let toPersist: HistoryItem[] = legacyHistory + await safeWriteJson(backupPath, legacyHistory, { + merge: (existing, incoming) => { + toPersist = mergeLegacyBackup( + incoming as HistoryItem[], + Array.isArray(existing) ? (existing as HistoryItem[]) : [], + ) + return toPersist + }, + }) let backup: HistoryItem[] | null = null try { diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index 67e037a4e3f..8ae1c2b65ed 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -1416,8 +1416,21 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { const swj = (swjRef = await import("../../../utils/safeWriteJson")) vi.mocked(swj.safeWriteJson) .mockReset() - .mockImplementation(async (p, data) => { - memFiles.set(toKey(p), JSON.stringify(data, null, " ")) + .mockImplementation(async (p, data, options) => { + // Mirror safeWriteJson's merge contract: existing is null + // when the file is absent or unparseable; the merge + // result replaces the written content. + const raw = memFiles.get(toKey(p)) + let existing: unknown = null + if (raw !== undefined) { + try { + existing = JSON.parse(raw) + } catch { + existing = null + } + } + const merged = options?.merge ? options.merge(existing, data) : data + memFiles.set(toKey(p), JSON.stringify(merged, null, " ")) return undefined as never }) } @@ -1762,11 +1775,17 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { const p = await buildProvider({ globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, dirs: [`${TASKS_DIR}/task-a`], - files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, beforeFlush: () => { + // The merge pre-check read succeeds so the backup write + // lands; only the post-write read-back fails. + let backupReads = 0 vi.mocked(fsMockRef.readFile).mockImplementation(async (p) => { if (toKey(p) === BACKUP_PATH) { - throw errno("EIO", toKey(p)) + backupReads += 1 + if (backupReads >= 2) { + throw errno("EIO", toKey(p)) + } } const key = toKey(p) const content = memFiles.get(key) @@ -1779,34 +1798,60 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { }) expect(p["taskHistoryStoreInitialized"]).toBe(true) + // The backup was written, so this is the read-back keep branch, + // not an early defer. + expect(memFiles.has(BACKUP_PATH)).toBe(true) expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) expect(state.taskHistory).toStrictEqual([itemA]) }) it("leaves the blob untouched while the backup write is pending", async () => { const itemA = makeItem("task-a", "A") - let pendingSnapshot: HistoryItem[] | undefined + let releaseWrite: (() => void) | undefined const p = await buildProvider({ globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, dirs: [`${TASKS_DIR}/task-a`], - files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, beforeFlush: () => { - vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data) => { - if (toKey(p) === BACKUP_PATH) { - // Observed while the write is still pending: the - // blob must still exist at this point. - pendingSnapshot = (state.taskHistory as HistoryItem[] | undefined)?.slice() + vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data, options) => { + if (toKey(p) !== BACKUP_PATH) { + memFiles.set(toKey(p), JSON.stringify(data, null, " ")) + return undefined as never } - memFiles.set(toKey(p), JSON.stringify(data, null, "\t")) + // Hold the backup write pending: the assertions below + // run before this promise resolves. + await new Promise((resolve) => { + releaseWrite = () => { + const raw = memFiles.get(toKey(p)) + let existing: unknown = null + if (raw !== undefined) { + try { + existing = JSON.parse(raw) + } catch { + existing = null + } + } + const merged = options?.merge ? options.merge(existing, data) : data + memFiles.set(toKey(p), JSON.stringify(merged, null, " ")) + resolve() + } + }) return undefined as never }) }, }) - expect(p["taskHistoryStoreInitialized"]).toBe(true) - expect(pendingSnapshot).toStrictEqual([itemA]) + // The sweep is parked on the pending backup write: the blob + // must still be in globalState, untouched. + expect(releaseWrite).toBeInstanceOf(Function) + expect(state.taskHistory).toStrictEqual([itemA]) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + + releaseWrite!() + await new Promise((resolve) => setTimeout(resolve, 50)) expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) expect(state.taskHistory).toBeUndefined() + expect(p["taskHistoryStoreInitialized"]).toBe(true) }) it("keeps the blob when a task directory access fails", async () => { From ffbf0b51b652f412272d265924e691eda3d79050 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 04:44:06 +0100 Subject: [PATCH 5/8] fix(webview): defer on a malformed legacy backup and model the write window CodeRabbit round 3 on PR 2873: - A valid-JSON backup that is not an array is malformed content: the sweep now defers (keeps the blob and the file) instead of letting the merge treat it as empty and overwrite possibly recoverable entries. Regression test added (RED on the previous code: the blob was cleared and the file overwritten). - Two-sweep interleaving test: a second window's sweep merges the first window's backup entries and both survive. - TaskHistoryMigration.tla: the delete request and its storage write are separate steps now (ClearRequest, ClearCommit), because VS Code schedules the write; a downgrade append that lands in shared storage inside that request window is the documented residual race, and SyncCache no longer flags post-request arrivals as guard-protected. Ratchet: 1 covered, 1 added, 1 gap. TLC (check.sh TaskHistoryMigration): base pass 15,767 states; NoSweep 242, NoVerify 5,094, NoBackup 2,183, StaleResurrect 566, NoCompareGuard 5,414, PeerOverwrite 7,209 - each fails exactly its named invariant. Gates: test:core 5,343, test:api 6,417, scoped vitest 75, tsc, eslint, prettier. Closes #1771 --- .../architecture/tla/TaskHistoryMigration.tla | 88 ++++++++++++------- src/core/webview/ClineProvider.ts | 9 +- .../ClineProvider.taskHistory.spec.ts | 51 +++++++++++ 3 files changed, 116 insertions(+), 32 deletions(-) diff --git a/docs/architecture/tla/TaskHistoryMigration.tla b/docs/architecture/tla/TaskHistoryMigration.tla index c0f105f0ae8..a259ea6331d 100644 --- a/docs/architecture/tla/TaskHistoryMigration.tla +++ b/docs/architecture/tla/TaskHistoryMigration.tla @@ -26,8 +26,11 @@ (* *) (* Model: a startup runs initialize and migration in one action. The *) (* sweep is a chain of separate actions - SweepRead via A1 and *) -(* RetrySweep, VerifyEntries, BackupWrite, ReadBackCheck, CompareBlob, *) -(* ClearBlob - because the code awaits between them. The globalState *) +(* RetrySweep, VerifyEntries, BackupWrite, ReadBackCheck, ClearRequest, *) +(* ClearCommit - because the code awaits between them, and the storage *) +(* write of the delete request lands later still. The compare and the *) +(* delete request run in one synchronous sequence, so they are one *) +(* action (ClearRequest). The globalState *) (* key is modeled as two variables: `shared` is the shared storage all *) (* windows write, `blob` is this window's cached view that `get` *) (* returns (VS Code extHostMemento). SyncCache models the change *) @@ -41,14 +44,15 @@ (* ReadBackCheck also explore an io-failure outcome that keeps the blob. *) (* *) (* Residual race (documented, not fixable at this API level): an entry *) -(* appended to shared after the compare but before the delete request *) -(* reaches shared storage is removed without a backup. VS Code Memento *) -(* has no compare-and-delete primitive (extHostMemento.ts: update *) -(* schedules an unconditional write), so the guard can only cover entries *) -(* the cache has already seen. The compare and the delete request are *) -(* adjacent synchronous calls, which is the smallest window the API *) -(* allows. A later startup re-reads shared through a fresh cache and *) -(* sweeps any entry that arrives later. *) +(* that reaches shared storage while the delete request is in flight - *) +(* between ClearRequest and ClearCommit - is removed without a backup, *) +(* whether it arrived before the compare (hidden by the stale cache) or *) +(* in the request window. VS Code Memento has no compare-and-delete *) +(* primitive (extHostMemento.ts: update schedules an unconditional write), *) +(* so the guard can only cover entries whose notification reached the cache *) +(* before the compare. The window is the smallest the API allows, and a *) +(* later startup's fresh cache re-reads shared and sweeps anything that *) +(* arrived later. *) (* *) (* Constants: SweepEnabled, VerifyEnabled, BackupEnabled, *) (* CompareGuardEnabled and PeerMergeEnabled guard the fix. *) @@ -73,16 +77,23 @@ (* named invariant only. State counts are in the PR evidence. *) (* Cost: about 2 minutes for all seven configs on 4 cores. *) (* Review ratchet (CR 2873 round 2): 1 covered, 3 added, 2 gap. *) -(* Added: 4814652338 (DowngradeAppend at MaxStartups; compare and delete *) -(* split into two actions), 4814651913 (cached view vs shared storage *) -(* with delayed notification), 4814653507 (backup read-merge-write under *) -(* the advisory lock, modeled atomic). Covered: 4814651541 (test-side *) +(* Added: 4814652338 (DowngradeAppend at MaxStartups), 4814651913 (cached *) +(* view vs shared storage with delayed notification), 4814653507 (backup *) +(* read-merge-write under the advisory lock, modeled atomic). Covered: *) +(* 4814651541 (test-side *) (* precision fixes; the behavior they pin is already modeled by the *) (* ReadBackCheck failure outcome and the BackupWrite ordering). Gap: *) (* the documented residual race above (no CAS primitive on Memento), *) (* 4814458155 (test-suite setup, no modeled behavior), 4814458167 *) (* (fallback read retry is a read-resilience path outside the sweep *) (* machine; a regression test pins it). *) +(* Review ratchet (CR 2873 round 3): 1 covered, 1 added, 1 gap. Added: *) +(* 4814856207 + 4814856220 (the scheduled storage write is its own *) +(* ClearCommit step, with the request-window append). Covered: 4814856631 *) +(* two-sweep interleaving (BackupWrite's atomic locked merge already *) +(* covers it; a regression test lands in the same commit). Gap: *) +(* 4814856631 non-array backup content (the model's backup is a set of *) +(* ids; the content-type check lives in the code plus a regression test). *) (***************************************************************************) EXTENDS Integers @@ -174,11 +185,14 @@ RetrySweep == /\ UNCHANGED <> (* The change notification catches this window's cache up with the - shared storage. It can run at any time, with any delay. *) + shared storage. It can run at any time, with any delay. An entry + that becomes visible while the sweep is still before its compare is + one the guard protects; after the delete request it is part of the + documented residual race, so it is not flagged. *) SyncCache == /\ blob # shared /\ blob' = shared - /\ appendedAfterRead' = (IF sweepPhase # "none" THEN appendedAfterRead \cup (shared \ blob) ELSE appendedAfterRead) + /\ appendedAfterRead' = (IF sweepPhase # "none" /\ sweepPhase # "requested" THEN appendedAfterRead \cup (shared \ blob) ELSE appendedAfterRead) /\ UNCHANGED <> (* Sweep step 2: verify every read entry against the file store. An @@ -219,29 +233,41 @@ ReadBackCheck == /\ backupOk' = FALSE) /\ UNCHANGED <> -(* Sweep step 5: compare the cached blob with the array the sweep read - and request the delete. The code runs both in one synchronous - sequence, so no action interleaves between them; the delete removes - the shared key while the compare sees only this window's cache, and - a shared-only append that the cache has not synced is the documented - residual race. *) -ClearBlob == +(* Sweep step 5: compare the cached blob and REQUEST the delete. The + code runs both in one synchronous sequence, so no action interleaves + between them; update() also flips this window's cache at once. *) +ClearRequest == /\ sweepPhase = "checked" /\ LET ok == (~CompareGuardEnabled \/ blob = readSnapshot) IN /\ compareOk' = ok /\ (IF ok - THEN /\ shared' = {} - /\ blob' = {} + THEN /\ blob' = {} /\ cleared' = TRUE /\ clearedSet' = blob /\ verifiedAtClear' = Held(blob, store) - ELSE /\ shared' = shared - /\ blob' = blob + /\ sweepPhase' = "requested" + ELSE /\ blob' = blob /\ cleared' = cleared /\ clearedSet' = clearedSet - /\ verifiedAtClear' = verifiedAtClear) + /\ verifiedAtClear' = verifiedAtClear + /\ sweepPhase' = "none") + /\ UNCHANGED <> + +(* Sweep step 6: the scheduled write reaches shared storage. VS Code + schedules the storage write, so a downgrade append can land in + shared between the request and this step; such an entry is removed + without a backup. That is the documented residual race: an append + that only ever lives in shared between the request and the commit is + invisible to this window's cache, so no compare can protect it and + Memento offers no compare-and-delete primitive. The next startup's + fresh cache re-reads shared and sweeps anything that arrives later + (a cleared entry re-appended by the downgrade is backed up again by + the merge). *) +ClearCommit == + /\ sweepPhase = "requested" + /\ shared' = {} /\ sweepPhase' = "none" - /\ UNCHANGED <> + /\ UNCHANGED <> (* A peer window completed its own verified sweep between our actions. It deletes the shared blob and merges what it saw into the shared @@ -278,7 +304,7 @@ Resurrect == Next == A1 \/ A1MigrationFails \/ RetrySweep \/ SyncCache \/ VerifyEntries \/ BackupWrite - \/ ReadBackCheck \/ ClearBlob \/ PeerClear \/ DowngradeAppend \/ Resurrect + \/ ReadBackCheck \/ ClearRequest \/ ClearCommit \/ PeerClear \/ DowngradeAppend \/ Resurrect Spec == Init /\ [][Next]_vars @@ -294,7 +320,7 @@ TypeOK == /\ verifiedAtClear \in BOOLEAN /\ peerCleared \in BOOLEAN /\ attempts \leq MaxStartups - /\ sweepPhase \in {"none", "read", "verified", "backed", "checked"} + /\ sweepPhase \in {"none", "read", "verified", "backed", "checked", "requested"} /\ readSnapshot \subseteq Ids /\ clearedSet \subseteq Ids /\ appendedAfterRead \subseteq Ids diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 6c66fc33909..494768e687d 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -727,7 +727,14 @@ export class ClineProvider // safeWriteJson re-reads the file under the advisory lock, so a // concurrent sweep cannot merge against the same old content. try { - JSON.parse(await fs.readFile(backupPath, "utf8")) + const parsed: unknown = JSON.parse(await fs.readFile(backupPath, "utf8")) + if (!Array.isArray(parsed)) { + // Valid JSON that is not an array is malformed backup + // content; the merge would treat it as empty and overwrite + // possibly recoverable entries. Defer instead. + this.log("[initializeTaskHistoryStore] Keeping legacy taskHistory blob: backup file is malformed") + return + } } catch (error) { if (getErrorCode(error) !== "ENOENT" && getErrorCode(error) !== "ENOTDIR") { throw error diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index 8ae1c2b65ed..c345b716950 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -1744,6 +1744,57 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { expect(backup).toStrictEqual([itemA, itemOld]) }) + it("keeps the blob when the backup file is not an array", async () => { + const itemA = makeItem("task-a", "A") + const p = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " "), + // Valid JSON that is not an array: the sweep must not + // treat it as empty and overwrite recoverable content. + [BACKUP_PATH]: JSON.stringify({ junk: true }, null, " "), + }, + }) + + expect(p["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).not.toHaveBeenCalledWith("taskHistory", undefined) + expect(state.taskHistory).toStrictEqual([itemA]) + // The malformed file is preserved for recovery. + expect(memFiles.get(BACKUP_PATH)).toContain("junk") + }) + + it("keeps entries an earlier sweep backed up when a second sweep runs", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + // First window sweeps [itemA] and writes the backup. + await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " "), + }, + }) + const firstBackup = memFiles.get(BACKUP_PATH) + expect(firstBackup).toBeDefined() + + // A second window sweeps [itemB] against the same storage; its + // merge must keep the first window's entry. + const second = await buildProvider({ + globalState: { taskHistory: [itemB], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-b`], + files: { + [`${TASKS_DIR}/task-b/history_item.json`]: JSON.stringify(itemB, null, " "), + [BACKUP_PATH]: firstBackup!, + }, + }) + + expect(second["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + expect(backup).toStrictEqual([itemB, itemA]) + }) + it("keeps the blob when the backup read-back does not match", async () => { const itemA = makeItem("task-a", "A") const itemB = makeItem("task-b", "B") From 87c7927940af674727bc20d5e476997ac05f0f5b Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 11:42:40 +0100 Subject: [PATCH 6/8] fix(webview): close the round-4 CodeRabbit findings on the legacy blob sweep CodeRabbit round 4 on PR 2873 (all seven unresolved threads verified against this head before acting): - mergeLegacyBackup: an ID-less entry has no merge key, so the id filter appended the prior copy again on every deferred sweep and grew the backup ([e,a]+[e] -> [e,a,e]). Identical ID-less records now match one-for-one and only the prior excess survives, so prior-only records keep their multiplicity. Regression tests: two unit tests plus an end-to-end deferred-sweep test (all RED on the previous merge). - getLegacyBackupItem: a cached miss re-reads the backup file once before confirming absence, so a peer window that merges new entries into the shared backup and clears the blob after this window cached its snapshot still resolves those ids; cached hits stay cached. Regression test RED on the previous code. - TaskHistoryMigration.tla: ClearCommit models a rejected clear write (shared keeps the blob, new clearFailed marks the retained verified state) and SweptWhenVerifiable admits it through an escape that only that branch can set (probe-verified: removing the escape fails the base cfg). vars now lists every declared variable (lateArrivals, clearFailed), so [][Next]_vars constrains stuttering. RetrySweep is blocked while sweepPhase = "requested" because the code awaits the delete inside the startup flow - a pending clear write can no longer be dropped by an interleaved retry. Ratchet: 2 covered, 2 added, 2 gap (header cites each thread). - ClineProvider.taskHistory.spec.ts: the sweep harness runs the REAL safeWriteJson via vi.importActual instead of a double that copied its parse and merge dispatch; only the filesystem is mocked (sync createWriteStream staging, fs/promises rename/open, no-op advisory lock). The deferred-write test parks the commit at its rename. TLC (check.sh TaskHistoryMigration): base pass 17,789 states; NoSweep 242, NoVerify 5,094, NoBackup 2,183, StaleResurrect 566, NoCompareGuard 5,414, PeerOverwrite 7,247 - each fails exactly as its cfg requires. Gates: test:core 5,347, test:api 6,417, scoped vitest 79, tsc, eslint, prettier. Closes #1771 --- .../architecture/tla/TaskHistoryMigration.tla | 68 ++++-- .../__tests__/legacyTaskHistoryBlob.spec.ts | 24 +++ .../task-persistence/legacyTaskHistoryBlob.ts | 29 ++- src/core/webview/ClineProvider.ts | 40 ++-- .../ClineProvider.taskHistory.spec.ts | 202 ++++++++++++++---- 5 files changed, 288 insertions(+), 75 deletions(-) diff --git a/docs/architecture/tla/TaskHistoryMigration.tla b/docs/architecture/tla/TaskHistoryMigration.tla index a259ea6331d..2edea31eb58 100644 --- a/docs/architecture/tla/TaskHistoryMigration.tla +++ b/docs/architecture/tla/TaskHistoryMigration.tla @@ -42,6 +42,9 @@ (* (safeWriteJson merge callback under the advisory lock), so a peer *) (* sweep cannot erase entries an earlier backup holds. BackupWrite and *) (* ReadBackCheck also explore an io-failure outcome that keeps the blob. *) +(* ClearCommit also explores a rejected clear write: shared keeps the *) +(* blob, clearFailed marks the retained verified state, and a later *) +(* startup re-sweeps it (RetrySweep re-runs the whole chain). *) (* *) (* Residual race (documented, not fixable at this API level): an entry *) (* that reaches shared storage while the delete request is in flight - *) @@ -94,6 +97,26 @@ (* covers it; a regression test lands in the same commit). Gap: *) (* 4814856631 non-array backup content (the model's backup is a set of *) (* ids; the content-type check lives in the code plus a regression test). *) +(* Review ratchet (CR 2873 round 4): 2 covered, 2 added, 2 gap. Added: *) +(* 4814737817 (ClearCommit failure branch + the clearFailed escape in *) +(* SweptWhenVerifiable; the escape reads a variable set only by that *) +(* branch, so it cannot hold vacuously), 4814936082 (lateArrivals and *) +(* clearFailed join vars, so [][Next]_vars constrains every declared *) +(* variable during stuttering) and 4815042563 (RetrySweep blocked while *) +(* sweepPhase = "requested"; the code awaits the delete, so a startup *) +(* cannot overlap a pending clear write). Covered: 4814737827 (the backup *) +(* read-merge-write already runs inside safeWriteJson's advisory lock via *) +(* the merge callback - commit 57fd66ebd closed it before this round; the *) +(* model has described BackupWrite as one atomic locked step since round *) +(* 2), 4814936085 (test-side: the doubles must use the real writer via *) +(* vi.importActual; the pinned behavior is already modeled by the *) +(* BackupWrite and ReadBackCheck failure outcomes). Gap: 4814737822 (the *) +(* id-less multiplicity of the backup array sits below the set-of-ids *) +(* abstraction; mergeLegacyBackup now matches identical id-less records *) +(* one-for-one and regression tests pin the repeated merge), 4815042571 *) +(* (the fallback lookup cache is a read path outside the sweep machine; *) +(* getLegacyBackupItem now re-reads after a cached miss, regression test *) +(* pins it). *) (***************************************************************************) EXTENDS Integers @@ -107,8 +130,8 @@ ResurrectEnabled == FALSE Ids == {"t1", "t2"} -VARIABLES shared, blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts, sweepPhase, readSnapshot, clearedSet, appendedAfterRead, backupOk, compareOk, readHappened, lateArrivals -vars == <> +VARIABLES shared, blob, store, dirs, backup, marker, initialized, cleared, verifiedAtClear, peerCleared, attempts, sweepPhase, readSnapshot, clearedSet, appendedAfterRead, backupOk, compareOk, readHappened, lateArrivals, clearFailed +vars == <> Held(ids, storeSet) == (ids \cap dirs) \subseteq storeSet @@ -132,6 +155,7 @@ Init == /\ compareOk = TRUE /\ readHappened = FALSE /\ lateArrivals = {} + /\ clearFailed = FALSE (* First startup: initialize the store, migrate entries whose task directories exist, set the marker, then open the sweep with a read @@ -150,7 +174,7 @@ A1 == ELSE /\ sweepPhase' = "none" /\ readSnapshot' = readSnapshot /\ readHappened' = readHappened) - /\ UNCHANGED <> + /\ UNCHANGED <> (* A startup whose migration fails. The marker stays unset, the blob stays, and the next startup retries. *) @@ -158,16 +182,21 @@ A1MigrationFails == /\ attempts < MaxStartups /\ ~initialized /\ attempts' = attempts + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> (* A later startup with the marker already set. Migration is skipped and the sweep opens with a fresh read of the cached blob, so entries an earlier sweep kept become visible to verification. A fresh cache in a - new window sees shared as it is. *) + new window sees shared as it is. A startup cannot run while a clear + write is pending: the code awaits the delete inside the startup flow, + so RetrySweep is blocked while sweepPhase = "requested" and the + pending request cannot be dropped by an interleaved retry (CR 2873 + thread 4815042563). *) RetrySweep == /\ attempts < MaxStartups /\ initialized /\ marker + /\ sweepPhase # "requested" /\ attempts' = attempts + 1 /\ store' = store /\ blob' = shared @@ -182,7 +211,7 @@ RetrySweep == /\ appendedAfterRead' = appendedAfterRead /\ clearedSet' = clearedSet /\ readHappened' = readHappened) - /\ UNCHANGED <> + /\ UNCHANGED <> (* The change notification catches this window's cache up with the shared storage. It can run at any time, with any delay. An entry @@ -193,14 +222,14 @@ SyncCache == /\ blob # shared /\ blob' = shared /\ appendedAfterRead' = (IF sweepPhase # "none" /\ sweepPhase # "requested" THEN appendedAfterRead \cup (shared \ blob) ELSE appendedAfterRead) - /\ UNCHANGED <> + /\ UNCHANGED <> (* Sweep step 2: verify every read entry against the file store. An unconfirmed entry stops the sweep and keeps the blob. *) VerifyEntries == /\ sweepPhase = "read" /\ sweepPhase' = (IF ~VerifyEnabled \/ Held(readSnapshot, store) THEN "verified" ELSE "none") - /\ UNCHANGED <> + /\ UNCHANGED <> (* Sweep step 3: write the backup. The read-merge-write runs as one atomic step under the advisory lock (safeWriteJson merge callback), @@ -218,7 +247,7 @@ BackupWrite == ELSE /\ backup' = backup /\ sweepPhase' = "none" /\ backupOk' = FALSE) - /\ UNCHANGED <> + /\ UNCHANGED <> (* Sweep step 4: read the backup back and compare its content. Without the backup requirement the check passes by design; a failed read or a @@ -231,7 +260,7 @@ ReadBackCheck == /\ backupOk' = TRUE ELSE /\ sweepPhase' = "none" /\ backupOk' = FALSE) - /\ UNCHANGED <> + /\ UNCHANGED <> (* Sweep step 5: compare the cached blob and REQUEST the delete. The code runs both in one synchronous sequence, so no action interleaves @@ -251,7 +280,7 @@ ClearRequest == /\ clearedSet' = clearedSet /\ verifiedAtClear' = verifiedAtClear /\ sweepPhase' = "none") - /\ UNCHANGED <> + /\ UNCHANGED <> (* Sweep step 6: the scheduled write reaches shared storage. VS Code schedules the storage write, so a downgrade append can land in @@ -265,7 +294,12 @@ ClearRequest == the merge). *) ClearCommit == /\ sweepPhase = "requested" - /\ shared' = {} + /\ \E ok \in BOOLEAN : + (IF ok + THEN /\ shared' = {} + /\ clearFailed' = clearFailed + ELSE /\ shared' = shared + /\ clearFailed' = TRUE) /\ sweepPhase' = "none" /\ UNCHANGED <> @@ -278,7 +312,7 @@ PeerClear == /\ shared' = {} /\ backup' = (IF PeerMergeEnabled THEN backup \cup shared ELSE shared) /\ peerCleared' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> (* An old build re-writes the legacy list in shared storage while the marker is set. Its entries were never migrated, so they are not held @@ -291,7 +325,7 @@ DowngradeAppend == /\ \E id \in Ids \ shared : /\ shared' = shared \cup {id} /\ lateArrivals' = lateArrivals \cup {id} - /\ UNCHANGED <> + /\ UNCHANGED <> (* Sabotage only: a buggy variant writes a stale in-memory array back after a peer cleared the shared blob. *) @@ -300,7 +334,7 @@ Resurrect == /\ peerCleared /\ shared' = Ids /\ blob' = Ids - /\ UNCHANGED <> + /\ UNCHANGED <> Next == A1 \/ A1MigrationFails \/ RetrySweep \/ SyncCache \/ VerifyEntries \/ BackupWrite @@ -328,6 +362,7 @@ TypeOK == /\ compareOk \in BOOLEAN /\ readHappened \in BOOLEAN /\ lateArrivals \subseteq Ids + /\ clearFailed \in BOOLEAN (* No startup that finished a verified migration leaves the blob behind without a reason, judged on the shared storage. A blob that survives @@ -338,7 +373,8 @@ SweptWhenVerifiable == (\/ shared = {} \/ ~Held(shared, store) \/ (shared # readSnapshot /\ readHappened) - \/ shared \subseteq lateArrivals) + \/ shared \subseteq lateArrivals + \/ clearFailed) \* CR 2873 thread 4814737817: the clear write failed; the blob stays for a later startup. (* A sweep only clears after every entry with a task directory is held by the file store. *) diff --git a/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts index 93557a595fb..af46b5a83c1 100644 --- a/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts +++ b/src/core/task-persistence/__tests__/legacyTaskHistoryBlob.spec.ts @@ -102,4 +102,28 @@ describe("mergeLegacyBackup", () => { const current = [{ id: "t1" }] as HistoryItem[] expect(mergeLegacyBackup(current, [])).toStrictEqual([{ id: "t1" }]) }) + + it("keeps the backup stable across repeated deferred sweeps with ID-less entries", () => { + const orphan = { task: "no-id" } as unknown as HistoryItem + const itemA = { id: "t1" } as HistoryItem + // Sweep 1 retains the blob, so sweep 2 reads the same current + // array and merges against the backup written before. + const first = mergeLegacyBackup([orphan, itemA], [orphan]) + expect(first).toStrictEqual([orphan, itemA]) + const second = mergeLegacyBackup([orphan, itemA], first) + expect(second).toStrictEqual([orphan, itemA]) + }) + + it("preserves the prior-only multiplicity of identical ID-less records", () => { + const orphan = { task: "no-id" } as unknown as HistoryItem + // The current array holds one copy; a second prior copy survives. + expect(mergeLegacyBackup([orphan] as HistoryItem[], [orphan, orphan])).toStrictEqual([orphan, orphan]) + // A distinct ID-less record never collapses into a matching one. + const distinct = { task: "other" } as unknown as HistoryItem + expect(mergeLegacyBackup([{ id: "t1" } as HistoryItem, orphan], [orphan, distinct])).toStrictEqual([ + { id: "t1" } as HistoryItem, + orphan, + distinct, + ]) + }) }) diff --git a/src/core/task-persistence/legacyTaskHistoryBlob.ts b/src/core/task-persistence/legacyTaskHistoryBlob.ts index c0c73a357e4..ec761ba8108 100644 --- a/src/core/task-persistence/legacyTaskHistoryBlob.ts +++ b/src/core/task-persistence/legacyTaskHistoryBlob.ts @@ -39,9 +39,36 @@ export function planLegacyBlobSweep( * * Entries only the earlier backup holds (e.g. orphans with no task * directory) must survive the write; current entries win on an id clash. + * Identical ID-less records match one-for-one, so a repeated deferred + * sweep does not duplicate them; unmatched prior-only records keep their + * existing multiplicity. */ export function mergeLegacyBackup(current: HistoryItem[], prior: HistoryItem[]): HistoryItem[] { const currentIds = new Set(current.map((item) => item?.id).filter((id): id is string => Boolean(id))) - const keptPrior = prior.filter((item) => !item?.id || !currentIds.has(item.id)) + // An ID-less entry has no merge key, so the id filter below would + // append the prior copy again on every deferred sweep and grow the + // backup. Match identical ID-less records one-for-one and keep only + // the prior excess (CR 2873 thread 4814737822). + const currentIdless = new Map() + for (const item of current) { + if (!item?.id) { + const key = JSON.stringify(item) + currentIdless.set(key, (currentIdless.get(key) ?? 0) + 1) + } + } + const keptPrior: HistoryItem[] = [] + for (const item of prior) { + if (!item?.id) { + const key = JSON.stringify(item) + const matched = currentIdless.get(key) ?? 0 + if (matched > 0) { + currentIdless.set(key, matched - 1) + continue + } + } else if (currentIds.has(item.id)) { + continue + } + keptPrior.push(item) + } return [...current, ...keptPrior] } diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 494768e687d..f831bad195c 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -801,22 +801,34 @@ export class ClineProvider /** * Read an item from the legacy blob sweep backup, parsed once. + * + * A cached hit stays cached; a cached miss re-reads the file once, + * because a peer window can extend the shared backup after this + * window cached its snapshot. */ private async getLegacyBackupItem(id: string): Promise { - if (this.legacyBackupItems === undefined) { - try { - const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) - const raw = await fs.readFile(backupPath, "utf8") - const parsed: unknown = JSON.parse(raw) - this.legacyBackupItems = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null - } catch (error) { - // A missing backup file is confirmed absence. Any other - // failure (e.g. EACCES, EIO) must stay retryable, so keep - // the unread state and let the next lookup read again. - const code = getErrorCode(error) - if (code === "ENOENT" || code === "ENOTDIR") { - this.legacyBackupItems = null - } + if (this.legacyBackupItems !== undefined) { + const hit = this.legacyBackupItems?.find((item) => item?.id === id) + if (hit !== undefined) { + return hit + } + // A cached miss can be stale: a peer window merges new entries + // into the shared backup and clears the blob after this window + // cached its snapshot. Read the backup again before confirming + // absence (CR 2873 thread 4815042571). + } + try { + const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) + const raw = await fs.readFile(backupPath, "utf8") + const parsed: unknown = JSON.parse(raw) + this.legacyBackupItems = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null + } catch (error) { + // A missing backup file is confirmed absence. Any other + // failure (e.g. EACCES, EIO) must stay retryable, so keep + // the unread state and let the next lookup read again. + const code = getErrorCode(error) + if (code === "ENOENT" || code === "ENOTDIR") { + this.legacyBackupItems = null } } return this.legacyBackupItems?.find((item) => item?.id === id) ?? undefined diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index c345b716950..99ed97984e0 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -1,3 +1,4 @@ +import { Writable } from "node:stream" import { WebviewFocusTracker } from "../WebviewFocusTracker" // pnpm --filter roo-cline test core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -29,6 +30,8 @@ vi.mock("fs/promises", () => { readFile: vi.fn().mockResolvedValue(""), readdir: vi.fn().mockResolvedValue([]), stat: vi.fn(), + rename: vi.fn(), + open: vi.fn(), unlink: vi.fn().mockResolvedValue(undefined), rmdir: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), @@ -37,6 +40,27 @@ vi.mock("fs/promises", () => { return { ...mock, default: mock } }) +// The sweep harness runs the real safeWriteJson against the in-memory +// fs (CR 2873 thread 4814936085). Its temp-file staging writes through +// the sync createWriteStream, so only that one function is mocked here. +vi.mock("fs", async (importOriginal) => { + const actual = await importOriginal() + const createWriteStream = vi.fn() + return { + ...actual, + default: { ...actual, createWriteStream }, + createWriteStream, + } +}) + +// The advisory lock protocol crosses process boundaries with real lock +// directories; the in-memory fs has none. The real safeWriteJson keeps +// its read-merge-write sequence and commits with this no-op lock. +vi.mock("../../../utils/fileLock", async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, acquireFileLock: vi.fn(async () => async () => {}) } +}) + vi.mock("axios", () => ({ default: { get: vi.fn().mockResolvedValue({ data: { data: [] } }), @@ -1362,6 +1386,7 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { const toKey = (p: unknown): string => String(p).replace(/\\/g, "/") const wireFsMocks = async () => { + renameGate = undefined fsMockRef = await import("fs/promises") const fsMock = fsMockRef vi.mocked(fsMock.mkdir).mockReset().mockResolvedValue(undefined) @@ -1413,30 +1438,65 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { } return { mtimeMs: content.length } as never }) - const swj = (swjRef = await import("../../../utils/safeWriteJson")) - vi.mocked(swj.safeWriteJson) + // The sweep's temp-file staging and commit run through the + // sync stream and the fs/promises rename, so wire them onto + // the same in-memory map (CR 2873 thread 4814936085: the real + // writer runs; only the filesystem is mocked). + const fsSyncRef = await import("fs") + vi.mocked(fsSyncRef.createWriteStream) .mockReset() - .mockImplementation(async (p, data, options) => { - // Mirror safeWriteJson's merge contract: existing is null - // when the file is absent or unparseable; the merge - // result replaces the written content. - const raw = memFiles.get(toKey(p)) - let existing: unknown = null - if (raw !== undefined) { - try { - existing = JSON.parse(raw) - } catch { - existing = null - } + .mockImplementation(((targetPath: unknown) => { + let staged = "" + return new Writable({ + write(chunk: unknown, _enc: unknown, cb: (error?: Error | null) => void) { + staged += String(chunk) + cb() + }, + final(cb: (error?: Error | null) => void) { + memFiles.set(toKey(targetPath), staged) + cb() + }, + }) as never + }) as never) + vi.mocked(fsMock.rename) + .mockReset() + .mockImplementation(async (fromPath, toPath) => { + const from = toKey(fromPath) + const to = toKey(toPath) + const content = memFiles.get(from) + if (content === undefined) { + throw errno("ENOENT", from) } - const merged = options?.merge ? options.merge(existing, data) : data - memFiles.set(toKey(p), JSON.stringify(merged, null, " ")) + if (renameGate && to === BACKUP_PATH) { + // The deferred-write test parks the commit rename. + await renameGate.promise + } + memFiles.set(to, content) + memFiles.delete(from) return undefined as never }) + vi.mocked(fsMock.open) + .mockReset() + .mockImplementation(async () => + Promise.resolve({ + sync: vi.fn().mockResolvedValue(undefined), + close: vi.fn().mockResolvedValue(undefined), + } as never), + ) + lockRef = await import("../../../utils/fileLock") + vi.mocked(lockRef.acquireFileLock) + .mockReset() + .mockImplementation(async () => async () => {}) + const swj = (swjRef = await import("../../../utils/safeWriteJson")) + const realWriter = + await vi.importActual("../../../utils/safeWriteJson") + vi.mocked(swj.safeWriteJson).mockReset().mockImplementation(realWriter.safeWriteJson) } let fsMockRef: typeof import("fs/promises") let swjRef: typeof import("../../../utils/safeWriteJson") + let lockRef: typeof import("../../../utils/fileLock") + let renameGate: { promise: Promise; release: () => void } | undefined const buildProvider = async (options: { globalState: Record @@ -1794,6 +1854,27 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] expect(backup).toStrictEqual([itemB, itemA]) }) + it("keeps ID-less backup entries stable across deferred sweeps", async () => { + const itemA = makeItem("task-a", "A") + const orphan = { number: 1, ts: 1, task: "no-id" } as unknown as HistoryItem + const providerWithOrphan = await buildProvider({ + globalState: { taskHistory: [orphan, itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { + [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t"), + // A previous sweep wrote this backup; the blob was retained + // because that sweep's clear did not run. + [BACKUP_PATH]: JSON.stringify([orphan], null, "\t"), + }, + }) + + expect(providerWithOrphan["taskHistoryStoreInitialized"]).toBe(true) + expect(context.globalState.update).toHaveBeenCalledWith("taskHistory", undefined) + const backup = JSON.parse(memFiles.get(BACKUP_PATH) ?? "[]") as HistoryItem[] + // The ID-less entry must not be appended a second time (CR 2873 + // thread 4814737822). + expect(backup).toStrictEqual([orphan, itemA]) + }) it("keeps the blob when the backup read-back does not match", async () => { const itemA = makeItem("task-a", "A") @@ -1828,13 +1909,14 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { dirs: [`${TASKS_DIR}/task-a`], files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, beforeFlush: () => { - // The merge pre-check read succeeds so the backup write - // lands; only the post-write read-back fails. + // The pre-check read and the writer's locked merge read + // succeed, so the backup write lands; only the post-write + // read-back fails. let backupReads = 0 vi.mocked(fsMockRef.readFile).mockImplementation(async (p) => { if (toKey(p) === BACKUP_PATH) { backupReads += 1 - if (backupReads >= 2) { + if (backupReads >= 3) { throw errno("EIO", toKey(p)) } } @@ -1864,31 +1946,17 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { dirs: [`${TASKS_DIR}/task-a`], files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, " ") }, beforeFlush: () => { - vi.mocked(swjRef.safeWriteJson).mockImplementation(async (p, data, options) => { - if (toKey(p) !== BACKUP_PATH) { - memFiles.set(toKey(p), JSON.stringify(data, null, " ")) - return undefined as never - } - // Hold the backup write pending: the assertions below - // run before this promise resolves. - await new Promise((resolve) => { - releaseWrite = () => { - const raw = memFiles.get(toKey(p)) - let existing: unknown = null - if (raw !== undefined) { - try { - existing = JSON.parse(raw) - } catch { - existing = null - } - } - const merged = options?.merge ? options.merge(existing, data) : data - memFiles.set(toKey(p), JSON.stringify(merged, null, " ")) - resolve() - } - }) - return undefined as never - }) + // Park the backup commit at its rename: the real writer has + // read, merged, and staged the temp file by then, and the + // assertions below run before the write lands. + let release: (() => void) | undefined + renameGate = { + promise: new Promise((resolve) => { + release = resolve + }), + release: () => release?.(), + } + releaseWrite = () => renameGate?.release() }, }) @@ -1974,5 +2042,51 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { const second = await p["getTaskHistoryItem"]("task-a") expect(second?.id).toBe("task-a") }) + + it("re-reads the backup after a cached miss when a peer extends it", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + let backupReads = 0 + const pStale = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + // Store init fails, so the provider keeps the legacy + // fallback path; count the backup reads from here on. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + vi.mocked(fsMockRef.readFile).mockImplementation(async (pathArg) => { + if (toKey(pathArg) === BACKUP_PATH) { + backupReads += 1 + } + const key = toKey(pathArg) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(pStale["taskHistoryStoreInitialized"]).toBe(false) + const cached = await pStale["getTaskHistoryItem"]("task-a") + expect(cached?.id).toBe("task-a") + const readsAfterCache = backupReads + + // A peer window merges B into the shared backup and clears the + // blob while this window still holds its cached [A]. + memFiles.set(BACKUP_PATH, JSON.stringify([itemB, itemA], null, "\t")) + + // The cached miss must re-read the file and find B without a + // restart (CR 2873 thread 4815042571). + const found = await pStale["getTaskHistoryItem"]("task-b") + expect(found?.id).toBe("task-b") + expect(backupReads).toBe(readsAfterCache + 1) + + // A cached hit keeps using the cache: no further read. + const again = await pStale["getTaskHistoryItem"]("task-a") + expect(again?.id).toBe("task-a") + expect(backupReads).toBe(readsAfterCache + 1) + }) }) }) From 73475ef8828e31b317215c3a2f1612c65cebca68 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 12:39:45 +0100 Subject: [PATCH 7/8] test(webview): normalize the drive anchor in taskHistory sweep fixture keys Windows-only platform-unit-test repair (PR #2873): the real safeWriteJson resolves fixture paths via path.resolve, which anchors the POSIX-rooted /test/storage/path fixtures to the runner's working drive on win32, so the mock-fs toKey lookups missed and migrateFromGlobalState threw ENOENT (D:/test/storage/path/tasks/task-a), deferring the sweep in 9 tests. Production is unaffected: a real Windows globalStorageUri.fsPath is drive-absolute already (same class as the #2872 normalize-stable repair). Strip the drive anchor in toKey. RED-verified with a win32 path.resolve anchor shim (9 failures, byte-identical log line), GREEN 68/68 under the shim; gates core 5347, api 6417+2skip, tsc/eslint/prettier clean. No TLA change: test-harness keying only, modeled sweep semantics untouched. --- .../__tests__/ClineProvider.taskHistory.spec.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index 99ed97984e0..e144b36ce94 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -1381,9 +1381,16 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { return err } - // Normalize separators: production path.join emits backslashes on - // Windows, while the in-memory keys use forward slashes. - const toKey = (p: unknown): string => String(p).replace(/\\/g, "/") + // Normalize separators and the drive anchor: production path.join + // emits backslashes on Windows, and the real safeWriteJson resolves + // fixture paths against the working drive (path.resolve in + // utils/safeWriteJson.ts), so a "/test/..." fixture arrives with a + // "D:" prefix on windows CI. The in-memory keys stay forward-slash, + // drive-less. + const toKey = (p: unknown): string => + String(p) + .replace(/\\/g, "/") + .replace(/^[A-Za-z]:/, "") const wireFsMocks = async () => { renameGate = undefined From be7cda173311ece38f3f3a37f44f780ebd55cfab Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 6 Dec 2026 13:31:48 +0100 Subject: [PATCH 8/8] fix(webview): close the round-5 CodeRabbit findings on the legacy blob sweep CodeRabbit round 5 on PR 2873 (five fresh threads on 87c792794; the Windows fixture-root Major was already repaired in 73475ef88 with both platform jobs green): - getLegacyBackupBasePath resolves the storage root per access instead of pinning the first result; getStorageBasePath re-reads the custom storage setting, so a runtime root change no longer leaves this window reading a stale path (4816587009). Regression test moves the root mid-lookup. - getLegacyBackupItem reads through readFileWithMissingRetry, so an interrupted replacement (committed content in a recovery file) is restored under the writer lock before absence is confirmed (4816587011). Regression test seeds a .bak_ recovery file without a canonical backup. - getTaskHistoryItem rechecks store authority after the awaited backup read; initialization completing in that window no longer delivers a stale fallback item past the authoritative store (4816587019). Regression test parks the read and flips the flag mid-lookup. - Mode-switch and sticky-profile persistence update store-held items field-only via TaskHistoryStore.atomicReadAndUpdate under the store lock, so a cost saved between a caller's lookup and the write is no longer reverted by the older full-item snapshot (4816587015). The legacy/backup fallback keeps the full-item write path. it.each regression tests replay a stale snapshot against a newer saved cost for both flows; the sticky-mode/sticky-profile suites now assert the persisted outcome and the atomic path. - TaskHistoryMigration.tla: Init admits marker = TRUE (an already- migrated startup), and A1 skips the migration update for it, so the model also checks the keep-when-unverified order on already-migrated inputs (4816587007). Ratchet round 5: 1 covered, 1 added, 4 gap. TLC (check.sh TaskHistoryMigration): base pass 27,075 states (the marker dimension widens the domain from 17,789); NoSweep 625, NoVerify 5,102, NoBackup 4,755, StaleResurrect 634, NoCompareGuard 9,585, PeerOverwrite 12,282 - each variant fails as its config requires. Gates: test:core 5,352, test:api 6,417, scoped vitest 113, tsc, eslint, prettier. Closes #1771 --- .../architecture/tla/TaskHistoryMigration.tla | 25 ++- src/core/webview/ClineProvider.ts | 66 +++++-- .../ClineProvider.sticky-mode.spec.ts | 83 ++++---- .../ClineProvider.sticky-profile.spec.ts | 59 +++--- .../ClineProvider.taskHistory.spec.ts | 177 +++++++++++++++++- src/eslint-suppressions.json | 4 +- 6 files changed, 320 insertions(+), 94 deletions(-) diff --git a/docs/architecture/tla/TaskHistoryMigration.tla b/docs/architecture/tla/TaskHistoryMigration.tla index 2edea31eb58..25c6d5e4396 100644 --- a/docs/architecture/tla/TaskHistoryMigration.tla +++ b/docs/architecture/tla/TaskHistoryMigration.tla @@ -117,6 +117,23 @@ (* (the fallback lookup cache is a read path outside the sweep machine; *) (* getLegacyBackupItem now re-reads after a cached miss, regression test *) (* pins it). *) +(* Review ratchet (CR 2873 round 5): 1 covered, 1 added, 4 gap. Added: *) +(* 4816587007 (the input domain admits marker = TRUE at startup: Init *) +(* draws the marker and A1 skips the migration update, so the model also *) +(* checks the keep-when-unverified order on already-migrated inputs). *) +(* Covered: 4816471340 (Windows drive-anchor normalization of the test *) +(* fixture root; the model has no path strings, and the harness fix landed *) +(* in commit 73475ef88 with the platform jobs green). Gap: 4816587009 *) +(* (the custom storage root is a setting read outside the sweep machine; *) +(* the backup root is resolved per access and a regression test pins the *) +(* runtime change), 4816587011 (interrupted-replacement recovery is the *) +(* writer's domain; getLegacyBackupItem reads through *) +(* readFileWithMissingRetry and a recovery-file regression test pins it), *) +(* 4816587015 (mode/profile persistence writes a full-item snapshot *) +(* outside the sweep machine; the store-held path updates the field under *) +(* the store lock and regression tests pin the preserved cost), 4816587019 *) +(* (the fallback authority recheck is a read-ordering rule outside the *) +(* sweep machine; a regression test pins it). *) (***************************************************************************) EXTENDS Integers @@ -141,7 +158,7 @@ Init == /\ store \in SUBSET Ids /\ dirs \in SUBSET Ids /\ backup = {} - /\ marker = FALSE + /\ marker \in BOOLEAN /\ initialized = FALSE /\ cleared = FALSE /\ verifiedAtClear = FALSE @@ -159,14 +176,16 @@ Init == (* First startup: initialize the store, migrate entries whose task directories exist, set the marker, then open the sweep with a read - of the cached blob. *) + of the cached blob. A provider can also start with the marker + already set; migration is skipped and the store stays empty, so the + sweep keeps the unverified blob (CR 2873 thread 4816587007). *) A1 == /\ attempts < MaxStartups /\ ~initialized /\ attempts' = attempts + 1 /\ marker' = TRUE /\ initialized' = TRUE - /\ store' = store \cup (blob \cap dirs) + /\ store' = (IF marker THEN store ELSE store \cup (blob \cap dirs)) /\ (IF SweepEnabled /\ blob # {} THEN /\ sweepPhase' = "read" /\ readSnapshot' = blob diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index f831bad195c..fff0594c88f 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -341,8 +341,6 @@ export class ClineProvider private readonly taskTitleService: TaskTitleService private taskHistoryStoreInitialized = false - /** Storage root of the legacy blob sweep backup, resolved once. */ - private legacyBackupPath: string | undefined /** Parsed legacy blob backup; undefined = not read yet, null = absent or unparsable. */ private legacyBackupItems: HistoryItem[] | null | undefined public static readonly PENDING_OPERATION_TIMEOUT_MS = 30000 // 30 seconds @@ -789,14 +787,15 @@ export class ClineProvider } /** - * Storage root for the legacy blob backup, resolved once per provider. + * Storage root for the legacy blob backup, resolved per access. + * + * getStorageBasePath re-reads the custom storage setting on every + * call, so a runtime root change is picked up instead of pinning the + * first resolution (CR 2873 thread 4816587009). */ private async getLegacyBackupBasePath(): Promise { - if (!this.legacyBackupPath) { - const { getStorageBasePath } = await import("../../utils/storage") - this.legacyBackupPath = await getStorageBasePath(this.contextProxy.globalStorageUri.fsPath) - } - return this.legacyBackupPath + const { getStorageBasePath } = await import("../../utils/storage") + return getStorageBasePath(this.contextProxy.globalStorageUri.fsPath) } /** @@ -819,7 +818,11 @@ export class ClineProvider } try { const backupPath = path.join(await this.getLegacyBackupBasePath(), LEGACY_TASK_HISTORY_BACKUP_FILE) - const raw = await fs.readFile(backupPath, "utf8") + // A replacement interrupted between its two renames keeps the + // committed content in a recovery file; this read retries the + // transient absence and restores it under the writer's lock + // (CR 2873 thread 4816587011). + const raw = await readFileWithMissingRetry(backupPath) const parsed: unknown = JSON.parse(raw) this.legacyBackupItems = Array.isArray(parsed) ? (parsed as HistoryItem[]) : null } catch (error) { @@ -2292,11 +2295,22 @@ export class ClineProvider task.emit(RooCodeEventName.TaskModeSwitched, task.taskId, newMode) try { - // Update the task history with the new mode first. - const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) + // Update the task history with the new mode first. A + // store-held item is updated field-only under the store + // lock, so a cost saved between the lookup and this write + // is not reverted by the older snapshot (CR 2873 thread + // 4816587015). + if (this.taskHistoryStore.get(task.taskId)) { + await this.taskHistoryStore.atomicReadAndUpdate(task.taskId, (current) => ({ + ...current, + mode: newMode, + })) + } else { + const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) - if (taskHistoryItem) { - await this.updateTaskHistory({ ...taskHistoryItem, mode: newMode }) + if (taskHistoryItem) { + await this.updateTaskHistory({ ...taskHistoryItem, mode: newMode }) + } } // Only update the task's mode after successful persistence. @@ -2675,10 +2689,21 @@ export class ClineProvider // been persisted into taskHistory (it will be captured on the next save). task.setTaskApiConfigName(apiConfigName) - const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) + // Store-held items are updated field-only under the store + // lock; a token or cost saved between the lookup and this + // write must not be reverted by the older snapshot (CR 2873 + // thread 4816587015). + if (this.taskHistoryStore.get(task.taskId)) { + await this.taskHistoryStore.atomicReadAndUpdate(task.taskId, (current) => ({ + ...current, + apiConfigName, + })) + } else { + const taskHistoryItem = await this.getTaskHistoryItem(task.taskId) - if (taskHistoryItem) { - await this.updateTaskHistory({ ...taskHistoryItem, apiConfigName }) + if (taskHistoryItem) { + await this.updateTaskHistory({ ...taskHistoryItem, apiConfigName }) + } } } catch (error) { // If persistence fails, log the error but don't fail the profile switch. @@ -2958,7 +2983,14 @@ export class ClineProvider // A peer window may have swept the blob while this provider's startup failed; // the sweep backup keeps the fallback working in that window. - return this.getLegacyBackupItem(id) + const backupItem = await this.getLegacyBackupItem(id) + // Initialization can complete while the backup read awaits; the + // file store is authoritative once it does (CR 2873 thread + // 4816587019). + if (this.taskHistoryStoreInitialized) { + return this.taskHistoryStore.get(id) + } + return backupItem } async getTaskWithId(id: string): Promise<{ diff --git a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts index f73101d4eeb..97edeb740d6 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts @@ -360,11 +360,8 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to track calls - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) - + // A store-held item is updated field-only under the store lock + // (CR 2873 thread 4816587015), so assert the persisted outcome. // Add task to provider stack await provider.addClineToStack(mockTask) @@ -375,12 +372,10 @@ describe("ClineProvider - Sticky Mode", () => { expect(mockContext.globalState.update).toHaveBeenCalledWith("mode", "architect") // Verify task history was updated with new mode - expect(updateTaskHistorySpy).toHaveBeenCalledWith( - expect.objectContaining({ - id: taskId, - mode: "architect", - }), - ) + expect(provider.taskHistoryStore.get(taskId)).toMatchObject({ + id: taskId, + mode: "architect", + }) }) it("should update task's taskMode property when switching modes", async () => { @@ -453,24 +448,19 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to track calls - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) - + // A store-held item is updated field-only under the store lock + // (CR 2873 thread 4816587015), so assert the persisted outcome. // Add task to provider stack await provider.addClineToStack(mockTask) // Switch mode await provider.handleModeSwitch("architect") - // Verify updateTaskHistory was called with mode in the history item - expect(updateTaskHistorySpy).toHaveBeenCalledWith( - expect.objectContaining({ - id: taskId, - mode: "architect", - }), - ) + // Verify the store holds the item with the new mode + expect(provider.taskHistoryStore.get(taskId)).toMatchObject({ + id: taskId, + mode: "architect", + }) }) }) @@ -576,12 +566,10 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to capture the updated history item - let updatedHistoryItem: any - vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { - updatedHistoryItem = item - return Promise.resolve([item]) - }) + // The switch updates a store-held item field-only under the + // store lock; capture the updater and apply it to the current + // cached item (CR 2873 thread 4816587015). + const atomicSpy = vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate") // Add task to provider stack await provider.addClineToStack(mockTask) @@ -590,7 +578,9 @@ describe("ClineProvider - Sticky Mode", () => { await provider.handleModeSwitch("debug") // Verify mode was included in the updated history item - expect(updatedHistoryItem).toBeDefined() + expect(atomicSpy).toHaveBeenCalledWith(taskId, expect.any(Function)) + const [, updater] = atomicSpy.mock.calls[atomicSpy.mock.calls.length - 1] + const updatedHistoryItem = updater(provider.taskHistoryStore.get(taskId)!) expect(updatedHistoryItem.mode).toBe("debug") }) }) @@ -636,7 +626,9 @@ describe("ClineProvider - Sticky Mode", () => { } }) - // Mock updateTaskHistory to track mode changes + // Track mode changes on both write paths: store-held items go + // through atomicReadAndUpdate (CR 2873 thread 4816587015), + // fallback-only items through updateTaskHistory. const updateTaskHistoryMock = vi.spyOn(provider, "updateTaskHistory") updateTaskHistoryMock.mockImplementation((item) => { // The handleModeSwitch method updates the task history for the current task @@ -646,6 +638,17 @@ describe("ClineProvider - Sticky Mode", () => { } return Promise.resolve([]) }) + vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate").mockImplementation(async (id, updater) => { + const current = provider.taskHistoryStore.get(id) + if (!current) { + throw new Error(`[TaskHistoryStore] atomicReadAndUpdate: task ${id} not found in cache`) + } + const updated = updater(current) + if (updated.mode !== undefined) { + taskModes[updated.id] = updated.mode + } + return [updated] + }) // Add parent task to stack await provider.addClineToStack(parentTask) @@ -859,11 +862,6 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) - // Clear previous calls to globalState.update vi.mocked(mockContext.globalState.update).mockClear() @@ -883,9 +881,10 @@ describe("ClineProvider - Sticky Mode", () => { // Verify the last mode switch wins expect(lastModeCall).toEqual(["mode", "code"]) - // Verify task history was updated with final mode - const lastCall = updateTaskHistorySpy.mock.calls[updateTaskHistorySpy.mock.calls.length - 1] - expect(lastCall[0]).toMatchObject({ + // Verify task history was updated with the final mode: the + // switches serialize through the store lock, so the last one + // wins (CR 2873 thread 4816587015). + expect(provider.taskHistoryStore.get(mockTask.taskId)).toMatchObject({ id: mockTask.taskId, mode: "code", }) @@ -1073,8 +1072,10 @@ describe("ClineProvider - Sticky Mode", () => { }, ]) - // Mock updateTaskHistory to throw error - vi.spyOn(provider, "updateTaskHistory").mockRejectedValue(new Error("Update failed")) + // A store-held item persists through atomicReadAndUpdate; its + // failure must propagate the same way (CR 2873 thread + // 4816587015). + vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate").mockRejectedValue(new Error("Update failed")) // Mock console.error const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 9b5996a6ea1..7b8ffd436a4 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -391,10 +391,8 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) - // Mock updateTaskHistory to track calls - const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockImplementation(() => { - return Promise.resolve([]) - }) + // A store-held item is updated field-only under the store + // lock (CR 2873 thread 4816587015), so assert the outcome. // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ @@ -412,12 +410,10 @@ describe("ClineProvider - Sticky Provider Profile", () => { await provider.activateProviderProfile({ name: "new-profile" }) // Verify task history was updated with new provider profile - expect(updateTaskHistorySpy).toHaveBeenCalledWith( - expect.objectContaining({ - id: mockTask.taskId, - apiConfigName: "new-profile", - }), - ) + expect(provider.taskHistoryStore.get(mockTask.taskId)).toMatchObject({ + id: mockTask.taskId, + apiConfigName: "new-profile", + }) // Verify task's setTaskApiConfigName was called expect(mockTask.setTaskApiConfigName).toHaveBeenCalledWith("new-profile") @@ -447,6 +443,7 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([]) + const atomicSpy = vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate") vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ name: "new-profile", id: "new-profile-id", @@ -459,9 +456,15 @@ describe("ClineProvider - Sticky Provider Profile", () => { expect(currentTask.setTaskApiConfigName).toHaveBeenCalledTimes(applies ? 1 : 0) const stickyWrite = expect.objectContaining({ id: currentTask.taskId, apiConfigName: "new-profile" }) if (applies) { - expect(updateTaskHistorySpy).toHaveBeenCalledWith(stickyWrite) + // Store-held items persist field-only under the store + // lock (CR 2873 thread 4816587015). + expect(atomicSpy).toHaveBeenCalledWith(currentTask.taskId, expect.any(Function)) + const [, updater] = atomicSpy.mock.calls[atomicSpy.mock.calls.length - 1] + expect(updater(provider.taskHistoryStore.get(currentTask.taskId)!)).toMatchObject(stickyWrite) + expect(updateTaskHistorySpy).not.toHaveBeenCalled() } else { expect(updateTaskHistorySpy).not.toHaveBeenCalled() + expect(atomicSpy).not.toHaveBeenCalled() } }, ) @@ -892,12 +895,9 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) - // Mock updateTaskHistory to capture the updated history item - let updatedHistoryItem: any - vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { - updatedHistoryItem = item - return Promise.resolve([item]) - }) + // The switch updates a store-held item field-only under the + // store lock; capture the updater (CR 2873 thread 4816587015). + const atomicSpy = vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate") // Add task to provider stack await provider.addClineToStack(mockTask as any) @@ -918,7 +918,9 @@ describe("ClineProvider - Sticky Provider Profile", () => { await provider.activateProviderProfile({ name: "new-profile" }) // Verify apiConfigName was included in the updated history item - expect(updatedHistoryItem).toBeDefined() + expect(atomicSpy).toHaveBeenCalledWith(mockTask.taskId, expect.any(Function)) + const [, updater] = atomicSpy.mock.calls[atomicSpy.mock.calls.length - 1] + const updatedHistoryItem = updater(provider.taskHistoryStore.get(mockTask.taskId)!) expect(updatedHistoryItem.apiConfigName).toBe("new-profile") }) }) @@ -980,14 +982,9 @@ describe("ClineProvider - Sticky Provider Profile", () => { await provider.taskHistoryStore.upsert(item as any) } - // Mock updateTaskHistory - vi.spyOn(provider, "updateTaskHistory").mockImplementation((item) => { - const index = taskHistory.findIndex((h) => h.id === item.id) - if (index >= 0) { - taskHistory[index] = { ...taskHistory[index], ...item } - } - return Promise.resolve(taskHistory) - }) + // The store-held item persists field-only under the store lock + // (CR 2873 thread 4816587015), so the assertions below read the + // authoritative store instead of a write-path double. // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ @@ -1008,10 +1005,10 @@ describe("ClineProvider - Sticky Provider Profile", () => { // Verify task 1's profile was updated expect(task1._taskApiConfigName).toBe("profile-c") - expect(taskHistory[0].apiConfigName).toBe("profile-c") + expect(provider.taskHistoryStore.get("task-1")?.apiConfigName).toBe("profile-c") // Verify task 2's profile remains unchanged - expect(taskHistory[1].apiConfigName).toBe("profile-b") + expect(provider.taskHistoryStore.get("task-2")?.apiConfigName).toBe("profile-b") }) }) @@ -1045,8 +1042,10 @@ describe("ClineProvider - Sticky Provider Profile", () => { totalCost: 0, }) - // Mock updateTaskHistory to throw error - vi.spyOn(provider, "updateTaskHistory").mockRejectedValue(new Error("Save failed")) + // A store-held item persists through atomicReadAndUpdate; its + // failure must stay swallowed by the profile-switch error + // handling (CR 2873 thread 4816587015). + vi.spyOn(provider.taskHistoryStore, "atomicReadAndUpdate").mockRejectedValue(new Error("Save failed")) // Mock providerSettingsManager.activateProfile vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({ diff --git a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts index e144b36ce94..ac4f62b7c89 100644 --- a/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.taskHistory.spec.ts @@ -58,7 +58,16 @@ vi.mock("fs", async (importOriginal) => { // its read-merge-write sequence and commits with this no-op lock. vi.mock("../../../utils/fileLock", async (importOriginal) => { const actual = await importOriginal() - return { ...actual, acquireFileLock: vi.fn(async () => async () => {}) } + // withFileLock calls the module-internal acquireFileLock, which the + // export-level mock cannot intercept; mock it directly so recovery + // helpers run without proper-lockfile touching the real filesystem. + return { + ...actual, + acquireFileLock: vi.fn(async () => async () => {}), + withFileLock: vi.fn(async (filePath: string, operation: (absoluteFilePath: string) => Promise) => + operation(filePath), + ), + } }) vi.mock("axios", () => ({ @@ -1394,6 +1403,7 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { const wireFsMocks = async () => { renameGate = undefined + readGate = undefined fsMockRef = await import("fs/promises") const fsMock = fsMockRef vi.mocked(fsMock.mkdir).mockReset().mockResolvedValue(undefined) @@ -1410,6 +1420,10 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { .mockReset() .mockImplementation(async (p) => { const key = toKey(p) + if (readGate && key === BACKUP_PATH) { + // The authority test parks the backup read here. + await readGate.promise + } const content = memFiles.get(key) if (content === undefined) { throw errno("ENOENT", key) @@ -1490,10 +1504,19 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { close: vi.fn().mockResolvedValue(undefined), } as never), ) + storageUtilsRef = await import("../../../utils/storage") + vi.mocked(storageUtilsRef.getStorageBasePath) + .mockReset() + .mockImplementation(async (defaultPath: string) => defaultPath) lockRef = await import("../../../utils/fileLock") vi.mocked(lockRef.acquireFileLock) .mockReset() .mockImplementation(async () => async () => {}) + vi.mocked(lockRef.withFileLock) + .mockReset() + .mockImplementation(async (filePath: string, operation: (absoluteFilePath: string) => Promise) => + operation(filePath), + ) const swj = (swjRef = await import("../../../utils/safeWriteJson")) const realWriter = await vi.importActual("../../../utils/safeWriteJson") @@ -1503,7 +1526,9 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { let fsMockRef: typeof import("fs/promises") let swjRef: typeof import("../../../utils/safeWriteJson") let lockRef: typeof import("../../../utils/fileLock") + let storageUtilsRef: typeof import("../../../utils/storage") let renameGate: { promise: Promise; release: () => void } | undefined + let readGate: { promise: Promise; release: () => void } | undefined const buildProvider = async (options: { globalState: Record @@ -2095,5 +2120,155 @@ describe("ClineProvider legacy taskHistory blob sweep (#1771)", () => { expect(again?.id).toBe("task-a") expect(backupReads).toBe(readsAfterCache + 1) }) + + it("re-resolves the backup root when the storage setting changes", async () => { + const itemA = makeItem("task-a", "A") + const itemB = makeItem("task-b", "B") + let backupReads = 0 + const pRoot = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + // Store init fails, so the provider keeps the legacy + // fallback path. + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + vi.mocked(fsMockRef.readFile).mockImplementation(async (pathArg) => { + if (toKey(pathArg) === BACKUP_PATH) { + backupReads += 1 + } + const key = toKey(pathArg) + const content = memFiles.get(key) + if (content === undefined) { + throw errno("ENOENT", key) + } + return content + }) + }, + }) + + expect(pRoot["taskHistoryStoreInitialized"]).toBe(false) + const cached = await pRoot["getTaskHistoryItem"]("task-a") + expect(cached?.id).toBe("task-a") + + // The user moves the storage root at runtime; a peer window + // writes its backup at the new root and clears the blob. + const movedRoot = `${STORAGE_ROOT}-moved` + vi.mocked(storageUtilsRef.getStorageBasePath).mockImplementation(async (defaultPath: string) => + toKey(defaultPath) === STORAGE_ROOT ? movedRoot : toKey(defaultPath), + ) + memFiles.set(`${movedRoot}/legacy-task-history.backup.json`, JSON.stringify([itemB, itemA], null, "\t")) + + // The next miss must read at the NEW root (CR 2873 thread + // 4816587009), not stay pinned to the first resolution. + const found = await pRoot["getTaskHistoryItem"]("task-b") + expect(found?.id).toBe("task-b") + expect(backupReads).toBeGreaterThan(0) + }) + + it("recovers an interrupted backup replacement before confirming absence", async () => { + const itemA = makeItem("task-a", "A") + // The canonical backup is absent; an interrupted replacement + // left its committed content in a recovery file. + const recoveryFile = `${STORAGE_ROOT}/.legacy-task-history.backup.json.bak_1_unit.tmp` + const pRec = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [recoveryFile]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + }, + }) + + expect(pRec["taskHistoryStoreInitialized"]).toBe(false) + // The committed backup content must be restored and served + // instead of answering "Task not found" (CR 2873 thread + // 4816587011). + const found = await pRec["getTaskHistoryItem"]("task-a") + expect(found?.id).toBe("task-a") + }) + + it("returns no backup item once initialization completes during its read", async () => { + const itemA = makeItem("task-a", "A") + let releaseRead: (() => void) | undefined + const pAuth = await buildProvider({ + globalState: { taskHistory: undefined, taskHistoryMigratedToFiles: true }, + files: { [BACKUP_PATH]: JSON.stringify([itemA], null, "\t") }, + beforeFlush: () => { + vi.mocked(fsMockRef.mkdir).mockReset().mockRejectedValue(new Error("store init failed")) + // Park the backup read; initialization "completes" + // while the lookup is awaiting it. + let release: (() => void) | undefined + readGate = { + promise: new Promise((resolve) => { + release = resolve + }), + release: () => release?.(), + } + releaseRead = () => readGate?.release() + }, + }) + + expect(pAuth["taskHistoryStoreInitialized"]).toBe(false) + const lookup = pAuth["getTaskHistoryItem"]("task-a") + ;(pAuth as unknown as { taskHistoryStoreInitialized: boolean }).taskHistoryStoreInitialized = true + releaseRead!() + const result = await lookup + // The store is authoritative now and does not hold the task, + // so the stale backup item must not be delivered (CR 2873 + // thread 4816587019). + expect(result).toBeUndefined() + }) + + it.each([ + ["mode switch", "mode"], + ["profile switch", "apiConfigName"], + ])("keeps a newer cost when a %s persists field-only", async (_name, field) => { + const itemA = makeItem("task-a", "A") + const pCost = await buildProvider({ + globalState: { taskHistory: [itemA], taskHistoryMigratedToFiles: true }, + dirs: [`${TASKS_DIR}/task-a`], + files: { [`${TASKS_DIR}/task-a/history_item.json`]: JSON.stringify(itemA, null, "\t") }, + }) + + expect(pCost["taskHistoryStoreInitialized"]).toBe(true) + // A token save lands a newer cost after the caller's snapshot + // was taken: the cached item now holds it. + const newer = { ...itemA, totalCost: 9 } + await pCost.updateTaskHistory(newer, { broadcast: false }) + expect(pCost["taskHistoryStore"].get("task-a")?.totalCost).toBe(9) + + // The switch flow still holds the OLDER full-item snapshot: + // stub the lookup so the pre-fix full-item write replays it. + vi.spyOn( + pCost as unknown as { getTaskHistoryItem: (id: string) => Promise }, + "getTaskHistoryItem", + ).mockResolvedValue(itemA) + + const taskDouble = { taskId: "task-a", emit: vi.fn(), setTaskApiConfigName: vi.fn() } as unknown as Task + const provider = pCost as unknown as { + getTaskHistoryItem: (id: string) => Promise + getCurrentTask: () => Task | undefined + } + vi.spyOn(provider, "getCurrentTask").mockReturnValue(taskDouble) + + if (field === "mode") { + await ( + pCost as unknown as { + handleModeSwitchUnlocked: (mode: string, task: Task | null) => Promise + } + ).handleModeSwitchUnlocked("arch", taskDouble) + const stored = pCost["taskHistoryStore"].get("task-a") + expect(stored?.totalCost).toBe(9) + expect(stored?.mode).toBe("arch") + } else { + await ( + pCost as unknown as { + persistStickyProviderProfileToCurrentTask: (name: string) => Promise + } + ).persistStickyProviderProfileToCurrentTask("sticky-profile") + const stored = pCost["taskHistoryStore"].get("task-a") + expect(stored?.totalCost).toBe(9) + expect(stored?.apiConfigName).toBe("sticky-profile") + } + }) }) }) diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index fd227822263..85a61217375 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -901,12 +901,12 @@ }, "core/webview/__tests__/ClineProvider.sticky-mode.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 27 + "count": 26 } }, "core/webview/__tests__/ClineProvider.sticky-profile.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 15 + "count": 14 } }, "core/webview/__tests__/ClineProvider.taskHistory.spec.ts": {