mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process controls every running native agent. Each run holds a native execution lease that the process must renew before it expires (60 seconds for a remote run, 20 minutes for a local run) > - Each run renewed its lease on its own timer, in its own transaction, on a private pool of two connections. At 1,000 remote runs that is about 50 transactions each second through two connections > - When renewals queue behind each other, a renewal can miss its 60 second deadline, and the run is lost although the server is healthy > - Each renewal also woke six live-run recovery queues for its run. The recovery owner then re-checked a healthy run about every 20 seconds, although a renewal only moves the deadline later > - This pull request renews all leases of one process with one shared timer. All leases that are due go into one transaction of fixed size, the same model that the legacy controller lease already uses. A renewal no longer wakes recovery, as #20924 did for the legacy lease > - The benefit is that the renewal cost no longer grows with the number of runs, and all safety properties of a single renewal stay the same ## Linked Issues or Issue Description Refs #20924 (the same change for the legacy controller lease), #21242. **What existing behavior does this improve?** Native execution lease renewal in `server/src/services/native-runtime/native-execution-lease.ts`. Each run had one `setInterval` and one transaction per renewal: statement timeout, row lock, recovery notification, update, commit. **Subsystem affected** Server: native runtime, controller lease renewal on the liveness connection pool. **Current behavior** The renewal cost grows with the number of runs. A local load model with 1,000 remote runs sends 35.7 lease transactions and 212.8 lease statements each second, and the event-loop utilization is 0.34. All of them use a pool of two connections. **Proposed behavior** One timer for each database client renews all due leases in one transaction for each 200 runs. With 1,000 remote runs the same model sends 0.29 lease transactions and 1.7 lease statements each second, and the event-loop utilization is 0.07. **Reason and benefit** The plan for 1,000 concurrent agents needs renewals that do not scale with the run count (item 1d). A renewal that misses its deadline loses the run. **Breaking changes** None. The `NativeExecutionLeaseRenewal` contract (`stop()`, `remainingMs()`) and `renewNativeSessionExecutionLease` do not change. ## What Changed - `native-execution-lease.ts`: a renewal (batched or single) no longer calls `notifyLiveRunRecovery`. A renewal only moves the lease deadline later. Recovery already holds a deadline at the earlier expiry. At that deadline it re-reads the row and moves to the new expiry. A lapsed lease is still found at its expiry. This change does not touch the signals of the writers that release, revoke or take over a lease, or that change the run status. This also removes six notifications for each renewal, which was 1,200 notifications for a batch of 200 runs during a deploy overlap. - `native-execution-lease.ts`: one shared schedule for each database client replaces the timer of each run. When the first lease is due, all leases that are due within a quarter of their own interval renew with it. Thus the leases of a process converge on one batch for each interval. - A batch is one transaction on the liveness pool for each 200 runs: `statement_timeout`, one `SELECT … FOR UPDATE SKIP LOCKED` of the coordinator rows, and one `UPDATE … FROM (VALUES …)`. - The batch keeps the guarantees of a single renewal: - It locks each coordinator row before it reads the expiry, as before. Thus an owner whose lease expired while another writer held the row is never revived. - It extends a row only for the exact owner: run, company, task, lease owner, attempt, controller boot id, pid, process start, and a live lease. - The confirmed deadline is sampled after the locks and before the update, as before. - A run whose row was locked and not extended fails with `native_session_lease_lost`. The other runs in the batch succeed. - These rows do not renew in the batch. They renew alone through the unchanged single-run path: - A row that another writer holds (`SKIP LOCKED`). Thus one busy row cannot hold the batch until the statement timeout. - A row that the lock did not find (another owner, or no row). The single path gives the same answer as before. - A local lease that lapsed (host sleep). Only the single path may take it back, under the run row lock. - A batch that is cancelled (statement timeout `57014` or deadlock `40P01`) extends nothing. Its runs retry after 1 second, and each run keeps its own deadline timer. Before this change, a statement timeout waited for the next 20 second tick. - Any other batch failure, also an error thrown while the statement is built, may come from one bad row. Each run of that batch then renews alone at once through the single path, so a bad row can cost only its own run. A run that fails alone while others in its batch renew keeps renewing alone (out of later batches) until a single renewal succeeds. During a database outage the single renewals also fail; those runs return to the batch at their next interval, not after a 1 second retry, so an outage causes at most one queued single transaction for each run and interval. - Runs that become due while a batch is in flight wait for that batch. A batch that runs for more than 15 seconds no longer holds back the next batch. - A tick that passed while a renewal was in flight is skipped, as a fixed interval skips it. Thus a slow database gets no extra load. - The shared timer replaces the interval timer of each run. It exists only while this process holds a lease, and it fires at the next renewal deadline. With no held lease there is no timer and no SQL. - New export `renewNativeExecutionLeasesNow(db)` renews all leases of the process at once. Tests use it. ## Verification - New PostgreSQL tests in `native-execution-lease-batch.test.ts`: - 3 runs and 60 runs each renew in 1 transaction with the same number of statements. - 450 runs renew in 3 transactions. - In one batch, the runs whose lease was taken over, whose controller boot changed, or whose lease expired fail with `native_session_lease_lost`. Their rows do not change. The healthy runs renew. A newer attempt under the same owner is not lost, as before. - Interleaving: another transaction holds a coordinator row from before its lease expires until after it expired. The healthy run in the same batch renews at once. After the lock is released, the expired owner is lost and its row stays expired. - A takeover that commits before the batch: the batch extends nothing and the run is lost. - A local and a remote lease renew in one transaction, each for its own lease length. - A poison binding (an attempt outside the integer range) makes the shared UPDATE fail with `22003`. The other 4 runs still renew in the same tick, only the poison run is lost, and the next tick renews the 4 runs in 1 transaction again. - An invalid date throws while the statement is built. The other runs renew, the broken run is lost alone, and no lease stays busy (the next call renews again in 1 transaction). - New PostgreSQL test in `live-recovery-work.test.ts` with the real registered recovery owners: another server's native run renews its lease. No recovery pass runs after the renewal. At the old expiry recovery re-reads the row, keeps the run running and moves its deadline to the new expiry. When renewals stop, recovery acts on the run within 10 seconds after the end of the last lease. - Red first: with a shim on `origin/master` that renews each lease alone, the transaction test failed (`expected 3 to be 1`) and the 450-run test failed. - The unit tests in `native-execution-lease.test.ts` now drive the batch. New tests show that a non-cancelled batch failure renews the run alone at once, and that an outage (batch and single renewal both fail) does not retry every second and loses no run. - `native-execution-lease-reacquire.test.ts`: the host-sleep tests now go through the batch, which hands the lapsed local lease to the single path. - Load model (`startNativeSessionExecutionLeaseRenewal` for N remote runs that start at random times over 20 seconds, 70 second window, local PostgreSQL, machine load average about 50): | Runs | Lease transactions/s before → after | Lease statements/s before → after | Event-loop utilization before → after | Smallest margin to the 60 s deadline | Lost | | --- | --- | --- | --- | --- | --- | | 50 | 1.81 → 0.11 | 10.9 → 0.69 | 0.015 → 0.095 (noise) | 40.0 s → 40.0 s | 0 → 0 | | 1,000 | 35.67 → 0.29 | 212.8 → 1.71 | 0.341 → 0.065 | 39.0 s → 40.0 s | 0 → 0 | The window includes the 20 second ramp, so the steady rate before is higher (one transaction each 20 seconds for each run, 50/s at 1,000 runs). After the change, one batch carries up to 200 runs. ## Risks - **Behavior change: batch-wide error handling.** One shared transaction now carries up to 200 runs, so one database error reaches all of them. A cancelled batch only skips the extension and retries after 1 second. Any other batch error sends each run to the single path at once, so one bad row (a bad value, a cast error, an error while the statement is built) costs only its own run. In a database outage, up to one single transaction for each run waits on the two-connection pool at each interval. Each run's own deadline is unchanged. - **Behavior change: no recovery signal on renewal.** See below. - During a deploy overlap the old server renews its runs one by one and the new server renews in batches. Both use the same row lock and the same conditions, so they do not conflict. Rows written by the old version have the same columns. - `SKIP LOCKED` sends a busy row to the single path, which waits for the lock as before. - **No recovery signal on renewal:** recovery of a healthy run of another server now runs once for each lease period at the old expiry, not after each renewal. A dead run is found at the same time as before: at the expiry of its last lease. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
387 lines
23 KiB
TypeScript
387 lines
23 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
agents, closeLivenessDb, companies, createDb, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
lockNativeExecutionLeaseForReacquire, nativeExecutionLeaseHeldCondition, renewNativeExecutionLeasesNow,
|
|
renewNativeSessionExecutionLease, startNativeSessionExecutionLeaseRenewal,
|
|
} from "./native-execution-lease.js";
|
|
import { OPERATOR_ATTESTED_CONTROLLER_HOST } from "./native-controller-host-recovery.js";
|
|
import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "./native-runner-ownership.js";
|
|
import {
|
|
getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase,
|
|
} from "../../__tests__/helpers/embedded-postgres.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = support.supported ? describe : describe.skip;
|
|
if (!support.supported) console.warn(`Skipping native lease re-acquire tests: ${support.reason ?? "unsupported environment"}`);
|
|
|
|
const controller = { bootId: `boot-${randomUUID()}`, pid: 4242, processStartedAt: new Date("2026-11-10T05:15:54.000Z") };
|
|
const GENERATION = 1;
|
|
|
|
/**
|
|
* Host sleep (restart-chaos TM2): the owner process is frozen while the wall
|
|
* clock and database clock move on, so its stored lease lapsed although nobody
|
|
* else took it. Each seeded run's lease lapsed 40 minutes ago, untouched.
|
|
*/
|
|
describeEmbeddedPostgres("native execution lease taken back after a host sleep", () => {
|
|
let db!: ReturnType<typeof createDb>;
|
|
let owner!: ReturnType<typeof createDb>;
|
|
let stopDatabase: (() => Promise<void>) | undefined;
|
|
let companyId!: string;
|
|
let agentId!: string;
|
|
|
|
beforeAll(async () => {
|
|
const started = await startEmbeddedPostgresTestDatabase("paperclip-native-lease-reacquire-");
|
|
stopDatabase = started.cleanup;
|
|
db = createDb(started.connectionString);
|
|
owner = createDb(started.connectionString);
|
|
companyId = randomUUID();
|
|
agentId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: "Lease", issuePrefix: "LRA",
|
|
requireBoardApprovalForNewAgents: false });
|
|
await db.insert(agents).values({ id: agentId, companyId, name: "Runner", role: "engineer", status: "active",
|
|
adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, runtimeConfig: {}, permissions: {} });
|
|
}, 120_000);
|
|
|
|
afterEach(() => vi.useRealTimers());
|
|
|
|
afterAll(async () => {
|
|
if (owner) await closeLivenessDb(owner, 1).catch(() => undefined);
|
|
await owner?.$client.end({ timeout: 1 });
|
|
await db?.$client.end({ timeout: 1 });
|
|
await stopDatabase?.();
|
|
});
|
|
|
|
async function seedSleptRun(label: string) {
|
|
const issueId = randomUUID();
|
|
const runId = randomUUID();
|
|
const leaseOwner = `runner-${label}:${randomUUID()}`;
|
|
await db.insert(issues).values({ id: issueId, companyId, identifier: `LRA-${runId.slice(0, 8)}`,
|
|
title: label, status: "in_progress", priority: "medium", workMode: "standard", assigneeAgentId: agentId });
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native",
|
|
nativeIssueId: issueId, invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId } });
|
|
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed", attempt: 1,
|
|
leaseOwner, leaseExpiresAt: sql`clock_timestamp() - interval '40 minutes'`,
|
|
controllerBootId: controller.bootId, controllerPid: controller.pid,
|
|
controllerProcessStartedAt: controller.processStartedAt, controllerHostHash: "host-a",
|
|
controllerGeneration: GENERATION });
|
|
const binding = { runId, companyId, issueId };
|
|
const renewal = { db: owner, ...binding, leaseOwner, attempt: 1, controller,
|
|
reacquire: { controllerGeneration: GENERATION } };
|
|
return { ...binding, leaseOwner, renewal };
|
|
}
|
|
type SleptRun = Awaited<ReturnType<typeof seedSleptRun>>;
|
|
|
|
async function row(runId: string) {
|
|
const [saved] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
|
|
return saved!;
|
|
}
|
|
|
|
it("lets the same owner take back a lease that lapsed untouched", async () => {
|
|
const run = await seedSleptRun("untouched");
|
|
await expect(renewNativeSessionExecutionLease(run.renewal)).resolves.toBeUndefined();
|
|
const saved = await row(run.runId);
|
|
expect(saved.leaseOwner).toBe(run.leaseOwner);
|
|
expect(saved.leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now() + 15 * 60_000);
|
|
});
|
|
|
|
it("renews from the shared timer after the sleep instead of interrupting the turn", async () => {
|
|
const run = await seedSleptRun("timer");
|
|
const onLost = vi.fn(async () => undefined);
|
|
const { reacquire: _reacquire, ...input } = run.renewal;
|
|
const guard = startNativeSessionExecutionLeaseRenewal({ ...input, remote: false,
|
|
controllerGeneration: GENERATION, onLost });
|
|
try {
|
|
// The shared batch finds the lapsed lease and hands it to the single-run
|
|
// path, which takes it back under the run row lock.
|
|
await renewNativeExecutionLeasesNow(owner);
|
|
await vi.waitFor(async () => expect((await row(run.runId)).leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now()));
|
|
expect(onLost).not.toHaveBeenCalled();
|
|
} finally {
|
|
await guard.stop();
|
|
}
|
|
});
|
|
|
|
it("handles rows saved by the previous release: same shape, and never another boot's lease", async () => {
|
|
// Rows saved before the host hash existed carry null there; the rule adds no column.
|
|
const legacyRow = await seedSleptRun("legacy-row");
|
|
await db.update(nativeRunFinalizations).set({ controllerHostHash: null })
|
|
.where(eq(nativeRunFinalizations.runId, legacyRow.runId));
|
|
await expect(renewNativeSessionExecutionLease(legacyRow.renewal)).resolves.toBeUndefined();
|
|
// A deploy that lands mid-run: the lapsed lease belongs to the previous
|
|
// server's boot, so the new process can never take it back as its own.
|
|
const previousServer = await seedSleptRun("previous-boot");
|
|
await expect(renewNativeSessionExecutionLease({ ...previousServer.renewal,
|
|
controller: { ...controller, bootId: `boot-${randomUUID()}`, pid: controller.pid + 1 } }))
|
|
.rejects.toThrow("native_session_lease_lost");
|
|
expect((await row(previousServer.runId)).leaseExpiresAt!.getTime()).toBeLessThan(Date.now());
|
|
});
|
|
|
|
it("still refuses a lapsed lease without the claimed generation, or on a remote target", async () => {
|
|
const run = await seedSleptRun("no-generation");
|
|
const { reacquire: _reacquire, ...legacy } = run.renewal;
|
|
await expect(renewNativeSessionExecutionLease(legacy)).rejects.toThrow("native_session_lease_lost");
|
|
await expect(renewNativeSessionExecutionLease({ ...legacy, reacquire: { controllerGeneration: GENERATION + 1 } }))
|
|
.rejects.toThrow("native_session_lease_lost");
|
|
const onLost = vi.fn(async () => undefined);
|
|
const guard = startNativeSessionExecutionLeaseRenewal({ ...legacy, remote: true,
|
|
controllerGeneration: GENERATION, onLost });
|
|
await renewNativeExecutionLeasesNow(owner);
|
|
await vi.waitFor(() => expect(onLost).toHaveBeenCalled());
|
|
await expect(guard.stop()).rejects.toThrow("native_session_lease_lost");
|
|
expect((await row(run.runId)).leaseExpiresAt!.getTime()).toBeLessThan(Date.now());
|
|
});
|
|
|
|
// Each actor that may act on a lapsed executor lease records that first. The
|
|
// late owner must stay fenced out and must not undo the record.
|
|
const claimants: Array<[string, (run: SleptRun) => Promise<unknown>]> = [
|
|
["restart recovery holds the run for evidence", run => db.update(nativeRunFinalizations)
|
|
.set({ recoveryState: "awaiting_evidence" }).where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["a recovery request was recorded", run => db.update(nativeRunFinalizations)
|
|
.set({ recoveryRequestId: randomUUID() }).where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["the finalizer claimed the row", run => db.update(nativeRunFinalizations)
|
|
.set({ leaseOwner: `native-finalizer:${randomUUID()}`, leaseExpiresAt: sql`clock_timestamp() + interval '5 minutes'` })
|
|
.where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["cleanup claimed the row", run => db.update(nativeRunFinalizations)
|
|
.set({ leaseOwner: `native-cleanup:${randomUUID()}` }).where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["a restarted controller took over", run => db.update(nativeRunFinalizations)
|
|
.set({ controllerBootId: `boot-${randomUUID()}`, controllerGeneration: GENERATION + 1 })
|
|
.where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["the same controller's generation moved on", run => db.update(nativeRunFinalizations)
|
|
.set({ controllerGeneration: GENERATION + 1 }).where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["a new provider attempt was claimed", run => db.update(nativeRunFinalizations)
|
|
.set({ attempt: 2 }).where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["failure settlement recorded a retry", run => db.update(nativeRunFinalizations)
|
|
.set({ phase: "retryable_failure", failureCode: "native_session_lease_lost", nextAttemptAt: new Date() })
|
|
.where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["a retry is scheduled", run => db.update(nativeRunFinalizations)
|
|
.set({ nextAttemptAt: new Date() }).where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["the run was already failed", run => db.update(heartbeatRuns)
|
|
.set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.runId))],
|
|
["the run was cancelled", run => db.update(heartbeatRuns)
|
|
.set({ status: "cancelled", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.runId))],
|
|
["the board confirmed the controller stopped", run => db.update(nativeRunFinalizations)
|
|
.set({ controllerHostHash: OPERATOR_ATTESTED_CONTROLLER_HOST }).where(eq(nativeRunFinalizations.runId, run.runId))],
|
|
["another server's orphan sweep marked ownership unverified", run => db.update(heartbeatRuns)
|
|
.set({ errorCode: NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE, error: "unverified" })
|
|
.where(eq(heartbeatRuns.id, run.runId))],
|
|
["startup cleanup was promoted", run => db.update(heartbeatRuns)
|
|
.set({ resultJson: { nativeStartupCleanup: { state: "pending" } } }).where(eq(heartbeatRuns.id, run.runId))],
|
|
];
|
|
|
|
it.each(claimants)("fences the late owner out when %s first", async (_name, claim) => {
|
|
const run = await seedSleptRun("claimed");
|
|
await claim(run);
|
|
const before = await row(run.runId);
|
|
await expect(renewNativeSessionExecutionLease(run.renewal)).rejects.toThrow("native_session_lease_lost");
|
|
expect(await row(run.runId)).toEqual(before);
|
|
});
|
|
|
|
/** The executor's release and failure settlement use the same lock and held condition. */
|
|
async function releaseAsOwner(run: SleptRun) {
|
|
return owner.transaction(async tx => {
|
|
await lockNativeExecutionLeaseForReacquire(tx, run);
|
|
return tx.update(nativeRunFinalizations).set({ leaseOwner: null, leaseExpiresAt: null })
|
|
.where(and(eq(nativeRunFinalizations.runId, run.runId), eq(nativeRunFinalizations.leaseOwner, run.leaseOwner),
|
|
eq(nativeRunFinalizations.attempt, 1), eq(nativeRunFinalizations.controllerBootId, controller.bootId),
|
|
nativeExecutionLeaseHeldCondition({ remote: false, controllerGeneration: GENERATION, relinquishAccepted: true })))
|
|
.returning({ runId: nativeRunFinalizations.runId });
|
|
});
|
|
}
|
|
|
|
function restartClaimEntry(overrides: Record<string, unknown> = {}) {
|
|
return { at: new Date().toISOString(), restartKind: "hard", controllerBootId: controller.bootId,
|
|
controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt.toISOString(),
|
|
controllerGeneration: GENERATION, disposition: "resume_dead_runner", reason: "dead_runner_with_exact_provider_checkpoint",
|
|
stateRootAction: "reuse_exact_root", recoveryRequestId: null, providerAttempt: 1, ...overrides };
|
|
}
|
|
|
|
async function seedResumedSleptRun(label: string, state = "resuming_session",
|
|
history: Array<Record<string, unknown>> = [restartClaimEntry()], recoveryRequestId: string | null = null) {
|
|
const run = await seedSleptRun(label);
|
|
await db.update(nativeRunFinalizations).set({ recoveryState: state, recoveryRequestId, recoveryHistory: history })
|
|
.where(eq(nativeRunFinalizations.runId, run.runId));
|
|
return run;
|
|
}
|
|
|
|
it.each([
|
|
["a dead Runner resumed", "resuming_session", "resume_dead_runner"],
|
|
["a live Runner reattached", "awaiting_runner_reattach", "reattach_existing_runner"],
|
|
["an incomplete bootstrap restarted", "bootstrap_incomplete", "bootstrap_incomplete"],
|
|
])("takes back a lease held under its own restart claim (%s)", async (_name, state, disposition) => {
|
|
const run = await seedResumedSleptRun(`resumed-${disposition}`, state, [
|
|
restartClaimEntry({ controllerGeneration: GENERATION - 1, controllerBootId: `boot-${randomUUID()}` }),
|
|
restartClaimEntry({ disposition }),
|
|
]);
|
|
await expect(renewNativeSessionExecutionLease(run.renewal)).resolves.toBeUndefined();
|
|
const saved = await row(run.runId);
|
|
expect(saved.leaseOwner).toBe(run.leaseOwner);
|
|
expect(saved.recoveryState).toBe(state);
|
|
expect(saved.leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now() + 15 * 60_000);
|
|
});
|
|
|
|
it("takes back a lease held under a requested restart claim with the same request", async () => {
|
|
const requestId = randomUUID();
|
|
const run = await seedResumedSleptRun("requested", "resuming_session",
|
|
[restartClaimEntry({ recoveryRequestId: requestId })], requestId);
|
|
await expect(renewNativeSessionExecutionLease(run.renewal)).resolves.toBeUndefined();
|
|
});
|
|
|
|
it("lets the owner release its own lapsed lease under its own restart claim", async () => {
|
|
const run = await seedResumedSleptRun("resumed-release");
|
|
expect(await releaseAsOwner(run)).toHaveLength(1);
|
|
});
|
|
|
|
async function settleFailureAsOwner(run: SleptRun) {
|
|
return owner.transaction(async tx => {
|
|
await lockNativeExecutionLeaseForReacquire(tx, { ...run, preResultOnly: true });
|
|
return tx.update(nativeRunFinalizations).set({
|
|
phase: "retryable_failure", leaseOwner: null, leaseExpiresAt: null, recoveryState: "resuming_session",
|
|
failureCode: "native_session_lease_lost", nextAttemptAt: new Date(),
|
|
recoveryHistory: sql`coalesce(${nativeRunFinalizations.recoveryHistory}, '[]'::jsonb)
|
|
|| jsonb_build_array(${JSON.stringify({ disposition: "retryable_failure", reason: "native_session_lease_lost",
|
|
controllerBootId: controller.bootId, controllerGeneration: GENERATION })}::jsonb)`,
|
|
}).where(and(eq(nativeRunFinalizations.runId, run.runId), eq(nativeRunFinalizations.leaseOwner, run.leaseOwner),
|
|
eq(nativeRunFinalizations.attempt, 1), eq(nativeRunFinalizations.controllerGeneration, GENERATION),
|
|
eq(nativeRunFinalizations.controllerBootId, controller.bootId),
|
|
nativeExecutionLeaseHeldCondition({ remote: false, controllerGeneration: GENERATION })))
|
|
.returning({ runId: nativeRunFinalizations.runId });
|
|
});
|
|
}
|
|
|
|
it("lets failure settlement write a resumable failure under its own restart claim", async () => {
|
|
const run = await seedResumedSleptRun("resumed-settle");
|
|
expect(await settleFailureAsOwner(run)).toHaveLength(1);
|
|
const saved = await row(run.runId);
|
|
expect(saved).toMatchObject({ phase: "retryable_failure", leaseOwner: null, recoveryState: "resuming_session",
|
|
failureCode: "native_session_lease_lost" });
|
|
expect((saved.recoveryHistory as Array<{ disposition?: string }>).at(-1)?.disposition).toBe("retryable_failure");
|
|
await expect(renewNativeSessionExecutionLease(run.renewal)).rejects.toThrow("native_session_lease_lost");
|
|
});
|
|
|
|
const restartClaimChanged: Array<[string, () => Promise<SleptRun>]> = [
|
|
["a graceful shutdown suspended the claim", () => seedResumedSleptRun("suspended", "awaiting_runner_reattach",
|
|
[restartClaimEntry({ disposition: "reattach_existing_runner" }),
|
|
{ at: new Date().toISOString(), restartKind: "graceful", disposition: "restart_suspended", reason: "SIGTERM" }])],
|
|
["the claim belongs to an earlier generation", () => seedResumedSleptRun("old-generation", "resuming_session",
|
|
[restartClaimEntry({ controllerGeneration: GENERATION - 1 })])],
|
|
["the claim belongs to another boot", () => seedResumedSleptRun("other-boot", "resuming_session",
|
|
[restartClaimEntry({ controllerBootId: `boot-${randomUUID()}` })])],
|
|
["the state does not match the claimed disposition", () => seedResumedSleptRun("mismatch", "awaiting_runner_reattach",
|
|
[restartClaimEntry()])],
|
|
["recovery now waits for evidence", () => seedResumedSleptRun("evidence", "awaiting_evidence", [restartClaimEntry()])],
|
|
["a later recovery request was recorded", () => seedResumedSleptRun("request", "resuming_session",
|
|
[restartClaimEntry()], randomUUID())],
|
|
["failure settlement appended its outcome", () => seedResumedSleptRun("settled", "resuming_session",
|
|
[restartClaimEntry(), { at: new Date().toISOString(), disposition: "retryable_failure", reason: "native_session_lease_lost",
|
|
controllerBootId: controller.bootId, controllerGeneration: GENERATION }])],
|
|
["no claim was ever recorded", () => seedResumedSleptRun("no-history", "resuming_session", [])],
|
|
];
|
|
|
|
it.each(restartClaimChanged)("stays fenced out when %s", async (_name, seed) => {
|
|
const run = await seed();
|
|
const before = await row(run.runId);
|
|
await expect(renewNativeSessionExecutionLease(run.renewal)).rejects.toThrow("native_session_lease_lost");
|
|
expect(await releaseAsOwner(run)).toHaveLength(0);
|
|
expect(await settleFailureAsOwner(run)).toHaveLength(0);
|
|
expect(await row(run.runId)).toEqual(before);
|
|
});
|
|
|
|
it("releases its own lapsed lease after the result was accepted, but never renews it", async () => {
|
|
const accepted = await seedSleptRun("accepted");
|
|
// Only the coordinator's accepted-result shape matters here; skip the
|
|
// completion-contract foreign keys rather than seed a whole contract.
|
|
const [result] = await db.transaction(async tx => {
|
|
await tx.execute(sql`set local session_replication_role = replica`);
|
|
return tx.insert(nativeRunResults).values({ companyId, issueId: accepted.issueId, runId: accepted.runId,
|
|
completionContractId: randomUUID(), serverFingerprint: randomUUID(), schemaStatus: "accepted", resultJson: {},
|
|
canonicalSha256: "a".repeat(64) }).returning({ id: nativeRunResults.id });
|
|
});
|
|
await db.update(nativeRunFinalizations).set({ phase: "workspace_finalizing", resultId: result!.id })
|
|
.where(eq(nativeRunFinalizations.runId, accepted.runId));
|
|
// Workspace finalization may act on a lapsed post-result lease, so it is never renewed ...
|
|
await expect(renewNativeSessionExecutionLease(accepted.renewal)).rejects.toThrow("native_session_lease_lost");
|
|
// ... only relinquished, which grants nothing.
|
|
expect(await releaseAsOwner(accepted)).toHaveLength(1);
|
|
expect((await row(accepted.runId)).leaseOwner).toBeNull();
|
|
});
|
|
|
|
it("does not release a lapsed lease over a recorded recovery claim", async () => {
|
|
const claimed = await seedSleptRun("release-claimed");
|
|
await db.update(nativeRunFinalizations).set({ recoveryState: "awaiting_runner_reattach" })
|
|
.where(eq(nativeRunFinalizations.runId, claimed.runId));
|
|
expect(await releaseAsOwner(claimed)).toHaveLength(0);
|
|
const saved = await row(claimed.runId);
|
|
expect(saved.recoveryState).toBe("awaiting_runner_reattach");
|
|
expect(saved.leaseOwner).toBe(claimed.leaseOwner);
|
|
});
|
|
|
|
/** A claimant that acts on expiry: lock the coordinator, re-check expiry, record the claim, in one transaction. */
|
|
async function claimIfLapsed(runId: string, holdMs: number) {
|
|
return db.transaction(async tx => {
|
|
const [locked] = await tx.select({ expired: sql<boolean>`${nativeRunFinalizations.leaseExpiresAt} <= clock_timestamp()` })
|
|
.from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)).for("update");
|
|
if (holdMs) await tx.execute(sql`select pg_sleep(${holdMs / 1000})`);
|
|
if (!locked?.expired) return false;
|
|
await tx.update(nativeRunFinalizations).set({ recoveryState: "awaiting_evidence" })
|
|
.where(eq(nativeRunFinalizations.runId, runId));
|
|
return true;
|
|
});
|
|
}
|
|
|
|
/** A run writer that does not take the coordinator lock. */
|
|
async function failRun(runId: string, holdMs: number) {
|
|
return db.transaction(async tx => {
|
|
const [run] = await tx.select({ status: heartbeatRuns.status }).from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId)).for("update");
|
|
await tx.execute(sql`select pg_sleep(${holdMs / 1000})`);
|
|
if (run?.status !== "running") return false;
|
|
await tx.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
|
return true;
|
|
});
|
|
}
|
|
|
|
const renewed = (run: SleptRun) => renewNativeSessionExecutionLease(run.renewal)
|
|
.then(() => true, (error: Error) => { expect(error.message).toBe("native_session_lease_lost"); return false; });
|
|
|
|
it.each([
|
|
["the claimant locks first", 0, 80, false],
|
|
["the owner locks first", 80, 0, true],
|
|
])("lets exactly one side win a race on the coordinator (%s)", async (_name, claimDelayMs, ownerDelayMs, ownerWins) => {
|
|
const run = await seedSleptRun("race");
|
|
const [claimed, ownerWon] = await Promise.all([
|
|
new Promise(resolve => setTimeout(resolve, claimDelayMs)).then(() => claimIfLapsed(run.runId, 300)),
|
|
new Promise(resolve => setTimeout(resolve, ownerDelayMs)).then(() => renewed(run)),
|
|
]);
|
|
expect(ownerWon).toBe(ownerWins);
|
|
expect(claimed).toBe(!ownerWins);
|
|
const saved = await row(run.runId);
|
|
expect(saved.recoveryState).toBe(ownerWins ? null : "awaiting_evidence");
|
|
expect(saved.leaseExpiresAt!.getTime() > Date.now()).toBe(ownerWins);
|
|
});
|
|
|
|
it("waits for an in-flight run status write instead of reading past it", async () => {
|
|
const run = await seedSleptRun("status-race");
|
|
const [failed, ownerWon] = await Promise.all([
|
|
failRun(run.runId, 400),
|
|
new Promise(resolve => setTimeout(resolve, 100)).then(() => renewed(run)),
|
|
]);
|
|
expect(failed).toBe(true);
|
|
expect(ownerWon).toBe(false);
|
|
expect((await row(run.runId)).leaseExpiresAt!.getTime()).toBeLessThan(Date.now());
|
|
});
|
|
|
|
it("has exactly one winner across simultaneous starts", async () => {
|
|
for (let index = 0; index < 8; index++) {
|
|
const run = await seedSleptRun(`burst-${index}`);
|
|
const [claimed, ownerWon] = await Promise.all([claimIfLapsed(run.runId, 0), renewed(run)]);
|
|
expect(Number(claimed) + Number(ownerWon)).toBe(1);
|
|
const saved = await row(run.runId);
|
|
expect(saved.recoveryState === null).toBe(ownerWon);
|
|
}
|
|
});
|
|
});
|