diff --git a/doc/run-log-events.md b/doc/run-log-events.md index bd6eec08115..0c80422eff0 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -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 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, 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. ## Managed Agent File Save Receipts diff --git a/server/src/__tests__/heartbeat-held-comment-wake.test.ts b/server/src/__tests__/heartbeat-held-comment-wake.test.ts index adacf580e66..3affe892351 100644 --- a/server/src/__tests__/heartbeat-held-comment-wake.test.ts +++ b/server/src/__tests__/heartbeat-held-comment-wake.test.ts @@ -805,17 +805,20 @@ describePostgres("saved intents while another run's accounting is pending", () = }, 180_000); it.each([ - { outcome: "succeeded", edit: false, consumed: true }, - { outcome: "succeeded", edit: true, consumed: false }, - { outcome: "failed", edit: false, 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: "succeeded", edit: "none", consumed: true }, + { outcome: "succeeded", edit: "during the run", consumed: false }, + { outcome: "succeeded", edit: "after the run finished", consumed: false }, + { 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(); await runningNativeSource(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)); + if (edit === "during the run") await editComment(Date.now() + 500); 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)); + 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, commentIds: [f.commentId] }); expect(delivered.has(f.commentId)).toBe(consumed); diff --git a/server/src/__tests__/muse-control.test.ts b/server/src/__tests__/muse-control.test.ts index 1ba4423b844..81e2bc22dd0 100644 --- a/server/src/__tests__/muse-control.test.ts +++ b/server/src/__tests__/muse-control.test.ts @@ -425,7 +425,10 @@ describe("personal Muse control plane",()=>{ 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(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(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}); diff --git a/server/src/services/queued-comment-delivery.ts b/server/src/services/queued-comment-delivery.ts index 6017b8c27ae..69d97ee4d41 100644 --- a/server/src/services/queued-comment-delivery.ts +++ b/server/src/services/queued-comment-delivery.ts @@ -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 { 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) { - 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}))`; + const readBy = (binding: SQL) => sql`exists (select 1 from ${heartbeatRuns} reading_run + cross join lateral (select 1 from ${heartbeatRunEvents} history_read + where history_read.company_id = ${companyId} and history_read.run_id = reading_run.id + and history_read.event_type = ${TASK_HISTORY_READ_EVENT} + and (history_read.payload->'comments'->>${issueComments.id}::text)::timestamptz + >= date_trunc('milliseconds', ${issueComments.updatedAt}) + limit 1) read_revision + where reading_run.company_id = ${companyId} and ${binding} + 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}`)})`; } /**