From ffb300e22a4101a94feab25d04cd7b38d2952818 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:50:27 -0600 Subject: [PATCH] fix(cloud): name a failed durable-data check instead of answering the eligibility read with 500 (#22646) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A hosted server moves from a volume to a volume-free shape without an outage > - Before the move, Cloud reads `GET /api/instance/ephemeral-enrollment/eligibility`, and the stack moves only when the read has no blockers > - On two staging stacks the read answers HTTP 500, so Cloud shows only "eligibility unavailable: HTTP 500" > - Each durable-data check in the read can throw, and one throw fails the whole read without a reason > - This pull request makes each check that throws report a named blocker with the owner's code > - The benefit is that a stack that cannot move always says which check stopped it and why ## Linked Issues or Issue Description Refs #22240, #22294, #22337 **What happened?** On current Core, the eligibility read answers HTTP 500 for some hosted stacks. The online durable-data pass also fails, because it reads the same eligibility at the end of each pass. **Expected behavior** The read always answers. When a check cannot finish, the read reports a named blocker, and the move stays blocked. **Steps to reproduce** 1. Keep a failed Runner run whose session is selected and whose local controller file has a second hard link (or another source that the controller check refuses, such as an execution input that no longer parses). 2. Call `readOnlineEphemeralEnrollmentEligibility`. 3. See that it throws `native_controller_migration_unsafe_source`. The route answers 500. **Additional context** Every check in `readEphemeralServerDataEligibility` can throw: the native controller scan reads files and parses saved execution input, the harness scan reads files, and the other checks query the database. The controller scan is the first one that throws on old Runner state. ## What Changed - `readEphemeralServerDataEligibility` runs each check through one guard. A check that throws adds `_check_failed`, plus `:` when the error message is a code such as `native_controller_migration_unsafe_source`. The guard logs the error. - The same blockers reach the startup gate, the offline migration and online preparation. Each of them still refuses, as before, but now with the named blocker instead of the raw error. ## Verification - Red: `cd server && npx vitest run src/services/native-runtime/native-controller-migration.integration.test.ts -t eligibility_unreadable` failed with `Error: native_controller_migration_unsafe_source` thrown from `readEphemeralServerDataEligibility` (embedded PostgreSQL, real controller file with a second hard link). - Green: the same test passes. The read returns `native_controllers_check_failed:native_controller_migration_unsafe_source`, the online read returns `eligible: false` with that blocker, and the controller file is unchanged. - `npx vitest run src/__tests__/ephemeral-server-data.test.ts src/services/ephemeral-enrollment.test.ts src/__tests__/runtime-skill-preservation.test.ts` and the `volume_free_owner` controller scenario pass. - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify` result is in a comment below. ## Risks - Low risk. A check that throws still blocks the move, the startup gate and the offline migration. Only the shape of the refusal changes: a named blocker instead of an exception. - Cloud receives new blocker names of the form `_check_failed[:code]`. Cloud shows unknown blockers as they are and does not move the stack. > 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 --- .../src/services/ephemeral-server-contract.ts | 93 ++++++++++++------- ...e-controller-migration.integration.test.ts | 26 +++++- 2 files changed, 85 insertions(+), 34 deletions(-) diff --git a/server/src/services/ephemeral-server-contract.ts b/server/src/services/ephemeral-server-contract.ts index 629bf01b026..7c0bc6107b7 100644 --- a/server/src/services/ephemeral-server-contract.ts +++ b/server/src/services/ephemeral-server-contract.ts @@ -120,39 +120,70 @@ export async function assertEphemeralServerData(db: Db) { throw new Error(`Volume-free server data is not eligible: ${blockers.map(detail).join(", ")}`); } +const failedCheckCode = (error: unknown) => { + const message = error instanceof Error ? error.message : ""; + if (/^[a-z_]{1,80}$/.test(message)) return `:${message}`; + if (error instanceof SyntaxError) return ":invalid_source_json"; + const errno = (error as { code?: unknown } | null)?.code; + return typeof errno === "string" && /^E[A-Z]{2,20}$/.test(errno) ? `:source_${errno.toLowerCase()}` : ""; +}; + export async function readEphemeralServerDataEligibility(db: Db, options: { purpose?: "migration" | "startup" } = {}) { const blockers: string[] = []; - const [missingFiles] = await db.select({ id: agents.id }).from(agents).leftJoin(agentFileRoots, - and(eq(agentFileRoots.companyId, agents.companyId), eq(agentFileRoots.agentId, agents.id))) - .where(isNull(agentFileRoots.agentId)).limit(1); - if (missingFiles) blockers.push("agent_files_require_migration"); - if (await hasUnsettledLocalInstructionCopies(db)) blockers.push("local_instruction_copies_require_settlement"); + const check = async (area: string, blocker: string, inspect: () => Promise) => { + try { + if (await inspect()) blockers.push(blocker); + } catch (error) { + logger.warn({ err: error, blocker }, "Volume-free data eligibility check failed"); + blockers.push(`${area}_check_failed${failedCheckCode(error)}`); + } + }; + await check("agent_files", "agent_files_require_migration", async () => { + const [missingFiles] = await db.select({ id: agents.id }).from(agents).leftJoin(agentFileRoots, + and(eq(agentFileRoots.companyId, agents.companyId), eq(agentFileRoots.agentId, agents.id))) + .where(isNull(agentFileRoots.agentId)).limit(1); + return Boolean(missingFiles); + }); + await check("local_instruction_copies", "local_instruction_copies_require_settlement", () => hasUnsettledLocalInstructionCopies(db)); // Only inspect configuration here; filesystem reads must never adopt an // empty directory on the replacement machine as the old server's content. - const configured = await db.select({ id: agents.id, companyId: agents.companyId, name: agents.name, adapterConfig: agents.adapterConfig }).from(agents); - if (configured.some(agent => agentInstructionsBundleMode(agent) === "external")) blockers.push("external_agent_instructions"); - const [localWorkspace] = await db.select({ id: executionWorkspaces.id }).from(executionWorkspaces) - .where(localWorkspaceDependencyWhere(db)).limit(1); - if (localWorkspace) blockers.push("workspaces_require_migration"); - const [localLog] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( - eq(heartbeatRuns.logStore, "local_file"), isNotNull(heartbeatRuns.logRef), - )).limit(1); - if (localLog) blockers.push("run_logs_require_migration"); - const [localTrace] = await db.select({ id: providerTraceRecords.id }).from(providerTraceRecords).where(and( - isNull(providerTraceRecords.deletedAt), sql`${providerTraceRecords.traceRef} not like 's3-segments-v1:%'`, - )).limit(1); - if (localTrace) blockers.push("provider_traces_require_migration"); - if (await hasLocalNativeHarnessObligations(db)) blockers.push("native_harness_backups_require_migration"); - const controller = await findLocalNativeControllerObligation(db); - if (controller) blockers.push("native_controllers_require_migration"); - if (await hasLocalRuntimeSkillObligations(db)) blockers.push(RUNTIME_SKILL_ASSETS_BLOCKER); - const skills = skillInstallationMaintenance(db); - let after: string | undefined; - for (;;) { - const page = await skills.eligibility({ after, limit: 50, purpose: options.purpose }); - if (page.results.some(skill => skill.status !== "version_backed")) { blockers.push("skills_require_migration"); break; } - if (page.inspected < 50 || !page.after) break; - after = page.after; - } - return { eligible: blockers.length === 0, blockers, controller }; + await check("agent_instructions", "external_agent_instructions", async () => { + const configured = await db.select({ id: agents.id, companyId: agents.companyId, name: agents.name, adapterConfig: agents.adapterConfig }).from(agents); + return configured.some(agent => agentInstructionsBundleMode(agent) === "external"); + }); + await check("workspaces", "workspaces_require_migration", async () => { + const [localWorkspace] = await db.select({ id: executionWorkspaces.id }).from(executionWorkspaces) + .where(localWorkspaceDependencyWhere(db)).limit(1); + return Boolean(localWorkspace); + }); + await check("run_logs", "run_logs_require_migration", async () => { + const [localLog] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.logStore, "local_file"), isNotNull(heartbeatRuns.logRef), + )).limit(1); + return Boolean(localLog); + }); + await check("provider_traces", "provider_traces_require_migration", async () => { + const [localTrace] = await db.select({ id: providerTraceRecords.id }).from(providerTraceRecords).where(and( + isNull(providerTraceRecords.deletedAt), sql`${providerTraceRecords.traceRef} not like 's3-segments-v1:%'`, + )).limit(1); + return Boolean(localTrace); + }); + await check("native_harness_backups", "native_harness_backups_require_migration", () => hasLocalNativeHarnessObligations(db)); + const found: { controller: Awaited> } = { controller: null }; + await check("native_controllers", "native_controllers_require_migration", async () => { + found.controller = await findLocalNativeControllerObligation(db); + return Boolean(found.controller); + }); + await check("runtime_skill_assets", RUNTIME_SKILL_ASSETS_BLOCKER, () => hasLocalRuntimeSkillObligations(db)); + await check("skills", "skills_require_migration", async () => { + const skills = skillInstallationMaintenance(db); + let after: string | undefined; + for (;;) { + const page = await skills.eligibility({ after, limit: 50, purpose: options.purpose }); + if (page.results.some(skill => skill.status !== "version_backed")) return true; + if (page.inspected < 50 || !page.after) return false; + after = page.after; + } + }); + return { eligible: blockers.length === 0, blockers, controller: found.controller }; } diff --git a/server/src/services/native-runtime/native-controller-migration.integration.test.ts b/server/src/services/native-runtime/native-controller-migration.integration.test.ts index bebd6db2bf9..84984a33168 100644 --- a/server/src/services/native-runtime/native-controller-migration.integration.test.ts +++ b/server/src/services/native-runtime/native-controller-migration.integration.test.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { chmod, link, mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { and, eq } from "drizzle-orm"; import { afterEach, expect, it, vi } from "vitest"; @@ -25,9 +25,10 @@ import { createStorageService } from "../../storage/service.js"; import { legacyNativeControllerArchive } from "./native-controller-archive.js"; import { restoreDurableNativeHarnessBackup } from "./native-harness-backup-storage.js"; import { claimVolumeFreeControllerState } from "./volume-free-controller-state.js"; -import { assertEphemeralServerData } from "../ephemeral-server-contract.js"; +import { assertEphemeralServerData, readEphemeralServerDataEligibility } from "../ephemeral-server-contract.js"; +import { readOnlineEphemeralEnrollmentEligibility } from "../ephemeral-enrollment.js"; -describeEmbeddedPostgres.each(["volume_free_owner", "archive_online", "archive_online_owned", "archive_online_changed", "archive_online_commit", "archive_online_active", "archive_online_foreign", +describeEmbeddedPostgres.each(["volume_free_owner", "eligibility_unreadable", "archive_online", "archive_online_owned", "archive_online_changed", "archive_online_commit", "archive_online_active", "archive_online_foreign", "active_warm", "source_scan", "active_durable", "active_durable_cold", "online_success", "online_owned", "online_same_source", "online_busy", "online_changed", "online_evidence", "import", "archive", "success", "batch", "durable_failed", "durable_inline_failed", "stale_confirmed", "stale_foreign", "stale_changed", "stale_queued", "stale_overlap", "stale_success", "stale_busy", "stale_durable", "stale_durable_absent", "stale_durable_runner", "stale_durable_session", "stale_durable_snapshot", @@ -96,6 +97,25 @@ describeEmbeddedPostgres.each(["volume_free_owner", "archive_online", "archive_o taskKey: f.issueId, lastRunId: f.runId }).returning(); return { ...f, companyId, agentId, paperclipHome, runtimeRoot, paths, file, source, profile, session, queuedId, identity, snapshot }; } + if (scenario === "eligibility_unreadable") it("names a controller check that cannot read its source instead of failing the eligibility read", async () => { + const f = await fixture(); + await link(f.file, `${f.file}.alias`); + const failed = "native_controllers_check_failed:native_controller_migration_unsafe_source"; + expect((await readEphemeralServerDataEligibility(f.db, { purpose: "startup" })).blockers).toContain(failed); + const online = await readOnlineEphemeralEnrollmentEligibility(f.db); + expect(online.eligible).toBe(false); + expect(online.blockers).toContain(failed); + expect(online.blockers).not.toContain("native_controllers_require_migration"); + expect(await readFile(f.file, "utf8")).toBe(f.source); + await rm(`${f.file}.alias`); + if (process.getuid?.() !== 0) { + await chmod(f.file, 0o000); + try { + expect((await readEphemeralServerDataEligibility(f.db, { purpose: "startup" })).blockers) + .toContain("native_controllers_check_failed:source_eacces"); + } finally { await chmod(f.file, 0o600); } + } + }); if (scenario === "volume_free_owner") it("starts a volume-free server over controller state it wrote itself and keeps unmarked state blocked", async () => { vi.stubEnv("PAPERCLIP_EPHEMERAL_SERVER", "true"); expect(await claimVolumeFreeControllerState(true)).toBe("claimed");