mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 14:20:12 +01:00
fix(workspaces): name online recovery and finalizer blockers, and move settled finalizers online as offline does
Inventory returns the recovery kind or finalizer state behind workspace_recovery_unresolved and execution_finalization_unresolved, and the online pass reports it. A settled native run whose files are already saved (finalized with a workspace_finalize receipt, or synced to another related workspace) no longer blocks the online move; publication locks and rechecks its finalizer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
32375d302f
commit
415941f56a
4 files changed
+120
-22
No files matched your search
@@ -385,6 +385,19 @@ describe("online durable-data migration pass", () => {
|
|||||||
expect(JSON.stringify(result)).not.toContain("private");
|
expect(JSON.stringify(result)).not.toContain("private");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("names the recovery kind and finalizer state that keep a workspace local", async () => {
|
||||||
|
const fixture = owners({
|
||||||
|
localWorkspaces: async () => [workspace(1), workspace(2)],
|
||||||
|
inventoryWorkspace: async (_db: Db, input: { workspaceId: string }) => input.workspaceId === "w1"
|
||||||
|
? { reasons: ["workspace_recovery_unresolved"], details: ["workspace_recovery_unresolved:active_run_watchdog"] }
|
||||||
|
: { reasons: ["execution_finalization_unresolved"], details: ["execution_finalization_unresolved:finalizer_leased", "bad:/private"] },
|
||||||
|
});
|
||||||
|
const result = await runOnlineDurableDataMigration(db, { budgetMs: 60_000 }, fixture.owners);
|
||||||
|
expect(result.deferred).toMatchObject({ "workspaces:workspace_recovery_unresolved": 1, "workspaces:workspace_recovery_unresolved:active_run_watchdog": 1,
|
||||||
|
"workspaces:execution_finalization_unresolved": 1, "workspaces:execution_finalization_unresolved:finalizer_leased": 1 });
|
||||||
|
expect(JSON.stringify(result)).not.toContain("private");
|
||||||
|
});
|
||||||
|
|
||||||
it("migrates an idle workspace through the online owner with a bounded source-lock wait, never the offline mode", async () => {
|
it("migrates an idle workspace through the online owner with a bounded source-lock wait, never the offline mode", async () => {
|
||||||
const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] }));
|
const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] }));
|
||||||
const fixture = owners({ localWorkspaces: async () => [workspace(1)], migrateWorkspace });
|
const fixture = owners({ localWorkspaces: async () => [workspace(1)], migrateWorkspace });
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ type Owners = {
|
|||||||
workspaceCompanies: typeof listLocalWorkspaceCompanies;
|
workspaceCompanies: typeof listLocalWorkspaceCompanies;
|
||||||
workspaceOperations: (db: Db, input: { companyId: string; signal: AbortSignal }) => Promise<{ reconciled: number; held: Array<{ reason: string }> }>;
|
workspaceOperations: (db: Db, input: { companyId: string; signal: AbortSignal }) => Promise<{ reconciled: number; held: Array<{ reason: string }> }>;
|
||||||
localWorkspaces: typeof listLocalWorkspaces;
|
localWorkspaces: typeof listLocalWorkspaces;
|
||||||
inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[]; sourceScopeUnproven?: string }>;
|
inventoryWorkspace: (db: Db, input: { companyId: string; workspaceId: string }) => Promise<{ reasons: string[]; sourceScopeUnproven?: string; details?: string[] }>;
|
||||||
migrateWorkspace: (input: { db: Db; storage: StorageService; companyId: string; workspaceId: string; apply: true;
|
migrateWorkspace: (input: { db: Db; storage: StorageService; companyId: string; workspaceId: string; apply: true;
|
||||||
signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>;
|
signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>;
|
||||||
nativeHarnessBackups: typeof prestageNativeHarnessBackups;
|
nativeHarnessBackups: typeof prestageNativeHarnessBackups;
|
||||||
@@ -258,6 +258,7 @@ async function migrate(db: Db, input: { budgetMs: number; now?: () => number },
|
|||||||
const inventory = await owners.inventoryWorkspace(db, { companyId, workspaceId });
|
const inventory = await owners.inventoryWorkspace(db, { companyId, workspaceId });
|
||||||
reasons = inventory.sourceScopeUnproven && /^[a-z_]{1,60}$/.test(inventory.sourceScopeUnproven)
|
reasons = inventory.sourceScopeUnproven && /^[a-z_]{1,60}$/.test(inventory.sourceScopeUnproven)
|
||||||
? [...inventory.reasons, `source_scope_${inventory.sourceScopeUnproven}`] : inventory.reasons;
|
? [...inventory.reasons, `source_scope_${inventory.sourceScopeUnproven}`] : inventory.reasons;
|
||||||
|
reasons = [...reasons, ...(inventory.details ?? []).filter(item => /^[a-z_]{1,60}:[a-z_]{1,60}$/.test(item))];
|
||||||
if (!reasons.length) {
|
if (!reasons.length) {
|
||||||
const work = owners.migrateWorkspace({ db, storage, companyId, workspaceId, apply: true, signal,
|
const work = owners.migrateWorkspace({ db, storage, companyId, workspaceId, apply: true, signal,
|
||||||
sourceLockWaitMs: WORKSPACE_SOURCE_LOCK_WAIT_MS });
|
sourceLockWaitMs: WORKSPACE_SOURCE_LOCK_WAIT_MS });
|
||||||
|
|||||||
@@ -564,6 +564,66 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
|
|||||||
}
|
}
|
||||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(before);
|
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(before);
|
||||||
});
|
});
|
||||||
|
it.each(["finalized", "missing-receipt", "leased", "prepared"])("moves online past a settled finalizer that already saved its files, and names the rest (%s)", async mode => {
|
||||||
|
const f = await failedCopybackFixture();
|
||||||
|
const contractId = randomUUID(), resultId = randomUUID();
|
||||||
|
await db.insert(completionContracts).values({ id: contractId, companyId: f.companyId, issueId: f.issueId, revision: 1,
|
||||||
|
schemaVersion: "v1", policyVersion: "v1", risk: "low", completionAuthority: "agent", incompleteCriteriaPolicy: "block",
|
||||||
|
contractJson: {}, canonicalSha256: "12".repeat(32), createdByActorType: "system", createdByActorId: "test" });
|
||||||
|
const state = mode === "prepared" ? "prepared" : "finalized";
|
||||||
|
await db.update(heartbeatRuns).set({ status: "succeeded", completionContractId: contractId,
|
||||||
|
runnerProfileJson: { nativeWorkspaceSync: { ...f.reference, state, finalHostSha256: state === "finalized" ? "56".repeat(32) : null } } })
|
||||||
|
.where(eq(heartbeatRuns.id, f.runId));
|
||||||
|
await db.insert(nativeRunResults).values({ id: resultId, companyId: f.companyId, issueId: f.issueId, runId: f.runId,
|
||||||
|
completionContractId: contractId, serverFingerprint: "saved-result", schemaStatus: "accepted", resultJson: { saved: true }, canonicalSha256: "34".repeat(32) });
|
||||||
|
await db.update(nativeRunFinalizations).set({ phase: "retryable_failure", resultId,
|
||||||
|
...(mode === "leased" ? { leaseOwner: "live-finalizer", leaseExpiresAt: new Date(Date.now() + 60_000) } : {}) })
|
||||||
|
.where(eq(nativeRunFinalizations.runId, f.runId));
|
||||||
|
const operationId = randomUUID();
|
||||||
|
if (mode !== "missing-receipt") await db.insert(workspaceOperations).values({ id: operationId,
|
||||||
|
companyId: f.companyId, executionWorkspaceId: f.workspaceId, heartbeatRunId: f.runId, issueId: f.issueId,
|
||||||
|
phase: "workspace_finalize", status: "succeeded" });
|
||||||
|
const [before] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId));
|
||||||
|
const inventory = await inventoryRemoteWorkspaceMigration(db, f);
|
||||||
|
if (mode !== "finalized") {
|
||||||
|
expect(inventory).toMatchObject({ eligible: false, details: expect.arrayContaining([mode === "prepared" ? expect.any(String)
|
||||||
|
: `execution_finalization_unresolved:${mode === "leased" ? "finalizer_leased" : "sync_finalized_without_receipt"}`]) });
|
||||||
|
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow(/execution_finalization_unresolved|remote_copyback_unresolved/);
|
||||||
|
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
|
||||||
|
} else {
|
||||||
|
expect(inventory).toMatchObject({ eligible: true, reasons: [] });
|
||||||
|
await migrateRemoteWorkspace({ db, storage, ...f, apply: true });
|
||||||
|
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)?.snapshotId).toBeTruthy();
|
||||||
|
expect(await attemptNativeWorkspaceFinalization({ db, runId: f.runId }))
|
||||||
|
.toMatchObject({ kind: "completed", operation: { id: operationId } });
|
||||||
|
}
|
||||||
|
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(before);
|
||||||
|
});
|
||||||
|
it("refuses an online move when the finalizer takes its lease during the upload", async () => {
|
||||||
|
const f = await failedCopybackFixture();
|
||||||
|
await db.update(heartbeatRuns).set({ status: "succeeded",
|
||||||
|
runnerProfileJson: { nativeWorkspaceSync: { ...f.reference, state: "finalized", finalHostSha256: "56".repeat(32) } } })
|
||||||
|
.where(eq(heartbeatRuns.id, f.runId));
|
||||||
|
await db.update(nativeRunFinalizations).set({ phase: "observed" }).where(eq(nativeRunFinalizations.runId, f.runId));
|
||||||
|
await db.insert(workspaceOperations).values({ companyId: f.companyId, executionWorkspaceId: f.workspaceId, heartbeatRunId: f.runId,
|
||||||
|
issueId: f.issueId, phase: "workspace_finalize", status: "succeeded" });
|
||||||
|
const put = storage.putFile.bind(storage);
|
||||||
|
storage.putFile = async input => { const result = await put(input);
|
||||||
|
await db.update(nativeRunFinalizations).set({ leaseOwner: "late-finalizer", leaseExpiresAt: new Date(Date.now() + 60_000) })
|
||||||
|
.where(eq(nativeRunFinalizations.runId, f.runId)); return result; };
|
||||||
|
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("execution_finalization_unresolved");
|
||||||
|
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
|
||||||
|
});
|
||||||
|
it.each([["active_run_watchdog", "native_session_interrupted", {}, "active_run_watchdog"],
|
||||||
|
["stranded_assigned_issue", "native_workspace_sync_out_unrecoverable", {}, "stranded_assigned_issue_export_cause"],
|
||||||
|
["configuration_validation", "configuration_incomplete", { workspaceRecovery: { schema: "x" } }, "configuration_validation_file_evidence"],
|
||||||
|
] as const)("names the recovery kind that keeps an online move blocked (%s)", async (kind, cause, evidence, code) => {
|
||||||
|
const f = await seed();
|
||||||
|
await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId,
|
||||||
|
kind, cause, fingerprint: randomUUID(), nextAction: "Preserve unresolved recovery", evidence });
|
||||||
|
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false, reasons: ["workspace_recovery_unresolved"],
|
||||||
|
details: [`workspace_recovery_unresolved:${code}`] });
|
||||||
|
});
|
||||||
it("migrates historical records without borrowing another workspace's finalizer", async () => {
|
it("migrates historical records without borrowing another workspace's finalizer", async () => {
|
||||||
const f = await failedCopybackFixture(); vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true");
|
const f = await failedCopybackFixture(); vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true");
|
||||||
const otherId = randomUUID(), cwd = path.join(root, "longer-historical-folder"); await fs.mkdir(cwd);
|
const otherId = randomUUID(), cwd = path.join(root, "longer-historical-folder"); await fs.mkdir(cwd);
|
||||||
|
|||||||
@@ -109,20 +109,34 @@ async function assertArchivedRepositoryIntents(root: string, repositories: reado
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function recoveryState(recovery: { kind: string; cause: string; evidence: Record<string, unknown> }) {
|
||||||
|
if (isTaskDispositionRecovery(recovery)) return `${recovery.kind}_unrelated_task`;
|
||||||
|
if (!isTaskDispositionRecovery({ ...recovery, cause: "", evidence: {} })) return recovery.kind;
|
||||||
|
return workspaceExportCauses.includes(recovery.cause) ? `${recovery.kind}_export_cause` : `${recovery.kind}_file_evidence`;
|
||||||
|
}
|
||||||
|
|
||||||
async function inspect(db: ReadDb, input: { companyId: string; workspaceId: string; operationId?: string; writersStopped?: boolean; onlineSource?: OnlineWorkspaceSource; onlineSourceUnproven?: boolean }, cohort?: WorkspaceMigrationCohort) {
|
async function inspect(db: ReadDb, input: { companyId: string; workspaceId: string; operationId?: string; writersStopped?: boolean; onlineSource?: OnlineWorkspaceSource; onlineSourceUnproven?: boolean }, cohort?: WorkspaceMigrationCohort) {
|
||||||
const [workspace] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, input.workspaceId)));
|
const [workspace] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, input.companyId), eq(executionWorkspaces.id, input.workspaceId)));
|
||||||
if (!workspace) throw new Error("remote_workspace_migration_workspace_missing");
|
if (!workspace) throw new Error("remote_workspace_migration_workspace_missing");
|
||||||
const authority = readRemoteWorkspaceAuthority(workspace.metadata);
|
const authority = readRemoteWorkspaceAuthority(workspace.metadata);
|
||||||
const marker = object(workspace.metadata?.remoteWorkspaceMigration);
|
const marker = object(workspace.metadata?.remoteWorkspaceMigration);
|
||||||
const allowedOperation = input.operationId ?? (marker.schema === SCHEMA && typeof marker.operationId === "string" ? marker.operationId : undefined);
|
const allowedOperation = input.operationId ?? (marker.schema === SCHEMA && typeof marker.operationId === "string" ? marker.operationId : undefined);
|
||||||
const reasons: string[] = [];
|
const reasons: string[] = [], details: string[] = [];
|
||||||
if (authority) return { workspace, reasons, authority, marker, source: authority.source, issueBinding: null, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[] };
|
const detail = (reason: string, state: string) => {
|
||||||
|
reasons.push(reason);
|
||||||
|
details.push(`${reason}:${/^[a-z_]{1,60}$/.test(state) ? state : "unrecognized"}`);
|
||||||
|
};
|
||||||
|
if (authority) return { workspace, reasons, details, settledFinalizationRunIds: [] as string[], authority, marker, source: authority.source, issueBinding: null, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[] };
|
||||||
if (input.writersStopped) reasons.push(...await offlineWorkspaceMigrationBlockers(db));
|
if (input.writersStopped) reasons.push(...await offlineWorkspaceMigrationBlockers(db));
|
||||||
if (input.onlineSourceUnproven) reasons.push("online_workspace_source_scope_unproven");
|
if (input.onlineSourceUnproven) reasons.push("online_workspace_source_scope_unproven");
|
||||||
if (input.onlineSource) {
|
if (input.onlineSource) {
|
||||||
const currentScope = await inspectOnlineWorkspaceSource(db, workspace);
|
const currentScope = await inspectOnlineWorkspaceSource(db, workspace);
|
||||||
if (canonical(currentScope) !== canonical(input.onlineSource)) reasons.push("online_workspace_source_scope_changed");
|
if (canonical(currentScope) !== canonical(input.onlineSource)) reasons.push("online_workspace_source_scope_changed");
|
||||||
else reasons.push(...await onlineOrdinarySourceBlockers(db as Db, workspace.companyId, currentScope!, workspace, allowedOperation, cohort));
|
else for (const reason of await onlineOrdinarySourceBlockers(db as Db, workspace.companyId, currentScope!, workspace, allowedOperation, cohort)) {
|
||||||
|
if (reason === "workspace_recovery_unresolved") detail(reason, "sibling_task");
|
||||||
|
else if (reason === "execution_finalization_unresolved") detail(reason, "sibling_run");
|
||||||
|
else reasons.push(reason);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!["local_fs", "git_worktree"].includes(workspace.providerType)) reasons.push("workspace_provider_unsupported");
|
if (!["local_fs", "git_worktree"].includes(workspace.providerType)) reasons.push("workspace_provider_unsupported");
|
||||||
if (!["active", "idle", "in_review", "archived"].includes(workspace.status)) reasons.push("workspace_not_active");
|
if (!["active", "idle", "in_review", "archived"].includes(workspace.status)) reasons.push("workspace_not_active");
|
||||||
@@ -212,37 +226,42 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
|||||||
eq(nativeRunFinalizations.companyId, workspace.companyId), eq(nativeRunFinalizations.issueId, workspace.sourceIssueId),
|
eq(nativeRunFinalizations.companyId, workspace.companyId), eq(nativeRunFinalizations.issueId, workspace.sourceIssueId),
|
||||||
sql`${nativeRunFinalizations.phase} not in ('committed', 'terminal_failure')`,
|
sql`${nativeRunFinalizations.phase} not in ('committed', 'terminal_failure')`,
|
||||||
)) : [];
|
)) : [];
|
||||||
|
const settledFinalizationRunIds: string[] = [];
|
||||||
for (const row of finalizations) {
|
for (const row of finalizations) {
|
||||||
if (legacyRecoverySources.some(source => source.runId === row.id && source.unresolvedFinalization)) continue;
|
if (legacyRecoverySources.some(source => source.runId === row.id && source.unresolvedFinalization)) continue;
|
||||||
if (onlineRecoveryAllowed) {
|
if (onlineRecoveryAllowed) {
|
||||||
const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: row.id });
|
const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: row.id });
|
||||||
if (source) { legacyRecoverySources.push(source); continue; }
|
if (source) { legacyRecoverySources.push(source); continue; }
|
||||||
}
|
}
|
||||||
const stopped = input.writersStopped && row.run.runtimeMode === "native"
|
const native = row.run.runtimeMode === "native";
|
||||||
&& ["succeeded", "failed", "cancelled", "interrupted", "timed_out"].includes(row.run.status)
|
const ended = ["succeeded", "failed", "cancelled", "interrupted", "timed_out"].includes(row.run.status);
|
||||||
&& !(row.run.controllerLeaseExpiresAt && row.run.controllerLeaseExpiresAt > new Date())
|
const controllerLeased = Boolean(row.run.controllerLeaseExpiresAt && row.run.controllerLeaseExpiresAt > new Date());
|
||||||
&& !(row.leaseOwner && (!row.leaseExpiresAt || row.leaseExpiresAt > new Date()));
|
const finalizerLeased = Boolean(row.leaseOwner && (!row.leaseExpiresAt || row.leaseExpiresAt > new Date()));
|
||||||
|
const settled = native && ended && !controllerLeased && !finalizerLeased;
|
||||||
|
const stopped = Boolean(input.writersStopped) && settled;
|
||||||
const reference = readNativeWorkspaceSyncReference(row.run.runnerProfileJson?.nativeWorkspaceSync);
|
const reference = readNativeWorkspaceSyncReference(row.run.runnerProfileJson?.nativeWorkspaceSync);
|
||||||
// The finalizer retries from its operation receipt, not the sync descriptor.
|
// The finalizer retries from its operation receipt, not the sync descriptor.
|
||||||
// Without that receipt it would try exporting the newly migrated workspace,
|
// Without that receipt it would try exporting the newly migrated workspace,
|
||||||
// which intentionally has no live location. Keep the local authority until
|
// which intentionally has no live location. Keep the local authority until
|
||||||
// the existing owner records completion; then assessment/status can resume.
|
// the existing owner records completion; then assessment/status can resume.
|
||||||
if (stopped && reference?.state === "finalized") {
|
if (settled && reference?.state === "finalized") {
|
||||||
const [finalized] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and(
|
const [finalized] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and(
|
||||||
eq(workspaceOperations.companyId, workspace.companyId), eq(workspaceOperations.heartbeatRunId, row.id),
|
eq(workspaceOperations.companyId, workspace.companyId), eq(workspaceOperations.heartbeatRunId, row.id),
|
||||||
eq(workspaceOperations.issueId, row.run.nativeIssueId!), eq(workspaceOperations.phase, "workspace_finalize"),
|
eq(workspaceOperations.issueId, row.run.nativeIssueId!), eq(workspaceOperations.phase, "workspace_finalize"),
|
||||||
eq(workspaceOperations.status, "succeeded"),
|
eq(workspaceOperations.status, "succeeded"),
|
||||||
)).limit(1);
|
)).limit(1);
|
||||||
if (finalized) continue;
|
if (finalized) { settledFinalizationRunIds.push(row.id); continue; }
|
||||||
}
|
}
|
||||||
if (stopped && reference && reference.workspaceId !== workspace.id) {
|
if (settled && reference && reference.workspaceId !== workspace.id) {
|
||||||
const [other] = await db.select({ providerType: executionWorkspaces.providerType, cwd: executionWorkspaces.cwd,
|
const [other] = await db.select({ providerType: executionWorkspaces.providerType, cwd: executionWorkspaces.cwd,
|
||||||
sourceIssueId: executionWorkspaces.sourceIssueId, metadata: executionWorkspaces.metadata }).from(executionWorkspaces).where(and(
|
sourceIssueId: executionWorkspaces.sourceIssueId, metadata: executionWorkspaces.metadata }).from(executionWorkspaces).where(and(
|
||||||
eq(executionWorkspaces.companyId, workspace.companyId), eq(executionWorkspaces.id, reference.workspaceId)));
|
eq(executionWorkspaces.companyId, workspace.companyId), eq(executionWorkspaces.id, reference.workspaceId)));
|
||||||
// The offline batch must migrate every local record before the app can
|
// The offline batch must migrate every local record before the app can
|
||||||
// start. Another workspace's coordinator is checked with its own source.
|
// start. Another workspace's coordinator is checked with its own source.
|
||||||
if (other && ((other.cwd && ["local_fs", "git_worktree"].includes(other.providerType)) || readRemoteWorkspaceAuthority(other.metadata))
|
if (other && ((other.cwd && ["local_fs", "git_worktree"].includes(other.providerType)) || readRemoteWorkspaceAuthority(other.metadata))
|
||||||
&& await isLegacyWorkspaceTaskRelated(db, { companyId: workspace.companyId, issueId: row.run.nativeIssueId, sourceIssueId: other.sourceIssueId })) continue;
|
&& await isLegacyWorkspaceTaskRelated(db, { companyId: workspace.companyId, issueId: row.run.nativeIssueId, sourceIssueId: other.sourceIssueId })) {
|
||||||
|
settledFinalizationRunIds.push(row.id); continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (stopped && row.run.runnerProfileJson?.nativeWorkspaceSync == null && row.run.runnerProfileJson?.remoteWorkspace == null
|
if (stopped && row.run.runnerProfileJson?.nativeWorkspaceSync == null && row.run.runnerProfileJson?.remoteWorkspace == null
|
||||||
&& row.resultId === null && ["observed", "retryable_failure"].includes(row.phase)) {
|
&& row.resultId === null && ["observed", "retryable_failure"].includes(row.phase)) {
|
||||||
@@ -252,7 +271,11 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
|||||||
leaseExpiresAt: row.leaseExpiresAt?.toISOString() ?? null } });
|
leaseExpiresAt: row.leaseExpiresAt?.toISOString() ?? null } });
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
reasons.push("execution_finalization_unresolved");
|
detail("execution_finalization_unresolved", !native ? "not_native" : !ended ? `run_${row.run.status}` : controllerLeased ? "controller_leased"
|
||||||
|
: finalizerLeased ? "finalizer_leased" : reference?.state === "prepared" ? "sync_prepared"
|
||||||
|
: reference?.state === "finalized" ? "sync_finalized_without_receipt" : reference ? "sync_unrelated_workspace"
|
||||||
|
: row.run.runnerProfileJson?.remoteWorkspace != null ? "remote_run" : row.resultId !== null ? "result_recorded"
|
||||||
|
: ["observed", "retryable_failure"].includes(row.phase) ? "legacy_finalizer_needs_maintenance" : `phase_${row.phase}`);
|
||||||
}
|
}
|
||||||
legacyRecoverySources.sort((a, b) => a.runId.localeCompare(b.runId));
|
legacyRecoverySources.sort((a, b) => a.runId.localeCompare(b.runId));
|
||||||
const [operation] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and(
|
const [operation] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and(
|
||||||
@@ -289,7 +312,7 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
|||||||
for (const recovery of recoveries.sort((a, b) => a.id.localeCompare(b.id))) {
|
for (const recovery of recoveries.sort((a, b) => a.id.localeCompare(b.id))) {
|
||||||
if (onlineRecoveryAllowed) {
|
if (onlineRecoveryAllowed) {
|
||||||
const held = await inspectOnlineLegacyWorkspaceRecoveryHold(db, { workspace, recovery });
|
const held = await inspectOnlineLegacyWorkspaceRecoveryHold(db, { workspace, recovery });
|
||||||
if (!held) { reasons.push("workspace_recovery_unresolved"); continue; }
|
if (!held) { detail("workspace_recovery_unresolved", recoveryState(recovery)); continue; }
|
||||||
onlineRecoveryHolds.push({ actionId: recovery.id, ...held });
|
onlineRecoveryHolds.push({ actionId: recovery.id, ...held });
|
||||||
if (held.preparedSource && !legacyRecoverySources.some(source => source.runId === held.preparedSource!.runId))
|
if (held.preparedSource && !legacyRecoverySources.some(source => source.runId === held.preparedSource!.runId))
|
||||||
legacyRecoverySources.push(held.preparedSource);
|
legacyRecoverySources.push(held.preparedSource);
|
||||||
@@ -303,11 +326,11 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
|||||||
if (!input.writersStopped) {
|
if (!input.writersStopped) {
|
||||||
const held = isTaskDispositionRecovery(recovery) ? await inspectOnlineLegacyWorkspaceRecoveryHold(db, { workspace, recovery }) : null;
|
const held = isTaskDispositionRecovery(recovery) ? await inspectOnlineLegacyWorkspaceRecoveryHold(db, { workspace, recovery }) : null;
|
||||||
if (held && !held.finalizedHold && !held.preparedSource && !held.remoteHold) onlineRecoveryHolds.push({ actionId: recovery.id, ...held });
|
if (held && !held.finalizedHold && !held.preparedSource && !held.remoteHold) onlineRecoveryHolds.push({ actionId: recovery.id, ...held });
|
||||||
else reasons.push("workspace_recovery_unresolved");
|
else detail("workspace_recovery_unresolved", recoveryState(recovery));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (object(recovery.evidence?.systemRecovery).state === "running") {
|
if (object(recovery.evidence?.systemRecovery).state === "running") {
|
||||||
reasons.push("workspace_recovery_unresolved"); continue;
|
detail("workspace_recovery_unresolved", "system_recovery_running"); continue;
|
||||||
}
|
}
|
||||||
if (legacyRecoverySources.some(source => source.runId === recovery.evidence?.runId && source.reference?.state !== "finalized")) continue;
|
if (legacyRecoverySources.some(source => source.runId === recovery.evidence?.runId && source.reference?.state !== "finalized")) continue;
|
||||||
const held = await inspectFinalizedWorkspaceRecoveryHold(db, { companyId: workspace.companyId,
|
const held = await inspectFinalizedWorkspaceRecoveryHold(db, { companyId: workspace.companyId,
|
||||||
@@ -323,7 +346,7 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
|||||||
if (!["stranded_assigned_issue", "configuration_validation", "missing_disposition", "deliberate_wait_without_target"].includes(recovery.kind)
|
if (!["stranded_assigned_issue", "configuration_validation", "missing_disposition", "deliberate_wait_without_target"].includes(recovery.kind)
|
||||||
|| workspaceExportCauses.includes(recovery.cause)
|
|| workspaceExportCauses.includes(recovery.cause)
|
||||||
|| ["workspaceRestoreRecovery", "workspaceRecovery", "historicalWorkspaceSource", "systemRecovery", "nativeFailureBlock"]
|
|| ["workspaceRestoreRecovery", "workspaceRecovery", "historicalWorkspaceSource", "systemRecovery", "nativeFailureBlock"]
|
||||||
.some(key => recovery.evidence?.[key] != null)) reasons.push("workspace_recovery_unresolved");
|
.some(key => recovery.evidence?.[key] != null)) detail("workspace_recovery_unresolved", recoveryState(recovery));
|
||||||
}
|
}
|
||||||
legacyRecoverySources.sort((a, b) => a.runId.localeCompare(b.runId));
|
legacyRecoverySources.sort((a, b) => a.runId.localeCompare(b.runId));
|
||||||
const repositories = await db.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.companyId, workspace.companyId),
|
const repositories = await db.select().from(executionWorkspaceRepositories).where(and(eq(executionWorkspaceRepositories.companyId, workspace.companyId),
|
||||||
@@ -338,7 +361,7 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
|||||||
const materialized = repositories.filter(repository => repository.state === "ready");
|
const materialized = repositories.filter(repository => repository.state === "ready");
|
||||||
if (materialized.length) source.repositories = materialized.map(repository => ({ id: repository.id, relativePath: repository.relativePath,
|
if (materialized.length) source.repositories = materialized.map(repository => ({ id: repository.id, relativePath: repository.relativePath,
|
||||||
repoUrl: repository.repoUrl, ref: repository.requestedRef, ...(repository.pinnedCommit ? { pinnedCommit: repository.pinnedCommit } : {}) }));
|
repoUrl: repository.repoUrl, ref: repository.requestedRef, ...(repository.pinnedCommit ? { pinnedCommit: repository.pinnedCommit } : {}) }));
|
||||||
return { workspace, reasons: [...new Set(reasons)], authority, marker, source, issueBinding: issue?.executionWorkspaceId ?? null, retainedDirectory, archivedGitSource, legacyRecoverySources, finalizedRecoveryHolds, onlineRecoveryHolds, archivedRepositoryIntents };
|
return { workspace, reasons: [...new Set(reasons)], details: [...new Set(details)].sort(), settledFinalizationRunIds: settledFinalizationRunIds.sort(), authority, marker, source, issueBinding: issue?.executionWorkspaceId ?? null, retainedDirectory, archivedGitSource, legacyRecoverySources, finalizedRecoveryHolds, onlineRecoveryHolds, archivedRepositoryIntents };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function inventoryRemoteWorkspaceMigration(db: Db, input: { companyId: string; workspaceId: string; writersStopped?: boolean }) {
|
export async function inventoryRemoteWorkspaceMigration(db: Db, input: { companyId: string; workspaceId: string; writersStopped?: boolean }) {
|
||||||
@@ -350,6 +373,7 @@ export async function inventoryRemoteWorkspaceMigration(db: Db, input: { company
|
|||||||
const result = await inspect(db, { ...input, onlineSource, onlineSourceUnproven });
|
const result = await inspect(db, { ...input, onlineSource, onlineSourceUnproven });
|
||||||
return { companyId: input.companyId, workspaceId: input.workspaceId, eligible: result.reasons.length === 0,
|
return { companyId: input.companyId, workspaceId: input.workspaceId, eligible: result.reasons.length === 0,
|
||||||
...(onlineSourceUnproven && explained && "unproven" in explained ? { sourceScopeUnproven: explained.unproven } : {}),
|
...(onlineSourceUnproven && explained && "unproven" in explained ? { sourceScopeUnproven: explained.unproven } : {}),
|
||||||
|
...(result.details.length ? { details: result.details } : {}),
|
||||||
alreadyMigrated: Boolean(result.authority), reasons: result.reasons, localPath: result.workspace.cwd ?? result.workspace.providerRef,
|
alreadyMigrated: Boolean(result.authority), reasons: result.reasons, localPath: result.workspace.cwd ?? result.workspace.providerRef,
|
||||||
source: result.source, operationId: typeof result.marker.operationId === "string" ? result.marker.operationId : null,
|
source: result.source, operationId: typeof result.marker.operationId === "string" ? result.marker.operationId : null,
|
||||||
snapshotId: result.authority?.snapshotId ?? null };
|
snapshotId: result.authority?.snapshotId ?? null };
|
||||||
@@ -395,7 +419,7 @@ async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWork
|
|||||||
if (!workspace) throw new Error("remote_workspace_migration_workspace_missing");
|
if (!workspace) throw new Error("remote_workspace_migration_workspace_missing");
|
||||||
if (workspace.sourceIssueId !== selected.sourceIssueId) throw new Error("remote_workspace_migration_source_changed");
|
if (workspace.sourceIssueId !== selected.sourceIssueId) throw new Error("remote_workspace_migration_source_changed");
|
||||||
const current = await inspect(tx as unknown as Db, { ...input, onlineSource }, cohort);
|
const current = await inspect(tx as unknown as Db, { ...input, onlineSource }, cohort);
|
||||||
if (current.authority) return { workspace, authority: current.authority, operation: null, source: current.source, sourceFingerprint: "", issueBinding: current.issueBinding, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[] };
|
if (current.authority) return { workspace, authority: current.authority, operation: null, source: current.source, sourceFingerprint: "", issueBinding: current.issueBinding, retainedDirectory: null, archivedGitSource: null, legacyRecoverySources: [] as LegacyWorkspaceRecoverySource[], finalizedRecoveryHolds: [] as FinalizedWorkspaceRecoveryHold[], onlineRecoveryHolds: [] as OnlineRecoveryHold[], archivedRepositoryIntents: [] as RepositoryRequest[], settledFinalizationRunIds: [] as string[] };
|
||||||
if (current.reasons.length) throw new Error(`remote_workspace_migration_blocked:${current.reasons.join(",")}`);
|
if (current.reasons.length) throw new Error(`remote_workspace_migration_blocked:${current.reasons.join(",")}`);
|
||||||
const nativeSessionContinuity = await inspectNativeWorkspaceMigration(tx as unknown as Db, workspace);
|
const nativeSessionContinuity = await inspectNativeWorkspaceMigration(tx as unknown as Db, workspace);
|
||||||
const source = remoteWorkspaceSourceSchema.parse(input.source ?? current.source);
|
const source = remoteWorkspaceSourceSchema.parse(input.source ?? current.source);
|
||||||
@@ -422,7 +446,7 @@ async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWork
|
|||||||
if (canonical(operation.metadata?.onlineRecoveryHolds ?? []) !== canonical(current.onlineRecoveryHolds)) throw new Error("remote_workspace_migration_source_changed");
|
if (canonical(operation.metadata?.onlineRecoveryHolds ?? []) !== canonical(current.onlineRecoveryHolds)) throw new Error("remote_workspace_migration_source_changed");
|
||||||
if (canonical(operation.metadata?.archivedRepositoryIntents ?? []) !== canonical(repositoryIntentBindings(current.archivedRepositoryIntents)))
|
if (canonical(operation.metadata?.archivedRepositoryIntents ?? []) !== canonical(repositoryIntentBindings(current.archivedRepositoryIntents)))
|
||||||
throw new Error("remote_workspace_migration_source_changed");
|
throw new Error("remote_workspace_migration_source_changed");
|
||||||
return { workspace, authority: null, operation, source, sourceFingerprint, issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents };
|
return { workspace, authority: null, operation, source, sourceFingerprint, issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents, settledFinalizationRunIds: current.settledFinalizationRunIds };
|
||||||
}
|
}
|
||||||
let migrationSupersession;
|
let migrationSupersession;
|
||||||
if (workspace.metadata?.remoteWorkspaceMigrationSupersession != null) {
|
if (workspace.metadata?.remoteWorkspaceMigrationSupersession != null) {
|
||||||
@@ -450,7 +474,7 @@ async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWork
|
|||||||
await tx.update(executionWorkspaces).set({ metadata: { ...workspace.metadata, remoteWorkspaceMigration: {
|
await tx.update(executionWorkspaces).set({ metadata: { ...workspace.metadata, remoteWorkspaceMigration: {
|
||||||
schema: SCHEMA, operationId: operation!.id, state: "running", sourceFingerprint, source,
|
schema: SCHEMA, operationId: operation!.id, state: "running", sourceFingerprint, source,
|
||||||
} }, updatedAt: new Date() }).where(eq(executionWorkspaces.id, workspace.id));
|
} }, updatedAt: new Date() }).where(eq(executionWorkspaces.id, workspace.id));
|
||||||
return { workspace, authority: null, operation: operation!, source, sourceFingerprint, issueBinding: current.issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents };
|
return { workspace, authority: null, operation: operation!, source, sourceFingerprint, issueBinding: current.issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds, archivedRepositoryIntents: current.archivedRepositoryIntents, settledFinalizationRunIds: current.settledFinalizationRunIds };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
type ReservedMigration = Awaited<ReturnType<typeof reserveMigration>>;
|
type ReservedMigration = Awaited<ReturnType<typeof reserveMigration>>;
|
||||||
@@ -626,7 +650,7 @@ async function validateMigrationPublication(tx: MigrationTransaction, input: Mig
|
|||||||
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, actionId))).for("update", { noWait: true });
|
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, actionId))).for("update", { noWait: true });
|
||||||
}
|
}
|
||||||
const protectedRunIds = [...new Set([...reserved.legacyRecoverySources.map(source => source.runId),
|
const protectedRunIds = [...new Set([...reserved.legacyRecoverySources.map(source => source.runId),
|
||||||
...reserved.finalizedRecoveryHolds.map(held => held.runId)])].sort();
|
...reserved.finalizedRecoveryHolds.map(held => held.runId), ...reserved.settledFinalizationRunIds])].sort();
|
||||||
for (const runId of protectedRunIds) {
|
for (const runId of protectedRunIds) {
|
||||||
await tx.select({ id: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
await tx.select({ id: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||||
.where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, runId))).for("update", { noWait: true });
|
.where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, runId))).for("update", { noWait: true });
|
||||||
|
|||||||
Reference in new issue
Block a user