Merge current master into Photon sleep delivery

Preserve all owned Photon changes and current master recovery, retention, instruction backoff, migration and committed shutdown-handoff behavior. All incoming physical paths are disjoint from owned paths. Current owning producers and assembled acceptance follow this source integration.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-11-14 03:03:49 -06:00
commit f14df19e6e
62 files changed
+2584 -361

No files matched your search

+10
View File
@@ -507,6 +507,16 @@ indexes also serve the comment and delivery `on delete set null` actions. Issue
lists share one external review-wait read per issue between the review and
blocked-inbox attention maps.
Migration 0487 builds two partial `heartbeat_runs` indexes concurrently for the
settled-process recovery queue. `heartbeat_runs_settled_process_identity_idx`
keys settled native runs that still hold a process identity by
`process_host_hash`, company and id. Each server reads only the runs recorded in
its own PID space, sandbox runs (`remote`) and rows saved before the hash, so
finished runs from replaced containers are not read at all.
`heartbeat_runs_pending_api_stop_idx` keys cancelled `cursor_cloud_api` runs
whose Stop is still `requested`. Without them, the queue reads every finished
run of a company on each hint.
Migration 0476 builds `agent_wakeup_requests_company_run_idx` concurrently. It
keys wake requests by company and `run_id`, partial on a non-null run. Queued-run
dispatch finds the person wakes that joined or were adopted by each queued run
@@ -276,6 +276,23 @@ turn, so memory per session counts for idle agents too.
| 1g | Size the shared limiters (log uploads, checkpoint pool, recovery pass) from the active run count | no fixed slot count below the run count |
| 1h | Keep one frozen, parsed tool catalog per catalog hash and company, shared by the sessions that use it, in place of two private copies per session (`assigned-mcp-tools.ts:146`) | server memory per live or warm session from about 5–11 MB (measured at 400–800 tools) to near zero; at 1,000 agents that is 5–11 GB |
### Background recovery sweeps
Run events used to send a company recovery hint, so the stranded-assignment
and assigned-work queues re-checked every open task of the company on each
run event (#21552). Local fixture: 1,500 open tasks, 60 agents, process agents
that fail at once, 180-second window that includes one 5-minute backstop pass.
| Build | Runs created (/s) | Stranded checks per window | Assigned-work checks per window | `agent_task_sessions` reads (/s) | Statements (/s) |
| --- | --- | --- | --- | --- | --- |
| Before #21552 (54c3616ad9) | 1.09 | 4,327 | 245 | 26.5 | 1,431 |
| #21552 at dcd170e29f | 1.00 | 702 | 276 | 7.2 | 1,060 |
| master at 340157d1d6 | 0.24 | 330 | 72 | 2.5 | 409 |
The master row has much less run churn than the earlier rows, so compare the
per-window totals with care. In that window the one backstop pass loaded 260
tasks into the stranded queue; run events loaded 147.
### Phase 2: several controller processes (target: 1,000)
| # | Change |
+1
View File
@@ -748,6 +748,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
"0472_runner_api_capture_pending_deletes.sql",
"0476_wakeup_request_run_index.sql",
"0486_heartbeat_runs_company_finished_index.sql",
"0487_heartbeat_runs_settled_process_indexes.sql",
"0469_zippy_photon.sql",
@@ -0,0 +1,5 @@
CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_settled_process_identity_idx" ON "heartbeat_runs" USING btree ("process_host_hash","company_id","id") WHERE "heartbeat_runs"."runtime_mode" = 'native' and "heartbeat_runs"."status" in ('failed', 'cancelled', 'timed_out', 'interrupted')
and "heartbeat_runs"."finished_at" is not null
and ("heartbeat_runs"."process_pid" is not null or "heartbeat_runs"."process_group_id" is not null or "heartbeat_runs"."process_started_at" is not null);--> statement-breakpoint
CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_pending_api_stop_idx" ON "heartbeat_runs" USING btree ("company_id","id") WHERE "heartbeat_runs"."status" = 'cancelled' and "heartbeat_runs"."driver_kind" = 'cursor_cloud_api'
and ("heartbeat_runs"."result_json"->'executionCancellation'->>'state') = 'requested';
@@ -1,6 +1,6 @@
{
"id": "8b353a38-62df-4834-be55-7e9ebefad5c5",
"prevId": "41eacc6a-6eab-4f01-965a-62aa0cd6778f",
"id": "73c8fa97-70fc-49c0-804e-e49cfdffd156",
"prevId": "0c3e74be-7936-4c97-9798-505daf53c16b",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -6582,6 +6582,111 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.automatic_run_brakes": {
"name": "automatic_run_brakes",
"schema": "",
"columns": {
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": true,
"notNull": true
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'closed'"
},
"reason": {
"name": "reason",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'{}'::jsonb"
},
"state_changed_at": {
"name": "state_changed_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"opened_at": {
"name": "opened_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"next_probe_at": {
"name": "next_probe_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"probe_run_id": {
"name": "probe_run_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"probe_successes": {
"name": "probe_successes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"release_window_started_at": {
"name": "release_window_started_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"release_window_starts": {
"name": "release_window_starts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"next_creation_at": {
"name": "next_creation_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"automatic_run_brakes_company_id_companies_id_fk": {
"name": "automatic_run_brakes_company_id_companies_id_fk",
"tableFrom": "automatic_run_brakes",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.board_api_keys": {
"name": "board_api_keys",
"schema": "",
@@ -36029,6 +36134,78 @@
"method": "btree",
"with": {}
},
"heartbeat_runs_company_finished_idx": {
"name": "heartbeat_runs_company_finished_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "finished_at",
"isExpression": false,
"asc": false,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"heartbeat_runs\".\"finished_at\" is not null",
"concurrently": true,
"method": "btree",
"with": {}
},
"heartbeat_runs_settled_process_identity_idx": {
"name": "heartbeat_runs_settled_process_identity_idx",
"columns": [
{
"expression": "process_host_hash",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"heartbeat_runs\".\"runtime_mode\" = 'native' and \"heartbeat_runs\".\"status\" in ('failed', 'cancelled', 'timed_out', 'interrupted')\n and \"heartbeat_runs\".\"finished_at\" is not null\n and (\"heartbeat_runs\".\"process_pid\" is not null or \"heartbeat_runs\".\"process_group_id\" is not null or \"heartbeat_runs\".\"process_started_at\" is not null)",
"concurrently": true,
"method": "btree",
"with": {}
},
"heartbeat_runs_pending_api_stop_idx": {
"name": "heartbeat_runs_pending_api_stop_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"heartbeat_runs\".\"status\" = 'cancelled' and \"heartbeat_runs\".\"driver_kind\" = 'cursor_cloud_api'\n and (\"heartbeat_runs\".\"result_json\"->'executionCancellation'->>'state') = 'requested'",
"concurrently": true,
"method": "btree",
"with": {}
},
"heartbeat_runs_company_created_at_desc_idx": {
"name": "heartbeat_runs_company_created_at_desc_idx",
"columns": [
@@ -59607,6 +59784,12 @@
"primaryKey": false,
"notNull": false
},
"progress": {
"name": "progress",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
@@ -60113,6 +60296,277 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_mcp_elicitations": {
"name": "tool_mcp_elicitations",
"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
},
"issue_id": {
"name": "issue_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"agent_id": {
"name": "agent_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"run_id": {
"name": "run_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"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
},
"catalog_tool_name": {
"name": "catalog_tool_name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"call_identity": {
"name": "call_identity",
"type": "text",
"primaryKey": false,
"notNull": true
},
"era": {
"name": "era",
"type": "text",
"primaryKey": false,
"notNull": true
},
"sealed_request_state": {
"name": "sealed_request_state",
"type": "text",
"primaryKey": false,
"notNull": false
},
"questions": {
"name": "questions",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
"arguments_identity": {
"name": "arguments_identity",
"type": "text",
"primaryKey": false,
"notNull": true
},
"dedupe_key": {
"name": "dedupe_key",
"type": "text",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true
},
"claimed_until": {
"name": "claimed_until",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"sent_at": {
"name": "sent_at",
"type": "timestamp with time zone",
"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_elicitations_call_idx": {
"name": "tool_mcp_elicitations_call_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "issue_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "call_identity",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "status",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_elicitations_invocation_idx": {
"name": "tool_mcp_elicitations_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_elicitations_waiting_uq": {
"name": "tool_mcp_elicitations_waiting_uq",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "issue_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "dedupe_key",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"where": "\"tool_mcp_elicitations\".\"status\" = 'waiting'",
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tool_mcp_elicitations_company_id_companies_id_fk": {
"name": "tool_mcp_elicitations_company_id_companies_id_fk",
"tableFrom": "tool_mcp_elicitations",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_elicitations_invocation_id_tool_invocations_id_fk": {
"name": "tool_mcp_elicitations_invocation_id_tool_invocations_id_fk",
"tableFrom": "tool_mcp_elicitations",
"tableTo": "tool_invocations",
"columnsFrom": [
"invocation_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_elicitations_connection_id_tool_connections_id_fk": {
"name": "tool_mcp_elicitations_connection_id_tool_connections_id_fk",
"tableFrom": "tool_mcp_elicitations",
"tableTo": "tool_connections",
"columnsFrom": [
"connection_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_mcp_gateway_tokens": {
"name": "tool_mcp_gateway_tokens",
"schema": "",
+7
View File
@@ -3396,6 +3396,13 @@
"when": 1794623177597,
"tag": "0486_heartbeat_runs_company_finished_index",
"breakpoints": true
},
{
"idx": 487,
"version": "7",
"when": 1794639469687,
"tag": "0487_heartbeat_runs_settled_process_indexes",
"breakpoints": true
}
]
}
+10
View File
@@ -250,6 +250,16 @@ export const heartbeatRuns = pgTable(
),
companyFinishedIdx: index("heartbeat_runs_company_finished_idx").on(table.companyId, table.finishedAt.desc())
.where(sql`${table.finishedAt} is not null`).concurrently(),
settledProcessIdentityIdx: index("heartbeat_runs_settled_process_identity_idx")
.on(table.processHostHash, table.companyId, table.id)
.where(sql`${table.runtimeMode} = 'native' and ${table.status} in ('failed', 'cancelled', 'timed_out', 'interrupted')
and ${table.finishedAt} is not null
and (${table.processPid} is not null or ${table.processGroupId} is not null or ${table.processStartedAt} is not null)`)
.concurrently(),
pendingApiStopIdx: index("heartbeat_runs_pending_api_stop_idx").on(table.companyId, table.id)
.where(sql`${table.status} = 'cancelled' and ${table.driverKind} = 'cursor_cloud_api'
and (${table.resultJson}->'executionCancellation'->>'state') = 'requested'`)
.concurrently(),
companyCreatedAtDescIdx: index("heartbeat_runs_company_created_at_desc_idx").on(
table.companyId,
table.createdAt.desc(),
@@ -0,0 +1,240 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { createHash, randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import { agents, agentInstructionWorkingCopies, authUsers, companies, createDb, heartbeatRuns } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
import {
agentInstructionWorkingCopyService,
instructionCopyRetryAt,
INSTRUCTION_COPY_MAX_RETRY_MS,
INSTRUCTION_COPY_RETRY_MS,
} from "../services/agent-instruction-working-copies.js";
import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_INSTRUCTION_COPY_TEST_DATABASE_URL");
const AGENT_FILES = "paperclip.agent-files.v1";
const MINUTE = 60_000, HOUR = 60 * MINUTE, DAY = 24 * HOUR;
const CONTENT = "# Instructions\n";
const CONTENT_HASH = createHash("sha256").update(CONTENT).digest("hex");
describe("instruction working copies that cannot make progress", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let meter: ReturnType<typeof meterDatabaseStatements>;
let home: string;
let companyId: string, agentId: string, userId: string;
const previousHome = process.env.PAPERCLIP_HOME;
beforeAll(async () => {
home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "instruction-copy-backoff-")));
process.env.PAPERCLIP_HOME = home;
if (!external) database = await startEmbeddedPostgresTestDatabase("instruction-copy-backoff-db-");
const url = external ?? database.connectionString;
db = createDb(url, { idleTimeoutSeconds: 0, maxLifetimeSeconds: 20 * 24 * 3600, connectTimeoutSeconds: 3600 });
meter = meterDatabaseStatements(db, url);
}, 90_000);
afterAll(async () => {
meter?.uninstall();
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
await db?.$client.end({ timeout: 1 });
await database?.cleanup();
if (home) await fs.rm(home, { recursive: true, force: true });
});
beforeEach(async () => {
companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Backoff", issuePrefix: randomUUID().slice(0, 8) });
await db.insert(authUsers).values({ id: userId, name: "Editor", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
await db.insert(agents).values({ id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed" } });
});
afterEach(async () => {
vi.useRealTimers(); vi.restoreAllMocks();
await db.delete(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.companyId, companyId));
});
const clock = () => vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
const coordinator = () => createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: () => {} });
async function runs(count: number, finishedAgo: number, runtimeMode = "native") {
const ids = Array.from({ length: count }, () => randomUUID());
const finishedAt = new Date(Date.now() - finishedAgo);
await db.insert(heartbeatRuns).values(ids.map(id => ({ id, companyId, agentId, status: "failed", runtimeMode,
invocationSource: "on_demand", responsibleUserId: userId, startedAt: finishedAt, finishedAt })));
return ids;
}
const entryPath = (runId: string) => path.join(home, "work", runId, ".paperclip-runtime", `instruction-edits-${runId}`, "instructions", "AGENTS.md");
async function unprovenStops(count: number, finishedAgo: number) {
const ids = await runs(count, finishedAgo);
await db.insert(agentInstructionWorkingCopies).values(ids.map(runId => ({ runId, companyId, agentId, responsibleUserId: userId,
entryFile: "AGENTS.md", baseHash: CONTENT_HASH, localRoot: path.dirname(entryPath(runId)), executionRoot: path.dirname(entryPath(runId)),
location: "local", state: "prepared" })));
for (const runId of ids) {
await fs.mkdir(path.dirname(entryPath(runId)), { recursive: true });
await fs.writeFile(entryPath(runId), CONTENT);
}
return ids;
}
async function stuckCleanups(count: number, options: { lockRoot?: boolean } = {}) {
const ids = await runs(count, 0, "legacy");
if (options.lockRoot !== false) for (const runId of ids) await fs.mkdir(path.join(home, "agents", agentId, "file-sync", "runs", runId, "live"), { recursive: true });
await db.insert(agentInstructionWorkingCopies).values(ids.map(runId => {
const localRoot = path.join(home, "agents", agentId, "file-sync", "runs", runId, "live");
return { runId, companyId, agentId, responsibleUserId: userId, entryFile: "AGENTS.md", baseHash: CONTENT_HASH,
localRoot, executionRoot: `/workspace/.paperclip-runtime/agent-files/${agentId}/${runId}`,
location: `remote:${randomUUID()}`, state: "saved", processStoppedAt: new Date(), receipt: { schema: AGENT_FILES, state: "saved",
cleanupPending: true, cleanup: { leaseId: randomUUID(), remoteCwd: "/workspace" }, materializationRunId: runId } };
}));
return ids;
}
async function copy(runId: string) {
const [row] = await db.select().from(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.runId, runId));
return row!;
}
async function settle() {
let last = -1;
for (let quiet = 0, turns = 0; quiet < 40 && turns < 20_000; turns++) {
await new Promise(resolve => setImmediate(resolve));
const current = meter.read().statements;
quiet = current === last && idleWorkSnapshot().active === 0 ? quiet + 1 : 0;
last = current;
}
}
async function advance(ms: number, wakeAt: () => number | null) {
const before = meter.read();
meter.startLog();
const end = Date.now() + ms;
while (Date.now() < end) {
const next = wakeAt();
const quietUntil = next === null || next > end ? end : Math.max(Date.now(), next - 1000);
if (quietUntil > Date.now()) await vi.advanceTimersByTimeAsync(quietUntil - Date.now());
if (Date.now() >= end) break;
for (let step = 0; step < 3; step++) { await vi.advanceTimersByTimeAsync(1000); await settle(); }
}
await settle();
const log = meter.stopLog();
const after = meter.read();
return { statements: after.statements - before.statements, transactions: after.transactions - before.transactions,
workSignals: log.filter(entry => entry.sql.includes("pg_current_xact_id")).length,
stopChecks: log.filter(entry => entry.sql.includes(`from "heartbeat_run_events"`)).length,
cleanupClaims: log.filter(entry => /^update "agent_instruction_working_copies" set "next_attempt_at" = \$1, "updated_at" = \$2 where/.test(entry.sql)).length };
}
async function start(...queues: Array<"collection" | "cleanup">) {
const worker = coordinator();
const service = agentInstructionWorkingCopyService(db);
if (queues.includes("collection")) await service.registerStoppedCollectionWork(worker, () => true, async () => true).ready;
if (queues.includes("cleanup")) await service.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
await settle();
return worker;
}
it("names a backoff that grows with the wait and stops growing at its cap", () => {
const now = Date.parse("2026-11-14T00:00:00Z");
expect(INSTRUCTION_COPY_RETRY_MS).toBe(30_000);
expect(INSTRUCTION_COPY_MAX_RETRY_MS).toBe(6 * HOUR);
const delay = (waited: number) => instructionCopyRetryAt(new Date(now - waited), now).getTime() - now;
expect([0, 30 * MINUTE, 2 * HOUR, 12 * HOUR, 30 * DAY].map(delay)).toEqual([30_000, 15 * MINUTE, HOUR, 6 * HOUR, 6 * HOUR]);
});
it("re-reads an old unproven stop on the capped backoff with five statements and no work signal", async () => {
const [runId] = await unprovenStops(1, 2 * DAY);
clock(); const worker = await start("collection");
try {
expect(await copy(runId!)).toMatchObject({ state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", attempts: 0 });
expect((await copy(runId!)).nextAttemptAt!.getTime() - Date.now()).toBeGreaterThan(6 * HOUR - MINUTE);
const window = await advance(12 * HOUR + MINUTE, worker.nextWakeAt);
expect(window.stopChecks).toBe(2);
expect(window.statements).toBe(10);
expect(window.transactions).toBe(2);
expect(window.workSignals).toBe(0);
expect(await copy(runId!)).toMatchObject({ state: "pending_collection", attempts: 0, processStoppedAt: null });
} finally { await worker.stop(); }
}, 120_000);
it("keeps re-checking a copy owned by a live older server and collects it once that server records the stop", async () => {
const [runId] = await unprovenStops(1, 5 * MINUTE);
clock(); const worker = await start("collection");
try {
const early = await advance(10 * MINUTE, worker.nextWakeAt);
expect(early.stopChecks).toBeGreaterThanOrEqual(2);
expect(await copy(runId!)).toMatchObject({ state: "pending_collection", processStoppedAt: null });
await appendHeartbeatRunEvent(db, { companyId, agentId, runId: runId!, eventType: "native.local_process_stopped", stream: "system" });
await advance(10 * MINUTE, worker.nextWakeAt);
expect(await copy(runId!)).toMatchObject({ state: "unchanged", nextAttemptAt: null });
expect((await copy(runId!)).processStoppedAt).not.toBeNull();
} finally { await worker.stop(); }
}, 120_000);
it("collects a copy that waited for weeks within one capped backoff of its stop being recorded", async () => {
const [runId] = await unprovenStops(1, 30 * DAY);
clock(); const worker = await start("collection");
try {
await advance(HOUR, worker.nextWakeAt);
await appendHeartbeatRunEvent(db, { companyId, agentId, runId: runId!, eventType: "native.local_process_stopped", stream: "system" });
await advance(INSTRUCTION_COPY_MAX_RETRY_MS, worker.nextWakeAt);
expect(await copy(runId!)).toMatchObject({ state: "unchanged", nextAttemptAt: null });
} finally { await worker.stop(); }
}, 120_000);
it("drains a backlog of old unproven stops in bounded batches without work signals", async () => {
await unprovenStops(300, 30 * DAY);
const signals: string[] = [];
const unsubscribe = [DELIVERY_QUEUES.instructionCollection, DELIVERY_QUEUES.strandedAgentStatus, DELIVERY_QUEUES.skillVersionRetention]
.map(queue => subscribeDeliveryWork(db, queue, () => signals.push(queue)));
clock(); const worker = coordinator();
try {
const before = meter.read();
await agentInstructionWorkingCopyService(db).registerStoppedCollectionWork(worker, () => true, async () => true).ready;
const drain = await advance(60_000, () => Date.now() + 1000);
const rows = await db.select({ next: agentInstructionWorkingCopies.nextAttemptAt }).from(agentInstructionWorkingCopies)
.where(eq(agentInstructionWorkingCopies.companyId, companyId));
expect(rows.every(row => row.next!.getTime() - Date.now() > 5 * HOUR)).toBe(true);
expect(meter.read().transactions - before.transactions).toBeLessThanOrEqual(300);
expect(drain.stopChecks).toBeLessThanOrEqual(300);
expect(drain.workSignals).toBe(0);
expect(signals).toEqual([]);
expect((await advance(HOUR, worker.nextWakeAt)).statements).toBe(0);
} finally { unsubscribe.forEach(stop => stop()); await worker.stop(); }
}, 120_000);
it("still signals when a write moves the deadline earlier or changes queue membership", async () => {
const [earlier, missing] = await unprovenStops(2, 2 * DAY);
clock(); const worker = await start("collection");
await worker.stop();
const service = agentInstructionWorkingCopyService(db);
const signals: string[] = [];
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.instructionCollection, () => signals.push("collection"));
try {
await fs.rm(entryPath(earlier!)); await fs.mkdir(entryPath(earlier!));
await service.collectStopped({ companyId, runId: earlier! });
expect(await copy(earlier!)).toMatchObject({ state: "pending_collection", attempts: 1, errorCode: "INSTRUCTION_COLLECTION_FAILED" });
expect((await copy(earlier!)).nextAttemptAt!.getTime() - Date.now()).toBeLessThanOrEqual(INSTRUCTION_COPY_RETRY_MS);
await vi.waitFor(() => expect(signals).toHaveLength(1));
await fs.rm(entryPath(missing!));
await service.collectStopped({ companyId, runId: missing! });
expect(await copy(missing!)).toMatchObject({ state: "unavailable", errorCode: "INSTRUCTION_FILE_MISSING" });
await vi.waitFor(() => expect(signals).toHaveLength(2));
} finally { unsubscribe(); }
}, 60_000);
it.each([true, false])("backs off a cleanup that cannot finish and keeps the saved copy (cleanup throws: %s)", async throws => {
const [runId] = await stuckCleanups(1, { lockRoot: !throws });
clock(); const worker = await start("cleanup");
try {
const window = await advance(6 * HOUR, worker.nextWakeAt);
expect(window.cleanupClaims).toBeGreaterThan(0);
expect(window.workSignals).toBe(0);
expect(window.cleanupClaims).toBeLessThanOrEqual(32);
expect((await advance(6 * HOUR, worker.nextWakeAt)).cleanupClaims).toBeLessThanOrEqual(4);
const row = await copy(runId!);
expect(row).toMatchObject({ state: "saved", receipt: expect.objectContaining({ cleanupPending: true }) });
expect(row.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now());
} finally { await worker.stop(); }
}, 120_000);
});
@@ -9,7 +9,8 @@ import { attentionRetentionService, registerAttentionRetentionWork } from "../se
import { workspaceOperationService } from "../services/workspace-operations.js";
import * as workspaceOperationLogs from "../services/workspace-operation-log-store.js";
import { budgetService, flushBudgetEvaluationWork } from "../services/budgets.js";
import { writeExecutionControl } from "../services/execution-control-notifications.js";
import { notifyExecutionRunWork, writeExecutionControl } from "../services/execution-control-notifications.js";
import { createHeartbeatAgentStatus } from "../services/heartbeat/agent-status.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { attentionService } from "../services/attention.js";
import { companyService } from "../services/companies.js";
@@ -26,6 +27,7 @@ import { idleWorkSnapshot } from "../services/task-admission.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { createFullDatabaseResponseCapture, installDatabaseResponseCapture } from "./helpers/full-database-response-capture.js";
const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_ATTENTION_RETENTION_TEST_DATABASE_URL");
const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
@@ -249,6 +251,45 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000;
expect(await db.select().from(decisionArchiveNotificationOutbox)).toHaveLength(0);
});
it("reads only the fields its decisions use from large runs, reviews and agents", async () => {
const payload = "saved-execution-input".repeat(2_000);
await db.update(agents).set({ adapterConfig: { instructions: payload }, runtimeConfig: { notes: payload } }).where(eq(agents.id, agentId));
const origins = await db.insert(issues).values(Array.from({ length: 50 }, () => ({ companyId,
title: randomUUID(), status: "in_review", assigneeAgentId: agentId, description: payload, updatedAt: old() }))).returning();
const runs = await db.insert(heartbeatRuns).values(origins.map(origin => ({ companyId, agentId, status: "failed",
contextSnapshot: { issueId: origin.id, prompt: payload }, runnerProfileJson: { instructions: payload },
stdoutExcerpt: payload, createdAt: old(), finishedAt: old() }))).returning({ id: heartbeatRuns.id });
await db.insert(heartbeatRunEvents).values(runs.map(run => ({ companyId, agentId, runId: run.id,
seq: 1, eventType: "lifecycle", message: "Bounded retry exhausted: byte fixture" })));
const [paused] = await db.insert(agents).values({ companyId, name: "Paused", role: "engineer", status: "paused",
adapterConfig: { instructions: payload } }).returning({ id: agents.id });
await db.insert(issueThreadInteractions).values(origins.slice(0, 10).map(row => ({ companyId, issueId: row.id,
kind: "ask_user_questions" as const, addresseeAgentId: paused.id, payload: { version: 1 as const, questions: [] } })));
const observed = createDb(externalUrl ?? temporary!.connectionString), events: Array<Record<string, unknown>> = [], now = Date.now();
const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));
installDatabaseResponseCapture(observed, { heartbeatRuns, issues, agents }, capture);
const decisions = new Map<string, string>();
try {
const service = attentionRetentionService(observed);
for (const sourceKind of ["failed_run", "review", "issue_thread_interaction"] as const) {
for (let page = 0; page < 3; page++) {
const loaded = await service.load({ companyId, sourceKind });
for (const entry of loaded.rows ?? []) decisions.set(entry.id, `${entry.sourceKind}:${entry.dueAt}:${entry.activityAt}`);
if (loaded.complete) break;
}
}
capture.flush();
} finally { capture.flush(); await observed.$client.end(); }
const bytes = (table: string) => events.filter(event => event.table === table && event.operation === "select")
.reduce((total, event) => total + Number(event.responseValueBytes), 0);
const kinds = [...decisions.values()].reduce((counts, value) => {
const kind = value.split(":")[0]; counts[kind] = (counts[kind] ?? 0) + 1; return counts; }, {} as Record<string, number>);
expect(kinds).toEqual({ failed_run: 50, review: 40, issue_thread_interaction: 10 });
expect(bytes("heartbeat_runs")).toBeLessThan(20_000);
expect(bytes("agents")).toBeLessThan(5_000);
expect(bytes("issues")).toBeLessThan(60_000);
});
it("batches 100 failed runs and rechecks late visibility and supersession before archive", async () => {
const origins = await db.insert(issues).values(Array.from({ length: 100 }, () => ({ companyId,
title: randomUUID(), status: "todo", updatedAt: old() }))).returning();
@@ -877,6 +918,24 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000;
expect(hints).toEqual([scoped, scoped]);
});
it("scopes run lifecycle attention hints to the run's task graph and agent status to agent alerts", async () => {
const parent = await insertIssue("blocked");
const issue = await insertIssue("todo", { parentId: parent.id });
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed",
contextSnapshot: { issueId: issue.id } }).returning();
const hints: string[] = [];
const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.attentionRetention, (event, values) => {
if (event === "settled") hints.push(...values ?? []);
});
try {
await writeExecutionControl(db, DELIVERY_QUEUES.executionFinalization, async () => undefined, { companyId, runId: run.id });
await db.transaction(tx => notifyExecutionRunWork(tx, { companyId, runId: run.id }));
await createHeartbeatAgentStatus(db).finalizeAgentStatus(agentId, "failed");
} finally { unsubscribe(); }
const scoped = JSON.stringify({ companyId, issueIds: [issue.id, parent.id].sort() });
expect(hints).toEqual([scoped, scoped, JSON.stringify({ companyId, sourceKind: "agent_error_alert" })]);
});
it("accepts ordinary liveness incident creation and completion with a none leaf sentinel", async () => {
const source = await insertIssue("blocked", { responsibleUserId: "board" });
const service = issueService(db);
@@ -1,7 +1,10 @@
import { eq } from "drizzle-orm";
import { eq, sql } from "drizzle-orm";
import { expect, it, vi } from "vitest";
import { heartbeatRuns, issues } from "@paperclipai/db";
import { randomUUID } from "node:crypto";
import { heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db";
import { issueService } from "../services/issues.js";
import { notifyExecutionRunWork } from "../services/execution-control-notifications.js";
import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js";
import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js";
describeIssueRecovery("issue recovery production producers and assignments", () => {
@@ -51,4 +54,55 @@ describeIssueRecovery("issue recovery production producers and assignments", ()
await completed(issue.id); await finish(issue.id); await quiet();
}, 90_000);
async function scopedStart() {
const f = await fixture(); await start({}); await settled({ backstopPending: true });
const task = async (status: "todo" | "in_progress" | "done") => (await state.db.insert(issues).values({ companyId: f.companyId,
title: `Task ${status}`, status, assigneeAgentId: f.agentId }).returning())[0];
const run = async (issueId: string, values: Partial<typeof heartbeatRuns.$inferInsert>) => (await state.db.insert(heartbeatRuns)
.values({ companyId: f.companyId, agentId: f.agentId, contextSnapshot: { issueId }, ...values }).returning())[0];
return { f, task, run };
}
async function recovered(issueId: string, sourceRunId: string) {
await vi.waitFor(async () => {
const runs = await state.db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`);
const actions = await state.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId));
expect(runs.filter(row => row.id !== sourceRunId).length + actions.length).toBeGreaterThan(0);
}, { timeout: 15_000 });
}
it("restarts a task whose run failed from that run's own hint", async () => {
const { f, task, run } = await scopedStart();
const issue = await task("in_progress");
const failed = await run(issue.id, { status: "failed", errorCode: "adapter_failed", finishedAt: new Date() });
await state.db.transaction(tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId: failed.id, agentId: f.agentId }));
await recovered(issue.id, failed.id); await finish(issue.id);
}, 90_000);
it("starts the agent's queued task when its run ends and frees the agent", async () => {
const { f, task, run } = await scopedStart();
const previous = await task("done");
const ended = await run(previous.id, { status: "succeeded", finishedAt: new Date() });
const next = await task("todo");
await run(next.id, { status: "queued", invocationSource: "assignment", triggerDetail: "system" });
await state.db.transaction(tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId: ended.id, agentId: f.agentId }));
await completed(next.id); await finish(next.id);
}, 90_000);
it("restarts a task whose run the system cancelled", async () => {
const { f, task, run } = await scopedStart();
const issue = await task("in_progress");
const cancelled = await run(issue.id, { status: "cancelled", finishedAt: new Date() });
await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: cancelled.id }));
await recovered(issue.id, cancelled.id); await finish(issue.id);
}, 90_000);
it("restarts a task whose run vanished without a final event once its lease lapses", async () => {
const f = await fixture();
const [issue] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Lost run", status: "in_progress",
assigneeAgentId: f.agentId }).returning();
const [lost] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running",
runtimeMode: "legacy", controllerBootId: randomUUID(), controllerLeaseExpiresAt: new Date(Date.now() + 5_000),
contextSnapshot: { issueId: issue.id }, processPid: 2_000_000_000, startedAt: new Date() }).returning();
await state.db.update(issues).set({ executionRunId: lost.id, checkoutRunId: lost.id }).where(eq(issues.id, issue.id));
await start({});
await recovered(issue.id, lost.id);
expect((await state.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, lost.id)))[0].status).not.toBe("running");
await finish(issue.id);
}, 90_000);
});
@@ -3,12 +3,18 @@ import { idleWorkSnapshot } from "../services/task-admission.js";
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { expect, it, vi } from "vitest";
import { agents, heartbeatRuns, issueRecoveryActions, issueRelations, issues, issueWatchdogs } from "@paperclipai/db";
import { agents, budgetPolicies, heartbeatRuns, issueRecoveryActions, issueRelations, issues, issueWatchdogs } from "@paperclipai/db";
import { heartbeatService } from "../services/heartbeat.js";
import { issueService } from "../services/issues.js";
import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";
import { registerIssueRecoveryWork } from "../services/recovery/work.js";
import { notifyIssueRecovery } from "../services/issue-recovery-notifications.js";
import { recoveryService } from "../services/recovery/service.js";
import { ISSUE_RECOVERY_BACKSTOP_MS, ISSUE_RECOVERY_MAX_ISSUE_IDS, notifyIssueRecovery, resolveIssueGraph }
from "../services/issue-recovery-notifications.js";
import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js";
import { notifyExecutionRunWork } from "../services/execution-control-notifications.js";
import { notifyRunDispatch } from "../services/run-dispatch-notifications.js";
import { promoteDeferredWorkIntents } from "../services/work-intent-outbox.js";
import { taskWatchdogService } from "../services/task-watchdogs.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js";
@@ -49,11 +55,12 @@ describeIssueRecovery("issue recovery production producers and deadlines", () =>
return query;
}) as typeof state.db.select);
await start(); await settled();
expect(scans.actions).toBe(1); expect(scans.blockers).toBe(0); expect(scans.loads).toBeLessThanOrEqual(8);
expect(scans.actions).toBe(1); expect(scans.blockers).toBe(0); expect(scans.loads).toBeLessThanOrEqual(11);
expect((await originalSelect().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id)))[0].status).toBe("resolved");
const [foreignSource] = await state.db.insert(issues).values({ companyId: foreign.companyId, title: "Foreign done", status: "done" }).returning();
const [foreignAction] = await state.db.insert(issueRecoveryActions).values({ companyId: foreign.companyId, sourceIssueId: foreignSource.id,
kind: "stranded_assigned_issue", ownerType: "board", cause: "stranded_assigned_issue", fingerprint: "foreign-query-budget", nextAction: "Inspect" }).returning();
await state.db.transaction(tx => notifyIssueRecovery(tx, { companyId: f.companyId })); await settled();
const before = { ...scans };
for (let index = 0; index < 100; index++) await state.db.transaction(tx => notifyIssueRecovery(tx, { companyId: f.companyId }));
await new Promise(resolve => setTimeout(resolve, 100));
@@ -64,12 +71,8 @@ describeIssueRecovery("issue recovery production producers and deadlines", () =>
expect((await originalSelect().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, foreignAction.id)))[0].status).toBe("active");
expect(await originalSelect().from(heartbeatRuns)).toHaveLength(0); await quiet();
});
it("limits an ordinary comment to its issue among one thousand open assignments", async () => {
const f = await fixture();
const rows = await state.db.insert(issues).values(Array.from({ length: 1000 }, (_, index) => ({
companyId: f.companyId, title: `Open work ${index}`, status: "todo", assigneeAgentId: f.agentId,
}))).returning({ id: issues.id });
const checked: string[] = [];
async function recordedRecovery(owner: Partial<Parameters<typeof registerIssueRecoveryWork>[2]>,
options?: Parameters<typeof registerIssueRecoveryWork>[4]) {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
state.coordinator = createDeliveryWorkCoordinator({ owner: state.db, canRun: () => true, onError: error => state.errors.push(error) });
const register = state.coordinator.register.bind(state.coordinator);
@@ -78,38 +81,181 @@ describeIssueRecovery("issue recovery production producers and deadlines", () =>
void pass.then(() => state.passes.delete(pass), () => state.passes.delete(pass));
return pass;
} });
// Observe the actual paged reconstruction boundary without executing one
// thousand adapters. The producer, transaction, coordinator and SQL are real;
// the other acceptance cases exercise the resulting recovery decisions.
state.worker = registerIssueRecoveryWork(state.db, state.coordinator, {
stranded: async scope => { checked.push(scope.issueId); },
orphanBlockers: async () => {}, recoveryActions: async () => {},
stranded: async () => {}, orphanBlockers: async () => {}, recoveryActions: async () => {},
dependencies: async () => ({ enqueueFailed: 0 }), locks: async () => {},
watchdogs: async () => ({ incomplete: 0 }), schedulingSuppressed: async () => false,
}, () => true);
watchdogs: async () => ({ incomplete: 0 }), schedulingSuppressed: async () => false, ...owner,
}, () => true, options);
await state.worker.ready;
async function settleWork() {
for (let step = 0; step < 120; step++) {
await vi.advanceTimersByTimeAsync(1000);
await Promise.allSettled([...state.passes]); await immediate();
if (state.coordinator.nextWakeAt() === null && idleWorkSnapshot().active === 0) return;
}
throw new Error("Recovery did not settle its committed work within two virtual minutes");
}
async function settleWork(options: { backstopPending?: boolean } = {}) {
for (let step = 0; step < 120; step++) {
await vi.advanceTimersByTimeAsync(1000);
await Promise.allSettled([...state.passes]); await immediate();
const next = state.coordinator.nextWakeAt();
const settledNow = next === null || (options.backstopPending === true && next > Date.now() + 60_000);
if (settledNow && idleWorkSnapshot().active === 0) return;
}
throw new Error("Recovery did not settle its committed work within two virtual minutes");
}
async function runGraph(companyId: string, agentId: string) {
const [other] = await state.db.insert(agents).values({ companyId, name: "Other agent", role: "engineer", status: "idle",
adapterType: "process", adapterConfig: {} }).returning({ id: agents.id });
const [parent] = await state.db.insert(issues).values({ companyId, title: "Parent", status: "in_progress", assigneeAgentId: agentId })
.returning({ id: issues.id });
const [task] = await state.db.insert(issues).values({ companyId, title: "Run task", status: "in_progress", assigneeAgentId: agentId,
parentId: parent.id }).returning({ id: issues.id });
const [dependent] = await state.db.insert(issues).values({ companyId, title: "Waits on the run task", status: "todo",
assigneeAgentId: other.id }).returning({ id: issues.id });
const [sibling] = await state.db.insert(issues).values({ companyId, title: "Next task of the agent", status: "todo",
assigneeAgentId: agentId }).returning({ id: issues.id });
await state.db.insert(issueRelations).values({ companyId, issueId: task.id, relatedIssueId: dependent.id, type: "blocks" });
const [run] = await state.db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", finishedAt: new Date(),
contextSnapshot: { issueId: task.id } }).returning({ id: heartbeatRuns.id });
const backlog = async (count: number) => (await state.db.insert(issues).values(Array.from({ length: count }, (_, index) => ({
companyId, title: `Backlog ${index}`, status: "todo", assigneeAgentId: other.id,
}))).returning({ id: issues.id })).map(row => row.id);
return { runId: run.id, taskId: task.id, siblingId: sibling.id, backlog, affected: [parent.id, task.id, dependent.id].sort() };
}
it("limits an ordinary comment to its issue among one thousand open assignments", async () => {
const f = await fixture();
const rows = await state.db.insert(issues).values(Array.from({ length: 1000 }, (_, index) => ({
companyId: f.companyId, title: `Open work ${index}`, status: "todo", assigneeAgentId: f.agentId,
}))).returning({ id: issues.id });
const checked: string[] = [];
await recordedRecovery({ stranded: async scope => { checked.push(scope.issueId); } });
await settleWork();
expect(new Set(checked).size).toBe(1000);
checked.length = 0;
await issueService(state.db).addComment(rows[0].id, "New evidence on this task", { userId: "recovery-user" });
await settleWork();
await settleWork({ backstopPending: true });
expect(checked).toEqual([rows[0].id]);
// Company eligibility changes still reconstruct all assignments. Narrowing
// comment hints must not hide unrelated work after an operator resumes it.
checked.length = 0;
await state.db.transaction(tx => notifyIssueRecovery(tx, { companyId: f.companyId }));
await settleWork();
await settleWork({ backstopPending: true });
expect(new Set(checked).size).toBe(1000);
await vi.advanceTimersByTimeAsync(ISSUE_RECOVERY_BACKSTOP_MS);
await settleWork();
await quiet();
});
it("re-checks only the tasks a run lifecycle event can affect, whatever the backlog", async () => {
const f = await fixture();
const graph = await runGraph(f.companyId, f.agentId);
await graph.backlog(1000);
const checked: string[] = [];
const assigned: string[] = [];
await recordedRecovery({
stranded: async scope => { checked.push(scope.issueId); },
assignedWork: {
listSuspects: (scope, cursor, limit) => recoveryService(state.db, { enqueueWakeup: async () => null })
.assignedWork.listSuspects(scope, cursor, limit),
checkIssue: async scope => { assigned.push(scope.issueId); },
},
}, { backstopMs: 60 * 60_000 });
await settleWork({ backstopPending: true });
expect(new Set(checked).size).toBe(1004);
expect(checked).toContain(graph.siblingId);
async function lifecycleEvent(producer: (tx: object) => Promise<unknown>, standalone?: () => Promise<unknown>) {
checked.length = 0; assigned.length = 0;
const statements: string[] = [], prior = state.db.$client.options.debug;
state.db.$client.options.debug = (_connection, query) => { statements.push(query); };
try {
if (standalone) await standalone(); else await state.db.transaction(tx => producer(tx));
await settleWork({ backstopPending: true });
} finally { state.db.$client.options.debug = prior; }
expect([...new Set(checked)].sort()).toEqual(graph.affected);
expect(assigned.every(id => graph.affected.includes(id))).toBe(true);
await vi.advanceTimersByTimeAsync(31_000);
return statements.length;
}
const finished = () => (tx: object) => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId });
const first = await lifecycleEvent(finished());
await lifecycleEvent(tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId: graph.runId, agentId: f.agentId }));
await lifecycleEvent(tx => notifyRunDispatch(tx, { companyId: f.companyId, issueId: graph.taskId }));
await lifecycleEvent(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "lock_released", issueId: graph.taskId }));
await lifecycleEvent(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "accounting_settled", runId: graph.runId }));
const recoveryActions = issueRecoveryActionService(state.db);
await lifecycleEvent(async () => {}, () => recoveryActions.upsertSourceScoped({ companyId: f.companyId, sourceIssueId: graph.taskId,
kind: "stranded_assigned_issue", ownerType: "board", cause: "stranded_assigned_issue", fingerprint: "run-failed",
nextAction: "Choose the next step", evidence: {} }));
await lifecycleEvent(async () => {}, () => recoveryActions.resolveActiveForIssue({ companyId: f.companyId, sourceIssueId: graph.taskId,
status: "resolved", outcome: "restored", resolutionNote: "Recovered" }));
await graph.backlog(4000);
expect(await lifecycleEvent(finished())).toBe(first);
});
it("resolves a run's task graph through index lookups, not the backlog", async () => {
const f = await fixture();
const graph = await runGraph(f.companyId, f.agentId);
await graph.backlog(2000);
await state.db.execute(sql`analyze issues`);
await state.db.execute(sql`analyze heartbeat_runs`);
const [read] = await state.db.transaction(async tx => {
expect(await resolveIssueGraph(tx as unknown as typeof state.db, { companyId: f.companyId, runId: graph.runId })).toEqual(graph.affected);
return tx.execute<{ rows: number }>(sql`select (coalesce(seq_tup_read, 0) + coalesce(idx_tup_fetch, 0))::int as rows
from pg_stat_xact_user_tables where relname = 'issues'`);
});
expect(read.rows).toBeLessThan(50);
});
it("finds a stranded task outside the affected set within the backstop bound", async () => {
const f = await fixture();
const graph = await runGraph(f.companyId, f.agentId);
await graph.backlog(50);
const checkedAt = new Map<string, number>();
await recordedRecovery({ stranded: async scope => { checkedAt.set(scope.issueId, Date.now()); } });
await settleWork({ backstopPending: true });
const fullPassAt = Date.now();
const [unrelated] = await graph.backlog(1);
checkedAt.clear();
await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId }));
await settleWork({ backstopPending: true });
expect(checkedAt.has(unrelated)).toBe(false);
expect(state.coordinator.nextWakeAt()).toBeLessThanOrEqual(fullPassAt + ISSUE_RECOVERY_BACKSTOP_MS);
await vi.advanceTimersByTimeAsync(ISSUE_RECOVERY_BACKSTOP_MS);
await settleWork();
expect(checkedAt.get(unrelated)! - fullPassAt).toBeLessThanOrEqual(ISSUE_RECOVERY_BACKSTOP_MS + 5_000);
checkedAt.clear();
await vi.advanceTimersByTimeAsync(20 * 60_000);
expect(checkedAt.size).toBe(0);
const [later] = await graph.backlog(1);
const eventAt = Date.now();
await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId }));
await settleWork();
expect(checkedAt.get(later)! - eventAt).toBeLessThanOrEqual(5_000);
await quiet();
});
it("keeps the company pass for hold releases that can admit any task", async () => {
const f = await fixture();
const graph = await runGraph(f.companyId, f.agentId);
const backlog = await graph.backlog(150);
const checked: string[] = [];
await recordedRecovery({ stranded: async scope => { checked.push(scope.issueId); } });
await settleWork({ backstopPending: true });
const everything = new Set([...graph.affected, graph.siblingId, ...backlog]);
await state.db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType: "company", scopeId: f.companyId,
metric: "billed_cents", windowKind: "calendar_month_utc", amount: 1000, hardStopEnabled: true, isActive: true });
for (const input of [{ trigger: "accounting_settled" as const, runId: graph.runId }, { trigger: "pause_lifted" as const }]) {
checked.length = 0;
await state.db.transaction(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, ...input }));
await settleWork({ backstopPending: true });
expect(new Set(checked)).toEqual(everything);
await vi.advanceTimersByTimeAsync(31_000);
}
});
it("falls back to the company pass when a run affects more tasks than a hint names", async () => {
const f = await fixture();
const graph = await runGraph(f.companyId, f.agentId);
const backlog = await graph.backlog(200);
const checked: string[] = [];
await recordedRecovery({ stranded: async scope => { checked.push(scope.issueId); } });
await settleWork({ backstopPending: true });
const dependents = await graph.backlog(ISSUE_RECOVERY_MAX_ISSUE_IDS);
await state.db.insert(issueRelations).values(dependents.map(id => ({ companyId: f.companyId, issueId: graph.taskId,
relatedIssueId: id, type: "blocks" as const })));
checked.length = 0;
await state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: graph.runId }));
await settleWork({ backstopPending: true });
expect(new Set(checked)).toEqual(new Set([...graph.affected, graph.siblingId, ...backlog, ...dependents]));
});
it("checks only blocked tasks whose blockers are done, however many still wait", async () => {
const f = await fixture();
const [openBlocker, doneBlocker] = await state.db.insert(issues).values([
@@ -126,28 +272,7 @@ describeIssueRecovery("issue recovery production producers and deadlines", () =>
{ companyId: f.companyId, issueId: doneBlocker.id, relatedIssueId: ready.id, type: "blocks" as const },
]);
const checked: string[] = [];
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
state.coordinator = createDeliveryWorkCoordinator({ owner: state.db, canRun: () => true, onError: error => state.errors.push(error) });
const register = state.coordinator.register.bind(state.coordinator);
state.coordinator.register = (queue, task) => register(queue, { ...task, run: signal => {
const pass = task.run(signal); state.passes.add(pass);
void pass.then(() => state.passes.delete(pass), () => state.passes.delete(pass));
return pass;
} });
state.worker = registerIssueRecoveryWork(state.db, state.coordinator, {
stranded: async () => {}, orphanBlockers: async () => {}, recoveryActions: async () => {},
dependencies: async scope => { checked.push(scope.issueId); return { enqueueFailed: 0 }; }, locks: async () => {},
watchdogs: async () => ({ incomplete: 0 }), schedulingSuppressed: async () => false,
}, () => true);
await state.worker.ready;
async function settleWork() {
for (let step = 0; step < 120; step++) {
await vi.advanceTimersByTimeAsync(1000);
await Promise.allSettled([...state.passes]); await immediate();
if (state.coordinator.nextWakeAt() === null && idleWorkSnapshot().active === 0) return;
}
throw new Error("Recovery did not settle its committed work within two virtual minutes");
}
await recordedRecovery({ dependencies: async scope => { checked.push(scope.issueId); return { enqueueFailed: 0 }; } });
await settleWork();
expect(checked).toEqual([ready.id]);
checked.length = 0;
@@ -156,8 +281,10 @@ describeIssueRecovery("issue recovery production producers and deadlines", () =>
expect(checked).toEqual([ready.id]);
checked.length = 0;
await issueService(state.db).update(openBlocker.id, { status: "done" });
await settleWork();
await settleWork({ backstopPending: true });
expect(new Set(checked)).toEqual(new Set([ready.id, ...waiting.map(row => row.id)]));
await vi.advanceTimersByTimeAsync(ISSUE_RECOVERY_BACKSTOP_MS);
await settleWork();
await quiet();
});
it("uses ordinary watchdog configuration and subtree closure to dispatch a reusable review", async () => {
@@ -50,7 +50,7 @@ export function issueRecoveryFixture() {
expect(errors).toEqual([]);
});
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); });
async function start() {
async function start(options: { backstopMs?: number } = { backstopMs: 0 }) {
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, canReconcile: () => true,
onError: error => errors.push(error) });
tasks.clear();
@@ -63,7 +63,7 @@ export function issueRecoveryFixture() {
return work;
} });
};
worker = heartbeat.registerIssueStateRecoveryWork(coordinator, () => !draining);
worker = heartbeat.registerIssueStateRecoveryWork(coordinator, () => !draining, options);
dispatch = heartbeat.registerRunDispatchWork(coordinator, () => !draining);
cancellation = heartbeat.registerScheduledRetryCancellationWork(coordinator, () => !draining);
await Promise.all([worker.ready, dispatch.ready, cancellation.ready]);
@@ -77,7 +77,7 @@ export function issueRecoveryFixture() {
void pass.then(() => passes.delete(pass), () => passes.delete(pass));
return pass;
} });
const work = other.registerIssueStateRecoveryWork(competing, () => true);
const work = other.registerIssueStateRecoveryWork(competing, () => true, { backstopMs: 0 });
extraStops.push(() => competing.stop()); extraDeadlines.push(competing.nextWakeAt); await work.ready;
}
async function fixture() {
@@ -115,11 +115,12 @@ export function issueRecoveryFixture() {
.where(eq(agents.id, f.agentId));
return failures;
}
async function settled() {
async function settled(options: { backstopPending?: boolean } = {}) {
await vi.waitFor(async () => {
await Promise.allSettled([...passes]);
await heartbeat.drainActiveRunExecutions();
const wake = coordinator.nextWakeAt();
const next = coordinator.nextWakeAt();
const wake = options.backstopPending && next !== null && next > Date.now() + 60_000 ? null : next;
const detail = wake === null ? "" : JSON.stringify({ now: Date.now(), tasks: await Promise.all([...tasks].map(async ([queue, task]) => ({ queue, at: task.nextRunAt?.(), pending: await task.hasPending() }))),
runs: (await db.select().from(heartbeatRuns)).map(run => ({ id: run.id, status: run.status, error: run.errorCode, lease: run.controllerLeaseExpiresAt, reason: run.contextSnapshot?.wakeReason })) });
expect(wake, detail).toBeNull();
@@ -104,7 +104,7 @@ describe("residual recovery production matrix", () => {
const admitted = () => !draining && !standby;
await heartbeat.registerResidualRecoveryWork(coordinator, admitted).ready;
await heartbeat.registerActiveRunSilenceWork(coordinator, admitted).ready;
await heartbeat.registerIssueStateRecoveryWork(coordinator, admitted).ready;
await heartbeat.registerIssueStateRecoveryWork(coordinator, admitted, { backstopMs: 0 }).ready;
await heartbeat.registerDeferredReceiptWork(coordinator, admitted).ready;
await heartbeat.registerRunDispatchWork(coordinator, admitted).ready;
await heartbeat.registerScheduledRetryCancellationWork(coordinator, admitted).ready;
@@ -1020,22 +1020,29 @@ describeEmbeddedPostgres("native harness backup expiration", () => {
// Every arm of the company's lease lookup must be index-backed, or the
// planner reads each lease's metadata (environment_leases_native_backup_scope_idx).
const lookup = queries.find(query => query.text.startsWith('select "id" from "environment_leases"')
&& query.text.includes("sessionScopeSha256"));
const lookup = queries.find(query => query.text.includes("jsonb_to_recordset") && query.text.includes("sessionScopeSha256"));
expect(lookup).toBeDefined();
const custom = JSON.stringify(await db.$client.unsafe(`explain (format json) ${lookup!.text}`, lookup!.params as never[]));
// A reused prepared statement gets a generic plan; the bound digest must
// still prove the partial index predicate.
const generic = JSON.stringify(await db.$client.begin(async tx => {
const leaseScans = (plan: unknown): string[] => {
const nodes: string[] = [];
const visit = (node: Record<string, unknown>) => {
if (String(node["One-Time Filter"] ?? "") === "$3") return;
if (node["Relation Name"] === "environment_leases" || String(node["Index Name"] ?? "").startsWith("environment_leases"))
nodes.push(`${node["Node Type"]}:${node["Index Name"] ?? ""}`);
for (const child of (node.Plans as Record<string, unknown>[] | undefined) ?? []) visit(child);
};
visit(((plan as Array<{ "QUERY PLAN": Array<{ Plan: Record<string, unknown> }> }>)[0]!["QUERY PLAN"][0]!).Plan);
return nodes;
};
const custom = leaseScans(await db.$client.unsafe(`explain (format json) ${lookup!.text}`, lookup!.params as never[]));
const generic = leaseScans(await db.$client.begin(async tx => {
await tx.unsafe("set local plan_cache_mode = force_generic_plan");
await tx.unsafe(`prepare backup_lease_lookup as ${lookup!.text}`);
const values = lookup!.params.map(value => `'${String(value).replaceAll("'", "''")}'`).join(", ");
return tx.unsafe(`explain (format json) execute backup_lease_lookup(${values})`);
}));
for (const text of [custom, generic]) {
expect(text).toContain("environment_leases_native_backup_scope_idx");
expect(text).toContain("BitmapOr");
expect(text).not.toContain("Seq Scan");
for (const scans of [custom, generic]) {
expect(scans.some(scan => scan.endsWith("environment_leases_native_backup_scope_idx"))).toBe(true);
expect(scans.filter(scan => scan.startsWith("Seq Scan"))).toEqual([]);
}
});
@@ -0,0 +1,164 @@
import { createHash, randomUUID } from "node:crypto";
import os from "node:os";
import path from "node:path";
import { promises as fs } from "node:fs";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import {
agents, agentTaskSessions, companies, createDb, environmentLeases, heartbeatRuns, issues,
nativeRunFinalizations, nativeRunnerCheckpoints,
} from "@paperclipai/db";
import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { nativeHarnessBackupExpirationService } from "../services/native-runtime/native-harness-backup-expiration.js";
import { registerNativeHarnessBackupExpirationWork } from "../services/native-runtime/native-harness-backup-expiration-work.js";
import { notifyRetainedNativeSessionCleanup } from "../services/retained-native-session-cleanup-notifications.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
const DAY_MS = 24 * 60 * 60 * 1000;
const describeEmbeddedPostgres = recoveryPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("native retention blockers", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startRecoveryPostgres>> | null = null;
let meter!: ReturnType<typeof meterDatabaseStatements>;
let stateBase = "";
const now = new Date();
beforeAll(async () => {
tempDb = await startRecoveryPostgres("paperclip-native-retention-blockers-");
db = createDb(tempDb.connectionString);
meter = meterDatabaseStatements(db, tempDb.connectionString);
}, 30_000);
afterEach(async () => {
vi.useRealTimers(); vi.restoreAllMocks();
await db.delete(nativeRunnerCheckpoints);
await db.delete(agentTaskSessions);
await db.delete(nativeRunFinalizations);
await db.delete(environmentLeases);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(agents);
await db.delete(companies);
if (stateBase) await fs.rm(stateBase, { recursive: true, force: true });
stateBase = "";
});
afterAll(async () => {
meter?.uninstall();
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
async function seedSessions(count: number, input: { runsPerSession?: number; issueStatus?: string; closedDaysAgo?: number; backup?: boolean } = {}) {
if (!stateBase) stateBase = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-retention-blockers-"));
const companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Retention", issuePrefix: `R${companyId.slice(0, 6)}` });
const [agent] = await db.insert(agents).values({ companyId, name: "Coder" }).returning();
const finishedAt = new Date(now.getTime() - 10 * DAY_MS);
const status = input.issueStatus ?? "todo";
const closedAt = new Date(now.getTime() - (input.closedDaysAgo ?? 10) * DAY_MS);
const sessions = [];
for (let index = 0; index < count; index++) {
const [issue] = await db.insert(issues).values({ companyId, title: "Work", status,
completedAt: status === "done" ? closedAt : null }).returning();
const sessionId = randomUUID();
const runs = await db.insert(heartbeatRuns).values(Array.from({ length: input.runsPerSession ?? 3 }, () => ({
companyId, agentId: agent!.id, status: "succeeded", issueId: issue!.id, nativeIssueId: issue!.id,
nativeSessionId: sessionId, finishedAt,
}))).returning();
await db.insert(nativeRunFinalizations).values(runs.map(run => ({ runId: run.id, companyId, issueId: issue!.id, phase: "committed" })));
await db.insert(nativeRunnerCheckpoints).values(runs.map(run => ({
companyId, issueId: issue!.id, runId: run.id, part: "header", material: { encrypted: true },
})));
const scope = createHash("sha256").update(randomUUID()).digest("hex");
if (input.backup) {
const root = path.join(stateBase, scope);
const current = path.join(root, "failover-backups", "current");
await fs.mkdir(path.join(root, "control-plane"), { recursive: true });
await fs.writeFile(path.join(root, "control-plane", "control-plane-state.json"),
JSON.stringify({ identity: { runId: runs[0]!.id, normalizedSessionId: sessionId } }));
await fs.mkdir(current, { recursive: true });
await fs.writeFile(path.join(current, "manifest.json"), "{}");
await fs.utimes(current, finishedAt, finishedAt);
}
sessions.push({ companyId, agentId: agent!.id, issueId: issue!.id, sessionId, scope, runIds: runs.map(run => run.id) });
}
return sessions;
}
function service() {
return nativeHarnessBackupExpirationService(db, { stateBase, closedForDays: 7, isSessionBusy: () => false });
}
async function startup() {
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: () => {} });
const before = meter.read();
try {
await service().registerCheckpointExpiration(coordinator).ready;
await vi.waitFor(() => expect(coordinator.nextWakeAt()).toBeNull(), { timeout: 60_000 });
} finally { await coordinator.stop(); }
const after = meter.read();
return { statements: after.statements - before.statements, transactions: after.transactions - before.transactions };
}
it("evaluates blocked checkpoint sessions in one statement per page and repeats nothing per checkpoint on restart", async () => {
await seedSessions(100);
const first = await startup();
const second = await startup();
expect(first).toEqual({ statements: 4, transactions: 0 });
expect(second).toEqual(first);
expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toHaveLength(300);
}, 120_000);
it("expires the checkpoints of a session on the next startup once its blocker clears", async () => {
const [blocked] = await seedSessions(1);
const cleared = await seedSessions(2, { issueStatus: "done", closedDaysAgo: 9 });
await startup();
const remaining = await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints);
expect(remaining.map(row => row.runId).sort()).toEqual([...blocked!.runIds].sort());
expect(cleared.flatMap(session => session.runIds).some(runId => remaining.some(row => row.runId === runId))).toBe(false);
await db.update(issues).set({ status: "done", completedAt: new Date(now.getTime() - 8 * DAY_MS) }).where(eq(issues.id, blocked!.issueId));
await startup();
expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toEqual([]);
}, 120_000);
it("keeps a checkpoint whose session still has a resume pointer", async () => {
const [session] = await seedSessions(1, { issueStatus: "done", closedDaysAgo: 9 });
await db.insert(agentTaskSessions).values({ companyId: session!.companyId, agentId: session!.agentId, adapterType: "paperclip_runner",
taskKey: session!.issueId, sessionParamsJson: { sessionId: session!.sessionId }, lastRunId: session!.runIds[0]! });
expect(await startup()).toEqual({ statements: 2, transactions: 0 });
expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toHaveLength(3);
}, 120_000);
it("lets two servers run the startup pass at once without duplicate or conflicting retirement", async () => {
const sessions = await seedSessions(20, { issueStatus: "done", closedDaysAgo: 9 });
const [left, right] = await Promise.all([service().tickCheckpoints(), service().tickCheckpoints()]);
expect(left.failed + right.failed).toBe(0);
expect(left.expiredCheckpoints + right.expiredCheckpoints).toBe(sessions.length * 3);
expect(await db.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints)).toEqual([]);
}, 120_000);
it("reads a blocked backup in one statement for each run hint that reaches it", async () => {
const sessions = await seedSessions(50, { backup: true, runsPerSession: 1 });
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: () => {} });
const worker = registerNativeHarnessBackupExpirationWork(coordinator, db, { stateBase, isSessionBusy: () => false }, () => true);
try {
await worker.ready;
await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(1000); expect(idleWorkSnapshot().active).toBe(0); });
const before = meter.read();
meter.startLog();
for (const session of sessions) await db.transaction(tx => notifyRetainedNativeSessionCleanup(tx, { companyId: session.companyId, runId: session.runIds[0]! }));
await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(1000); expect(idleWorkSnapshot().active).toBe(0); }, { timeout: 30_000 });
await vi.advanceTimersByTimeAsync(5000);
const log = meter.stopLog();
const after = meter.read();
const hintWrites = sessions.length * 3;
expect(after.transactions - before.transactions).toBe(sessions.length);
expect(after.statements - before.statements - hintWrites).toBeLessThanOrEqual(sessions.length * 2);
expect(log.filter(entry => entry.sql.includes("jsonb_to_recordset")).length).toBe(sessions.length);
for (const session of sessions) expect(await fs.lstat(path.join(stateBase, session.scope, "failover-backups", "current")).then(() => true)).toBe(true);
} finally { await worker.stop(); await coordinator.stop(); }
}, 120_000);
});
@@ -0,0 +1,62 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import { expect, it } from "vitest";
import { issueRelations, issues } from "@paperclipai/db";
import { resolvedDependencyCandidate } from "../services/recovery/work.js";
import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js";
const earlierPredicate = sql`exists (select 1 from ${issueRelations} r where r.company_id = ${issues.companyId}
and r.related_issue_id = ${issues.id} and r.type = 'blocks')
and not exists (select 1 from ${issueRelations} r inner join ${issues} blocker
on blocker.id = r.issue_id and blocker.company_id = r.company_id
where r.company_id = ${issues.companyId} and r.related_issue_id = ${issues.id}
and r.type = 'blocks' and blocker.status <> 'done')`;
describeIssueRecovery("resolved dependency candidates", () => {
const state = issueRecoveryFixture();
async function blockedGraph(companyId: string, agentId: string, count: number) {
const blockers = await state.db.insert(issues).values([
{ companyId, title: "Open blocker", status: "in_progress", assigneeAgentId: agentId },
{ companyId, title: "Done blocker", status: "done" },
{ companyId, title: "Cancelled blocker", status: "cancelled" },
]).returning({ id: issues.id });
const blocked = await state.db.insert(issues).values(Array.from({ length: count }, (_, index) => ({
companyId, title: `Blocked ${index}`, status: "blocked", assigneeAgentId: agentId,
}))).returning({ id: issues.id });
const relations = blocked.flatMap((row, index) => {
const shape = index % 4;
if (shape === 0) return [{ blocker: 1, row }];
if (shape === 1) return [{ blocker: 0, row }];
if (shape === 2) return [{ blocker: 1, row }, { blocker: 2, row }];
return [];
}).map(({ blocker, row }) => ({ companyId, issueId: blockers[blocker].id, relatedIssueId: row.id, type: "blocks" as const }));
for (let index = 0; index < relations.length; index += 500) await state.db.insert(issueRelations).values(relations.slice(index, index + 500));
}
const candidates = (companyId: string, predicate: ReturnType<typeof sql>) => state.db.select({ id: issues.id }).from(issues)
.where(and(eq(issues.companyId, companyId), inArray(issues.status, ["blocked"]), predicate)).orderBy(issues.id);
it("selects the same tasks as the earlier predicate", async () => {
const f = await state.fixture();
await blockedGraph(f.companyId, f.agentId, 40);
const current = await candidates(f.companyId, resolvedDependencyCandidate);
expect(current).toEqual(await candidates(f.companyId, earlierPredicate));
expect(current).toHaveLength(10);
});
it("probes the relations of each task, whatever the planner statistics say", async () => {
const small = await state.fixture();
await blockedGraph(small.companyId, small.agentId, 8);
await state.db.execute(sql`analyze issues`);
await state.db.execute(sql`analyze issue_relations`);
const large = await state.fixture();
await blockedGraph(large.companyId, large.agentId, 3000);
const query = candidates(large.companyId, resolvedDependencyCandidate).limit(100).toSQL();
const [{ "QUERY PLAN": plan }] = await state.db.$client.unsafe(`explain (format json) ${query.sql}`, query.params as never[]) as Array<{ "QUERY PLAN": unknown }>;
const text = JSON.stringify(plan);
expect(text).not.toMatch(/"Join Type":"(Semi|Anti)"/);
expect(text.match(/"Subplan Name"/g)).toHaveLength(2);
const rows = await state.db.transaction(async tx => {
await tx.execute(sql`set local statement_timeout = '5s'`);
return tx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, large.companyId),
inArray(issues.status, ["blocked"]), resolvedDependencyCandidate)).limit(100);
});
expect(rows).toHaveLength(100);
});
});
@@ -697,3 +697,27 @@ it("drops an entry that vanished from a keyed scope and keeps other companies' s
expect(coordinator.nextWakeAt()).toBeNull();
expect(onError).not.toHaveBeenCalled();
});
it("keeps a backstop hint's deadline without holding the worker busy", async () => {
vi.useFakeTimers();
const owner = installDatabaseWorkSignals({ execute: vi.fn(async () => []), transaction: vi.fn(async () => undefined) });
coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => true, onError: vi.fn() });
const backstopAt = Date.now() + 300_000;
const load = vi.fn(async (_scope?: string) => []);
const worker = registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.externalObjectRefresh, minimumPassIntervalMs: 0,
decodeScope: hint => hint === "*" ? undefined : hint,
backstop: scope => scope === "backstop" ? backstopAt : null,
matches: () => true, load, check: async () => null,
}, () => true);
await worker.ready;
load.mockClear();
worker.invalidate("backstop");
await vi.advanceTimersByTimeAsync(1);
expect(load).not.toHaveBeenCalled();
expect(coordinator.nextWakeAt()).toBe(backstopAt);
expect(worker.reconciliationSnapshot().reconciled).toBe(true);
await vi.advanceTimersByTimeAsync(300_000);
expect(load).toHaveBeenCalledWith("backstop", expect.anything());
expect(coordinator.nextWakeAt()).toBeNull();
});
@@ -0,0 +1,296 @@
import { randomUUID } from "node:crypto";
import os from "node:os";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { setImmediate as immediate } from "node:timers/promises";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, applyPendingMigrations, authUsers, closeCheckpointDb, closeLivenessDb, companies, companyMemberships,
controllerInstances, createDb, environmentLeases, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { heartbeatService } from "../services/heartbeat.js";
import { notifyLiveRunRecovery } from "../services/live-run-recovery-notifications.js";
import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";
import { persistHeartbeatRunProcessMetadata } from "../services/heartbeat/run-lifecycle.js";
import { discoverSettledNativeRunProcesses } from "../services/native-local-process-stop.js";
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
vi.setConfig({ testTimeout: 300_000, hookTimeout: 180_000 });
describe("settled native process re-checks", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let db: ReturnType<typeof createDb>;
let meter: ReturnType<typeof meterDatabaseStatements>;
let heartbeat: ReturnType<typeof heartbeatService>;
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator>;
const errors: unknown[] = [];
const passes = new Set<Promise<unknown>>();
const children: number[] = [];
const checks = new Map<string, number>();
const stops: Array<() => Promise<void>> = [];
beforeAll(async () => {
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_SETTLED_RECHECK_TEST_DATABASE_URL");
if (!external) temporary = await startEmbeddedPostgresTestDatabase("settled-recheck-");
else await applyPendingMigrations(external);
const url = external ?? temporary!.connectionString;
db = createDb(url, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
meter = meterDatabaseStatements(db, url);
await Promise.all(Array.from({ length: 4 }, () => db.execute(sql`select pg_sleep(0.01)`)));
db.$client.options.debug = (_connection, query, parameters) => {
if (!/for update/i.test(query) || !query.includes("sessionCheckpoint")) return;
const runId = (parameters as unknown[]).find(value => typeof value === "string" && checks.has(value)) as string | undefined;
if (runId) checks.set(runId, checks.get(runId)! + 1);
};
});
beforeEach(async () => {
await db.execute(sql`truncate companies, controller_instances cascade`);
errors.length = 0; checks.clear();
heartbeat = heartbeatService(db);
coordinator = newCoordinator();
});
afterEach(async () => {
for (const stop of stops.splice(0)) await stop();
await coordinator.stop(); await heartbeat.drainActiveRunExecutions();
for (const pid of children.splice(0)) { try { process.kill(-pid, "SIGKILL"); } catch { } }
vi.useRealTimers(); vi.restoreAllMocks(); expect(errors).toEqual([]);
});
afterAll(async () => {
meter?.uninstall();
if (db) { await closeLivenessDb(db, 1); await closeCheckpointDb(db, 1); }
await db?.$client.end({ timeout: 1 }); await temporary?.cleanup();
});
function newCoordinator() {
const created = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true,
onError: error => errors.push(error) });
const register = created.register.bind(created);
created.register = (queue, task) => register(queue, { ...task, run: signal => {
const pass = Promise.resolve(task.run(signal)); passes.add(pass);
void pass.finally(() => passes.delete(pass)); return pass;
} });
return created;
}
async function fixture() {
const companyId = randomUUID(), actorId = "settled-recheck-user";
await db.insert(authUsers).values({ id: actorId, name: "Owner", email: `${actorId}@example.test`,
createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing();
await db.insert(companies).values({ id: companyId, name: "Settled", issuePrefix: `SR${companyId.slice(0, 6)}`,
requireBoardApprovalForNewAgents: false, defaultResponsibleUserId: actorId });
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: actorId,
status: "active", membershipRole: "owner" });
const [agent] = await db.insert(agents).values({ companyId, name: "Worker", status: "idle", adapterType: "process",
adapterConfig: {}, runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } } }).returning();
const [issue] = await db.insert(issues).values({ companyId, title: "Work", status: "done", assigneeAgentId: agent.id }).returning();
return { companyId, agentId: agent.id, issueId: issue.id };
}
type Fixture = Awaited<ReturnType<typeof fixture>>;
async function exitedPid() {
const child = spawn(process.execPath, ["-e", "0"], { detached: true, stdio: "ignore" });
const pid = child.pid!; await once(child, "exit"); return pid;
}
function livePid() {
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" });
child.unref(); children.push(child.pid!); return child.pid!;
}
async function kill(pid: number) {
try { process.kill(-pid, "SIGKILL"); } catch { }
for (let attempt = 0; attempt < 100; attempt++) {
try { process.kill(pid, 0); } catch { return; }
await new Promise(resolve => setImmediate(resolve));
}
}
type Seed = { host?: { hostname: string; hash: string | null }; phase?: string | null; checkpoint?: boolean; live?: boolean;
birthMismatch?: boolean; remote?: "stopped" | "unconfirmed" };
async function seed(f: Fixture, options: Seed = {}) {
const pid = options.live ? livePid() : await exitedPid();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, runtimeMode: "native",
nativeIssueId: f.issueId, status: "running", invocationSource: "assignment", triggerDetail: "system",
runnerProfileJson: options.checkpoint === false ? {} : { sessionCheckpoint: { providerSessionId: "thread" } } }).returning();
if (options.host || options.birthMismatch) {
const startedAt = new Date();
const host = options.host ?? { hostname: os.hostname(), hash: null };
await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId: run.id, agentId: f.agentId,
eventType: "native.process_identity_recorded", stream: "system", level: "info", message: "identity",
payload: { targetKind: options.remote ? "remote" : "local", hostname: host.hostname, processPid: pid, processGroupId: pid,
processStartedAt: new Date(startedAt.getTime() - (options.birthMismatch ? 5_000 : 0)).toISOString() },
runUpdate: { processPid: pid, processGroupId: pid, processStartedAt: startedAt, processHostHash: host.hash } });
} else {
await persistHeartbeatRunProcessMetadata(db, run.id, { pid, processGroupId: pid, startedAt: new Date().toISOString(), targetKind: "local" });
}
if (options.phase !== null) await db.insert(nativeRunFinalizations).values({ companyId: f.companyId, issueId: f.issueId,
runId: run.id, phase: options.phase ?? "committed", controllerBootId: randomUUID() });
const [lease] = await db.insert(environmentLeases).values({ companyId: f.companyId, issueId: f.issueId, heartbeatRunId: run.id,
provider: options.remote ? "daytona" : "local", providerLeaseId: options.remote ? randomUUID() : null, leasePolicy: "ephemeral",
status: "released", releasedAt: new Date(), cleanupStatus: "success" }).returning();
if (options.remote === "stopped") await db.update(environmentLeases).set({ metadata: {
remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }),
} }).where(eq(environmentLeases.id, lease.id));
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.id));
checks.set(run.id, 0);
return { runId: run.id, pid };
}
async function start(target = coordinator) {
if (!vi.isFakeTimers()) vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
await heartbeat.registerResidualRecoveryWork(target, () => true).ready;
await advance(2_000);
}
async function advance(ms: number) {
const until = Date.now() + ms;
while (Date.now() < until) {
await vi.advanceTimersByTimeAsync(Math.min(1_000, until - Date.now()));
await Promise.allSettled([...passes]); await immediate();
}
}
const companyHint = (companyId: string) => db.transaction(tx => notifyLiveRunRecovery(tx, { companyId }));
const runHint = (companyId: string, runId: string) => db.transaction(tx => notifyLiveRunRecovery(tx, { companyId, runId }));
async function hints(companyId: string, count: number) {
for (let index = 0; index < count; index++) { await companyHint(companyId); await advance(31_000); }
}
const processPid = async (id: string) => (await db.select({ pid: heartbeatRuns.processPid }).from(heartbeatRuns)
.where(eq(heartbeatRuns.id, id)))[0]!.pid;
const stopReceipts = async (id: string) => (await db.select().from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.runId, id), eq(heartbeatRunEvents.eventType, "native.local_process_stopped")))).length;
it.each([
["recorded by a replaced container", { host: { hostname: "replaced-container", hash: "replaced-container-space" } }],
["whose coordinator phase is unsettled", { phase: "workspace_finalizing" }],
["without a checkpoint or provider evidence", { checkpoint: false }],
] as const)("never re-reads a terminal run %s on company hints", async (_name, options) => {
const f = await fixture();
const { runId, pid } = await seed(f, options as Seed);
await start();
await hints(f.companyId, 4);
expect(checks.get(runId)).toBe(0);
expect(await processPid(runId)).toBe(pid);
});
it.each(["live", "stopped"] as const)("leaves a %s older server's runs to that server", async state => {
const f = await fixture();
const bootId = randomUUID();
await db.insert(controllerInstances).values({ bootId, processSpace: "older-server-space", pid: 4242,
leaseExpiresAt: new Date(Date.now() + (state === "live" ? 60_000 : -600_000)),
stoppedAt: state === "stopped" ? new Date() : null });
const { runId, pid } = await seed(f, { host: { hostname: "older-server", hash: "older-server-space" } });
await db.update(nativeRunFinalizations).set({ controllerBootId: bootId, controllerHostHash: "older-server-space" })
.where(eq(nativeRunFinalizations.runId, runId));
const own = await seed(f);
await start();
expect(await processPid(own.runId)).toBeNull();
await hints(f.companyId, 2);
expect(checks.get(runId)).toBe(0);
expect(await processPid(runId)).toBe(pid);
expect(await stopReceipts(runId)).toBe(0);
});
it("re-admits a run once its coordinator phase settles", async () => {
const f = await fixture();
const { runId } = await seed(f, { phase: "workspace_finalizing" });
await start();
await hints(f.companyId, 1);
expect(await processPid(runId)).not.toBeNull();
await db.update(nativeRunFinalizations).set({ phase: "committed" }).where(eq(nativeRunFinalizations.runId, runId));
await hints(f.companyId, 1);
expect(await processPid(runId)).toBeNull();
expect(checks.get(runId)).toBe(1);
expect(await stopReceipts(runId)).toBe(1);
});
it("re-admits a run once late provider evidence arrives", async () => {
const f = await fixture();
const { runId } = await seed(f, { checkpoint: false });
await start();
await hints(f.companyId, 1);
expect(await processPid(runId)).not.toBeNull();
await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId, agentId: f.agentId, eventType: "harness.ready",
stream: "system", level: "info", message: "ready" });
await hints(f.companyId, 1);
expect(await processPid(runId)).toBeNull();
expect(checks.get(runId)).toBe(1);
});
it("releases legacy rows without a PID-space hash only when this host recorded them", async () => {
const f = await fixture();
const own = await seed(f, { host: { hostname: os.hostname(), hash: null } });
const foreign = await seed(f, { host: { hostname: "legacy-other-host", hash: null } });
await start();
expect(await processPid(own.runId)).toBeNull();
await hints(f.companyId, 2);
expect(checks.get(foreign.runId)).toBe(0);
expect(await processPid(foreign.runId)).toBe(foreign.pid);
});
it("releases a sandbox run from any server once its termination receipt exists", async () => {
const f = await fixture();
const pending = await seed(f, { host: { hostname: "replaced-container", hash: "remote" }, remote: "unconfirmed" });
const stopped = await seed(f, { host: { hostname: "replaced-container", hash: "remote" }, remote: "stopped" });
await start();
expect(await processPid(stopped.runId)).toBeNull();
expect(await processPid(pending.runId)).not.toBeNull();
const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, pending.runId));
await db.update(environmentLeases).set({ metadata: {
remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }),
} }).where(eq(environmentLeases.id, lease.id));
await runHint(f.companyId, pending.runId);
await advance(2_000);
expect(await processPid(pending.runId)).toBeNull();
});
it("backs off a live local process and releases it on the next run-scoped hint after it exits", async () => {
const f = await fixture();
const { runId, pid } = await seed(f, { live: true });
await start();
expect(checks.get(runId)).toBe(1);
await hints(f.companyId, 8);
expect(checks.get(runId)).toBeLessThanOrEqual(4);
expect(await processPid(runId)).toBe(pid);
await kill(pid);
await runHint(f.companyId, runId);
await advance(2_000);
expect(await processPid(runId)).toBeNull();
expect(await stopReceipts(runId)).toBe(1);
});
it("checks a same-host skip once with one locking statement, then only on its own trigger", async () => {
const f = await fixture();
const { runId } = await seed(f, { birthMismatch: true, host: { hostname: os.hostname(), hash: null } });
meter.startLog();
await start();
const log = meter.stopLog();
expect(checks.get(runId)).toBe(1);
const inCheck = log.filter(entry => entry.inTransaction || /^\s*begin/i.test(entry.sql));
expect(inCheck.filter(entry => /for update/i.test(entry.sql))).toHaveLength(1);
expect(inCheck.length).toBeLessThanOrEqual(3);
await hints(f.companyId, 3);
expect(checks.get(runId)).toBe(1);
await runHint(f.companyId, runId);
await advance(2_000);
expect(checks.get(runId)).toBe(2);
});
it("checks a pending run at most once after a restart and discovers no excluded run at startup", async () => {
const f = await fixture();
const { runId } = await seed(f, { live: true });
for (let index = 0; index < 50; index++) await seed(f, { host: { hostname: "replaced-container", hash: "replaced-container-space" } });
await start();
expect(checks.get(runId)).toBe(1);
await coordinator.stop();
const restarted = newCoordinator();
stops.push(() => restarted.stop());
await start(restarted);
expect(checks.get(runId)).toBe(2);
vi.useRealTimers();
const before = meter.read();
const counted = [...checks.values()].reduce((sum, value) => sum + value, 0);
await discoverSettledNativeRunProcesses(db, { skip: id => id === runId });
expect(meter.read().statements - before.statements).toBe(1);
expect([...checks.values()].reduce((sum, value) => sum + value, 0)).toBe(counted);
});
});
+3 -3
View File
@@ -1303,7 +1303,7 @@ async function startServerWithDatabaseTeardown(
) => Promise<unknown>) | null = null;
let drainHeartbeatExecutionFinalizers: (() => Promise<void>) | null = null;
let handOffNativeRunsForShutdown: ((signal: "SIGINT" | "SIGTERM") => Promise<string[]>) | null = null;
let prepareHotRestartShutdown: ((signal: "SIGINT" | "SIGTERM") => Promise<{
let prepareHotRestartShutdown: ((signal: "SIGINT" | "SIGTERM", now?: Date, abort?: AbortSignal) => Promise<{
skipDrain: boolean;
drainRunIds?: string[];
}>) | null = null;
@@ -2281,8 +2281,8 @@ async function startServerWithDatabaseTeardown(
signal,
prepareHotRestartShutdown: prepareHotRestart
? async (preparationSignal) => {
const preparation = await preDrain.run("hot_restart_prepare", () =>
prepareHotRestart(preparationSignal));
const preparation = await preDrain.run("hot_restart_prepare", abort =>
prepareHotRestart(preparationSignal, undefined, abort));
if (preparation.outcome === "completed") return preparation.value;
if (preparation.outcome === "failed") throw preparation.error;
throw new Error("hot-restart shutdown preparation timed out");
@@ -158,7 +158,7 @@ export async function wakeWorkspaceBusyWaitersInTx(tx: Db, input: {
);
const waiters = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(waiting).for("update");
if (waiters.length === 0) return 0;
await notifyScheduledRetryDispatch(tx, { companyId: input.companyId });
await notifyScheduledRetryDispatch(tx, { companyId: input.companyId, runId: input.runId });
const woken = await tx
.update(heartbeatRuns)
.set({ scheduledRetryAt: input.now, updatedAt: input.now })
@@ -732,7 +732,7 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru
.returning()
.then((rows) => rows[0]);
await notifyRunDispatch(tx, { companyId });
await notifyRunDispatch(tx, { companyId, issueId: issue.id });
const queuedRun = await tx
.insert(heartbeatRuns)
.values({
@@ -811,7 +811,7 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru
.returning()
.then((rows) => rows[0]);
await notifyRunDispatch(tx, { companyId });
await notifyRunDispatch(tx, { companyId, issueId: issue.id });
const queuedRun = await tx
.insert(heartbeatRuns)
.values({
@@ -35,6 +35,15 @@ const hash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("h
const quote = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`;
const completed = new Set(["saved", "unchanged", "resolved"]);
const MAX_COLLECTION_ATTEMPTS = 3;
export const INSTRUCTION_COPY_RETRY_MS = 30_000;
export const INSTRUCTION_COPY_MAX_RETRY_MS = 6 * 60 * 60_000;
const settledStates = new Set(["saved", "unchanged", "resolved", "unavailable", "conflict"]);
export function instructionCopyRetryAt(waitingSince: Date, now = Date.now()) {
const waited = Math.max(0, now - waitingSince.getTime());
return new Date(now + Math.min(INSTRUCTION_COPY_MAX_RETRY_MS, Math.max(INSTRUCTION_COPY_RETRY_MS, Math.floor(waited / 2))));
}
// Only orchestration can register a live target; tools and HTTP callers cannot
// supply one. These handles are optional: durable captured bytes survive restart.
const liveTargets = new Map<string, AdapterExecutionTarget>();
@@ -100,20 +109,25 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
return row ?? null;
}
async function tryPatch(row: Copy, values: Partial<typeof copies.$inferInsert>, requireDue = false, condition?: SQL) {
const signalsCollection = collectionCandidate(row) || collectionCandidate({ ...row, ...values });
const signalsCleanup = directoryCleanupEntry(row) !== null || directoryCleanupEntry({ ...row, ...values }) !== null;
const next = { ...row, ...values } as Copy;
const signalsCollection = collectionCandidate(row) || collectionCandidate(next);
const signalsCleanup = directoryCleanupEntry(row) !== null || directoryCleanupEntry(next) !== null;
const signalsCommit = row.state === "pending_commit" || values.state === "pending_commit";
const where = and(
scope(row.companyId, row.runId), eq(copies.state, row.state), eq(copies.attempts, row.attempts), eq(copies.baseHash, row.baseHash), eq(copies.localRoot, row.localRoot),
sql`${copies.receipt}->>'retainedByRunId' IS NOT DISTINCT FROM ${typeof row.receipt?.retainedByRunId === "string" ? row.receipt.retainedByRunId : null}`,
requireDue ? or(isNull(copies.nextAttemptAt), lte(copies.nextAttemptAt, new Date())) : undefined, condition,
);
if (onlyDefers(row, next)) {
return db.transaction(async tx => (await tx.update(copies).set({ ...values, updatedAt: new Date() }).where(where).returning())[0]);
}
const write = async (tx: Db) => {
await notifyStrandedAgentStatus(tx, { companyId: row.companyId, agentId: row.agentId });
if (signalsCommit)
await notifyInstructionCommit(tx, { companyId: row.companyId, runId: row.runId });
if (signalsCleanup) await notifyDirectoryCleanup(tx, { companyId: row.companyId, runId: row.runId });
if (signalsCollection) await notifyInstructionCollection(tx, { companyId: row.companyId, runId: row.runId });
const [updated] = await tx.update(copies).set({ ...values, updatedAt: new Date() }).where(and(
scope(row.companyId, row.runId), eq(copies.state, row.state), eq(copies.attempts, row.attempts), eq(copies.baseHash, row.baseHash), eq(copies.localRoot, row.localRoot),
sql`${copies.receipt}->>'retainedByRunId' IS NOT DISTINCT FROM ${typeof row.receipt?.retainedByRunId === "string" ? row.receipt.retainedByRunId : null}`,
requireDue ? or(isNull(copies.nextAttemptAt), lte(copies.nextAttemptAt, new Date())) : undefined, condition,
)).returning();
const [updated] = await tx.update(copies).set({ ...values, updatedAt: new Date() }).where(where).returning();
return updated;
};
return db.transaction(tx => write(tx as unknown as Db));
@@ -128,15 +142,12 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
return { type: "agent", companyId: row.companyId, agentId: row.agentId, runId: row.runId, onBehalfOfUserId: row.responsibleUserId };
}
const directories = agentDirectoryWorkingCopyService(db, get, patch, options.environmentRuntime);
async function recoverDirectoryCleanup(row: Copy, cleanup: () => Promise<unknown>) {
// Reserve a later retry before I/O, including lock waits. A blocked owner
// must not occupy every sweep or prevent other copies from being reclaimed.
async function recoverDirectoryCleanup(row: Copy, retryAt: Date, cleanup: () => Promise<unknown>) {
try {
await patch(row, { nextAttemptAt: new Date(Date.now() + 30_000) });
await cleanup();
}
catch (error) {
try { await patch(row, { nextAttemptAt: new Date(Date.now() + 30_000) }); }
try { await patch(row, { nextAttemptAt: retryAt }); }
catch (retryError) {
logger.warn({ err: retryError, runId: row.runId }, "Agent file cleanup retry could not be scheduled");
}
@@ -380,6 +391,19 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
|| row.state === "preparing" && isAgentDirectoryCopy(row))
|| row.state === "unavailable" && !row.processStoppedAt && row.location.startsWith("remote:") && isAgentDirectoryCopy(row));
}
function strandsAgent(row: Copy) {
return !settledStates.has(row.state) || !row.processStoppedAt || row.nextAttemptAt !== null
|| Object.hasOwn(row.receipt ?? {}, "baseline") || row.receipt?.cleanupPending === true;
}
function onlyDefers(row: Copy, next: Copy) {
const due = (copy: Copy) => copy.nextAttemptAt?.getTime() ?? 0;
const deferred = (before: boolean, after: boolean) => before === after && (!after || due(next) >= due(row));
return deferred(collectionCandidate(row), collectionCandidate(next))
&& deferred(directoryCleanupEntry(row) !== null, directoryCleanupEntry(next) !== null)
&& deferred(commitEntry(row) !== null, commitEntry(next) !== null)
&& (row.state === "pending_commit") === (next.state === "pending_commit")
&& strandsAgent(row) === strandsAgent(next);
}
function collectionPredicate() {
return and(sql`NOT (coalesce(${copies.receipt}, '{}'::jsonb) ? 'retainedByRunId') AND (
(${copies.attempts} < 3 AND (${copies.state} IN ('prepared', 'pending_collection', 'unchanged_turn', 'warm_saved')
@@ -388,39 +412,41 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
AND ${copies.location} LIKE 'remote:%' AND ${copies.receipt}->>'schema' = 'paperclip.agent-files.v1'))`,
inArray(heartbeatRuns.status, ["succeeded", "failed", "cancelled", "timed_out", "interrupted"]));
}
async function collectRecovered(row: Copy, runtimeMode: string | null) {
if (row.state === "unavailable" && isAgentDirectoryCopy(row)) {
await recoverDirectoryCleanup(row, () => directories.recoverUnavailable(row));
} else if (row.state === "preparing" && isAgentDirectoryCopy(row)) {
type StopEvidence = "directory_unavailable" | "directory_preparing" | "local" | "remote" | null;
async function stopEvidence(row: Copy, runtimeMode: string | null): Promise<StopEvidence> {
if (row.state === "unavailable" && isAgentDirectoryCopy(row)) return "directory_unavailable";
if (row.state === "preparing" && isAgentDirectoryCopy(row)) return "directory_preparing";
if (row.location === "local") return row.processStoppedAt || runtimeMode === "native" &&
await hasNativeLocalProcessStop(db, row.companyId, row.runId) ? "local" : null;
return await remoteExecutionHasStopped(db, row.companyId, row.runId) ? "remote" : null;
}
function awaitingStop(row: Copy, waitingSince: Date): Partial<typeof copies.$inferInsert> {
return { ...(row.state === "prepared" ? { state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED",
errorMessage: "The provider's stop has not been confirmed. Instruction collection is pending; no save is claimed." } : {}),
nextAttemptAt: instructionCopyRetryAt(waitingSince) };
}
async function collectRecovered(row: Copy, evidence: Exclude<StopEvidence, null>, retryAt: Date): Promise<Copy | null | undefined> {
if (evidence === "directory_unavailable") {
await recoverDirectoryCleanup(row, retryAt, () => directories.recoverUnavailable(row));
} else if (evidence === "directory_preparing") {
await directories.release(await patch(row, { state: "unavailable", processStoppedAt: new Date(),
errorCode: "AGENT_FILES_PREPARE_FAILED", errorMessage: "Agent-file preparation was interrupted. The temporary copy was discarded.", nextAttemptAt: null }));
} else if (row.location === "local" && (row.processStoppedAt || runtimeMode === "native" &&
await hasNativeLocalProcessStop(db, row.companyId, row.runId))) {
} else if (evidence === "local") {
const result = await collectStopped({ companyId: row.companyId, runId: row.runId });
if (result && isAgentDirectoryCopy(result) && completed.has(result.state)) await directories.release(result);
} else if (row.location !== "local" && await remoteExecutionHasStopped(db, row.companyId, row.runId)) {
if (row.receipt?.warm === true) {
const unavailable = row.receipt?.warm === true
? await patch(row, { state: "unavailable", errorCode: "AGENT_FILES_FINAL_COLLECTION_UNAVAILABLE",
errorMessage: "The last completed checkpoint remains saved. Files changed afterwards could not be collected after remote termination.", nextAttemptAt: null })
: await reportUnavailable(row.companyId, row.runId);
if (unavailable && isAgentDirectoryCopy(unavailable)) {
} else if (row.receipt?.warm === true) {
const unavailable = await patch(row, { state: "unavailable", errorCode: "AGENT_FILES_FINAL_COLLECTION_UNAVAILABLE",
errorMessage: "The last completed checkpoint remains saved. Files changed afterwards could not be collected after remote termination.", nextAttemptAt: null });
if (isAgentDirectoryCopy(unavailable)) {
await directories.release(await patch(unavailable, { processStoppedAt: unavailable.processStoppedAt ?? new Date() }));
}
} else {
if (isAgentDirectoryCopy(row)) await directories.recoverStoppedRemote(row);
else await reportUnavailable(row.companyId, row.runId);
} else if (isAgentDirectoryCopy(row)) {
const result = await directories.recoverStoppedRemote(row);
if (result && collectionCandidate(result) && !result.processStoppedAt && (result.nextAttemptAt?.getTime() ?? 0) < retryAt.getTime()) {
return patch(result, { nextAttemptAt: retryAt });
}
} else if (row.state === "prepared") {
await patch(row, { state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED",
errorMessage: "The provider's stop has not been confirmed. Instruction collection is pending; no save is claimed.", nextAttemptAt: new Date(Date.now() + 30_000) });
} else if (["warm_saved", "pending_collection", "unchanged_turn"].includes(row.state)) {
await patch(row, { nextAttemptAt: new Date(Date.now() + 30_000) });
}
} else await reportUnavailable(row.companyId, row.runId);
return undefined;
}
type CollectionEntry = { id: string; companyId: string; dueAt: number };
async function loadCollection(scope: InstructionCollectionScope | undefined, admitted: () => boolean) {
@@ -439,7 +465,8 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
throw new Error("Instruction collection reconstruction stopped");
}
async function readCollection(entry: CollectionEntry) {
const [current] = await db.select({ copy: copies, runtimeMode: heartbeatRuns.runtimeMode }).from(copies)
const [current] = await db.select({ copy: copies, runtimeMode: heartbeatRuns.runtimeMode,
waitingSince: sql<Date>`(extract(epoch from coalesce(${heartbeatRuns.finishedAt}, ${copies.createdAt})) * 1000)::float8`.mapWith(value => new Date(Number(value))) }).from(copies)
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, copies.companyId), eq(heartbeatRuns.id, copies.runId)))
.where(and(collectionPredicate(), scope(entry.companyId, entry.id)));
return current;
@@ -450,14 +477,18 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
const dueAt = current.copy.nextAttemptAt?.getTime() ?? 0;
if (dueAt > Date.now()) return { ...entry, dueAt };
if (!admitted()) throw new Error("Instruction collection recovery stopped");
const claimed = await tryPatch(current.copy, { nextAttemptAt: new Date(Date.now() + 30_000) }, true,
const evidence = await stopEvidence(current.copy, current.runtimeMode);
const retryAt = instructionCopyRetryAt(current.waitingSince);
const claimed = await tryPatch(current.copy, evidence === null ? awaitingStop(current.copy, current.waitingSince)
: { nextAttemptAt: evidence === "directory_unavailable" ? retryAt : new Date(Date.now() + INSTRUCTION_COPY_RETRY_MS) }, true,
sql`EXISTS (SELECT 1 FROM ${heartbeatRuns} WHERE ${heartbeatRuns.id} = ${copies.runId}
AND ${heartbeatRuns.companyId} = ${copies.companyId}
AND ${heartbeatRuns.status} IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted'))`);
if (claimed) await collectRecovered(claimed, current.runtimeMode);
const remaining = await readCollection(entry);
const settled = claimed && evidence !== null ? await collectRecovered(claimed, evidence, retryAt) : claimed;
const remaining = settled === undefined || settled === null ? (await readCollection(entry))?.copy
: collectionCandidate(settled) ? settled : null;
if (!remaining) return null;
const next = { ...entry, dueAt: remaining.copy.nextAttemptAt?.getTime() ?? 0 };
const next = { ...entry, dueAt: remaining.nextAttemptAt?.getTime() ?? 0 };
if (next.dueAt <= Date.now()) throw new Error("Instruction collection remains unresolved without a future retry");
return next;
}
@@ -522,9 +553,21 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
const current = directoryCleanupEntry(row);
if (!row || !current || current.dueAt > Date.now()) return current;
if (!admitted()) throw new Error("Directory cleanup recovery stopped");
const claimed = await tryPatch(row, { nextAttemptAt: new Date(Date.now() + 30_000) }, true);
if (claimed) await directories.release(claimed);
const remaining = directoryCleanupEntry(await get(entry.companyId, entry.id));
const retryAt = instructionCopyRetryAt(row.processStoppedAt ?? row.updatedAt);
const claimed = await tryPatch(row, { nextAttemptAt: new Date(Date.now() + INSTRUCTION_COPY_RETRY_MS) }, true);
const deferCleanup = async () => {
const latest = await get(entry.companyId, entry.id);
const pending = directoryCleanupEntry(latest);
return claimed && latest && pending && pending.dueAt < retryAt.getTime() ? patch(latest, { nextAttemptAt: retryAt }) : latest;
};
if (claimed) {
try { await directories.release(claimed); }
catch (error) {
await deferCleanup();
throw error;
}
}
const remaining = directoryCleanupEntry(await deferCleanup());
if (remaining && remaining.dueAt <= Date.now()) throw new Error("Directory cleanup remains unresolved without a future retry");
return remaining;
}
+31 -17
View File
@@ -1,8 +1,8 @@
import { and, eq, getTableColumns, inArray, isNull, sql, type SQL } from "drizzle-orm";
import { and, eq, inArray, isNull, sql, type SQL } from "drizzle-orm";
import { agents, decisionRetention, decisions, heartbeatRuns,
issueApprovals, issueRecoveryActions, issueThreadInteractions, issues, approvals, type Db } from "@paperclipai/db";
import { evaluateAgentInvokability } from "./agent-invokability.js";
import { HUMAN_RECOVERY_OWNER_TYPES, ATTENTION_BUDGET_WARNING_PERCENT, ATTENTION_AGENT_ERROR_STATUS, collapsePendingConfirmationsToNewest, listFailedRunsWithNewerRun, loadNewestSettledConfirmationAt, readRunIssueId, requiresReviewAttention, terminalBlockerRequiresAttention } from "./attention-source-eligibility.js";
import { HUMAN_RECOVERY_OWNER_TYPES, ATTENTION_BUDGET_WARNING_PERCENT, ATTENTION_AGENT_ERROR_STATUS, collapsePendingConfirmationsToNewest, listFailedRunsWithNewerRun, loadNewestSettledConfirmationAt, requiresReviewAttention, terminalBlockerRequiresAttention } from "./attention-source-eligibility.js";
import { decisionRetentionService, DEFAULT_DECISION_ARCHIVE_DAYS } from "./decision-retention.js";
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
@@ -23,12 +23,22 @@ type Candidate = { sourceKind: Kind; sourceId: string; companyId: string; activi
type Entry = Candidate & { id: string; dueAt: number; rootId: string; variant?: "owner" | "terminal" };
type Cursor = { sourceKind: string; sourceId: string };
type PageIssue = typeof issues.$inferSelect & { activityAt: string; deadlineAt: number;
const pageIssueColumns = { id: issues.id, companyId: issues.companyId, parentId: issues.parentId, identifier: issues.identifier,
title: issues.title, status: issues.status, assigneeAgentId: issues.assigneeAgentId, assigneeUserId: issues.assigneeUserId,
executionRunId: issues.executionRunId, unblockDescriptor: issues.unblockDescriptor, blockedTransitionAt: issues.blockedTransitionAt };
const contextSnapshot = heartbeatRuns.contextSnapshot;
const runProbeColumns = { id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, createdAt: heartbeatRuns.createdAt,
issueId: sql<string | null>`case when jsonb_typeof(${contextSnapshot}->'issueId') is not null and jsonb_typeof(${contextSnapshot}->'issueId') <> 'null'
then case when jsonb_typeof(${contextSnapshot}->'issueId') = 'string' then nullif(${contextSnapshot}->>'issueId', '') end
else case when jsonb_typeof(${contextSnapshot}->'taskId') = 'string' then nullif(${contextSnapshot}->>'taskId', '') end end` };
type VisibleIssue = { [K in keyof typeof pageIssueColumns]: (typeof issues.$inferSelect)[K] };
type PageIssue = VisibleIssue & { activityAt: string; deadlineAt: number;
blockedActivityAt: string | null; blockedDeadlineAt: number | null };
type RunProbe = { id: string; agentId: string; createdAt: Date; issueId: string | null };
type PageEvidence = {
decisions: Map<string, { originIssueId: string }>;
recoveries: Map<string, typeof issueRecoveryActions.$inferSelect>;
runs: Map<string, typeof heartbeatRuns.$inferSelect>;
recoveries: Map<string, { id: string; sourceIssueId: string }>;
runs: Map<string, RunProbe>;
agents: Set<string>;
visibleIssues: Map<string, PageIssue>;
newerRuns: Set<string>;
@@ -127,7 +137,7 @@ export function attentionRetentionService(db: Db) {
const candidates = listAttentionRetentionCandidates;
async function visibleIssue(database: Db, companyId: string, issueId: string, conversations = false) {
const [row] = await database.select().from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId),
const [row] = await database.select(pageIssueColumns).from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId),
attentionIssueCondition(conversations)));
return row;
}
@@ -149,7 +159,8 @@ export function attentionRetentionService(db: Db) {
const visible = await database.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, companyId),
inArray(issues.id, rows.map(row => row.issueId)), attentionIssueCondition(true)));
const visibleIds = new Set(visible.map(row => row.id));
const roster = await database.select().from(agents).where(eq(agents.companyId, companyId));
const roster = await database.select({ id: agents.id, companyId: agents.companyId, name: agents.name,
reportsTo: agents.reportsTo, status: agents.status }).from(agents).where(eq(agents.companyId, companyId));
const boardAddressed = (row: typeof issueThreadInteractions.$inferSelect) => !row.addresseeAgentId
|| !evaluateAgentInvokability(roster.find(agent => agent.id === row.addresseeAgentId), roster).invokable;
const confirmationIssueIds = rows.filter(row => row.kind === "request_confirmation").map(row => row.issueId);
@@ -175,7 +186,8 @@ export function attentionRetentionService(db: Db) {
byCompany.set(candidate.companyId, ids);
}
for (const [companyId, ids] of byCompany) {
const rows = await database.select().from(issues).where(and(eq(issues.companyId, companyId),
const rows = await database.select({ id: issues.id, companyId: issues.companyId, status: issues.status,
executionState: issues.executionState, assigneeUserId: issues.assigneeUserId }).from(issues).where(and(eq(issues.companyId, companyId),
inArray(issues.id, ids), attentionIssueCondition(false)));
const pendingApprovals = await database.select({ issueId: issueApprovals.issueId }).from(issueApprovals)
.innerJoin(approvals, eq(approvals.id, issueApprovals.approvalId)).where(and(
@@ -209,14 +221,15 @@ export function attentionRetentionService(db: Db) {
const decisionIds = ids("decision"), recoveryIds = ids("recovery_action"), runIds = ids("failed_run"), blockerIds = ids("blocker_attention");
const decisionRows = decisionIds.length ? await database.select({ id: decisions.id, originIssueId: decisions.originIssueId })
.from(decisions).where(and(eq(decisions.companyId, companyId), inArray(decisions.id, decisionIds), eq(decisions.status, "open"))) : [];
const recoveryRows = recoveryIds.length ? await database.select().from(issueRecoveryActions).where(and(
const recoveryRows = recoveryIds.length ? await database.select({ id: issueRecoveryActions.id,
sourceIssueId: issueRecoveryActions.sourceIssueId }).from(issueRecoveryActions).where(and(
eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.id, recoveryIds))) : [];
const runRows = runIds.length ? await database.select().from(heartbeatRuns).where(and(
const runRows: RunProbe[] = runIds.length ? await database.select(runProbeColumns).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.id, runIds))) : [];
const runAgents = runRows.length ? await database.select({ id: agents.id }).from(agents).where(and(
eq(agents.companyId, companyId), inArray(agents.id, [...new Set(runRows.map(row => row.agentId))]),
sql`${agents.status} <> 'terminated'`)) : [];
const readIssues = async (issueIds: string[]) => issueIds.length ? database.select({ ...getTableColumns(issues),
const readIssues = async (issueIds: string[]) => issueIds.length ? database.select({ ...pageIssueColumns,
activityAt: sql<string>`${issues.updatedAt}::text`,
deadlineAt: sql<number>`ceil(extract(epoch from ${issues.updatedAt}) * 1000 + ${archiveDelay})`.mapWith(Number),
blockedActivityAt: sql<string | null>`${issues.blockedTransitionAt}::text`,
@@ -224,7 +237,7 @@ export function attentionRetentionService(db: Db) {
}).from(issues).where(and(eq(issues.companyId, companyId), inArray(issues.id, [...new Set(issueIds)]),
attentionIssueCondition(false))) : [];
const issueIds = [...blockerIds, ...decisionRows.map(row => row.originIssueId), ...recoveryRows.map(row => row.sourceIssueId),
...runRows.map(row => readRunIssueId(row.contextSnapshot))].filter((id): id is string => Boolean(id));
...runRows.map(row => row.issueId)].filter((id): id is string => Boolean(id));
const visibleRows = await readIssues(issueIds);
const visible = new Map(visibleRows.map(row => [row.id, row]));
const blockerRoots = visibleRows.filter(row => blockerIds.includes(row.id));
@@ -238,7 +251,7 @@ export function attentionRetentionService(db: Db) {
decisions: new Map(decisionRows.map(row => [row.id, row])), recoveries: new Map(recoveryRows.map(row => [row.id, row])),
runs: new Map(runRows.map(row => [row.id, row])), agents: new Set(runAgents.map(row => row.id)), visibleIssues: visible,
newerRuns: await listFailedRunsWithNewerRun(database, companyId,
runRows.map(run => ({ ...run, issueId: readRunIssueId(run.contextSnapshot) }))), blockers, deferredRoots: blockerBatch.deferredRootIds,
runRows), blockers, deferredRoots: blockerBatch.deferredRootIds,
});
}
return result;
@@ -261,7 +274,8 @@ export function attentionRetentionService(db: Db) {
const attention = interactionAttention ?? await interactionEligibility(database, [candidate]);
if (!attention.get(sourceId)) return null;
} else if (candidate.sourceKind === "recovery_action") {
const row = evidence ? evidence.recoveries.get(sourceId) : (await database.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, candidate.companyId), eq(issueRecoveryActions.id, sourceId))))[0];
const row = evidence ? evidence.recoveries.get(sourceId) : (await database.select({ id: issueRecoveryActions.id,
sourceIssueId: issueRecoveryActions.sourceIssueId }).from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, candidate.companyId), eq(issueRecoveryActions.id, sourceId))))[0];
if (!row || !(evidence ? evidence.visibleIssues.has(row.sourceIssueId)
: await visibleIssue(database, candidate.companyId, row.sourceIssueId))) return null;
} else if (candidate.sourceKind === "review") {
@@ -297,14 +311,14 @@ export function attentionRetentionService(db: Db) {
eq(decisionRetention.sourceKind, candidate.sourceKind), eq(decisionRetention.sourceId, sourceId)));
if (retention?.keep || retention?.archivedAt) return null;
} else if (candidate.sourceKind === "failed_run") {
const run = evidence ? evidence.runs.get(sourceId) : (await database.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.id, sourceId))))[0];
const run: RunProbe | undefined = evidence ? evidence.runs.get(sourceId) : (await database.select(runProbeColumns).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.id, sourceId))))[0];
if (!run) return null;
const agent = evidence ? evidence.agents.has(run.agentId) : (await database.select({ id: agents.id }).from(agents).where(and(eq(agents.companyId, candidate.companyId),
eq(agents.id, run.agentId), sql`${agents.status} <> 'terminated'`)))[0];
const issueId = readRunIssueId(run.contextSnapshot);
const issueId = run.issueId;
if (!agent || issueId && !(evidence ? evidence.visibleIssues.has(issueId)
: await visibleIssue(database, candidate.companyId, issueId))) return null;
if ((evidence ? evidence.newerRuns : await listFailedRunsWithNewerRun(database, candidate.companyId, [{ ...run, issueId }])).has(run.id)) return null;
if ((evidence ? evidence.newerRuns : await listFailedRunsWithNewerRun(database, candidate.companyId, [run])).has(run.id)) return null;
}
return { ...candidate, sourceId, activityAt, rootId: candidate.sourceId, variant,
id: `${candidate.sourceKind}:${candidate.sourceId}:${variant ?? "source"}`, dueAt };
@@ -5,10 +5,8 @@ import { chatActions, chatConversations, chatEndpointLeases, chatEndpointResourc
chatPublications, fastResponseRequests, chatEndpoints, chatMessageLinks, type Db } from "@paperclipai/db";
import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js";
import type { ChatResponseScope } from "../../chat-response-availability.js";
import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js";
type Scope = ChatResponseScope & { endpointId?: string; repositoryId?: string; number?: number };
import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js";
type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string;
issueId: string | null; conversationId: string | null; repositoryId: string | null; number: number | null; dueAt: number };
type FastResponse = { status: string; expiresAt: string; publicationState: string | null };
@@ -83,6 +81,7 @@ export function registerGitHubAcknowledgementWork(
}
return registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.chatGitHubAcknowledgements,
reconstructionIntervalMs: githubResponseReconstructionIntervalMs,
decodeScope: (hint: string): Scope | undefined => hint === "*" ? undefined : JSON.parse(hint),
matches: (value: Entry, scope?: Scope) => !scope || (value.companyId === scope.companyId &&
(!scope.issueId || value.issueId === scope.issueId) && (!scope.deliveryId || value.deliveryId === scope.deliveryId) &&
@@ -0,0 +1,118 @@
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { createDb, type Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { registerGitHubAcknowledgementWork } from "./acknowledgement-work.js";
import { registerGitHubTerminalResponseWork } from "./terminal-response-work.js";
import { GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS } from "./response-sweep-scope.js";
const support = await getEmbeddedPostgresTestSupport();
const suite = support.supported ? describe : describe.skip;
type Task = { run(signal: AbortSignal): Promise<unknown>; onSettled?(hints?: ReadonlySet<string>): void };
suite("GitHub response sweep scopes", () => {
let db!: Db;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let companyId = "";
const parkedIssues: string[] = [];
let clock = Date.now();
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("paperclip-github-response-sweep-scope-");
db = createDb(temporary.connectionString);
const client = db.$client;
const [{ company }] = await client.unsafe(`insert into companies (name, issue_prefix) values ('Sweep', 'SW') returning id as company`);
companyId = company;
const [{ agent }] = await client.unsafe(`insert into agents (company_id, name) values ($1, 'GitHub agent') returning id as agent`, [company]);
const [{ application }] = await client.unsafe(`insert into tool_applications (company_id, application_key, name, type)
values ($1, 'github', 'GitHub', 'chat') returning id as application`, [company]);
const [{ connection }] = await client.unsafe(`insert into tool_connections (company_id, application_id, name, uid, transport, connection_purpose)
values ($1, $2, 'GitHub', 'github-sweep', 'chat_sdk', 'channel') returning id as connection`, [company, application]);
const [{ endpoint }] = await client.unsafe(`insert into chat_endpoints (company_id, connection_id, provider, public_id, assigned_agent_id, status)
values ($1, $2, 'github', 'sweep', $3, 'active') returning id as endpoint`, [company, connection, agent]);
for (let n = 1; n <= 6; n++) {
const [{ issue }] = await client.unsafe(`insert into issues (company_id, title, status) values ($1, $2, 'in_progress') returning id as issue`,
[company, `Issue ${n}`]);
parkedIssues.push(issue);
const [{ conversation }] = await client.unsafe(`insert into chat_conversations (company_id, endpoint_id, issue_id,
external_conversation_id, external_label, external_thread_id) values ($1, $2, $3, $4, $4, $4) returning id as conversation`,
[company, endpoint, issue, `github:paperclipai/paperclip:${n}`]);
const [{ delivery }] = await client.unsafe(`insert into chat_deliveries (company_id, endpoint_id, provider_event_id, deduplication_key,
event_kind, normalized_event, conversation_id, state) values ($1, $2, $3, $3, 'message', '{}', $4, 'processed') returning id as delivery`,
[company, endpoint, `event-${n}`, conversation]);
const [{ comment }] = await client.unsafe(`insert into issue_comments (company_id, issue_id, body) values ($1, $2, 'Request')
returning id as comment`, [company, issue]);
await client.unsafe(`insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, comment_id,
provider_message_id, direction) values ($1, $2, $3, $4, $5, $6, 'inbound')`,
[company, endpoint, conversation, delivery, comment, `in-${n}`]);
await client.unsafe(`insert into chat_actions (company_id, endpoint_id, delivery_id, conversation_id, kind, provider_action_id, status, result)
values ($1, $2, $3, $4, 'github_response_comment', $5, $6, $7::jsonb)`,
[company, endpoint, delivery, conversation, `github_response:${delivery}`, n % 2 ? "received" : "processed",
n % 2 ? null : JSON.stringify({ id: `IC_${n}`, final: false })]);
await client.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, runtime_mode, scope_kind, issue_id, native_issue_id,
context_snapshot, finished_at) values ($1, $2, 'succeeded', 'native', 'issue', $3, $3, $4::jsonb, now())`,
[company, agent, issue, JSON.stringify({ issueId: issue, wakeCommentId: comment })]);
}
}, 120_000);
afterEach(() => { vi.restoreAllMocks(); });
afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); });
function sweeps() {
let reads = 0;
const counted = new Proxy(db, { get(target, key) {
if (key !== "select") return Reflect.get(target, key);
return (...fields: Parameters<Db["select"]>) => {
const builder = target.select(...fields), from = builder.from.bind(builder);
builder.from = ((...args: Parameters<typeof from>) => {
const selection = from(...args), execute = selection.execute.bind(selection);
selection.execute = (async () => {
if (selection.toSQL().sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) reads += 1;
return execute();
}) as typeof selection.execute;
return selection;
}) as typeof builder.from;
return builder;
};
} }) as Db;
const tasks: Task[] = [];
const coordinator = { register: (_queue: unknown, task: Task) => { tasks.push(task); return { wake() {}, stop: async () => {} }; } };
const acknowledge = vi.fn(async () => undefined);
registerGitHubAcknowledgementWork(counted, coordinator as never, acknowledge, () => true);
registerGitHubTerminalResponseWork(counted, coordinator as never, acknowledge, () => true);
vi.spyOn(Date, "now").mockImplementation(() => clock);
const pass = async (hint?: string) => {
clock += 2_000;
const before = reads;
for (const task of tasks) {
if (hint) task.onSettled?.(new Set([hint]));
await task.run(new AbortController().signal);
}
return reads - before;
};
return { pass, acknowledge };
}
it("rebuilds parked requests once per interval for company-wide hints", async () => {
const { pass, acknowledge } = sweeps();
expect(await pass()).toBe(parkedIssues.length);
const companyHint = JSON.stringify({ companyId });
const repeated = [];
for (let index = 0; index < 5; index++) repeated.push(await pass(companyHint));
expect(repeated).toEqual([parkedIssues.length, 0, 0, 0, 0]);
clock += GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS;
expect(await pass()).toBe(parkedIssues.length);
expect(acknowledge).not.toHaveBeenCalled();
}, 60_000);
it("still rebuilds an issue, request or other company immediately", async () => {
const { pass } = sweeps();
await pass();
await pass(JSON.stringify({ companyId }));
expect(await pass(JSON.stringify({ companyId, issueId: parkedIssues[0] }))).toBe(1);
expect(await pass(JSON.stringify({ companyId, issueId: parkedIssues[1] }))).toBe(1);
expect(await pass(JSON.stringify({ companyId, issueId: parkedIssues[0] }))).toBe(1);
expect(await pass(JSON.stringify({ companyId: randomUUID() }))).toBe(0);
}, 60_000);
});
@@ -0,0 +1,10 @@
import type { ChatResponseScope } from "../../chat-response-availability.js";
export type GitHubResponseSweepScope = ChatResponseScope & { endpointId?: string; repositoryId?: string; number?: number };
export const GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS = 30_000;
export function githubResponseReconstructionIntervalMs(scope: GitHubResponseSweepScope | undefined) {
return scope && !scope.issueId && !scope.deliveryId && !scope.conversationId && !scope.endpointId
&& !scope.repositoryId && !scope.number ? GITHUB_RESPONSE_COMPANY_RECONSTRUCTION_MS : 0;
}
@@ -3,12 +3,10 @@ import { chatActions, chatConversations, chatDeliveries, chatEndpointLeases, cha
chatEndpoints, chatMessageLinks, heartbeatRuns, issues, type Db } from "@paperclipai/db";
import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js";
import type { ChatResponseScope } from "../../chat-response-availability.js";
import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js";
import { githubResponseExecution } from "./response-execution.js";
import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js";
import { HttpError } from "../../../errors.js";
type Scope = ChatResponseScope & { endpointId?: string; repositoryId?: string; number?: number };
type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string;
issueId: string; conversationId: string; repositoryId: string | null; number: number | null; dueAt: number };
@@ -87,6 +85,7 @@ export function registerGitHubTerminalResponseWork(
return registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.chatGitHubTerminalResponses,
reconstructionIntervalMs: githubResponseReconstructionIntervalMs,
decodeScope: (hint: string): Scope | undefined => hint === "*" ? undefined : JSON.parse(hint),
matches: (value: Entry, scope?: Scope) => !scope || (value.companyId === scope.companyId &&
(!scope.issueId || value.issueId === scope.issueId) && (!scope.deliveryId || value.deliveryId === scope.deliveryId) &&
+4 -4
View File
@@ -1,6 +1,6 @@
import { notifyStatusCardIssueChange } from "./status-card-notifications.js";
import { assertAgentInteraction } from "./agent-interaction-policy.js";
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-notifications.js";
import { randomUUID } from "node:crypto";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
@@ -290,7 +290,7 @@ export function documentService(db: Db) {
.where(eq(issueDocuments.issueId, issue.id));
const fallbackKey = nextAvailableDocumentKey(key, issueDocumentKeys.map((row) => row.key));
await notifyIssueRecovery(tx, { companyId: issue.companyId });
await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id });
const [document] = await tx
.insert(documents)
.values({
@@ -392,7 +392,7 @@ export function documentService(db: Db) {
});
}
await notifyIssueRecovery(tx, { companyId: issue.companyId });
await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id });
const nextRevisionNumber = existing.latestRevisionNumber + 1;
const [revision] = await tx
.insert(documentRevisions)
@@ -455,7 +455,7 @@ export function documentService(db: Db) {
throw conflict("Document does not exist yet", { key });
}
await notifyIssueRecovery(tx, { companyId: issue.companyId });
await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id });
const [document] = await tx
.insert(documents)
.values({
@@ -1,5 +1,5 @@
import { notifyLiveRunRecovery, notifyLiveResourceRecovery } from "./live-run-recovery-notifications.js";
import { notifyAttentionRetentionWork } from "./retention-work-notifications.js";
import { notifyAttentionRetentionWork, notifyIssueAttentionRetentionWork } from "./retention-work-notifications.js";
import { notifyDeferredExecutionEligibility } from "./deferred-execution-notifications.js";
import { notifyRunDispatch } from "./run-dispatch-notifications.js";
import { notifyStatusCardIssueChange } from "./status-card-notifications.js";
@@ -9,9 +9,14 @@ import { DELIVERY_QUEUES, notifyDeliveryWork, type DeliveryQueue } from "./deliv
export type ExecutionWorkScope = { companyId: string; agentId?: string; runId?: string; issueId?: string };
async function notifyExecutionAttentionRetention(transaction: object, scope: ExecutionWorkScope) {
if (scope.issueId || scope.runId) await notifyIssueAttentionRetentionWork(transaction, { companyId: scope.companyId, issueId: scope.issueId, runId: scope.runId });
else await notifyAttentionRetentionWork(transaction, scope);
}
export async function notifyExecutionRunWork(transaction: object, scope?: ExecutionWorkScope) {
if (scope) {
await notifyAttentionRetentionWork(transaction, scope);
await notifyExecutionAttentionRetention(transaction, scope);
await notifyRunDispatch(transaction, scope);
await notifyStatusCardIssueChange(transaction, scope.companyId);
await notifyDeferredExecutionEligibility(transaction, scope);
@@ -36,7 +41,7 @@ export function writeExecutionControl<T>(
await notifyRunDispatch(transaction, scope);
if (scope) {
await notifyStatusCardIssueChange(transaction, scope.companyId);
await notifyAttentionRetentionWork(transaction, scope);
await notifyExecutionAttentionRetention(transaction, scope);
await notifyRoutineExecutionStatus(transaction, scope.issueId, scope.companyId);
await notifyDeferredExecutionEligibility(transaction, scope);
await notifyLiveRunRecovery(transaction, scope);
@@ -1,9 +1,10 @@
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import type { ExternalConversationSettlementScope } from "./slack-conversation-lifecycle.js";
export async function notifyExternalConversationSettlement(tx: object, scope?: ExternalConversationSettlementScope) {
await notifyIssueRecovery(tx, scope);
if (scope?.issueId || scope?.runId) await notifyIssueGraphRecovery(tx, scope);
else await notifyIssueRecovery(tx, scope);
return notifyDeliveryWork(tx, DELIVERY_QUEUES.externalConversationSettlement,
scope ? JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }) : "*");
}
+4 -3
View File
@@ -4121,7 +4121,7 @@ export function heartbeatService(
await writeExecutionControl(db, DELIVERY_QUEUES.executionFinalization, tx => tx
.update(heartbeatRuns)
.set({ executionControlDeadlineAt: null })
.where(eq(heartbeatRuns.id, run.id)), { companyId: run.companyId });
.where(eq(heartbeatRuns.id, run.id)), { companyId: run.companyId, runId: run.id });
}
nativeOwnershipHeld =
nativeOwnershipHeld ||
@@ -4725,7 +4725,8 @@ export function heartbeatService(
schedulingSuppressed: async () => (await getSchedulingSuppression(true)).suppressed,
prepareChatRetry,
}, () => canRun() && readTaskDrain(new Date()) === null),
registerIssueStateRecoveryWork: (coordinator: Parameters<typeof registerIssueRecoveryWork>[1], canRun: () => boolean) =>
registerIssueStateRecoveryWork: (coordinator: Parameters<typeof registerIssueRecoveryWork>[1], canRun: () => boolean,
options?: Parameters<typeof registerIssueRecoveryWork>[4]) =>
registerIssueRecoveryWork(db, coordinator, {
stranded: scope => reconcileStrandedAssignedIssues({ ...scope, skipExternalConversationSettlement: true, skipRelatedRecovery: true }),
orphanBlockers: recovery.reconcileUnassignedBlockingIssues,
@@ -4739,7 +4740,7 @@ export function heartbeatService(
checkIssue: recovery.assignedWork.checkIssue,
},
schedulingSuppressed: async () => (await getSchedulingSuppression(true)).suppressed,
}, () => canRun() && readTaskDrain(new Date()) === null),
}, () => canRun() && readTaskDrain(new Date()) === null, options),
registerRunDispatchWork: (coordinator: Parameters<typeof registerRunDispatchWork>[0], canRun: () => boolean) =>
registerRunDispatchWork(coordinator, {
promoteDueScheduledRetries,
@@ -94,7 +94,7 @@ export function createHeartbeatAgentStatus(db: Db) {
const nextStatus = running ? "running" : settledStatus(outcome, options?.keepIdleOnFailure);
const now = new Date();
await notifyStrandedAgentStatus(tx, { companyId: existing.companyId, agentId });
await notifyAttentionRetentionWork(tx, { companyId: existing.companyId });
await notifyAttentionRetentionWork(tx, { companyId: existing.companyId, sourceKind: "agent_error_alert" });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
const [updated] = await tx.update(agents).set({
status: nextStatus,
@@ -152,7 +152,7 @@ export function createHeartbeatAgentStatus(db: Db) {
eq(heartbeatRuns.agentId, candidate.id)))
.orderBy(desc(heartbeatRuns.finishedAt), desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);
const nextStatus = settledStatus(lastRun?.status);
await notifyAttentionRetentionWork(tx, { companyId: candidate.companyId });
await notifyAttentionRetentionWork(tx, { companyId: candidate.companyId, sourceKind: "agent_error_alert" });
const [agent] = await tx.update(agents).set({ status: nextStatus,
errorReason: nextStatus === "error" ? errorReason(lastRun?.error) : null, updatedAt: now,
}).where(and(eq(agents.id, candidate.id), eq(agents.companyId, candidate.companyId),
@@ -1,6 +1,6 @@
import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js";
import { legacyWorkspaceRecoveryNotMigrated } from "../legacy-workspace-recovery-migration.js";
import { settledNativeProcessIdentityCondition } from "../native-local-process-stop.js";
import { settledNativeProcessCandidates } from "../native-local-process-stop.js";
import { and, asc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
import { agents, environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
@@ -9,6 +9,8 @@ import type { LiveResourceRecoveryScope, LiveRunRecoveryScope } from "../live-ru
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
const TERMINAL = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"];
const SETTLED_PENDING_BASE_DELAY_MS = 30_000;
const SETTLED_PENDING_MAX_DELAY_MS = 15 * 60_000;
type Scope = LiveRunRecoveryScope & LiveResourceRecoveryScope;
type Entry = { id: string; companyId: string; runId?: string | null; dueAt: number };
type CheckScope = { companyId: string; runId?: string; leaseId?: string; agentId?: string;
@@ -27,6 +29,8 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType<typeof
}, canRun: () => boolean) {
function register(queue: DeliveryQueue, kind: RunKind | "orphanLease" | "shutdown" | "agent") {
const cursors = new Map<string, string>();
const settledOutcomes = new Map<string, { companyId: string; parked: boolean; attempts: number; notBefore: number }>();
const settledScans = new Map<string, Set<string>>();
let enabled = false;
async function load(scope?: Scope) {
const key = scope ? JSON.stringify({ companyId: scope.companyId, runId: scope.runId,
@@ -63,12 +67,11 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType<typeof
? row.runId ? row.updatedAt.getTime() : row.updatedAt.getTime() + 5 * 60_000
: Date.parse(String((row.metadata?.legacyShutdownWorkspaceSettlement as Record<string, unknown>)?.deadlineAt)) || Date.now(),
}));
} else if (kind === "settled") {
const page = await loadSettled(scope, cursor);
if (page.complete) cursors.delete(key); else cursors.set(key, page.rows.at(-1)!.id);
return { complete: page.complete, rows: applySettledOutcomes(key, scope, page.rows, page.complete) };
} else {
// Retirement may commit before Stop acknowledgement. This is only a
// work hint; the owner rechecks the complete provider/process proof.
const pendingApiStop = and(eq(heartbeatRuns.status, "cancelled"), eq(heartbeatRuns.driverKind, "cursor_cloud_api"),
sql`${heartbeatRuns.runnerProfileJson}->>'backend' = 'cursor_cloud_api'`,
sql`${heartbeatRuns.resultJson}->'executionCancellation'->>'state' = 'requested'`);
const candidates = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId,
nextAttemptAt: nativeRunFinalizations.nextAttemptAt, leaseExpiresAt: nativeRunFinalizations.leaseExpiresAt })
.from(heartbeatRuns).leftJoin(nativeRunFinalizations, and(eq(nativeRunFinalizations.runId, heartbeatRuns.id),
@@ -83,12 +86,8 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType<typeof
: kind === "question" ? and(or(inArray(heartbeatRuns.status, ["queued", "running", "scheduled_retry"]),
pendingFailedNativeRetryCancellationCondition()),
sql`${heartbeatRuns.contextSnapshot}->'nativeQuestionCancellation' is not null`)
: kind === "active" ? and(eq(heartbeatRuns.status, "running"),
sql`${heartbeatRuns.contextSnapshot}->'nativeQuestionCancellation' is null`)
: and(eq(heartbeatRuns.runtimeMode, "native"), inArray(heartbeatRuns.status, ["failed", "cancelled", "timed_out", "interrupted"]),
isNotNull(heartbeatRuns.finishedAt), or(pendingApiStop,
and(or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId),
isNotNull(heartbeatRuns.processStartedAt)), settledNativeProcessIdentityCondition(db)))),
: and(eq(heartbeatRuns.status, "running"),
sql`${heartbeatRuns.contextSnapshot}->'nativeQuestionCancellation' is null`),
)).orderBy(asc(heartbeatRuns.id)).limit(100);
rows = candidates.map(row => ({ id: row.id, companyId: row.companyId, dueAt: kind === "native"
? Math.max(Date.now(), row.nextAttemptAt?.getTime() ?? 0, row.leaseExpiresAt?.getTime() ?? 0) : Date.now() }));
@@ -97,6 +96,50 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType<typeof
if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id);
return { complete, rows };
}
async function loadSettled(scope: Scope | undefined, cursor: string | undefined) {
const bounds = and(scope ? eq(heartbeatRuns.companyId, scope.companyId) : undefined,
scope?.runId ? eq(heartbeatRuns.id, scope.runId) : undefined, cursor ? gt(heartbeatRuns.id, cursor) : undefined);
const select = (condition: ReturnType<typeof and>) => db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId })
.from(heartbeatRuns).where(and(bounds, condition)).orderBy(asc(heartbeatRuns.id)).limit(100);
const processes = await settledNativeProcessCandidates(db, { companyId: scope?.companyId, runId: scope?.runId,
after: cursor, limit: 100 });
const stops = await select(and(eq(heartbeatRuns.status, "cancelled"), eq(heartbeatRuns.driverKind, "cursor_cloud_api"),
sql`(${heartbeatRuns.resultJson}->'executionCancellation'->>'state') = 'requested'`,
eq(heartbeatRuns.runtimeMode, "native"), isNotNull(heartbeatRuns.finishedAt),
sql`${heartbeatRuns.runnerProfileJson}->>'backend' = 'cursor_cloud_api'`));
const merged = [...new Map([...processes, ...stops].map(row => [row.id, row])).values()]
.sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
const complete = processes.length < 100 && stops.length < 100 && merged.length <= 100;
return { complete, rows: merged.slice(0, 100).map(row => ({ ...row, dueAt: Date.now() })) };
}
function applySettledOutcomes(key: string, scope: Scope | undefined, rows: Entry[], complete: boolean) {
if (scope?.runId) settledOutcomes.delete(scope.runId);
const seen = settledScans.get(key) ?? new Set<string>();
for (const row of rows) seen.add(row.id);
if (!complete) settledScans.set(key, seen);
else {
settledScans.delete(key);
if (!scope?.runId) for (const [id, outcome] of settledOutcomes)
if ((!scope || outcome.companyId === scope.companyId) && !seen.has(id)) settledOutcomes.delete(id);
}
return rows.flatMap(row => {
const outcome = settledOutcomes.get(row.id);
if (outcome?.parked) return [];
return [{ ...row, dueAt: Math.max(row.dueAt, outcome?.notBefore ?? 0) }];
});
}
function recordSettledOutcome(entry: Entry, outcome: unknown): Entry | null | undefined {
if (outcome === "released") { settledOutcomes.delete(entry.id); return null; }
if (outcome === "skipped") {
settledOutcomes.set(entry.id, { companyId: entry.companyId, parked: true, attempts: 0, notBefore: 0 });
return null;
}
if (outcome !== "pending") return undefined;
const attempts = (settledOutcomes.get(entry.id)?.attempts ?? 0) + 1;
const notBefore = Date.now() + Math.min(SETTLED_PENDING_MAX_DELAY_MS, SETTLED_PENDING_BASE_DELAY_MS * 2 ** (attempts - 1));
settledOutcomes.set(entry.id, { companyId: entry.companyId, parked: false, attempts, notBefore });
return { ...entry, dueAt: notBefore };
}
return registerScopedDeadlineWork<Entry, Scope>(coordinator, {
queue,
reconstructionIntervalMs: 30_000,
@@ -114,10 +157,12 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType<typeof
const currentScope = { companyId: entry.companyId,
...(kind === "agent" ? { agentId: entry.id } : kind === "orphanLease" || kind === "shutdown"
? { leaseId: entry.id } : { runId: entry.id }) };
const loaded = await load(currentScope);
const current = (Array.isArray(loaded) ? loaded : loaded.rows).find(row => row.id === entry.id);
if (!current) return null;
if (current.dueAt > Date.now()) return current;
if (kind !== "settled") {
const loaded = await load(currentScope);
const current = (Array.isArray(loaded) ? loaded : loaded.rows).find(row => row.id === entry.id);
if (!current) return null;
if (current.dueAt > Date.now()) return current;
}
let next: number | null = null;
const errors: unknown[] = [];
const scope: CheckScope = { companyId: entry.companyId,
@@ -126,8 +171,12 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType<typeof
onDeferredDeadline: at => { next = next === null ? at : Math.min(next, at); },
onError: error => { errors.push(error); },
};
await owner[kind](scope);
const outcome = await owner[kind](scope);
if (errors.length) throw new AggregateError(errors, `Recovery obligation ${entry.id} failed`);
if (kind === "settled") {
const settled = recordSettledOutcome(entry, outcome);
if (settled !== undefined) return settled;
}
if (kind === "native") {
const refreshed = await load(currentScope);
const remaining = (Array.isArray(refreshed) ? refreshed : refreshed.rows).find(row => row.id === entry.id);
+1 -1
View File
@@ -5355,7 +5355,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
}
const queueOutcome = await db.transaction(async (tx) => {
await notifyRunDispatch(tx, { companyId: agent.companyId });
await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId) });
await tx.execute(
sql`select id from agents where id = ${agentId} and company_id = ${agent.companyId} for update`,
);
@@ -31,6 +31,7 @@ import { persistHeartbeatRunProcessMetadata } from "./run-lifecycle.js";
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
import { hasNativeLocalProcessStop, PROCESS_START_REQUESTED, releaseSettledNativeRunProcess } from "../native-local-process-stop.js";
import { legacyControllerBootId } from "../legacy-controller-lease.js";
import { runBoundedShutdownStep } from "../../shutdown.js";
type Run = typeof heartbeatRuns.$inferSelect;
@@ -44,10 +45,12 @@ const native = vi.hoisted(() => ({
}));
const hotRestart = vi.hoisted(() => ({
read: vi.fn<() => Promise<HotRestartIntent | null>>(async () => null),
write: vi.fn(async () => undefined),
}));
vi.mock("../hot-restart.js", async (importOriginal) => ({
...await importOriginal<typeof import("../hot-restart.js")>(),
readHotRestartIntent: hotRestart.read,
writeHotRestartShutdownSnapshot: hotRestart.write,
}));
vi.mock("../native-runtime/index.js", async (importOriginal) => ({
...await importOriginal<typeof import("../native-runtime/index.js")>(),
@@ -1500,6 +1503,122 @@ describePostgres("heartbeat recovery module ownership", () => {
}
});
async function seedOwnedNativeRun() {
const run = await seedRun();
const identity = await currentNativeControllerIdentity();
await db.update(agents).set({ adapterType: "paperclip_runner" }).where(eq(agents.id, run.agentId));
const [nativeRun] = await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: run.issueId, nativeSessionId: randomUUID() })
.where(eq(heartbeatRuns.id, run.id)).returning();
await db.insert(nativeRunFinalizations).values({ runId: run.id, companyId: run.companyId, issueId: run.issueId!,
phase: "observed", controllerBootId: identity.bootId, leaseOwner: "departing-server", leaseExpiresAt: new Date(Date.now() + 60_000) });
return nativeRun;
}
async function removeNativeRun(runId: string) {
await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
}
const finalization = async (runId: string) =>
(await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0];
const drainHasStarted = () => new Promise(resolve => setTimeout(resolve, 250));
it("does not count an early hand-off as suspended while its detach is still pending at the shutdown drain", async () => {
const run = await seedOwnedNativeRun(), recovery = createHeartbeatRecovery(db, callbacks(db));
let finishDetach!: () => void;
native.detach.mockImplementationOnce(() => new Promise<number>(resolve => { finishDetach = () => resolve(0); }));
try {
const early = recovery.handOffNativeRunsForShutdown("SIGTERM");
await vi.waitFor(() => expect(native.detach).toHaveBeenCalledTimes(1));
let drained = false;
const drain = recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id]).finally(() => { drained = true; });
await drainHasStarted();
expect(drained).toBe(false);
expect((await finalization(run.id)).recoveryState).toBeNull();
finishDetach();
expect(await early).toEqual([run.id]);
expect((await drain).restartSuspendedRunIds).toEqual([run.id]);
expect(native.detach).toHaveBeenCalledTimes(1);
expect(await finalization(run.id)).toMatchObject({ recoveryState: "awaiting_runner_reattach" });
} finally {
finishDetach?.();
await removeNativeRun(run.id);
}
});
it("hands off a run at the shutdown drain when its pending early hand-off fails", async () => {
const run = await seedOwnedNativeRun(), recovery = createHeartbeatRecovery(db, callbacks(db));
let failDetach!: (error: Error) => void;
native.detach.mockImplementationOnce(() => new Promise<number>((_resolve, reject) => { failDetach = reject; }));
try {
const early = recovery.handOffNativeRunsForShutdown("SIGTERM");
await vi.waitFor(() => expect(native.detach).toHaveBeenCalledTimes(1));
const drain = recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id]);
await drainHasStarted();
failDetach(new Error("runner detach failed"));
expect(await early).toEqual([]);
expect((await drain).restartSuspendedRunIds).toEqual([run.id]);
expect(native.detach).toHaveBeenCalledTimes(2);
expect(await finalization(run.id)).toMatchObject({ recoveryState: "awaiting_runner_reattach" });
} finally {
await removeNativeRun(run.id);
}
});
it("writes no hot-restart snapshot and detaches nothing after a timed-out preparation hands over to the drain", async () => {
const run = await seedOwnedNativeRun(), recovery = createHeartbeatRecovery(db, callbacks(db));
hotRestart.read.mockResolvedValue({ version: 1, requestedAt: new Date().toISOString(), previousServerPid: process.pid,
previousServerVersion: null, drainRequired: false, requestedByRunId: null, preflightActiveRunIds: [] });
let finishIdleClose!: () => void;
native.closeIdle.mockImplementationOnce(() => new Promise(resolve => { finishIdleClose = () => resolve({ closed: 0, failed: 0 }); }));
let preparation: ReturnType<typeof recovery.prepareHotRestartShutdown> | undefined;
try {
const step = await runBoundedShutdownStep({ step: "hot_restart_prepare", signal: "SIGTERM", timeoutMs: 50,
log: { info: vi.fn(), error: vi.fn() },
run: abort => (preparation = recovery.prepareHotRestartShutdown("SIGTERM", new Date(), abort)) });
expect(step.outcome).toBe("timed_out");
expect((await recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), [run.id])).restartSuspendedRunIds).toEqual([run.id]);
expect(native.detach).toHaveBeenCalledTimes(1);
finishIdleClose();
await expect(preparation).rejects.toThrow("timed out");
expect(hotRestart.write).not.toHaveBeenCalled();
expect(native.detach).toHaveBeenCalledTimes(1);
} finally {
finishIdleClose?.();
await preparation?.catch(() => undefined);
await removeNativeRun(run.id);
}
});
it("records no more hot-restart run events after the preparation times out during its first event", async () => {
const runs = [await seedOwnedNativeRun(), await seedOwnedNativeRun(), await seedOwnedNativeRun()];
const deps = callbacks(db), recovery = createHeartbeatRecovery(db, deps);
hotRestart.read.mockResolvedValue({ version: 1, requestedAt: new Date().toISOString(), previousServerPid: process.pid,
previousServerVersion: null, drainRequired: false, requestedByRunId: null, preflightActiveRunIds: [] });
let finishFirstEvent!: () => void;
const firstEvent = new Promise<undefined>(resolve => { finishFirstEvent = () => resolve(undefined); });
deps.appendRunEvent.mockImplementationOnce(() => firstEvent);
const hotRestartEvents = () => deps.appendRunEvent.mock.calls
.filter(([, event]) => event.message?.startsWith("Hot restart requested") === true).length;
let preparation: ReturnType<typeof recovery.prepareHotRestartShutdown> | undefined;
try {
const step = await runBoundedShutdownStep({ step: "hot_restart_prepare", signal: "SIGTERM", timeoutMs: 2_000,
log: { info: vi.fn(), error: vi.fn() },
run: abort => (preparation = recovery.prepareHotRestartShutdown("SIGTERM", new Date(), abort)) });
expect(step.outcome).toBe("timed_out");
expect(hotRestartEvents()).toBe(1);
const runIds = runs.map(run => run.id);
expect((await recovery.drainRunningRunsForShutdown("SIGTERM", new Date(), runIds)).restartSuspendedRunIds.sort())
.toEqual([...runIds].sort());
finishFirstEvent();
await expect(preparation).rejects.toThrow("timed out");
expect(hotRestartEvents()).toBe(1);
expect(native.detach).toHaveBeenCalledTimes(runs.length);
} finally {
finishFirstEvent?.();
await preparation?.catch(() => undefined);
for (const run of runs) await removeNativeRun(run.id);
}
});
it("does not dispatch recovery for a run still preparing in this heartbeat process", async () => {
const run = await seedRun();
await db.update(agents).set({ adapterType: "paperclip_runner" }).where(eq(agents.id, run.agentId));
+63 -16
View File
@@ -39,7 +39,7 @@ import {
hasStopOnlyCleanup,
settleStopOnlyCleanup,
} from "../sandbox-stop-and-retain.js";
import { discoverSettledNativeRunProcesses, PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, recordNativeLocalProcessStopInTransaction, releaseSettledNativeRunProcess, retryPendingSettledNativeRunProcesses } from "../native-local-process-stop.js";
import { discoverSettledNativeRunProcesses, inspectSettledNativeRunProcess, PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, recordNativeLocalProcessStopInTransaction, retryPendingSettledNativeRunProcesses } from "../native-local-process-stop.js";
import { pendingCaseHandoffForRun } from "./case-handoff-lifecycle.js";
import { portableTaskPreparationLeaseId } from "../plugin-task-ownership.js";
import { retireInheritedRemoteRunnerIdentity } from "../native-runtime/native-inherited-runner-retry.js";
@@ -213,6 +213,8 @@ export const DETACHED_PROCESS_ERROR_CODE = "process_detached";
const NATIVE_OWNERSHIP_UNVERIFIED_MESSAGE =
"Native execution ownership could not be verified; automatic recovery is blocked";
const EARLY_NATIVE_HAND_OFF_DRAIN_WAIT_MS = 30_000;
// The reaper sweeps at most this many pending_cleanup leases per tick.
const PENDING_CLEANUP_SWEEP_PAGE_SIZE = 20;
// An environment delete tries each of that environment's cleanups once, from
@@ -490,12 +492,14 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
async function prepareHotRestartShutdown(
signal: "SIGINT" | "SIGTERM",
now = new Date(),
abort?: AbortSignal,
) {
enterShutdown();
const idleSessions = await closeIdleWarmNativeSessionsForRestart();
if (idleSessions.failed > 0) {
logger.warn({ idleSessions }, "idle native session cleanup failed before controller shutdown");
}
abort?.throwIfAborted();
let intent: Awaited<ReturnType<typeof readHotRestartIntent>>;
try {
intent = await readHotRestartIntent();
@@ -544,6 +548,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
.from(heartbeatRuns)
.innerJoin(agents, eq(heartbeatRuns.agentId, agents.id))
.where(eq(heartbeatRuns.status, "running"));
abort?.throwIfAborted();
const snapshotRuns = activeRuns.map(toHotRestartIntentRun);
const intentWithVersion = {
...intent,
@@ -589,8 +594,8 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
activeRuns: snapshotRuns,
capturedAt: now,
});
for (const { run } of activeRuns) {
abort?.throwIfAborted();
await appendRunEvent(run, {
eventType: "lifecycle",
stream: "system",
@@ -614,6 +619,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
isNativeSessionId(run.nativeSessionId),
)
.map(({ run }) => run.id);
abort?.throwIfAborted();
for (const runId of nativeRunIds) markHandedOffByThisController(runId);
const detachedNativeSessions =
await detachNativeSessionsForRestart(nativeRunIds);
@@ -1158,10 +1164,27 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
}
}
const nativeRunsHandedOffEarly = new Set<string>();
const nativeRunsHandedOffEarly = new Map<string, Promise<boolean>>();
async function settleEarlyNativeHandOff(runId: string, handOff: Promise<boolean>) {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const outcome = await Promise.race([handOff, new Promise<"unfinished">(resolve => {
timer = setTimeout(() => resolve("unfinished"), EARLY_NATIVE_HAND_OFF_DRAIN_WAIT_MS);
timer.unref?.();
})]);
if (outcome === "unfinished") {
logger.warn({ runId, waitedMs: EARLY_NATIVE_HAND_OFF_DRAIN_WAIT_MS },
"early native run hand-off is unfinished at the shutdown drain; the drain hands it off");
}
return outcome === true;
} finally {
clearTimeout(timer);
}
}
async function suspendNativeRunForShutdown(run: typeof heartbeatRuns.$inferSelect, signal: "SIGINT" | "SIGTERM",
now: Date, controllerBootId: string) {
now: Date, controllerBootId: string, timing?: { detachMs: number; transactionMs: number }) {
const [owner] = await db.select({ bootId: nativeRunFinalizations.controllerBootId })
.from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id));
if (owner?.bootId && owner.bootId !== controllerBootId) return false;
@@ -1170,7 +1193,9 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
// finalizer interrupt/suspend Claude while the next server is adopting
// the same turn.
markHandedOffByThisController(run.id);
const detachStartedAt = performance.now();
await detachNativeSessionsForRestart([run.id]);
if (timing) timing.detachMs = Math.round(performance.now() - detachStartedAt);
const recoveryHistoryEntry = JSON.stringify({
at: now.toISOString(),
restartKind: "graceful",
@@ -1183,6 +1208,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
// execution lease must still be released: the detached executor will
// not finalize, and the next controller's reconciler skips leased rows.
// A finalizer lease belongs to finalization already in progress here.
const transactionStartedAt = performance.now();
const released = await db.transaction(async tx => {
await notifyLiveRunRecovery(tx, { companyId: run.companyId, runId: run.id });
await notifyReattachHandOver(tx, run.id);
@@ -1217,6 +1243,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
)
.returning({ resultId: nativeRunFinalizations.resultId, leaseOwner: nativeRunFinalizations.leaseOwner });
});
if (timing) timing.transactionMs = Math.round(performance.now() - transactionStartedAt);
const resultAccepted = Boolean(released[0]?.resultId);
const finalizerHeld = resultAccepted && Boolean(released[0]?.leaseOwner?.startsWith("native-finalizer:"));
await appendRunEvent(run, {
@@ -1243,25 +1270,40 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
}
async function handOffNativeRunsForShutdown(signal: "SIGINT" | "SIGTERM", now = new Date()) {
const startedAt = performance.now();
const elapsed = (from: number) => Math.round(performance.now() - from);
const intent = await readHotRestartIntent().catch(() => null);
const intentReadMs = elapsed(startedAt);
if (intent && !intent.drainRequired && shouldHonorHotRestartIntentForProcess(intent)) return [];
const identityStartedAt = performance.now();
const nativeController = await currentNativeControllerIdentity();
const controllerIdentityMs = elapsed(identityStartedAt);
const selectStartedAt = performance.now();
const liveRuns = await db.select({ run: heartbeatRuns }).from(heartbeatRuns)
.innerJoin(agents, eq(heartbeatRuns.agentId, agents.id))
.where(and(eq(heartbeatRuns.status, "running"), eq(heartbeatRuns.runtimeMode, "native"),
eq(agents.adapterType, "paperclip_runner")));
const selectMs = elapsed(selectStartedAt);
const handedOff: string[] = [];
let maxDetachMs = 0, maxTransactionMs = 0, failed = 0;
await Promise.allSettled(liveRuns.map(async ({ run }) => {
if (isNativeRunnerOwnershipHeld(run) || nativeRunsHandedOffEarly.has(run.id)) return;
nativeRunsHandedOffEarly.add(run.id);
try {
if (await suspendNativeRunForShutdown(run, signal, now, nativeController.bootId)) handedOff.push(run.id);
else nativeRunsHandedOffEarly.delete(run.id);
} catch (error) {
nativeRunsHandedOffEarly.delete(run.id);
const timing = { detachMs: 0, transactionMs: 0 };
const handOff = suspendNativeRunForShutdown(run, signal, now, nativeController.bootId, timing).catch(error => {
failed += 1;
logger.warn({ err: error, runId: run.id }, "early native run hand-off failed; the shutdown drain retries it");
}
return false;
});
nativeRunsHandedOffEarly.set(run.id, handOff);
const suspended = await handOff;
maxDetachMs = Math.max(maxDetachMs, timing.detachMs);
maxTransactionMs = Math.max(maxTransactionMs, timing.transactionMs);
if (suspended) handedOff.push(run.id);
else if (nativeRunsHandedOffEarly.get(run.id) === handOff) nativeRunsHandedOffEarly.delete(run.id);
}));
logger.info({ signal, liveRuns: liveRuns.length, handedOff: handedOff.length, failed, intentReadMs,
controllerIdentityMs, selectMs, maxDetachMs, maxTransactionMs, totalMs: elapsed(startedAt) },
"native run shutdown hand-off phase timings");
return handedOff;
}
@@ -1311,8 +1353,12 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
run.runtimeMode === "native" &&
agent.adapterType === "paperclip_runner"
) {
if (nativeRunsHandedOffEarly.has(run.id)
|| await suspendNativeRunForShutdown(run, signal, now, nativeController.bootId)) restartSuspendedRunIds.push(run.id);
const earlyHandOff = nativeRunsHandedOffEarly.get(run.id);
if (earlyHandOff && await settleEarlyNativeHandOff(run.id, earlyHandOff)) {
restartSuspendedRunIds.push(run.id);
return;
}
if (await suspendNativeRunForShutdown(run, signal, now, nativeController.bootId)) restartSuspendedRunIds.push(run.id);
return;
}
if (agent.adapterType === "paperclip_runner" && run.runtimeMode === "legacy" && run.scopeKind === "issue" &&
@@ -3109,10 +3155,11 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
if (!scope.runId || activeRunExecutions.has(scope.runId) || runningProcesses.has(scope.runId)
|| adapterExecutionControls.has(scope.runId)) {
scope.onDeferredDeadline(Date.now() + 30_000);
return;
return "deferred";
}
const outcome = await releaseSettledNativeRunProcess(db, scope.runId, scope);
if (outcome !== "pending") await acknowledgeRemoteStop(scope.runId, scope.companyId);
const { outcome, remoteStop } = await inspectSettledNativeRunProcess(db, scope.runId, scope);
if (outcome !== "pending" && remoteStop) await acknowledgeRemoteStop(scope.runId, scope.companyId);
return outcome;
},
orphanLease: scope => sweepOrphanedActiveLeases({ ...scope, backoffMs: 5 * 60_000 }),
shutdown: scope => sweepLegacyShutdownWorkspaceSettlements(db, new Date(), scope),
+4 -4
View File
@@ -3,7 +3,7 @@ import { runOwnerFenceHeldSql } from "../remote-workspace-writer-hold.js";
import { AGENT_DIRECTORY_BUSY_ERROR_CODE, AGENT_DIRECTORY_BUSY_MAX_DEFERRALS, AGENT_DIRECTORY_BUSY_RETRY_REASON, AGENT_DIRECTORY_BUSY_RETRY_WAKE_REASON, agentDirectoryBusyRetryDelayMs, type AgentDirectoryPreparationDeferral } from "./agent-directory-busy.js";
import { isInterruptedNativePreparation } from "../cancelled-native-startup.js";
import { isPreDispatchExecutionWaitVerified } from "../pre-dispatch-execution-wait.js";
import { notifyAttentionRetentionWork } from "../retention-work-notifications.js";
import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js";
import { normalizeAgentNameKey } from "../agent-name-key.js";
import { notifyStatusCardIssueChange } from "../status-card-notifications.js";
import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js";
@@ -1209,8 +1209,8 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen
}
}
await notifyAttentionRetentionWork(tx, { companyId: run.companyId });
await notifyScheduledRetryDispatch(tx, { companyId: run.companyId });
await notifyIssueAttentionRetentionWork(tx, { companyId: run.companyId, runId: run.id });
await notifyScheduledRetryDispatch(tx, { companyId: run.companyId, runId: run.id });
const wakeupRequest = await tx
.insert(agentWakeupRequests)
.values({
@@ -2068,7 +2068,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen
};
const updated = await db.transaction(async (tx) => {
await notifyScheduledRetryDispatch(tx, { companyId: scheduled.run.companyId });
await notifyScheduledRetryDispatch(tx, { companyId: scheduled.run.companyId, runId: scheduled.run.id });
const row = await tx
.update(heartbeatRuns)
.set({
@@ -1557,11 +1557,15 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl
) {
if (!wakeupRequestId) return;
await db.transaction(async tx => {
const [current] = await tx.select({ companyId: agentWakeupRequests.companyId, agentId: agentWakeupRequests.agentId, status: agentWakeupRequests.status })
const [current] = await tx.select({ companyId: agentWakeupRequests.companyId, agentId: agentWakeupRequests.agentId, status: agentWakeupRequests.status,
runId: agentWakeupRequests.runId, issueId: sql<string | null>`${agentWakeupRequests.payload}->>'issueId'` })
.from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeupRequestId)).for("update");
if (!current || current.status === "cancelled") return;
if (current.status !== (patch?.status ?? status) || patch?.payload !== undefined || patch?.runId !== undefined) {
await notifyExternalConversationSettlement(tx, { companyId: current.companyId });
const runId = patch?.runId ?? current.runId;
const issueId = current.issueId && /^[0-9a-f-]{36}$/i.test(current.issueId) ? current.issueId : undefined;
await notifyExternalConversationSettlement(tx, issueId || runId
? { companyId: current.companyId, issueId, runId: runId ?? undefined } : { companyId: current.companyId });
}
await notifyStrandedAgentStatus(tx, { companyId: current.companyId, agentId: current.agentId });
await tx.update(agentWakeupRequests)
@@ -2605,7 +2609,7 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl
.returning()
.then((rows) => rows[0]);
await notifyRunDispatch(tx, { companyId: run.companyId });
await notifyRunDispatch(tx, { companyId: run.companyId, issueId });
const queuedRun = await tx
.insert(heartbeatRuns)
.values({
@@ -1054,7 +1054,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
eq(heartbeatRuns.id, run.id),
eq(heartbeatRuns.status, "running"),
),
), { companyId: run.companyId });
), { companyId: run.companyId, runId: run.id });
const workspaceFinalizeStatus = hasWorkspaceRestoreFailure(adapterResult.resultJson) ? "failed" : "succeeded";
await recordWorkspaceFinalize(workspaceFinalizeStatus);
if (adapterResult.nativeFinalization) {
@@ -1135,7 +1135,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
eq(heartbeatRuns.id, run.id),
eq(heartbeatRuns.status, "running"),
),
), { companyId: run.companyId });
), { companyId: run.companyId, runId: run.id });
} catch (writeError) {
if (adapterErr instanceof NativeStartupCleanupPendingError) throw adapterErr;
throw writeError;
+11 -11
View File
@@ -1,5 +1,5 @@
import { notifyAttentionRetentionWork } from "./retention-work-notifications.js";
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
import { notifyIssueGraphRecovery } from "./issue-recovery-notifications.js";
import { notifyNativeRecoveryNotices } from "./native-recovery-notice-notifications.js";
import { notifyUnsafeWorkspaceExportRecovery } from "./unsafe-workspace-export-notifications.js";
import { writeExecutionControl } from "./execution-control-notifications.js";
@@ -345,7 +345,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
try {
const created = await db.transaction(async (tx) => {
await notifyAttentionRetentionWork(tx, { companyId: input.companyId });
await notifyIssueRecovery(tx, { companyId: input.companyId });
await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionDisposition);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionContinuation);
@@ -417,7 +417,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
const [updated] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], tx => tx.update(issueRecoveryActions).set({ nextAction: input.nextAction, updatedAt: now })
.where(and(eq(issueRecoveryActions.id, existing.id),
inArray(issueRecoveryActions.status, [...ACTIVE_RECOVERY_ACTION_STATUSES]),
sql`${issueRecoveryActions.evidence}->'workspaceOwnerStop' is null`)).returning(), { companyId: input.companyId });
sql`${issueRecoveryActions.evidence}->'workspaceOwnerStop' is null`)).returning(), { companyId: input.companyId, issueId: input.sourceIssueId });
if (updated) return toReadModel(updated);
}
return existing;
@@ -438,7 +438,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
Math.min(nextAttemptCount, effectiveMaxAttempts),
);
const [exhausted] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], async tx => {
await notifyIssueRecovery(tx, { companyId: input.companyId });
await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
if ((!input.preserveExistingOwner && existing.cause !== input.cause)
|| (input.evidence?.runId !== undefined && input.evidence.runId !== existing.evidence?.runId)) {
@@ -493,14 +493,14 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
),
)
.returning();
}, { companyId: input.companyId });
}, { companyId: input.companyId, issueId: input.sourceIssueId });
if (!exhausted) {
return retryUpsertSourceScoped(input, retryCount);
}
return toReadModel(exhausted);
}
const [updated] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], async tx => {
await notifyIssueRecovery(tx, { companyId: input.companyId });
await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
if ((!input.preserveExistingOwner && existing.cause !== input.cause)
|| (input.evidence?.runId !== undefined && input.evidence.runId !== existing.evidence?.runId)) {
@@ -566,7 +566,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
),
)
.returning();
}, { companyId: input.companyId });
}, { companyId: input.companyId, issueId: input.sourceIssueId });
if (!updated) {
return retryUpsertSourceScoped(input, retryCount);
}
@@ -575,14 +575,14 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
try {
const [created] = await writeExecutionControl(db, [DELIVERY_QUEUES.executionDisposition, DELIVERY_QUEUES.executionContinuation], async tx => {
await notifyIssueRecovery(tx, { companyId: input.companyId });
await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
return tx
.insert(issueRecoveryActions)
.values(buildInsertValues(input, ownerType, now))
.returning();
}, { companyId: input.companyId });
}, { companyId: input.companyId, issueId: input.sourceIssueId });
return toReadModel(created!);
} catch (error) {
if (!isUniqueRecoveryActionConflict(error)) throw error;
@@ -632,7 +632,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
isNotNull(nativeRunFinalizations.leaseOwner), inArray(heartbeatRuns.status, ["failed", "timed_out", "interrupted"]),
)).limit(1);
if (waiter) await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionFinalization);
await notifyIssueRecovery(tx, { companyId: input.companyId });
await notifyIssueGraphRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyNativeRecoveryNotices(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.companyId, issueId: input.sourceIssueId });
return tx
@@ -646,7 +646,7 @@ export function issueRecoveryActionService(db: DbOrTransaction) {
})
.where(and(...predicates))
.returning();
}, { companyId: input.companyId });
}, { companyId: input.companyId, issueId: input.sourceIssueId });
return updated ? toReadModel(updated) : null;
}
@@ -1,9 +1,20 @@
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { DELIVERY_QUEUES, notifyDeliveryWork, type DeliveryQueue } from "./delivery-work-notifications.js";
/** An issue hint is reserved for local facts such as comments. Lifecycle,
* graph, run and eligibility changes retain company scope because their
* consequences can include ancestors and shared execution references. */
export type IssueRecoveryScope = { companyId: string; issueId?: string };
export type IssueRecoveryScope = { companyId: string; issueId?: string; graphRunId?: string; graphIssueId?: string; backstop?: true;
issueIds?: string[]; wholeCompany?: boolean };
export const ISSUE_RECOVERY_MAX_ISSUE_IDS = 100;
export const ISSUE_RECOVERY_BACKSTOP_MS = 5 * 60_000;
const UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
const COMPANY_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, DELIVERY_QUEUES.taskWatchdogs];
const TASK_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.assignedWorkInvariant,
DELIVERY_QUEUES.resolvedDependencies, DELIVERY_QUEUES.staleIssueLocks];
export async function notifyIssueRecovery(transaction: object, scope?: IssueRecoveryScope) {
const companyHint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*";
@@ -14,3 +25,49 @@ export async function notifyIssueRecovery(transaction: object, scope?: IssueReco
queue === DELIVERY_QUEUES.strandedAssignments || queue === DELIVERY_QUEUES.staleIssueLocks ? issueHint : companyHint);
}
}
export function decodeIssueRecoveryHint(hint: string): IssueRecoveryScope | undefined {
return hint === "*" ? undefined : JSON.parse(hint) as IssueRecoveryScope;
}
export function issueRecoveryScopeMatches(entry: { id: string; companyId: string }, scope?: IssueRecoveryScope) {
if (!scope) return true;
if (entry.companyId !== scope.companyId) return false;
if (scope.issueId) return entry.id === scope.issueId;
if (scope.graphRunId || scope.graphIssueId) return scope.wholeCompany === true || (scope.issueIds?.includes(entry.id) ?? false);
return true;
}
export async function notifyIssueGraphRecovery(transaction: object,
scope: { companyId: string; runId?: string | null; issueId?: string | null }) {
if (!scope.runId && !scope.issueId) return notifyIssueRecovery(transaction, { companyId: scope.companyId });
const companyHint = JSON.stringify({ companyId: scope.companyId });
for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint);
const graphHint = JSON.stringify({ companyId: scope.companyId, graphRunId: scope.runId ?? undefined, graphIssueId: scope.issueId ?? undefined });
for (const queue of TASK_QUEUES) {
await notifyDeliveryWork(transaction, queue, graphHint);
await notifyDeliveryWork(transaction, queue, JSON.stringify({ companyId: scope.companyId, backstop: true }));
}
}
export async function resolveIssueGraph(db: Db, scope: { companyId: string; runId?: string; issueId?: string }): Promise<string[] | null> {
const company = sql`${scope.companyId}::uuid`;
const run = scope.runId ? sql`${scope.runId}::uuid` : sql`null::uuid`;
const rows = await db.execute<{ id: string }>(sql`with seed(id) as (
select id from issues where company_id = ${company} and id = ${scope.issueId ?? null}::uuid
union select issue_id from heartbeat_runs where company_id = ${company} and id = ${run} and issue_id is not null
union select native_issue_id from heartbeat_runs where company_id = ${company} and id = ${run} and native_issue_id is not null
union select issue.id from heartbeat_runs run
cross join lateral (select coalesce(run.context_snapshot->>'issueId', run.context_snapshot->>'taskId') as saved) context
inner join issues issue on issue.company_id = run.company_id
and issue.id = case when context.saved ~* ${UUID_PATTERN} then context.saved::uuid end
where run.company_id = ${company} and run.id = ${run}
), affected(id) as (
select id from seed
union select parent_id from issues where company_id = ${company} and id in (select id from seed) and parent_id is not null
union (select related_issue_id from issue_relations where company_id = ${company} and type = 'blocks'
and issue_id in (select id from seed) limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1})
) select id::text as id from affected limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1}`);
const issueIds = rows.map(row => row.id).sort();
return issueIds.length && issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null;
}
+5 -4
View File
@@ -12196,7 +12196,8 @@ export function issueService(db: Db) {
|| patch.hiddenAt !== undefined || patch.conversationAgentId !== undefined || patch.parentId !== undefined
|| patch.executionState !== undefined || patch.executionRunId !== undefined || patch.checkoutRunId !== undefined
|| blockedByIssueIds !== undefined) {
await notifyRunDispatch(tx, { companyId: receiptExisting.companyId });
await notifyRunDispatch(tx, patch.parentId !== undefined && patch.parentId !== receiptExisting.parentId
? { companyId: receiptExisting.companyId } : { companyId: receiptExisting.companyId, issueId: id });
await notifyDeferredExecutionEligibility(tx, { companyId: receiptExisting.companyId });
await notifyActiveRunSilence(tx, { companyId: receiptExisting.companyId, issueId: id });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
@@ -12827,7 +12828,7 @@ export function issueService(db: Db) {
await notifyStatusCardIssueChange(tx, issueCompany.companyId);
await notifyIssueAttentionRetentionWork(tx, { companyId: issueCompany.companyId, issueId: id });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors);
await notifyRunDispatch(tx, { companyId: issueCompany.companyId });
await notifyRunDispatch(tx, { companyId: issueCompany.companyId, issueId: id });
await notifyDeferredExecutionEligibility(tx, { companyId: issueCompany.companyId });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
await notifyRoutineExecutionStatus(tx, id);
@@ -13238,7 +13239,7 @@ export function issueService(db: Db) {
await notifyNativeStatusReassessment(tx, { companyId: existing.companyId, issueId: id });
await notifyIssueAttentionRetentionWork(tx, { companyId: existing.companyId, issueId: id });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors);
await notifyRunDispatch(tx, { companyId: existing.companyId });
await notifyRunDispatch(tx, { companyId: existing.companyId, issueId: id });
await notifyDeferredExecutionEligibility(tx, { companyId: existing.companyId });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
await notifyRoutineExecutionStatus(tx, id);
@@ -13303,7 +13304,7 @@ export function issueService(db: Db) {
await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: existing.companyId, issueId: id });
}
await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors);
await notifyRunDispatch(tx, { companyId: existing.companyId });
await notifyRunDispatch(tx, { companyId: existing.companyId, issueId: id });
await notifyDeferredExecutionEligibility(tx, { companyId: existing.companyId });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
await notifyRoutineExecutionStatus(tx, id);
@@ -158,7 +158,7 @@ export async function terminalizeLegacyExecution(input: {
};
if (issueId) await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: current.companyId, issueId });
await notifyInstructionCollection(tx, { companyId: current.companyId, runId: current.id });
await notifyExecutionRunWork(tx, { companyId: current.companyId });
await notifyExecutionRunWork(tx, { companyId: current.companyId, runId: current.id });
let [updated] = await tx
.update(heartbeatRuns)
.set({
+108 -57
View File
@@ -1,13 +1,13 @@
import { notifyLiveRunRecovery } from "./live-run-recovery-notifications.js";
import { and, asc, desc, eq, exists, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { and, desc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db";
import { notifyRetainedNativeSessionCleanup } from "./retained-native-session-cleanup-notifications.js";
import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { nativeSessionProviderEvidence } from "./native-runtime/native-session-resume.js";
import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
import { NATIVE_SESSION_PROVIDER_EVENT_TYPES } from "./native-runtime/native-session-resume.js";
import os from "node:os";
import { currentProcessSpaceHash } from "./controller-process-identity.js";
import { currentProcessSpaceHash, UNKNOWN_PROCESS_SPACE } from "./controller-process-identity.js";
import { proveOwnerGone } from "./owner-proof.js";
export const PROCESS_START_REQUESTED = "native.process_start_requested";
@@ -69,6 +69,12 @@ export async function recordNativeLocalProcessStop(db: Db, run: Pick<typeof hear
if (leases.some(lease => lease.provider !== "local")) return false;
if ((run.processPid && !absent(run.processPid)) ||
(run.processGroupId && !absent(-run.processGroupId))) return false;
await appendLocalProcessStop(db, { ...run, processStartedAt: run.processStartedAt?.toISOString() ?? null });
return true;
}
async function appendLocalProcessStop(db: Db, run: { id: string; companyId: string; agentId: string;
processPid: number | null; processGroupId: number | null; processStartedAt: string | null }) {
await notifyDeliveryWork(db, DELIVERY_QUEUES.executionReplacement,
JSON.stringify({ companyId: run.companyId, runId: run.id }));
await appendHeartbeatRunEvent(db, {
@@ -79,10 +85,8 @@ export async function recordNativeLocalProcessStop(db: Db, run: Pick<typeof hear
stream: "system",
level: "info",
message: "Recovery verified the local process stopped before clearing its identity.",
payload: { processPid: run.processPid, processGroupId: run.processGroupId,
processStartedAt: run.processStartedAt?.toISOString() ?? null },
payload: { processPid: run.processPid, processGroupId: run.processGroupId, processStartedAt: run.processStartedAt },
});
return true;
}
/** Transaction form for callers that clear the process identity: a stopped
@@ -376,69 +380,122 @@ export async function readNativeLocalProcessStop(db: Db, companyId: string, runI
}
type SettledProcessRelease = "released" | "pending" | "skipped";
export type SettledProcessReleaseResult = { outcome: SettledProcessRelease; remoteStop: boolean };
export function settledNativeProcessIdentityCondition(db: Db) {
const identity = db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, heartbeatRuns.companyId), eq(heartbeatRunEvents.runId, heartbeatRuns.id),
eq(heartbeatRunEvents.eventType, PROCESS_IDENTITY_RECORDED), isNull(heartbeatRunEvents.sourceEventId),
)).orderBy(desc(heartbeatRunEvents.seq)).limit(1).as("settled_process_identity");
return or(isNotNull(heartbeatRuns.processStartedAt), exists(db.select({ id: environmentLeases.id })
.from(environmentLeases).where(and(eq(environmentLeases.companyId, heartbeatRuns.companyId),
eq(environmentLeases.heartbeatRunId, heartbeatRuns.id), sql`${environmentLeases.provider} <> 'local'`))),
and(gt(heartbeatRuns.processPid, 1), eq(heartbeatRuns.processPid, heartbeatRuns.processGroupId),
exists(db.select({ payload: identity.payload }).from(identity).where(and(
sql`${identity.payload}->>'targetKind' = 'local'`, sql`${identity.payload}->>'hostname' = ${os.hostname()}`,
sql`${identity.payload}->>'processPid' = ${heartbeatRuns.processPid}::text`,
sql`${identity.payload}->>'processGroupId' = ${heartbeatRuns.processGroupId}::text`,
)))));
const providerEventTypes = () => sql.join(NATIVE_SESSION_PROVIDER_EVENT_TYPES.map(type => sql`${type}`), sql`, `);
function settledNativeProcessReleaseCondition() {
const processSpace = currentProcessSpaceHash();
const ownSpace = processSpace === UNKNOWN_PROCESS_SPACE ? undefined : eq(heartbeatRuns.processHostHash, processSpace);
const remoteLease = sql`exists (select 1 from environment_leases settled_lease where settled_lease.company_id = ${heartbeatRuns.companyId}
and settled_lease.heartbeat_run_id = ${heartbeatRuns.id} and settled_lease.provider is distinct from 'local')`;
const unrecordedSpace = or(isNull(heartbeatRuns.processHostHash), eq(heartbeatRuns.processHostHash, UNKNOWN_PROCESS_SPACE));
return and(eq(heartbeatRuns.runtimeMode, "native"), inArray(heartbeatRuns.status, SETTLED_RUN_STATUSES),
isNotNull(heartbeatRuns.finishedAt),
or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId), isNotNull(heartbeatRuns.processStartedAt)),
or(ownSpace, eq(heartbeatRuns.processHostHash, "remote"), isNull(heartbeatRuns.processHostHash),
eq(heartbeatRuns.processHostHash, UNKNOWN_PROCESS_SPACE)),
or(ownSpace, remoteLease, and(unrecordedSpace, sql`(select settled_identity.payload->>'hostname' from heartbeat_run_events settled_identity
where settled_identity.company_id = ${heartbeatRuns.companyId} and settled_identity.run_id = ${heartbeatRuns.id}
and settled_identity.event_type = ${PROCESS_IDENTITY_RECORDED} and settled_identity.source_event_id is null
order by settled_identity.seq desc limit 1) = ${os.hostname()}::text`)),
sql`not exists (select 1 from native_run_finalizations settled_coordinator
where settled_coordinator.run_id = ${heartbeatRuns.id} and settled_coordinator.phase not in ('committed', 'terminal_failure'))`,
sql`(coalesce(${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint', 'null'::jsonb) <> 'null'::jsonb
or exists (select 1 from heartbeat_run_events settled_evidence where settled_evidence.company_id = ${heartbeatRuns.companyId}
and settled_evidence.run_id = ${heartbeatRuns.id} and settled_evidence.event_type in (${providerEventTypes()})))`);
}
export async function settledNativeProcessCandidates(db: Pick<Db, "execute">, input: {
companyId?: string; runId?: string; after?: string | null; limit: number;
}): Promise<Array<{ id: string; companyId: string }>> {
const processSpace = currentProcessSpaceHash();
const condition = and(input.companyId ? eq(heartbeatRuns.companyId, input.companyId) : undefined,
input.runId ? eq(heartbeatRuns.id, input.runId) : undefined, input.after ? gt(heartbeatRuns.id, input.after) : undefined,
settledNativeProcessReleaseCondition());
const spaces = [processSpace === UNKNOWN_PROCESS_SPACE ? null : eq(heartbeatRuns.processHostHash, processSpace),
eq(heartbeatRuns.processHostHash, "remote"), eq(heartbeatRuns.processHostHash, UNKNOWN_PROCESS_SPACE),
isNull(heartbeatRuns.processHostHash)].filter(space => space !== null);
const branches = spaces.map(space => sql`(select ${heartbeatRuns.id} as id, ${heartbeatRuns.companyId} as company_id
from ${heartbeatRuns} where ${and(space, condition)} offset 0)`);
return await db.execute(sql`select id, company_id as "companyId" from (${sql.join(branches, sql` union all `)}) candidates
order by id limit ${input.limit}`) as unknown as Array<{ id: string; companyId: string }>;
}
type SettledProcessFacts = {
companyId: string; agentId: string; runtimeMode: string; status: string; finished: boolean;
processPid: number | null; processGroupId: number | null; processStartedAt: string | null; apiDriver: boolean | null;
hasSessionCheckpoint: boolean; phase: string | null; providerEvidence: boolean; remoteLeases: boolean;
localLeasePending: boolean; identityMatches: boolean | null;
};
function readSettledProcessFacts(tx: Db, runId: string) {
return tx.execute(sql`select r.company_id as "companyId", r.agent_id as "agentId", r.runtime_mode as "runtimeMode",
r.status, r.finished_at is not null as "finished", r.process_pid as "processPid", r.process_group_id as "processGroupId",
to_char(r.process_started_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') as "processStartedAt",
r.driver_kind = 'cursor_cloud_api' as "apiDriver",
coalesce(r.runner_profile_json->'sessionCheckpoint', 'null'::jsonb) <> 'null'::jsonb as "hasSessionCheckpoint",
(select f.phase from native_run_finalizations f where f.run_id = r.id limit 1) as "phase",
exists (select 1 from heartbeat_run_events e where e.company_id = r.company_id and e.run_id = r.id
and e.event_type in (${providerEventTypes()})) as "providerEvidence",
exists (select 1 from environment_leases l where l.company_id = r.company_id and l.heartbeat_run_id = r.id
and l.provider is distinct from 'local') as "remoteLeases",
exists (select 1 from environment_leases l where l.company_id = r.company_id and l.heartbeat_run_id = r.id
and (l.released_at is null or l.status = 'pending_cleanup' or l.cleanup_status = 'failed')) as "localLeasePending",
(select identity.payload->>'targetKind' = 'local' and identity.payload->>'hostname' = ${os.hostname()}::text
and identity.payload ? 'processPid' and identity.payload->'processPid' = coalesce(to_jsonb(r.process_pid), 'null'::jsonb)
and identity.payload ? 'processGroupId' and identity.payload->'processGroupId' = coalesce(to_jsonb(r.process_group_id), 'null'::jsonb)
and case when r.process_started_at is not null
then identity.payload->>'processStartedAt' = to_char(r.process_started_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')
else coalesce(r.process_pid > 1 and r.process_group_id = r.process_pid, false) end
from (select e.payload from heartbeat_run_events e where e.company_id = r.company_id and e.run_id = r.id
and e.event_type = ${PROCESS_IDENTITY_RECORDED}::text and e.source_event_id is null order by e.seq desc limit 1) identity
) as "identityMatches"
from heartbeat_runs r where r.id = ${runId}::uuid for update of r`) as unknown as Promise<SettledProcessFacts[]>;
}
export async function releaseSettledNativeRunProcess(db: Db, runId: string, options: { onDeferredDeadline?: (at: number) => void } = {}): Promise<SettledProcessRelease> {
return (await inspectSettledNativeRunProcess(db, runId, options)).outcome;
}
export async function inspectSettledNativeRunProcess(db: Db, runId: string, options: { onDeferredDeadline?: (at: number) => void } = {}): Promise<SettledProcessReleaseResult> {
let remoteStop = false;
const outcome = await db.transaction(async transaction => {
const tx = transaction as unknown as Db;
const [run] = await tx.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt,
processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, processStartedAt: heartbeatRuns.processStartedAt,
hasSessionCheckpoint: sql<boolean>`coalesce(${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint', 'null'::jsonb) <> 'null'::jsonb`,
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).for("update").limit(1);
if (!run || run.runtimeMode !== "native" || !SETTLED_RUN_STATUSES.includes(run.status) || !run.finishedAt ||
const [run] = await readSettledProcessFacts(tx, runId);
if (!run) return "skipped";
remoteStop = run.remoteLeases || (run.status === "cancelled" && run.apiDriver === true);
if (run.runtimeMode !== "native" || !SETTLED_RUN_STATUSES.includes(run.status) || !run.finished ||
(run.processPid === null && run.processGroupId === null && run.processStartedAt === null)) return "skipped";
const [coordinator] = await tx.select({ phase: nativeRunFinalizations.phase }).from(nativeRunFinalizations)
.where(eq(nativeRunFinalizations.runId, run.id)).limit(1);
if (coordinator && !SETTLED_COORDINATOR_PHASES.includes(coordinator.phase)) return "skipped";
if (!run.hasSessionCheckpoint &&
!(await nativeSessionProviderEvidence(tx, [run.id])).has(run.id)) return "skipped";
const leases = await tx.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
));
if (leases.some(lease => lease.provider !== "local")) {
if (run.phase !== null && !SETTLED_COORDINATOR_PHASES.includes(run.phase)) return "skipped";
if (!run.hasSessionCheckpoint && !run.providerEvidence) return "skipped";
if (run.remoteLeases) {
const leases = await tx.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, runId),
));
if (!leases.every(hasRemoteTerminationReceipt)) return "pending";
} else {
if (leases.some(lease => !lease.releasedAt || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return "pending";
const [identity] = await tx.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
eq(heartbeatRunEvents.eventType, PROCESS_IDENTITY_RECORDED), isNull(heartbeatRunEvents.sourceEventId),
)).orderBy(desc(heartbeatRunEvents.seq)).limit(1);
if (identity?.payload?.targetKind !== "local" || identity.payload.hostname !== os.hostname() ||
identity.payload.processPid !== run.processPid || identity.payload.processGroupId !== run.processGroupId ||
(run.processStartedAt ? identity.payload.processStartedAt !== run.processStartedAt.toISOString()
: !Number.isSafeInteger(run.processPid) || run.processPid! <= 1 || run.processGroupId !== run.processPid)) return "skipped";
if (!(await recordNativeLocalProcessStop(tx, run))) {
if (run.localLeasePending) return "pending";
if (run.identityMatches !== true) return "skipped";
if ((!run.processPid && !run.processGroupId) || (run.processPid && !absent(run.processPid))
|| (run.processGroupId && !absent(-run.processGroupId))) {
options.onDeferredDeadline?.(Date.now() + 30_000);
return "pending";
}
await appendLocalProcessStop(tx, { id: runId, companyId: run.companyId, agentId: run.agentId,
processPid: run.processPid, processGroupId: run.processGroupId, processStartedAt: run.processStartedAt });
}
await notifyLiveRunRecovery(tx, { companyId: run.companyId, runId: run.id, agentId: run.agentId });
await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId: run.id });
await notifyLiveRunRecovery(tx, { companyId: run.companyId, runId, agentId: run.agentId });
await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId });
// Local and remote stops both close the run's usage source.
await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId);
await tx.update(heartbeatRuns).set({
processPid: null, processGroupId: null, processStartedAt: null, updatedAt: new Date(),
}).where(eq(heartbeatRuns.id, run.id));
}).where(eq(heartbeatRuns.id, runId));
return "released" as const;
});
if (outcome !== "pending") pendingSettledProcessReleases.delete(runId);
return outcome;
return { outcome, remoteStop };
}
const MAX_SETTLED_PROCESS_RELEASE_ATTEMPTS = 20;
@@ -473,13 +530,7 @@ export async function discoverSettledNativeRunProcesses(db: Db, input: {
let after: string | null = null;
let released = 0;
do {
const candidates: Array<{ id: string }> = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.runtimeMode, "native"),
inArray(heartbeatRuns.status, SETTLED_RUN_STATUSES),
isNotNull(heartbeatRuns.finishedAt),
or(isNotNull(heartbeatRuns.processPid), isNotNull(heartbeatRuns.processGroupId), isNotNull(heartbeatRuns.processStartedAt)),
...(after ? [gt(heartbeatRuns.id, after)] : []),
)).orderBy(asc(heartbeatRuns.id)).limit(limit);
const candidates: Array<{ id: string }> = await settledNativeProcessCandidates(db, { after, limit });
for (const candidate of candidates) {
if (input.skip?.(candidate.id)) continue;
if (await settleNativeRunProcess(db, candidate.id) === "released") released += 1;
@@ -16,6 +16,7 @@ import {
type Db,
} from "@paperclipai/db";
import { logger } from "../../middleware/logger.js";
import { assessSessionRetention } from "./native-session-retention-blockers.js";
import { nativeHarnessStateBase } from "./native-harness-backup-stamp.js";
import { nativeSessionScopeDigestIsBusy } from "./native-session-executor.js";
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
@@ -185,7 +186,7 @@ type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
async function sessionRetentionBlocker(
tx: Tx,
input: { scopeDigest: string | null; identity: SessionIdentity; closedBefore: Date; checkpoint?: boolean; lock?: boolean },
input: { scopeDigest: string | null; identity: SessionIdentity; closedBefore: Date; checkpoint?: boolean },
): Promise<{ reason: string } | { companyId: string; agentId: string; runIds: string[]; issueIds: string[]; closedAt: number }> {
const [owner] = await tx
.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId })
@@ -225,7 +226,7 @@ async function sessionRetentionBlocker(
})
.from(issues)
.where(and(eq(issues.companyId, owner.companyId), inArray(issues.id, issueIds)));
const issueRows = await (input.lock === false ? issueQuery : issueQuery.for("share"));
const issueRows = await issueQuery.for("share");
if (issueRows.length !== issueIds.length) return { reason: "issue_unknown" };
for (const issue of issueRows) {
if (!CLOSED_ISSUE_STATUSES.includes(issue.status)) return { reason: "issue_open" };
@@ -314,6 +315,11 @@ export function nativeHarnessBackupExpirationService(
.where(and(durableBackupCursor ? gt(nativeHarnessBackups.id, durableBackupCursor) : undefined,
or(eq(nativeHarnessBackups.status, "retired"), lt(nativeHarnessBackups.createdAt, options.closedBefore))))
.orderBy(asc(nativeHarnessBackups.id)).limit(options.maxEntries + 1);
const assessments = await assessSessionRetention(db, candidates.slice(0, options.maxEntries)
.filter(candidate => candidate.survivingRunId && candidate.sessionId && !["retired", "pending", "superseded"].includes(candidate.status))
.map(candidate => ({ key: candidate.id, scopeDigest: candidate.scopeDigest,
identity: { runId: candidate.runId, normalizedSessionId: candidate.sessionId!, environmentLeaseId: null } })),
{ closedBefore: options.closedBefore, checkpoint: true });
let processed = 0;
for (const candidate of candidates) {
if (!options.shouldContinue() || processed++ >= options.maxEntries || result.expired >= options.maxRemovals) {
@@ -321,6 +327,7 @@ export function nativeHarnessBackupExpirationService(
}
durableBackupCursor = candidate.id;
if (candidate.survivingRunId && !candidate.sessionId) continue;
if (assessments.get(candidate.id)?.reason) continue;
try {
const retired = candidate.status === "retired" || await db.transaction(async tx => {
if (["pending", "superseded"].includes(candidate.status)) {
@@ -385,6 +392,11 @@ export function nativeHarnessBackupExpirationService(
isNull(nativeRunFinalizations.leaseOwner), isNull(nativeRunFinalizations.recoveryState),
))
.orderBy(asc(nativeRunnerCheckpoints.runId)).limit(options.maxEntries + 1);
const assessments = await assessSessionRetention(db, candidates.slice(0, options.maxEntries)
.filter(candidate => candidate.sessionId && !candidate.retirement)
.map(candidate => ({ key: candidate.runId, scopeDigest: null,
identity: { runId: candidate.runId, normalizedSessionId: candidate.sessionId!, environmentLeaseId: null } })),
{ closedBefore: options.closedBefore, checkpoint: true });
let processed = 0;
let removed = 0;
for (const candidate of candidates) {
@@ -395,6 +407,9 @@ export function nativeHarnessBackupExpirationService(
processed++;
checkpointCursor = candidate.runId;
if (!candidate.sessionId) continue; // Unknown identity is never expiration evidence.
const assessment = assessments.get(candidate.runId);
if (assessment && (assessment.reason || assessment.resumable
|| assessment.runIds.length > MAX_NATIVE_CHECKPOINT_RETIREMENT_RUNS)) continue;
try {
const previousRetirement = readNativeCheckpointRetirement(candidate.retirement, candidate);
if (previousRetirement && previousRetirement.sessionId !== candidate.sessionId) throw new Error("native_runner_checkpoint_retirement_invalid");
@@ -861,25 +876,6 @@ export function nativeHarnessBackupExpirationService(
});
}
async function backupDependencies(scopeDigest: string, identity: SessionIdentity): Promise<NativeHarnessBackupDependencies | null> {
const [owner] = await db.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
issueId: sql<string | null>`coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId})`,
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, identity.runId));
if (!owner) return null;
const runs = await db.select({ id: heartbeatRuns.id,
issueId: sql<string | null>`coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId})`,
}).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, owner.companyId),
eq(heartbeatRuns.agentId, owner.agentId), eq(heartbeatRuns.nativeSessionId, identity.normalizedSessionId)));
const runIds = [...new Set([identity.runId, ...runs.map(run => run.id)])];
const issueIds = [...new Set([owner.issueId, ...runs.map(run => run.issueId)].filter((id): id is string => Boolean(id)))];
const leases = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, owner.companyId), or(inArray(environmentLeases.heartbeatRunId, runIds),
sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'sessionScopeSha256' = ${scopeDigest}`,
identity.environmentLeaseId ? eq(environmentLeases.id, identity.environmentLeaseId) : undefined)));
return { companyId: owner.companyId, agentId: owner.agentId, sessionId: identity.normalizedSessionId,
runIds, issueIds, leaseIds: leases.map(lease => lease.id) };
}
async function resolveBackupScope(scope: NativeHarnessBackupExpirationScope) {
let runId = scope.runId;
let issueId = scope.issueId;
@@ -910,18 +906,20 @@ export function nativeHarnessBackupExpirationService(
if (!stat?.isDirectory() || stat.isSymbolicLink()) return null;
const identity = await readSessionIdentity(root);
if (!identity) return null;
const dependencies = await backupDependencies(scopeDigest, identity);
if (!dependencies) return null;
const assessment = (await assessSessionRetention(db, [{ key: scopeDigest, identity, scopeDigest }],
{ closedBefore: "infinity", checkpoint: false })).get(scopeDigest);
if (!assessment?.companyId || !assessment.agentId) return null;
const dependencies: NativeHarnessBackupDependencies = { companyId: assessment.companyId, agentId: assessment.agentId,
sessionId: identity.normalizedSessionId, runIds: [...new Set([identity.runId, ...assessment.runIds])],
issueIds: [...new Set([assessment.ownerIssueId, ...assessment.issueIds].filter((id): id is string => Boolean(id)))],
leaseIds: assessment.leaseIds };
const source = { id: scopeDigest, companyId: dependencies.companyId, agentId: dependencies.agentId, dependencies };
if (await fs.lstat(path.join(root, "cleanup-activation.json")).then(() => true, () => false)) {
return { ...source, dueAt: null };
}
const blocker = await db.transaction(tx => sessionRetentionBlocker(tx, {
scopeDigest, identity, closedBefore: new Date(8_000_000_000_000_000), lock: false,
}));
if ("reason" in blocker) return { ...source, dueAt: null };
if (assessment.reason || assessment.closedAt === null) return { ...source, dueAt: null };
const retentionMs = Math.max(1, defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS) * DAY_MS;
return { ...source, dueAt: Math.max(stat!.mtime.getTime(), blocker.closedAt) + retentionMs + 1 };
return { ...source, dueAt: Math.max(stat!.mtime.getTime(), assessment.closedAt) + retentionMs + 1 };
}
async function backupScopes(after?: string, limit = 100) {
@@ -52,7 +52,7 @@ export async function materializeNativeProviderCapacityRetry(input: {
executionRetryAccounting: accountingForScheduledRetry(run, NATIVE_PROVIDER_OVERLOADED_CODE, attempt),
};
await notifyAttentionRetentionWork(input.tx, { companyId: input.companyId });
await notifyScheduledRetryDispatch(input.tx, { companyId: run.companyId });
await notifyScheduledRetryDispatch(input.tx, { companyId: run.companyId, runId: run.id });
const [wake] = await input.tx.insert(agentWakeupRequests).values({
companyId: run.companyId, agentId: run.agentId, source: "automation", triggerDetail: "system",
reason: NATIVE_PROVIDER_OVERLOADED_CODE, status: "queued", runId: retryId,
@@ -775,8 +775,8 @@ export async function reconcileSafeNativeReplacements(
idempotencyKey: `native-safe-replacement:${run.id}`,
})
.returning();
await notifyExecutionRunWork(tx, { companyId: run.companyId });
await notifyScheduledRetryDispatch(tx, { companyId: run.companyId });
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
await notifyScheduledRetryDispatch(tx, { companyId: run.companyId, runId: run.id });
await tx.insert(heartbeatRuns).values({
id: successorRunId,
companyId: run.companyId,
@@ -210,7 +210,7 @@ export function selectNativeSessionResumeRun<
return null;
}
const NATIVE_SESSION_PROVIDER_EVENT_TYPES = [
export const NATIVE_SESSION_PROVIDER_EVENT_TYPES = [
"harness.ready",
"session.started",
"session.resumed",
@@ -0,0 +1,84 @@
import type { Db } from "@paperclipai/db";
const SESSION_RETENTION_BLOCKERS_SQL = `
with input as (
select * from jsonb_to_recordset($1::jsonb) as i(key text, run_id uuid, session_id uuid, scope_digest text, lease_id uuid)
), owner as (
select i.*, r.company_id, r.agent_id, coalesce(r.native_issue_id, r.issue_id) as owner_issue_id
from input i join heartbeat_runs r on r.id = i.run_id
), sessions as (
select o.key, o.run_id, o.session_id, o.scope_digest, o.lease_id, o.company_id, o.agent_id, o.owner_issue_id,
coalesce(array_agg(r.id order by r.id) filter (where r.id is not null), '{}') as run_ids,
coalesce(array_agg(distinct coalesce(r.native_issue_id, r.issue_id)) filter (where coalesce(r.native_issue_id, r.issue_id) is not null), '{}') as issue_ids,
coalesce(bool_or(r.status in ('queued', 'scheduled_retry', 'running') or r.finished_at is null), false) as live,
coalesce(bool_or((r.runner_profile_json->'nativeControllerRecovery'->>'schema' = 'paperclip.native-controller-recovery.v1'
and r.runner_profile_json->'nativeControllerRecovery'->'checkpoint' = 'null'::jsonb) is true), false) as incomplete,
coalesce(bool_or(r.finished_at >= $2::timestamptz), false) as recent
from owner o
left join heartbeat_runs r on r.company_id = o.company_id and r.agent_id = o.agent_id and r.native_session_id = o.session_id
group by o.key, o.run_id, o.session_id, o.scope_digest, o.lease_id, o.company_id, o.agent_id, o.owner_issue_id
), assessed as (
select s.*,
(select count(*) from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids)) as issues_found,
exists (select 1 from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids)
and x.status not in ('done', 'cancelled')) as issue_open,
exists (select 1 from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids)
and x.execution_run_id is not null) as issue_executing,
exists (select 1 from issues x where x.company_id = s.company_id and x.id = any(s.issue_ids)
and (coalesce(x.completed_at, x.cancelled_at) is null or coalesce(x.completed_at, x.cancelled_at) >= $2::timestamptz)) as issue_recent,
(select (extract(epoch from max(coalesce(x.completed_at, x.cancelled_at))) * 1000)::float8 from issues x
where x.company_id = s.company_id and x.id = any(s.issue_ids)) as closed_at,
(select count(*) from native_run_finalizations f where f.run_id = any(s.run_ids)) as finalizations,
exists (select 1 from native_run_finalizations f where f.run_id = any(s.run_ids)
and (f.phase not in ('committed', 'terminal_failure') or f.lease_owner is not null)) as finalization_pending,
exists (select 1 from (
select l.status from environment_leases l where l.heartbeat_run_id = any(s.run_ids)
union all select l.status from environment_leases l
where l.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' = s.scope_digest
union all select l.status from environment_leases l where $3::boolean and l.company_id = s.company_id and l.issue_id = any(s.issue_ids)
union all select l.status from environment_leases l where $3::boolean and l.company_id = s.company_id
and l.metadata->'nativeHarnessBackup'->>'normalizedSessionId' = s.session_id::text
union all select l.status from environment_leases l where l.id = s.lease_id
) referenced where referenced.status in ('active', 'released', 'retained', 'pending_cleanup')) as lease_live,
coalesce((select array_agg(distinct referenced.id order by referenced.id) from (
select l.id from environment_leases l where l.company_id = s.company_id and l.heartbeat_run_id = any(s.run_ids || s.run_id)
union all select l.id from environment_leases l where l.company_id = s.company_id
and l.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' = s.scope_digest
union all select l.id from environment_leases l where l.company_id = s.company_id and l.id = s.lease_id
) referenced), '{}') as lease_ids,
exists (select 1 from agent_task_sessions t where t.company_id = s.company_id and t.agent_id = s.agent_id
and (t.last_run_id = any(s.run_ids) or t.session_params_json->>'sessionId' = s.session_id::text)) as resumable
from sessions s
)
select i.key, a.company_id, a.agent_id, a.run_ids, a.issue_ids, a.owner_issue_id, a.lease_ids, a.closed_at, coalesce(a.resumable, false) as resumable,
case
when a.key is null then 'run_missing'
when a.live then 'live_run'
when a.incomplete then 'native_recovery_incomplete'
when $3::boolean and a.recent then 'recent_run'
when cardinality(a.issue_ids) = 0 or a.issues_found <> cardinality(a.issue_ids) then 'issue_unknown'
when a.issue_open then 'issue_open'
when $3::boolean and a.issue_executing then 'live_run'
when a.issue_recent then 'recently_closed'
when ($3::boolean and a.finalizations <> cardinality(a.run_ids)) or a.finalization_pending then 'pending_finalization'
when a.lease_live then 'live_lease'
end as reason
from input i left join assessed a on a.key = i.key`;
export type SessionRetentionAssessment = {
reason: string | null; companyId: string | null; agentId: string | null; runIds: string[]; issueIds: string[];
ownerIssueId: string | null; leaseIds: string[]; closedAt: number | null; resumable: boolean;
};
export async function assessSessionRetention(db: Db, sessions: Array<{ key: string; identity: { runId: string; normalizedSessionId: string; environmentLeaseId: string | null }; scopeDigest: string | null }>,
options: { closedBefore: Date | "infinity"; checkpoint: boolean }): Promise<Map<string, SessionRetentionAssessment>> {
if (sessions.length === 0) return new Map();
const rows = await db.$client.unsafe<Array<{ key: string; company_id: string | null; agent_id: string | null; run_ids: string[] | null;
issue_ids: string[] | null; owner_issue_id: string | null; lease_ids: string[] | null; closed_at: number | null; resumable: boolean; reason: string | null }>>(
SESSION_RETENTION_BLOCKERS_SQL, [JSON.stringify(sessions.map(session => ({ key: session.key, run_id: session.identity.runId,
session_id: session.identity.normalizedSessionId, scope_digest: session.scopeDigest, lease_id: session.identity.environmentLeaseId }))),
options.closedBefore === "infinity" ? "infinity" : options.closedBefore.toISOString(), options.checkpoint]);
return new Map(rows.map(row => [row.key, { reason: row.reason, companyId: row.company_id, agentId: row.agent_id,
runIds: row.run_ids ?? [], issueIds: row.issue_ids ?? [], ownerIssueId: row.owner_issue_id, leaseIds: row.lease_ids ?? [],
closedAt: row.closed_at === null ? null : Number(row.closed_at), resumable: row.resumable }]));
}
@@ -10,7 +10,7 @@ import { createCostEventInTransaction } from "../costs.js";
import { withOperationAccountingTransaction } from "../accounting-transaction.js";
import { notifyStatusCardIssueChange } from "../status-card-notifications.js";
import { nativeRunKeyScope, nativeSkillTestToolAllowed, assertNativeSkillTestTool } from "./native-skill-test-scope.js";
import { notifyAttentionRetentionWork } from "../retention-work-notifications.js";
import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js";
import { requiredQualityReviewSchema, type RequestCheckboxConfirmationOption } from "@paperclipai/shared";
import { priorRecoveryApiReceipt } from "../recovery-effect-receipts.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js";
@@ -2560,7 +2560,7 @@ export class PaperclipRunnerToolAuthority {
replayMonitor = summarizeIssueMonitor(target, normalizeIssueExecutionPolicy(target.executionPolicy));
return { taskId: target.id, status: target.status, monitor: replayMonitor };
}
await notifyAttentionRetentionWork(tx, { companyId: this.binding.companyId });
await notifyIssueAttentionRetentionWork(tx, { companyId: this.binding.companyId, issueId: target.id });
const patch = prepareIssueMonitorUpdate(target, input.monitor, actor);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors);
await notifyStatusCardIssueChange(tx, this.binding.companyId);
@@ -1,6 +1,6 @@
import { notifyStatusCardIssueChange } from "./status-card-notifications.js";
import { notifyIssueAttentionRetentionWork } from "./retention-work-notifications.js";
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
import { notifyIssueGraphRecovery } from "./issue-recovery-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
export type NativeStatusReassessmentScope = { companyId: string; issueId?: string; runId?: string; agentId?: string };
@@ -8,7 +8,7 @@ export type NativeStatusReassessmentScope = { companyId: string; issueId?: strin
export async function notifyNativeStatusReassessment(tx: object, scope: NativeStatusReassessmentScope) {
await notifyStatusCardIssueChange(tx, scope.companyId);
await notifyIssueAttentionRetentionWork(tx, { companyId: scope.companyId, issueId: scope.issueId, runId: scope.runId });
await notifyIssueRecovery(tx, scope ? { companyId: scope.companyId } : undefined);
await notifyIssueGraphRecovery(tx, scope);
return notifyDeliveryWork(tx, DELIVERY_QUEUES.nativeStatusReassessment,
JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId, runId: scope.runId, agentId: scope.agentId }));
}
@@ -505,7 +505,8 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
order by lr.created_at desc limit 1), false)`;
}
async function listSuspects(scope: { companyId?: string; issueId?: string; createdAfter?: Date | null }, cursor: string | null, limit: number) {
async function listSuspects(scope: { companyId?: string; issueId?: string; issueIds?: string[]; createdAfter?: Date | null },
cursor: string | null, limit: number) {
const at = now();
const liveRun = sql`exists (select 1 from heartbeat_runs r where r.company_id = ${issues.companyId}
and (r.context_snapshot->>'issueId') = ${issues.id}::text
@@ -521,6 +522,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
return db.select({ id: issues.id, companyId: issues.companyId, updatedAt: issues.updatedAt }).from(issues).where(and(
scope.companyId ? eq(issues.companyId, scope.companyId) : undefined,
scope.issueId ? eq(issues.id, scope.issueId) : undefined,
scope.issueIds ? inArray(issues.id, scope.issueIds) : undefined,
cursor ? sql`${issues.id} > ${cursor}` : undefined,
scope.createdAfter ? gte(issues.createdAt, scope.createdAfter) : undefined,
inArray(issues.status, [...OPEN_STATUSES]),
+2 -2
View File
@@ -2832,7 +2832,7 @@ export function recoveryService(
const now = new Date();
const retryAt = readProviderQuotaRetryAt(input.latestRun, now);
return database.transaction(async (tx) => {
await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId });
await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId, issueId: input.issue.id });
const wakeup = await tx
.insert(agentWakeupRequests)
.values({
@@ -3429,7 +3429,7 @@ export function recoveryService(
created = Boolean(enqueuedRun);
} else {
scheduledRun = await db.transaction(async (tx) => {
await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId });
await notifyScheduledRetryDispatch(tx, { companyId: input.issue.companyId, issueId: input.issue.id });
const wakeup = await tx
.insert(agentWakeupRequests)
.values({
+70 -19
View File
@@ -3,7 +3,8 @@ import { and, asc, eq, gt, inArray, isNotNull, isNull, or, sql, type SQL } from
import { issueRecoveryActions, issueRelations, issues, type Db } from "@paperclipai/db";
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
import { DELIVERY_QUEUES, type DeliveryQueue } from "../delivery-work-notifications.js";
import type { IssueRecoveryScope } from "../issue-recovery-notifications.js";
import { decodeIssueRecoveryHint, ISSUE_RECOVERY_BACKSTOP_MS, issueRecoveryScopeMatches, resolveIssueGraph, type IssueRecoveryScope }
from "../issue-recovery-notifications.js";
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
import { recoveryActionSweepCondition } from "./blocker-stall-wakeups.js";
@@ -11,6 +12,13 @@ type Entry = { id: string; companyId: string; dueAt: number };
type Scope = { companyId: string; issueId: string; onDeferredDeadline: (at: number) => void };
const PAGE_SIZE = 100;
export const resolvedDependencyCandidate = sql`exists (select 1 from ${issueRelations} r where r.company_id = ${issues.companyId}
and r.related_issue_id = ${issues.id} and r.type = 'blocks' offset 0)
and not exists (select 1 from ${issueRelations} r inner join ${issues} blocker
on blocker.id = r.issue_id and blocker.company_id = r.company_id
where r.company_id = ${issues.companyId} and r.related_issue_id = ${issues.id}
and r.type = 'blocks' and blocker.status <> 'done' offset 0)`;
export function registerIssueRecoveryWork(
db: Db,
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
@@ -24,29 +32,69 @@ export function registerIssueRecoveryWork(
schedulingSuppressed(): Promise<boolean>;
/** The assigned-work invariant (assigned-work-sweep.ts). */
assignedWork?: {
listSuspects(scope: { companyId?: string; issueId?: string }, cursor: string | null, limit: number):
listSuspects(scope: { companyId?: string; issueId?: string; issueIds?: string[] }, cursor: string | null, limit: number):
Promise<Array<{ id: string; companyId: string; updatedAt: Date }>>;
checkIssue(scope: Scope): Promise<unknown>;
};
},
canRun: () => boolean,
options: { backstopMs?: number } = {},
) {
function fullPasses() {
const completedAt = new Map<string, number>();
return {
backstop: (scope: IssueRecoveryScope | undefined) => scope?.backstop
? Math.max(completedAt.get("*") ?? 0, completedAt.get(scope.companyId) ?? 0) + (options.backstopMs ?? ISSUE_RECOVERY_BACKSTOP_MS)
: null,
loaded(scope: IssueRecoveryScope | undefined, complete: boolean) {
if (complete && !scope?.issueId && (!isGraph(scope) || scope?.wholeCompany)) completedAt.set(scope?.companyId ?? "*", Date.now());
},
};
}
const reconstructionIntervalMs = (scope: IssueRecoveryScope | undefined) => scope?.backstop || scope?.graphRunId || scope?.graphIssueId ? 0 : 30_000;
const scopeKey = (scope: IssueRecoveryScope | undefined) => scope
? JSON.stringify([scope.companyId, scope.issueId, scope.graphRunId, scope.graphIssueId, scope.backstop]) : "*";
const isGraph = (scope: IssueRecoveryScope | undefined) => Boolean(scope?.graphRunId || scope?.graphIssueId);
const graphs = new Map<string, { at: number; ids: Promise<string[] | null> }>();
async function resolveGraph(scope: IssueRecoveryScope | undefined) {
if (!scope || !isGraph(scope)) return;
const key = scopeKey(scope);
for (const [other, cached] of graphs) if (cached.at < Date.now() - 2_000) graphs.delete(other);
let cached = graphs.get(key);
if (!cached) {
cached = { at: Date.now(), ids: resolveIssueGraph(db, { companyId: scope.companyId, runId: scope.graphRunId, issueId: scope.graphIssueId }) };
graphs.set(key, cached);
}
const ids = await cached.ids.catch(error => { graphs.delete(key); throw error; });
scope.issueIds = ids ?? undefined;
scope.wholeCompany = ids === null;
}
async function toCompany(scope: IssueRecoveryScope | undefined, worker: { invalidate(hint?: string): void }) {
await resolveGraph(scope);
if (!scope?.wholeCompany) return false;
worker.invalidate(JSON.stringify({ companyId: scope.companyId }));
return true;
}
function register(queue: DeliveryQueue, statuses: string[] | null, check: (scope: Scope) => Promise<unknown>, eligible?: SQL) {
const cursors = new Map<string, string>();
const passes = fullPasses();
let enabled = false;
return registerScopedDeadlineWork<Entry, IssueRecoveryScope>(coordinator, {
const worker: ReturnType<typeof registerScopedDeadlineWork<Entry, IssueRecoveryScope>> = registerScopedDeadlineWork<Entry, IssueRecoveryScope>(coordinator, {
queue,
reconstructionIntervalMs: 30_000,
reconstructionIntervalMs,
backstop: passes.backstop,
beforePass: async () => { enabled = !(await owner.schedulingSuppressed()); },
decodeScope: hint => hint === "*" ? undefined : JSON.parse(hint) as IssueRecoveryScope,
matches: (entry, scope) => !scope || (entry.companyId === scope.companyId && (!scope.issueId || entry.id === scope.issueId)),
decodeScope: decodeIssueRecoveryHint,
matches: issueRecoveryScopeMatches,
load: async scope => {
const key = scope ? JSON.stringify([scope.companyId, scope.issueId]) : "*";
const key = scopeKey(scope);
if (!enabled) { cursors.delete(key); return []; }
if (await toCompany(scope, worker)) return { rows: null, complete: true };
const cursor = cursors.get(key);
const rows = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(and(
scope ? eq(issues.companyId, scope.companyId) : undefined,
scope?.issueId ? eq(issues.id, scope.issueId) : undefined,
scope?.issueIds ? inArray(issues.id, scope.issueIds) : undefined,
cursor ? gt(issues.id, cursor) : undefined,
statuses ? inArray(issues.status, statuses) : or(isNotNull(issues.checkoutRunId), isNotNull(issues.executionRunId)),
statuses ? isNull(issues.hiddenAt) : undefined,
@@ -56,6 +104,7 @@ export function registerIssueRecoveryWork(
)).orderBy(asc(issues.id)).limit(PAGE_SIZE);
const complete = rows.length < PAGE_SIZE;
if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id);
passes.loaded(scope, complete);
return { rows: rows.map(row => ({ ...row, dueAt: Date.now() })), complete };
},
check: async entry => {
@@ -66,6 +115,7 @@ export function registerIssueRecoveryWork(
return next === null ? null : { ...entry, dueAt: next };
},
}, canRun);
return worker;
}
/** Event-driven: run terminal states, hold settlements and boot mark the
* company dirty; checks schedule their own grace and back-off deadlines.
@@ -73,22 +123,27 @@ export function registerIssueRecoveryWork(
function registerAssignedWork(sweep: NonNullable<typeof owner.assignedWork>) {
type Suspect = Entry & { updatedAt: number };
const cursors = new Map<string, string>();
const passes = fullPasses();
let enabled = false;
return registerScopedDeadlineWork<Suspect, IssueRecoveryScope>(coordinator, {
const worker: ReturnType<typeof registerScopedDeadlineWork<Suspect, IssueRecoveryScope>> = registerScopedDeadlineWork<Suspect, IssueRecoveryScope>(coordinator, {
queue: DELIVERY_QUEUES.assignedWorkInvariant,
reconstructionIntervalMs: 30_000,
reconstructionIntervalMs,
backstop: passes.backstop,
batchSize: 25,
beforePass: async () => { enabled = !(await owner.schedulingSuppressed()); },
decodeScope: hint => hint === "*" ? undefined : JSON.parse(hint) as IssueRecoveryScope,
matches: (entry, scope) => !scope || (entry.companyId === scope.companyId && (!scope.issueId || entry.id === scope.issueId)),
decodeScope: decodeIssueRecoveryHint,
matches: issueRecoveryScopeMatches,
priority: entry => entry.updatedAt,
mergeEntry: (pending, loaded) => ({ ...loaded, dueAt: Math.max(pending.dueAt, loaded.dueAt) }),
load: async scope => {
const key = scope ? JSON.stringify([scope.companyId, scope.issueId]) : "*";
const key = scopeKey(scope);
if (!enabled) { cursors.delete(key); return []; }
const rows = await sweep.listSuspects(scope ?? {}, cursors.get(key) ?? null, PAGE_SIZE);
if (await toCompany(scope, worker)) return { rows: null, complete: true };
const rows = await sweep.listSuspects(scope ? { companyId: scope.companyId, issueId: scope.issueId,
issueIds: scope.issueIds } : {}, cursors.get(key) ?? null, PAGE_SIZE);
const complete = rows.length < PAGE_SIZE;
if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id);
passes.loaded(scope, complete);
return { rows: rows.map(row => ({ id: row.id, companyId: row.companyId, updatedAt: row.updatedAt.getTime(), dueAt: Date.now() })), complete };
},
check: async entry => {
@@ -99,6 +154,7 @@ export function registerIssueRecoveryWork(
return next === null ? null : { ...entry, dueAt: next };
},
}, canRun);
return worker;
}
function registerCompany(queue: DeliveryQueue, kind: "blockers" | "actions", check: (scope: { companyId: string }) => Promise<number | null | void>) {
const cursors = new Map<string, string>();
@@ -155,12 +211,7 @@ export function registerIssueRecoveryWork(
const dependencies = register(DELIVERY_QUEUES.resolvedDependencies, ["blocked"], async scope => {
const result = await owner.dependencies(scope);
if (result.enqueueFailed > 0) throw new Error("Resolved dependency wake remains undelivered");
}, sql`exists (select 1 from ${issueRelations} r where r.company_id = ${issues.companyId}
and r.related_issue_id = ${issues.id} and r.type = 'blocks')
and not exists (select 1 from ${issueRelations} r inner join ${issues} blocker
on blocker.id = r.issue_id and blocker.company_id = r.company_id
where r.company_id = ${issues.companyId} and r.related_issue_id = ${issues.id}
and r.type = 'blocks' and blocker.status <> 'done')`);
}, resolvedDependencyCandidate);
const locks = register(DELIVERY_QUEUES.staleIssueLocks, null, owner.locks);
const assignedWork = owner.assignedWork ? registerAssignedWork(owner.assignedWork) : null;
const watchdogs = registerTaskWatchdogWork(db, coordinator, {
@@ -6,6 +6,7 @@ import type { AttentionSourceKind } from "@paperclipai/shared";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
export const ATTENTION_RETENTION_MAX_ISSUE_IDS = 100;
const UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
export type AttentionRetentionScope = { companyId?: string; sourceKind?: AttentionSourceKind;
issueId?: string; issueIds?: string[]; sourceId?: string };
@@ -27,9 +28,10 @@ export async function notifyIssueAttentionRetentionWork(transaction: object,
where company_id = ${scope.companyId}::uuid and id = ${scope.runId}::uuid and issue_id is not null
union select native_issue_id::text from heartbeat_runs
where company_id = ${scope.companyId}::uuid and id = ${scope.runId}::uuid and native_issue_id is not null
union select issue.id::text from heartbeat_runs run inner join issues issue
on issue.company_id = run.company_id
and issue.id::text = coalesce(run.context_snapshot->>'issueId', run.context_snapshot->>'taskId')
union select issue.id::text from heartbeat_runs run
cross join lateral (select coalesce(run.context_snapshot->>'issueId', run.context_snapshot->>'taskId') as saved) context
inner join issues issue on issue.company_id = run.company_id
and issue.id = case when context.saved ~* ${UUID_PATTERN} then context.saved::uuid end
where run.company_id = ${scope.companyId}::uuid and run.id = ${scope.runId}::uuid`);
for (const row of rows) seeds.push(row.id as string);
}
+6 -6
View File
@@ -166,8 +166,8 @@ const nativeProviderWorkNeverStarted = sql`${heartbeatRuns.runtimeMode} = 'nativ
/** A run's accounting settled: an admission hold may have cleared. Held work
* (queued runs, saved messages and Retries, and tasks whose start or
* continuation was refused) waits passively, so wake its owners. */
async function notifyAccountingHoldRelease(tx: object, companyId: string) {
await promoteDeferredWorkIntents(tx, { companyId, trigger: "accounting_settled" });
async function notifyAccountingHoldRelease(tx: object, companyId: string, runId: string) {
await promoteDeferredWorkIntents(tx, { companyId, trigger: "accounting_settled", runId });
}
export const ACCOUNTING_CLOSURE_TIMEOUT_MS = REMOTE_RUNNER_RECONNECT_GRACE_MS + 3 * 60_000;
@@ -289,11 +289,11 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService
if (run.costAccountedAt) {
if (object(run.usageJson).accountingLateReceiptPending === true) {
// Clearing late debt can release an admission hold too.
await notifyAccountingHoldRelease(tx, run.companyId);
await notifyAccountingHoldRelease(tx, run.companyId, run.id);
return reconcileLateRunUsageReceiptInTransaction(tx, run, publications);
}
await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: run.agentId });
await notifyAccountingHoldRelease(tx, run.companyId);
await notifyAccountingHoldRelease(tx, run.companyId, run.id);
await tx.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, run.id));
await queueBudgetEvaluation(tx, { companyId: run.companyId, agentId: run.agentId,
projectId: text(object(object(run.usageJson).ledgerScope).projectId) });
@@ -333,7 +333,7 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService
// Acknowledgement is part of the same transaction. Budget checks inside
// this transaction must not mistake this receipt for missing accounting.
await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: run.agentId });
await notifyAccountingHoldRelease(tx, run.companyId);
await notifyAccountingHoldRelease(tx, run.companyId, run.id);
await tx.update(heartbeatRuns).set({ costAccountingPending: false, costAccountedAt: new Date() }).where(eq(heartbeatRuns.id, run.id));
await tx.update(budgetReservations).set({ state: preProviderFailure ? "released" : "settled", settledAt: new Date() })
.where(and(eq(budgetReservations.companyId, run.companyId), eq(budgetReservations.runId, run.id), eq(budgetReservations.state, "held")));
@@ -426,7 +426,7 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService
await queueBudgetEvaluation(tx, { companyId: run.companyId, agentId: run.agentId, projectId: text(scope.projectId) });
// Late usage reported by a later run can arrive before this charge posts.
const lateDebt = usage.accountingLateReceiptPending === true;
if (!lateDebt) await notifyAccountingHoldRelease(tx, run.companyId);
if (!lateDebt) await notifyAccountingHoldRelease(tx, run.companyId, run.id);
await tx.update(heartbeatRuns).set({ costAccountingPending: lateDebt, costAccountedAt: new Date(), accountingProjectionVersion: "v2",
accountingLastError: lateDebt ? "late_usage_requires_reconciliation" : null, accountingLastAttemptAt: new Date(),
// A complete receipt arriving later may price this charge (see usage-receipts).
@@ -1,7 +1,7 @@
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
export type RunDispatchScope = { companyId: string };
export type RunDispatchScope = { companyId: string; issueId?: string | null; runId?: string | null };
export async function notifyQueuedRunDispatch(transaction: object, scope?: RunDispatchScope) {
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.queuedRunDispatch,
@@ -9,7 +9,8 @@ export async function notifyQueuedRunDispatch(transaction: object, scope?: RunDi
}
export async function notifyRunDispatch(transaction: object, scope?: RunDispatchScope) {
await notifyIssueRecovery(transaction, scope ? { companyId: scope.companyId } : undefined);
if (scope?.issueId || scope?.runId) await notifyIssueGraphRecovery(transaction, scope);
else await notifyIssueRecovery(transaction, scope ? { companyId: scope.companyId } : undefined);
const hint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*";
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.nativeProcessSessions, hint);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.executionReplacement, hint);
+12 -5
View File
@@ -26,6 +26,7 @@ export function registerScopedDeadlineWork<Entry extends ScheduledEntry, Scope>(
admitDueWhileActive?: boolean;
};
reconstructionIntervalMs?: number | ((scope: Scope | undefined) => number);
backstop?(scope: Scope | undefined): number | null;
beforePass?(): Promise<void>;
decodeScope(hint: string): Scope | undefined;
matches(entry: Entry, scope?: Scope): boolean;
@@ -67,6 +68,12 @@ export function registerScopedDeadlineWork<Entry extends ScheduledEntry, Scope>(
decodedScopes.set(hint, scope);
return scope;
}
function backstopAt(hint: string) {
if (!options.backstop) return null;
try { return options.backstop(decode(hint)); } catch { return null; }
}
const holdsIdle = (hint: string) => backstopAt(hint) === null;
const gate = (hint: string) => Math.max(reconstructAfter.get(hint) ?? 0, backstopAt(hint) ?? 0);
function forgetDecoded() {
for (const hint of decodedScopes.keys()) if (!dirty.has(hint) && !scans.has(hint)) decodedScopes.delete(hint);
}
@@ -92,14 +99,14 @@ export function registerScopedDeadlineWork<Entry extends ScheduledEntry, Scope>(
function dirtyScopes() {
return [...dirty].filter(hint => hint !== "*" || !scopeFailures.has(hint))
.filter(hint => !scans.has(hint) || scopeFailures.has(hint))
.filter(hint => (reconstructAfter.get(hint) ?? 0) <= Date.now() || scopeFailures.has(hint))
.filter(hint => gate(hint) <= Date.now() || scopeFailures.has(hint))
.map(hint => { try { return decode(hint); } catch { return undefined; } });
}
function next() {
if (!canRun()) return dirty.size > 0 || entries.size > 0 ? Date.now() + 30_000 : null;
let nextAt: number | null = null;
const take = (at: number) => { nextAt = nextAt === null ? at : Math.min(nextAt, at); };
for (const hint of dirty) take(Math.max(earliest, reconstructAfter.get(hint) ?? 0, scopeFailures.get(hint)?.retryAt ?? 0));
for (const hint of dirty) take(Math.max(earliest, gate(hint), scopeFailures.get(hint)?.retryAt ?? 0));
const unavailable = matcher(dirtyScopes());
for (const entry of entries.values()) if (!unavailable(entry))
take(Math.max(earliest, entry.dueAt, failures.get(entry.id)?.retryAt ?? 0));
@@ -119,7 +126,7 @@ export function registerScopedDeadlineWork<Entry extends ScheduledEntry, Scope>(
for (const [hint, until] of reconstructAfter) {
if (until <= Date.now()) reconstructAfter.delete(hint);
}
const ready = [...dirty].filter(hint => Math.max(reconstructAfter.get(hint) ?? 0, scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now());
const ready = [...dirty].filter(hint => Math.max(gate(hint), scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now());
if (ready.length === 0 && ![...entries.values()].some(entry => Math.max(entry.dueAt, failures.get(entry.id)?.retryAt ?? 0) <= Date.now())) return;
earliest = Date.now() + (options.minimumPassIntervalMs ?? 1000);
try { await options.beforePass?.(); } catch (error) {
@@ -325,7 +332,7 @@ export function registerScopedDeadlineWork<Entry extends ScheduledEntry, Scope>(
},
// Retain scopes/deadlines for resume without retaining a settled write's
// idle hold during drain. The coordinator still fences unresolved XIDs.
hasPending: async () => canRun() && dirty.size > 0,
hasPending: async () => canRun() && [...dirty].some(holdsIdle),
nextRunAt: next,
nextRunAtOnError: next,
});
@@ -337,7 +344,7 @@ export function registerScopedDeadlineWork<Entry extends ScheduledEntry, Scope>(
return { ...worker,
reconciliationSnapshot: (): DeadlineReconciliationSnapshot => ({
revision: `${ownerRevision}:${revision}`,
reconciled: !stopped && !running && !lastRunFailed && dirty.size === 0 && scans.size === 0
reconciled: !stopped && !running && !lastRunFailed && ![...dirty].some(holdsIdle) && scans.size === 0
&& failures.size === 0 && scopeFailures.size === 0,
}),
wake() { revision++; worker.wake(); },
@@ -6,7 +6,7 @@ import { and, asc, desc, eq, gt, inArray, isNull, sql } from "drizzle-orm";
import { chatConversations, chatEndpoints, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db";
import { persistActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
export type ExternalConversationSettlementScope = { companyId: string; issueId?: string };
export type ExternalConversationSettlementScope = { companyId: string; issueId?: string; runId?: string };
+9 -4
View File
@@ -1,5 +1,5 @@
import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
import { agentWakeupRequests, issueComments, issues, type Db } from "@paperclipai/db";
import { agentWakeupRequests, budgetPolicies, issueComments, issues, type Db } from "@paperclipai/db";
import { notifyDeferredExecutionEligibility, notifyDeferredExecutionWork, notifyDeferredWakesForIssue } from "./deferred-execution-notifications.js";
import { withQueuedCommentIdsInWakePayload } from "./issue-queued-comment-queue.js";
import { deliveredQueuedCommentIds } from "./queued-comment-delivery.js";
@@ -65,12 +65,17 @@ const DEFERRED_RETRY_BACKOFF = sql`interval '30 seconds'`;
* issue by id. All notifications publish on commit.
*/
export async function promoteDeferredWorkIntents(tx: object, input: {
companyId: string; trigger: WorkIntentHoldTrigger; issueId?: string | null;
companyId: string; trigger: WorkIntentHoldTrigger; issueId?: string | null; runId?: string | null;
}) {
const hardStop = input.trigger === "accounting_settled" && input.runId ? (await (tx as Pick<Db, "select">)
.select({ id: budgetPolicies.id }).from(budgetPolicies).where(and(eq(budgetPolicies.companyId, input.companyId),
eq(budgetPolicies.isActive, true), eq(budgetPolicies.hardStopEnabled, true))).limit(1)).length > 0 : true;
const scope = input.trigger === "lock_released" && input.issueId ? { companyId: input.companyId, issueId: input.issueId }
: input.trigger === "accounting_settled" && input.runId && !hardStop ? { companyId: input.companyId, runId: input.runId } : null;
// Register the work signals before the write they announce.
await notifyRunDispatch(tx, { companyId: input.companyId });
await notifyRunDispatch(tx, scope ?? { companyId: input.companyId });
await notifyDeferredExecutionEligibility(tx, { companyId: input.companyId });
await notifyIssueRecovery(tx, { companyId: input.companyId });
if (!scope) await notifyIssueRecovery(tx, { companyId: input.companyId });
if (input.issueId) await notifyDeferredWakesForIssue(tx, { companyId: input.companyId, issueId: input.issueId });
const db = tx as Pick<Db, "update">;
await db.update(agentWakeupRequests).set({
+15
View File
@@ -410,6 +410,21 @@ describe("runBoundedShutdownStep", () => {
}
});
it("aborts the signal of a step that outlives its bound, and only that step", async () => {
vi.useFakeTimers();
try {
const signals: AbortSignal[] = [];
const budget = createPreDrainShutdownBudget({ signal: "SIGTERM", budgetMs: 250, log: stubLogger() });
await budget.run("delivery_work_stop", async abort => { signals.push(abort); });
const pending = budget.run("hot_restart_prepare", abort => { signals.push(abort); return new Promise<void>(() => undefined); });
await vi.advanceTimersByTimeAsync(250);
await expect(pending).resolves.toMatchObject({ outcome: "timed_out" });
expect(signals.map(signal => signal.aborted)).toEqual([false, true]);
} finally {
vi.useRealTimers();
}
});
it("logs a step that rejects and does not reject the shutdown", async () => {
const log = stubLogger();
const error = new Error("skill sync stop failed");
+5 -3
View File
@@ -23,18 +23,19 @@ export async function runBoundedShutdownStep<T>(input: {
step: string;
signal: "SIGINT" | "SIGTERM";
timeoutMs: number;
run: () => Promise<T>;
run: (abort: AbortSignal) => Promise<T>;
log: ShutdownLogger;
now?: () => number;
}): Promise<ShutdownStepResult<T>> {
const now = input.now ?? Date.now;
const startedAt = now();
const timeoutMs = Math.max(0, input.timeoutMs);
const abort = new AbortController();
let timer: NodeJS.Timeout | null = null;
try {
const result = await Promise.race([
Promise.resolve()
.then(input.run)
.then(() => input.run(abort.signal))
.then(
(value) => ({ outcome: "completed" as const, value }),
(error: unknown) => ({ outcome: "failed" as const, error }),
@@ -54,6 +55,7 @@ export async function runBoundedShutdownStep<T>(input: {
input.log.error({ ...fields, err: result.error }, "shutdown step failed; continuing shutdown");
return { outcome: "failed", error: result.error, durationMs };
}
abort.abort(new Error(`shutdown step ${input.step} timed out`));
input.log.info(fields, "shutdown step timed out; continuing shutdown without it");
return { outcome: "timed_out", durationMs };
} finally {
@@ -70,7 +72,7 @@ export function createPreDrainShutdownBudget(input: {
const now = input.now ?? Date.now;
const deadline = now() + (input.budgetMs ?? PRE_DRAIN_SHUTDOWN_BUDGET_MS);
return {
run<T>(step: string, run: () => Promise<T>) {
run<T>(step: string, run: (abort: AbortSignal) => Promise<T>) {
return runBoundedShutdownStep({
step,
signal: input.signal,