Skip to content

Commit baed078

Browse files
author
Zoo (VP)
committed
test(task-persistence): cover mutation edge cases for live child liveness guard
1 parent 8363a17 commit baed078

2 files changed

Lines changed: 277 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,7 @@ export class TaskHistoryStore {
477477
// recently is owned by another live window, not a crash orphan.
478478
const mtimeMs = await this.getChildFileMtimeMs(child.id)
479479
const isLiveElsewhere =
480+
// Stryker disable next-line ConditionalExpression: replacing `mtimeMs !== undefined` with `true` is mutation-equivalent; with a defined mtimeMs `true && X === X`, and with undefined the right operand is `NaN < threshold === false`, identical to the short-circuit result.
480481
mtimeMs !== undefined &&
481482
Date.now() - mtimeMs < TaskHistoryStore.LIVE_CHILD_MTIME_THRESHOLD_MS
482483
if (isLiveElsewhere) {

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

Lines changed: 276 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ vi.mock("../../../utils/safeWriteJson", () => ({ safeWriteJson: safeWriteJsonMoc
2424

2525
safeWriteJsonMock.mockImplementation(writeJson)
2626

27+
// Private static member read for the threshold-constant test. There is no
28+
// typed accessor; this casts through `unknown` (not `as any`) following the
29+
// same private-member access pattern used by
30+
// "removes the repair-intent file after successful replay" below.
31+
const LIVE_CHILD_MTIME_THRESHOLD_MS = (TaskHistoryStore as unknown as {
32+
LIVE_CHILD_MTIME_THRESHOLD_MS: number
33+
}).LIVE_CHILD_MTIME_THRESHOLD_MS
34+
2735
function makeItem(overrides: Partial<HistoryItem> = {}): HistoryItem {
2836
return {
2937
id: `task-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`,
@@ -172,11 +180,49 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
172180
await fs.utimes(filePath, stale, stale)
173181
}
174182

183+
/**
184+
* Deterministic wall clock for liveness-boundary tests. `fs.utimes` accepts
185+
* ms-precision Date values and the store's `Date.now()` is spied to return
186+
* this same instant, so `Date.now() - mtimeMs` is exact regardless of how
187+
* long the test body takes to run.
188+
*/
189+
const FIXED_NOW = 1_756_886_400_000 // 2025-09-03T08:00:00.000Z
190+
191+
async function setChildMtimeAge(taskId: string, ageMs: number): Promise<void> {
192+
const filePath = path.join(tmpDir, "tasks", taskId, GlobalFileNames.historyItem)
193+
const stamp = new Date(FIXED_NOW - ageMs)
194+
await fs.utimes(filePath, stamp, stamp)
195+
// Guard the assumption that the filesystem round-trips millisecond
196+
// precision, so a boundary test failure is diagnosable rather than a
197+
// silent live/stale flip.
198+
const written = await fs.stat(filePath)
199+
expect(Math.round(written.mtimeMs)).toBe(FIXED_NOW - ageMs)
200+
}
201+
175202
beforeEach(async () => {
176203
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "reconcile-test-"))
177204
store = registerStore(new TaskHistoryStore(tmpDir))
178205
})
179206

207+
it("getChildFileMtimeMs returns the file mtime for an existing child and undefined for a missing one", async () => {
208+
// Direct coverage of the private mtime probe used by the cross-instance
209+
// liveness guard (TaskHistoryStore.ts getChildFileMtimeMs): the happy
210+
// path returns stat.mtimeMs and the catch path returns undefined.
211+
// Bracket/typed access follows the same private-member pattern used by
212+
// "removes the repair-intent file after successful replay" below.
213+
const internals = store as unknown as {
214+
getChildFileMtimeMs: (childId: string) => Promise<number | undefined>
215+
}
216+
217+
expect(await internals.getChildFileMtimeMs("missing-mtime-child")).toBeUndefined()
218+
219+
const child = makeItem({ id: "present-mtime-child", status: "active" })
220+
await seedItems([child])
221+
const mtimeMs = await internals.getChildFileMtimeMs("present-mtime-child")
222+
expect(typeof mtimeMs).toBe("number")
223+
expect(mtimeMs).toBeGreaterThan(0)
224+
})
225+
180226
afterEach(async () => {
181227
safeWriteJsonMock.mockImplementation(writeJson)
182228
for (const disposable of disposables) disposable.dispose()
@@ -287,7 +333,16 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
287333
expect(persistedParent.delegatedToId).toBeUndefined()
288334
})
289335

336+
it("pins LIVE_CHILD_MTIME_THRESHOLD_MS to exactly 5 minutes in milliseconds", () => {
337+
// Kills the TaskHistoryStore.ts line-105 ArithmeticOperator mutants
338+
// directly: every mutated expression (5 * 60 / 1000 → 0.3,
339+
// 5 + 60 * 1000 → 60005, 5 * 60 % 1000 → 300, ...) changes the
340+
// constant's own value, so this assertion fails under all of them.
341+
expect(LIVE_CHILD_MTIME_THRESHOLD_MS).toBe(5 * 60 * 1000)
342+
})
343+
290344
it("skips repair for active child with recent mtime (live in another window)", async () => {
345+
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {})
291346
const child = makeItem({
292347
id: "child-live",
293348
status: "active",
@@ -326,9 +381,20 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
326381
) as HistoryItem
327382
expect(persistedParent.status).toBe("delegated")
328383
expect(persistedParent.awaitingChildId).toBe("child-live")
384+
385+
// Kills the line-484/485 StringLiteral mutants: the two concatenated
386+
// fragments of the skip message are asserted independently, so either
387+
// fragment mutated to '' breaks its matching stringContaining check.
388+
expect(logSpy).toHaveBeenCalledWith(
389+
expect.stringContaining("Skipping repair for live child child-live"),
390+
)
391+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("owned by another window"))
392+
393+
logSpy.mockRestore()
329394
})
330395

331396
it("repairs active child with stale mtime (crash orphan)", async () => {
397+
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {})
332398
const child = makeItem({
333399
id: "child-stale",
334400
status: "active",
@@ -366,6 +432,216 @@ describe("TaskHistoryStore reconcileDelegationState", () => {
366432
expect(repairedParent).toMatchObject({ id: "parent-stale", status: "active" })
367433
expect(repairedParent?.awaitingChildId).toBeUndefined()
368434
expect(repairedParent?.delegatedToId).toBeUndefined()
435+
436+
// Kills line-495 StringLiteral mutants on the orphan-repair warning.
437+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Reconciled orphaned active child"))
438+
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("child-stale"))
439+
440+
warnSpy.mockRestore()
441+
})
442+
443+
it("repairs when child file age is exactly the liveness threshold (strict '<' boundary)", async () => {
444+
// Kills the TaskHistoryStore.ts line-481 EqualityOperator mutant `<=`:
445+
// under `<=`, age === threshold (300000 ms) would count as live and the
446+
// repair would be skipped. With the real strict `<`, age === threshold
447+
// is NOT live, so the crash orphan must be repaired.
448+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(FIXED_NOW)
449+
try {
450+
const child = makeItem({
451+
id: "child-boundary-equal",
452+
status: "active",
453+
parentTaskId: "parent-boundary-equal",
454+
rootTaskId: "parent-boundary-equal",
455+
})
456+
const parent = makeItem({
457+
id: "parent-boundary-equal",
458+
status: "delegated",
459+
awaitingChildId: "child-boundary-equal",
460+
delegatedToId: "child-boundary-equal",
461+
})
462+
await seedItems([parent, child])
463+
await setChildMtimeAge("child-boundary-equal", 300_000)
464+
465+
await store.initialize()
466+
467+
expect(store.get("child-boundary-equal")?.status).toBe("interrupted")
468+
expect(store.get("parent-boundary-equal")?.status).toBe("active")
469+
expect(store.get("parent-boundary-equal")?.awaitingChildId).toBeUndefined()
470+
expect(store.get("parent-boundary-equal")?.delegatedToId).toBeUndefined()
471+
} finally {
472+
nowSpy.mockRestore()
473+
}
474+
})
475+
476+
it("skips repair when child file age is one millisecond below the liveness threshold", async () => {
477+
// Kills:
478+
// - line-481 EqualityOperator mutants `>` / `>=`: with either, age
479+
// 299999 < 300000 would evaluate stale and the repair would run.
480+
// - line-105 ArithmeticOperator mutants behaviorally: every mutated
481+
// threshold (0.3, 83.3, 60005, 1300, -700, 300, 5000, ...) is far
482+
// below 299999, so the child would no longer be considered live.
483+
// - line-484/485 StringLiteral mutants: both message fragments are
484+
// asserted independently.
485+
// - line-485 `/ 1000` ArithmeticOperator mutants: Math.round(299999 /
486+
// 1000) renders "300", while `* 1000`, `+ 1000`, `- 1000` and
487+
// `% 1000` all render a different second count.
488+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(FIXED_NOW)
489+
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {})
490+
try {
491+
const child = makeItem({
492+
id: "child-boundary-live",
493+
status: "active",
494+
parentTaskId: "parent-boundary-live",
495+
rootTaskId: "parent-boundary-live",
496+
})
497+
const parent = makeItem({
498+
id: "parent-boundary-live",
499+
status: "delegated",
500+
awaitingChildId: "child-boundary-live",
501+
delegatedToId: "child-boundary-live",
502+
})
503+
await seedItems([parent, child])
504+
await setChildMtimeAge("child-boundary-live", 299_999)
505+
506+
await store.initialize()
507+
508+
expect(store.get("child-boundary-live")?.status).toBe("active")
509+
expect(store.get("parent-boundary-live")?.status).toBe("delegated")
510+
expect(store.get("parent-boundary-live")?.awaitingChildId).toBe("child-boundary-live")
511+
expect(store.get("parent-boundary-live")?.delegatedToId).toBe("child-boundary-live")
512+
expect(logSpy).toHaveBeenCalledWith(
513+
expect.stringContaining("[TaskHistoryStore] Skipping repair for live child child-boundary-live"),
514+
)
515+
// Split around the non-ASCII em dash so the assertion depends only on
516+
// the seconds count rendered from (Date.now() - mtimeMs) / 1000:
517+
// Math.round(299.999) = 300, while `* 1000`, `+ 1000`, `- 1000` and
518+
// `% 1000` ArithmeticOperator mutants all render a different string.
519+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("(mtime 300s ago)"))
520+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("owned by another window"))
521+
} finally {
522+
logSpy.mockRestore()
523+
nowSpy.mockRestore()
524+
}
525+
})
526+
527+
it("repairs a child whose file mtime is at the unix epoch (kills '-' -> '%' mutant at the liveness subtraction)", async () => {
528+
// Files stamped 1970-01-01 (epoch-zero artifacts from misconfigured clocks,
529+
// zip extraction, or container images) must be treated as stale orphans.
530+
// Kills the ArithmeticOperator mutant `Date.now() - mtimeMs` ->
531+
// `Date.now() % mtimeMs`: with mtimeMs = 1000, the real subtraction is
532+
// ~56 years (stale -> repair), while FIXED_NOW % 1000 === 0 would be read
533+
// as live and skip the repair. The same mutant inside the skip-path log is
534+
// never reached under the mutant because the guard already diverges.
535+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(FIXED_NOW)
536+
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {})
537+
try {
538+
const child = makeItem({
539+
id: "child-epoch-mtime",
540+
status: "active",
541+
parentTaskId: "parent-epoch-mtime",
542+
rootTaskId: "parent-epoch-mtime",
543+
})
544+
const parent = makeItem({
545+
id: "parent-epoch-mtime",
546+
status: "delegated",
547+
awaitingChildId: "child-epoch-mtime",
548+
delegatedToId: "child-epoch-mtime",
549+
})
550+
await seedItems([parent, child])
551+
const childFilePath = path.join(tmpDir, "tasks", "child-epoch-mtime", GlobalFileNames.historyItem)
552+
const epochStamp = new Date(1_000) // 1970-01-01T00:00:01.000Z
553+
await fs.utimes(childFilePath, epochStamp, epochStamp)
554+
const written = await fs.stat(childFilePath)
555+
expect(Math.round(written.mtimeMs)).toBe(1_000)
556+
557+
await store.initialize()
558+
559+
expect(store.get("child-epoch-mtime")?.status).toBe("interrupted")
560+
expect(store.get("parent-epoch-mtime")?.status).toBe("active")
561+
expect(store.get("parent-epoch-mtime")?.awaitingChildId).toBeUndefined()
562+
expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("Skipping repair for live child"))
563+
} finally {
564+
logSpy.mockRestore()
565+
nowSpy.mockRestore()
566+
}
567+
})
568+
569+
it("treats a future child-file mtime as live and renders the negative age (kills '-' -> '%' in the skip log)", async () => {
570+
// Clock skew can put a child file's mtime ahead of Date.now(). The skip
571+
// path renders (Date.now() - mtimeMs) / 1000 = -100s. The
572+
// ArithmeticOperator mutant `Date.now() % mtimeMs` would instead render
573+
// the whole epoch magnitude (1756886400s), so the seconds-count
574+
// assertion below kills it. The live-side status assertions also kill
575+
// the same mutant on the guard subtraction in TaskHistoryStore.ts.
576+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(FIXED_NOW)
577+
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {})
578+
try {
579+
const child = makeItem({
580+
id: "child-future-mtime",
581+
status: "active",
582+
parentTaskId: "parent-future-mtime",
583+
rootTaskId: "parent-future-mtime",
584+
})
585+
const parent = makeItem({
586+
id: "parent-future-mtime",
587+
status: "delegated",
588+
awaitingChildId: "child-future-mtime",
589+
delegatedToId: "child-future-mtime",
590+
})
591+
await seedItems([parent, child])
592+
const childFilePath = path.join(tmpDir, "tasks", "child-future-mtime", GlobalFileNames.historyItem)
593+
const futureStamp = new Date(FIXED_NOW + 100_000)
594+
await fs.utimes(childFilePath, futureStamp, futureStamp)
595+
const written = await fs.stat(childFilePath)
596+
expect(Math.round(written.mtimeMs)).toBe(FIXED_NOW + 100_000)
597+
598+
await store.initialize()
599+
600+
expect(store.get("child-future-mtime")?.status).toBe("active")
601+
expect(store.get("parent-future-mtime")?.status).toBe("delegated")
602+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Skipping repair for live child"))
603+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("(mtime -100s ago)"))
604+
} finally {
605+
logSpy.mockRestore()
606+
nowSpy.mockRestore()
607+
}
608+
})
609+
610+
it("skips repair and renders 299s for a child file age of threshold-501ms (kills Math.ceil mutant)", async () => {
611+
// Companion to the 299999 ms test: Math.round(299.499) = 299 while
612+
// Math.ceil(299.499) = 300 and Math.floor(299.499) = 299. The 299999 ms
613+
// test above covers the floor mutant (round = ceil = 300 there), and
614+
// this one covers the ceil mutant. It also re-asserts the live side of
615+
// the strict `<` boundary and the line-105 threshold mutants.
616+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(FIXED_NOW)
617+
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {})
618+
try {
619+
const child = makeItem({
620+
id: "child-boundary-ceil",
621+
status: "active",
622+
parentTaskId: "parent-boundary-ceil",
623+
rootTaskId: "parent-boundary-ceil",
624+
})
625+
const parent = makeItem({
626+
id: "parent-boundary-ceil",
627+
status: "delegated",
628+
awaitingChildId: "child-boundary-ceil",
629+
delegatedToId: "child-boundary-ceil",
630+
})
631+
await seedItems([parent, child])
632+
await setChildMtimeAge("child-boundary-ceil", 299_499)
633+
634+
await store.initialize()
635+
636+
expect(store.get("child-boundary-ceil")?.status).toBe("active")
637+
expect(store.get("parent-boundary-ceil")?.status).toBe("delegated")
638+
expect(store.get("parent-boundary-ceil")?.awaitingChildId).toBe("child-boundary-ceil")
639+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Skipping repair for live child"))
640+
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("(mtime 299s ago)"))
641+
} finally {
642+
logSpy.mockRestore()
643+
nowSpy.mockRestore()
644+
}
369645
})
370646

371647
it("repairs a delegated child with an omitted status as implicit active", async () => {

0 commit comments

Comments
 (0)