fix: ACP run lifecycle corrections — failure settlement, workspace sync-back, lease cleanup (#11454)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent adapters run ACP sessions and manage runtime, workspace, and
lease resources.
> - Several failure paths left runtime bridges, staged workspaces, or
environment leases active after an error.
> - These leaks reduce run reliability and can leave later runs without
clean resources.
> - This pull request closes the failure paths, applies one teardown
policy, and adds regression tests.
> - The benefit is consistent failure settlement and safer reuse of
agent workspaces and leases.

## Linked Issues or Issue Description

**What happened?**

ACP runs could leave runtime bridges, staged workspaces, or environment
leases active after failures. Claude and Gemini ACP runs did not restore
the sandbox workspace on teardown. Lease release stopped when one lease
returned an error.

**Expected behavior**

Each ACP failure must return an error result and settle its resources.
Teardown must run each step, release leases independently, and restore
the host workspace when the sandbox ends. Pending cleanup leases must
receive bounded retry attempts.

**Steps to reproduce**

1. Run an ACP session that fails after runtime creation or during turn
preparation.
2. Run an ACP session that fails during a warm hit or staged runtime
handoff.
3. Run lease cleanup with more than one lease when the first release
returns an error.
4. Inspect the result phase, teardown calls, workspace state, and lease
metadata.
5. Run the regression suites listed in the Verification section.

## What Changed

- Settle every ACP failure after runtime creation with an error result
and one sandbox.startup span closure.
- Close the ACP runtime and remove warm entries after every pre-turn
failure.
- Run all teardown steps, record teardown errors, release staging leases
in finally, and prevent duplicate teardown.
- Dispose staged runtimes after seam failures and remove borrowed staged
entries with identity guards.
- Add fail-open workspace sync-back teardown for Claude and Gemini ACP
adapters.
- Isolate lease release errors and add bounded retry sweeps for stranded
pending_cleanup leases.
- Atomically claim pending_cleanup retries and clamp attempt readers to
keep the five-attempt bound.
- Default absent provider reusableLeases values to false and align the
fake provider with its runtime declaration.
- Add regression tests for engine, adapter, server, and shared
environment behavior.

## Verification

- [x] `npx vitest run
packages/adapter-utils/src/acpx-engine/execute.test.ts` — 124 tests
passed.
- [x] `npx vitest run
packages/adapters/codex-local/src/server/acp.test.ts
packages/adapters/claude-local/src/server/acp.test.ts
packages/adapters/gemini-local/src/server/acp.test.ts` — 61 tests
passed.
- [x] `npx vitest run server/src/__tests__/environment-runtime.test.ts
server/src/__tests__/heartbeat-pending-cleanup-sweep.test.ts
server/src/__tests__/reusable-leases-default.test.ts
server/src/__tests__/environment-routes.test.ts
packages/shared/src/environment-support.test.ts` — passed.
- [x] All listed suites ran from the repository root.
- [x] GitHub CI completed successfully for
`cfc349c9f232711433897915112a1c52c0e462ca`.
- [x] Greptile completed with a 5/5 confidence score and no blocking
finding.

## Risks

The engine changes affect failure settlement and teardown order across
ACP runs. The server changes add retry state to existing lease metadata
without a schema migration. The adapter changes restore workspaces after
sandbox execution. Regression tests cover the changed paths. GitHub CI
and Greptile passed for the current head.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. This change fixes runtime
reliability and does not duplicate a roadmap feature.

## Model Used

OpenAI GPT-5 Codex. The model used tool-based repository inspection,
GitHub operations, and code review support. The runtime does not expose
a context-window value.

## 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 (for example, `docs/...` or
`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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-08-15 18:52:08 -07:00
1 parent 38752c4e5e
commit e52b8a343f
16 files changed
+3046 -394

No files matched your search

@@ -561,7 +561,11 @@ export function environmentRunOrchestrator(
let releasedLeases: EnvironmentRuntimeLeaseRecord[];
try {
releasedLeases = await environmentRuntime.releaseRunLeases(input.heartbeatRunId, status);
releasedLeases = await environmentRuntime.releaseRunLeases(
input.heartbeatRunId,
status,
(leaseId, error) => result.errors.push({ leaseId, error }),
);
} catch (err) {
result.errors.push({ leaseId: "*", error: err });
return result;
+30 -21
View File
@@ -1968,6 +1968,7 @@ export function environmentRuntimeService(
async releaseRunLeases(
heartbeatRunId: string,
status: Extract<EnvironmentLeaseStatus, "released" | "expired" | "failed"> = "released",
onLeaseReleaseError?: (leaseId: string, error: unknown) => void,
): Promise<EnvironmentRuntimeLeaseRecord[]> {
const leaseRows = await db
.select()
@@ -1982,31 +1983,39 @@ export function environmentRuntimeService(
return [];
}
// Release each lease in its own try/catch. One driver error must not stop
// the release of the later leases. The caller records each lease-specific
// error through `onLeaseReleaseError` for its log path. Keep the order
// serial.
const released: EnvironmentRuntimeLeaseRecord[] = [];
for (const leaseRow of leaseRows) {
const environment = await environmentsSvc.getById(leaseRow.environmentId);
if (!environment) continue;
try {
const environment = await environmentsSvc.getById(leaseRow.environmentId);
if (!environment) continue;
const leaseSnapshot = toEnvironmentLeaseSnapshot(leaseRow);
const driver = getDriver(getLeaseDriverKey(leaseSnapshot, environment));
const lease = driver
? await driver.releaseRunLease({
environment,
lease: leaseSnapshot,
status,
})
: await environmentsSvc.releaseLease(leaseRow.id, status);
if (!lease) continue;
const leaseSnapshot = toEnvironmentLeaseSnapshot(leaseRow);
const driver = getDriver(getLeaseDriverKey(leaseSnapshot, environment));
const lease = driver
? await driver.releaseRunLease({
environment,
lease: leaseSnapshot,
status,
})
: await environmentsSvc.releaseLease(leaseRow.id, status);
if (!lease) continue;
released.push({
environment,
lease,
leaseContext: {
executionWorkspaceId: lease.executionWorkspaceId,
executionWorkspaceMode:
(lease.metadata?.executionWorkspaceMode as ExecutionWorkspace["mode"] | null | undefined) ?? null,
},
});
released.push({
environment,
lease,
leaseContext: {
executionWorkspaceId: lease.executionWorkspaceId,
executionWorkspaceMode:
(lease.metadata?.executionWorkspaceMode as ExecutionWorkspace["mode"] | null | undefined) ?? null,
},
});
} catch (error) {
onLeaseReleaseError?.(leaseRow.id, error);
}
}
return released;
+248
View File
@@ -44,6 +44,7 @@ import {
documentAnnotationComments,
documentAnnotationThreads,
documentRevisions,
environmentLeases,
issueDocuments,
executionWorkspaces,
heartbeatRunEvents,
@@ -356,6 +357,67 @@ const PAPERCLIP_WAKE_PAYLOAD_KEY = "paperclipWake";
const PAPERCLIP_AGENT_MESSAGE_KEY = "paperclipAgentMessage";
const PAPERCLIP_HARNESS_CHECKOUT_KEY = "paperclipHarnessCheckedOut";
const DETACHED_PROCESS_ERROR_CODE = "process_detached";
// The reaper sweeps at most this many pending_cleanup leases per tick.
const PENDING_CLEANUP_SWEEP_PAGE_SIZE = 20;
// The reaper stops retrying a pending_cleanup lease after this many attempts.
const PENDING_CLEANUP_SWEEP_ATTEMPT_CAP = 5;
// The reaper stores its retry state under these keys in the lease metadata.
const PENDING_CLEANUP_ATTEMPTS_METADATA_KEY = "pendingCleanupRetryAttempts";
const PENDING_CLEANUP_CAP_WARNED_METADATA_KEY = "pendingCleanupRetryCapWarned";
// A provider or plugin destroy rejection can carry a bearer credential, a
// signed URL, or provider response detail in its name, code, message, cause, or
// stack. The exception fields cross the server boundary, so they are not a
// trusted enum. The pending_cleanup sweep logs never read the exception. Each
// catch site logs a constant, locally generated `errorKind` instead.
const PENDING_CLEANUP_RETRY_ERROR_KIND = "destroy_failed";
const PENDING_CLEANUP_SWEEP_ERROR_KIND = "sweep_failed";
// Read the stored retry attempt count as a safe value, directly in SQL. A
// provider can write a malformed value under the attempts key. The type guard
// makes any non-number value read as zero. The reader computes as numeric and
// never casts to int, so a finite number outside the 32-bit range (for example
// 1e300) never throws. The reader clamps a negative value to zero and a positive
// value to the attempt cap. One malformed lease therefore never aborts the page
// sweep. This matches the TypeScript reader `readPendingCleanupRetryAttempts`,
// which clamps to the same range. The claim predicate compares the two readers,
// so both must yield the same value for every input.
function pendingCleanupAttemptsSql() {
return sql`
case
when jsonb_typeof(${environmentLeases.metadata} -> ${PENDING_CLEANUP_ATTEMPTS_METADATA_KEY}) = 'number'
then least(
greatest(
floor((${environmentLeases.metadata} ->> ${PENDING_CLEANUP_ATTEMPTS_METADATA_KEY})::numeric),
0
),
${PENDING_CLEANUP_SWEEP_ATTEMPT_CAP}
)
else 0
end`;
}
// Choose the `jsonb_set` target root. A provider can write a scalar or array
// metadata root. `jsonb_set` fails on a non-object root, so the reader uses the
// stored metadata only when its root is an object. A NULL, scalar, or array root
// reads as an empty object. `jsonb_typeof(NULL)` is NULL, so the else branch also
// covers a NULL root.
function pendingCleanupMetadataObjectSql() {
return sql`case when jsonb_typeof(${environmentLeases.metadata}) = 'object' then ${environmentLeases.metadata} else '{}'::jsonb end`;
}
// Read the stored cap-warned flag as a safe boolean, directly in SQL. A
// malformed value reads as false, so the boolean cast never throws.
function pendingCleanupCapWarnedSql() {
return sql`coalesce(
case
when jsonb_typeof(${environmentLeases.metadata} -> ${PENDING_CLEANUP_CAP_WARNED_METADATA_KEY}) = 'boolean'
then (${environmentLeases.metadata} ->> ${PENDING_CLEANUP_CAP_WARNED_METADATA_KEY})::boolean
else false
end,
false
)`;
}
const REPO_ONLY_CWD_SENTINEL = "/__paperclip_repo_only__";
const MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS = 10 * 60 * 1000;
const MAX_INLINE_WAKE_COMMENTS = 8;
@@ -13123,6 +13185,170 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
.then((rows) => rows[0] ?? null);
}
// Clamp the stored attempt count to the range [0, cap]. The SQL reader
// `pendingCleanupAttemptsSql` clamps to the same range, so both readers yield
// the same value for every input. The claim predicate compares the two values,
// so this alignment lets the claim match for a malformed lease.
function readPendingCleanupRetryAttempts(metadata: Record<string, unknown>): number {
const value = metadata[PENDING_CLEANUP_ATTEMPTS_METADATA_KEY];
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return 0;
return Math.min(Math.floor(value), PENDING_CLEANUP_SWEEP_ATTEMPT_CAP);
}
// Atomically claim one retry attempt on a pending_cleanup lease. The update
// only matches when the lease is still pending_cleanup and its stored attempt
// count still equals `expectedAttempts`. Two concurrent sweeps read the same
// count, but Postgres serializes the two updates on the row and only the first
// matches the guard. The loser gets zero rows and skips the lease. This bounds
// the retries to the cap and stops a second destroy of the same lease.
// Returns true only for the sweep that won the claim.
//
// The update writes only the attempts key with `jsonb_set`. It never writes a
// copied metadata object, so a concurrent write to an unrelated metadata key
// survives. The guard reads the stored count through the safe SQL reader, so a
// malformed value never throws.
async function claimPendingCleanupRetryAttempt(
leaseId: string,
expectedAttempts: number,
): Promise<boolean> {
const now = new Date();
const claimed = await db
.update(environmentLeases)
.set({
metadata: sql`jsonb_set(${pendingCleanupMetadataObjectSql()}, array[${PENDING_CLEANUP_ATTEMPTS_METADATA_KEY}], to_jsonb(${expectedAttempts + 1}::int), true)`,
lastUsedAt: now,
updatedAt: now,
})
.where(
and(
eq(environmentLeases.id, leaseId),
eq(environmentLeases.status, "pending_cleanup"),
sql`${pendingCleanupAttemptsSql()} = ${expectedAttempts}`,
),
)
.returning({ id: environmentLeases.id });
return claimed.length > 0;
}
// Atomically claim the one-time cap warning for a lease. The update only
// matches when the lease is still pending_cleanup, its stored attempt count is
// at or above the cap, and it has not yet carried the warned flag. Two
// concurrent sweeps that both reach the cap race here, but only one update
// sets the flag and returns a row. The loser skips the warning. This keeps the
// warning to one log line per lease.
//
// The status and cap predicates are the last line of defense. They stop a warn
// flag write to a lease that left pending_cleanup or dropped below the cap
// between the read and this claim. The update writes only the warned key with
// `jsonb_set`, so a concurrent write to an unrelated metadata key survives.
async function claimPendingCleanupCapWarning(leaseId: string): Promise<boolean> {
const now = new Date();
const claimed = await db
.update(environmentLeases)
.set({
metadata: sql`jsonb_set(${pendingCleanupMetadataObjectSql()}, array[${PENDING_CLEANUP_CAP_WARNED_METADATA_KEY}], to_jsonb(true), true)`,
updatedAt: now,
})
.where(
and(
eq(environmentLeases.id, leaseId),
eq(environmentLeases.status, "pending_cleanup"),
sql`${pendingCleanupAttemptsSql()} >= ${PENDING_CLEANUP_SWEEP_ATTEMPT_CAP}`,
sql`${pendingCleanupCapWarnedSql()} = false`,
),
)
.returning({ id: environmentLeases.id });
return claimed.length > 0;
}
// Retry the leases stranded in "pending_cleanup". A failed destroy leaves a
// lease in that state forever without this sweep. The reaper tick runs the
// sweep. The backoff equals the reaper staleness threshold, so a lease waits
// for that period between attempts. The sweep reads and writes the attempt
// count in the lease metadata. It warns once when a lease reaches the attempt
// cap and then stops the retries for that lease.
async function sweepPendingCleanupLeases(opts?: { backoffMs?: number }): Promise<{
swept: number;
destroyed: number;
capped: number;
}> {
const backoffMs = opts?.backoffMs ?? 0;
const now = new Date();
const cutoff = new Date(now.getTime() - backoffMs);
const rows = await db
.select()
.from(environmentLeases)
.where(
and(
eq(environmentLeases.status, "pending_cleanup"),
backoffMs > 0 ? lte(environmentLeases.updatedAt, cutoff) : undefined,
),
)
.orderBy(asc(environmentLeases.updatedAt))
.limit(PENDING_CLEANUP_SWEEP_PAGE_SIZE);
let destroyed = 0;
let capped = 0;
for (const row of rows) {
const metadata = { ...(row.metadata ?? {}) } as Record<string, unknown>;
const attempts = readPendingCleanupRetryAttempts(metadata);
if (attempts >= PENDING_CLEANUP_SWEEP_ATTEMPT_CAP) {
capped += 1;
// Warn once, then leave the lease for manual cleanup. The atomic claim
// keeps the warning to one log line even when two sweeps overlap.
if (metadata[PENDING_CLEANUP_CAP_WARNED_METADATA_KEY] !== true) {
const warned = await claimPendingCleanupCapWarning(row.id);
if (warned) {
logger.warn(
{ leaseId: row.id, environmentId: row.environmentId, attempts },
"environment lease reached the pending_cleanup retry cap; left for manual cleanup",
);
}
}
continue;
}
const environment = await environmentsSvc.getById(row.environmentId);
const lease = await environmentsSvc.getLeaseById(row.id);
if (!environment || !lease) continue;
// Atomically claim the attempt before the retry. Only the winning sweep
// increments the count and destroys the lease, so an overlapping sweep
// never destroys the same lease twice or exceeds the attempt cap. The
// claim records the attempt before the retry, so a thrown driver error
// still counts against the cap.
const claimed = await claimPendingCleanupRetryAttempt(row.id, attempts);
if (!claimed) continue;
try {
const result = await environmentRuntime.destroyRunLease({
environment,
lease,
failureReason: "pending_cleanup_retry",
});
if (result && result.status !== "pending_cleanup") {
destroyed += 1;
}
} catch {
// Log a constant errorKind only. The exception can carry a credential in
// its name, code, message, cause, or stack, so the sweep never reads it.
logger.warn(
{
errorKind: PENDING_CLEANUP_RETRY_ERROR_KIND,
leaseId: row.id,
environmentId: row.environmentId,
attempts: attempts + 1,
},
"pending_cleanup lease retry failed",
);
}
}
return { swept: rows.length, destroyed, capped };
}
async function reapOrphanedRuns(opts?: { staleThresholdMs?: number }) {
const staleThresholdMs = opts?.staleThresholdMs ?? 0;
const now = new Date();
@@ -13316,6 +13542,27 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
if (reaped.length > 0) {
logger.warn({ reapedCount: reaped.length, runIds: reaped }, "reaped orphaned heartbeat runs");
}
// Retry stranded pending_cleanup leases on the same tick. Isolate the sweep
// so its failure never hides the reaper result. The backoff equals the
// reaper staleness threshold.
try {
const sweep = await sweepPendingCleanupLeases({ backoffMs: staleThresholdMs });
if (sweep.destroyed > 0 || sweep.capped > 0) {
logger.warn(
{ destroyed: sweep.destroyed, capped: sweep.capped, swept: sweep.swept },
"swept pending_cleanup environment leases",
);
}
} catch {
// Log a constant errorKind only. The exception can carry a credential in
// its name, code, message, cause, or stack, so the sweep never reads it.
logger.error(
{ errorKind: PENDING_CLEANUP_SWEEP_ERROR_KIND },
"pending_cleanup lease sweep failed",
);
}
return { reaped: reaped.length, runIds: reaped };
}
@@ -18992,6 +19239,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
prepareHotRestartShutdown,
reconcileHotRestartAdoption,
reapOrphanedRuns,
sweepPendingCleanupLeases,
// Override-aware scheduling-suppression check (honors the worktree
// run-execution experimental setting). Callers outside the service that
// gate on suppression should prefer this over the env-only resolver.