mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 01:50:13 +01:00
## Thinking Path > - Paperclip manages AI agents and preserves their work. > - Workspace migration must keep saved files and their recovery records. > - A crashed finalization attempt can remain running after a later attempt succeeds. > - The old row then blocks migration even when the saved result and export have exact receipts. > - Offline maintenance can reconcile the obsolete attempt after Cloud stops all old writers. > - This pull request fails only that attempt and records the receipt that supersedes it. > - Missing proof still blocks migration. ## Linked Issues or Issue Description Related storage migration work: #18841 and #18943. **What happened?** An old running workspace finalization row can block offline enrollment after a later finalization has saved the same run and workspace. **Expected behavior** Maintenance should reconcile the old attempt when exact saved receipts prove it is obsolete. It must preserve the accepted result, successful receipt, execution ownership, local files and recovery records. **Steps to reproduce** 1. Retain a running finalization attempt for a native run. 2. Commit an accepted run result, a finalized workspace reference and a later successful finalization receipt for the same company, task, run and workspace. 3. Stop all application and worker deployments. Run offline enrollment. 4. The old attempt blocks enrollment. This change records it as failed with receipt provenance before workspace import. ## What Changed - Add a bounded offline reconciliation service for local workspace sources that still need migration. - Require the stopped-writer acknowledgement, maintenance switch and existing active-execution gate. - Lock the finalizer ownership, run, coordinator, workspace, accepted result and operation receipts. Hold busy or incomplete records. - Fail only the obsolete attempt. Preserve its metadata and add the superseding receipt, result and workspace digests. Persist the activity audit in the same transaction. - Run reconciliation before workspace import. Keep unrelated, uncertain and saved-work obligations held. - Add real PostgreSQL tests for receipt proof, company scope, ownership races, queued work, audit rollback and repeated maintenance. ## Verification - `cd server && node ../node_modules/vitest/vitest.mjs run src/services/offline-workspace-operation-reconciliation.test.ts src/services/remote-workspace-migration.test.ts src/services/remote-workspace-migration-concurrency.test.ts src/maintenance/ephemeral-migration-service.test.ts`: 135 tests passed across four suites before the final integration test. The final focused suite passed all 33 cases, including a real local-files-to-object-storage workspace import after reconciliation. - The local server TypeScript check found one unrelated stale Runner declaration: `codexUsageBaselineForNextRun` is absent from the reused build output. It found no error in the changed files. CI must verify fresh build outputs. - Fresh GitHub Actions CI passed on `d302fbddd430d42346611302ad7307cf809c3449`, including typecheck, build, Runner, server and browser gates. Greptile gave 5/5 on the same head with no findings. - The external Paperclip Review check remains queued while it waits for its assigned reviewer agent. Do not merge until that check passes. - This PR does not claim live-data or deployed migration acceptance. A legacy preparation attempt without a superseding receipt remains held. ## Risks - The Cloud caller must establish the stop-all-deployments fence. An environment switch cannot prove that old writers stopped. - Only a succeeded native run with an unowned committed finalizer, an accepted result, a finalized matching workspace and a later completed successful receipt can pass. - Future controller leases, retained workspace owners, busy rows, uncertain work and independent save-work obligations stay held. - Expired legacy controller lease fields remain unchanged. The service changes no run, task, lease, recovery or source authority. ## Model Used OpenAI Codex, exact model ID `gpt-6.1-sol`. Context window size is not exposed. Used code reasoning, repository tools and local code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
139 lines
9.3 KiB
TypeScript
139 lines
9.3 KiB
TypeScript
import { and, asc, desc, eq, gt, inArray, isNotNull, sql } from "drizzle-orm";
|
|
import { executionWorkspaces, heartbeatRuns, nativeRunFinalizations, nativeRunResults, workspaceOperations, type Db } from "@paperclipai/db";
|
|
import { persistActivity } from "./activity-log.js";
|
|
import { offlineWorkspaceMigrationBlockers } from "./remote-workspace-migration-tree.js";
|
|
import { readNativeWorkspaceSyncReference } from "./native-runtime/native-workspace-sync.js";
|
|
import { tryLockNativeWorkspaceFinalization } from "./native-runtime/native-workspace-finalization-ownership.js";
|
|
|
|
type Candidate = typeof workspaceOperations.$inferSelect;
|
|
type Held = { operationId: string; reason: string };
|
|
const unresolved = () => inArray(workspaceOperations.status, ["running", "pending"]);
|
|
const localMigrationSource = () => and(isNotNull(executionWorkspaces.cwd),
|
|
inArray(executionWorkspaces.providerType, ["local_fs", "git_worktree"]),
|
|
sql`coalesce(${executionWorkspaces.metadata}->'remoteWorkspace'->>'schema', '') <> 'paperclip.remote-workspace.v1'`);
|
|
|
|
async function assertOffline(db: Db, writersStopped: boolean) {
|
|
// Only the Cloud maintenance caller can establish that all old deployments
|
|
// stopped. The environment switch alone is never that acknowledgement.
|
|
if (!writersStopped) throw new Error("offline_maintenance_required");
|
|
const blockers = await offlineWorkspaceMigrationBlockers(db);
|
|
if (blockers.length) throw new Error(blockers[0]);
|
|
}
|
|
|
|
function databaseCode(error: unknown): string | undefined {
|
|
const value = error as { code?: string; cause?: unknown } | null;
|
|
return value?.code ?? (value?.cause ? databaseCode(value.cause) : undefined);
|
|
}
|
|
|
|
async function reconcileAttempt(db: Db, candidate: Candidate, input: { writersStopped: boolean; signal: AbortSignal }) {
|
|
const held = (reason: string): Held => ({ operationId: candidate.id, reason });
|
|
const { heartbeatRunId: runId, issueId, executionWorkspaceId: workspaceId } = candidate;
|
|
if (candidate.phase !== "workspace_finalize" || !runId || !issueId || !workspaceId)
|
|
return held("superseding_finalization_receipt_missing");
|
|
try {
|
|
return await db.transaction(async tx => {
|
|
const database = tx as unknown as Db;
|
|
input.signal.throwIfAborted();
|
|
await assertOffline(database, input.writersStopped);
|
|
if (!await tryLockNativeWorkspaceFinalization(database, { companyId: candidate.companyId, runId }))
|
|
return held("finalization_owner_busy");
|
|
// Follow the finalizer's coordinator-before-run order. NOWAIT keeps an
|
|
// unexpected surviving writer visible instead of waiting or stealing it.
|
|
const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and(
|
|
eq(nativeRunFinalizations.companyId, candidate.companyId), eq(nativeRunFinalizations.issueId, issueId),
|
|
eq(nativeRunFinalizations.runId, runId),
|
|
)).for("update", { noWait: true });
|
|
const [run] = await tx.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.id, runId), eq(heartbeatRuns.nativeIssueId, issueId),
|
|
)).for("update", { noWait: true });
|
|
if (!run || run.runtimeMode !== "native" || run.status !== "succeeded"
|
|
|| (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date())
|
|
|| run.runnerProfileJson?.nativeWorkspaceFinalizationOwner != null || !coordinator || coordinator.phase !== "committed"
|
|
|| !coordinator.resultId || coordinator.leaseOwner !== null || coordinator.leaseExpiresAt !== null || coordinator.nextAttemptAt !== null)
|
|
return held("committed_finalization_proof_missing");
|
|
const reference = readNativeWorkspaceSyncReference(run.runnerProfileJson?.nativeWorkspaceSync);
|
|
if (!reference || reference.state !== "finalized" || !reference.finalHostSha256 || reference.workspaceId !== workspaceId)
|
|
return held("finalized_workspace_proof_missing");
|
|
const [workspace] = await tx.select({ id: executionWorkspaces.id }).from(executionWorkspaces).where(and(
|
|
eq(executionWorkspaces.companyId, candidate.companyId), eq(executionWorkspaces.id, workspaceId), localMigrationSource(),
|
|
)).for("share", { noWait: true });
|
|
if (!workspace) return held("workspace_authority_changed");
|
|
const [result] = await tx.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
|
|
eq(nativeRunResults.companyId, candidate.companyId), eq(nativeRunResults.issueId, issueId),
|
|
eq(nativeRunResults.runId, runId), eq(nativeRunResults.id, coordinator.resultId),
|
|
eq(nativeRunResults.completionContractId, run.completionContractId!), eq(nativeRunResults.schemaStatus, "accepted"),
|
|
)).for("share", { noWait: true });
|
|
if (!result) return held("accepted_result_proof_missing");
|
|
const [current] = await tx.select().from(workspaceOperations).where(and(
|
|
eq(workspaceOperations.id, candidate.id), eq(workspaceOperations.companyId, candidate.companyId),
|
|
eq(workspaceOperations.executionWorkspaceId, workspaceId), eq(workspaceOperations.issueId, issueId),
|
|
eq(workspaceOperations.heartbeatRunId, runId), eq(workspaceOperations.phase, "workspace_finalize"), unresolved(),
|
|
)).for("update", { noWait: true });
|
|
if (!current) return held("attempt_changed");
|
|
// These fields represent independent obligations. A successful later
|
|
// export does not authorize dropping them or rewriting earlier history.
|
|
if (current.metadata?.uncertain === true || current.metadata?.uncertain === "true"
|
|
|| current.metadata?.saveWork != null || current.metadata?.offlineReconciliation != null)
|
|
return held("independent_operation_obligation");
|
|
const [receipt] = await tx.select().from(workspaceOperations).where(and(
|
|
eq(workspaceOperations.companyId, candidate.companyId), eq(workspaceOperations.executionWorkspaceId, workspaceId),
|
|
eq(workspaceOperations.issueId, issueId), eq(workspaceOperations.heartbeatRunId, runId),
|
|
eq(workspaceOperations.phase, "workspace_finalize"), eq(workspaceOperations.status, "succeeded"),
|
|
isNotNull(workspaceOperations.finishedAt),
|
|
// Keep PostgreSQL timestamp precision when proving which attempt is later.
|
|
sql`${workspaceOperations.createdAt} > (select created_at from workspace_operations where id = ${current.id}::uuid)`,
|
|
)).orderBy(desc(workspaceOperations.createdAt), desc(workspaceOperations.id)).limit(1).for("share", { noWait: true });
|
|
if (!receipt || receipt.metadata?.uncertain === true || receipt.metadata?.uncertain === "true")
|
|
return held("superseding_finalization_receipt_missing");
|
|
input.signal.throwIfAborted();
|
|
await assertOffline(database, input.writersStopped);
|
|
const now = new Date();
|
|
const provenance = { schema: "paperclip.offline-workspace-operation-reconciliation.v1",
|
|
reason: "superseded_workspace_finalization", reconciledAt: now.toISOString(), previousStatus: current.status,
|
|
supersedingOperationId: receipt.id, runId, resultId: result.id,
|
|
descriptorSha256: reference.descriptorSha256, finalHostSha256: reference.finalHostSha256 };
|
|
await tx.update(workspaceOperations).set({ status: "failed", finishedAt: now, updatedAt: now,
|
|
metadata: { ...current.metadata, offlineReconciliation: provenance } }).where(and(
|
|
eq(workspaceOperations.id, current.id), eq(workspaceOperations.companyId, current.companyId), unresolved(),
|
|
));
|
|
// No live publication is needed in the stopped maintenance process. The
|
|
// audit and the failed attempt commit (or roll back) together.
|
|
await persistActivity(database, { companyId: current.companyId, actorType: "system", actorId: "ephemeral-migration",
|
|
action: "workspace_operation.reconciled", entityType: "workspace_operation", entityId: current.id,
|
|
runId, issueId, details: provenance });
|
|
return null;
|
|
});
|
|
} catch (error) {
|
|
if (databaseCode(error) === "55P03") return held("execution_rows_busy");
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Reconcile receipts only after Cloud has stopped all old application and
|
|
* worker deployments. This never executes workspace work, declares success,
|
|
* clears execution authority, or retires a recovery/source obligation. */
|
|
export async function reconcileOfflineWorkspaceOperations(db: Db, input: {
|
|
writersStopped: boolean; signal: AbortSignal; companyId?: string;
|
|
}) {
|
|
await assertOffline(db, input.writersStopped);
|
|
let after: string | undefined, inspected = 0, reconciled = 0;
|
|
const held: Held[] = [];
|
|
for (;;) {
|
|
input.signal.throwIfAborted();
|
|
const rows = await db.select({ operation: workspaceOperations }).from(workspaceOperations).innerJoin(executionWorkspaces, and(
|
|
eq(executionWorkspaces.companyId, workspaceOperations.companyId), eq(executionWorkspaces.id, workspaceOperations.executionWorkspaceId),
|
|
)).where(and(unresolved(), localMigrationSource(),
|
|
input.companyId ? eq(workspaceOperations.companyId, input.companyId) : undefined,
|
|
after ? gt(workspaceOperations.id, after) : undefined,
|
|
)).orderBy(asc(workspaceOperations.id)).limit(100);
|
|
if (!rows.length) return { inspected, reconciled, held };
|
|
for (const { operation } of rows) {
|
|
input.signal.throwIfAborted();
|
|
const outcome = await reconcileAttempt(db, operation, input);
|
|
inspected++;
|
|
if (outcome) held.push(outcome); else reconciled++;
|
|
}
|
|
after = rows.at(-1)!.operation.id;
|
|
}
|
|
}
|