mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 09:05:15 +01:00
perf(run-events): append a native event in one transaction of two statements (#21131)
One appended native run event cost eight statements on the database connection (BEGIN, SAVEPOINT, run lock, replay probe, sequence update, insert, count/max read, COMMIT). The query builder built five of them again for every event, and each event created two transaction objects. A native source event now takes the run lock and then runs one statement that finds a replayed event or reserves the sequence and inserts, and reads the retained count and maximum for the acknowledgement. The lock stays a statement of its own so the append reads a snapshot taken after the lock was granted. The control-plane port passes its controller check to the append instead of opening an outer transaction, so there is no SAVEPOINT. The hot statements are fixed SQL text. Events that wake a queue still register the wake before the write and only when the event is new. Order, sequence numbers and durability do not change: every event still commits before its append returns. Local benchmark (server/scripts/benchmark-run-event-append.ts), one native event: 8.3 -> 4.6 statements, 589 -> 222 KB allocated, 1.09 -> 0.53 ms CPU, 28 -> 11.5 garbage collections per 1,000 events. One ordinary event: 105 -> 27 KB allocated. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
5c953c1c1b
commit
5b698b68cf
6 files changed
+720
-173
No files matched your search
@@ -328,6 +328,19 @@ missing successor. The acknowledgement keeps its contiguous-prefix rule without
|
||||
returning every historical sequence number. All events stay stored. Counting the
|
||||
index entries still grows with the stream length.
|
||||
|
||||
A native source event commits in one transaction of two statements. The first
|
||||
statement locks the run row. The second statement finds a replayed event, or
|
||||
reserves the next sequence and inserts the event, and reads the count and
|
||||
maximum for the acknowledgement. The lock stays a separate statement: a
|
||||
statement that waits for the lock keeps the snapshot it took before the wait,
|
||||
and would miss an event that the lock holder committed. An event that wakes a
|
||||
queue looks for its replay in a statement of its own first, because a wake is
|
||||
registered before its write and a replayed event registers none. An ordinary
|
||||
event without a source identity commits in one statement. Each event commits
|
||||
before its append returns; no event waits for another. Measure the cost of one
|
||||
event with
|
||||
`TSX_DISABLE_CACHE=1 pnpm --filter @paperclipai/server exec tsx scripts/benchmark-run-event-append.ts`.
|
||||
|
||||
Conversation recovery reads only the saved run fields used to settle a turn.
|
||||
Settlement locks and reads current conversation state without loading the task
|
||||
description or comment bodies. It still checks the durable reply or pending
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* What one appended run event costs: statements, wall time, CPU and allocation.
|
||||
*
|
||||
* It drives the real append path on a local PostgreSQL:
|
||||
*
|
||||
* - `native-stream`: one native run. A runner stream appends its events one
|
||||
* after another through `PaperclipControlPlanePort.appendEvent`, which is
|
||||
* what the session runtime calls for every PRP event.
|
||||
* - `native-burst`: RUNS native runs streaming at the same time, each one in
|
||||
* order, on one connection pool.
|
||||
* - `ordinary`: adapter log events through `appendHeartbeatRunEvent`.
|
||||
*
|
||||
* Seven of ten native events are text deltas. The other three are progress
|
||||
* events (`tool.execution.started`, `tool.execution.completed`,
|
||||
* `item.completed`), which also wake the chat progress queue.
|
||||
*
|
||||
* Statements are counted in the driver, so the count includes BEGIN, COMMIT
|
||||
* and SAVEPOINT. CPU is the whole process (`process.cpuUsage`); busy time is
|
||||
* the main thread only (event loop utilization). Allocated bytes are V8's
|
||||
* `total_allocated_bytes` and are omitted on a Node.js without that counter.
|
||||
*
|
||||
* TSX_DISABLE_CACHE=1 pnpm --filter @paperclipai/server exec tsx scripts/benchmark-run-event-append.ts
|
||||
*
|
||||
* TSX_DISABLE_CACHE keeps tsx from scanning its shared cache directory while
|
||||
* the first passes run, which otherwise shows up as allocation and CPU here.
|
||||
*
|
||||
* To compare with another revision in the same process, in alternating
|
||||
* passes, write that revision's two modules next to the current ones first:
|
||||
*
|
||||
* git show <base>:server/src/services/heartbeat-run-events.ts \
|
||||
* > server/src/services/heartbeat-run-events.baseline.ts
|
||||
* git show <base>:server/src/services/native-runtime/paperclip-control-plane-port.ts \
|
||||
* | sed 's#"../heartbeat-run-events.js"#"../heartbeat-run-events.baseline.js"#' \
|
||||
* > server/src/services/native-runtime/paperclip-control-plane-port.baseline.ts
|
||||
*
|
||||
* Optional: EVENTS (default 2000 per pass and scenario), PASSES (3 per
|
||||
* implementation), RUNS (8), TEXT_BYTES (96), HISTORY (0 events already
|
||||
* retained in each run). Delete the baseline copies afterwards.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import { PerformanceObserver, performance, type PerformanceEntry } from "node:perf_hooks";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import v8 from "node:v8";
|
||||
import vm from "node:vm";
|
||||
import { eq, sql as drizzleSql } from "drizzle-orm";
|
||||
import { companies, completionContracts, createDb, heartbeatRunEvents, heartbeatRuns, issues,
|
||||
startEmbeddedPostgresTestDatabase } from "../../packages/db/src/index.js";
|
||||
import { createAgentLifecycle } from "../src/services/agent-lifecycle.js";
|
||||
import * as currentEvents from "../src/services/heartbeat-run-events.js";
|
||||
import * as currentPort from "../src/services/native-runtime/paperclip-control-plane-port.js";
|
||||
import type { PrpEvent } from "../src/vendor/paperclip-runner/index.js";
|
||||
|
||||
type Implementation = { label: string; events: typeof currentEvents; port: typeof currentPort };
|
||||
const size = (name: string, fallback: number) => Number(process.env[name] ?? fallback);
|
||||
const EVENTS = size("EVENTS", 2000), PASSES = size("PASSES", 3), RUNS = size("RUNS", 8);
|
||||
const TEXT_BYTES = size("TEXT_BYTES", 96), HISTORY = size("HISTORY", 0);
|
||||
process.env.PAPERCLIP_SECRETS_MASTER_KEY ??= randomBytes(32).toString("base64");
|
||||
|
||||
const baselineEvents = fileURLToPath(new URL("../src/services/heartbeat-run-events.baseline.ts", import.meta.url));
|
||||
const baselinePort = fileURLToPath(new URL("../src/services/native-runtime/paperclip-control-plane-port.baseline.ts", import.meta.url));
|
||||
const implementations: Implementation[] = [{ label: "current", events: currentEvents, port: currentPort }];
|
||||
if (existsSync(baselineEvents) && existsSync(baselinePort)) {
|
||||
implementations.unshift({ label: "baseline", events: await import(baselineEvents), port: await import(baselinePort) });
|
||||
}
|
||||
|
||||
const keepAlive = setInterval(() => {}, 1_000);
|
||||
const temporary = await startEmbeddedPostgresTestDatabase("run-event-append-");
|
||||
const db = createDb(temporary.connectionString);
|
||||
// postgres.js reads this hook for every statement it sends, on every connection.
|
||||
const sent = { statements: 0, control: 0 };
|
||||
(db.$client.options as { debug?: unknown }).debug = (_connection: number, text: string) => {
|
||||
sent.statements += 1;
|
||||
if (/^\s*(begin|commit|rollback|savepoint|release)\b/i.test(text)) sent.control += 1;
|
||||
};
|
||||
// Collections are attributed by their own start time, not by when the
|
||||
// observer delivers them: delivery is asynchronous and can lag the append.
|
||||
let collections: PerformanceEntry[] = [];
|
||||
const gcObserver = new PerformanceObserver(list => { collections.push(...list.getEntries()); });
|
||||
gcObserver.observe({ entryTypes: ["gc"] });
|
||||
function collectionsBetween(start: number, end: number) {
|
||||
collections.push(...gcObserver.takeRecords());
|
||||
const within = collections.filter(entry => entry.startTime >= start && entry.startTime <= end);
|
||||
collections = collections.filter(entry => entry.startTime > end);
|
||||
return { count: within.length, ms: within.reduce((sum, entry) => sum + entry.duration, 0) };
|
||||
}
|
||||
const allocated = () => (v8.getHeapStatistics() as { total_allocated_bytes?: number }).total_allocated_bytes;
|
||||
// A full collection before each pass, without a command-line flag, so that
|
||||
// garbage from the pass before is not collected inside this one.
|
||||
v8.setFlagsFromString("--expose-gc");
|
||||
const collectGarbage = vm.runInNewContext("gc") as () => void;
|
||||
|
||||
try {
|
||||
const [company] = await db.insert(companies).values({ name: "Append", issuePrefix: "APD" }).returning();
|
||||
const agent = { id: randomUUID() };
|
||||
await createAgentLifecycle(db).requestHire(company!.id, { id: agent.id, name: "Native", role: "engineer", status: "idle",
|
||||
adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} }, { runnerResolved: true });
|
||||
const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Streaming task", status: "in_progress",
|
||||
assigneeAgentId: agent.id }).returning();
|
||||
const contractSha = "run-event-append-benchmark";
|
||||
const [contract] = await db.insert(completionContracts).values({ companyId: company!.id, issueId: issue!.id, revision: 1,
|
||||
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "benchmark", risk: "standard",
|
||||
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal",
|
||||
contractJson: { revision: "benchmark", objective: "Benchmark", criteria: [{ id: "objective", requirement: "Append" }] },
|
||||
canonicalSha256: contractSha, createdByActorType: "system", createdByActorId: "benchmark" }).returning();
|
||||
const text = randomBytes(Math.ceil(TEXT_BYTES * 0.75)).toString("base64").slice(0, TEXT_BYTES);
|
||||
|
||||
async function seedHistory(runId: string, sourceInstanceId: string | null) {
|
||||
for (let start = 1; start <= HISTORY; start += 500) {
|
||||
await db.insert(heartbeatRunEvents).values(Array.from({ length: Math.min(500, HISTORY - start + 1) }, (_, index) => ({
|
||||
companyId: company!.id, agentId: agent.id, runId, seq: start + index, eventType: "item.delta",
|
||||
...(sourceInstanceId ? { sourceInstanceId, sourceSeq: start + index, sourceEventId: `${sourceInstanceId}:${start + index}` } : {}),
|
||||
})));
|
||||
}
|
||||
if (HISTORY) await db.update(heartbeatRuns).set({ nextEventSeq: HISTORY + 1 }).where(eq(heartbeatRuns.id, runId));
|
||||
}
|
||||
|
||||
async function nativeRun(implementation: Implementation) {
|
||||
const runId = randomUUID(), sessionId = randomUUID(), runnerId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: company!.id, agentId: agent.id, status: "running",
|
||||
runtimeMode: "native", nativeIssueId: issue!.id, issueId: issue!.id, nativeSessionId: sessionId, runnerInstanceId: runnerId,
|
||||
completionContractId: contract!.id, completionContractSha256: contractSha, contextSnapshot: { issueId: issue!.id } });
|
||||
await seedHistory(runId, runnerId);
|
||||
const identity = { companyId: company!.id, issueId: issue!.id, runId, agentId: agent.id, sessionId };
|
||||
const port = new implementation.port.PaperclipControlPlanePort(db, { ...identity, completionContractId: contract!.id,
|
||||
completionContractSha256: contractSha, sourceInstanceId: runnerId, controlPlaneSourceInstanceId: `control-${runId}` });
|
||||
await port.openRun({ identity, backendKind: "mock", sourceInstanceId: runnerId } as Parameters<typeof port.openRun>[0]);
|
||||
const event = (ordinal: number): PrpEvent => {
|
||||
const sourceSeq = HISTORY + ordinal, step = ordinal % 10;
|
||||
const base = { schema: "paperclip.prp.event.v1" as const, sourceEventId: `${runnerId}:${sourceSeq}`, sourceSeq,
|
||||
sourceInstanceId: runnerId, sourceKind: "runner" as const, runId, normalizedSessionId: sessionId,
|
||||
turnId: "turn-1", schemaVersion: 1 as const, priority: 1, emittedAt: new Date().toISOString() };
|
||||
if (step < 7) return { ...base, itemId: "message-1", eventType: "item.delta", payload: { kind: "agentMessage", text } } as PrpEvent;
|
||||
if (step === 9) return { ...base, itemId: `command-${ordinal}`, eventType: "item.completed",
|
||||
payload: { kind: "commandExecution", item: { type: "command", id: `command-${ordinal}`, output: text } } } as PrpEvent;
|
||||
return { ...base, itemId: `tool-${ordinal}`, eventType: step === 7 ? "tool.execution.started" : "tool.execution.completed",
|
||||
payload: { schema: "paperclip.tool.execution.v1", executionId: `tool-${ordinal - (step === 7 ? 0 : 1)}`, transport: "builtin",
|
||||
operation: "execute", name: "shell", target: null, namespace: null, readOnly: true,
|
||||
status: step === 7 ? "running" : "completed", durationMs: step === 7 ? null : 12, exitCode: step === 7 ? null : 0,
|
||||
progress: null, output: text, outputBytes: text.length, outputTruncated: false,
|
||||
outputDigest: `sha256:${"a".repeat(64)}` } } as PrpEvent;
|
||||
};
|
||||
return { runId, append: async (count: number) => {
|
||||
for (let ordinal = 1; ordinal <= count; ordinal++) {
|
||||
const receipt = await port.appendEvent(event(ordinal));
|
||||
assert.equal(receipt.disposition, "committed");
|
||||
assert.equal(receipt.highestContiguousSourceSeq, HISTORY + ordinal);
|
||||
}
|
||||
} };
|
||||
}
|
||||
|
||||
async function ordinaryRun(implementation: Implementation) {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: company!.id, agentId: agent.id, status: "running" });
|
||||
await seedHistory(runId, null);
|
||||
return { runId, append: async (count: number) => {
|
||||
for (let ordinal = 1; ordinal <= count; ordinal++) {
|
||||
const receipt = await implementation.events.appendHeartbeatRunEvent(db, { companyId: company!.id, runId, agentId: agent.id,
|
||||
eventType: "adapter.output", stream: "stdout", level: "info", message: text, payload: { chunk: ordinal } });
|
||||
assert.equal(receipt.row.seq, HISTORY + ordinal);
|
||||
}
|
||||
} };
|
||||
}
|
||||
|
||||
const scenarios = {
|
||||
"native-stream": async (implementation: Implementation) => [{ run: await nativeRun(implementation), events: EVENTS }],
|
||||
"native-burst": async (implementation: Implementation) => Promise.all(Array.from({ length: RUNS }, async () =>
|
||||
({ run: await nativeRun(implementation), events: Math.ceil(EVENTS / RUNS) }))),
|
||||
ordinary: async (implementation: Implementation) => [{ run: await ordinaryRun(implementation), events: EVENTS }],
|
||||
};
|
||||
|
||||
async function measure(name: keyof typeof scenarios, implementation: Implementation) {
|
||||
const streams = await scenarios[name](implementation);
|
||||
const events = streams.reduce((sum, stream) => sum + stream.events, 0);
|
||||
collectGarbage();
|
||||
const before = { statements: sent.statements, control: sent.control, cpu: process.cpuUsage(), loop: performance.eventLoopUtilization(),
|
||||
bytes: allocated(), at: performance.now() };
|
||||
await Promise.all(streams.map(stream => stream.run.append(stream.events)));
|
||||
const endedAt = performance.now(), wallMs = endedAt - before.at, cpu = process.cpuUsage(before.cpu);
|
||||
const loop = performance.eventLoopUtilization(before.loop), bytes = allocated();
|
||||
const statements = sent.statements - before.statements, control = sent.control - before.control;
|
||||
// Every measurement stops at endedAt, before the stored rows are read
|
||||
// back. Node.js reports a collection from a later immediate, so wait one
|
||||
// turn before draining; only collections that began in the window count.
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
const gc = collectionsBetween(before.at, endedAt);
|
||||
for (const stream of streams) {
|
||||
const rows = await db.select({ seq: heartbeatRunEvents.seq }).from(heartbeatRunEvents)
|
||||
.where(eq(heartbeatRunEvents.runId, stream.run.runId)).orderBy(heartbeatRunEvents.seq);
|
||||
assert.deepEqual(rows.map(row => row.seq), Array.from({ length: HISTORY + stream.events }, (_, index) => index + 1),
|
||||
"Every event is stored once, in order, without a gap");
|
||||
}
|
||||
return { events, statementsPerEvent: statements / events, transactionControlPerEvent: control / events,
|
||||
wallMsPerEvent: wallMs / events, cpuMsPerEvent: (cpu.user + cpu.system) / 1000 / events,
|
||||
mainThreadBusyMsPerEvent: loop.active / events,
|
||||
allocatedKbPerEvent: bytes === undefined || before.bytes === undefined ? null : (bytes - before.bytes) / 1024 / events,
|
||||
gcPausesPer1000Events: gc.count * 1000 / events, gcMsPer1000Events: gc.ms * 1000 / events };
|
||||
}
|
||||
|
||||
const names = Object.keys(scenarios) as Array<keyof typeof scenarios>;
|
||||
// One discarded pass per implementation warms the JIT and the connection pool.
|
||||
for (const implementation of implementations) for (const name of names) await measure(name, implementation);
|
||||
const samples = new Map<string, Array<Awaited<ReturnType<typeof measure>>>>();
|
||||
for (let pass = 0; pass < PASSES; pass++) {
|
||||
// Alternate the order so machine load drifts over both implementations alike.
|
||||
for (const implementation of pass % 2 === 0 ? implementations : [...implementations].reverse()) {
|
||||
for (const name of names) {
|
||||
const key = `${name}/${implementation.label}`;
|
||||
samples.set(key, [...samples.get(key) ?? [], await measure(name, implementation)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!;
|
||||
const round = (value: number) => Number(value.toFixed(3));
|
||||
const results = names.flatMap(name => implementations.map(implementation => {
|
||||
const passes = samples.get(`${name}/${implementation.label}`)!;
|
||||
const field = (key: keyof (typeof passes)[number]) => passes.every(pass => pass[key] !== null)
|
||||
? round(median(passes.map(pass => pass[key] as number))) : null;
|
||||
return { scenario: name, implementation: implementation.label, events: passes[0]!.events,
|
||||
statementsPerEvent: field("statementsPerEvent"), transactionControlPerEvent: field("transactionControlPerEvent"),
|
||||
wallMsPerEvent: field("wallMsPerEvent"), cpuMsPerEvent: field("cpuMsPerEvent"),
|
||||
mainThreadBusyMsPerEvent: field("mainThreadBusyMsPerEvent"), allocatedKbPerEvent: field("allocatedKbPerEvent"),
|
||||
gcPausesPer1000Events: field("gcPausesPer1000Events"), gcMsPer1000Events: field("gcMsPer1000Events") };
|
||||
}));
|
||||
const [{ version }] = await db.execute(drizzleSql`select version() as version`) as unknown as [{ version: string }];
|
||||
console.log(JSON.stringify({ node: process.version, postgres: version.split(" ").slice(0, 2).join(" "),
|
||||
passes: PASSES, runs: RUNS, textBytes: TEXT_BYTES, history: HISTORY, results }, null, 2));
|
||||
} finally {
|
||||
gcObserver.disconnect();
|
||||
clearInterval(keepAlive);
|
||||
await temporary.cleanup();
|
||||
}
|
||||
@@ -115,6 +115,145 @@ describeEmbeddedPostgres("atomic ordinary run events", () => {
|
||||
expect((await readRun(runId)).nextEventSeq).toBe(41);
|
||||
});
|
||||
|
||||
/** Every statement the driver sends, transaction control included. */
|
||||
const sentStatements = async <T>(client: typeof db.$client, action: () => Promise<T>) => {
|
||||
const statements: string[] = [];
|
||||
const options = client.options as { debug?: unknown };
|
||||
const previous = options.debug;
|
||||
options.debug = (_connection: number, text: string) => { statements.push(text.trim().replace(/\s+/g, " ")); };
|
||||
try { return { result: await action(), statements }; } finally { options.debug = previous; }
|
||||
};
|
||||
const nativeEvent = (runId: string, sourceSeq: number, eventType = "item.delta") => ({
|
||||
companyId, agentId, runId, eventType, stream: "system", level: "info", payload: { prpEvent: { sourceSeq } },
|
||||
nativeSource: { sourceInstanceId: "native-writer", sourceEventId: `native-writer:${sourceSeq}`, sourceSeq,
|
||||
protocolSchemaVersion: 1, canonicalPayload: { sourceSeq } },
|
||||
});
|
||||
|
||||
it("appends a native source event with one lock read and one write statement", async () => {
|
||||
const runId = await makeRun();
|
||||
const first = await sentStatements(db.$client, () => appendHeartbeatRunEvent(db, nativeEvent(runId, 1)));
|
||||
// BEGIN, the run lock, the append, COMMIT. The lock is a statement of its
|
||||
// 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[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 });
|
||||
expect(first.result.row.createdAt).toBeInstanceOf(Date);
|
||||
expect(await readEvents(runId)).toEqual([first.result.row]);
|
||||
|
||||
const replay = await sentStatements(db.$client, () => appendHeartbeatRunEvent(db, nativeEvent(runId, 1)));
|
||||
expect(replay.statements).toHaveLength(4);
|
||||
expect(replay.result).toEqual({ row: first.result.row, disposition: "duplicate", highestContiguousSourceSeq: 1 });
|
||||
expect((await readRun(runId)).nextEventSeq).toBe(2);
|
||||
|
||||
// A caller's transaction adds only its SAVEPOINT; a writer check adds nothing.
|
||||
const nested = await sentStatements(db.$client, () => db.transaction(tx =>
|
||||
appendHeartbeatRunEvent(tx as unknown as typeof db, nativeEvent(runId, 2))));
|
||||
expect(nested.statements).toHaveLength(5);
|
||||
let checks = 0;
|
||||
const checked = await sentStatements(db.$client, () => appendHeartbeatRunEvent(db, {
|
||||
...nativeEvent(runId, 3), assertWritable: () => { checks += 1; },
|
||||
}));
|
||||
expect(checked.statements).toHaveLength(4);
|
||||
expect(checks).toBe(2);
|
||||
expect(checked.result).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: 3 });
|
||||
expect((await readEvents(runId)).map(row => [row.seq, row.sourceSeq])).toEqual([[1, 1], [2, 2], [3, 3]]);
|
||||
});
|
||||
|
||||
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();
|
||||
await db.update(heartbeatRuns).set({ nativeIssueId: issue!.id, runtimeMode: "native" }).where(eq(heartbeatRuns.id, runId));
|
||||
const first = await sentStatements(db.$client, () => appendHeartbeatRunEvent(db, nativeEvent(runId, 1, "item.completed")));
|
||||
// BEGIN, lock, duplicate probe, the wake's transaction id, the append, COMMIT.
|
||||
expect(first.statements).toHaveLength(6);
|
||||
const wake = first.statements.findIndex(text => text.includes("pg_current_xact_id"));
|
||||
expect(wake).toBeGreaterThan(0);
|
||||
expect(wake).toBeLessThan(first.statements.findIndex(text => text.includes("insert into heartbeat_run_events")));
|
||||
expect(first.result).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: 1 });
|
||||
const replay = await sentStatements(db.$client, () => appendHeartbeatRunEvent(db, nativeEvent(runId, 1, "item.completed")));
|
||||
expect(replay.statements.some(text => text.includes("pg_current_xact_id"))).toBe(false);
|
||||
expect(replay.result).toEqual({ row: first.result.row, disposition: "duplicate", highestContiguousSourceSeq: 1 });
|
||||
expect(await readEvents(runId)).toEqual([first.result.row]);
|
||||
});
|
||||
|
||||
it("keeps one ordered row per source event when two servers append the same stream", async () => {
|
||||
const runId = await makeRun();
|
||||
const stream = async (connection: typeof db) => {
|
||||
const receipts = [];
|
||||
for (let sourceSeq = 1; sourceSeq <= 40; sourceSeq += 1) {
|
||||
receipts.push(await appendHeartbeatRunEvent(connection, nativeEvent(runId, sourceSeq)));
|
||||
}
|
||||
return receipts;
|
||||
};
|
||||
const [ours, theirs] = await Promise.all([stream(db), stream(otherDb)]);
|
||||
const rows = await readEvents(runId);
|
||||
// Each writer appends in source order, so the stored order is the source order.
|
||||
expect(rows.map(row => [row.seq, row.sourceSeq])).toEqual(Array.from({ length: 40 }, (_, index) => [index + 1, index + 1]));
|
||||
expect((await readRun(runId)).nextEventSeq).toBe(41);
|
||||
for (let index = 0; index < 40; index += 1) {
|
||||
expect([ours[index]!.disposition, theirs[index]!.disposition].sort()).toEqual(["committed", "duplicate"]);
|
||||
for (const receipt of [ours[index]!, theirs[index]!]) {
|
||||
expect(receipt.row).toEqual(rows[index]);
|
||||
// An acknowledgement covers the event and never passes what is stored.
|
||||
expect(receipt.highestContiguousSourceSeq).toBeGreaterThanOrEqual(index + 1);
|
||||
expect(receipt.highestContiguousSourceSeq).toBeLessThanOrEqual(40);
|
||||
}
|
||||
}
|
||||
const conflicting = nativeEvent(runId, 7);
|
||||
await expect(appendHeartbeatRunEvent(otherDb, { ...conflicting,
|
||||
nativeSource: { ...conflicting.nativeSource, canonicalPayload: { sourceSeq: 999 } } }))
|
||||
.rejects.toThrow("native_event_replay_conflict");
|
||||
expect(await readEvents(runId)).toEqual(rows);
|
||||
expect((await readRun(runId)).nextEventSeq).toBe(41);
|
||||
});
|
||||
|
||||
it("leaves no sequence or row behind when a native append fails in the middle of a stream", async () => {
|
||||
const runId = await makeRun();
|
||||
const failing = { ...nativeEvent(runId, 3), message: "force-native-event-failure" };
|
||||
await appendHeartbeatRunEvent(db, nativeEvent(runId, 1));
|
||||
await appendHeartbeatRunEvent(db, nativeEvent(runId, 2));
|
||||
await db.execute(sql`alter table heartbeat_run_events add constraint atomic_native_event_failure
|
||||
check (message is distinct from 'force-native-event-failure') not valid`);
|
||||
try {
|
||||
const before = await readRun(runId);
|
||||
await expect(appendHeartbeatRunEvent(db, failing)).rejects.toThrow();
|
||||
// A writer revoked while its append ran rolls the append back before the commit.
|
||||
let checks = 0;
|
||||
await expect(appendHeartbeatRunEvent(db, { ...nativeEvent(runId, 3),
|
||||
assertWritable: () => { if (++checks === 2) throw new Error("writer revoked"); } })).rejects.toThrow("writer revoked");
|
||||
expect(await readRun(runId)).toEqual(before);
|
||||
expect((await readEvents(runId)).map(row => row.sourceSeq)).toEqual([1, 2]);
|
||||
// The stream continues past the failed event. Later events are stored
|
||||
// and the acknowledgement stays below the gap.
|
||||
expect((await appendHeartbeatRunEvent(db, nativeEvent(runId, 4))).highestContiguousSourceSeq).toBe(2);
|
||||
expect((await appendHeartbeatRunEvent(db, nativeEvent(runId, 5))).highestContiguousSourceSeq).toBe(2);
|
||||
} finally {
|
||||
await db.execute(sql`alter table heartbeat_run_events drop constraint atomic_native_event_failure`);
|
||||
}
|
||||
expect(await appendHeartbeatRunEvent(db, failing)).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: 5 });
|
||||
expect((await readEvents(runId)).map(row => [row.seq, row.sourceSeq])).toEqual([[1, 1], [2, 2], [3, 4], [4, 5], [5, 3]]);
|
||||
expect((await readRun(runId)).nextEventSeq).toBe(6);
|
||||
});
|
||||
|
||||
it("never reuses a retained sequence when history is ahead of the run cursor", async () => {
|
||||
const runId = await makeRun();
|
||||
// An older writer stored events without advancing the run's cursor.
|
||||
await db.insert(heartbeatRunEvents).values([1, 2].map(seq => ({ companyId, agentId, runId, seq, eventType: "stdout",
|
||||
message: `retained-${seq}` })));
|
||||
const retained = await readEvents(runId);
|
||||
for (const input of [nativeEvent(runId, 1), { companyId, agentId, runId, eventType: "stdout", message: "ordinary" }]) {
|
||||
const seq = await appendHeartbeatRunEvent(db, input).then(receipt => receipt.row.seq, () => null);
|
||||
const rows = await readEvents(runId);
|
||||
expect(rows.slice(0, 2)).toEqual(retained);
|
||||
expect(new Set(rows.map(row => row.seq)).size).toBe(rows.length);
|
||||
if (seq === null) expect(rows).toHaveLength(2);
|
||||
else expect(seq).toBeGreaterThan(2);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["native", "retry-exhaustion"])("locks only run bindings for %s events with large run payloads", async (kind) => {
|
||||
const runId = await makeRun();
|
||||
await db.update(heartbeatRuns).set({
|
||||
|
||||
@@ -6,7 +6,7 @@ import { isNativeResponseEvidence, notifyNativeResponsePresentation } from "./na
|
||||
import { isSafeNativeChatProgressEventType } from "./safe-native-chat-progress.js";
|
||||
import { notifyChatNativeProgress } from "./chat-native-progress-notifications.js";
|
||||
import { boundRunIssueIdSql } from "./run-task-binding.js";
|
||||
import { and, asc, eq, getTableColumns, or, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, getTableColumns, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { heartbeatRunEvents, heartbeatRuns } from "@paperclipai/db";
|
||||
import { nativeSha256 } from "./native-runtime/canonical.js";
|
||||
@@ -44,8 +44,19 @@ export interface AppendHeartbeatRunEventInput {
|
||||
* with, an unrelated transaction that holds one of those rows FOR UPDATE.
|
||||
*/
|
||||
runUpdate?: HeartbeatRunEventRunUpdate;
|
||||
/**
|
||||
* Checks that the writer may still write to the run. It runs inside the
|
||||
* append's transaction, before the first statement and again before the
|
||||
* commit; when it throws, the event and its sequence roll back. A writer
|
||||
* passes its check here instead of wrapping the append in a transaction of
|
||||
* its own, which would add a SAVEPOINT round trip to every event.
|
||||
*/
|
||||
assertWritable?: () => void;
|
||||
}
|
||||
|
||||
type NativeSourceEventInput = AppendHeartbeatRunEventInput & Required<Pick<AppendHeartbeatRunEventInput, "nativeSource">>;
|
||||
type RunEventWakes = { recovery: boolean; reassessment: boolean; progress: boolean; response: boolean; retention: boolean };
|
||||
|
||||
export type HeartbeatRunEventRunUpdate = Partial<Pick<typeof heartbeatRuns.$inferInsert,
|
||||
"legacyProcessSettlement" | "processPid" | "processGroupId" | "processHostHash" | "processStartedAt">>;
|
||||
|
||||
@@ -101,175 +112,264 @@ export async function appendHeartbeatRunEvent(
|
||||
const projectsResponse = isNativeResponseEvidence(input.eventType, input.payload?.prpEvent);
|
||||
// Deduplicated receipts return without allocating, so they cannot carry run changes.
|
||||
if (input.runUpdate && (input.nativeSource || input.retryExhaustion)) throw new Error("heartbeat_run_event_run_update_unsupported");
|
||||
if (!input.runUpdate && !input.nativeSource && !input.retryExhaustion && !projectsProgress && !projectsResponse && !projectsReassessment && !projectsRecovery && !projectsRetention) {
|
||||
const allocated = db.$with("allocated_run_event", {}).as(sql`
|
||||
update ${heartbeatRuns}
|
||||
set next_event_seq = ${heartbeatRuns.nextEventSeq} + 1,
|
||||
updated_at = ${sql.param(new Date(), heartbeatRuns.updatedAt)}
|
||||
where ${heartbeatRuns.id} = ${input.runId}
|
||||
and ${heartbeatRuns.companyId} = ${input.companyId}
|
||||
and ${heartbeatRuns.agentId} = ${input.agentId}
|
||||
returning company_id, id as run_id, agent_id, next_event_seq - 1 as seq
|
||||
`);
|
||||
const appended = db.$with("appended_run_event", getTableColumns(heartbeatRunEvents)).as(sql`
|
||||
insert into ${heartbeatRunEvents}
|
||||
const wakes = { recovery: projectsRecovery, reassessment: projectsReassessment, progress: projectsProgress,
|
||||
response: projectsResponse, retention: projectsRetention };
|
||||
if (!input.runUpdate && !input.nativeSource && !input.retryExhaustion && !input.assertWritable && !Object.values(wakes).some(Boolean)) {
|
||||
const [appended] = await db.execute<Record<string, unknown>>(sql`
|
||||
with allocated_run_event as (
|
||||
update heartbeat_runs
|
||||
set next_event_seq = next_event_seq + 1,
|
||||
updated_at = ${sql.param(new Date(), heartbeatRuns.updatedAt)}
|
||||
where id = ${input.runId} and company_id = ${input.companyId} and agent_id = ${input.agentId}
|
||||
returning company_id, id as run_id, agent_id, next_event_seq - 1 as seq
|
||||
)
|
||||
insert into heartbeat_run_events
|
||||
(company_id, run_id, agent_id, seq, event_type, stream, level, color, message, payload)
|
||||
select company_id, run_id, agent_id, seq,
|
||||
${input.eventType}, ${input.stream ?? null}, ${input.level ?? null},
|
||||
${input.color ?? null}, ${input.message ?? null},
|
||||
${sql.param(input.payload ?? null, heartbeatRunEvents.payload)}
|
||||
from ${allocated}
|
||||
from allocated_run_event
|
||||
returning *
|
||||
`);
|
||||
const [row] = await db.with(allocated, appended).select().from(appended);
|
||||
if (!row) throw new Error("heartbeat_run_event_binding_mismatch");
|
||||
return { row, disposition: "committed", highestContiguousSourceSeq: 0 };
|
||||
if (!appended) throw new Error("heartbeat_run_event_binding_mismatch");
|
||||
return { row: decodeRunEventRow(appended), disposition: "committed", highestContiguousSourceSeq: 0 };
|
||||
}
|
||||
return db.transaction(async (tx) => {
|
||||
const run = await tx
|
||||
.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
||||
// Only progress needs the task binding. Other native/recovery events
|
||||
// must not read a potentially large context snapshot to append a log.
|
||||
...(projectsProgress || projectsResponse || projectsReassessment ? { runtimeMode: heartbeatRuns.runtimeMode } : {}),
|
||||
...(projectsProgress ? { issueId: boundRunIssueIdSql() } : {}) })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, input.runId))
|
||||
// Appenders, Stop, recovery and deletion still serialize on this row.
|
||||
// The append never changes key columns, so it must not block foreign
|
||||
// key checks (FOR KEY SHARE) of child rows, such as controller
|
||||
// checkpoints, that are written for the same run while events stream.
|
||||
.for("no key update")
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!run || run.companyId !== input.companyId || run.agentId !== input.agentId) {
|
||||
throw new Error("heartbeat_run_event_binding_mismatch");
|
||||
}
|
||||
|
||||
if (projectsRecovery) await notifyLiveRunRecovery(tx, input);
|
||||
|
||||
if (input.retryExhaustion && !input.nativeSource) {
|
||||
// The run lock also serializes concurrent recovery checks across server
|
||||
// instances. Reusing the receipt must not allocate a sequence or publish
|
||||
// another live event on each scheduler tick.
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(heartbeatRunEvents)
|
||||
.where(and(
|
||||
eq(heartbeatRunEvents.companyId, input.companyId),
|
||||
eq(heartbeatRunEvents.runId, input.runId),
|
||||
eq(heartbeatRunEvents.agentId, input.agentId),
|
||||
eq(heartbeatRunEvents.eventType, "lifecycle"),
|
||||
sql`${heartbeatRunEvents.message} like ${`${RETRY_EXHAUSTION_MESSAGE_PREFIX}%`}`,
|
||||
sql`${heartbeatRunEvents.payload} @> ${JSON.stringify(input.retryExhaustion)}::jsonb`,
|
||||
))
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (existing) {
|
||||
return {
|
||||
row: existing,
|
||||
disposition: "duplicate" as const,
|
||||
highestContiguousSourceSeq: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const sourceHash = input.nativeSource
|
||||
? nativeSha256(input.nativeSource.canonicalPayload)
|
||||
: null;
|
||||
if (input.nativeSource) {
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(heartbeatRunEvents)
|
||||
.where(and(
|
||||
eq(heartbeatRunEvents.runId, input.runId),
|
||||
or(
|
||||
eq(heartbeatRunEvents.sourceEventId, input.nativeSource.sourceEventId),
|
||||
and(
|
||||
eq(heartbeatRunEvents.sourceInstanceId, input.nativeSource.sourceInstanceId),
|
||||
eq(heartbeatRunEvents.sourceSeq, input.nativeSource.sourceSeq),
|
||||
),
|
||||
),
|
||||
))
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (existing) {
|
||||
if (existing.sourcePayloadSha256 !== sourceHash) {
|
||||
throw new HeartbeatRunEventConflictError();
|
||||
}
|
||||
return {
|
||||
row: existing,
|
||||
disposition: "duplicate" as const,
|
||||
highestContiguousSourceSeq: await contiguousCursor(
|
||||
tx as unknown as Db,
|
||||
input.runId,
|
||||
input.nativeSource.sourceInstanceId,
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (projectsReassessment && run.runtimeMode === "native") {
|
||||
await notifyNativeStatusReassessment(tx, { companyId: run.companyId, runId: input.runId });
|
||||
}
|
||||
if (projectsProgress && run.runtimeMode === "native" && run.issueId) {
|
||||
await notifyChatNativeProgress(tx, { companyId: run.companyId, issueId: run.issueId });
|
||||
}
|
||||
if (projectsResponse && run.runtimeMode === "native") {
|
||||
await notifyNativeResponsePresentation(tx, { companyId: run.companyId, runId: input.runId });
|
||||
}
|
||||
if (projectsRetention) await notifyAttentionRetentionWork(tx, { companyId: input.companyId, sourceKind: "failed_run" });
|
||||
const seq = await allocateHeartbeatRunEventSeq(
|
||||
tx as unknown as Db,
|
||||
input.runId,
|
||||
input.runUpdate,
|
||||
);
|
||||
const [row] = await tx.insert(heartbeatRunEvents).values({
|
||||
companyId: input.companyId,
|
||||
runId: input.runId,
|
||||
agentId: input.agentId,
|
||||
seq,
|
||||
eventType: input.eventType,
|
||||
stream: input.stream ?? null,
|
||||
level: input.level ?? null,
|
||||
color: input.color ?? null,
|
||||
message: input.message ?? null,
|
||||
payload: input.payload ?? null,
|
||||
sourceInstanceId: input.nativeSource?.sourceInstanceId ?? null,
|
||||
sourceEventId: input.nativeSource?.sourceEventId ?? null,
|
||||
sourceSeq: input.nativeSource?.sourceSeq ?? null,
|
||||
sourcePayloadSha256: sourceHash,
|
||||
protocolSchemaVersion: input.nativeSource?.protocolSchemaVersion ?? null,
|
||||
}).returning();
|
||||
if (!row) throw new Error("heartbeat_run_event_not_persisted");
|
||||
return {
|
||||
row,
|
||||
disposition: "committed" as const,
|
||||
highestContiguousSourceSeq: input.nativeSource
|
||||
? await contiguousCursor(
|
||||
tx as unknown as Db,
|
||||
input.runId,
|
||||
input.nativeSource.sourceInstanceId,
|
||||
)
|
||||
: 0,
|
||||
};
|
||||
input.assertWritable?.();
|
||||
const receipt = input.nativeSource
|
||||
? await appendNativeSourceEvent(tx as unknown as Db, input as NativeSourceEventInput, wakes)
|
||||
: await appendLockedEvent(tx as unknown as Db, input, wakes);
|
||||
input.assertWritable?.();
|
||||
return receipt;
|
||||
});
|
||||
}
|
||||
|
||||
async function contiguousCursor(db: Db, runId: string, sourceInstanceId: string): Promise<number> {
|
||||
const scope = and(
|
||||
eq(heartbeatRunEvents.runId, runId),
|
||||
eq(heartbeatRunEvents.sourceInstanceId, sourceInstanceId),
|
||||
sql`${heartbeatRunEvents.sourceSeq} >= 1`,
|
||||
);
|
||||
const runEventColumns = Object.entries(getTableColumns(heartbeatRunEvents));
|
||||
|
||||
/**
|
||||
* Decodes a `returning *` row the way a Drizzle select of the table does. The
|
||||
* statements of an event stream are fixed SQL text: building the same
|
||||
* statement through the query builder for every event costs more CPU and
|
||||
* garbage than running it.
|
||||
*/
|
||||
function decodeRunEventRow(raw: Record<string, unknown>): typeof heartbeatRunEvents.$inferSelect {
|
||||
const row: Record<string, unknown> = {};
|
||||
for (const [key, column] of runEventColumns) {
|
||||
const value = raw[column.name];
|
||||
row[key] = value === null || value === undefined ? null : column.mapFromDriverValue(value);
|
||||
}
|
||||
return row as typeof heartbeatRunEvents.$inferSelect;
|
||||
}
|
||||
|
||||
/**
|
||||
* A native source event: one lock read, then one statement that finds a
|
||||
* replayed event or reserves the sequence and inserts, and reads how much of
|
||||
* the source is retained. The lock must stay a statement of its own. A
|
||||
* statement that waits for the run lock keeps the snapshot it took before
|
||||
* waiting, so it would not see an event the lock holder had just committed.
|
||||
*/
|
||||
async function appendNativeSourceEvent(
|
||||
tx: Db,
|
||||
input: NativeSourceEventInput,
|
||||
wakes: RunEventWakes,
|
||||
): Promise<AppendHeartbeatRunEventResult> {
|
||||
const source = input.nativeSource;
|
||||
// Appenders, Stop, recovery and deletion still serialize on this row.
|
||||
// The append never changes key columns, so it must not block foreign
|
||||
// key checks (FOR KEY SHARE) of child rows, such as controller
|
||||
// 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()}${
|
||||
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");
|
||||
}
|
||||
if (wakes.recovery) await notifyLiveRunRecovery(tx, input);
|
||||
|
||||
const sourceHash = nativeSha256(source.canonicalPayload);
|
||||
const replayed = sql`run_id = ${input.runId} and (source_event_id = ${source.sourceEventId}
|
||||
or (source_instance_id = ${source.sourceInstanceId} and source_seq = ${source.sourceSeq}))`;
|
||||
const native = run.runtime_mode === "native";
|
||||
const reassessment = wakes.reassessment && native, progress = wakes.progress && native && run.issue_id;
|
||||
const response = wakes.response && native;
|
||||
if (reassessment || progress || response || wakes.retention) {
|
||||
// A wake is registered before the write it announces, and a replayed
|
||||
// event registers none. So these events look for their replay first.
|
||||
const [existing] = await tx.execute<Record<string, unknown>>(sql`select * from heartbeat_run_events where ${replayed} limit 1`);
|
||||
if (existing) {
|
||||
const row = decodeRunEventRow(existing);
|
||||
if (row.sourcePayloadSha256 !== sourceHash) throw new HeartbeatRunEventConflictError();
|
||||
return { row, disposition: "duplicate", highestContiguousSourceSeq: 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 });
|
||||
if (progress) await notifyChatNativeProgress(tx, { companyId: run.company_id, issueId: progress });
|
||||
if (response) await notifyNativeResponsePresentation(tx, { companyId: run.company_id, runId: input.runId });
|
||||
if (wakes.retention) await notifyAttentionRetentionWork(tx, { companyId: input.companyId, sourceKind: "failed_run" });
|
||||
}
|
||||
|
||||
// `existing` and `retained` read the snapshot from before this statement's
|
||||
// own insert. A replayed event reserves no sequence and inserts nothing.
|
||||
const [result] = await tx.execute<Record<string, unknown>>(sql`
|
||||
with existing as (
|
||||
select * from heartbeat_run_events where ${replayed} limit 1
|
||||
), allocated as (
|
||||
update heartbeat_runs
|
||||
set next_event_seq = next_event_seq + 1,
|
||||
updated_at = ${sql.param(new Date(), heartbeatRuns.updatedAt)}
|
||||
where id = ${input.runId} and not exists (select 1 from existing)
|
||||
returning next_event_seq - 1 as seq
|
||||
), appended as (
|
||||
insert into heartbeat_run_events
|
||||
(company_id, run_id, agent_id, seq, event_type, stream, level, color, message, payload,
|
||||
source_instance_id, source_event_id, source_seq, source_payload_sha256, protocol_schema_version)
|
||||
select ${input.companyId}::uuid, ${input.runId}::uuid, ${input.agentId}::uuid, seq,
|
||||
${input.eventType}::text, ${input.stream ?? null}::text, ${input.level ?? null}::text,
|
||||
${input.color ?? null}::text, ${input.message ?? null}::text,
|
||||
${sql.param(input.payload ?? null, heartbeatRunEvents.payload)}::jsonb,
|
||||
${source.sourceInstanceId}::text, ${source.sourceEventId}::text, ${source.sourceSeq}::bigint,
|
||||
${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
|
||||
)
|
||||
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
|
||||
`);
|
||||
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;
|
||||
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),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every other event that needs the run lock: receipts, run changes and wakes. */
|
||||
async function appendLockedEvent(
|
||||
tx: Db,
|
||||
input: AppendHeartbeatRunEventInput,
|
||||
wakes: RunEventWakes,
|
||||
): Promise<AppendHeartbeatRunEventResult> {
|
||||
const run = await tx
|
||||
.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
||||
// Only progress needs the task binding. Other native/recovery events
|
||||
// must not read a potentially large context snapshot to append a log.
|
||||
...(wakes.progress || wakes.response || wakes.reassessment ? { runtimeMode: heartbeatRuns.runtimeMode } : {}),
|
||||
...(wakes.progress ? { issueId: boundRunIssueIdSql() } : {}) })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, input.runId))
|
||||
// Appenders, Stop, recovery and deletion still serialize on this row.
|
||||
// The append never changes key columns, so it must not block foreign
|
||||
// key checks (FOR KEY SHARE) of child rows, such as controller
|
||||
// checkpoints, that are written for the same run while events stream.
|
||||
.for("no key update")
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!run || run.companyId !== input.companyId || run.agentId !== input.agentId) {
|
||||
throw new Error("heartbeat_run_event_binding_mismatch");
|
||||
}
|
||||
|
||||
if (wakes.recovery) await notifyLiveRunRecovery(tx, input);
|
||||
|
||||
if (input.retryExhaustion) {
|
||||
// The run lock also serializes concurrent recovery checks across server
|
||||
// instances. Reusing the receipt must not allocate a sequence or publish
|
||||
// another live event on each scheduler tick.
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(heartbeatRunEvents)
|
||||
.where(and(
|
||||
eq(heartbeatRunEvents.companyId, input.companyId),
|
||||
eq(heartbeatRunEvents.runId, input.runId),
|
||||
eq(heartbeatRunEvents.agentId, input.agentId),
|
||||
eq(heartbeatRunEvents.eventType, "lifecycle"),
|
||||
sql`${heartbeatRunEvents.message} like ${`${RETRY_EXHAUSTION_MESSAGE_PREFIX}%`}`,
|
||||
sql`${heartbeatRunEvents.payload} @> ${JSON.stringify(input.retryExhaustion)}::jsonb`,
|
||||
))
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (existing) {
|
||||
return {
|
||||
row: existing,
|
||||
disposition: "duplicate" as const,
|
||||
highestContiguousSourceSeq: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (wakes.reassessment && run.runtimeMode === "native") {
|
||||
await notifyNativeStatusReassessment(tx, { companyId: run.companyId, runId: input.runId });
|
||||
}
|
||||
if (wakes.progress && run.runtimeMode === "native" && run.issueId) {
|
||||
await notifyChatNativeProgress(tx, { companyId: run.companyId, issueId: run.issueId });
|
||||
}
|
||||
if (wakes.response && run.runtimeMode === "native") {
|
||||
await notifyNativeResponsePresentation(tx, { companyId: run.companyId, runId: input.runId });
|
||||
}
|
||||
if (wakes.retention) await notifyAttentionRetentionWork(tx, { companyId: input.companyId, sourceKind: "failed_run" });
|
||||
const seq = await allocateHeartbeatRunEventSeq(tx, input.runId, input.runUpdate);
|
||||
const [row] = await tx.insert(heartbeatRunEvents).values({
|
||||
companyId: input.companyId,
|
||||
runId: input.runId,
|
||||
agentId: input.agentId,
|
||||
seq,
|
||||
eventType: input.eventType,
|
||||
stream: input.stream ?? null,
|
||||
level: input.level ?? null,
|
||||
color: input.color ?? null,
|
||||
message: input.message ?? null,
|
||||
payload: input.payload ?? null,
|
||||
}).returning();
|
||||
if (!row) throw new Error("heartbeat_run_event_not_persisted");
|
||||
return { row, disposition: "committed" as const, highestContiguousSourceSeq: 0 };
|
||||
}
|
||||
|
||||
const sourceEvents = (runId: string, sourceInstanceId: string) => and(
|
||||
eq(heartbeatRunEvents.runId, runId),
|
||||
eq(heartbeatRunEvents.sourceInstanceId, sourceInstanceId),
|
||||
sql`${heartbeatRunEvents.sourceSeq} >= 1`,
|
||||
);
|
||||
|
||||
/** How many events of one source a run retains, and the highest source sequence among them. */
|
||||
async function retainedSourceRange(db: Db, runId: string, sourceInstanceId: string) {
|
||||
const [range] = await db
|
||||
.select({
|
||||
count: sql<number>`count(*)`.mapWith(Number),
|
||||
max: sql<number | null>`max(${heartbeatRunEvents.sourceSeq})`.mapWith(Number),
|
||||
})
|
||||
.from(heartbeatRunEvents)
|
||||
.where(scope);
|
||||
if (!range || !range.count) return 0;
|
||||
.where(sourceEvents(runId, sourceInstanceId));
|
||||
return { count: range?.count ?? 0, max: range?.max ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest source sequence retained without a gap before it. A stream that
|
||||
* arrives in order needs no read: its count equals its highest sequence.
|
||||
*/
|
||||
async function contiguousCursor(
|
||||
db: Db,
|
||||
runId: string,
|
||||
sourceInstanceId: string,
|
||||
range: { count: number; max: number },
|
||||
): Promise<number> {
|
||||
if (!range.count) return 0;
|
||||
if (range.max === range.count) return range.count;
|
||||
const scope = sourceEvents(runId, sourceInstanceId);
|
||||
const [first] = await db
|
||||
.select({ sourceSeq: heartbeatRunEvents.sourceSeq })
|
||||
.from(heartbeatRunEvents)
|
||||
|
||||
@@ -838,6 +838,72 @@ describe("PaperclipControlPlanePort conformance", () => {
|
||||
expect(await readTaskPanelActivations(db, randomUUID(), identity.runId)).toEqual([]);
|
||||
});
|
||||
|
||||
it("persists each streamed event in one transaction of two statements and rolls back a revoked writer", async () => {
|
||||
const identity = { ...CONTROL_PLANE_CONFORMANCE_OPEN.identity, runId: randomUUID(), sessionId: randomUUID() };
|
||||
const runnerId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: identity.runId, companyId: identity.companyId, agentId: identity.agentId,
|
||||
status: "running", runtimeMode: "native", nativeIssueId: identity.issueId,
|
||||
nativeSessionId: identity.sessionId, runnerInstanceId: runnerId,
|
||||
completionContractId: contractId, completionContractSha256: contractSha,
|
||||
contextSnapshot: { issueId: identity.issueId },
|
||||
});
|
||||
let active = true;
|
||||
const committed: number[] = [];
|
||||
const port = new PaperclipControlPlanePort(db, {
|
||||
...identity, completionContractId: contractId, completionContractSha256: contractSha,
|
||||
sourceInstanceId: runnerId, controlPlaneSourceInstanceId: `stream-${identity.runId}`,
|
||||
}, {
|
||||
assertControllerActive: () => { if (!active) throw new Error("controller_revoked"); },
|
||||
onCommittedEvent: async (_event, cursor) => { committed.push(cursor); },
|
||||
});
|
||||
await port.openRun({ identity, backendKind: "mock", sourceInstanceId: runnerId });
|
||||
const emittedAt = new Date().toISOString();
|
||||
const delta = (sourceSeq: number): PrpEvent => ({
|
||||
schema: "paperclip.prp.event.v1", sourceEventId: `${runnerId}:${sourceSeq}`, sourceSeq,
|
||||
sourceInstanceId: runnerId, sourceKind: "runner", runId: identity.runId,
|
||||
normalizedSessionId: identity.sessionId, turnId: "stream-turn", itemId: "stream-message",
|
||||
eventType: "item.delta", schemaVersion: 1, priority: 1, emittedAt,
|
||||
payload: { kind: "agentMessage", text: `chunk ${sourceSeq}` },
|
||||
});
|
||||
// Every statement the driver sends, transaction control included.
|
||||
const options = db.$client.options as { debug?: unknown };
|
||||
const statements: string[] = [];
|
||||
options.debug = (_connection: number, text: string) => { statements.push(text.trim().replace(/\s+/g, " ")); };
|
||||
try {
|
||||
for (const sourceSeq of [1, 2, 3]) {
|
||||
statements.length = 0;
|
||||
await expect(port.appendEvent(delta(sourceSeq))).resolves.toEqual({
|
||||
cursor: sourceSeq, highestContiguousSourceSeq: sourceSeq, disposition: "committed",
|
||||
});
|
||||
// BEGIN, the run lock, the append, COMMIT: no SAVEPOINT and no separate
|
||||
// replay, sequence, insert or cursor statement.
|
||||
expect(statements).toHaveLength(4);
|
||||
expect(statements.filter(text => /^(begin|commit)/i.test(text))).toHaveLength(2);
|
||||
}
|
||||
statements.length = 0;
|
||||
await expect(port.appendEvent(delta(2))).resolves.toEqual({ cursor: 2, highestContiguousSourceSeq: 3, disposition: "duplicate" });
|
||||
expect(statements).toHaveLength(4);
|
||||
// The controller loses the run while its append is in flight: the lock
|
||||
// read is the first statement after the opening check.
|
||||
options.debug = (_connection: number, text: string) => { if (/for no key update$/.test(text.trim())) active = false; };
|
||||
await expect(port.appendEvent(delta(4))).rejects.toThrow("controller_revoked");
|
||||
} finally { options.debug = undefined; }
|
||||
active = true;
|
||||
expect(committed).toEqual([1, 2, 3]);
|
||||
const stored = () => db.select({ seq: heartbeatRunEvents.seq, sourceSeq: heartbeatRunEvents.sourceSeq })
|
||||
.from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, identity.runId)).orderBy(asc(heartbeatRunEvents.seq));
|
||||
expect(await stored()).toEqual([1, 2, 3].map(seq => ({ seq, sourceSeq: seq })));
|
||||
// The rolled-back event took no sequence: a replacement writes it next.
|
||||
const replacement = new PaperclipControlPlanePort(db, {
|
||||
...identity, completionContractId: contractId, completionContractSha256: contractSha,
|
||||
sourceInstanceId: runnerId, controlPlaneSourceInstanceId: `stream-${identity.runId}`,
|
||||
});
|
||||
await replacement.openRun({ identity, backendKind: "mock", sourceInstanceId: runnerId });
|
||||
await expect(replacement.appendEvent(delta(4))).resolves.toEqual({ cursor: 4, highestContiguousSourceSeq: 4, disposition: "committed" });
|
||||
expect(await stored()).toEqual([1, 2, 3, 4].map(seq => ({ seq, sourceSeq: seq })));
|
||||
});
|
||||
|
||||
it("omits API credentials from persisted tool events and checkpoints without changing wire results", async () => {
|
||||
const identity = { ...CONTROL_PLANE_CONFORMANCE_OPEN.identity, runId: randomUUID(), sessionId: randomUUID() };
|
||||
const runnerId = randomUUID();
|
||||
|
||||
@@ -411,28 +411,24 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
|
||||
event = redactRunnerApiEvent(event);
|
||||
const observerKey = JSON.stringify([event.sourceInstanceId, event.sourceEventId]);
|
||||
const pendingObservation = this.#deferredEventObservers.get(observerKey);
|
||||
const persisted = await this.#db.transaction(async tx => {
|
||||
this.#assertActive(options);
|
||||
const receipt = await appendHeartbeatRunEvent(tx as unknown as Db, {
|
||||
companyId: this.#binding.companyId,
|
||||
runId: this.#binding.runId,
|
||||
agentId: this.#binding.agentId,
|
||||
eventType: event.eventType,
|
||||
stream: "system",
|
||||
level: event.eventType.includes("failed") ? "error" : "info",
|
||||
payload: { prpEvent: event as unknown as Record<string, unknown> },
|
||||
nativeSource: {
|
||||
sourceInstanceId: event.sourceInstanceId,
|
||||
sourceEventId: event.sourceEventId,
|
||||
sourceSeq: event.sourceSeq,
|
||||
protocolSchemaVersion: event.schemaVersion,
|
||||
canonicalPayload: event as unknown as Record<string, unknown>,
|
||||
},
|
||||
});
|
||||
// The nested append has no publication side effects. Revocation rolls
|
||||
// back its event and sequence allocation before the outer commit.
|
||||
this.#assertActive(options);
|
||||
return receipt;
|
||||
const persisted = await appendHeartbeatRunEvent(this.#db, {
|
||||
companyId: this.#binding.companyId,
|
||||
runId: this.#binding.runId,
|
||||
agentId: this.#binding.agentId,
|
||||
eventType: event.eventType,
|
||||
stream: "system",
|
||||
level: event.eventType.includes("failed") ? "error" : "info",
|
||||
payload: { prpEvent: event as unknown as Record<string, unknown> },
|
||||
nativeSource: {
|
||||
sourceInstanceId: event.sourceInstanceId,
|
||||
sourceEventId: event.sourceEventId,
|
||||
sourceSeq: event.sourceSeq,
|
||||
protocolSchemaVersion: event.schemaVersion,
|
||||
canonicalPayload: event as unknown as Record<string, unknown>,
|
||||
},
|
||||
// The append has no publication side effects. Revocation rolls back
|
||||
// its event and sequence allocation before the append commits.
|
||||
assertWritable: () => this.#assertActive(options),
|
||||
});
|
||||
this.#assertActive(options);
|
||||
const persistenceEndedAt = persistenceStartedAt + performance.now() - persistenceClock;
|
||||
|
||||
Reference in new issue
Block a user