diff --git a/packages/db/src/migrations/0479_short_darkstar.sql b/packages/db/src/migrations/0479_short_darkstar.sql new file mode 100644 index 00000000000..d743d7d8eab --- /dev/null +++ b/packages/db/src/migrations/0479_short_darkstar.sql @@ -0,0 +1 @@ +ALTER TABLE "heartbeat_runs" ADD COLUMN "native_source_cursors" jsonb; \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0474_snapshot.json b/packages/db/src/migrations/meta/0479_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0474_snapshot.json rename to packages/db/src/migrations/meta/0479_snapshot.json index bc1fefbdb18..36323203dc1 100644 --- a/packages/db/src/migrations/meta/0474_snapshot.json +++ b/packages/db/src/migrations/meta/0479_snapshot.json @@ -1,6 +1,6 @@ { - "id": "a7108924-4d75-41e2-9139-f43f9396c02d", - "prevId": "f14430e8-1ebf-414a-8c89-93c32740c4e6", + "id": "f5f852bd-0568-4b2d-bc35-0dac5d9c8c5b", + "prevId": "349cdd89-db04-4340-a5d3-3b877bf7227d", "version": "7", "dialect": "postgresql", "tables": { @@ -3954,6 +3954,28 @@ "method": "btree", "with": {} }, + "agent_wakeup_requests_company_run_idx": { + "name": "agent_wakeup_requests_company_run_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"agent_wakeup_requests\".\"run_id\" IS NOT NULL", + "concurrently": true, + "method": "btree", + "with": {} + }, "agent_wakeup_requests_review_path_recovery_idempotency_uq": { "name": "agent_wakeup_requests_review_path_recovery_idempotency_uq", "columns": [ @@ -35239,6 +35261,12 @@ "notNull": true, "default": 1 }, + "native_source_cursors": { + "name": "native_source_cursors", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "native_phase": { "name": "native_phase", "type": "text", @@ -53942,6 +53970,7 @@ } ], "isUnique": true, + "where": "\"sandbox_creation_operations\".\"state\" <> 'resolved'", "concurrently": false, "method": "btree", "with": {} @@ -57541,6 +57570,12 @@ "primaryKey": false, "notNull": false }, + "icons": { + "name": "icons", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "risk_level": { "name": "risk_level", "type": "text", @@ -59762,6 +59797,18 @@ "primaryKey": false, "notNull": true }, + "model_context": { + "name": "model_context", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "model_context_updated_at": { + "name": "model_context_updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -60955,6 +61002,392 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.tool_mcp_tasks": { + "name": "tool_mcp_tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "invocation_id": { + "name": "invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "connection_id": { + "name": "connection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "grant_id": { + "name": "grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "agent_id": { + "name": "agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "run_id": { + "name": "run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "identity_context_id": { + "name": "identity_context_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "catalog_tool_name": { + "name": "catalog_tool_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "endpoint_hash": { + "name": "endpoint_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sealed_caller_headers": { + "name": "sealed_caller_headers", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "protocol_version": { + "name": "protocol_version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sealed_provider_task_id": { + "name": "sealed_provider_task_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_task_id_hash": { + "name": "provider_task_id_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "poll_interval_ms": { + "name": "poll_interval_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "ttl_ms": { + "name": "ttl_ms", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "next_poll_at": { + "name": "next_poll_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_polled_at": { + "name": "last_polled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "poll_failures": { + "name": "poll_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "lease_owner": { + "name": "lease_owner", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "arguments_identity": { + "name": "arguments_identity", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "answered_input_keys": { + "name": "answered_input_keys", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "surfaced_input_keys": { + "name": "surfaced_input_keys", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "input_wake_count": { + "name": "input_wake_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "input_wake_at": { + "name": "input_wake_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "wake_requested_at": { + "name": "wake_requested_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "delivered_at": { + "name": "delivered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_invocation_id": { + "name": "last_invocation_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tool_mcp_tasks_provider_task_uq": { + "name": "tool_mcp_tasks_provider_task_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "provider_task_id_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_tasks_attach_idx": { + "name": "tool_mcp_tasks_attach_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connection_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "request_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_tasks_invocation_idx": { + "name": "tool_mcp_tasks_invocation_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "invocation_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_mcp_tasks_next_poll_idx": { + "name": "tool_mcp_tasks_next_poll_idx", + "columns": [ + { + "expression": "next_poll_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_mcp_tasks\".\"next_poll_at\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tool_mcp_tasks_company_id_companies_id_fk": { + "name": "tool_mcp_tasks_company_id_companies_id_fk", + "tableFrom": "tool_mcp_tasks", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_tasks_invocation_id_tool_invocations_id_fk": { + "name": "tool_mcp_tasks_invocation_id_tool_invocations_id_fk", + "tableFrom": "tool_mcp_tasks", + "tableTo": "tool_invocations", + "columnsFrom": [ + "invocation_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tool_mcp_tasks_connection_id_tool_connections_id_fk": { + "name": "tool_mcp_tasks_connection_id_tool_connections_id_fk", + "tableFrom": "tool_mcp_tasks", + "tableTo": "tool_connections", + "columnsFrom": [ + "connection_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.tool_oauth_states": { "name": "tool_oauth_states", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 11496828cb9..29a110630c2 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3340,6 +3340,13 @@ "when": 1794577652781, "tag": "0478_jazzy_vertigo", "breakpoints": true + }, + { + "idx": 479, + "version": "7", + "when": 1794589077537, + "tag": "0479_short_darkstar", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.ts index 44fcd369ae7..b2979d52b30 100644 --- a/packages/db/src/schema/heartbeat_runs.ts +++ b/packages/db/src/schema/heartbeat_runs.ts @@ -76,6 +76,13 @@ export const heartbeatRuns = pgTable( completionContractId: uuid("completion_contract_id"), completionContractSha256: text("completion_contract_sha256"), nextEventSeq: bigint("next_event_seq", { mode: "number" }).notNull().default(1), + // Per native source instance, the highest source sequence below which the + // run stores every event: {"": }. The append that + // reserves the sequence keeps it, so an in-order event needs no count of + // the run's events. It is a lower bound: a missing or stale entry (rows + // saved before it existed, or by a writer that does not keep it) makes the + // next out-of-order append recount the source's events from the table. + nativeSourceCursors: jsonb("native_source_cursors").$type>(), nativePhase: text("native_phase"), nativePhaseUpdatedAt: timestamp("native_phase_updated_at", { withTimezone: true }), sessionIdBefore: text("session_id_before"), diff --git a/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts b/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts index 036729efe36..b666576f16a 100644 --- a/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts +++ b/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts @@ -5,6 +5,7 @@ import { eq, inArray, sql } from "drizzle-orm"; import { drizzle } from "drizzle-orm/postgres-js"; import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunnerCheckpoints } from "@paperclipai/db"; import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js"; +import { nativeSha256 } from "../services/native-runtime/canonical.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; const externalTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_ATOMIC_EVENTS_TEST_DATABASE_URL"); @@ -136,7 +137,7 @@ describeEmbeddedPostgres("atomic ordinary run events", () => { // own so that the append reads a snapshot taken after the lock was granted. expect(first.statements).toHaveLength(4); expect(first.statements[0]).toMatch(/^begin/i); - expect(first.statements[1]).toMatch(/^select "company_id", "agent_id" from "heartbeat_runs" .* for no key update$/); + expect(first.statements[1]).toMatch(/^select "company_id", "agent_id", \("native_source_cursors" ->> \$1\)::bigint as "source_cursor" from "heartbeat_runs" .* for no key update$/); expect(first.statements[2]).toMatch(/^with existing as .* insert into heartbeat_run_events /); expect(first.statements[3]).toMatch(/^commit/i); expect(first.result).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: 1 }); @@ -162,6 +163,48 @@ describeEmbeddedPostgres("atomic ordinary run events", () => { expect((await readEvents(runId)).map(row => [row.seq, row.sourceSeq])).toEqual([[1, 1], [2, 2], [3, 3]]); }); + it("keeps the source cursor on the run so an in-order append does not count the run's events", async () => { + const runId = await makeRun(); + await appendHeartbeatRunEvent(db, nativeEvent(runId, 1)); + for (let sourceSeq = 2; sourceSeq <= 6; sourceSeq += 1) { + const appended = await sentStatements(db.$client, () => appendHeartbeatRunEvent(db, nativeEvent(runId, sourceSeq))); + expect(appended.result).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: sourceSeq }); + expect(appended.statements).toHaveLength(4); + // The append statement reads no other event of the run. + expect(appended.statements[2]).not.toMatch(/count\(|max\(source_seq\)/); + } + const replay = await sentStatements(db.$client, () => appendHeartbeatRunEvent(db, nativeEvent(runId, 3))); + expect(replay.result).toMatchObject({ disposition: "duplicate", highestContiguousSourceSeq: 6 }); + expect(replay.statements[2]).not.toMatch(/count\(/); + expect((await readRun(runId)).nativeSourceCursors).toEqual({ "native-writer": 6 }); + }); + + it("recounts a source whose run has no cursor or a cursor behind its stored events", async () => { + const runId = await makeRun(); + const stored = (sourceSeqs: number[], firstSeq: number) => db.insert(heartbeatRunEvents).values(sourceSeqs.map((sourceSeq, index) => ({ + companyId, agentId, runId, seq: firstSeq + index, eventType: "item.delta", stream: "system", level: "info", + payload: { prpEvent: { sourceSeq } }, sourceInstanceId: "native-writer", sourceEventId: `native-writer:${sourceSeq}`, + sourceSeq, sourcePayloadSha256: nativeSha256({ sourceSeq }), protocolSchemaVersion: 1, + }))); + // A server from before the cursor stored events 1 to 3 of a run that is still streaming. + await stored([1, 2, 3], 1); + await db.update(heartbeatRuns).set({ nextEventSeq: 4 }).where(eq(heartbeatRuns.id, runId)); + expect(await appendHeartbeatRunEvent(db, nativeEvent(runId, 4))).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: 4 }); + expect((await readRun(runId)).nativeSourceCursors).toEqual({ "native-writer": 4 }); + // A writer that does not keep the cursor stored 5 to 7. + await stored([5, 6, 7], 5); + await db.update(heartbeatRuns).set({ nextEventSeq: 8 }).where(eq(heartbeatRuns.id, runId)); + expect(await appendHeartbeatRunEvent(db, nativeEvent(runId, 6))).toMatchObject({ disposition: "duplicate" }); + expect(await appendHeartbeatRunEvent(db, nativeEvent(runId, 8))).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: 8 }); + expect((await readRun(runId)).nativeSourceCursors).toEqual({ "native-writer": 8 }); + // A gap removes the cursor, so the event that fills it recounts. + expect(await appendHeartbeatRunEvent(db, nativeEvent(runId, 10))).toMatchObject({ highestContiguousSourceSeq: 8 }); + expect((await readRun(runId)).nativeSourceCursors).toEqual({}); + expect(await appendHeartbeatRunEvent(db, nativeEvent(runId, 9))).toMatchObject({ highestContiguousSourceSeq: 10 }); + expect((await readRun(runId)).nativeSourceCursors).toEqual({ "native-writer": 10 }); + expect((await readEvents(runId)).map(row => row.sourceSeq)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 10, 9]); + }); + it("registers a native event's wakes before its write and only when the event is new", async () => { const runId = await makeRun(); const [issue] = await db.insert(issues).values({ companyId, title: "Progress task" }).returning(); @@ -288,7 +331,7 @@ describeEmbeddedPostgres("atomic ordinary run events", () => { query.includes('from "heartbeat_runs"') && query.endsWith("for no key update")); expect(lockReads).toHaveLength(2); for (const query of lockReads) { - expect(query).toMatch(/^select "company_id", "agent_id" from "heartbeat_runs" /); + expect(query).toMatch(/^select "company_id", "agent_id"(, \("native_source_cursors" ->> \$1\)::bigint as "source_cursor")? from "heartbeat_runs" /); expect(query).not.toMatch(/context_snapshot|runner_profile_json|result_json|stdout_excerpt/); } }); diff --git a/server/src/services/heartbeat-run-events.ts b/server/src/services/heartbeat-run-events.ts index 29a46c5cf0e..cab99298136 100644 --- a/server/src/services/heartbeat-run-events.ts +++ b/server/src/services/heartbeat-run-events.ts @@ -181,13 +181,22 @@ async function appendNativeSourceEvent( // checkpoints, that are written for the same run while events stream. // Only progress needs the task binding. Other native/recovery events // must not read a potentially large context snapshot to append a log. - const [run] = await tx.execute<{ company_id: string; agent_id: string; runtime_mode?: string | null; issue_id?: string | null }>( - sql`select "company_id", "agent_id"${wakes.progress || wakes.response || wakes.reassessment ? sql`, "runtime_mode"` : sql.empty()}${ + const [run] = await tx.execute<{ company_id: string; agent_id: string; source_cursor: string | number | null; + runtime_mode?: string | null; issue_id?: string | null }>( + sql`select "company_id", "agent_id", ("native_source_cursors" ->> ${source.sourceInstanceId})::bigint as "source_cursor"${ + wakes.progress || wakes.response || wakes.reassessment ? sql`, "runtime_mode"` : sql.empty()}${ wakes.progress ? sql`, ${boundRunIssueIdSql()} as "issue_id"` : sql.empty() } from "heartbeat_runs" where "id" = ${input.runId} for no key update`); if (!run || run.company_id !== input.companyId || run.agent_id !== input.agentId) { throw new Error("heartbeat_run_event_binding_mismatch"); } + // The stored cursor says the run holds every event of this source up to it. + // An event at or just past it moves the cursor without counting the run's + // events; any other event, or a run without a cursor, recounts them. + const storedCursor = run.source_cursor === null || run.source_cursor === undefined ? null : Number(run.source_cursor); + const inOrderCursor = storedCursor !== null && source.sourceSeq <= storedCursor + 1 + ? (source.sourceSeq === storedCursor + 1 ? source.sourceSeq : storedCursor) + : null; if (wakes.recovery) await notifyLiveRunRecovery(tx, input); const sourceHash = nativeSha256(source.canonicalPayload); @@ -203,7 +212,7 @@ async function appendNativeSourceEvent( if (existing) { const row = decodeRunEventRow(existing); if (row.sourcePayloadSha256 !== sourceHash) throw new HeartbeatRunEventConflictError(); - return { row, disposition: "duplicate", highestContiguousSourceSeq: await contiguousCursor(tx, input.runId, + return { row, disposition: "duplicate", highestContiguousSourceSeq: inOrderCursor ?? await contiguousCursor(tx, input.runId, source.sourceInstanceId, await retainedSourceRange(tx, input.runId, source.sourceInstanceId)) }; } if (reassessment) await notifyNativeStatusReassessment(tx, { companyId: run.company_id, runId: input.runId }); @@ -214,13 +223,32 @@ async function appendNativeSourceEvent( // `existing` and `retained` read the snapshot from before this statement's // own insert. A replayed event reserves no sequence and inserts nothing. + const counted = source.sourceSeq >= 1 ? 1 : 0; + const cursorKey = sql`array[${source.sourceInstanceId}::text]`; + // An in-order event keeps the cursor without reading other events. Any + // other event recounts the source: it stores the cursor when the source has + // no gap and removes it otherwise, so the event that fills a gap recounts. + const cursorUpdate = inOrderCursor !== null + ? (inOrderCursor === storedCursor ? sql.empty() : sql`, native_source_cursors = jsonb_set( + coalesce(native_source_cursors, '{}'::jsonb), ${cursorKey}, to_jsonb(${inOrderCursor}::bigint))`) + : sql`, native_source_cursors = case + when retained.retained_count + ${counted}::integer + = greatest(coalesce(retained.retained_max, 0), ${counted ? source.sourceSeq : 0}::bigint) + then jsonb_set(coalesce(native_source_cursors, '{}'::jsonb), ${cursorKey}, + to_jsonb(retained.retained_count + ${counted}::integer)) + else coalesce(native_source_cursors, '{}'::jsonb) - ${source.sourceInstanceId}::text end`; const [result] = await tx.execute>(sql` with existing as ( select * from heartbeat_run_events where ${replayed} limit 1 - ), allocated as ( + )${inOrderCursor !== null ? sql.empty() : sql`, retained as ( + select count(*) as retained_count, max(source_seq) as retained_max + from heartbeat_run_events + where run_id = ${input.runId} and source_instance_id = ${source.sourceInstanceId} and source_seq >= 1 + )`}, allocated as ( update heartbeat_runs set next_event_seq = next_event_seq + 1, - updated_at = ${sql.param(new Date(), heartbeatRuns.updatedAt)} + updated_at = ${sql.param(new Date(), heartbeatRuns.updatedAt)}${cursorUpdate} + ${inOrderCursor !== null ? sql.empty() : sql`from retained`} where id = ${input.runId} and not exists (select 1 from existing) returning next_event_seq - 1 as seq ), appended as ( @@ -235,26 +263,28 @@ async function appendNativeSourceEvent( ${sourceHash}::text, ${source.protocolSchemaVersion}::integer from allocated returning * - ), retained as ( - select count(*) as retained_count, max(source_seq) as retained_max - from heartbeat_run_events - where run_id = ${input.runId} and source_instance_id = ${source.sourceInstanceId} and source_seq >= 1 - ) + )${inOrderCursor !== null ? sql` + select true as appended, event.* from appended event + union all + select false as appended, event.* from existing event` : sql` select true as appended, event.*, retained.* from appended event cross join retained union all - select false as appended, event.*, retained.* from existing event cross join retained + select false as appended, event.*, retained.* from existing event cross join retained`} `); if (!result) throw new Error("heartbeat_run_event_not_persisted"); const row = decodeRunEventRow(result); const appended = result.appended === true; if (!appended && row.sourcePayloadSha256 !== sourceHash) throw new HeartbeatRunEventConflictError(); - const counted = appended && source.sourceSeq >= 1; + if (inOrderCursor !== null) { + return { row, disposition: appended ? "committed" : "duplicate", highestContiguousSourceSeq: inOrderCursor }; + } + const countedHere = appended && counted === 1; return { row, disposition: appended ? "committed" : "duplicate", highestContiguousSourceSeq: await contiguousCursor(tx, input.runId, source.sourceInstanceId, { - count: Number(result.retained_count) + (counted ? 1 : 0), - max: Math.max(Number(result.retained_max ?? 0), counted ? source.sourceSeq : 0), + count: Number(result.retained_count) + (countedHere ? 1 : 0), + max: Math.max(Number(result.retained_max ?? 0), countedHere ? source.sourceSeq : 0), }), }; }