Skip to content

Commit 0d004f7

Browse files
committed
fix(task-history): serialize store mutations with shared lock
1 parent 370e9c6 commit 0d004f7

2 files changed

Lines changed: 58 additions & 22 deletions

File tree

‎src/core/task-persistence/TaskHistoryStore.ts‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import type { HistoryItem } from "@roo-code/types"
77
import { GlobalFileNames } from "../../shared/globalFileNames"
88
import { safeWriteJson } from "../../utils/safeWriteJson"
99
import { getStorageBasePath } from "../../utils/storage"
10+
import { taskHistoryLock } from "./TaskHistoryLock"
1011

1112
/** Valid status values for a task's HistoryItem. */
1213
export type HistoryItemStatus = NonNullable<HistoryItem["status"]>
@@ -184,7 +185,7 @@ export class TaskHistoryStore {
184185
* updates the in-memory Map, and schedules a debounced index write.
185186
*/
186187
async upsert(item: HistoryItem): Promise<HistoryItem[]> {
187-
return this.withLock(() => this.upsertCore(item))
188+
return this.withSharedStorageLock(() => this.upsertCore(item))
188189
}
189190

190191
/**
@@ -237,7 +238,7 @@ export class TaskHistoryStore {
237238
* Delete a single task's history item.
238239
*/
239240
async delete(taskId: string): Promise<void> {
240-
return this.withLock(async () => {
241+
return this.withSharedStorageLock(async () => {
241242
this.cache.delete(taskId)
242243

243244
// Remove per-task file (best-effort)
@@ -261,7 +262,7 @@ export class TaskHistoryStore {
261262
* Delete multiple tasks' history items in a batch.
262263
*/
263264
async deleteMany(taskIds: string[]): Promise<void> {
264-
return this.withLock(() => this.deleteManyCore(taskIds))
265+
return this.withSharedStorageLock(() => this.deleteManyCore(taskIds))
265266
}
266267

267268
private async deleteManyCore(taskIds: string[]): Promise<void> {
@@ -293,8 +294,8 @@ export class TaskHistoryStore {
293294
* - Tasks in cache but missing from disk: remove
294295
*/
295296
async reconcile(): Promise<void> {
296-
// Run through the write lock to prevent interleaving with upsert/delete
297-
return this.withLock(() => this.reconcileCore())
297+
// Run through the shared storage lock and write lock to prevent interleaving with upsert/delete.
298+
return this.withSharedStorageLock(() => this.reconcileCore())
298299
}
299300

300301
private async reconcileCore(): Promise<void> {
@@ -363,7 +364,7 @@ export class TaskHistoryStore {
363364
* A parent awaiting an `active`, `interrupted`, or `delegated` child is left as-is — the child is resumable.
364365
*/
365366
private async reconcileDelegationState(): Promise<void> {
366-
return this.withLock(() => this.reconcileDelegationStateCore())
367+
return this.withSharedStorageLock(() => this.reconcileDelegationStateCore())
367368
}
368369

369370
private async reconcileDelegationStateCore(): Promise<void> {
@@ -464,11 +465,11 @@ export class TaskHistoryStore {
464465
* file if one doesn't already exist. This is idempotent and safe to re-run.
465466
*/
466467
async migrateFromGlobalState(taskHistoryEntries: HistoryItem[]): Promise<void> {
467-
return this.withLock(() => this.migrateFromGlobalStateCore(taskHistoryEntries))
468+
return this.withSharedStorageLock(() => this.migrateFromGlobalStateCore(taskHistoryEntries))
468469
}
469470

470471
async mutateLocked<T>(fn: () => Promise<T>): Promise<T> {
471-
return this.withLock(fn)
472+
return this.withSharedStorageLock(fn)
472473
}
473474

474475
async reconcileLocked(): Promise<void> {
@@ -703,7 +704,7 @@ export class TaskHistoryStore {
703704
* @throws If the task ID is not present in the cache.
704705
*/
705706
public atomicReadAndUpdate(taskId: string, updater: (current: HistoryItem) => HistoryItem): Promise<HistoryItem[]> {
706-
return this.withLock(async () => {
707+
return this.withSharedStorageLock(async () => {
707708
const current = this.cache.get(taskId)
708709
if (!current) {
709710
throw new Error(`[TaskHistoryStore] atomicReadAndUpdate: task ${taskId} not found in cache`)
@@ -734,7 +735,7 @@ export class TaskHistoryStore {
734735
firstUpdater: (current: HistoryItem) => HistoryItem,
735736
secondUpdater: (current: HistoryItem) => HistoryItem,
736737
): Promise<HistoryItem[]> {
737-
return this.withLock(async () => {
738+
return this.withSharedStorageLock(async () => {
738739
const first = this.cache.get(firstId)
739740
if (!first) throw new Error(`[TaskHistoryStore] atomicUpdatePair: ${firstId} not found`)
740741
const second = this.cache.get(secondId)
@@ -791,6 +792,13 @@ export class TaskHistoryStore {
791792

792793
// ────────────────────────────── Private: Write lock ──────────────────────────────
793794

795+
/**
796+
* Acquires the shared task-history storage lock before entering the instance-local queue.
797+
*/
798+
private withSharedStorageLock<T>(fn: () => Promise<T>): Promise<T> {
799+
return taskHistoryLock.withLock(this.globalStoragePath, () => this.withLock(fn))
800+
}
801+
794802
/**
795803
* Serializes all read-modify-write operations within a single extension
796804
* host process to prevent concurrent interleaving.

‎src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts‎

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,16 @@ import * as os from "os"
66

77
import type { HistoryItem } from "@roo-code/types"
88

9+
const { taskHistoryLockWithLockMock } = vi.hoisted(() => ({
10+
taskHistoryLockWithLockMock: vi.fn(async (_globalStoragePath: string, fn: () => Promise<unknown>) => fn()),
11+
}))
12+
13+
vi.mock("../TaskHistoryLock", () => ({
14+
taskHistoryLock: {
15+
withLock: taskHistoryLockWithLockMock,
16+
},
17+
}))
18+
919
import { TaskHistoryStore, assertValidTransition } from "../TaskHistoryStore"
1020
import { GlobalFileNames } from "../../../shared/globalFileNames"
1121

@@ -42,6 +52,10 @@ describe("TaskHistoryStore", () => {
4252
let store: TaskHistoryStore
4353

4454
beforeEach(async () => {
55+
taskHistoryLockWithLockMock.mockClear()
56+
taskHistoryLockWithLockMock.mockImplementation(async (_globalStoragePath: string, fn: () => Promise<unknown>) =>
57+
fn(),
58+
)
4559
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "task-history-test-"))
4660
store = new TaskHistoryStore(tmpDir)
4761
})
@@ -231,6 +245,17 @@ describe("TaskHistoryStore", () => {
231245
expect(store.getAll()).toHaveLength(1)
232246
expect(store.get("batch-2")).toBeDefined()
233247
})
248+
249+
it("acquires the shared storage lock before entering the instance queue", async () => {
250+
await store.initialize()
251+
await store.upsert(makeHistoryItem({ id: "shared-lock-delete" }))
252+
taskHistoryLockWithLockMock.mockClear()
253+
254+
await store.deleteMany(["shared-lock-delete"])
255+
256+
expect(taskHistoryLockWithLockMock).toHaveBeenCalledTimes(1)
257+
expect(taskHistoryLockWithLockMock).toHaveBeenCalledWith(tmpDir, expect.any(Function))
258+
})
234259
})
235260

236261
describe("locked mutation helpers", () => {
@@ -247,21 +272,24 @@ describe("TaskHistoryStore", () => {
247272
JSON.stringify(makeHistoryItem({ id: "locked-orphan" })),
248273
)
249274

250-
const result = await Promise.race([
251-
store
252-
.mutateLocked(async () => {
253-
await store.reconcileLocked()
254-
expect(store.get("locked-orphan")).toBeDefined()
255-
await store.deleteManyLocked(["locked-delete", "locked-orphan"])
256-
})
257-
.then(() => "completed"),
258-
new Promise<string>((resolve) => setTimeout(() => resolve("deadlocked"), 100)),
259-
])
260-
261-
expect(result).toBe("completed")
275+
await store.mutateLocked(async () => {
276+
await store.reconcileLocked()
277+
expect(store.get("locked-orphan")).toBeDefined()
278+
await store.deleteManyLocked(["locked-delete", "locked-orphan"])
279+
})
280+
262281
expect(store.get("locked-delete")).toBeUndefined()
263282
expect(store.get("locked-orphan")).toBeUndefined()
264283
})
284+
it("acquires the shared storage lock before entering the instance queue", async () => {
285+
await store.initialize()
286+
taskHistoryLockWithLockMock.mockClear()
287+
288+
await store.mutateLocked(async () => undefined)
289+
290+
expect(taskHistoryLockWithLockMock).toHaveBeenCalledTimes(1)
291+
expect(taskHistoryLockWithLockMock).toHaveBeenCalledWith(tmpDir, expect.any(Function))
292+
})
265293
})
266294

267295
describe("reconcile()", () => {

0 commit comments

Comments
 (0)