mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 09:05:15 +01:00
<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before it asks a provider to create a sandbox, the server writes a creation intent that names its creator process > - If the creator dies during the provider call, the intent waits for a 30-minute settle deadline before recovery reconciles it with the provider > - After a restart, creation recovery made such intents due early with its own process check (`promoteAbandonedSandboxCreations`) > - Phase 2 of the durable ownership plan moves each in-progress record kind onto one shared owner proof and deletes its bespoke check > - This pull request registers a settle for `sandbox_creation_intent` and calls the shared path where creation recovery called the bespoke promotion > - The benefit is one proof for every kind, while the provider absence proof and the cross-host handoff stay unchanged ## Linked Issues or Issue Description Refs #19964 Refs #19933 **What happened?** Sandbox creation recovery had its own liveness check (`controllerProcessExited`) for the creator of a pending intent. Each kind with its own check can drift from the shared rules (PID space, PID reuse, current boot, deployment replacement). **Expected behavior** The shared prover judges the creator. On gone, the intent becomes due now and its creator is marked lost. Provider absence stays inconclusive until the settle deadline. A creator on another host is never proven gone; its intent keeps the deadline. **Steps to reproduce** 1. Start a sandbox acquire so a creation intent is written. 2. Kill the server before the provider reply is committed. 3. Restart. The intent must become due through the shared ownership path, not a separate check. ## What Changed - `sandbox-creation-intent-settlement.ts` (new): compare-and-swap settle on the exact creator and a deadline that is still in the future. It sets `nextAttemptAt` to now, marks `creationControllerLost` with the proof reason, and wakes creation recovery in the same transaction. - `recovery/ownership-registry.ts`: `sandbox_creation_intent` registers the settle. An intent whose creator is already lost is no longer listed; it belongs to the creation recovery deadline. - `sandbox-creation-operations.ts`: creation recovery calls `settleOwnableKind(db, "sandbox_creation_intent")`. Deleted `promoteAbandonedSandboxCreations` and its use of `controllerProcessExited`. ## Verification - `cd server && npx vitest run src/__tests__/sandbox-creation-intent-ownership.test.ts src/__tests__/sandbox-creation-operations.test.ts src/__tests__/ownership-reconciliation-report.test.ts` (embedded Postgres). - The existing lost-creator matrix stays green on the shared path: destroy on the next sweep; page past unprovable creators; issue-bound creation after a later run; reused PID; live creator here; live creator in another process; creator on another host; early lookup finds nothing yet (absence inconclusive); committed lease untouched. - New, red on master and green here (written after the code): the reconciler pass makes a dead creator's intent due now and keeps the absence deadline. - New counter-cases (green): live creator, another host, and an intent without a creator keep their deadline; a read-only pass changes nothing. - Full typecheck is left to CI (local memory limit). ## Risks - Low risk. The settle writes the same state the deleted promotion wrote, plus the proof reason. - Previous-release rows: every creation intent already stored its creator with a PID space, so no fallback is needed. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edit, embedded Postgres tests). ## 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>
136 lines
7.1 KiB
TypeScript
136 lines
7.1 KiB
TypeScript
import { spawn } from "node:child_process";
|
|
import { randomUUID } from "node:crypto";
|
|
import { eq } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
import { companies, createDb, sandboxCreationOperations } from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { currentControllerProcessStamp, currentProcessSpaceHash } from "../services/controller-process-identity.js";
|
|
import { nextEnvironmentCleanupAt } from "../services/environment-cleanup-state.js";
|
|
import { createOwnershipReportState, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js";
|
|
import { settleSandboxCreationIntent } from "../services/sandbox-creation-intent-settlement.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
const suite = support.supported ? describe : describe.skip;
|
|
const KIND = "sandbox_creation_intent";
|
|
|
|
async function exitedPid(): Promise<number> {
|
|
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
|
const pid = child.pid!;
|
|
await new Promise<void>(resolve => { child.once("exit", () => resolve()); child.kill("SIGKILL"); });
|
|
return pid;
|
|
}
|
|
|
|
suite("sandbox_creation_intent on the shared ownership path", () => {
|
|
let db!: ReturnType<typeof createDb>;
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
|
let companyId = "";
|
|
|
|
beforeAll(async () => {
|
|
temporary = await startEmbeddedPostgresTestDatabase("paperclip-sandbox-creation-intent-ownership-");
|
|
db = createDb(temporary.connectionString);
|
|
companyId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: "SCI",
|
|
requireBoardApprovalForNewAgents: false });
|
|
}, 30_000);
|
|
|
|
afterEach(async () => {
|
|
await db.delete(sandboxCreationOperations);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await temporary?.cleanup();
|
|
});
|
|
|
|
/** The state a crash between the intent write and the provider reply leaves:
|
|
* a pending intent waiting for its 30-minute settle deadline. */
|
|
async function intent(creationController: Record<string, unknown>) {
|
|
const id = randomUUID();
|
|
const settleAt = new Date(Date.now() + 30 * 60_000);
|
|
await db.insert(sandboxCreationOperations).values({ id, companyId, originalEnvironmentId: randomUUID(),
|
|
runId: randomUUID(), requestKey: "run", provider: "fixture", driverKey: "fixture", state: "pending", config: {},
|
|
nextAttemptAt: settleAt, metadata: { creationController, creationSettleAt: settleAt.toISOString() } });
|
|
return id;
|
|
}
|
|
|
|
async function row(id: string) {
|
|
const [found] = await db.select().from(sandboxCreationOperations).where(eq(sandboxCreationOperations.id, id));
|
|
return found!;
|
|
}
|
|
|
|
async function pass(record = true) {
|
|
const report = await runOwnershipReconciliationPass(db, { state: createOwnershipReportState(), record });
|
|
return report.kinds.find(entry => entry.kind === KIND)!;
|
|
}
|
|
|
|
it("makes a dead creator's intent due on the next pass, keeping the provider absence deadline", async () => {
|
|
const id = await intent({ bootId: "earlier-boot", pid: await exitedPid(), hostHash: currentProcessSpaceHash(),
|
|
processStartedAt: null });
|
|
expect(await pass()).toMatchObject({ settled: 1, reasons: { pid_dead: 1 } });
|
|
const settled = await row(id);
|
|
expect(settled.state).toBe("pending");
|
|
expect(settled.nextAttemptAt.getTime()).toBeLessThanOrEqual(Date.now());
|
|
expect(settled.metadata).toMatchObject({ creationControllerLost: true, creationControllerLostProof: "pid_dead" });
|
|
// Creation recovery is due now; the saved settle deadline still guards absence.
|
|
expect(await nextEnvironmentCleanupAt(db)).toBeLessThanOrEqual(Date.now());
|
|
expect(Date.parse(String(settled.metadata.creationSettleAt))).toBeGreaterThan(Date.now() + 25 * 60_000);
|
|
// A lost creator's intent belongs to creation recovery now.
|
|
expect(await pass()).toMatchObject({ inProgress: 0 });
|
|
});
|
|
|
|
it("keeps the deadline of a live creator, a creator on another host, and an intent with no creator", async () => {
|
|
const ids = [
|
|
await intent(currentControllerProcessStamp()),
|
|
await intent({ bootId: "other", pid: await exitedPid(), hostHash: "f".repeat(32), processStartedAt: null }),
|
|
await intent({}),
|
|
];
|
|
const before = await Promise.all(ids.map(row));
|
|
expect(await pass()).toMatchObject({ settled: 0,
|
|
reasons: { current_process: 1, different_process_space: 1, no_owner_stamp: 1 } });
|
|
expect(await Promise.all(ids.map(row))).toEqual(before);
|
|
});
|
|
|
|
describe("the settle compares and swaps on the exact creator it was given", () => {
|
|
async function record(id: string, creator: Record<string, unknown>) {
|
|
return { recordId: id, companyId, runId: null, issueId: null, updatedAt: new Date(),
|
|
owner: { kind: "process" as const, stamp: { kind: "local" as const, scope: KIND, generation: null, host: null,
|
|
processSpace: String(creator.hostHash), bootId: String(creator.bootId), pid: Number(creator.pid),
|
|
processStartedAt: null, processGroupId: null } } };
|
|
}
|
|
const proof = { verdict: "gone" as const, reason: "pid_dead" as const };
|
|
|
|
it.each([
|
|
["a creator that changed since the proof", "owner_changed_since_proof"],
|
|
["an intent already due", "intent_already_due"],
|
|
["an intent no longer pending", "intent_no_longer_pending"],
|
|
["an intent whose creator is already lost", "creator_already_lost"],
|
|
] as const)("leaves %s unchanged", async (label, reason) => {
|
|
const creator = { bootId: "earlier-boot", pid: await exitedPid(), hostHash: currentProcessSpaceHash(), processStartedAt: null };
|
|
const id = await intent(creator);
|
|
if (label.startsWith("a creator")) {
|
|
await db.update(sandboxCreationOperations).set({ metadata: { creationController: { ...creator, bootId: "newer-boot" } } })
|
|
.where(eq(sandboxCreationOperations.id, id));
|
|
} else if (label.includes("already due")) {
|
|
await db.update(sandboxCreationOperations).set({ nextAttemptAt: new Date(Date.now() - 1_000) })
|
|
.where(eq(sandboxCreationOperations.id, id));
|
|
} else if (label.includes("no longer pending")) {
|
|
await db.update(sandboxCreationOperations).set({ state: "cleanup_pending" }).where(eq(sandboxCreationOperations.id, id));
|
|
} else {
|
|
await db.update(sandboxCreationOperations).set({ metadata: { creationController: creator, creationControllerLost: true } })
|
|
.where(eq(sandboxCreationOperations.id, id));
|
|
}
|
|
const before = await row(id);
|
|
expect(await settleSandboxCreationIntent(db, await record(id, creator), { now: new Date(), proof }))
|
|
.toEqual({ settled: false, reason });
|
|
expect(await row(id)).toEqual(before);
|
|
});
|
|
});
|
|
|
|
it("never changes an intent on a read-only pass", async () => {
|
|
const id = await intent({ bootId: "earlier-boot", pid: await exitedPid(), hostHash: currentProcessSpaceHash(),
|
|
processStartedAt: null });
|
|
const before = await row(id);
|
|
expect(await pass(false)).toMatchObject({ settled: 0, verdicts: { gone: 1 } });
|
|
expect(await row(id)).toEqual(before);
|
|
});
|
|
});
|