fix(heartbeat): atomically claim due timer intervals (#10584)

<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip coordinates AI agents through scheduled heartbeat runs.
> - The heartbeat scheduler can call `tickTimers()` again before an
earlier tick has finished.
> - Each overlapping tick can read the same old `lastHeartbeatAt` value
and decide that the same agent is due.
> - The existing queue checks do not make that due-time decision atomic.
> - This pull request atomically advances the timer baseline before it
enqueues the wake.
> - The benefit is that one timer interval can create at most one
scheduled run for an agent.

## Linked Issues or Issue Description

No public GitHub issue describes this exact scheduler race. Related pull
requests address active-run overlap or queued-run buildup, but they do
not atomically claim a due timer interval: #9457, #8416, and #3858.

**What happened?**

Two overlapping calls to `tickTimers()` could both read the same due
timer baseline. Both calls could enqueue a timer run for the same agent
and interval.

**Expected behavior**

Only one scheduler tick must claim a due timer interval. A second
overlapping tick must observe that the interval was already claimed and
skip it.

**Steps to reproduce**

1. Create an active agent with a 60-second timer interval.
2. Set `lastHeartbeatAt` to more than 60 seconds in the past.
3. Call `tickTimers(now)` twice with `Promise.all()`.
4. Observe that the old code can enqueue two runs for the same interval.

**Paperclip version or commit**

Reproduced on `master` before this branch.

**Deployment mode**

Local development with embedded PostgreSQL.

## What Changed

- Added an atomic conditional update that claims a due timer interval by
advancing `lastHeartbeatAt`.
- Made `tickTimers()` enqueue only after that conditional update
succeeds.
- Preserved first-heartbeat telemetry when the timer claim advances
`lastHeartbeatAt` before run completion.
- Added regression tests for concurrent claims and first-heartbeat
telemetry.

## Verification

- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-stale-queue-invalidation.test.ts` — 24 tests
passed on the final rebased commit.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-process-recovery.test.ts -t "preserves
first-heartbeat telemetry after a timer interval claim|tracks the first
heartbeat with the agent role"` — 2 tests passed.
- `pnpm --filter @paperclipai/server typecheck` — passed after the
review fix.
- `pnpm -r typecheck` — passed.
- `pnpm build` — passed.
- `pnpm test:run` — 3,121 tests passed and 2 tests skipped. One
unrelated runtime-skills test exceeded its 5-second limit under
full-suite load.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-runtime-skills.test.ts` — the timed-out file
passed in isolation, 2 tests passed.
- `pnpm --filter @paperclipai/db exec vitest run
src/status-card-migrations.test.ts` — the unrelated CI timeout passed in
isolation.
- The full PR CI matrix passed after one rerun of that unrelated
timeout.
- Greptile passed with zero new comments and no unresolved review
threads.

## Risks

- Low risk. The change only affects due timer claims.
- If enqueue fails after the claim, the next timer attempt waits for one
interval. This is safer than duplicate agent execution.
- No schema, migration, API, UI, or dependency changes are included.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex based on GPT-5. The exact deployment ID and
context-window size are not exposed to this runtime. Agentic reasoning,
shell tools, code execution, and GitHub operations were enabled.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-07-31 17:30:41 -07:00
1 parent 90ead239a8
commit 7301fae942
3 files changed
+120 -7

No files matched your search

@@ -3567,6 +3567,29 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
);
});
it("preserves first-heartbeat telemetry after a timer interval claim", async () => {
const { agentId, runId } = await seedRunFixture({
agentStatus: "running",
includeIssue: false,
contextSnapshot: { timerClaimWasFirstHeartbeat: true },
});
await db
.update(agents)
.set({ lastHeartbeatAt: new Date("2026-03-19T00:00:00.000Z") })
.where(eq(agents.id, agentId));
const heartbeat = heartbeatService(db);
await heartbeat.cancelRun(runId);
expect(mockTrackAgentFirstHeartbeat).toHaveBeenCalledWith(
mockTelemetryClient,
expect.objectContaining({
agentRole: "engineer",
agentId,
}),
);
});
it("terminates the in-memory process before persisting cancellation status", async () => {
const { runId } = await seedRunFixture({
agentStatus: "running",
@@ -367,6 +367,48 @@ describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {
expect(agent?.lastHeartbeatAt?.getTime()).toBeGreaterThan(now.getTime() - 120_000);
});
it("atomically claims a due timer interval across overlapping scheduler ticks", async () => {
const { agentId } = await seedCompanyAndAgent({
heartbeatConfig: {
enabled: true,
intervalSec: 60,
},
});
const now = new Date();
await db
.update(agents)
.set({
createdAt: new Date(now.getTime() - 120_000),
lastHeartbeatAt: null,
})
.where(eq(agents.id, agentId));
const results = await Promise.all([
heartbeat.tickTimers(now),
heartbeat.tickTimers(now),
]);
expect(results.reduce((total, result) => total + result.enqueued, 0)).toBe(1);
const runs = await db
.select({
id: heartbeatRuns.id,
contextSnapshot: heartbeatRuns.contextSnapshot,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.agentId, agentId));
const [agent] = await db
.select({ lastHeartbeatAt: agents.lastHeartbeatAt })
.from(agents)
.where(eq(agents.id, agentId));
expect(runs).toHaveLength(1);
expect(runs[0]?.contextSnapshot).toMatchObject({
timerClaimWasFirstHeartbeat: true,
});
expect(agent?.lastHeartbeatAt?.getTime()).toBeGreaterThanOrEqual(now.getTime());
});
it("allows generic timer wakes when the agent has assigned todo work", async () => {
const { companyId, agentId } = await seedCompanyAndAgent({
heartbeatConfig: {
+55 -7
View File
@@ -9964,7 +9964,9 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
},
});
await finalizeAgentStatus(run.agentId, "interrupted", message);
await finalizeAgentStatus(run.agentId, "interrupted", message, {
wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),
});
interruptedRunIds.push(interrupted.id);
}
@@ -11428,6 +11430,40 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
.where(eq(agents.id, agentId));
}
async function claimDueTimerHeartbeat(
agent: typeof agents.$inferSelect,
now: Date,
intervalSec: number,
) {
const dueBefore = new Date(now.getTime() - intervalSec * 1000);
const claimed = await db
.update(agents)
.set({
lastHeartbeatAt: now,
updatedAt: now,
})
.where(and(
eq(agents.id, agent.id),
eq(agents.companyId, agent.companyId),
or(
lte(agents.lastHeartbeatAt, dueBefore),
and(isNull(agents.lastHeartbeatAt), lte(agents.createdAt, dueBefore)),
),
))
.returning({ id: agents.id })
.then((rows) => rows[0] ?? null);
if (!claimed) return null;
return { wasFirstHeartbeat: !agent.lastHeartbeatAt };
}
function timerClaimWasFirstHeartbeat(
run: Pick<typeof heartbeatRuns.$inferSelect, "contextSnapshot">,
): true | undefined {
return parseObject(run.contextSnapshot).timerClaimWasFirstHeartbeat === true
? true
: undefined;
}
function parseMaxTurnContinuationPolicy(agent: typeof agents.$inferSelect): MaxTurnContinuationPolicy {
const runtimeConfig = parseObject(agent.runtimeConfig);
const heartbeat = parseObject(runtimeConfig.heartbeat);
@@ -11919,7 +11955,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
agentId: string,
outcome: "succeeded" | "interrupted" | "failed" | "cancelled" | "timed_out",
failureReason?: string | null,
options?: { keepIdleOnFailure?: boolean },
options?: { keepIdleOnFailure?: boolean; wasFirstHeartbeat?: boolean },
) {
const existing = await getAgent(agentId);
if (!existing) return;
@@ -11928,7 +11964,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
return;
}
const isFirstHeartbeat = !existing.lastHeartbeatAt;
const isFirstHeartbeat = options?.wasFirstHeartbeat ?? !existing.lastHeartbeatAt;
const runningCount = await countRunningRunsForAgent(agentId);
const nextStatus =
@@ -12373,7 +12409,9 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
},
});
await finalizeAgentStatus(run.agentId, "failed", baseMessage);
await finalizeAgentStatus(run.agentId, "failed", baseMessage, {
wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),
});
await startNextQueuedRunForAgent(run.agentId);
runningProcesses.delete(run.id);
reaped.push(run.id);
@@ -14976,6 +15014,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
keepIdleOnFailure:
outcome === "failed" &&
(finalizedRun ? readHeartbeatRunErrorFamily(finalizedRun) === "provider_quota" : runErrorCode === "provider_quota"),
wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),
},
);
} catch (err) {
@@ -15099,7 +15138,9 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
}
}
await finalizeAgentStatus(agent.id, "failed", message);
await finalizeAgentStatus(agent.id, "failed", message, {
wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),
});
}
} catch (outerErr) {
// Setup code before adapter.execute threw (e.g. ensureRuntimeState, resolveWorkspaceForRun).
@@ -15199,7 +15240,9 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
// path owned the terminal transition. If another path already finalized
// the run, keep that terminal outcome authoritative.
if (setupFailureWrite.updated) {
await finalizeAgentStatus(run.agentId, "failed", message).catch(() => undefined);
await finalizeAgentStatus(run.agentId, "failed", message, {
wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),
}).catch(() => undefined);
}
} finally {
const latestRun = await getRun(run.id).catch(() => null);
@@ -17501,7 +17544,9 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
await releaseIssueExecutionAndPromote(cancelled);
}
await finalizeAgentStatus(run.agentId, "cancelled");
await finalizeAgentStatus(run.agentId, "cancelled", undefined, {
wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run),
});
await startNextQueuedRunForAgent(run.agentId);
return cancelled;
}
@@ -17980,6 +18025,8 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
const baseline = new Date(agent.lastHeartbeatAt ?? agent.createdAt).getTime();
const elapsedMs = now.getTime() - baseline;
if (elapsedMs < policy.intervalSec * 1000) continue;
const timerClaim = await claimDueTimerHeartbeat(agent, now, policy.intervalSec);
if (!timerClaim) continue;
const run = await enqueueWakeup(agent.id, {
source: "timer",
@@ -17991,6 +18038,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
source: "scheduler",
reason: "interval_elapsed",
now: now.toISOString(),
timerClaimWasFirstHeartbeat: timerClaim.wasFirstHeartbeat,
},
});
if (run) enqueued += 1;