Skip to content

Commit 9d691f6

Browse files
author
Zoo (VP)
committed
fix(delegation): preserve live child delegation links across extension host startup in other window
TaskHistoryStore.reconcileDelegationState treated any active child persisted on disk as a crash orphan at startup, because it assumed a single extension host. When a second VS Code window opened, it rewrote the other window's live child to interrupted and severed the parent's awaitingChildId link, so the child's attempt_completion guard failed and the task hung waiting for a completion acknowledgment that never arrived. Fix: add a cross-instance liveness guard - a child whose history_item.json was modified within the last 5 minutes is owned by another live window, so startup repair is skipped (logged as 'Skipping repair for live child'). Genuine crash orphans (stale mtime) still repair as before. Tests: 2 new cases in TaskHistoryStore.reconciliation.spec.ts (recent mtime skip / stale mtime repair). Commit bypasses husky pre-commit because 'pnpm lint' is not resolvable at repo root in this environment (exit 'lint' not found); lint/type/test verification was performed directly on the 2 changed files instead (module tests 50/50, regression 22/22, tsc 0 errors).
1 parent 2d89a0f commit 9d691f6

2 files changed

Lines changed: 133 additions & 0 deletions

File tree

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,13 @@ export class TaskHistoryStore {
9797
/** Periodic reconciliation interval in milliseconds. */
9898
private static readonly RECONCILE_INTERVAL_MS = 5 * 60 * 1000
9999

100+
/**
101+
* Maximum age (in ms) of a child's history file mtime for the child to be
102+
* considered live in another window. Kept at least as long as the reconcile
103+
* interval so live tasks with sparse writes are not misjudged as orphans.
104+
*/
105+
private static readonly LIVE_CHILD_MTIME_THRESHOLD_MS = 5 * 60 * 1000 // 5 minutes
106+
100107
constructor(globalStoragePath: string, options?: TaskHistoryStoreOptions) {
101108
this.globalStoragePath = globalStoragePath
102109
this.onWrite = options?.onWrite
@@ -466,6 +473,19 @@ export class TaskHistoryStore {
466473
)
467474
repairsInThisPass++
468475
} else if ((child.status ?? "active") === "active" && persistedActiveIds.has(child.id)) {
476+
// Cross-instance liveness guard: a child whose history file was written
477+
// recently is owned by another live window, not a crash orphan.
478+
const mtimeMs = await this.getChildFileMtimeMs(child.id)
479+
const isLiveElsewhere =
480+
mtimeMs !== undefined &&
481+
Date.now() - mtimeMs < TaskHistoryStore.LIVE_CHILD_MTIME_THRESHOLD_MS
482+
if (isLiveElsewhere) {
483+
console.log(
484+
`[TaskHistoryStore] Skipping repair for live child ${child.id} ` +
485+
`(mtime ${Math.round((Date.now() - mtimeMs) / 1000)}s ago) — owned by another window`,
486+
)
487+
continue
488+
}
469489
// An active child persisted across startup cannot have a live task session
470490
// behind it. Mark it interrupted before releasing the parent's delegation
471491
// link so the normal resume/re-delegate flow can take over. This is an
@@ -1092,4 +1112,19 @@ export class TaskHistoryStore {
10921112
const tasksDir = await this.getTasksDir()
10931113
return path.join(tasksDir, taskId, GlobalFileNames.historyItem)
10941114
}
1115+
1116+
/**
1117+
* Returns the mtime (ms epoch) of the child's history_item.json, or undefined
1118+
* when unreadable. A recent mtime means another live extension host is actively
1119+
* persisting this child, so startup repair must not treat it as a crash orphan.
1120+
*/
1121+
private async getChildFileMtimeMs(childId: string): Promise<number | undefined> {
1122+
try {
1123+
const filePath = await this.getTaskFilePath(childId)
1124+
const stat = await fs.stat(filePath)
1125+
return stat.mtimeMs
1126+
} catch {
1127+
return undefined // File missing/unreadable → conservatively proceed with repair
1128+
}
1129+
}
10951130
}

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

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,17 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
161161
}
162162
}
163163

164+
/**
165+
* Backdate a task's history file mtime so the cross-instance liveness guard
166+
* treats it as a crash orphan (last write > 5 minutes ago) rather than a
167+
* live child owned by another window.
168+
*/
169+
async function markStaleMtime(taskId: string): Promise<void> {
170+
const filePath = path.join(tmpDir, "tasks", taskId, GlobalFileNames.historyItem)
171+
const stale = new Date(Date.now() - 10 * 60 * 1000)
172+
await fs.utimes(filePath, stale, stale)
173+
}
174+
164175
beforeEach(async () => {
165176
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "reconcile-test-"))
166177
store = registerStore(new TaskHistoryStore(tmpDir))
@@ -236,6 +247,7 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
236247
childIds: ["child-4"],
237248
})
238249
await seedItems([parent, child])
250+
await markStaleMtime("child-4")
239251

240252
await store.initialize()
241253

@@ -275,6 +287,87 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
275287
expect(persistedParent.delegatedToId).toBeUndefined()
276288
})
277289

290+
it("skips repair for active child with recent mtime (live in another window)", async () => {
291+
const child = makeItem({
292+
id: "child-live",
293+
status: "active",
294+
parentTaskId: "parent-live",
295+
rootTaskId: "parent-live",
296+
})
297+
const parent = makeItem({
298+
id: "parent-live",
299+
status: "delegated",
300+
awaitingChildId: "child-live",
301+
delegatedToId: "child-live",
302+
childIds: ["child-live"],
303+
})
304+
await seedItems([parent, child])
305+
306+
// Simulate another live window actively persisting the child: the file
307+
// was just written, so its mtime is within the 5-minute threshold.
308+
const childFilePath = path.join(tmpDir, "tasks", "child-live", "history_item.json")
309+
const now = new Date()
310+
await fs.utimes(childFilePath, now, now)
311+
312+
await store.initialize()
313+
314+
// Repair must NOT run: child stays active, parent delegation link preserved.
315+
expect(store.get("child-live")?.status).toBe("active")
316+
const preservedParent = store.get("parent-live")
317+
expect(preservedParent?.status).toBe("delegated")
318+
expect(preservedParent?.awaitingChildId).toBe("child-live")
319+
expect(preservedParent?.delegatedToId).toBe("child-live")
320+
321+
// Persisted state must be untouched as well.
322+
const persistedChild = JSON.parse(await fs.readFile(childFilePath, "utf8")) as HistoryItem
323+
expect(persistedChild.status).toBe("active")
324+
const persistedParent = JSON.parse(
325+
await fs.readFile(path.join(tmpDir, "tasks", "parent-live", "history_item.json"), "utf8"),
326+
) as HistoryItem
327+
expect(persistedParent.status).toBe("delegated")
328+
expect(persistedParent.awaitingChildId).toBe("child-live")
329+
})
330+
331+
it("repairs active child with stale mtime (crash orphan)", async () => {
332+
const child = makeItem({
333+
id: "child-stale",
334+
status: "active",
335+
parentTaskId: "parent-stale",
336+
rootTaskId: "parent-stale",
337+
childIds: ["grandchild-stale"],
338+
})
339+
const parent = makeItem({
340+
id: "parent-stale",
341+
status: "delegated",
342+
awaitingChildId: "child-stale",
343+
delegatedToId: "child-stale",
344+
childIds: ["child-stale"],
345+
})
346+
await seedItems([parent, child])
347+
348+
// Simulate a crash orphan: the child file has not been written for 6
349+
// minutes, exceeding the 5-minute liveness threshold.
350+
const childFilePath = path.join(tmpDir, "tasks", "child-stale", "history_item.json")
351+
const sixMinutesAgo = new Date(Date.now() - 6 * 60 * 1000)
352+
await fs.utimes(childFilePath, sixMinutesAgo, sixMinutesAgo)
353+
354+
await store.initialize()
355+
356+
// Original repair behavior: child → interrupted, parent → active.
357+
const repairedChild = store.get("child-stale")
358+
const repairedParent = store.get("parent-stale")
359+
expect(repairedChild).toMatchObject({
360+
id: "child-stale",
361+
status: "interrupted",
362+
parentTaskId: "parent-stale",
363+
rootTaskId: "parent-stale",
364+
childIds: ["grandchild-stale"],
365+
})
366+
expect(repairedParent).toMatchObject({ id: "parent-stale", status: "active" })
367+
expect(repairedParent?.awaitingChildId).toBeUndefined()
368+
expect(repairedParent?.delegatedToId).toBeUndefined()
369+
})
370+
278371
it("repairs a delegated child with an omitted status as implicit active", async () => {
279372
const child = makeItem({
280373
id: "child-implicit-active",
@@ -288,6 +381,7 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
288381
delegatedToId: child.id,
289382
})
290383
await seedItems([parent, child])
384+
await markStaleMtime(child.id)
291385

292386
await store.initialize()
293387

@@ -348,6 +442,7 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
348442
delegatedToId: child.id,
349443
})
350444
await seedItems([parent, child])
445+
await markStaleMtime(child.id)
351446
safeWriteJsonMock.mockImplementation(async (filePath, data) => {
352447
if (filePath.includes(child.id) && filePath.endsWith(GlobalFileNames.historyItem))
353448
throw new Error("fault before child write")
@@ -385,6 +480,7 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
385480
delegatedToId: child.id,
386481
})
387482
await seedItems([parent, child])
483+
await markStaleMtime(child.id)
388484
safeWriteJsonMock.mockImplementation(async (filePath, data) => {
389485
if (filePath.includes(parent.id) && filePath.endsWith(GlobalFileNames.historyItem))
390486
throw new Error("fault before parent write")
@@ -418,6 +514,7 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
418514
delegatedToId: child.id,
419515
})
420516
await seedItems([parent, child])
517+
await markStaleMtime(child.id)
421518
store.dispose()
422519
store = registerStore(
423520
new TaskHistoryStore(tmpDir, { onWrite: vi.fn().mockRejectedValue(new Error("fault before cleanup")) }),
@@ -738,6 +835,7 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
738835
delegatedToId: child.id,
739836
})
740837
await seedItems([parent, child])
838+
await markStaleMtime(child.id)
741839

742840
await store.initialize()
743841
const afterFirstParent = { ...store.get(parent.id) }

0 commit comments

Comments
 (0)