mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents in a `sandbox` environment run each task in a paid remote
sandbox that an environment lease tracks
> - When a run stops, the control plane must release that lease, and
terminating an agent waits until every lease of the agent is released
> - In a load test, a run stopped after its sandbox was ready but before
its runner started never released its lease, so the sandbox kept running
and the agent stayed in "terminating" forever
> - In the same test, terminating an agent whose failed run had a
scheduled same-run retry waited about 18 minutes, until the stale retry
time
> - This pull request makes lease release finish for every stop window,
records any release that must wait with a retry time, adds a hint-driven
safety net, and makes termination cancel a pending native retry at once
> - The benefit is that a stopped run never leaves a paid sandbox
running, and agent termination finishes in seconds without manual repair
## Linked Issues or Issue Description
**What happened?**
A load test with ten OpenCode agents in a `sandbox` environment stopped
its agents mid-run (pause, then terminate). Two defects appeared.
1. A run cancelled while it selected its provider pack (after the
sandbox was acquired and the workspace was prepared, before the runner
started) kept its environment lease `active` for more than 40 minutes.
The agent stayed in lifecycle `terminating`. The lifecycle worker
retried every pass and wrote `updatedAt` each time with no recorded
reason. Delete returned 409 "Complete termination before deleting the
agent".
2. A failed native run with a scheduled bootstrap retry kept its lease
until the stale retry time. Agent termination took about 18 minutes. The
run still showed "retry_scheduled" after the agent was terminated.
**Expected behavior**
A stopped run releases its sandbox lease within seconds. If release must
wait, the wait has a recorded reason and retry time, and a background
pass finishes it. Terminating an agent cancels a pending retry, releases
its lease, and reaches `terminated` promptly.
**Steps to reproduce**
1. Start a native run in a `sandbox` environment.
2. Stop it after the sandbox is acquired and the workspace is prepared,
before the runner starts.
3. Pause and then terminate the agent.
4. See that the lease stays `active` and the agent stays `terminating`.
**Paperclip version or commit**
Reproduced on `master` at 62033b9994 (load test build 2026.1106.0+2564).
**Relevant logs or output**
Root causes found in the code:
- `releaseEnvironmentLeasesForRun` returned with no record when
workspace retention refused a cancelled run. The refusal was permanent
when the run's native finalization owner had expired but was not
cleared. The owner is cleared only after `agentExecutionsHaveStopped`
sees every lease released, so the two waited on each other.
- `releaseRunLeases` silently skipped a lease whose prepared native
workspace was still "pending export", even for a run that never started
a runner and so never changed those files.
- The destroy path deferred on any busy warm session in the same
environment, also with no record.
- `stopInvocationsForAgents` returned on the first run that was still
live, so it did not release the leases of the other runs of the agent.
- The agent stop cancelled only `queued`, `running` and
`scheduled_retry` runs. A failed native run with a pending same-run
retry kept its lease until that retry fired.
- The lifecycle worker deferred a pending host step by 2 seconds every
pass, with no reason and no backoff.
## What Changed
- `releaseEnvironmentLeasesForRun` (`run-control.ts`):
- A native run with no runner launch evidence (no
`native.process_start_requested`, no runner event, no process id) skips
workspace retention and warm-session closing. No runner process exists
to fence, and no work ran against the prepared files.
- When retention is refused only because the run's native finalization
owner lease has expired, the release clears that expired owner
(compare-and-set on the exact expired owner of a cancelled run with no
result) and retries retention once. A recorded recovery then stops and
retains the sandbox, so the files stay recoverable.
- Every release that cannot finish now records
`metadata.releaseDeferral` (`reason`, `attempts`, `retryAt`,
disposition) on the active lease and publishes an `orphan-active-leases`
hint. The retry time backs off from 30 seconds to 15 minutes, then
retries hourly without end. The record keeps `failingSince` and the last
reason. A new Stop or terminate operation, or a server restart, triggers
an immediate attempt.
- `nativeWorkspaceExportPendingForLease` treats a cancelled run with no
runner launch evidence as owing no export.
- Safety net: `sweepOrphanedActiveLeases` (the existing hint- and
deadline-driven orphan-lease work) now retries the run's own release for
a due deferral or for a cancelled native run, after the native owner
lease has expired. The orphan-lease loader uses the stored `retryAt` as
the due time. No new timer or poller.
- Agent stop:
- It cancels a failed native run that has a pending same-run retry (or
an interrupted cancellation of one), through the existing
retry-cancellation path. A pause stamps `pauseStop` on those runs too,
so a budget resume can continue them.
- It releases the leases of every terminal run, and it skips a lease
whose deferral is not yet due.
- `agentInvocationStopBlocker` and `agentExecutionStopBlocker` return
why the stop must still wait.
- Lifecycle worker: a pending host or plugin step records
`pendingReason` and `pendingPasses` on the operation, and its retry
backs off from 2 seconds to a 60 second cap. When a release leaves a run
with no unsettled lease, the stopping agent's saved retry time is
cleared and the lifecycle queue is notified, so Pause or Terminate
finishes on the next pass.
- Cancelled-workspace preservation: a stopped run that never started a
runner has its prepared reference moved to
`nativeWorkspaceSyncReleasedUnchanged` when its lease is released, so
the preservation worker no longer selects it. The worker records the
same settlement itself for older runs, and waits on a live owner's exact
lease expiry.
## Verification
- Red on `master`, green on this branch (embedded PostgreSQL, fake
plugin sandbox provider):
-
`server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts`:
agent pause then terminate, and board Stop, for each window between
sandbox acquire and runner attach (artifact discovery, pack select, pack
upload, runner launch, transport connect, session open). Each test
checks that the provider gets a stop or destroy call, the lease is
released, the run is cancelled, and the agent reaches `terminated`
within one extra worker pass. It also checks the orphan-lease safety net
for a leaked lease and a recorded deferral that the background pass
finishes when due.
-
`server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts`:
terminating an agent whose failed run has a bootstrap retry 17 minutes
away cancels the retry, releases the lease and reaches `terminated` at
once. The test covers an open task and a cancelled task.
-
`server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts`:
a host step that stays pending records its reason, and its retry delay
grows to a 60 second cap.
- Related suites pass: run-control, recovery, orphaned active lease
sweep, environment runtime, agent lifecycle, native workspace
preservation and recovery, held comment wake.
- `server` typecheck passes.
## Risks
- A cancelled native run with no launch evidence now gets its prepared
sandbox destroyed instead of kept. The proof is the same launch evidence
that restart recovery uses.
- A launched cancelled run whose retention owes nothing is stopped and
retained, as before. A retention that throws (lock or write error, or a
live owner) now keeps the lease active with a recorded reason and retry
time, instead of a silent skip.
- Release now clears an expired native finalization owner of a cancelled
run. An old controller whose lease already expired then fails its next
owner check and stops, which is the normal lease rule.
- On the first start after deploy, the orphan-lease work releases leases
already leaked by cancelled native runs.
- Task state after pause then terminate: the run-scoped stop keeps the
task status (an open task stays open, a cancelled task stays cancelled),
and a run that held prepared files gets the existing workspace recovery
record on its stopped sandbox. No new state is added.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (code search, shell, test runs).
## 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
- [ ] 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>
130 lines
7.0 KiB
TypeScript
130 lines
7.0 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import type { LifecycleDriver, LifecycleStore, LifecycleFailure } from "./ports.js";
|
|
import { isLifecycleWorkPending } from "../domain/policy.js";
|
|
import { lifecycleFailureCode, lifecycleFailureMessage, lifecycleVerificationNeedsRetry } from "./failure.js";
|
|
|
|
/** Database leases protect each attempt across server processes. */
|
|
export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDriver, reportFailure: (context: LifecycleFailure, error: unknown) => void, canRun = () => true) {
|
|
let stopped = false;
|
|
const active = new Map<string, Promise<void>>();
|
|
let running: Promise<void> | undefined;
|
|
|
|
async function attempt<T>(context: LifecycleFailure, work: () => Promise<T>): Promise<T> {
|
|
try { return await work(); }
|
|
catch (error) { reportFailure(context, error); throw error; }
|
|
}
|
|
|
|
async function process(id: string) {
|
|
phase: for (let step = 0; !stopped && canRun() && step < 8; step++) {
|
|
const owner = randomUUID();
|
|
const agent = await attempt({ stage: "claim", agentId: id }, () => store.claim(id, owner, new Date()));
|
|
if (!agent || !isLifecycleWorkPending(agent.lifecycleState)) return;
|
|
const context = { agentId: agent.id, companyId: agent.companyId, phase: agent.lifecycleState,
|
|
operationId: agent.lifecycleOperation?.id, version: agent.lifecycleVersion,
|
|
attempts: agent.lifecycleOperation?.attempts };
|
|
let failureContext: LifecycleFailure = { ...context, stage: "host" };
|
|
const runStep = <T>(stage: LifecycleFailure["stage"], work: () => Promise<T>, pluginId?: string) => {
|
|
const stepContext = { ...context, stage, ...(pluginId ? { pluginId } : {}) };
|
|
return attempt(stepContext, work).catch(error => { failureContext = stepContext; throw error; });
|
|
};
|
|
const renewal = setInterval(() => {
|
|
void attempt({ ...context, stage: "renew" }, () => store.renew(agent, owner, new Date())).catch(() => {});
|
|
}, 30_000);
|
|
renewal.unref?.();
|
|
try {
|
|
const operation = agent.lifecycleOperation!;
|
|
const saved = agent.lifecycleRequiredPluginIds;
|
|
const selecting = saved === null || (["preparing", "resuming"].includes(agent.lifecycleState)
|
|
&& !operation.hostComplete && operation.completedPluginIds.length === 0);
|
|
const pluginIds = !selecting ? saved
|
|
: [...new Set([...(saved ?? []), ...await runStep("select_plugins", () => driver.requiredPluginIds(agent))])];
|
|
if ((saved === null || pluginIds.length !== saved.length) && !await runStep("save_plugins", () => store.setRequiredPlugins(agent, owner, pluginIds))) continue;
|
|
if (!canRun()) {
|
|
await runStep("defer", () => store.defer(agent, owner, null, new Date()));
|
|
return;
|
|
}
|
|
if (!operation.hostComplete) {
|
|
if (!await runStep("renew", () => store.renew(agent, owner, new Date()))) continue;
|
|
const host = await runStep("host", () => driver.runHost(agent));
|
|
if (host === "waiting") {
|
|
if (agent.lifecycleState !== "verifying") throw new Error("Only host verification may await an external event");
|
|
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { waitForSignal: true }))) continue;
|
|
return;
|
|
}
|
|
if (host === "pending" || typeof host === "object") {
|
|
const pendingReason = typeof host === "object" ? host.pending : "host_step_pending";
|
|
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason }))) continue;
|
|
return;
|
|
}
|
|
if (!await runStep("complete_host", () => store.completeHost(agent, owner))) continue;
|
|
}
|
|
for (const pluginId of pluginIds) {
|
|
if (operation.completedPluginIds.includes(pluginId)) continue;
|
|
if (!canRun()) {
|
|
await runStep("defer", () => store.defer(agent, owner, null, new Date()));
|
|
return;
|
|
}
|
|
if (!await runStep("renew", () => store.renew(agent, owner, new Date()))) continue phase;
|
|
if (await runStep("plugin", () => driver.runPlugin(agent, pluginId), pluginId) === "pending") {
|
|
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason: "plugin_step_pending" }))) continue phase;
|
|
return;
|
|
}
|
|
if (!await runStep("complete_plugin", () => store.completePlugin(agent, owner, pluginId), pluginId)) continue phase;
|
|
}
|
|
const changed = await runStep("transition", () => store.change(id, "complete", { version: agent.lifecycleVersion, owner }));
|
|
if (changed?.lifecycleState === "ready" && !stopped && canRun()) {
|
|
// Accepted messages may already be waiting for verification. Do not
|
|
// leave them until the periodic queue sweep. Readiness is committed;
|
|
// a dispatch failure must not replay setup or defer the old phase.
|
|
await attempt({ ...context, stage: "ready", phase: changed.lifecycleState,
|
|
version: changed.lifecycleVersion, operationId: changed.lifecycleOperation?.id },
|
|
async () => { await driver.onReady?.(changed); }).catch(() => {});
|
|
}
|
|
if (changed && !isLifecycleWorkPending(changed.lifecycleState)) return;
|
|
} catch (error) {
|
|
// Claims can defer before runHost. Only a failed host test spends this budget.
|
|
const verificationFailures = failureContext.stage === "host" && agent.lifecycleState === "verifying"
|
|
&& lifecycleFailureCode(error) === "harness_test_failed"
|
|
? (agent.lifecycleOperation?.verificationFailures ?? 0) + 1 : undefined;
|
|
failureContext = { ...failureContext, verificationFailures };
|
|
const message = lifecycleFailureMessage(failureContext, error);
|
|
const retryRequired = lifecycleVerificationNeedsRetry(failureContext, error);
|
|
if (!await runStep("defer", () => retryRequired || verificationFailures !== undefined
|
|
? store.defer(agent, owner, message, new Date(), { retryRequired, ...(verificationFailures !== undefined ? { verificationFailures } : {}) })
|
|
: store.defer(agent, owner, message, new Date()))) continue;
|
|
return;
|
|
} finally {
|
|
clearInterval(renewal);
|
|
}
|
|
}
|
|
}
|
|
|
|
async function sweep() {
|
|
const pending = await attempt({ stage: "scan" }, () => store.pending(100, new Date()));
|
|
const entries = pending.values();
|
|
await Promise.all(Array.from({ length: Math.min(4, pending.length) }, async () => {
|
|
for (const id of entries) await start(id);
|
|
}));
|
|
}
|
|
|
|
function start(id: string): Promise<void> {
|
|
if (stopped || !canRun()) return Promise.resolve();
|
|
const existing = active.get(id);
|
|
if (existing) return existing;
|
|
const work = process(id).finally(() => { active.delete(id); });
|
|
active.set(id, work);
|
|
return work;
|
|
}
|
|
|
|
return {
|
|
process: start,
|
|
async stop() {
|
|
stopped = true;
|
|
await Promise.allSettled([...active.values()]);
|
|
},
|
|
sweep() {
|
|
return running ??= sweep().finally(() => { running = undefined; });
|
|
},
|
|
};
|
|
}
|