diff --git a/doc/idle-sleep-safety.md b/doc/idle-sleep-safety.md index 84a53f96f46..2b8aef71a34 100644 --- a/doc/idle-sleep-safety.md +++ b/doc/idle-sleep-safety.md @@ -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 diff --git a/server/src/__tests__/idle-sleep-safety.test.ts b/server/src/__tests__/idle-sleep-safety.test.ts index 51ef2ce29f3..7d0995689d7 100644 --- a/server/src/__tests__/idle-sleep-safety.test.ts +++ b/server/src/__tests__/idle-sleep-safety.test.ts @@ -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; + 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), ...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>)( + "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 = { ...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; + 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), 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; + 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 }) => { diff --git a/server/src/services/idle-sleep-safety.ts b/server/src/services/idle-sleep-safety.ts index 9ff2a5e009f..3a5126efc84 100644 --- a/server/src/services/idle-sleep-safety.ts +++ b/server/src/services/idle-sleep-safety.ts @@ -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') diff --git a/server/src/services/remote-workspace-idle-proof.ts b/server/src/services/remote-workspace-idle-proof.ts new file mode 100644 index 00000000000..a2238fe8847 --- /dev/null +++ b/server/src/services/remote-workspace-idle-proof.ts @@ -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")}))))`; +} diff --git a/tests/e2e/board-attachment-receipts.spec.ts b/tests/e2e/board-attachment-receipts.spec.ts index 2359edca999..ce6947282b4 100644 --- a/tests/e2e/board-attachment-receipts.spec.ts +++ b/tests/e2e/board-attachment-receipts.spec.ts @@ -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( response: Pick, @@ -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.",