perf(run-events): keep each native source's cursor on the run row (#21435)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - One server process stores every event of every running native agent
in `heartbeat_run_events`
> - Each native source event append counted all retained events of its
source (`count(*)`, `max(source_seq)`) to compute the acknowledgement
cursor
> - So the cost of each append grew with the length of the run, and long
runs made every text delta slower
> - This pull request keeps the gap-free cursor of each source on the
run row and moves it in the same UPDATE that reserves the event sequence
> - The benefit is that an in-order append stops reading other events,
so its cost does not grow with run length

## Linked Issues or Issue Description

Refs #21131 (earlier reduction of statements per event). Item 1b of the
agent scaling plan in #21418.

**What existing behavior does this improve?**
The append of a native source event (`appendNativeSourceEvent` in
`server/src/services/heartbeat-run-events.ts`). It ran a `retained` CTE
that counted every event of the source on every append.

**Subsystem affected**
Server run event ingest (`heartbeat_run_events`, `heartbeat_runs`).

**Current behavior**
On a run that already holds 50,000 events, one in-order append takes
about 10–13 ms (p50) on a local PostgreSQL. On a run with 400 events it
takes about 3.3 ms.

**Proposed behavior**
The append reads the stored cursor in the run lock statement that it
already sends. An in-order event moves the cursor and does not count
events. On the same 50,000-event run an append takes about 1.7–3.3 ms
(p50).

**Reason and benefit**
Text deltas are about 85% of the server's statements in the load model.
Their cost must not grow with run length.

**Breaking changes**
None. The new column is nullable. The previous release ignores it.

## What Changed

- Add the nullable column `heartbeat_runs.native_source_cursors`
(`jsonb`, `{"<source instance id>": <seq>}`). Migration `0479` is `ADD
COLUMN` only and classifies as `online_compatible`.
- The run lock read of a native append also reads the cursor of its
source.
- When the event sequence is at most cursor + 1, the append statement
has no `retained` CTE. It moves the cursor in the UPDATE that reserves
the sequence, and the receipt uses the cursor.
- Every other case (no cursor, a gap, or a cursor behind the stored
events) runs the earlier recount. In the same UPDATE it stores the
cursor when the source has no gap, and removes it when the source has a
gap. So the event that fills a gap recounts.
- The cursor is a lower bound. A writer that does not keep it (the
previous release during a deploy overlap, or
`NativeRunCoordinatorStore`) can only make it lag. The next out-of-order
event then recounts and corrects it.

## Verification

- `cd server && npx vitest run
src/__tests__/heartbeat-run-event-atomic-append.test.ts
src/__tests__/heartbeat-run-event-sequencing.test.ts` passes (19 tests).
- Red/green: before the change, 3 tests failed: the two new tests and
the updated lock-read statement test. After the change, all pass.
- New: "keeps the source cursor on the run so an in-order append does
not count the run's events" checks that the append statement has no
`count(` and that a replay returns the cursor.
- New: "recounts a source whose run has no cursor or a cursor behind its
stored events" covers rows saved before the change, rows from a writer
that does not keep the cursor, a gap, and the event that fills the gap.
- Focused related tests: `paperclip-control-plane-port.test.ts`,
`native-observer-replay`, `native-event-boundary-golden`,
`chat-native-progress-work`, `live-recovery-work`,
`native-interaction-bridge`.
- `pnpm check:module-boundaries` passes. `pnpm verify` returned exit 2
(broader CI coverage required) because of local benchmark scripts that
are not in this pull request. Required CI supplies the broad coverage.
- Append cost on a run with many events (local embedded PostgreSQL,
1,000 in-order appends, busy machine, load average about 20–40):

  | Events already in run | Before p50 / p90 | After p50 / p90 |
  | --- | --- | --- |
  | 50,000 (run 1) | 10.4 / 15.8 ms | 1.7 / 3.7 ms |
  | 50,000 (run 2) | 12.9 / 21.6 ms | 3.3 / 5.9 ms |
  | 400 | 3.3 / 6.2 ms | 3.7 / 7.7 ms (noise) |

- Statements per event do not change: BEGIN, run lock read, one append
statement, COMMIT (4). The append statement no longer scans the source's
events.
- Load model (`scripts/benchmark-agent-scaling-load.ts` from #21418,
`AGENTS=50 SECONDS=20`): the machine was too busy for a stable result.
Deltas only: before 20,000 of 20,000 done at 3,999 statements/s. After:
13,796 and 14,817 of 20,000 in two runs. All sources: before 6,346 of
20,000 deltas done. After: 20,000 and 2,083 in two runs. A 20-second
window gives only 400 events per run, so it cannot show this change. The
long-run figures above are the evidence.

## Risks

- Low. The column is nullable and the previous release does not read it.
Runs that are in flight during a deploy have no cursor. Their first
append recounts once and stores the cursor.
- A stale cursor can only make the acknowledgement lag, never pass the
stored events. Event rows are deleted only with their company or agent.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-13 14:36:08 -06:00
1 parent 0d832a02d3
commit 969cf246ae
6 files changed
+539 -18

No files matched your search

@@ -0,0 +1 @@
ALTER TABLE "heartbeat_runs" ADD COLUMN "native_source_cursors" jsonb;
@@ -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": "",
+7
View File
@@ -3340,6 +3340,13 @@
"when": 1794577652781,
"tag": "0478_jazzy_vertigo",
"breakpoints": true
},
{
"idx": 479,
"version": "7",
"when": 1794589077537,
"tag": "0479_short_darkstar",
"breakpoints": true
}
]
}
+7
View File
@@ -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: {"<source instance id>": <seq>}. 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<Record<string, number>>(),
nativePhase: text("native_phase"),
nativePhaseUpdatedAt: timestamp("native_phase_updated_at", { withTimezone: true }),
sessionIdBefore: text("session_id_before"),
@@ -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/);
}
});
+44 -14
View File
@@ -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<Record<string, unknown>>(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),
}),
};
}