feat(recovery): prove a replaced container's records gone through a fenced controller epoch (#20054)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - After a restart, the control plane settles in-progress records
(leases, claims, intents) only once it proves their owner process is
gone
> - The proof compares host and PID space, so a stamp from a replaced
container or a rebooted machine stays unprovable forever, and its
records never settle
> - Self-hosted users on Docker, Kubernetes and Fly hit this on every
redeploy; a Railway deployment with an exclusive volume is covered by
`deployment_replaced` (#20026)
> - This pull request adds a fenced controller epoch: each boot holds a
database lease, and an expired boot is fenced so its records can be
proven gone
> - The benefit is that work stranded by a replaced container is
recovered, without keeping an idle database awake

## Linked Issues or Issue Description

Follow-up to #20026 and the Phase 2 durable-ownership data. Related:
#19965 (owner stamps), #19883 (process space). No duplicate PR was
found.

**What happened?**

A record stamped by a server process in another container reports
`different_process_space`. A dead PID elsewhere is never proof, so the
record stays `unprovable` and is never settled. Every redeploy of a
self-hosted container leaves such records behind.

**Expected behavior**

A record owned by a server boot that was replaced (stopped cleanly, or
lost its lease and was fenced) is proven gone and settled exactly once.
A live boot's records stay with it. An idle server issues no recurring
queries.

**Steps to reproduce**

1. Run Paperclip in a container and start work, so an environment lease
is stamped by that boot.
2. Replace the container. The new container has a new PID namespace.
3. The ownership reconciler reports `different_process_space`
(unprovable) for the old lease, forever.

**Paperclip version or commit**

`master` before this PR.

## What Changed

- New `controller_instances` table (migration 0449): boot id, epoch
(bigserial), process space, pid, a lease on the database clock,
`fenced_at` / `fenced_by_epoch`, `stopped_at`.
- `controller-instance-lease.ts`, registered with the shared
delivery-work coordinator (`controller-instance-lease` queue, runs
during drain):
- **Holds work → renews; idle → silent.** One upsert creates the row on
first use and extends the lease only if the boot holds work: a stamp
within the last 90 s, or a stamp whose ownership write may still be
pending (held until the server's tracked work settles, capped at 10
minutes; a renewal that sees some other held record does not clear it,
so a slow ownership write cannot be outlived), or an in-progress record
held by its boot id. Those records are active environment leases,
in-flight cleanup claims, sandbox creation intents, workspace finalize
attempts, agent lifecycle steps, native finalizer and cleanup leases
(`lease_holder` bound to the token), open native coordinator claims, and
running legacy runs. Renewal runs every 30 s while the boot holds work.
When it finds none, the lease lapses and the worker sleeps until the
next stamp (`onControllerStamp`).
- **No idle trailing statements.** When the server's last tracked work
settles, the worker re-checks holdings at once, at most every 5 s (the
rate limit also absorbs the worker's own run). So the last check happens
with the work, not 30 s later.
- **Quiesce, don't crash.** Each renewal has a 10 s bound. A failed or
timed-out renewal applies an internal task drain, so no new work is
dispatched. A recovered renewal resumes. The boot exits only after 60 s
of failure (counted from the first failed attempt's start) while it
still holds work, or at once when it finds itself fenced.
- **Fence on demand, by a newer epoch.** For a stamp from another host
or PID space, the prover reads that boot's row:
    - `stopped` or `fenced`: gone.
    - live lease: alive.
- otherwise, the boot's last sign of life is the later of its lease
expiry and the record's last write plus the TTL. Within 30 s of that,
the owner stays `alive` (`controller_lease_grace`), so the settle watch
keeps rechecking. After that, the prover fences the boot, but only with
a lease row of its own (created on demand) and only an older epoch.
  - A graceful shutdown records `stopped_at`.
- A reconciliation pass that settles nothing (`record: false` or
`settle: false`) never fences and never creates the boot's row.
- `owner-proof.ts`: these proofs apply only to server-held records. A
stamp with a recorded process group stays unprovable, because agent
processes can outlive their server. The reconciler passes each record's
`updatedAt` to the proof.
- `task-admission.ts`:
- the quiesce drain never replaces an operator's drain, and has no idle
owner, so HTTP stays open;
- a `subscribeIdleWorkSettled` hook fires when the last tracked work
finishes.
- Off on a Railway deployment with an exclusive volume (it has its own
replacement proof). `PAPERCLIP_CONTROLLER_INSTANCE_LEASE=on|off`
overrides this. A stateless Railway service keeps the lease. A server
without its own lease row never fences.
- `maintenance-server-routes.test.ts`: in the post-run quiet window, the
lease may check once more that the run's records were released. The test
now excludes those statements, then asserts that the lease issues
nothing in a further window.
- Docs: `doc/execution-semantics.md`; the Phase 2 data doc records the
two known gaps.

## Verification

- `controller-instance-lease.test.ts` (15 cases):
- a replaced container with all Railway variables empty is fenced and
settled exactly once over two passes;
  - a live lease is alive;
- an owner in grace, and work written after an idle lapse, stay alive
and watched;
  - an older epoch never fences a newer one;
- no fencing without its own lease row (off or unregistered), and an
idle prover creates its row on demand;
  - a stopped boot is gone;
  - process-group stamps stay unprovable;
- idle issues zero statements, and one upsert renews only while records
are held;
  - **a 45 s outage:** quiesced, no exit, resumes;
- **a renewal that never answers:** bounded, and the boot exits on time;
- **a 70 s outage:** exits at 60–65 s, and the successor recovers the
work exactly once;
  - fenced: stops;
  - the settle re-check;
- graceful stop; off on a volume-exclusive Railway deployment, on for a
stateless one, and the on/off override;
  - a running legacy run keeps the lease live.
- Red, with the proof's instance check removed: the replaced-container,
live, stopped and successor cases fail.
- Wider: task-drain, idle-sleep, idle-local-work, owner-proof and
ownership suites, plus the maintenance quiet-window tests. Server
low-memory typecheck is clean.

## Risks

- **Clock skew.** The proof compares a record's `updatedAt` (often the
writer's clock) with the lease (database clock). The 30 s grace absorbs
ordinary skew.
- **A new exit path exists.** A server whose database is unreachable for
more than 60 s while it holds work now exits, after first quiescing.
This is the intended safety backstop.
- **Bounded trailing activity.** A lease that holds work issues one
statement every 30 s, plus at most one check when its work settles. An
idle server issues none.
- **Boots from before this release** have no row, and their records stay
unprovable. The board "mark owner gone" action for those follows in a
separate PR.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with
tool use.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-08 11:06:32 -06:00
1 parent 0a64c9b4ab
commit e8a3f1f6f2
16 files changed
+6106 -5018

No files matched your search

@@ -0,0 +1,418 @@
import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, companies, controllerInstances, createDb, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import {
controllerInstanceLeaseEnabled, proveControllerInstance, registerControllerInstanceDb, registerControllerInstanceLeaseWork,
resetControllerInstanceLeaseForTests, stopControllerInstanceLease, tickControllerInstanceLease,
} from "../services/controller-instance-lease.js";
import { currentControllerBootId, currentControllerProcessStamp, currentProcessSpaceHash } from "../services/controller-process-identity.js";
import type { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "../services/environment-lease-controller.js";
import { proveOwnerGone, type LocalOwnerStamp } from "../services/owner-proof.js";
import { createOwnershipReportState, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js";
import { beginIdleTrackedWork, readTaskDrain } from "../services/task-admission.js";
const support = await getEmbeddedPostgresTestSupport();
const suite = support.supported ? describe : describe.skip;
suite("controller instance lease: a replaced container's records are provable", () => {
let db!: ReturnType<typeof createDb>;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let companyId = "";
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("paperclip-controller-instance-lease-");
db = createDb(temporary.connectionString);
companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: "CIL", requireBoardApprovalForNewAgents: false });
}, 30_000);
afterEach(async () => {
vi.unstubAllEnvs();
resetControllerInstanceLeaseForTests();
await db.delete(environmentLeases);
await db.delete(controllerInstances);
});
afterAll(async () => { await temporary?.cleanup(); });
const coordinator = { register: () => ({ ready: Promise.resolve(), wake: vi.fn(), stop: async () => {} }) } as unknown as
ReturnType<typeof createDeliveryWorkCoordinator>;
/** A server boot in another container: its own PID space, no platform deployment identity. */
async function otherBoot(lease: { expiredMsAgo?: number; liveForMs?: number; epoch?: number } = {}) {
const bootId = `boot-${randomUUID()}`;
const expires = lease.liveForMs !== undefined ? sql`now() + ${`${lease.liveForMs} milliseconds`}::interval`
: sql`now() - ${`${lease.expiredMsAgo ?? 120_000} milliseconds`}::interval`;
await db.insert(controllerInstances).values({ bootId, processSpace: "old-container", pid: 7, leaseExpiresAt: expires,
...(lease.epoch !== undefined ? { epoch: lease.epoch } : {}) });
return bootId;
}
const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();
const stampOf = (bootId: string, extra: Partial<LocalOwnerStamp> = {}): LocalOwnerStamp => ({
kind: "local", scope: "test", generation: null, host: null, processSpace: "old-container", bootId, pid: 7,
processStartedAt: null, processGroupId: null, touchedAt: minutesAgo(10), ...extra });
/** Registers this boot's lease; a stamp plus one tick creates its row and epoch. */
async function startHere(options: Parameters<typeof registerControllerInstanceLeaseWork>[2] = {}, stamp = true) {
registerControllerInstanceDb(db);
const lost = vi.fn();
registerControllerInstanceLeaseWork(db, coordinator, { onLost: lost, ...options });
if (stamp) { currentControllerProcessStamp(); await tickControllerInstanceLease(); }
const [row] = await db.select().from(controllerInstances).where(eq(controllerInstances.bootId, currentControllerBootId()));
return { lost, epoch: row?.epoch ?? null };
}
it("proves a replaced container's records gone by fencing its boot, with no Railway environment", async () => {
for (const key of ["RAILWAY_PROJECT_ID", "RAILWAY_ENVIRONMENT_ID", "RAILWAY_SERVICE_ID", "RAILWAY_DEPLOYMENT_ID"]) vi.stubEnv(key, "");
expect(controllerInstanceLeaseEnabled()).toBe(true);
const replaced = await otherBoot({ expiredMsAgo: 120_000 });
const another = await otherBoot({ expiredMsAgo: 120_000 });
const { epoch } = await startHere();
expect(await proveOwnerGone(stampOf(replaced))).toEqual({ verdict: "gone", reason: "controller_fenced" });
const [row] = await db.select().from(controllerInstances).where(eq(controllerInstances.bootId, replaced));
expect(row).toMatchObject({ fencedByEpoch: epoch });
const leaseId = randomUUID();
await db.insert(environmentLeases).values({ id: leaseId, companyId, heartbeatRunId: null, status: "active",
leasePolicy: "ephemeral", provider: "fake", providerLeaseId: `sandbox://fake/${leaseId}`, updatedAt: new Date(minutesAgo(10)),
metadata: { [ENVIRONMENT_LEASE_CONTROLLER_KEY]: { bootId: another, pid: 7, hostHash: "old-container", processStartedAt: null } } });
const first = await runOwnershipReconciliationPass(db, { state: createOwnershipReportState() });
expect(first.kinds.find(kind => kind.kind === "environment_login_probe_lease")).toMatchObject({
settled: 1, reasons: { controller_fenced: 1 } });
const second = await runOwnershipReconciliationPass(db, { state: createOwnershipReportState() });
expect(second.kinds.find(kind => kind.kind === "environment_login_probe_lease")).toMatchObject({ settled: 0 });
});
it("treats a live lease as alive", async () => {
const live = await otherBoot({ liveForMs: 60_000 });
registerControllerInstanceDb(db);
expect(await proveOwnerGone(stampOf(live))).toEqual({ verdict: "alive", reason: "controller_lease_held" });
});
it("keeps an owner alive (and watched) through the grace, and for work written after an idle lapse", async () => {
const justExpired = await otherBoot({ expiredMsAgo: 5_000 });
const resumed = await otherBoot({ expiredMsAgo: 600_000 });
await startHere();
expect(await proveOwnerGone(stampOf(justExpired))).toEqual({ verdict: "alive", reason: "controller_lease_grace" });
expect(await proveOwnerGone(stampOf(resumed, { touchedAt: minutesAgo(1) }))).toEqual({ verdict: "alive", reason: "controller_lease_grace" });
expect(await proveOwnerGone(stampOf(resumed, { touchedAt: null }))).toEqual({ verdict: "unprovable", reason: "different_process_space" });
for (const bootId of [justExpired, resumed]) expect(await proveControllerInstance(db, bootId, null)).toBe("expired");
});
it("never lets an older epoch fence a newer one", async () => {
await startHere();
const newer = await otherBoot({ expiredMsAgo: 600_000, epoch: 9_000_000 });
expect(await proveOwnerGone(stampOf(newer))).toEqual({ verdict: "unprovable", reason: "different_process_space" });
expect(await proveControllerInstance(db, newer, null)).toBe("expired");
});
it("never fences without a lease row of its own: off, or not registered", async () => {
const replaced = await otherBoot({ expiredMsAgo: 600_000 });
registerControllerInstanceDb(db);
expect(await proveOwnerGone(stampOf(replaced))).toEqual({ verdict: "unprovable", reason: "different_process_space" });
expect(await proveControllerInstance(db, replaced, null)).toBe("expired");
});
it("an idle prover creates its own row on demand, then fences", async () => {
const replaced = await otherBoot({ expiredMsAgo: 600_000 });
await startHere({}, false);
expect(await db.select().from(controllerInstances).where(eq(controllerInstances.bootId, currentControllerBootId()))).toEqual([]);
expect(await proveOwnerGone(stampOf(replaced))).toEqual({ verdict: "gone", reason: "controller_fenced" });
const [own] = await db.select().from(controllerInstances).where(eq(controllerInstances.bootId, currentControllerBootId()));
const [fenced] = await db.select().from(controllerInstances).where(eq(controllerInstances.bootId, replaced));
expect(fenced?.fencedByEpoch).toBe(own?.epoch);
});
it("never fences on a read-only pass", async () => {
const replaced = await otherBoot({ expiredMsAgo: 600_000 });
await startHere();
const leaseId = randomUUID();
await db.insert(environmentLeases).values({ id: leaseId, companyId, heartbeatRunId: null, status: "active",
leasePolicy: "ephemeral", provider: "fake", providerLeaseId: `sandbox://fake/${leaseId}`, updatedAt: new Date(minutesAgo(15)),
metadata: { [ENVIRONMENT_LEASE_CONTROLLER_KEY]: { bootId: replaced, pid: 7, hostHash: "old-container", processStartedAt: null } } });
const report = await runOwnershipReconciliationPass(db, { state: createOwnershipReportState(), record: false });
expect(report.kinds.find(kind => kind.kind === "environment_login_probe_lease")).toMatchObject({ settled: 0 });
expect(await proveControllerInstance(db, replaced, null)).toBe("expired");
});
it("keeps renewing while this boot holds a native finalizer lease", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date() });
try {
await startHere();
vi.setSystemTime(Date.now() + 120_000);
const holder = { token: "token-1", bootId: currentControllerBootId(), pid: process.pid, hostHash: currentProcessSpaceHash(), processStartedAt: null };
const agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId, name: "Finalizer", adapterType: "codex_local", status: "idle" });
await db.insert(issues).values({ id: issueId, companyId, title: "Native task" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "succeeded", invocationSource: "on_demand", runtimeMode: "native", nativeIssueId: issueId, issueId });
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed",
leaseOwner: "token-1", leaseHolder: holder, leaseExpiresAt: new Date(Date.now() + 300_000) });
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
currentControllerProcessStamp(); vi.setSystemTime(Date.now() + 120_000);
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("live");
await db.delete(nativeRunFinalizations);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(agents);
} finally { vi.useRealTimers(); }
});
it("keeps renewing while this boot runs a legacy run", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date() });
try {
await startHere();
vi.setSystemTime(Date.now() + 120_000);
const agentId = randomUUID(), runId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId, name: "Legacy", adapterType: "codex_local", status: "running" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", invocationSource: "on_demand",
runtimeMode: "legacy", controllerBootId: currentControllerBootId() });
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
currentControllerProcessStamp(); vi.setSystemTime(Date.now() + 120_000);
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("live");
await db.delete(heartbeatRuns);
await db.delete(agents);
} finally { vi.useRealTimers(); }
});
it("proves a cleanly stopped boot gone at once", async () => {
const stopped = await otherBoot({ liveForMs: 60_000 });
await db.update(controllerInstances).set({ stoppedAt: sql`now()` }).where(eq(controllerInstances.bootId, stopped));
registerControllerInstanceDb(db);
expect(await proveOwnerGone(stampOf(stopped))).toEqual({ verdict: "gone", reason: "controller_stopped" });
});
it("keeps a record that names a process group unprovable: agent processes may outlive their server", async () => {
const replaced = await otherBoot();
await startHere();
expect(await proveOwnerGone(stampOf(replaced, { processGroupId: 7 }))).toEqual({ verdict: "unprovable", reason: "different_process_space" });
});
it("issues no statements while idle, and renews in one statement only while it holds stamped work", async () => {
let now = 0;
vi.useFakeTimers({ toFake: ["Date"], now: new Date() });
try {
await startHere({ now: () => now }, false);
await tickControllerInstanceLease();
expect(await db.select().from(controllerInstances)).toEqual([]);
currentControllerProcessStamp();
await tickControllerInstanceLease();
const [created] = await db.select().from(controllerInstances);
expect(created).toMatchObject({ bootId: currentControllerBootId(), processSpace: currentProcessSpaceHash() });
// Past the stamp window, a record stamped with this boot still holds the lease.
now = 120_000;
vi.setSystemTime(Date.now() + 120_000);
const leaseId = randomUUID();
await db.insert(environmentLeases).values({ id: leaseId, companyId, heartbeatRunId: null, status: "active", leasePolicy: "ephemeral",
metadata: { [ENVIRONMENT_LEASE_CONTROLLER_KEY]: { bootId: currentControllerBootId(), pid: process.pid, hostHash: currentProcessSpaceHash(), processStartedAt: null } } });
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
await tickControllerInstanceLease();
expect((await proveControllerInstance(db, currentControllerBootId(), null))).toBe("live");
// Released, and the server's work settled (every stamped write committed): the next renewal
// lets the lease lapse and the worker goes quiet.
await db.delete(environmentLeases);
beginIdleTrackedWork()();
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
await tickControllerInstanceLease();
expect((await proveControllerInstance(db, currentControllerBootId(), null))).toBe("expired");
const renew = vi.fn();
resetControllerInstanceLeaseForTests();
registerControllerInstanceLeaseWork(db, coordinator, { renew });
await tickControllerInstanceLease();
expect(renew).not.toHaveBeenCalled();
} finally { vi.useRealTimers(); }
});
it("re-checks holdings when other work settles, not on its own run's settle, at most every 5 s", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date() });
try {
const wake = vi.fn();
const capturing = { register: () => ({ ready: Promise.resolve(), wake, stop: async () => {} }) } as unknown as
ReturnType<typeof createDeliveryWorkCoordinator>;
registerControllerInstanceDb(db);
registerControllerInstanceLeaseWork(db, capturing, { renew: async () => "holding" as const });
currentControllerProcessStamp();
expect(wake).toHaveBeenCalledTimes(1);
await tickControllerInstanceLease();
beginIdleTrackedWork()();
expect(wake).toHaveBeenCalledTimes(1);
beginIdleTrackedWork()();
expect(wake).toHaveBeenCalledTimes(1);
vi.setSystemTime(Date.now() + 6_000);
beginIdleTrackedWork()();
expect(wake).toHaveBeenCalledTimes(2);
} finally { vi.useRealTimers(); }
});
it("never loses a stamp taken while a renewal is in flight", async () => {
const wake = vi.fn();
const capturing = { register: () => ({ ready: Promise.resolve(), wake, stop: async () => {} }) } as unknown as
ReturnType<typeof createDeliveryWorkCoordinator>;
registerControllerInstanceDb(db);
registerControllerInstanceLeaseWork(db, capturing, { renew: async () => { currentControllerProcessStamp(); return "idle" as const; } });
currentControllerProcessStamp();
wake.mockClear();
await tickControllerInstanceLease();
expect(wake).toHaveBeenCalledTimes(1);
});
it("counts a cleanup claim as held only while its attempt is in flight", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date() });
try {
await startHere();
vi.setSystemTime(Date.now() + 60_000);
const leaseId = randomUUID();
const claim = { bootId: currentControllerBootId(), pid: process.pid, hostHash: currentProcessSpaceHash(), processStartedAt: null };
await db.insert(environmentLeases).values({ id: leaseId, companyId, heartbeatRunId: null, status: "pending_cleanup", leasePolicy: "ephemeral",
metadata: { pendingCleanupController: claim, pendingCleanupInFlight: false } });
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
// A stamp whose record no renewal saw holds the lease until the 10-minute cap.
currentControllerProcessStamp(); vi.setSystemTime(Date.now() + 120_000);
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("live");
vi.setSystemTime(Date.now() + 11 * 60_000);
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("expired");
await db.update(environmentLeases).set({ metadata: { pendingCleanupController: claim, pendingCleanupInFlight: true } });
currentControllerProcessStamp(); vi.setSystemTime(Date.now() + 120_000);
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("live");
} finally { vi.useRealTimers(); }
});
it("holds an unobserved stamp only until the server's work settles", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date() });
try {
await startHere();
vi.setSystemTime(Date.now() + 120_000);
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("live");
beginIdleTrackedWork()();
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("expired");
} finally { vi.useRealTimers(); }
});
it("keeps a pending stamped write held when a renewal sees another held record", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: new Date() });
try {
await startHere();
const agentId = randomUUID(), runId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId, name: "Legacy", adapterType: "codex_local", status: "running" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", invocationSource: "on_demand",
runtimeMode: "legacy", controllerBootId: currentControllerBootId() });
// A second stamp whose ownership write has not committed yet.
currentControllerProcessStamp();
await tickControllerInstanceLease();
// The other record finishes; the pending write is still uncommitted past the stamp window.
await db.delete(heartbeatRuns);
await db.delete(agents);
vi.setSystemTime(Date.now() + 120_000);
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("live");
beginIdleTrackedWork()();
await db.update(controllerInstances).set({ leaseExpiresAt: sql`now()` });
await tickControllerInstanceLease();
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("expired");
} finally { vi.useRealTimers(); }
});
it("rides out a 45 s database outage: quiesces dispatch, never exits, and resumes", async () => {
let now = 0, down = true;
const renew = vi.fn(async () => { if (down) throw new Error("connection refused"); return "holding" as const; });
const { lost } = await startHere({ now: () => now, renew }, false);
currentControllerProcessStamp();
for (now = 0; now <= 45_000; now += 5_000) {
await tickControllerInstanceLease();
expect(readTaskDrain(new Date())).not.toBeNull();
}
down = false;
await tickControllerInstanceLease();
expect(lost).not.toHaveBeenCalled();
expect(readTaskDrain(new Date())).toBeNull();
});
it("bounds a renewal that never answers, counting from the attempt's start", async () => {
let now = 0;
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
const { lost } = await startHere({ now: () => now, renew: () => new Promise(() => {}) }, false);
currentControllerProcessStamp();
const attempt = tickControllerInstanceLease();
now = 10_000;
await vi.advanceTimersByTimeAsync(10_000);
await attempt;
expect(readTaskDrain(new Date())).not.toBeNull();
for (now = 15_000; now <= 60_000; now += 5_000) {
const next = tickControllerInstanceLease();
await vi.advanceTimersByTimeAsync(10_000);
await next;
}
expect(lost).toHaveBeenCalledWith("lease_lost");
} finally { vi.useRealTimers(); }
});
it("stops after a 70 s outage while holding work, and the successor recovers its work exactly once", async () => {
let now = 0;
const { lost } = await startHere({ now: () => now, renew: async () => { throw new Error("down"); } }, false);
currentControllerProcessStamp();
for (now = 0; now <= 70_000 && !lost.mock.calls.length; now += 5_000) await tickControllerInstanceLease();
expect(lost).toHaveBeenCalledWith("lease_lost");
expect(now).toBeGreaterThanOrEqual(60_000);
expect(now).toBeLessThanOrEqual(70_000);
// The stopped boot as its successor sees it: lease expired long ago, work last written under it.
resetControllerInstanceLeaseForTests();
await db.insert(controllerInstances).values({ bootId: "exited-boot", processSpace: "old-container", pid: 7,
leaseExpiresAt: sql`now() - interval '3 minutes'`, epoch: 1 });
await startHere();
const leaseId = randomUUID();
await db.insert(environmentLeases).values({ id: leaseId, companyId, heartbeatRunId: null, status: "active",
leasePolicy: "ephemeral", provider: "fake", providerLeaseId: `sandbox://fake/${leaseId}`, updatedAt: new Date(minutesAgo(5)),
metadata: { [ENVIRONMENT_LEASE_CONTROLLER_KEY]: { bootId: "exited-boot", pid: 7, hostHash: "old-container", processStartedAt: null } } });
const passes = [];
for (let pass = 0; pass < 2; pass += 1) {
const report = await runOwnershipReconciliationPass(db, { state: createOwnershipReportState() });
passes.push(report.kinds.find(kind => kind.kind === "environment_login_probe_lease")?.settled);
}
expect(passes).toEqual([1, 0]);
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]).toMatchObject({ status: "pending_cleanup" });
});
it("stops at once when a newer boot fenced it", async () => {
const { lost } = await startHere();
await db.update(controllerInstances).set({ fencedAt: sql`now()` }).where(eq(controllerInstances.bootId, currentControllerBootId()));
currentControllerProcessStamp();
await tickControllerInstanceLease();
expect(lost).toHaveBeenCalledWith("fenced");
});
it("records a graceful stop, and is off on a volume-exclusive Railway deployment or when disabled", async () => {
await startHere();
await stopControllerInstanceLease(db);
expect(await proveControllerInstance(db, currentControllerBootId(), null)).toBe("stopped");
vi.stubEnv("PAPERCLIP_CONTROLLER_INSTANCE_LEASE", "off");
expect(controllerInstanceLeaseEnabled()).toBe(false);
vi.unstubAllEnvs();
for (const [key, value] of [["RAILWAY_PROJECT_ID", "p"], ["RAILWAY_ENVIRONMENT_ID", "e"], ["RAILWAY_SERVICE_ID", "s"], ["RAILWAY_DEPLOYMENT_ID", "d"]]) {
vi.stubEnv(key!, value!);
}
// A stateless Railway service has no deployment-replacement proof, so it keeps the lease.
expect(controllerInstanceLeaseEnabled()).toBe(true);
vi.stubEnv("RAILWAY_VOLUME_ID", "v");
vi.stubEnv("RAILWAY_VOLUME_MOUNT_PATH", "/data");
expect(controllerInstanceLeaseEnabled()).toBe(false);
vi.stubEnv("PAPERCLIP_CONTROLLER_INSTANCE_LEASE", "on");
expect(controllerInstanceLeaseEnabled()).toBe(true);
vi.unstubAllEnvs();
});
});