Permit idle sleep with proved passive remote workspaces (#23335)

## Thinking Path

> - Paperclip runs agent work and retains its files after a run ends.
> - Remote workspaces save those files in a durable archive.
> - The idle inventory still treats every remote workspace row as active
work.
> - A saved archive or an unused setup reservation can then keep an idle
instance awake.
> - This PR adds a read-only proof in the remote workspace owner and
uses it in the existing idle check.
> - The proof keeps active work and uncertain recovery awake and
preserves all retained data.

## Linked Issues or Issue Description

**What happened?**

A retained `cloud_sandbox` workspace blocks idle sleep after its archive
commits and its allocation is released. The passive workspace check only
accepts local directories and git worktrees. An unused reservation can
also remain after a bootstrap failure that started no provider work.

**Expected behavior**

An idle instance can sleep when existing receipts prove that its remote
files are saved or that a setup reservation was never used. Missing,
foreign, contradictory, and unfinished state must keep blocking sleep.

**Steps to reproduce**

1. Save a remote workspace and finish its snapshot operation.
2. Release its allocation with the matching stop receipt, or retain no
allocation.
3. Keep the workspace row and inspect idle safety. Before this change,
the row still reports work.

Related: remote workspace storage in #18403. No duplicate open
sleep/workspace PR was found.

## What Changed

- Add a pure SQL proof for a committed, scoped archive and its completed
source operation. Require the stored encryption scheme and correctly
shaped IV, tag, and ciphertext. An unchanged save can reuse an older
snapshot.
- Require exact release evidence for a retained location and every
allocation of an unused reservation. Unused reservations require an
ended legacy bootstrap, an explicit no-provider-work result, no live
controller or retry, and no native finalization. A pristine reservation
cannot carry retained recovery-file references.
- Apply that proof through the existing passive workspace check. Keep
runtime configuration, commands, due cleanup, reopen fences, and every
independent run, lease, and recovery check.
- Add PostgreSQL regression cases and describe the proof in the
idle-safety documentation. The existing shared database fixture keeps
the tests in one suite instead of adding another database startup.
- Correct two pre-existing receipt browser assertions uncovered by
required CI. Plain comments have supported keyed retries since October
28; the older tests assumed one POST even when receipt reads lose the
race to backoff. Assert exact request identity and payload across
retries, one saved comment, and preservation of the next draft.

## Verification

- Receipt CI follow-up, Node 25.6.1 on macOS: the full
`board-attachment-receipts.spec.ts` passed twice with four Chromium
workers (28/28). Both corrected cases passed with delayed issue reads
after reproducing both old failures under the same delay. `node
scripts/typecheck-test-projects.mjs --reuse-declarations tests/e2e` and
the focused test-budget check passed. Only browser assertions changed
after the 323-test server verification.
- Node 25.6.1 on macOS: `pnpm --filter @paperclipai/server typecheck`
passed.
- Final revision: `pnpm exec vitest run
server/src/__tests__/idle-sleep-safety.test.ts
server/src/__tests__/idle-sleep-diagnostics.test.ts`: 323 passed. Both
suites used real embedded PostgreSQL. An earlier run also selected the
remote-workspace lifecycle suite; its 16 cases were skipped because its
external test database was not configured.
- Red-green: the new saved-workspace regression failed before the first
proof. Both unused-reservation cases failed before that proof was added.
The focused regressions passed after the changes. Empty key material and
a foreign allocation bound to an unused writer were also reproduced
red-green during review.
- `pnpm verify --explain` returned the documented exit 2 because the
documentation path requires broader CI. Required CI will supply that
coverage; a full local repository run was not substituted.
- After rebasing onto current `master`, the focused passive-state tests
and server typecheck passed again.
- `git diff --check` and a staged secret/PII scan passed.
- The previous revision (`078e60f`) received Greptile 5/5 with its
key-format thread resolved. [Initial
CI](https://github.com/paperclipai/paperclip/actions/runs/46536659729)
failed in a Rust executable fixture (`ExecutableFileBusy`) and a browser
receipt assertion. The targeted rerun passed Rust but failed the
companion receipt test. Both browser assertions expected one POST,
contrary to the documented keyed retry contract. A scratch fault fixture
delaying issue reads by 1.6 seconds reproduced both old failures
(`Expected: 1 / Received: 2`); both revised cases passed under the same
delay. The delay fixture is kept outside the branch. Final head
`97269b3420387b28fda5f35f69a6b9ed45d5bb54` is merge-ready: all required
gates passed, 81 checks succeeded and four were skipped by workflow
policy, Greptile is 5/5 on this head, and the one review thread is
resolved. GitHub reports `MERGEABLE` / `CLEAN`. The skipped
external-database local cases and earlier failed attempts remain
recorded above.
- No provider suspension, external wake, deployment, or cost-saving
result is claimed from these local checks. The proof adds no provider
call, recurring scan, or extra database round trip. It runs within the
existing bounded, read-only snapshot.

## Risks

This expands automatic sleep eligibility for proved passive remote
state. A proof error could stop an instance with unfinished work. The
new cases cover dirty or foreign authority, missing or malformed
snapshot key material, incomplete operations, foreign or unverified
leases, active ownership, retry state, and retained recovery references.
The SQL checks the stored key format; archive decryption and object
verification remain with the restore owner. The existing owned hold,
generation checks, runtime probes, and final host authorization still
apply. The change does not delete files, clear reservations, rewrite
history, create receipts, change schedules, or add a migration. Revert
the remote-provider predicate to restore the previous refusal behavior.
Hosted stop/wake qualification remains part of deployment acceptance.

## Model Used

OpenAI GPT-6.1-sol with xhigh reasoning through Codex in T3 Code.
Tool-assisted implementation, source review, and PostgreSQL
verification.

## 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 described the issue in-PR following the bug report template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id or instance-derived details
- [x] I have run relevant tests locally and they pass; skipped
external-database cases are stated above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented risks
- [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

- Final revision [ci /
e2e](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275047883):
passed.

- Final revision [ci /
verify](https://github.com/paperclipai/paperclip/actions/runs/46539276027/job/142275348382):
passed.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-30 17:29:31 -08:00
1 parent fb6632530d
commit 158613ef81
5 files changed
+427 -17

No files matched your search

+20
View File
@@ -167,6 +167,26 @@ can resolve that creation. Settled startup cancellations without a committed
native result manifest remain conservatively blocked by native finalization;
their cleanup marker alone is not a history exemption.
A retained remote workspace can be passive when its authority has no dirty files
or unfinished writer and names a committed archive for the same company and workspace.
The archive must retain its object reference, hashes, size, key and completed
save or migration operation. The key must use the supported stored encryption
scheme with correctly shaped IV, tag and ciphertext fields. Inspection does not
decrypt the archive. An unchanged save may reuse an older snapshot;
the snapshot epoch must not be newer than the workspace authority.
If the authority still names an allocation, its exact lease must be released
with successful cleanup and a bound stop or host cleanup receipt. A status
label, missing lease, or elapsed expiry does not establish this proof.
An unused reservation can remain passive after an explicitly failed bootstrap:
its run must have ended before provider work, have no retry or live controller,
and carry no native finalization. Every allocation of that run needs exact
release evidence. A reservation without a snapshot must also have no remote
location or retained recovery-file references. These checks retain the source
recipe and reservation; they do not claim that missing file contents were saved.
Inspection does not remove archives, clear allocation references or manufacture
receipts. Dirty files, writers, unknown providers, runtime configuration, due
cleanup and all independent run, operation, lease and recovery checks still block.
Workspace runtime inspection also reads the owner's process-local resource
state. Startup reconstruction must succeed before that probe becomes quiet.
Adopted/live services, provisioning/control/replacement work, live allocation
+262 -3
View File
@@ -1,10 +1,10 @@
import { beginIdleTrackedWork, idleWorkSnapshot } from "../services/task-admission.js";
import { randomUUID } from "node:crypto";
import { createCipheriv, randomBytes, randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agentInstructionWorkingCopies, agents, agentApiKeys, agentWakeupRequests, budgetPolicies, companies, companySecretProposals, createDb,
adapterAuthSessions, environments, environmentLeases, executionWorkspaces,
adapterAuthSessions, environments, environmentLeases, executionWorkspaces, executionWorkspaceSnapshots,
feedbackExports, feedbackVotes, companySkills, companySkillVersions, companySkillRepositorySnapshots,
heartbeatRuns, issues, issueWatchdogs, issueThreadInteractions, issueQuestionResponseDeliveries,
projects, projectWorkspaces, routines, routineTriggers, toolApplications, toolConnections, workspaceOperations, executionWorkspaceRuntimeLeases, type Db,
@@ -174,7 +174,7 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
if (!externalDatabaseUrl) database = await startEmbeddedPostgresTestDatabase("idle-sleep-safety-");
db = createDb(externalDatabaseUrl ?? database.connectionString, { maxConnections: 4 });
}, 60_000);
afterEach(async () => { await db.execute(sql`TRUNCATE companies, plugins, environments CASCADE`); });
afterEach(async () => { await db.execute(sql`TRUNCATE companies, plugins, environments, execution_workspace_snapshots CASCADE`); });
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
const read = () => readIdleSleepSafety(db, owned, () => now, ownerId, emptyLocal);
@@ -899,6 +899,265 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
return workspace!;
}
async function seedSavedRemoteWorkspace() {
const snapshotId = randomUUID();
const workspace = await seedRetainedWorkspace({ providerType: "cloud_sandbox", metadata: {
remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: 2, snapshotId,
source: { kind: "empty" }, dirty: false, writerRunId: null, location: null },
} });
const [operation] = await db.insert(workspaceOperations).values({
companyId: workspace.companyId, executionWorkspaceId: workspace.id,
phase: "remote_workspace_snapshot", status: "succeeded", finishedAt: new Date(now),
}).returning();
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", randomBytes(32), iv);
const ciphertext = Buffer.concat([cipher.update("fixture snapshot key"), cipher.final()]);
const key = { scheme: "local_encrypted_v1", iv: iv.toString("base64"),
tag: cipher.getAuthTag().toString("base64"), ciphertext: ciphertext.toString("base64") };
const [snapshot] = await db.insert(executionWorkspaceSnapshots).values({
id: snapshotId, companyId: workspace.companyId, executionWorkspaceId: workspace.id,
sourceOperationId: operation!.id, epoch: 1, generation: 1, status: "committed",
objectKey: `${workspace.companyId}/workspace-snapshots/${workspace.id}/${snapshotId}/fixture`,
sha256: "a".repeat(64), manifestDigest: "b".repeat(64), byteSize: 4096,
key,
}).returning();
return { workspace, snapshot: snapshot!, operation: operation! };
}
it("permits a saved remote workspace without deleting files or inventing cleanup receipts", async () => {
const { workspace, snapshot, operation } = await seedSavedRemoteWorkspace();
expect(await read()).toEqual(none);
expect(await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace.id))).toEqual([workspace]);
expect(await db.select().from(executionWorkspaceSnapshots).where(eq(executionWorkspaceSnapshots.id, snapshot.id))).toEqual([snapshot]);
expect(await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, operation.id))).toEqual([operation]);
});
async function seedReleasedRemoteLocation() {
const saved = await seedSavedRemoteWorkspace();
const { workspace } = saved;
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, workspace.companyId));
await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, run!.id));
const [environment] = await db.insert(environments).values({ name: "Remote fixture", driver: "sandbox" }).returning();
const leaseId = randomUUID(), providerLeaseId = "fixture-remote-allocation", remoteCwd = "/remote/fixture";
const receipt = { schema: "paperclip.remote-termination.v1", companyId: workspace.companyId,
runId: run!.id, leaseId, provider: "fixture-remote", providerLeaseId, state: "stopped", confirmedAt: new Date(now).toISOString() };
const [lease] = await db.insert(environmentLeases).values({
id: leaseId, companyId: workspace.companyId, environmentId: environment!.id,
executionWorkspaceId: workspace.id, heartbeatRunId: run!.id,
provider: "fixture-remote", providerLeaseId, status: "released", cleanupStatus: "success", releasedAt: new Date(now),
metadata: { remoteCwd, remoteExecutionTermination: receipt },
}).returning();
const authority = workspace.metadata!.remoteWorkspace as Record<string, unknown>;
const metadata = { ...workspace.metadata, remoteWorkspace: { ...authority,
location: { environmentId: environment!.id, leaseId, providerLeaseId, remoteCwd } } };
await db.update(executionWorkspaces).set({ metadata }).where(eq(executionWorkspaces.id, workspace.id));
return { ...saved, workspace: { ...workspace, metadata }, lease: lease!, run: run!, receipt };
}
it.each(["stopped", "destroyed"])("permits a saved remote location with its exact released %s receipt", async state => {
const f = await seedReleasedRemoteLocation();
await db.update(environmentLeases).set({ metadata: { ...f.lease.metadata,
remoteExecutionTermination: { ...f.receipt, state } } }).where(eq(environmentLeases.id, f.lease.id));
expect(await read()).toEqual(none);
expect((await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspace.id)))[0]?.metadata).toEqual(f.workspace.metadata);
});
it.each([
{ dirty: true }, { dirty: "false" }, { writerRunId: randomUUID() }, { snapshotId: null },
{ schema: "future.workspace.v1" }, { epoch: 0 }, { epoch: "2" }, { epoch: 1.5 },
{ epoch: 9007199254740992 }, { location: [] }, { futureWorker: true }, { source: { kind: "future" } },
])("keeps a remote workspace with unproved authority awake: %j", async change => {
const { workspace } = await seedSavedRemoteWorkspace();
await db.update(executionWorkspaces).set({ metadata: { ...workspace.metadata,
remoteWorkspace: { ...(workspace.metadata!.remoteWorkspace as Record<string, unknown>), ...change } } })
.where(eq(executionWorkspaces.id, workspace.id));
expect(await read()).toEqual(present);
});
it.each([
{ status: "pending" }, { status: "uploaded" }, { status: "deleted" },
{ companyId: randomUUID() }, { executionWorkspaceId: randomUUID() }, { sourceOperationId: randomUUID() },
{ format: "future.archive.v1" }, { epoch: 3 }, { generation: 0 }, { objectKey: "foreign/object" },
{ sha256: null }, { manifestDigest: null }, { byteSize: 1 }, { key: null },
{ deleteAfter: new Date(now) }, { lastError: "save_unconfirmed" },
] satisfies Array<Partial<typeof executionWorkspaceSnapshots.$inferInsert>>)(
"keeps a remote workspace with an unproved snapshot awake: %j", async change => {
const { snapshot } = await seedSavedRemoteWorkspace();
await db.update(executionWorkspaceSnapshots).set(change).where(eq(executionWorkspaceSnapshots.id, snapshot.id));
expect(await read()).toEqual(present);
},
);
it.each([
{ status: "running" }, { status: "failed" }, { finishedAt: null }, { phase: "future_save" },
{ heartbeatRunId: randomUUID() },
])("keeps a remote workspace with an unproved save operation awake: %j", async change => {
const { operation } = await seedSavedRemoteWorkspace();
const patch: Partial<typeof workspaceOperations.$inferInsert> = { ...change };
if (change.heartbeatRunId) {
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, operation.companyId));
patch.heartbeatRunId = run!.id;
}
await db.update(workspaceOperations).set(patch).where(eq(workspaceOperations.id, operation.id));
expect(await read()).toEqual(present);
});
it.each(["active", "unreleased", "cleanup_failed", "missing_receipt", "wrong_receipt", "wrong_directory", "unfinished_run", "pending_export"])(
"keeps a saved remote location awake with %s evidence", async kind => {
const f = await seedReleasedRemoteLocation();
if (kind === "active") await db.update(environmentLeases).set({ status: "active" }).where(eq(environmentLeases.id, f.lease.id));
if (kind === "unreleased") await db.update(environmentLeases).set({ releasedAt: null }).where(eq(environmentLeases.id, f.lease.id));
if (kind === "cleanup_failed") await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, f.lease.id));
if (kind === "unfinished_run") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, f.run.id));
if (kind === "missing_receipt") await db.update(environmentLeases).set({ metadata: { remoteCwd: "/remote/fixture" } }).where(eq(environmentLeases.id, f.lease.id));
if (kind === "wrong_receipt") await db.update(environmentLeases).set({ metadata: { ...f.lease.metadata,
remoteExecutionTermination: { ...f.receipt, leaseId: randomUUID() } } }).where(eq(environmentLeases.id, f.lease.id));
if (kind === "wrong_directory") await db.update(environmentLeases).set({ metadata: { ...f.lease.metadata, remoteCwd: "/remote/other" } }).where(eq(environmentLeases.id, f.lease.id));
if (kind === "pending_export") await db.update(environmentLeases).set({ metadata: { ...f.lease.metadata, nativeWorkspaceExportResume: {} } }).where(eq(environmentLeases.id, f.lease.id));
expect(await read()).toEqual(present);
},
);
it("requires the snapshot source run to finish even when its terminal label is already set", async () => {
const { workspace, snapshot, operation } = await seedSavedRemoteWorkspace();
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, workspace.companyId));
await db.update(executionWorkspaceSnapshots).set({ sourceRunId: run!.id }).where(eq(executionWorkspaceSnapshots.id, snapshot.id));
await db.update(workspaceOperations).set({ heartbeatRunId: run!.id }).where(eq(workspaceOperations.id, operation.id));
expect(await read()).toEqual(present);
await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, run!.id));
expect(await read()).toEqual(none);
});
it("requires the exact source operation company and workspace", async () => {
const saved = await seedSavedRemoteWorkspace();
const other = await seedSavedRemoteWorkspace();
await db.update(workspaceOperations).set({ companyId: other.workspace.companyId })
.where(eq(workspaceOperations.id, saved.operation.id));
expect(await read()).toEqual(present);
await db.update(workspaceOperations).set({ companyId: saved.workspace.companyId, executionWorkspaceId: other.workspace.id })
.where(eq(workspaceOperations.id, saved.operation.id));
expect(await read()).toEqual(present);
});
it("accepts exact host cleanup proof for a released allocation without a run", async () => {
const f = await seedReleasedRemoteLocation();
const [stamp] = await db.execute<{ value: string }>(sql`SELECT to_char(updated_at AT TIME ZONE 'UTC',
'YYYY-MM-DD"T"HH24:MI:SS.US') AS value FROM environment_leases WHERE id = ${f.lease.id}`);
const proof = { schema: "paperclip.cleanup-verification.v1", kind: "lease", resourceId: f.lease.id,
companyId: f.workspace.companyId, environmentId: f.lease.environmentId,
provider: f.lease.provider, providerLeaseId: f.lease.providerLeaseId, heartbeatRunId: null,
state: "destroyed", rowUpdatedAt: stamp!.value };
await db.update(environmentLeases).set({ heartbeatRunId: null, metadata: {
remoteCwd: "/remote/fixture", paperclipCleanupVerification: proof } }).where(eq(environmentLeases.id, f.lease.id));
expect(await read()).toEqual(none);
await db.update(environmentLeases).set({ metadata: { remoteCwd: "/remote/fixture",
paperclipCleanupVerification: { ...proof, rowUpdatedAt: "not-current" } } }).where(eq(environmentLeases.id, f.lease.id));
expect(await read()).toEqual(present);
});
async function seedUnusedRemoteReservation(pristine = false) {
const saved = await seedSavedRemoteWorkspace();
const { workspace } = saved;
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, workspace.companyId));
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date(now), runtimeMode: "legacy",
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }).where(eq(heartbeatRuns.id, run!.id));
const authority = workspace.metadata!.remoteWorkspace as Record<string, unknown>;
const metadata = { ...workspace.metadata, remoteWorkspace: { ...authority,
writerRunId: run!.id, ...(pristine ? { snapshotId: null } : {}) } };
await db.update(executionWorkspaces).set({ metadata }).where(eq(executionWorkspaces.id, workspace.id));
if (pristine) {
await db.delete(executionWorkspaceSnapshots).where(eq(executionWorkspaceSnapshots.id, saved.snapshot.id));
await db.delete(workspaceOperations).where(eq(workspaceOperations.id, saved.operation.id));
}
return { ...saved, workspace: { ...workspace, metadata }, run: run! };
}
it.each([false, true])("permits a proved unused reservation after bootstrap ended, pristine=%s", async pristine => {
const f = await seedUnusedRemoteReservation(pristine);
expect(await read()).toEqual(none);
expect((await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, f.workspace.id)))[0]?.metadata).toEqual(f.workspace.metadata);
});
it.each(["started", "unknown_start", "unfinished", "retry", "controller", "wrong_kind", "succeeded"])(
"keeps an unused-looking reservation awake with %s evidence", async kind => {
const f = await seedUnusedRemoteReservation(true);
if (kind === "started" || kind === "unknown_start" || kind === "wrong_kind") {
await db.update(heartbeatRuns).set({ resultJson: { executionRecovery: {
kind: kind === "wrong_kind" ? "unknown" : "bootstrap",
providerWorkStarted: kind === "started" ? true : kind === "unknown_start" ? "false" : false,
} } }).where(eq(heartbeatRuns.id, f.run.id));
}
if (kind === "succeeded") await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.run.id));
if (kind === "unfinished") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, f.run.id));
if (kind === "retry") await db.update(heartbeatRuns).set({ scheduledRetryAt: new Date(Date.UTC(2099, 0, 1)) }).where(eq(heartbeatRuns.id, f.run.id));
if (kind === "controller") await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.UTC(2099, 0, 1)) }).where(eq(heartbeatRuns.id, f.run.id));
expect(await read()).toEqual(present);
},
);
it("keeps a pristine-looking reservation with retained recovery files awake", async () => {
const f = await seedUnusedRemoteReservation(true);
await db.update(executionWorkspaces).set({ metadata: { ...f.workspace.metadata,
remoteWorkspaceRecoveredFiles: [] } }).where(eq(executionWorkspaces.id, f.workspace.id));
expect(await read()).toEqual(present);
});
it("requires release proof for every allocation of an unused writer", async () => {
const f = await seedReleasedRemoteLocation();
await db.update(heartbeatRuns).set({ status: "failed", runtimeMode: "legacy",
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }).where(eq(heartbeatRuns.id, f.run.id));
await db.update(executionWorkspaces).set({ metadata: { ...f.workspace.metadata, remoteWorkspace: {
...(f.workspace.metadata.remoteWorkspace as Record<string, unknown>), writerRunId: f.run.id,
} } }).where(eq(executionWorkspaces.id, f.workspace.id));
expect(await read()).toEqual(none);
const [otherLease] = await db.insert(environmentLeases).values({ companyId: f.workspace.companyId,
environmentId: f.lease.environmentId, heartbeatRunId: f.run.id, provider: "fixture-remote",
providerLeaseId: "fixture-other-allocation", status: "released", cleanupStatus: "success", releasedAt: new Date(now),
}).returning();
expect(await read()).toEqual(present);
await db.delete(environmentLeases).where(eq(environmentLeases.id, otherLease!.id));
expect(await read()).toEqual(none);
});
it.each(["saved", "pristine"])("accepts a known git source recipe with %s remote state", async kind => {
const f = await seedUnusedRemoteReservation(kind === "pristine");
const authority = f.workspace.metadata.remoteWorkspace as Record<string, unknown>;
await db.update(executionWorkspaces).set({ metadata: { ...f.workspace.metadata,
remoteWorkspace: { ...authority, source: { kind: "git", repoUrl: "fixture-repository", ref: null } } } })
.where(eq(executionWorkspaces.id, f.workspace.id));
expect(await read()).toEqual(none);
await db.update(executionWorkspaces).set({ metadata: { ...f.workspace.metadata,
remoteWorkspace: { ...authority, source: { kind: "git" } } } }).where(eq(executionWorkspaces.id, f.workspace.id));
expect(await read()).toEqual(present);
});
it("does not ignore a foreign allocation bound to an unused writer", async () => {
const f = await seedUnusedRemoteReservation(true);
const other = await seed();
const [environment] = await db.insert(environments).values({ name: "Foreign fixture", driver: "sandbox" }).returning();
await db.insert(environmentLeases).values({ companyId: other.companyId, environmentId: environment!.id,
heartbeatRunId: f.run.id, provider: "fixture-remote", providerLeaseId: "foreign-allocation",
status: "released", cleanupStatus: "success", releasedAt: new Date(now) });
expect(await read()).toEqual(present);
});
it("keeps a saved archive with an empty key object awake", async () => {
const { snapshot } = await seedSavedRemoteWorkspace();
await db.update(executionWorkspaceSnapshots).set({ key: {} }).where(eq(executionWorkspaceSnapshots.id, snapshot.id));
expect(await read()).toEqual(present);
});
it.each([
{ scheme: "future_encryption" }, { iv: null }, { iv: "" }, { iv: "not-base64" },
{ tag: null }, { tag: "" }, { tag: "too-short" },
{ ciphertext: null }, { ciphertext: "" }, { ciphertext: "not-base64" },
])("keeps a saved archive with malformed encryption material awake: %j", async change => {
const { snapshot } = await seedSavedRemoteWorkspace();
await db.update(executionWorkspaceSnapshots).set({ key: { ...snapshot.key, ...change } })
.where(eq(executionWorkspaceSnapshots.id, snapshot.id));
expect(await read()).toEqual(present);
});
it.each(["local_fs", "git_worktree"].flatMap(providerType =>
["active", "idle", "in_review", "archived"].map(status => ({ providerType, status }))))(
"permits a passive local directory without removing retained data: %j", async ({ providerType, status }) => {
+5 -2
View File
@@ -29,6 +29,7 @@ import { idleDecisionHistoryChecks } from "./decision-idle-proof.js";
import { idleWorkspaceHistoryChecks } from "./workspace-history-idle-proof.js";
import { idleMcpHistoryChecks } from "./public-mcp/idle-history-proof.js";
import { idleExternalAgentHistoryChecks } from "../modules/external-agents/index.js";
import { passiveRemoteWorkspace } from "./remote-workspace-idle-proof.js";
export const completedHistoryChecks = [
...idleChatHistoryChecks, ...idleToolActionHistoryChecks, ...idleBrowserHistoryChecks,
@@ -158,12 +159,14 @@ const WORK_CHECKS = [
// retry after immediate evaluation failed before creating a review/run.
workCheck("issue_watchdogs", `SELECT 1 FROM issue_watchdogs WHERE status <> 'disabled'`),
workCheck("workspace_operations", `SELECT 1 FROM workspace_operations WHERE status NOT IN ('succeeded', 'failed', 'cancelled')`),
// A local directory has no independent worker. Keep unfamiliar providers,
// A local directory or proved saved remote workspace has no independent worker.
// Keep unfamiliar providers,
// runtime/command configuration, reopen fences and due cleanup awake. Runs,
// operations, runtime services, retained leases and backup work are checked
// separately; inspecting the row never deletes or shortens retained data.
workCheck("execution_workspaces", `SELECT 1 FROM execution_workspaces w WHERE (
w.provider_type IN ('local_fs', 'git_worktree')
(w.provider_type IN ('local_fs', 'git_worktree')
OR (w.provider_type = 'cloud_sandbox' AND (${passiveRemoteWorkspace("w")})))
AND w.strategy_type IN ('project_primary', 'git_worktree')
AND w.mode IN ('inherit', 'shared_workspace', 'isolated_workspace', 'operator_branch', 'reuse_existing', 'agent_default')
AND w.status IN ('active', 'idle', 'in_review', 'archived')
@@ -0,0 +1,112 @@
import { verifiedResourceCleanup } from "./cleanup-verification-proof.js";
import { finishedIdleRun } from "./idle-work-proof.js";
/** The same exact release evidence used by the remote workspace owner. */
function releasedRemoteLease(alias: string): string {
const receipt = `(${alias}.metadata->'remoteExecutionTermination')`;
return `${alias}.provider IS NOT NULL AND ${alias}.provider <> 'local'
AND ${alias}.provider_lease_id IS NOT NULL AND ${alias}.provider_lease_id <> ''
AND ${alias}.status IN ('released', 'expired', 'failed')
AND ${alias}.released_at IS NOT NULL AND ${alias}.cleanup_status = 'success'
AND COALESCE(${alias}.metadata->>'pendingCleanupInFlight', 'false') = 'false'
AND NOT (COALESCE(${alias}.metadata, '{}'::jsonb) ?| ARRAY['nativeWorkspaceExportResume', 'sandboxStopAndRetain'])
AND ((${receipt}->>'schema' = 'paperclip.remote-termination.v1'
AND ${receipt}->>'companyId' = ${alias}.company_id::text
AND ${receipt}->>'runId' = ${alias}.heartbeat_run_id::text
AND ${receipt}->>'leaseId' = ${alias}.id::text
AND ${receipt}->>'provider' = ${alias}.provider
AND ${receipt}->>'providerLeaseId' = ${alias}.provider_lease_id
AND ${receipt}->>'state' IN ('stopped', 'destroyed')
AND EXISTS (SELECT 1 FROM heartbeat_runs idle_remote_lease_run
WHERE idle_remote_lease_run.id = ${alias}.heartbeat_run_id
AND idle_remote_lease_run.company_id = ${alias}.company_id AND ${finishedIdleRun("idle_remote_lease_run")}))
OR (${verifiedResourceCleanup(alias, "lease")}))`;
}
/** Fixed SQL aliases only. A retained archive is data, not a running sandbox.
* This proves only the workspace's saved state. Run, recovery, runtime-service,
* operation and lease work still pass through their independent sleep checks. */
export function passiveRemoteWorkspace(alias: string): string {
const authority = `(${alias}.metadata->'remoteWorkspace')`;
const location = `(${authority}->'location')`;
// Reservation precedes allocation and marks the workspace dirty before use.
// The owner already permits reusing an unused reservation. For sleep, require
// explicit ended bootstrap evidence, no live controller, and every lease's
// exact release proof. Never clear the reservation during this read.
const unusedWriter = `EXISTS (SELECT 1 FROM heartbeat_runs idle_remote_writer
WHERE idle_remote_writer.id::text = ${authority}->>'writerRunId'
AND idle_remote_writer.company_id = ${alias}.company_id AND ${finishedIdleRun("idle_remote_writer")}
AND idle_remote_writer.status IN ('failed', 'cancelled', 'interrupted', 'timed_out')
AND idle_remote_writer.runtime_mode = 'legacy'
AND idle_remote_writer.result_json->'executionRecovery'->>'kind' = 'bootstrap'
AND idle_remote_writer.result_json->'executionRecovery'->'providerWorkStarted' = 'false'::jsonb
AND COALESCE(idle_remote_writer.controller_lease_expires_at <= now(), true)
AND NOT EXISTS (SELECT 1 FROM native_run_finalizations idle_remote_finalization
WHERE idle_remote_finalization.company_id = ${alias}.company_id
AND idle_remote_finalization.run_id = idle_remote_writer.id)
AND NOT EXISTS (SELECT 1 FROM environment_leases idle_remote_writer_lease
WHERE idle_remote_writer_lease.heartbeat_run_id = idle_remote_writer.id
AND (idle_remote_writer_lease.company_id IS DISTINCT FROM ${alias}.company_id
OR (${releasedRemoteLease("idle_remote_writer_lease")}) IS NOT TRUE)))`;
return `jsonb_typeof(${authority}) = 'object'
AND (${authority} - ARRAY['schema', 'epoch', 'snapshotId', 'source', 'location', 'writerRunId', 'dirty']) = '{}'::jsonb
AND ${authority}->>'schema' = 'paperclip.remote-workspace.v1'
AND ${authority}->'dirty' = 'false'::jsonb
AND (${authority}->'writerRunId' = 'null'::jsonb OR (${unusedWriter}))
AND CASE WHEN jsonb_typeof(${authority}->'epoch') = 'number' THEN
(${authority}->>'epoch')::numeric BETWEEN 1 AND 9007199254740991
AND trunc((${authority}->>'epoch')::numeric) = (${authority}->>'epoch')::numeric ELSE false END
AND jsonb_typeof(${authority}->'source') = 'object'
AND (${authority}->'source'->>'kind' = 'empty' OR (${authority}->'source'->>'kind' = 'git'
AND jsonb_typeof(${authority}->'source'->'repoUrl') = 'string' AND length(${authority}->'source'->>'repoUrl') > 0
AND (${authority}->'source'->'ref' = 'null'::jsonb OR jsonb_typeof(${authority}->'source'->'ref') = 'string')))
AND (EXISTS (SELECT 1 FROM execution_workspace_snapshots idle_remote_snapshot
JOIN workspace_operations idle_remote_save ON idle_remote_save.id = idle_remote_snapshot.source_operation_id
WHERE jsonb_typeof(${authority}->'snapshotId') = 'string'
AND idle_remote_snapshot.id::text = ${authority}->>'snapshotId'
AND idle_remote_snapshot.company_id = ${alias}.company_id
AND idle_remote_snapshot.execution_workspace_id = ${alias}.id
AND idle_remote_snapshot.status = 'committed'
AND idle_remote_snapshot.format = 'paperclip.remote-workspace-archive.v1'
AND idle_remote_snapshot.generation > 0 AND idle_remote_snapshot.epoch > 0
-- An unchanged final save can reuse an older committed snapshot.
AND CASE WHEN jsonb_typeof(${authority}->'epoch') = 'number' THEN
(${authority}->>'epoch')::numeric >= idle_remote_snapshot.epoch ELSE false END
AND idle_remote_snapshot.object_key LIKE idle_remote_snapshot.company_id::text || '/workspace-snapshots/'
|| idle_remote_snapshot.execution_workspace_id::text || '/' || idle_remote_snapshot.id::text || '/%'
AND idle_remote_snapshot.sha256 ~ '^[a-f0-9]{64}$'
AND idle_remote_snapshot.manifest_digest ~ '^[a-f0-9]{64}$'
AND idle_remote_snapshot.byte_size >= 35 AND jsonb_typeof(idle_remote_snapshot.key) = 'object'
AND idle_remote_snapshot.key->>'scheme' = 'local_encrypted_v1'
AND jsonb_typeof(idle_remote_snapshot.key->'iv') = 'string'
AND idle_remote_snapshot.key->>'iv' ~ '^[A-Za-z0-9+/]{16}$'
AND jsonb_typeof(idle_remote_snapshot.key->'tag') = 'string'
AND idle_remote_snapshot.key->>'tag' ~ '^[A-Za-z0-9+/]{22}==$'
AND jsonb_typeof(idle_remote_snapshot.key->'ciphertext') = 'string'
AND length(idle_remote_snapshot.key->>'ciphertext') > 0
AND idle_remote_snapshot.key->>'ciphertext' ~ '^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$'
AND idle_remote_snapshot.delete_after IS NULL AND idle_remote_snapshot.last_error IS NULL
AND idle_remote_save.company_id = ${alias}.company_id
AND idle_remote_save.execution_workspace_id = ${alias}.id
AND idle_remote_save.phase IN ('remote_workspace_snapshot', 'remote_workspace_migration')
AND idle_remote_save.status = 'succeeded' AND idle_remote_save.finished_at IS NOT NULL
AND idle_remote_save.heartbeat_run_id IS NOT DISTINCT FROM idle_remote_snapshot.source_run_id
AND (idle_remote_snapshot.source_run_id IS NULL OR EXISTS (
SELECT 1 FROM heartbeat_runs idle_remote_source WHERE idle_remote_source.id = idle_remote_snapshot.source_run_id
AND idle_remote_source.company_id = ${alias}.company_id AND ${finishedIdleRun("idle_remote_source")})))
OR (${authority}->'snapshotId' = 'null'::jsonb AND ${location} = 'null'::jsonb AND (${unusedWriter})
AND NOT (COALESCE(${alias}.metadata, '{}'::jsonb) ?| ARRAY['workspaceFilesUnavailable', 'legacyWorkspaceRecoveryMigration',
'remoteWorkspaceUnchangedBaseline', 'remoteWorkspaceSnapshotRepositories', 'remoteWorkspaceRecoveredFiles',
'remoteWorkspaceRecoverySourceRunIds', 'remoteWorkspaceAbandonedEpochs'])))
AND (${location} = 'null'::jsonb OR (jsonb_typeof(${location}) = 'object'
AND (${location} - ARRAY['environmentId', 'leaseId', 'providerLeaseId', 'remoteCwd']) = '{}'::jsonb
AND jsonb_typeof(${location}->'remoteCwd') = 'string' AND length(${location}->>'remoteCwd') > 0
AND EXISTS (SELECT 1 FROM environment_leases idle_remote_lease
WHERE idle_remote_lease.id::text = ${location}->>'leaseId'
AND idle_remote_lease.company_id = ${alias}.company_id
AND idle_remote_lease.environment_id::text = ${location}->>'environmentId'
AND idle_remote_lease.provider_lease_id = ${location}->>'providerLeaseId'
AND idle_remote_lease.metadata->>'remoteCwd' = ${location}->>'remoteCwd'
AND (idle_remote_lease.execution_workspace_id IS NULL OR idle_remote_lease.execution_workspace_id = ${alias}.id)
AND (${releasedRemoteLease("idle_remote_lease")}))))`;
}
+28 -12
View File
@@ -17,6 +17,11 @@ type Attachment = {
contentPath: string;
};
type Comment = { id: string; body: string; clientRequestId?: string | null };
type CommentRequest = {
body: string;
clientRequestId: string;
attachmentIds?: string[];
};
async function body<T>(
response: Pick<APIResponse, "json" | "ok" | "status" | "text">,
@@ -356,7 +361,7 @@ for (const classic of [false, true]) {
{
const classic = false;
test(`lost accepted response settles from its exact receipt without replay (classic=${classic})`, async ({
test(`lost accepted response settles without duplicate delivery (classic=${classic})`, async ({
page,
request,
}, testInfo) => {
@@ -364,13 +369,13 @@ for (const classic of [false, true]) {
await fixture.editor.fill("Accepted once: inspect this exact file.");
const receipt = await upload(page, fixture, files[0]!);
let accepted = false;
let attempts = 0;
const attempts: CommentRequest[] = [];
let acceptedRequestId: string | undefined;
await page.route("**/api/issues/*/comments", async (route) => {
if (route.request().method() !== "POST") return route.continue();
attempts++;
attempts.push(route.request().postDataJSON());
if (accepted) return route.continue();
acceptedRequestId = route.request().postDataJSON().clientRequestId;
acceptedRequestId = attempts[0]!.clientRequestId;
const response = await route.fetch();
expect(response.status()).toBe(201);
accepted = true;
@@ -386,14 +391,16 @@ for (const classic of [false, true]) {
?.issueCommentId,
).toBeTruthy();
await page.reload();
// The durable request receipt proves delivery even though the POST reply
// was lost. No manual Review/Discard bookkeeping or blind replay remains.
// A restored plain comment may retry with its original key before its
// receipt loads. That retry must preserve the payload and save no duplicate.
await expect(fixture.editor).toBeEmpty();
await expect(fixture.composer.getByRole("alert")).toHaveCount(0);
await expect(fixture.composer.getByText("board-fresh.txt", { exact: true })).toHaveCount(0);
await expect(fixture.send).toBeDisabled();
for (const attempt of attempts) expect(attempt).toEqual(attempts[0]);
const settledAttempts = attempts.length;
await fixture.editor.press("Control+Enter");
expect(attempts).toBe(1);
expect(attempts).toHaveLength(settledAttempts);
expect(await fixture.comments()).toHaveLength(1);
await page.screenshot({
path: testInfo.outputPath("accepted-response-lost.png"),
@@ -456,12 +463,13 @@ for (const classic of [false, true]) {
release = resolve;
});
let accepted = false;
let attempts = 0;
const attempts: CommentRequest[] = [];
let acceptedRequestId: string | undefined;
await page.route("**/api/issues/*/comments", async (route) => {
if (route.request().method() !== "POST") return route.continue();
attempts++;
acceptedRequestId ??= route.request().postDataJSON().clientRequestId;
const payload = route.request().postDataJSON() as CommentRequest;
attempts.push(payload);
acceptedRequestId ??= payload.clientRequestId;
const response = await route.fetch();
expect(response.status()).toBe(201);
accepted = true;
@@ -482,13 +490,21 @@ for (const classic of [false, true]) {
);
await expect(fixture.composer.getByRole("alert")).toHaveCount(0);
await expect(fixture.send).toBeEnabled();
expect(attempts).toBe(1);
// Reload can race the keyed resend backoff. Every attempt before the
// deliberate next send must still be the exact original request.
for (const attempt of attempts) expect(attempt).toEqual(attempts[0]);
expect(await fixture.comments()).toHaveLength(1);
expect(acceptedRequestId).toEqual(expect.any(String));
expect((await fixture.comments())[0]!.clientRequestId).toBe(acceptedRequestId);
await fixture.sendComment();
await expect.poll(async () => (await fixture.comments()).length).toBe(2);
expect(attempts).toBe(2);
const nextRequest = attempts.find(attempt => attempt.clientRequestId !== acceptedRequestId);
expect(nextRequest).toMatchObject({ body: "A newer draft written while delivery was pending." });
for (const attempt of attempts) {
expect(attempt).toEqual(attempt.clientRequestId === acceptedRequestId ? attempts[0] : nextRequest);
}
expect(new Set((await fixture.comments()).map(comment => comment.clientRequestId)))
.toEqual(new Set([acceptedRequestId, nextRequest!.clientRequestId]));
expect((await fixture.comments()).map((comment) => comment.body).sort()).toEqual([
"A newer draft written while delivery was pending.",
"One text-only save interrupted by reload.",