From 1d0048500a27a2fc59022bbde8bae3216e64e365 Mon Sep 17 00:00:00 2001 From: Ankit Patel Date: Mon, 23 Nov 2026 19:11:39 +0530 Subject: [PATCH 1/4] refactor(cli): lift the run heartbeat out of its timer so a test can drive one beat --- packages/cli/src/taskScheduler.ts | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/cli/src/taskScheduler.ts b/packages/cli/src/taskScheduler.ts index bcadff0721..d24addeb9c 100644 --- a/packages/cli/src/taskScheduler.ts +++ b/packages/cli/src/taskScheduler.ts @@ -591,15 +591,7 @@ export class TaskScheduler { } private track(run: TrackedRun): void { - const heartbeatTimer = setInterval(async () => { - const renewed = await this.syncService.renewTaskLease(run.taskId, this.daemonId); - if (!renewed) { - this.log(`Lease renewal failed for task ${run.taskId}, stopping monitor`); - this.cleanupTask(run.taskId); - } - - await this.checkTaskCompletion(run.taskId); - }, HEARTBEAT_INTERVAL_MS); + const heartbeatTimer = setInterval(() => this.heartbeat(run.taskId), HEARTBEAT_INTERVAL_MS); this.running.set(run.taskId, { ...run, heartbeatTimer }); // Link the run's conversation to the task as soon as it syncs (bounded @@ -732,6 +724,16 @@ export class TaskScheduler { }, delaysMs[attempt]); } + private async heartbeat(taskId: string): Promise { + const renewed = await this.syncService.renewTaskLease(taskId, this.daemonId); + if (!renewed) { + this.log(`Lease renewal failed for task ${taskId}, stopping monitor`); + this.cleanupTask(taskId); + } + + await this.checkTaskCompletion(taskId); + } + private async checkTaskCompletion(taskId: string): Promise { const entry = this.running.get(taskId); if (!entry) return; From 3fa63faf31ec045e4a8b7f07c119e5da021cc584 Mon Sep 17 00:00:00 2001 From: Ankit Patel Date: Mon, 23 Nov 2026 19:16:50 +0530 Subject: [PATCH 2/4] fix(cli): a lease renewal the backend never answered no longer stops the run's monitor renewTaskLease turned every exception into false, and the heartbeat read false as "the lease is gone": it cleared the run's timer for good. After a laptop wake the first calls time out, so one failed beat left a live run with no renewals. The 5 minute lease lapsed and reclaimStaleTasks fired the trigger a second time while the first run was still working. renewTaskLease now answers null when it got no answer. Only false, the backend's own "you no longer hold it", stops the monitor; null logs and tries again on the next beat. --- packages/cli/src/syncService.timeout.test.ts | 19 +++++++++++ packages/cli/src/syncService.ts | 9 +++-- packages/cli/src/taskScheduler.test.ts | 36 ++++++++++++++++++++ packages/cli/src/taskScheduler.ts | 9 +++-- 4 files changed, 68 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/syncService.timeout.test.ts b/packages/cli/src/syncService.timeout.test.ts index d0e53e0108..6b60629f6e 100644 --- a/packages/cli/src/syncService.timeout.test.ts +++ b/packages/cli/src/syncService.timeout.test.ts @@ -432,3 +432,22 @@ describe("SyncService mutation queue bypass (skipQueue)", () => { expect(direct[0]).toContain("skipQueue: true"); }); }); + +describe("SyncService.renewTaskLease", () => { + const serviceWith = (mutate: () => Promise) => { + const svc = new SyncService({ convexUrl: "http://localhost:0", userId: "u", authToken: "t" }) as any; + svc.apiToken = "token"; + svc.mutate = mutate; + return svc as SyncService; + }; + + it("answers null, not false, when the backend cannot be reached", async () => { + const svc = serviceWith(async () => { throw new Error("The operation timed out."); }); + expect(await svc.renewTaskLease("t1", "daemon")).toBeNull(); + }); + + it("passes the backend's answer through", async () => { + expect(await serviceWith(async () => true).renewTaskLease("t1", "daemon")).toBe(true); + expect(await serviceWith(async () => false).renewTaskLease("t1", "daemon")).toBe(false); + }); +}); diff --git a/packages/cli/src/syncService.ts b/packages/cli/src/syncService.ts index 30c64579dc..688c5f1300 100644 --- a/packages/cli/src/syncService.ts +++ b/packages/cli/src/syncService.ts @@ -2725,8 +2725,11 @@ export class SyncService { } } - async renewTaskLease(taskId: string, daemonId: string): Promise { - if (!this.apiToken) return false; + /** true: renewed. false: the backend answered that this daemon no longer holds + * the lease. null: no answer (offline, timed out, signed out), which says + * nothing about the lease, so the caller keeps its monitor and tries again. */ + async renewTaskLease(taskId: string, daemonId: string): Promise { + if (!this.apiToken) return null; try { const result = await this.mutate( "agentTasks:renewLease" as any, @@ -2734,7 +2737,7 @@ export class SyncService { ); return result as boolean; } catch { - return false; + return null; } } diff --git a/packages/cli/src/taskScheduler.test.ts b/packages/cli/src/taskScheduler.test.ts index b23b7ff70b..e7fd00b54e 100644 --- a/packages/cli/src/taskScheduler.test.ts +++ b/packages/cli/src/taskScheduler.test.ts @@ -789,3 +789,39 @@ describe("runs already going never hold due triggers (ct-92447)", () => { expect(lines.some((l) => l.includes("Poll error") && l.includes("timed out"))).toBe(true); }); }); + +describe("a run's lease renewal", () => { + const trackOne = (scheduler: any) => { + scheduler.track({ taskId: "t1", tmuxSession: "ct-claude-renew", startedAt: Date.now(), maxRuntimeMs: 600_000 }); + // The tmux probe is not under test: a beat here is only about the renewal. + scheduler.checkTaskCompletion = async () => {}; + }; + + it("keeps watching the run when the backend cannot be reached, and renews on the next beat", async () => { + const { scheduler } = makeScheduler([]); + const answers: Array = [null, true]; + scheduler.syncService.renewTaskLease = async () => answers.shift(); + trackOne(scheduler); + try { + await scheduler.heartbeat("t1"); + expect(scheduler.running.has("t1")).toBe(true); + await scheduler.heartbeat("t1"); + expect(answers).toEqual([]); + expect(scheduler.running.has("t1")).toBe(true); + } finally { + scheduler.stop(); + } + }); + + it("stops watching the run when the backend answers that the lease is no longer held", async () => { + const { scheduler } = makeScheduler([]); + scheduler.syncService.renewTaskLease = async () => false; + trackOne(scheduler); + try { + await scheduler.heartbeat("t1"); + expect(scheduler.running.has("t1")).toBe(false); + } finally { + scheduler.stop(); + } + }); +}); diff --git a/packages/cli/src/taskScheduler.ts b/packages/cli/src/taskScheduler.ts index d24addeb9c..e299a63310 100644 --- a/packages/cli/src/taskScheduler.ts +++ b/packages/cli/src/taskScheduler.ts @@ -726,9 +726,14 @@ export class TaskScheduler { private async heartbeat(taskId: string): Promise { const renewed = await this.syncService.renewTaskLease(taskId, this.daemonId); - if (!renewed) { - this.log(`Lease renewal failed for task ${taskId}, stopping monitor`); + if (renewed === false) { + this.log(`Lease for task ${taskId} is no longer held, stopping monitor`); this.cleanupTask(taskId); + } else if (renewed === null) { + // No answer is not a lost lease: after a wake the first calls time out, + // and dropping the monitor here lets the lease lapse under a live run, so + // the reclaim sweep fires the trigger again. + this.log(`Lease renewal for task ${taskId} got no answer, will retry`, "warn"); } await this.checkTaskCompletion(taskId); From 746efe7e67785b732d1efc726ed6d0e7594a3f1c Mon Sep 17 00:00:00 2001 From: Ankit Patel Date: Mon, 23 Nov 2026 21:20:48 +0530 Subject: [PATCH 3/4] fix(cli): satisfy the max-lines, boot-graph and daemon-stamp guards for the lease fix - The heartbeat tests move to taskScheduler.heartbeat.test.ts: adding them to taskScheduler.test.ts took it over 800 lines (850), which the max-lines ratchet refuses for a new oversized file. - index.ts's static graph sat at 4851 KB, the pin, and the lease fix's comment in syncService.ts pushed it to 4852. The explanation now sits on the scheduler's heartbeat, which is off that graph. - Re-stamp the daemon build id: the lease fix changes the daemon closure. --- packages/cli/src/daemonBuildId.ts | 2 +- packages/cli/src/syncService.ts | 3 -- .../cli/src/taskScheduler.heartbeat.test.ts | 54 +++++++++++++++++++ packages/cli/src/taskScheduler.test.ts | 36 ------------- packages/cli/src/taskScheduler.ts | 10 ++-- 5 files changed, 60 insertions(+), 45 deletions(-) create mode 100644 packages/cli/src/taskScheduler.heartbeat.test.ts diff --git a/packages/cli/src/daemonBuildId.ts b/packages/cli/src/daemonBuildId.ts index 7b0d4a0ce2..8a67dec89e 100644 --- a/packages/cli/src/daemonBuildId.ts +++ b/packages/cli/src/daemonBuildId.ts @@ -10,4 +10,4 @@ // // This file is excluded from its own hash, and it imports nothing on purpose: // the CLI fast path reads it, so it must never pull in a module graph. -export const DAEMON_BUILD_ID = "43ce973d63b5"; +export const DAEMON_BUILD_ID = "2788e9b42deb"; diff --git a/packages/cli/src/syncService.ts b/packages/cli/src/syncService.ts index 688c5f1300..9a56968c05 100644 --- a/packages/cli/src/syncService.ts +++ b/packages/cli/src/syncService.ts @@ -2725,9 +2725,6 @@ export class SyncService { } } - /** true: renewed. false: the backend answered that this daemon no longer holds - * the lease. null: no answer (offline, timed out, signed out), which says - * nothing about the lease, so the caller keeps its monitor and tries again. */ async renewTaskLease(taskId: string, daemonId: string): Promise { if (!this.apiToken) return null; try { diff --git a/packages/cli/src/taskScheduler.heartbeat.test.ts b/packages/cli/src/taskScheduler.heartbeat.test.ts new file mode 100644 index 0000000000..bc7620e790 --- /dev/null +++ b/packages/cli/src/taskScheduler.heartbeat.test.ts @@ -0,0 +1,54 @@ +import { describe, it, expect, beforeEach, afterEach } from "bun:test"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { TaskScheduler } from "./taskScheduler.js"; + +let dir: string; + +beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "tasksched-heartbeat-")); +}); + +afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); +}); + +function makeScheduler(renew: () => Promise) { + const scheduler = new TaskScheduler({ + syncService: { renewTaskLease: renew } as any, + config: {}, + log: () => {}, + runsFile: path.join(dir, "trigger-runs.json"), + }) as any; + scheduler.track({ taskId: "t1", tmuxSession: "ct-claude-renew", startedAt: Date.now(), maxRuntimeMs: 600_000 }); + // The tmux probe is not under test: a beat here is only about the renewal. + scheduler.checkTaskCompletion = async () => {}; + return scheduler; +} + +describe("a run's lease renewal", () => { + it("keeps watching the run when the backend cannot be reached, and renews on the next beat", async () => { + const answers: Array = [null, true]; + const scheduler = makeScheduler(async () => answers.shift() as boolean | null); + try { + await scheduler.heartbeat("t1"); + expect(scheduler.running.has("t1")).toBe(true); + await scheduler.heartbeat("t1"); + expect(answers).toEqual([]); + expect(scheduler.running.has("t1")).toBe(true); + } finally { + scheduler.stop(); + } + }); + + it("stops watching the run when the backend answers that the lease is no longer held", async () => { + const scheduler = makeScheduler(async () => false); + try { + await scheduler.heartbeat("t1"); + expect(scheduler.running.has("t1")).toBe(false); + } finally { + scheduler.stop(); + } + }); +}); diff --git a/packages/cli/src/taskScheduler.test.ts b/packages/cli/src/taskScheduler.test.ts index e7fd00b54e..b23b7ff70b 100644 --- a/packages/cli/src/taskScheduler.test.ts +++ b/packages/cli/src/taskScheduler.test.ts @@ -789,39 +789,3 @@ describe("runs already going never hold due triggers (ct-92447)", () => { expect(lines.some((l) => l.includes("Poll error") && l.includes("timed out"))).toBe(true); }); }); - -describe("a run's lease renewal", () => { - const trackOne = (scheduler: any) => { - scheduler.track({ taskId: "t1", tmuxSession: "ct-claude-renew", startedAt: Date.now(), maxRuntimeMs: 600_000 }); - // The tmux probe is not under test: a beat here is only about the renewal. - scheduler.checkTaskCompletion = async () => {}; - }; - - it("keeps watching the run when the backend cannot be reached, and renews on the next beat", async () => { - const { scheduler } = makeScheduler([]); - const answers: Array = [null, true]; - scheduler.syncService.renewTaskLease = async () => answers.shift(); - trackOne(scheduler); - try { - await scheduler.heartbeat("t1"); - expect(scheduler.running.has("t1")).toBe(true); - await scheduler.heartbeat("t1"); - expect(answers).toEqual([]); - expect(scheduler.running.has("t1")).toBe(true); - } finally { - scheduler.stop(); - } - }); - - it("stops watching the run when the backend answers that the lease is no longer held", async () => { - const { scheduler } = makeScheduler([]); - scheduler.syncService.renewTaskLease = async () => false; - trackOne(scheduler); - try { - await scheduler.heartbeat("t1"); - expect(scheduler.running.has("t1")).toBe(false); - } finally { - scheduler.stop(); - } - }); -}); diff --git a/packages/cli/src/taskScheduler.ts b/packages/cli/src/taskScheduler.ts index e299a63310..d85a78e7e2 100644 --- a/packages/cli/src/taskScheduler.ts +++ b/packages/cli/src/taskScheduler.ts @@ -724,16 +724,16 @@ export class TaskScheduler { }, delaysMs[attempt]); } + /** One lease beat. renewTaskLease answers null when the backend did not answer: that says nothing + * about the lease, so the monitor stays (after a wake the first calls time out, and stopping here + * lets a live run's lease lapse and the trigger refire). Only false, the backend's "lost", stops it. */ private async heartbeat(taskId: string): Promise { const renewed = await this.syncService.renewTaskLease(taskId, this.daemonId); if (renewed === false) { - this.log(`Lease for task ${taskId} is no longer held, stopping monitor`); + this.log(`Lease for task ${taskId} lost, stopping monitor`); this.cleanupTask(taskId); } else if (renewed === null) { - // No answer is not a lost lease: after a wake the first calls time out, - // and dropping the monitor here lets the lease lapse under a live run, so - // the reclaim sweep fires the trigger again. - this.log(`Lease renewal for task ${taskId} got no answer, will retry`, "warn"); + this.log(`Lease renewal for task ${taskId} unanswered`, "warn"); } await this.checkTaskCompletion(taskId); From 824320ad8c23e6b10af2ba6dacab428eb7f2dbc5 Mon Sep 17 00:00:00 2001 From: Ankit Patel Date: Mon, 23 Nov 2026 21:30:06 +0530 Subject: [PATCH 4/4] ci: re-run test-cli (allocatePorts port-collision test failed on the runner, unrelated)