Files
PaperClipAI/server/src/services/sandbox-creation-intent-settlement.ts
T
DottaandClaude Opus 5.5 838e9bf3d2 feat(recovery): settle sandbox creation intents of dead creators on the shared ownership path (#19978)
<!-- 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>
2026-11-08 01:07:58 -06:00

56 lines
3.6 KiB
TypeScript

import { and, eq, gt, sql } from "drizzle-orm";
import { sandboxCreationOperations, type Db } from "@paperclipai/db";
import { readControllerProcess } from "./controller-process-identity.js";
import { notifyEnvironmentCleanup } from "./environment-cleanup-notifications.js";
import type { OwnerProof } from "./owner-proof.js";
import type { InProgressRecord, SettleOutcome } from "./recovery/ownership-registry.js";
/**
* Settle of the `sandbox_creation_intent` ownership kind (plan Phase 2).
*
* A creation intent is written before the provider call and names the server
* process that makes it. While that process lives, the intent waits for its
* settle deadline. Once the shared prover proves the creator gone, it cannot
* still be waiting for the provider, so this settle makes the intent due now
* and marks the creator lost; the creation recovery worker then reconciles it.
*
* It settles ownership only. Whether the sandbox exists is still decided by
* the provider: absence stays inconclusive until the creation settle deadline
* (`creationAbsenceInconclusive`), and an unidentifiable creation becomes an
* operator reconciliation. A creator on another host is never proven gone by
* a process proof; its intent keeps the deadline, which is the handoff.
*
* The update compares and swaps on the exact creator the proof judged and
* only moves a deadline that is still in the future.
*/
export async function settleSandboxCreationIntent(db: Db, record: InProgressRecord,
context: { now: Date; proof: OwnerProof }): Promise<SettleOutcome> {
if (record.owner.kind !== "process") return { settled: false, reason: "owner_not_a_process" };
const stamp = record.owner.stamp;
const now = context.now;
return db.transaction(async transaction => {
const tx = transaction as unknown as Db;
const [operation] = await tx.select().from(sandboxCreationOperations)
.where(and(eq(sandboxCreationOperations.id, record.recordId), eq(sandboxCreationOperations.state, "pending")))
.for("update");
if (!operation) return { settled: false, reason: "intent_no_longer_pending" };
if (operation.metadata.creationControllerLost === true) return { settled: false, reason: "creator_already_lost" };
const creator = readControllerProcess(operation.metadata.creationController);
if (!creator || creator.bootId !== stamp.bootId || creator.pid !== stamp.pid || creator.hostHash !== stamp.processSpace) {
return { settled: false, reason: "owner_changed_since_proof" };
}
if (operation.nextAttemptAt <= now) return { settled: false, reason: "intent_already_due" };
// Wake creation recovery before the write it announces.
await notifyEnvironmentCleanup(tx, { companyId: operation.companyId, runId: operation.runId });
const updated = await tx.update(sandboxCreationOperations).set({ nextAttemptAt: now, updatedAt: now,
metadata: sql`coalesce(${sandboxCreationOperations.metadata}, '{}'::jsonb) || ${JSON.stringify({
creationControllerLost: true, creationControllerLostProof: context.proof.reason })}::jsonb` })
.where(and(eq(sandboxCreationOperations.id, operation.id), eq(sandboxCreationOperations.state, "pending"),
gt(sandboxCreationOperations.nextAttemptAt, now),
sql`coalesce(${sandboxCreationOperations.metadata}->>'creationControllerLost', '') <> 'true'`,
sql`${sandboxCreationOperations.metadata}->'creationController' = ${JSON.stringify(operation.metadata.creationController)}::jsonb`))
.returning({ id: sandboxCreationOperations.id });
return updated.length ? { settled: true, reason: context.proof.reason } : { settled: false, reason: "intent_no_longer_pending" };
});
}