fix(heartbeat): stop a comment the closing run already read from reopening its finished task

A person's comment posted during a run became its own queued run when the
running run was executed by another server (K15 overlap). The run read the
comment through get_task_history and finished the task, but nothing proved
that read. The queued run waited for an agent slot, was cancelled as a stale
continuation, and its message was saved again, reopening the done task for a
second completion turn.

- Record the comment revisions a native run's task-history read returned
  (run-log event task_history.read) and count a succeeded reader as delivery
  in deliveredQueuedCommentIds.
- Hold a comment behind a same-agent running run even when this process does
  not track that run, so the release drain settles it when the run finishes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-12 13:28:02 -06:00
1 parent ef6d347f79
commit fe9a5e93cc
6 files changed
+164 -4

No files matched your search

+16
View File
@@ -1002,6 +1002,22 @@ creates no Telemetry or OpenTelemetry export.
Neither wait consumes the provider-failure retry allowance. Each stops after 30
deferrals, after which the run follows the normal failure path.
## Task history reads
When a native run reads its task's comments through `get_task_history`, the
server writes one `task_history.read` event (`stream: "system"`, level `info`)
to that run's log. Its payload has one field, `comments`, which maps each
returned comment ID to that comment's `updatedAt` timestamp. It contains no comment bodies or
author identifiers. The event creates no Telemetry or OpenTelemetry export.
Per-comment delivery (`deliveredQueuedCommentIds`) reads this event. A
person's comment counts as received when a run of the task's assignee succeeded
after reading the comment's current revision. The comment's queued
wake then neither reopens the finished task nor starts another turn. An edit
after the read, or a read by a run that did not succeed, leaves the comment
owed, so it is delivered once. A failure to write the event leaves the comment
owed in the same way.
## Managed Agent File Save Receipts
The server writes `instruction_save` after managed file collection or a warm
@@ -15,6 +15,7 @@ import { heartbeatService } from "../services/heartbeat.js";
import { createOwnershipReportState, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js";
import { applyOwnershipReportBackstops } from "../services/native-runtime/native-finalization-reconciler.js";
import { promoteDeferredWorkIntents, TEMPORARY_REFUSAL_TRIGGERS, WORK_INTENT_TERMINAL_OUTCOMES } from "../services/work-intent-outbox.js";
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js";
const describePostgres = recoveryPostgresSupport.supported ? describe : describe.skip;
@@ -32,6 +33,7 @@ describePostgres("saved intents while another run's accounting is pending", () =
let heartbeat: ReturnType<typeof heartbeatService>;
const adapterType = "codex_local";
const dispatched: Array<{ runId: string; context: Record<string, unknown> }> = [];
let duringTurn: ((runId: string) => Promise<void>) | null = null;
const oldHome = process.env.PAPERCLIP_HOME;
let home: string;
@@ -45,6 +47,7 @@ describePostgres("saved intents while another run's accounting is pending", () =
type: adapterType, supportsLocalAgentJwt: false,
execute: async input => {
dispatched.push({ runId: input.runId, context: input.context as Record<string, unknown> });
await duringTurn?.(input.runId);
// The agent finishes the task, so no disposition repair follows.
await db.update(issues).set({ status: "done" }).where(eq(issues.id, String(input.context.issueId)));
return { exitCode: 0, signal: null, timedOut: false, resultJson: {} };
@@ -732,6 +735,109 @@ describePostgres("saved intents while another run's accounting is pending", () =
expect(deliveries(f.commentId)).toHaveLength(1);
}, 180_000);
async function runningNativeSource(f: Awaited<ReturnType<typeof seedHeldComment>>) {
await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, f.pendingRunId));
await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId));
await db.update(heartbeatRuns).set({ status: "running", runtimeMode: "native", nativeIssueId: f.issueId, finishedAt: null,
startedAt: new Date(Date.now() - 30_000) }).where(eq(heartbeatRuns.id, f.sourceRunId));
await db.update(issues).set({ executionRunId: f.sourceRunId, executionLockedAt: new Date() }).where(eq(issues.id, f.issueId));
}
async function readHistoryDuringTurn(f: Awaited<ReturnType<typeof seedHeldComment>>) {
const reader = new PaperclipRunnerToolAuthority(db, { companyId: f.companyId, agentId: f.agentId, issueId: f.issueId,
runId: f.sourceRunId });
try {
const history = await reader.execute({ tool: "get_task_history", callId: `history-${f.sourceRunId}`, arguments: {} });
expect((history as { comments: Array<{ id: string }> }).comments.map(comment => comment.id)).toContain(f.commentId);
} finally { reader.close(); }
}
async function closeSourceRun(f: Awaited<ReturnType<typeof seedHeldComment>>) {
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(Date.now() + 1_000) })
.where(eq(heartbeatRuns.id, f.sourceRunId));
await db.update(issues).set({ status: "done", completedAt: new Date() }).where(eq(issues.id, f.issueId));
await closeByAgent(f);
}
const issueStatus = async (f: { issueId: string }) =>
(await db.select({ status: issues.status }).from(issues).where(eq(issues.id, f.issueId)))[0]?.status;
const postComment = (f: Awaited<ReturnType<typeof seedHeldComment>>) => heartbeat.wakeup(f.agentId, {
source: "automation", triggerDetail: "system", reason: "issue_commented",
payload: { issueId: f.issueId, commentId: f.commentId, mutation: "comment" },
requestedByActorType: "user", requestedByActorId: f.userId,
contextSnapshot: { issueId: f.issueId, taskId: f.issueId, commentId: f.commentId, wakeCommentId: f.commentId,
source: "issue.comment", wakeReason: "issue_commented" },
});
it("consumes a message the closing run read mid-turn, so its stale queued run reopens nothing", async () => {
const f = await seedHeldComment();
await runningNativeSource(f);
const [wake] = await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, source: "automation",
triggerDetail: "system", reason: "issue_commented", status: "queued", requestedByActorType: "user", requestedByActorId: f.userId,
payload: { issueId: f.issueId, commentId: f.commentId, mutation: "comment" } }).returning();
const [stale] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", status: "queued", wakeupRequestId: wake!.id,
contextSnapshot: { issueId: f.issueId, taskId: f.issueId, commentId: f.commentId, wakeCommentId: f.commentId,
wakeCommentIds: [f.commentId], wakeReason: "issue_commented", source: "issue.comment" } }).returning();
await db.update(agentWakeupRequests).set({ runId: stale!.id }).where(eq(agentWakeupRequests.id, wake!.id));
await readHistoryDuringTurn(f);
await closeSourceRun(f);
await db.update(issues).set({ executionRunId: null, executionLockedAt: null }).where(eq(issues.id, f.issueId));
await settle(f); await settle(f);
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, stale!.id)))[0]).toMatchObject({
status: "cancelled", errorCode: "continuation_task_ownership_changed" });
await db.update(agentWakeupRequests).set({ updatedAt: new Date(Date.now() - 60_000) })
.where(and(eq(agentWakeupRequests.companyId, f.companyId), eq(agentWakeupRequests.status, "deferred_issue_execution")));
await settle(f); await settle(f);
expect(deliveries(f.commentId)).toHaveLength(0);
expect(await issueStatus(f)).toBe("done");
const report = await runOwnershipReconciliationPass(db, { state: createOwnershipReportState(), record: false });
expect(report.violations.filter(row => row.recordId === f.commentId)).toEqual([]);
}, 180_000);
it("holds a message behind a run another server is executing instead of queueing a run of its own", async () => {
const f = await seedHeldComment();
await runningNativeSource(f);
await postComment(f);
const queued = (await issueRuns(f)).filter(run => run.id !== f.sourceRunId && run.status === "queued");
expect(queued).toEqual([]);
const held = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId),
eq(agentWakeupRequests.status, "deferred_issue_execution")));
expect(held.map(row => row.payload?.commentId)).toEqual([f.commentId]);
}, 180_000);
it.each([
{ read: true, delivered: 0 },
{ read: false, delivered: 1 },
])("settles a held message as soon as its run closes the task (read mid-turn: $read)", async ({ read, delivered }) => {
const f = await seedHeldComment();
await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, f.pendingRunId));
await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId));
let closingRunId: string | null = null;
duringTurn = async runId => {
duringTurn = null;
closingRunId = runId;
await postComment(f);
if (!read) return;
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: f.issueId }).where(eq(heartbeatRuns.id, runId));
await readHistoryDuringTurn({ ...f, sourceRunId: runId });
await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, runId));
await closeByAgent(f);
};
if (!read) await closeByAgent(f);
await heartbeat.wakeup(f.agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned",
payload: { issueId: f.issueId }, contextSnapshot: { issueId: f.issueId, taskId: f.issueId, wakeReason: "issue_assigned" } });
await heartbeat.drainActiveRunExecutions();
await heartbeat.drainActiveRunExecutions();
expect(closingRunId).not.toBeNull();
expect(deliveries(f.commentId)).toHaveLength(delivered);
expect((await issueRuns(f)).filter(run => run.status === "cancelled")).toEqual([]);
await settle(f); await settle(f);
expect(deliveries(f.commentId)).toHaveLength(delivered);
expect(await issueStatus(f)).toBe("done");
}, 180_000);
it("still refuses work at a reached hard stop, which the board owns", async () => {
const f = await seedHeldComment({ hardStopReached: true });
await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, f.pendingRunId));
@@ -904,7 +904,8 @@ export function createAdmitWakeBehindIssueExecution(deps: {
isSameExecutionAgent,
shouldDeferFollowupWake,
shouldQueueFollowupForRunningWake,
availableActiveExecutionRunPresent: availableActiveExecutionRun !== null,
availableActiveExecutionRunPresent: availableActiveExecutionRun !== null || (shouldDeferFollowupWake &&
isSameExecutionAgent && input.activeExecutionRun.status === "running" && Boolean(input.wakeCommentId)),
});
if (decision.kind === "proceed") return { kind: "proceed" };
@@ -138,6 +138,8 @@ import {
READ_CHAT_ATTACHMENT_TOOL_NAME,
type NativeChatAttachmentReadScope,
} from "./chat-attachment-read.js";
import { recordTaskHistoryRead } from "../queued-comment-delivery.js";
import { logger } from "../../middleware/logger.js";
const EXTERNAL_WORKSPACE_OPERATIONS = new Set(["get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "register_deliverable"]);
const IMPLEMENTED_OPERATIONS = new Set([
@@ -993,6 +995,7 @@ export class PaperclipRunnerToolAuthority {
authorAgentId: issueComments.authorAgentId,
authorUserId: issueComments.authorUserId,
createdAt: issueComments.createdAt,
updatedAt: issueComments.updatedAt,
}).from(issueComments)
.where(and(
eq(issueComments.companyId, this.binding.companyId),
@@ -1001,7 +1004,10 @@ export class PaperclipRunnerToolAuthority {
))
.orderBy(desc(issueComments.createdAt))
.limit(limit);
return { comments: comments.reverse().map(comment => {
await recordTaskHistoryRead(this.db, { companyId: this.binding.companyId, agentId: this.binding.agentId,
runId: this.binding.runId, comments }).catch(error =>
logger.warn({ err: error, runId: this.binding.runId }, "could not record the task history a run read"));
return { comments: comments.reverse().map(({ updatedAt: _updatedAt, ...comment }) => {
const visible = isLowTrustQuarantined(readerSourceTrust) ? comment : sanitizeQuarantinedCommentForHigherTrust(comment);
return { ...visible, body: fastResponseHistoryBody(visible) };
}) };
@@ -7,6 +7,8 @@ import {
sanitizeQuarantinedCommentForHigherTrust,
} from "../source-trust.js";
import { and, desc, eq, isNull } from "drizzle-orm";
import { recordTaskHistoryRead } from "../queued-comment-delivery.js";
import { logger } from "../../middleware/logger.js";
import type { Db } from "@paperclipai/db";
import {
@@ -166,6 +168,7 @@ export class PaperclipRunnerSemanticAuthority {
authorAgentId: issueComments.authorAgentId,
authorUserId: issueComments.authorUserId,
createdAt: issueComments.createdAt,
updatedAt: issueComments.updatedAt,
})
.from(issueComments)
.where(
@@ -182,7 +185,10 @@ export class PaperclipRunnerSemanticAuthority {
issue: context.issue,
actor: { actorType: "agent", actorId: context.agent.id, agentId: context.agent.id, runId: context.run.id },
});
const comments = rows.reverse().map(row => {
await recordTaskHistoryRead(this.#db, { companyId: this.#binding.companyId, agentId: this.#binding.agentId,
runId: this.#binding.runId, comments: rows }).catch(error =>
logger.warn({ err: error, runId: this.#binding.runId }, "could not record the task history a run read"));
const comments = rows.reverse().map(({ updatedAt: _updatedAt, ...row }) => {
const comment = isLowTrustQuarantined(readerSourceTrust)
? row
: sanitizeQuarantinedCommentForHigherTrust(row);
+26 -1
View File
@@ -1,5 +1,6 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import { heartbeatRunEvents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db";
import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
/** The wake reason an inbound chat message records (see chat inbound wakeups). */
export const EXTERNAL_CHAT_MESSAGE_WAKE_REASON = "External chat message received";
@@ -41,11 +42,35 @@ export async function deliveredQueuedCommentIds(tx: Pick<Db, "select">, input: {
jsonb_build_object('id', ${issueComments.id}::text))
or jsonb_path_exists(delivered_run.context_snapshot, '$.paperclipWake.messages[*] ? (@.id == $id)',
jsonb_build_object('id', ${issueComments.id}::text)))))
or ${firstTurnDeliveredSql(companyId, issueId, input.agentId)})`,
or ${firstTurnDeliveredSql(companyId, issueId, input.agentId)}
or ${historyReadDeliveredSql(companyId, issueId, input.agentId)})`,
));
return new Set(rows.map(row => row.id));
}
export const TASK_HISTORY_READ_EVENT = "task_history.read";
export async function recordTaskHistoryRead(db: Db, input: {
companyId: string; agentId: string; runId: string; comments: ReadonlyArray<{ id: string; updatedAt: Date }>;
}): Promise<void> {
if (input.comments.length === 0) return;
await appendHeartbeatRunEvent(db, { companyId: input.companyId, runId: input.runId, agentId: input.agentId,
eventType: TASK_HISTORY_READ_EVENT, stream: "system", level: "info",
payload: { comments: Object.fromEntries(input.comments.map(comment => [comment.id, comment.updatedAt.toISOString()])) } });
}
function historyReadDeliveredSql(companyId: string, issueId: string, agentId: string) {
return sql`exists (select 1 from ${heartbeatRuns} reading_run
join ${heartbeatRunEvents} history_read on history_read.run_id = reading_run.id
where reading_run.company_id = ${companyId} and reading_run.agent_id = ${agentId}
and reading_run.status = 'succeeded'
and (reading_run.native_issue_id = ${issueId} or reading_run.context_snapshot->>'issueId' = ${issueId})
and history_read.company_id = ${companyId}
and history_read.event_type = ${TASK_HISTORY_READ_EVENT}
and (history_read.payload->'comments'->>${issueComments.id}::text)::timestamptz
>= date_trunc('milliseconds', ${issueComments.updatedAt}))`;
}
/**
* The comment row was taken into an accepted first provider turn of a run of
* this agent on this task, and not edited after that run sealed its input.