perf(heartbeat): bound the history-read delivery check to the task's runs that finished after the comment

Probe each run binding separately through its index, keep only the
assignee's succeeded runs that finished at or after the comment's current
revision, and stop at the first matching task_history.read event of each run.
The Muse control test now allows the history read's own run-log append.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-12 14:37:39 -06:00
1 parent f43e79c369
commit 239f059742
4 files changed
+28 -17

No files matched your search

+3 -1
View File
@@ -1015,7 +1015,9 @@ 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 after reading the comment's current revision. The comment's queued
wake then neither reopens the finished task nor starts another turn. An edit 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 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, so it is delivered once. The check reads only the assignee's succeeded
runs of that task that finished at or after the comment's current revision,
through the existing run-binding and `(company_id, run_id)` event indexes. A failure to write the event leaves the comment
owed in the same way. owed in the same way.
## Managed Agent File Save Receipts ## Managed Agent File Save Receipts
@@ -805,17 +805,20 @@ describePostgres("saved intents while another run's accounting is pending", () =
}, 180_000); }, 180_000);
it.each([ it.each([
{ outcome: "succeeded", edit: false, consumed: true }, { outcome: "succeeded", edit: "none", consumed: true },
{ outcome: "succeeded", edit: true, consumed: false }, { outcome: "succeeded", edit: "during the run", consumed: false },
{ outcome: "failed", edit: false, consumed: false }, { outcome: "succeeded", edit: "after the run finished", consumed: false },
])("counts a mid-turn history read as delivery only for a run that $outcome on the read revision (edited: $edit)", async ({ outcome, edit, consumed }) => { { outcome: "failed", edit: "none", consumed: false },
])("counts a mid-turn history read as delivery only for a run that $outcome on the current revision (edited: $edit)", async ({ outcome, edit, consumed }) => {
const f = await seedHeldComment(); const f = await seedHeldComment();
await runningNativeSource(f); await runningNativeSource(f);
await readHistoryDuringTurn(f); await readHistoryDuringTurn(f);
if (edit) await db.update(issueComments).set({ body: "Edited after the read.", updatedAt: new Date(Date.now() + 500) }) const editComment = (at: number) => db.update(issueComments).set({ body: "Edited after the read.", updatedAt: new Date(at) })
.where(eq(issueComments.id, f.commentId)); .where(eq(issueComments.id, f.commentId));
if (edit === "during the run") await editComment(Date.now() + 500);
await db.update(heartbeatRuns).set({ status: outcome, finishedAt: new Date(Date.now() + 1_000), await db.update(heartbeatRuns).set({ status: outcome, finishedAt: new Date(Date.now() + 1_000),
...(outcome === "failed" ? { errorCode: "adapter_failed" } : {}) }).where(eq(heartbeatRuns.id, f.sourceRunId)); ...(outcome === "failed" ? { errorCode: "adapter_failed" } : {}) }).where(eq(heartbeatRuns.id, f.sourceRunId));
if (edit === "after the run finished") await editComment(Date.now() + 60_000);
const delivered = await deliveredQueuedCommentIds(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, const delivered = await deliveredQueuedCommentIds(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId,
commentIds: [f.commentId] }); commentIds: [f.commentId] });
expect(delivered.has(f.commentId)).toBe(consumed); expect(delivered.has(f.commentId)).toBe(consumed);
+4 -1
View File
@@ -425,7 +425,10 @@ describe("personal Muse control plane",()=>{
expect(read.comments.find(row=>row.id===standardId)).toMatchObject({body:"Ordinary coordination",sourceTrust:null}); expect(read.comments.find(row=>row.id===standardId)).toMatchObject({body:"Ordinary coordination",sourceTrust:null});
expect(await db.select().from(issueComments).where(eq(issueComments.issueId,f.issue.id)).orderBy(issueComments.id)).toEqual(stored); expect(await db.select().from(issueComments).where(eq(issueComments.issueId,f.issue.id)).orderBy(issueComments.id)).toEqual(stored);
} }
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,f.runId)))[0]).toEqual(committed.run); const {nextEventSeq:readEventSeq,updatedAt:_readAt,...readRun}=(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,f.runId)))[0]!;
const {nextEventSeq:committedEventSeq,updatedAt:_committedAt,...committedRun}=committed.run;
expect(readRun).toEqual(committedRun);
expect(readEventSeq).toBe(committedEventSeq+1);
expect(committed.run.contextSnapshot).toEqual(writerContext); expect(committed.run.contextSnapshot).toEqual(writerContext);
expect(await db.select().from(externalAgentHolds).where(eq(externalAgentHolds.assignmentId,f.assignment.id))).toEqual(beforeHolds); expect(await db.select().from(externalAgentHolds).where(eq(externalAgentHolds.assignmentId,f.assignment.id))).toEqual(beforeHolds);
expect((await db.select({status:assignments.status,acceptedResultAt:assignments.acceptedResultAt,finalizedAt:assignments.finalizedAt}).from(assignments).where(eq(assignments.id,f.assignment.id)))[0]).toEqual({status:"accepted",acceptedResultAt:null,finalizedAt:null}); expect((await db.select({status:assignments.status,acceptedResultAt:assignments.acceptedResultAt,finalizedAt:assignments.finalizedAt}).from(assignments).where(eq(assignments.id,f.assignment.id)))[0]).toEqual({status:"accepted",acceptedResultAt:null,finalizedAt:null});
+13 -10
View File
@@ -1,4 +1,4 @@
import { and, eq, inArray, sql } from "drizzle-orm"; import { and, eq, inArray, sql, type SQL } from "drizzle-orm";
import { heartbeatRunEvents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db"; import { heartbeatRunEvents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db";
import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
@@ -60,15 +60,18 @@ export async function recordTaskHistoryRead(db: Db, input: {
} }
function historyReadDeliveredSql(companyId: string, issueId: string, agentId: string) { function historyReadDeliveredSql(companyId: string, issueId: string, agentId: string) {
return sql`exists (select 1 from ${heartbeatRuns} reading_run const readBy = (binding: SQL) => sql`exists (select 1 from ${heartbeatRuns} reading_run
join ${heartbeatRunEvents} history_read on history_read.run_id = reading_run.id cross join lateral (select 1 from ${heartbeatRunEvents} history_read
where reading_run.company_id = ${companyId} and reading_run.agent_id = ${agentId} where history_read.company_id = ${companyId} and history_read.run_id = reading_run.id
and reading_run.status = 'succeeded' and history_read.event_type = ${TASK_HISTORY_READ_EVENT}
and (reading_run.native_issue_id = ${issueId} or reading_run.context_snapshot->>'issueId' = ${issueId}) and (history_read.payload->'comments'->>${issueComments.id}::text)::timestamptz
and history_read.company_id = ${companyId} >= date_trunc('milliseconds', ${issueComments.updatedAt})
and history_read.event_type = ${TASK_HISTORY_READ_EVENT} limit 1) read_revision
and (history_read.payload->'comments'->>${issueComments.id}::text)::timestamptz where reading_run.company_id = ${companyId} and ${binding}
>= date_trunc('milliseconds', ${issueComments.updatedAt}))`; and reading_run.agent_id = ${agentId} and reading_run.status = 'succeeded'
and reading_run.finished_at >= date_trunc('milliseconds', ${issueComments.updatedAt}) offset 0)`;
return sql`(${readBy(sql`reading_run.native_issue_id = ${issueId}`)}
or ${readBy(sql`reading_run.context_snapshot->>'issueId' = ${issueId}`)})`;
} }
/** /**