mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
fix(workspaces): name online recovery and finalizer blockers, and move settled finalizers online as offline does (#22696)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted server moves each local workspace to shared storage in
bounded online passes while it serves work
> - Staging passes now leave workspaces with
`workspace_recovery_unresolved` (15 on one stack) and
`execution_finalization_unresolved` (3 on another)
> - The pass does not say which recovery kind or which finalizer state
blocks, so nobody can tell a safe case from a real one
> - The offline move also lets a settled native run past when its files
are already saved, but the online move refuses every unsettled finalizer
> - This pull request names the recovery kind and the finalizer state,
and lets the online move do what the offline move does for settled
finalizers that cannot touch the workspace
> - The benefit is fewer blocked moves and an exact cause for each one
that stays blocked
## Linked Issues or Issue Description
Refs #22644, #22650
**What happened?**
After repeated online passes on staging, one stack reports
`workspaces:workspace_recovery_unresolved` for 15 workspaces and another
reports `workspaces:execution_finalization_unresolved` for 3. The codes
do not say which recovery kind or which finalizer state is the cause.
For finalizers, the online move refuses every finalizer that is not
committed, even when the offline move would move the workspace.
**Expected behavior**
Each blocked workspace names the recovery kind or the finalizer state.
The online move accepts a settled finalizer in the same cases as the
offline move, when the finalizer cannot write to this workspace.
**Steps to reproduce**
1. Create a local workspace. Settle a native run on its task with a
finalized sync descriptor and a succeeded `workspace_finalize`
operation. Leave the finalizer in `retryable_failure` with no lease.
2. Run the online move. It fails with
`execution_finalization_unresolved`. The offline move of the same
workspace succeeds.
## What Changed
- Inventory returns `details`, for example
`workspace_recovery_unresolved:active_run_watchdog` or
`execution_finalization_unresolved:finalizer_leased`. The `reasons` list
does not change. The online pass reports each detail as
`workspaces:<reason>:<state>`.
- Recovery states: the action kind; `<kind>_export_cause` or
`<kind>_file_evidence` for a task-only kind that carries a workspace
export cause or file evidence; `<kind>_unrelated_task`;
`system_recovery_running`; `sibling_task` for an action on another task
in the same proven Git source.
- Finalizer states: `not_native`, `run_<status>`, `controller_leased`,
`finalizer_leased`, `sync_other_workspace`, `sync_prepared`,
`sync_finalized_without_receipt`, `remote_run`, `result_recorded`,
`legacy_finalizer_needs_maintenance`, `phase_<phase>`, and
`sibling_run`.
- A settled native run (ended, no live controller lease, no live
finalizer lease) no longer blocks the online move when its sync
descriptor is finalized and its `workspace_finalize` operation
succeeded. The offline move already accepts this case. The finalizer
retries from that receipt and does not touch this workspace.
- A settled run whose descriptor names another workspace of the task
stays blocked online as `sync_other_workspace`. The finalizer selects
the task's current workspace before the descriptor, so it could not save
the other workspace after this one moved. Only the offline batch, which
moves every local record, accepts it.
- Publication locks the finalizer and run rows of these runs (`FOR
UPDATE NOWAIT`) and inspects again. A finalizer that takes a lease
during the upload makes publication refuse.
- No change for the other states. A finalizer that is still running or
leased, a prepared descriptor, a finalized descriptor without a receipt,
a recorded result and a remote run stay blocked, as offline. A legacy
finalizer without a descriptor stays blocked online: the offline move
adopts it only because the maintenance fence stopped the old controller,
and it then releases the coordinator lease.
## Verification
- `cd server && npx vitest run
src/services/remote-workspace-migration.test.ts
src/services/remote-workspace-online-source.test.ts
src/services/remote-workspace-cohort-migration.test.ts
src/services/workspace-git-source-roots.test.ts
src/services/online-durable-data-migration.test.ts
src/services/online-durable-data-migration-postgres.test.ts
src/services/finalized-workspace-recovery-migration.test.ts
src/services/online-remote-workspace-recovery-hold.test.ts
src/services/online-legacy-workspace-recovery.test.ts` (embedded
PostgreSQL): 9 files, 473 of 474 passed. The one failure was a 15 s
timeout of `preserves archived Git edits or refuses an unavailable
restore point (nested-linked)` under the full parallel run. It passes
when run alone (19 of 19 for that group), and this change does not touch
that path.
- Red/green: 8 new tests fail on `origin/master` and pass with this
change: the online settled-finalizer move (`finalized`), the three named
blocked finalizer states (`missing-receipt`, `leased`, `prepared`), and
the three named recovery kinds, and the other-workspace run that stays
blocked (it moved on 415941f). A new test that takes the finalizer lease
during the upload checks that publication refuses.
- New pass test: details become `workspaces:<reason>:<state>` keys and
unsafe text is dropped.
- `pnpm --filter @paperclipai/server typecheck`: passed.
## Risks
- The online move now proceeds past one settled finalizer state, which
the offline move already accepts. Publication locks and rechecks the
finalizer, so a finalizer that resumes during the upload stops
publication.
- The offline publication also locks these settled runs now. With
writers stopped, nothing else holds those rows.
- The pass result gets new `workspaces:<reason>:<state>` keys.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.
## 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
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a00e31967b
commit
980caf1167
4 files changed
+130
-21
No files matched your search
@@ -385,6 +385,19 @@ describe("online durable-data migration pass", () => {
|
||||
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 () => {
|
||||
const migrateWorkspace = vi.fn(async () => ({ alreadyMigrated: true, reasons: [] }));
|
||||
const fixture = owners({ localWorkspaces: async () => [workspace(1)], migrateWorkspace });
|
||||
|
||||
@@ -43,7 +43,7 @@ type Owners = {
|
||||
workspaceCompanies: typeof listLocalWorkspaceCompanies;
|
||||
workspaceOperations: (db: Db, input: { companyId: string; signal: AbortSignal }) => Promise<{ reconciled: number; held: Array<{ reason: string }> }>;
|
||||
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;
|
||||
signal: AbortSignal; sourceLockWaitMs: number }) => Promise<{ alreadyMigrated: boolean; reasons: string[] }>;
|
||||
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 });
|
||||
reasons = inventory.sourceScopeUnproven && /^[a-z_]{1,60}$/.test(inventory.sourceScopeUnproven)
|
||||
? [...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) {
|
||||
const work = owners.migrateWorkspace({ db, storage, companyId, workspaceId, apply: true, signal,
|
||||
sourceLockWaitMs: WORKSPACE_SOURCE_LOCK_WAIT_MS });
|
||||
|
||||
@@ -564,6 +564,77 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
|
||||
}
|
||||
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([`execution_finalization_unresolved:${
|
||||
mode === "leased" ? "finalizer_leased" : mode === "prepared" ? "sync_prepared" : "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("keeps an online move blocked while a settled run still has to save another workspace of the task", async () => {
|
||||
const f = await failedCopybackFixture(), otherId = randomUUID(), cwd = path.join(root, "other-run-workspace"); await fs.mkdir(cwd);
|
||||
await db.insert(executionWorkspaces).values({ id: otherId, companyId: f.companyId, sourceIssueId: f.issueId,
|
||||
name: "Run workspace", mode: "isolated_workspace", strategyType: "project_primary", providerType: "local_fs", cwd });
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded",
|
||||
runnerProfileJson: { nativeWorkspaceSync: { ...f.reference, workspaceId: otherId, state: "prepared" } } }).where(eq(heartbeatRuns.id, f.runId));
|
||||
await db.update(nativeRunFinalizations).set({ phase: "observed" }).where(eq(nativeRunFinalizations.runId, f.runId));
|
||||
expect(await inventoryRemoteWorkspaceMigration(db, f)).toMatchObject({ eligible: false,
|
||||
details: expect.arrayContaining(["execution_finalization_unresolved:sync_other_workspace"]) });
|
||||
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("execution_finalization_unresolved");
|
||||
});
|
||||
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 () => {
|
||||
const f = await failedCopybackFixture(); vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true");
|
||||
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) {
|
||||
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");
|
||||
const authority = readRemoteWorkspaceAuthority(workspace.metadata);
|
||||
const marker = object(workspace.metadata?.remoteWorkspaceMigration);
|
||||
const allowedOperation = input.operationId ?? (marker.schema === SCHEMA && typeof marker.operationId === "string" ? marker.operationId : undefined);
|
||||
const reasons: 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 reasons: string[] = [], details: string[] = [];
|
||||
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.onlineSourceUnproven) reasons.push("online_workspace_source_scope_unproven");
|
||||
if (input.onlineSource) {
|
||||
const currentScope = await inspectOnlineWorkspaceSource(db, workspace);
|
||||
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 (!["active", "idle", "in_review", "archived"].includes(workspace.status)) reasons.push("workspace_not_active");
|
||||
@@ -212,28 +226,31 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
||||
eq(nativeRunFinalizations.companyId, workspace.companyId), eq(nativeRunFinalizations.issueId, workspace.sourceIssueId),
|
||||
sql`${nativeRunFinalizations.phase} not in ('committed', 'terminal_failure')`,
|
||||
)) : [];
|
||||
const settledFinalizationRunIds: string[] = [];
|
||||
for (const row of finalizations) {
|
||||
if (legacyRecoverySources.some(source => source.runId === row.id && source.unresolvedFinalization)) continue;
|
||||
if (onlineRecoveryAllowed) {
|
||||
const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: row.id });
|
||||
if (source) { legacyRecoverySources.push(source); continue; }
|
||||
}
|
||||
const stopped = input.writersStopped && row.run.runtimeMode === "native"
|
||||
&& ["succeeded", "failed", "cancelled", "interrupted", "timed_out"].includes(row.run.status)
|
||||
&& !(row.run.controllerLeaseExpiresAt && row.run.controllerLeaseExpiresAt > new Date())
|
||||
&& !(row.leaseOwner && (!row.leaseExpiresAt || row.leaseExpiresAt > new Date()));
|
||||
const native = row.run.runtimeMode === "native";
|
||||
const ended = ["succeeded", "failed", "cancelled", "interrupted", "timed_out"].includes(row.run.status);
|
||||
const controllerLeased = Boolean(row.run.controllerLeaseExpiresAt && row.run.controllerLeaseExpiresAt > 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);
|
||||
// The finalizer retries from its operation receipt, not the sync descriptor.
|
||||
// Without that receipt it would try exporting the newly migrated workspace,
|
||||
// which intentionally has no live location. Keep the local authority until
|
||||
// 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(
|
||||
eq(workspaceOperations.companyId, workspace.companyId), eq(workspaceOperations.heartbeatRunId, row.id),
|
||||
eq(workspaceOperations.issueId, row.run.nativeIssueId!), eq(workspaceOperations.phase, "workspace_finalize"),
|
||||
eq(workspaceOperations.status, "succeeded"),
|
||||
)).limit(1);
|
||||
if (finalized) continue;
|
||||
if (finalized) { settledFinalizationRunIds.push(row.id); continue; }
|
||||
}
|
||||
if (stopped && reference && reference.workspaceId !== workspace.id) {
|
||||
const [other] = await db.select({ providerType: executionWorkspaces.providerType, cwd: executionWorkspaces.cwd,
|
||||
@@ -242,7 +259,9 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
||||
// The offline batch must migrate every local record before the app can
|
||||
// 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))
|
||||
&& 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
|
||||
&& 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 } });
|
||||
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 && reference.workspaceId !== workspace.id ? "sync_other_workspace"
|
||||
: reference?.state === "prepared" ? "sync_prepared" : reference ? "sync_finalized_without_receipt"
|
||||
: 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));
|
||||
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))) {
|
||||
if (onlineRecoveryAllowed) {
|
||||
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 });
|
||||
if (held.preparedSource && !legacyRecoverySources.some(source => source.runId === held.preparedSource!.runId))
|
||||
legacyRecoverySources.push(held.preparedSource);
|
||||
@@ -303,11 +326,11 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
|
||||
if (!input.writersStopped) {
|
||||
const held = isTaskDispositionRecovery(recovery) ? await inspectOnlineLegacyWorkspaceRecoveryHold(db, { workspace, recovery }) : null;
|
||||
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;
|
||||
}
|
||||
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;
|
||||
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)
|
||||
|| workspaceExportCauses.includes(recovery.cause)
|
||||
|| ["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));
|
||||
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");
|
||||
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 } : {}) }));
|
||||
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 }) {
|
||||
@@ -350,6 +373,7 @@ export async function inventoryRemoteWorkspaceMigration(db: Db, input: { company
|
||||
const result = await inspect(db, { ...input, onlineSource, onlineSourceUnproven });
|
||||
return { companyId: input.companyId, workspaceId: input.workspaceId, eligible: result.reasons.length === 0,
|
||||
...(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,
|
||||
source: result.source, operationId: typeof result.marker.operationId === "string" ? result.marker.operationId : 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.sourceIssueId !== selected.sourceIssueId) throw new Error("remote_workspace_migration_source_changed");
|
||||
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(",")}`);
|
||||
const nativeSessionContinuity = await inspectNativeWorkspaceMigration(tx as unknown as Db, workspace);
|
||||
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?.archivedRepositoryIntents ?? []) !== canonical(repositoryIntentBindings(current.archivedRepositoryIntents)))
|
||||
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;
|
||||
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: {
|
||||
schema: SCHEMA, operationId: operation!.id, state: "running", sourceFingerprint, source,
|
||||
} }, 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>>;
|
||||
@@ -626,7 +650,7 @@ async function validateMigrationPublication(tx: MigrationTransaction, input: Mig
|
||||
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, actionId))).for("update", { noWait: true });
|
||||
}
|
||||
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) {
|
||||
await tx.select({ id: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||
.where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, runId))).for("update", { noWait: true });
|
||||
|
||||
Reference in new issue
Block a user